ngram
listlengths
0
82k
[ "-*- __author__ = \"\"\"<NAME>\"\"\" __email__ = '<EMAIL>' __version__ = '0.1.0'", "utf-8 -*- __author__ = \"\"\"<NAME>\"\"\" __email__ = '<EMAIL>' __version__ =", "-*- coding: utf-8 -*- __author__ = \"\"\"<NAME>\"\"\" __email__ = '<EMAIL>'", "coding: utf-8 -*- __author__ = \"\"\"<NAME>\"\"\" __email__ = '<EMAIL>' __version__", "# -*- coding: utf-8 -*- __author__ = \"\"\"<NAME>\"\"\" __email__ =" ]
[ "path) def save_to_s3(self, bucket, access_key, secret_key, **kwargs): \"\"\"Save the backup", "\"\"\"A new directory which is subsequently added to the backup\"\"\"", "file %s\" % self._path) def include_directory(self, path, preserve_paths=False, name=None): \"\"\"Add", "filename = filename.replace(directory, \"\") if name is not None: filename", "zipfile import ZipFile, ZIP_DEFLATED from datetime import datetime from boto.s3.connection", "logger.debug(\"Walking directory %s\" % path) for file in files: filename", "self._path = mkstemp() logger.debug(\"Created temporary file %s\" % self._path) def", "setting up some sane logging defaults\"\"\" opts = dict(LOGGING_DEFAULTS.items() +", "the backup\"\"\" path = os.path.abspath(path) logger.debug(\"Adding directory %s\" % path)", "directory %s\" % self.path) def __str__(self): return self.path def __enter__(self):", "import rmtree from zipfile import ZipFile, ZIP_DEFLATED from datetime import", "= dict(LOGGING_DEFAULTS.items() + kwargs.items()) logging.basicConfig(**opts) class ZipBackup(object): \"\"\" A compressed", "key = Key(bucket) key.key = '%<KEY>' % \\ (self.name, datetime.now().strftime(\"%Y%m%d%H%M%S\"))", "_get_filename_for_archive(self, directory, filename, preserve_paths, name): if not preserve_paths: filename =", "ZipBackup(object): \"\"\" A compressed ZIP file backup Note: large inclusion", "preserve_paths=False, name=None): \"\"\"Add the contents of a directory to the", "contents of a directory to the backup\"\"\" path = os.path.abspath(path)", "logger.debug(\"Finished directory %s\" % path) def save_to_s3(self, bucket, access_key, secret_key,", "to Amazon S3\"\"\" logger.info(\"Saving to S3 in '%s' bucket\" %", "file backup Note: large inclusion operations can sometimes take time", "LOGGING_DEFAULTS = {\"level\": logging.INFO, \"format\": \"%(asctime)s [%(levelname)s]: %(message)s\"} def setup_logging(**kwargs):", "path = os.path.abspath(path) logger.debug(\"Adding directory %s\" % path) with ZipFile(self._path,", "+ kwargs.items()) logging.basicConfig(**opts) class ZipBackup(object): \"\"\" A compressed ZIP file", "boto.s3.key import Key __version__ = \"0.1.8\" __author__ = \"<NAME>\" __email__", "logging.basicConfig(**opts) class ZipBackup(object): \"\"\" A compressed ZIP file backup Note:", "is not None: filename = name + os.sep + filename", "datetime import datetime from boto.s3.connection import S3Connection from boto.s3.key import", "inclusion operations can sometimes take time as files are compressed", "rmtree from zipfile import ZipFile, ZIP_DEFLATED from datetime import datetime", "zipfile: for base,dirs,files in os.walk(path): logger.debug(\"Walking directory %s\" % path)", "\"\"\"Convenience function for setting up some sane logging defaults\"\"\" opts", "self.name = name self.path = mkdtemp() self._owner = owner logger.debug(\"Created", "**kwargs) bucket = conn.get_bucket(bucket) key = Key(bucket) key.key = '%<KEY>'", "return filename class BackupIncludedDirectory(object): \"\"\"A new directory which is subsequently", "temporary directory %s\" % self.path) def __str__(self): return self.path def", "which is subsequently added to the backup\"\"\" def __init__(self, name,", "filename = name + os.sep + filename return filename class", "= owner logger.debug(\"Created temporary directory %s\" % self.path) def __str__(self):", "Amazon S3\"\"\" logger.info(\"Saving to S3 in '%s' bucket\" % bucket)", "sometimes take time as files are compressed on the fly.", "logger.warn(\"Could not add file %s\" % file, exc_info=True) logger.debug(\"Finished directory", "in os.walk(path): logger.debug(\"Walking directory %s\" % path) for file in", "from tempfile import mkstemp, mkdtemp from shutil import rmtree from", "__enter__(self): return self def __exit__(self, type, value, traceback): self.close() def", "import datetime from boto.s3.connection import S3Connection from boto.s3.key import Key", "This prevents all the files being copied to a temporary", "%(message)s\"} def setup_logging(**kwargs): \"\"\"Convenience function for setting up some sane", "Note: large inclusion operations can sometimes take time as files", "value, traceback): self._owner.include_directory(self.path, preserve_paths=False, name=self.name) rmtree(self.path) logger.debug(\"Removed temporary directory %s\"", "time as files are compressed on the fly. This prevents", "%s\" % self._path) def __enter__(self): return self def __exit__(self, type,", "self def __exit__(self, type, value, traceback): self.close() def close(self): os.remove(self._path)", "= S3Connection(access_key, secret_key, **kwargs) bucket = conn.get_bucket(bucket) key = Key(bucket)", "self._get_filename_for_archive( path, filename, preserve_paths, name)) logger.info(\"Added file %s\" % filename)", "key.key) def include_new_dir(self, name): \"\"\"Add a new empty directory to", "name): \"\"\"Add a new empty directory to the backup\"\"\" return", "traceback): self._owner.include_directory(self.path, preserve_paths=False, name=self.name) rmtree(self.path) logger.debug(\"Removed temporary directory %s\" %", "logger.info(\"Saving to S3 done %s\" % key.key) def include_new_dir(self, name):", "directory, filename, preserve_paths, name): if not preserve_paths: filename = filename.replace(directory,", "\"%(asctime)s [%(levelname)s]: %(message)s\"} def setup_logging(**kwargs): \"\"\"Convenience function for setting up", "= name _, self._path = mkstemp() logger.debug(\"Created temporary file %s\"", "file in files: filename = os.path.join(base, file) try: zipfile.write(filename, self._get_filename_for_archive(", "is subsequently added to the backup\"\"\" def __init__(self, name, owner):", "bucket, access_key, secret_key, **kwargs): \"\"\"Save the backup to Amazon S3\"\"\"", "name + os.sep + filename return filename class BackupIncludedDirectory(object): \"\"\"A", "'%s' bucket\" % bucket) conn = S3Connection(access_key, secret_key, **kwargs) bucket", "up the need for a potentially large compression at the", "file, exc_info=True) logger.debug(\"Finished directory %s\" % path) def save_to_s3(self, bucket,", "the end. \"\"\" def __init__(self, name): self.name = name _,", "access_key, secret_key, **kwargs): \"\"\"Save the backup to Amazon S3\"\"\" logger.info(\"Saving", "% \\ (self.name, datetime.now().strftime(\"%Y%m%d%H%M%S\")) key.set_contents_from_filename(self._path) logger.info(\"Saving to S3 done %s\"", "logger.info(\"Added file %s\" % filename) except: logger.warn(\"Could not add file", "% path) with ZipFile(self._path, 'a', ZIP_DEFLATED, allowZip64=True) as zipfile: for", "large inclusion operations can sometimes take time as files are", "BackupIncludedDirectory(name, self) def _get_filename_for_archive(self, directory, filename, preserve_paths, name): if not", "logger = logging.getLogger(__name__) logger.addHandler(logging.NullHandler()) LOGGING_DEFAULTS = {\"level\": logging.INFO, \"format\": \"%(asctime)s", "directory which is subsequently added to the backup\"\"\" def __init__(self,", "logging.INFO, \"format\": \"%(asctime)s [%(levelname)s]: %(message)s\"} def setup_logging(**kwargs): \"\"\"Convenience function for", "logger.debug(\"Removed temporary file %s\" % self._path) def include_directory(self, path, preserve_paths=False,", "directory to the backup\"\"\" path = os.path.abspath(path) logger.debug(\"Adding directory %s\"", "= mkstemp() logger.debug(\"Created temporary file %s\" % self._path) def __enter__(self):", "file) try: zipfile.write(filename, self._get_filename_for_archive( path, filename, preserve_paths, name)) logger.info(\"Added file", "os.walk(path): logger.debug(\"Walking directory %s\" % path) for file in files:", "add file %s\" % file, exc_info=True) logger.debug(\"Finished directory %s\" %", "filename.replace(directory, \"\") if name is not None: filename = name", "type, value, traceback): self._owner.include_directory(self.path, preserve_paths=False, name=self.name) rmtree(self.path) logger.debug(\"Removed temporary directory", "S3 done %s\" % key.key) def include_new_dir(self, name): \"\"\"Add a", "temporary file %s\" % self._path) def include_directory(self, path, preserve_paths=False, name=None):", "directory %s\" % path) with ZipFile(self._path, 'a', ZIP_DEFLATED, allowZip64=True) as", "% file, exc_info=True) logger.debug(\"Finished directory %s\" % path) def save_to_s3(self,", "self._path) def __enter__(self): return self def __exit__(self, type, value, traceback):", "%s\" % path) for file in files: filename = os.path.join(base,", "logger.debug(\"Created temporary file %s\" % self._path) def __enter__(self): return self", "%s\" % self._path) def include_directory(self, path, preserve_paths=False, name=None): \"\"\"Add the", "directory %s\" % path) def save_to_s3(self, bucket, access_key, secret_key, **kwargs):", "S3\"\"\" logger.info(\"Saving to S3 in '%s' bucket\" % bucket) conn", "\"\"\" A compressed ZIP file backup Note: large inclusion operations", "location (and using unnecessary extra space) and storing up the", "self._path) def include_directory(self, path, preserve_paths=False, name=None): \"\"\"Add the contents of", "self.close() def close(self): os.remove(self._path) logger.debug(\"Removed temporary file %s\" % self._path)", "ZIP file backup Note: large inclusion operations can sometimes take", "kwargs.items()) logging.basicConfig(**opts) class ZipBackup(object): \"\"\" A compressed ZIP file backup", "exc_info=True) logger.debug(\"Finished directory %s\" % path) def save_to_s3(self, bucket, access_key,", "space) and storing up the need for a potentially large", "traceback): self.close() def close(self): os.remove(self._path) logger.debug(\"Removed temporary file %s\" %", "preserve_paths, name)) logger.info(\"Added file %s\" % filename) except: logger.warn(\"Could not", "added to the backup\"\"\" def __init__(self, name, owner): self.name =", "%s\" % key.key) def include_new_dir(self, name): \"\"\"Add a new empty", "directory to the backup\"\"\" return BackupIncludedDirectory(name, self) def _get_filename_for_archive(self, directory,", "files are compressed on the fly. This prevents all the", "conn = S3Connection(access_key, secret_key, **kwargs) bucket = conn.get_bucket(bucket) key =", "logging.getLogger(__name__) logger.addHandler(logging.NullHandler()) LOGGING_DEFAULTS = {\"level\": logging.INFO, \"format\": \"%(asctime)s [%(levelname)s]: %(message)s\"}", "backup\"\"\" def __init__(self, name, owner): self.name = name self.path =", "% key.key) def include_new_dir(self, name): \"\"\"Add a new empty directory", "\"<NAME>\" __email__ = \"<EMAIL>\" logger = logging.getLogger(__name__) logger.addHandler(logging.NullHandler()) LOGGING_DEFAULTS =", "__email__ = \"<EMAIL>\" logger = logging.getLogger(__name__) logger.addHandler(logging.NullHandler()) LOGGING_DEFAULTS = {\"level\":", "preserve_paths: filename = filename.replace(directory, \"\") if name is not None:", "base,dirs,files in os.walk(path): logger.debug(\"Walking directory %s\" % path) for file", "file %s\" % file, exc_info=True) logger.debug(\"Finished directory %s\" % path)", "to the backup\"\"\" return BackupIncludedDirectory(name, self) def _get_filename_for_archive(self, directory, filename,", "owner logger.debug(\"Created temporary directory %s\" % self.path) def __str__(self): return", "new empty directory to the backup\"\"\" return BackupIncludedDirectory(name, self) def", "% bucket) conn = S3Connection(access_key, secret_key, **kwargs) bucket = conn.get_bucket(bucket)", "sane logging defaults\"\"\" opts = dict(LOGGING_DEFAULTS.items() + kwargs.items()) logging.basicConfig(**opts) class", "subsequently added to the backup\"\"\" def __init__(self, name, owner): self.name", "from boto.s3.key import Key __version__ = \"0.1.8\" __author__ = \"<NAME>\"", "name=None): \"\"\"Add the contents of a directory to the backup\"\"\"", "import os import logging from tempfile import mkstemp, mkdtemp from", "class ZipBackup(object): \"\"\" A compressed ZIP file backup Note: large", "if not preserve_paths: filename = filename.replace(directory, \"\") if name is", "__exit__(self, type, value, traceback): self.close() def close(self): os.remove(self._path) logger.debug(\"Removed temporary", "all the files being copied to a temporary location (and", "= conn.get_bucket(bucket) key = Key(bucket) key.key = '%<KEY>' % \\", "owner): self.name = name self.path = mkdtemp() self._owner = owner", "__enter__(self): return self def __exit__(self, type, value, traceback): self._owner.include_directory(self.path, preserve_paths=False,", "name): self.name = name _, self._path = mkstemp() logger.debug(\"Created temporary", "and storing up the need for a potentially large compression", "path, preserve_paths=False, name=None): \"\"\"Add the contents of a directory to", "boto.s3.connection import S3Connection from boto.s3.key import Key __version__ = \"0.1.8\"", "__exit__(self, type, value, traceback): self._owner.include_directory(self.path, preserve_paths=False, name=self.name) rmtree(self.path) logger.debug(\"Removed temporary", "= name self.path = mkdtemp() self._owner = owner logger.debug(\"Created temporary", "Key __version__ = \"0.1.8\" __author__ = \"<NAME>\" __email__ = \"<EMAIL>\"", "path) with ZipFile(self._path, 'a', ZIP_DEFLATED, allowZip64=True) as zipfile: for base,dirs,files", "defaults\"\"\" opts = dict(LOGGING_DEFAULTS.items() + kwargs.items()) logging.basicConfig(**opts) class ZipBackup(object): \"\"\"", "None: filename = name + os.sep + filename return filename", "ZIP_DEFLATED from datetime import datetime from boto.s3.connection import S3Connection from", "% filename) except: logger.warn(\"Could not add file %s\" % file,", "take time as files are compressed on the fly. This", "A compressed ZIP file backup Note: large inclusion operations can", "ZipFile(self._path, 'a', ZIP_DEFLATED, allowZip64=True) as zipfile: for base,dirs,files in os.walk(path):", "logger.info(\"Saving to S3 in '%s' bucket\" % bucket) conn =", "__init__(self, name): self.name = name _, self._path = mkstemp() logger.debug(\"Created", "ZipFile, ZIP_DEFLATED from datetime import datetime from boto.s3.connection import S3Connection", "(and using unnecessary extra space) and storing up the need", "%s\" % filename) except: logger.warn(\"Could not add file %s\" %", "extra space) and storing up the need for a potentially", "self.path = mkdtemp() self._owner = owner logger.debug(\"Created temporary directory %s\"", "backup Note: large inclusion operations can sometimes take time as", "files: filename = os.path.join(base, file) try: zipfile.write(filename, self._get_filename_for_archive( path, filename,", "filename return filename class BackupIncludedDirectory(object): \"\"\"A new directory which is", "+ os.sep + filename return filename class BackupIncludedDirectory(object): \"\"\"A new", "__version__ = \"0.1.8\" __author__ = \"<NAME>\" __email__ = \"<EMAIL>\" logger", "self.path) def __str__(self): return self.path def __enter__(self): return self def", "= '%<KEY>' % \\ (self.name, datetime.now().strftime(\"%Y%m%d%H%M%S\")) key.set_contents_from_filename(self._path) logger.info(\"Saving to S3", "import Key __version__ = \"0.1.8\" __author__ = \"<NAME>\" __email__ =", "directory %s\" % path) for file in files: filename =", "ZIP_DEFLATED, allowZip64=True) as zipfile: for base,dirs,files in os.walk(path): logger.debug(\"Walking directory", "logger.debug(\"Adding directory %s\" % path) with ZipFile(self._path, 'a', ZIP_DEFLATED, allowZip64=True)", "def include_directory(self, path, preserve_paths=False, name=None): \"\"\"Add the contents of a", "= \"<EMAIL>\" logger = logging.getLogger(__name__) logger.addHandler(logging.NullHandler()) LOGGING_DEFAULTS = {\"level\": logging.INFO,", "self._owner.include_directory(self.path, preserve_paths=False, name=self.name) rmtree(self.path) logger.debug(\"Removed temporary directory %s\" % self.path)", "% path) for file in files: filename = os.path.join(base, file)", "name is not None: filename = name + os.sep +", "def __init__(self, name, owner): self.name = name self.path = mkdtemp()", "+ filename return filename class BackupIncludedDirectory(object): \"\"\"A new directory which", "of a directory to the backup\"\"\" path = os.path.abspath(path) logger.debug(\"Adding", "\"\") if name is not None: filename = name +", "zipfile.write(filename, self._get_filename_for_archive( path, filename, preserve_paths, name)) logger.info(\"Added file %s\" %", "= os.path.abspath(path) logger.debug(\"Adding directory %s\" % path) with ZipFile(self._path, 'a',", "storing up the need for a potentially large compression at", "return self def __exit__(self, type, value, traceback): self.close() def close(self):", "the fly. This prevents all the files being copied to", "(self.name, datetime.now().strftime(\"%Y%m%d%H%M%S\")) key.set_contents_from_filename(self._path) logger.info(\"Saving to S3 done %s\" % key.key)", "datetime from boto.s3.connection import S3Connection from boto.s3.key import Key __version__", "os.path.join(base, file) try: zipfile.write(filename, self._get_filename_for_archive( path, filename, preserve_paths, name)) logger.info(\"Added", "= os.path.join(base, file) try: zipfile.write(filename, self._get_filename_for_archive( path, filename, preserve_paths, name))", "def __init__(self, name): self.name = name _, self._path = mkstemp()", "= logging.getLogger(__name__) logger.addHandler(logging.NullHandler()) LOGGING_DEFAULTS = {\"level\": logging.INFO, \"format\": \"%(asctime)s [%(levelname)s]:", "operations can sometimes take time as files are compressed on", "self.name = name _, self._path = mkstemp() logger.debug(\"Created temporary file", "temporary file %s\" % self._path) def __enter__(self): return self def", "% self._path) def __enter__(self): return self def __exit__(self, type, value,", "Key(bucket) key.key = '%<KEY>' % \\ (self.name, datetime.now().strftime(\"%Y%m%d%H%M%S\")) key.set_contents_from_filename(self._path) logger.info(\"Saving", "on the fly. This prevents all the files being copied", "'%<KEY>' % \\ (self.name, datetime.now().strftime(\"%Y%m%d%H%M%S\")) key.set_contents_from_filename(self._path) logger.info(\"Saving to S3 done", "= \"0.1.8\" __author__ = \"<NAME>\" __email__ = \"<EMAIL>\" logger =", "__init__(self, name, owner): self.name = name self.path = mkdtemp() self._owner", "not None: filename = name + os.sep + filename return", "preserve_paths, name): if not preserve_paths: filename = filename.replace(directory, \"\") if", "logger.addHandler(logging.NullHandler()) LOGGING_DEFAULTS = {\"level\": logging.INFO, \"format\": \"%(asctime)s [%(levelname)s]: %(message)s\"} def", "are compressed on the fly. This prevents all the files", "a new empty directory to the backup\"\"\" return BackupIncludedDirectory(name, self)", "self) def _get_filename_for_archive(self, directory, filename, preserve_paths, name): if not preserve_paths:", "logging defaults\"\"\" opts = dict(LOGGING_DEFAULTS.items() + kwargs.items()) logging.basicConfig(**opts) class ZipBackup(object):", "tempfile import mkstemp, mkdtemp from shutil import rmtree from zipfile", "os.remove(self._path) logger.debug(\"Removed temporary file %s\" % self._path) def include_directory(self, path,", "compressed on the fly. This prevents all the files being", "name, owner): self.name = name self.path = mkdtemp() self._owner =", "name)) logger.info(\"Added file %s\" % filename) except: logger.warn(\"Could not add", "def save_to_s3(self, bucket, access_key, secret_key, **kwargs): \"\"\"Save the backup to", "self._owner = owner logger.debug(\"Created temporary directory %s\" % self.path) def", "def include_new_dir(self, name): \"\"\"Add a new empty directory to the", "logger.debug(\"Created temporary directory %s\" % self.path) def __str__(self): return self.path", "the contents of a directory to the backup\"\"\" path =", "%s\" % path) with ZipFile(self._path, 'a', ZIP_DEFLATED, allowZip64=True) as zipfile:", "name): if not preserve_paths: filename = filename.replace(directory, \"\") if name", "def _get_filename_for_archive(self, directory, filename, preserve_paths, name): if not preserve_paths: filename", "large compression at the end. \"\"\" def __init__(self, name): self.name", "[%(levelname)s]: %(message)s\"} def setup_logging(**kwargs): \"\"\"Convenience function for setting up some", "self def __exit__(self, type, value, traceback): self._owner.include_directory(self.path, preserve_paths=False, name=self.name) rmtree(self.path)", "conn.get_bucket(bucket) key = Key(bucket) key.key = '%<KEY>' % \\ (self.name,", "return BackupIncludedDirectory(name, self) def _get_filename_for_archive(self, directory, filename, preserve_paths, name): if", "being copied to a temporary location (and using unnecessary extra", "to the backup\"\"\" path = os.path.abspath(path) logger.debug(\"Adding directory %s\" %", "def close(self): os.remove(self._path) logger.debug(\"Removed temporary file %s\" % self._path) def", "not preserve_paths: filename = filename.replace(directory, \"\") if name is not", "% self.path) def __str__(self): return self.path def __enter__(self): return self", "potentially large compression at the end. \"\"\" def __init__(self, name):", "at the end. \"\"\" def __init__(self, name): self.name = name", "import ZipFile, ZIP_DEFLATED from datetime import datetime from boto.s3.connection import", "backup\"\"\" return BackupIncludedDirectory(name, self) def _get_filename_for_archive(self, directory, filename, preserve_paths, name):", "%s\" % path) def save_to_s3(self, bucket, access_key, secret_key, **kwargs): \"\"\"Save", "secret_key, **kwargs) bucket = conn.get_bucket(bucket) key = Key(bucket) key.key =", "import S3Connection from boto.s3.key import Key __version__ = \"0.1.8\" __author__", "__str__(self): return self.path def __enter__(self): return self def __exit__(self, type,", "%s\" % file, exc_info=True) logger.debug(\"Finished directory %s\" % path) def", "files being copied to a temporary location (and using unnecessary", "include_new_dir(self, name): \"\"\"Add a new empty directory to the backup\"\"\"", "the need for a potentially large compression at the end.", "include_directory(self, path, preserve_paths=False, name=None): \"\"\"Add the contents of a directory", "secret_key, **kwargs): \"\"\"Save the backup to Amazon S3\"\"\" logger.info(\"Saving to", "\"<EMAIL>\" logger = logging.getLogger(__name__) logger.addHandler(logging.NullHandler()) LOGGING_DEFAULTS = {\"level\": logging.INFO, \"format\":", "copied to a temporary location (and using unnecessary extra space)", "name _, self._path = mkstemp() logger.debug(\"Created temporary file %s\" %", "dict(LOGGING_DEFAULTS.items() + kwargs.items()) logging.basicConfig(**opts) class ZipBackup(object): \"\"\" A compressed ZIP", "for base,dirs,files in os.walk(path): logger.debug(\"Walking directory %s\" % path) for", "backup to Amazon S3\"\"\" logger.info(\"Saving to S3 in '%s' bucket\"", "def __enter__(self): return self def __exit__(self, type, value, traceback): self._owner.include_directory(self.path,", "filename = os.path.join(base, file) try: zipfile.write(filename, self._get_filename_for_archive( path, filename, preserve_paths,", "% self._path) def include_directory(self, path, preserve_paths=False, name=None): \"\"\"Add the contents", "backup\"\"\" path = os.path.abspath(path) logger.debug(\"Adding directory %s\" % path) with", "mkdtemp from shutil import rmtree from zipfile import ZipFile, ZIP_DEFLATED", "can sometimes take time as files are compressed on the", "**kwargs): \"\"\"Save the backup to Amazon S3\"\"\" logger.info(\"Saving to S3", "= mkdtemp() self._owner = owner logger.debug(\"Created temporary directory %s\" %", "a temporary location (and using unnecessary extra space) and storing", "S3 in '%s' bucket\" % bucket) conn = S3Connection(access_key, secret_key,", "return self.path def __enter__(self): return self def __exit__(self, type, value,", "in '%s' bucket\" % bucket) conn = S3Connection(access_key, secret_key, **kwargs)", "\\ (self.name, datetime.now().strftime(\"%Y%m%d%H%M%S\")) key.set_contents_from_filename(self._path) logger.info(\"Saving to S3 done %s\" %", "_, self._path = mkstemp() logger.debug(\"Created temporary file %s\" % self._path)", "to S3 done %s\" % key.key) def include_new_dir(self, name): \"\"\"Add", "type, value, traceback): self.close() def close(self): os.remove(self._path) logger.debug(\"Removed temporary file", "as files are compressed on the fly. This prevents all", "\"format\": \"%(asctime)s [%(levelname)s]: %(message)s\"} def setup_logging(**kwargs): \"\"\"Convenience function for setting", "save_to_s3(self, bucket, access_key, secret_key, **kwargs): \"\"\"Save the backup to Amazon", "shutil import rmtree from zipfile import ZipFile, ZIP_DEFLATED from datetime", "%s\" % self.path) def __str__(self): return self.path def __enter__(self): return", "allowZip64=True) as zipfile: for base,dirs,files in os.walk(path): logger.debug(\"Walking directory %s\"", "done %s\" % key.key) def include_new_dir(self, name): \"\"\"Add a new", "def __str__(self): return self.path def __enter__(self): return self def __exit__(self,", "= \"<NAME>\" __email__ = \"<EMAIL>\" logger = logging.getLogger(__name__) logger.addHandler(logging.NullHandler()) LOGGING_DEFAULTS", "BackupIncludedDirectory(object): \"\"\"A new directory which is subsequently added to the", "__author__ = \"<NAME>\" __email__ = \"<EMAIL>\" logger = logging.getLogger(__name__) logger.addHandler(logging.NullHandler())", "mkstemp() logger.debug(\"Created temporary file %s\" % self._path) def __enter__(self): return", "\"0.1.8\" __author__ = \"<NAME>\" __email__ = \"<EMAIL>\" logger = logging.getLogger(__name__)", "setup_logging(**kwargs): \"\"\"Convenience function for setting up some sane logging defaults\"\"\"", "value, traceback): self.close() def close(self): os.remove(self._path) logger.debug(\"Removed temporary file %s\"", "def __exit__(self, type, value, traceback): self._owner.include_directory(self.path, preserve_paths=False, name=self.name) rmtree(self.path) logger.debug(\"Removed", "to S3 in '%s' bucket\" % bucket) conn = S3Connection(access_key,", "fly. This prevents all the files being copied to a", "with ZipFile(self._path, 'a', ZIP_DEFLATED, allowZip64=True) as zipfile: for base,dirs,files in", "def setup_logging(**kwargs): \"\"\"Convenience function for setting up some sane logging", "the backup\"\"\" return BackupIncludedDirectory(name, self) def _get_filename_for_archive(self, directory, filename, preserve_paths,", "\"\"\"Add the contents of a directory to the backup\"\"\" path", "import logging from tempfile import mkstemp, mkdtemp from shutil import", "function for setting up some sane logging defaults\"\"\" opts =", "name self.path = mkdtemp() self._owner = owner logger.debug(\"Created temporary directory", "'a', ZIP_DEFLATED, allowZip64=True) as zipfile: for base,dirs,files in os.walk(path): logger.debug(\"Walking", "unnecessary extra space) and storing up the need for a", "filename) except: logger.warn(\"Could not add file %s\" % file, exc_info=True)", "return self def __exit__(self, type, value, traceback): self._owner.include_directory(self.path, preserve_paths=False, name=self.name)", "bucket = conn.get_bucket(bucket) key = Key(bucket) key.key = '%<KEY>' %", "{\"level\": logging.INFO, \"format\": \"%(asctime)s [%(levelname)s]: %(message)s\"} def setup_logging(**kwargs): \"\"\"Convenience function", "path, filename, preserve_paths, name)) logger.info(\"Added file %s\" % filename) except:", "try: zipfile.write(filename, self._get_filename_for_archive( path, filename, preserve_paths, name)) logger.info(\"Added file %s\"", "for setting up some sane logging defaults\"\"\" opts = dict(LOGGING_DEFAULTS.items()", "= Key(bucket) key.key = '%<KEY>' % \\ (self.name, datetime.now().strftime(\"%Y%m%d%H%M%S\")) key.set_contents_from_filename(self._path)", "some sane logging defaults\"\"\" opts = dict(LOGGING_DEFAULTS.items() + kwargs.items()) logging.basicConfig(**opts)", "file %s\" % filename) except: logger.warn(\"Could not add file %s\"", "os.path.abspath(path) logger.debug(\"Adding directory %s\" % path) with ZipFile(self._path, 'a', ZIP_DEFLATED,", "= filename.replace(directory, \"\") if name is not None: filename =", "empty directory to the backup\"\"\" return BackupIncludedDirectory(name, self) def _get_filename_for_archive(self,", "if name is not None: filename = name + os.sep", "new directory which is subsequently added to the backup\"\"\" def", "from shutil import rmtree from zipfile import ZipFile, ZIP_DEFLATED from", "from zipfile import ZipFile, ZIP_DEFLATED from datetime import datetime from", "def __exit__(self, type, value, traceback): self.close() def close(self): os.remove(self._path) logger.debug(\"Removed", "for a potentially large compression at the end. \"\"\" def", "file %s\" % self._path) def __enter__(self): return self def __exit__(self,", "\"\"\"Save the backup to Amazon S3\"\"\" logger.info(\"Saving to S3 in", "end. \"\"\" def __init__(self, name): self.name = name _, self._path", "= {\"level\": logging.INFO, \"format\": \"%(asctime)s [%(levelname)s]: %(message)s\"} def setup_logging(**kwargs): \"\"\"Convenience", "bucket) conn = S3Connection(access_key, secret_key, **kwargs) bucket = conn.get_bucket(bucket) key", "% path) def save_to_s3(self, bucket, access_key, secret_key, **kwargs): \"\"\"Save the", "the files being copied to a temporary location (and using", "need for a potentially large compression at the end. \"\"\"", "key.set_contents_from_filename(self._path) logger.info(\"Saving to S3 done %s\" % key.key) def include_new_dir(self,", "a potentially large compression at the end. \"\"\" def __init__(self,", "S3Connection from boto.s3.key import Key __version__ = \"0.1.8\" __author__ =", "from datetime import datetime from boto.s3.connection import S3Connection from boto.s3.key", "os.sep + filename return filename class BackupIncludedDirectory(object): \"\"\"A new directory", "mkdtemp() self._owner = owner logger.debug(\"Created temporary directory %s\" % self.path)", "compression at the end. \"\"\" def __init__(self, name): self.name =", "import mkstemp, mkdtemp from shutil import rmtree from zipfile import", "using unnecessary extra space) and storing up the need for", "as zipfile: for base,dirs,files in os.walk(path): logger.debug(\"Walking directory %s\" %", "path) for file in files: filename = os.path.join(base, file) try:", "filename class BackupIncludedDirectory(object): \"\"\"A new directory which is subsequently added", "from boto.s3.connection import S3Connection from boto.s3.key import Key __version__ =", "except: logger.warn(\"Could not add file %s\" % file, exc_info=True) logger.debug(\"Finished", "the backup to Amazon S3\"\"\" logger.info(\"Saving to S3 in '%s'", "def __enter__(self): return self def __exit__(self, type, value, traceback): self.close()", "close(self): os.remove(self._path) logger.debug(\"Removed temporary file %s\" % self._path) def include_directory(self,", "temporary location (and using unnecessary extra space) and storing up", "\"\"\" def __init__(self, name): self.name = name _, self._path =", "bucket\" % bucket) conn = S3Connection(access_key, secret_key, **kwargs) bucket =", "class BackupIncludedDirectory(object): \"\"\"A new directory which is subsequently added to", "the backup\"\"\" def __init__(self, name, owner): self.name = name self.path", "a directory to the backup\"\"\" path = os.path.abspath(path) logger.debug(\"Adding directory", "to a temporary location (and using unnecessary extra space) and", "datetime.now().strftime(\"%Y%m%d%H%M%S\")) key.set_contents_from_filename(self._path) logger.info(\"Saving to S3 done %s\" % key.key) def", "key.key = '%<KEY>' % \\ (self.name, datetime.now().strftime(\"%Y%m%d%H%M%S\")) key.set_contents_from_filename(self._path) logger.info(\"Saving to", "os import logging from tempfile import mkstemp, mkdtemp from shutil", "opts = dict(LOGGING_DEFAULTS.items() + kwargs.items()) logging.basicConfig(**opts) class ZipBackup(object): \"\"\" A", "for file in files: filename = os.path.join(base, file) try: zipfile.write(filename,", "not add file %s\" % file, exc_info=True) logger.debug(\"Finished directory %s\"", "compressed ZIP file backup Note: large inclusion operations can sometimes", "prevents all the files being copied to a temporary location", "S3Connection(access_key, secret_key, **kwargs) bucket = conn.get_bucket(bucket) key = Key(bucket) key.key", "= name + os.sep + filename return filename class BackupIncludedDirectory(object):", "filename, preserve_paths, name)) logger.info(\"Added file %s\" % filename) except: logger.warn(\"Could", "\"\"\"Add a new empty directory to the backup\"\"\" return BackupIncludedDirectory(name,", "to the backup\"\"\" def __init__(self, name, owner): self.name = name", "filename, preserve_paths, name): if not preserve_paths: filename = filename.replace(directory, \"\")", "logging from tempfile import mkstemp, mkdtemp from shutil import rmtree", "in files: filename = os.path.join(base, file) try: zipfile.write(filename, self._get_filename_for_archive( path,", "up some sane logging defaults\"\"\" opts = dict(LOGGING_DEFAULTS.items() + kwargs.items())", "mkstemp, mkdtemp from shutil import rmtree from zipfile import ZipFile,", "self.path def __enter__(self): return self def __exit__(self, type, value, traceback):" ]
[ "'邀请面试'), ('WJ', '婉拒')], default='DD', max_length=2, verbose_name='投递状态')), ], options={ 'verbose_name': '面试',", "13:03 from django.db import migrations, models class Migration(migrations.Migration): initial =", "'待定'), ('YQ', '邀请面试'), ('WJ', '婉拒')], default='DD', max_length=2, verbose_name='投递状态')), ], options={", "migrations, models class Migration(migrations.Migration): initial = True dependencies = [", "('WJ', '婉拒')], default='DD', max_length=2, verbose_name='投递状态')), ], options={ 'verbose_name': '面试', 'verbose_name_plural':", "operations = [ migrations.CreateModel( name='Delivery', fields=[ ('create_time', models.DateTimeField(auto_now_add=True, verbose_name='创建时间')), ('update_time',", "models.CharField(choices=[('DD', '待定'), ('YQ', '邀请面试'), ('WJ', '婉拒')], default='DD', max_length=2, verbose_name='投递状态')), ],", "= [ migrations.CreateModel( name='Delivery', fields=[ ('create_time', models.DateTimeField(auto_now_add=True, verbose_name='创建时间')), ('update_time', models.DateTimeField(auto_now=True,", "initial = True dependencies = [ ] operations = [", "2019-03-08 13:03 from django.db import migrations, models class Migration(migrations.Migration): initial", "('delivery_status', models.CharField(choices=[('DD', '待定'), ('YQ', '邀请面试'), ('WJ', '婉拒')], default='DD', max_length=2, verbose_name='投递状态')),", "class Migration(migrations.Migration): initial = True dependencies = [ ] operations", "verbose_name='更新时间')), ('is_delete', models.BooleanField(default=False, verbose_name='删除标记')), ('id', models.AutoField(primary_key=True, serialize=False, verbose_name='投递ID')), ('delivery_status', models.CharField(choices=[('DD',", "[ migrations.CreateModel( name='Delivery', fields=[ ('create_time', models.DateTimeField(auto_now_add=True, verbose_name='创建时间')), ('update_time', models.DateTimeField(auto_now=True, verbose_name='更新时间')),", "models.DateTimeField(auto_now=True, verbose_name='更新时间')), ('is_delete', models.BooleanField(default=False, verbose_name='删除标记')), ('id', models.AutoField(primary_key=True, serialize=False, verbose_name='投递ID')), ('delivery_status',", "default='DD', max_length=2, verbose_name='投递状态')), ], options={ 'verbose_name': '面试', 'verbose_name_plural': '面试', },", "by Django 2.0.2 on 2019-03-08 13:03 from django.db import migrations,", "= [ ] operations = [ migrations.CreateModel( name='Delivery', fields=[ ('create_time',", "verbose_name='投递ID')), ('delivery_status', models.CharField(choices=[('DD', '待定'), ('YQ', '邀请面试'), ('WJ', '婉拒')], default='DD', max_length=2,", "verbose_name='投递状态')), ], options={ 'verbose_name': '面试', 'verbose_name_plural': '面试', }, ), ]", "models.DateTimeField(auto_now_add=True, verbose_name='创建时间')), ('update_time', models.DateTimeField(auto_now=True, verbose_name='更新时间')), ('is_delete', models.BooleanField(default=False, verbose_name='删除标记')), ('id', models.AutoField(primary_key=True,", "migrations.CreateModel( name='Delivery', fields=[ ('create_time', models.DateTimeField(auto_now_add=True, verbose_name='创建时间')), ('update_time', models.DateTimeField(auto_now=True, verbose_name='更新时间')), ('is_delete',", "dependencies = [ ] operations = [ migrations.CreateModel( name='Delivery', fields=[", "('update_time', models.DateTimeField(auto_now=True, verbose_name='更新时间')), ('is_delete', models.BooleanField(default=False, verbose_name='删除标记')), ('id', models.AutoField(primary_key=True, serialize=False, verbose_name='投递ID')),", "2.0.2 on 2019-03-08 13:03 from django.db import migrations, models class", "Django 2.0.2 on 2019-03-08 13:03 from django.db import migrations, models", "fields=[ ('create_time', models.DateTimeField(auto_now_add=True, verbose_name='创建时间')), ('update_time', models.DateTimeField(auto_now=True, verbose_name='更新时间')), ('is_delete', models.BooleanField(default=False, verbose_name='删除标记')),", "('is_delete', models.BooleanField(default=False, verbose_name='删除标记')), ('id', models.AutoField(primary_key=True, serialize=False, verbose_name='投递ID')), ('delivery_status', models.CharField(choices=[('DD', '待定'),", "('id', models.AutoField(primary_key=True, serialize=False, verbose_name='投递ID')), ('delivery_status', models.CharField(choices=[('DD', '待定'), ('YQ', '邀请面试'), ('WJ',", "('create_time', models.DateTimeField(auto_now_add=True, verbose_name='创建时间')), ('update_time', models.DateTimeField(auto_now=True, verbose_name='更新时间')), ('is_delete', models.BooleanField(default=False, verbose_name='删除标记')), ('id',", "True dependencies = [ ] operations = [ migrations.CreateModel( name='Delivery',", "models.AutoField(primary_key=True, serialize=False, verbose_name='投递ID')), ('delivery_status', models.CharField(choices=[('DD', '待定'), ('YQ', '邀请面试'), ('WJ', '婉拒')],", "# Generated by Django 2.0.2 on 2019-03-08 13:03 from django.db", "[ ] operations = [ migrations.CreateModel( name='Delivery', fields=[ ('create_time', models.DateTimeField(auto_now_add=True,", "verbose_name='创建时间')), ('update_time', models.DateTimeField(auto_now=True, verbose_name='更新时间')), ('is_delete', models.BooleanField(default=False, verbose_name='删除标记')), ('id', models.AutoField(primary_key=True, serialize=False,", "('YQ', '邀请面试'), ('WJ', '婉拒')], default='DD', max_length=2, verbose_name='投递状态')), ], options={ 'verbose_name':", "on 2019-03-08 13:03 from django.db import migrations, models class Migration(migrations.Migration):", "from django.db import migrations, models class Migration(migrations.Migration): initial = True", "Generated by Django 2.0.2 on 2019-03-08 13:03 from django.db import", "] operations = [ migrations.CreateModel( name='Delivery', fields=[ ('create_time', models.DateTimeField(auto_now_add=True, verbose_name='创建时间')),", "django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies", "max_length=2, verbose_name='投递状态')), ], options={ 'verbose_name': '面试', 'verbose_name_plural': '面试', }, ),", "verbose_name='删除标记')), ('id', models.AutoField(primary_key=True, serialize=False, verbose_name='投递ID')), ('delivery_status', models.CharField(choices=[('DD', '待定'), ('YQ', '邀请面试'),", "'婉拒')], default='DD', max_length=2, verbose_name='投递状态')), ], options={ 'verbose_name': '面试', 'verbose_name_plural': '面试',", "models class Migration(migrations.Migration): initial = True dependencies = [ ]", "name='Delivery', fields=[ ('create_time', models.DateTimeField(auto_now_add=True, verbose_name='创建时间')), ('update_time', models.DateTimeField(auto_now=True, verbose_name='更新时间')), ('is_delete', models.BooleanField(default=False,", "models.BooleanField(default=False, verbose_name='删除标记')), ('id', models.AutoField(primary_key=True, serialize=False, verbose_name='投递ID')), ('delivery_status', models.CharField(choices=[('DD', '待定'), ('YQ',", "= True dependencies = [ ] operations = [ migrations.CreateModel(", "Migration(migrations.Migration): initial = True dependencies = [ ] operations =", "serialize=False, verbose_name='投递ID')), ('delivery_status', models.CharField(choices=[('DD', '待定'), ('YQ', '邀请面试'), ('WJ', '婉拒')], default='DD',", "import migrations, models class Migration(migrations.Migration): initial = True dependencies =" ]
[ "hour, minute = int(time[11:13]), int(time[14:16]) return f\"{int(time[0:2])} {months[int(time[3:5])-1]} {time[6:10]} year", "minute!=1 else ''}\" if __name__ == '__main__': print(date_time(\"01.01.2018 00:00\")) assert", "15 minutes\" assert date_time(\"17.12.1990 07:42\") == \"17 December 1990 year", "8 hours 15 minutes\" assert date_time(\"17.12.1990 07:42\") == \"17 December", "\"August\", \"September\", \"October\", \"November\", \"December\"] hour, minute = int(time[11:13]), int(time[14:16])", "def date_time(time): months = [\"January\", \"February\", \"March\", \"April\", \"May\", \"June\",", "= [\"January\", \"February\", \"March\", \"April\", \"May\", \"June\", \"July\", \"August\", \"September\",", "minute = int(time[11:13]), int(time[14:16]) return f\"{int(time[0:2])} {months[int(time[3:5])-1]} {time[6:10]} year {hour}", "0 minutes\" assert date_time(\"04.08.1984 08:15\") == \"4 August 1984 year", "== \"1 January 2018 year 0 hours 0 minutes\" assert", "January 2018 year 0 hours 0 minutes\" assert date_time(\"04.08.1984 08:15\")", "if hour!=1 else ''} {minute} minute{'s' if minute!=1 else ''}\"", "else ''}\" if __name__ == '__main__': print(date_time(\"01.01.2018 00:00\")) assert date_time(\"01.01.2018", "int(time[11:13]), int(time[14:16]) return f\"{int(time[0:2])} {months[int(time[3:5])-1]} {time[6:10]} year {hour} hour{'s' if", "== '__main__': print(date_time(\"01.01.2018 00:00\")) assert date_time(\"01.01.2018 00:00\") == \"1 January", "#!/usr/bin/env python3 def date_time(time): months = [\"January\", \"February\", \"March\", \"April\",", "07:42\") == \"17 December 1990 year 7 hours 42 minutes\"", "\"December\"] hour, minute = int(time[11:13]), int(time[14:16]) return f\"{int(time[0:2])} {months[int(time[3:5])-1]} {time[6:10]}", "print(date_time(\"01.01.2018 00:00\")) assert date_time(\"01.01.2018 00:00\") == \"1 January 2018 year", "\"September\", \"October\", \"November\", \"December\"] hour, minute = int(time[11:13]), int(time[14:16]) return", "{months[int(time[3:5])-1]} {time[6:10]} year {hour} hour{'s' if hour!=1 else ''} {minute}", "08:15\") == \"4 August 1984 year 8 hours 15 minutes\"", "{hour} hour{'s' if hour!=1 else ''} {minute} minute{'s' if minute!=1", "python3 def date_time(time): months = [\"January\", \"February\", \"March\", \"April\", \"May\",", "date_time(\"01.01.2018 00:00\") == \"1 January 2018 year 0 hours 0", "hour!=1 else ''} {minute} minute{'s' if minute!=1 else ''}\" if", "''}\" if __name__ == '__main__': print(date_time(\"01.01.2018 00:00\")) assert date_time(\"01.01.2018 00:00\")", "\"4 August 1984 year 8 hours 15 minutes\" assert date_time(\"17.12.1990", "'__main__': print(date_time(\"01.01.2018 00:00\")) assert date_time(\"01.01.2018 00:00\") == \"1 January 2018", "minute{'s' if minute!=1 else ''}\" if __name__ == '__main__': print(date_time(\"01.01.2018", "year 8 hours 15 minutes\" assert date_time(\"17.12.1990 07:42\") == \"17", "2018 year 0 hours 0 minutes\" assert date_time(\"04.08.1984 08:15\") ==", "hours 0 minutes\" assert date_time(\"04.08.1984 08:15\") == \"4 August 1984", "[\"January\", \"February\", \"March\", \"April\", \"May\", \"June\", \"July\", \"August\", \"September\", \"October\",", "''} {minute} minute{'s' if minute!=1 else ''}\" if __name__ ==", "\"May\", \"June\", \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"] hour, minute", "\"June\", \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"] hour, minute =", "{time[6:10]} year {hour} hour{'s' if hour!=1 else ''} {minute} minute{'s'", "else ''} {minute} minute{'s' if minute!=1 else ''}\" if __name__", "assert date_time(\"17.12.1990 07:42\") == \"17 December 1990 year 7 hours", "date_time(\"17.12.1990 07:42\") == \"17 December 1990 year 7 hours 42", "\"February\", \"March\", \"April\", \"May\", \"June\", \"July\", \"August\", \"September\", \"October\", \"November\",", "year 0 hours 0 minutes\" assert date_time(\"04.08.1984 08:15\") == \"4", "minutes\" assert date_time(\"04.08.1984 08:15\") == \"4 August 1984 year 8", "= int(time[11:13]), int(time[14:16]) return f\"{int(time[0:2])} {months[int(time[3:5])-1]} {time[6:10]} year {hour} hour{'s'", "August 1984 year 8 hours 15 minutes\" assert date_time(\"17.12.1990 07:42\")", "\"November\", \"December\"] hour, minute = int(time[11:13]), int(time[14:16]) return f\"{int(time[0:2])} {months[int(time[3:5])-1]}", "year {hour} hour{'s' if hour!=1 else ''} {minute} minute{'s' if", "minutes\" assert date_time(\"17.12.1990 07:42\") == \"17 December 1990 year 7", "months = [\"January\", \"February\", \"March\", \"April\", \"May\", \"June\", \"July\", \"August\",", "1984 year 8 hours 15 minutes\" assert date_time(\"17.12.1990 07:42\") ==", "assert date_time(\"01.01.2018 00:00\") == \"1 January 2018 year 0 hours", "return f\"{int(time[0:2])} {months[int(time[3:5])-1]} {time[6:10]} year {hour} hour{'s' if hour!=1 else", "\"October\", \"November\", \"December\"] hour, minute = int(time[11:13]), int(time[14:16]) return f\"{int(time[0:2])}", "{minute} minute{'s' if minute!=1 else ''}\" if __name__ == '__main__':", "0 hours 0 minutes\" assert date_time(\"04.08.1984 08:15\") == \"4 August", "hours 15 minutes\" assert date_time(\"17.12.1990 07:42\") == \"17 December 1990", "\"July\", \"August\", \"September\", \"October\", \"November\", \"December\"] hour, minute = int(time[11:13]),", "\"1 January 2018 year 0 hours 0 minutes\" assert date_time(\"04.08.1984", "\"April\", \"May\", \"June\", \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"] hour,", "int(time[14:16]) return f\"{int(time[0:2])} {months[int(time[3:5])-1]} {time[6:10]} year {hour} hour{'s' if hour!=1", "== \"4 August 1984 year 8 hours 15 minutes\" assert", "if __name__ == '__main__': print(date_time(\"01.01.2018 00:00\")) assert date_time(\"01.01.2018 00:00\") ==", "f\"{int(time[0:2])} {months[int(time[3:5])-1]} {time[6:10]} year {hour} hour{'s' if hour!=1 else ''}", "00:00\")) assert date_time(\"01.01.2018 00:00\") == \"1 January 2018 year 0", "if minute!=1 else ''}\" if __name__ == '__main__': print(date_time(\"01.01.2018 00:00\"))", "date_time(\"04.08.1984 08:15\") == \"4 August 1984 year 8 hours 15", "hour{'s' if hour!=1 else ''} {minute} minute{'s' if minute!=1 else", "date_time(time): months = [\"January\", \"February\", \"March\", \"April\", \"May\", \"June\", \"July\",", "\"March\", \"April\", \"May\", \"June\", \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"]", "assert date_time(\"04.08.1984 08:15\") == \"4 August 1984 year 8 hours", "__name__ == '__main__': print(date_time(\"01.01.2018 00:00\")) assert date_time(\"01.01.2018 00:00\") == \"1", "00:00\") == \"1 January 2018 year 0 hours 0 minutes\"" ]
[ "port as an integer.\"\"\" return self._port('ssl_port') @cachedproperty def tcp_port(self): \"\"\"Returns", "in-place.\"\"\" try: tmp = Peer(self.host, features) except Exception: pass else:", "pruning > 0: return pruning return None def _protocol_version_string(self, key):", "A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL", "a peer server.\"\"\" from ipaddress import ip_address from lbry.wallet.server import", "be # included in all copies or substantial portions of", "Peer(self.host, features) except Exception: pass else: self.update_features_from_peer(tmp) def update_features_from_peer(self, peer):", "def genesis_hash(self): \"\"\"Returns None if no SSL port, otherwise the", "\"\"\"Minimum protocol version as a string, e.g., 1.0\"\"\" return self._protocol_version_string('protocol_min')", "[pair for pair in pairs if pair[1]] def mark_bad(self): \"\"\"Mark", "try when making a connection.\"\"\" # Use a list not", "\"erbium1.sytes.net v1.0 s t\" Returns an instance of this Peer", "permission notice shall be # included in all copies or", "_string(self, key): result = self.features.get(key) return result if isinstance(result, str)", "int] = {} def __init__(self, host, features, source='unknown', ip_addr=None, last_good=0,", "feature in self.FEATURES: setattr(self, feature, getattr(peer, feature)) def connection_port_pairs(self): \"\"\"Return", "host) if port and 0 < port < 65536: return", "== 1: port = cls.DEFAULT_PORTS[part[0]] else: port = part[1:] if", "This should be set by the application DEFAULT_PORTS: Dict[str, int]", "port return None def _integer(self, key, d=None): d = d", "\"\"\"Return peers whose host matches our hostname or IP address.", "peer in peers if peer.host.lower() in candidates or peer.ip_addr ==", "features) except Exception: pass else: self.update_features_from_peer(tmp) def update_features_from_peer(self, peer): if", "the port as an integer.\"\"\" return self._port('ssl_port') @cachedproperty def tcp_port(self):", "represents the last connection that was # successful *and* successfully", "ATTRS = ('host', 'features', # metadata 'source', 'ip_addr', 'last_good', 'last_try',", "an integer.\"\"\" return self._port('tcp_port') @cachedproperty def server_version(self): \"\"\"Returns the server", "KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO", "making a connection.\"\"\" # Use a list not a set", "# All rights reserved. # # The MIT License (MIT)", "'v' + self.protocol_max] if self.pruning: parts.append(f'p{self.pruning:d}') for letter, port in", "for letter, port in (('s', self.ssl_port), ('t', self.tcp_port)): if port:", "real name as on IRC, such as \"erbium1.sytes.net v1.0 s", "except ValueError: pass return result if isinstance(result, int) else None", "features, source=source) for host in hosts if isinstance(host, str)] return", "charge, to any person obtaining # a copy of this", "item): \"\"\"Deserialize from a dictionary.\"\"\" return cls(**item) def matches(self, peers):", "if peer != self: self.features = peer.features for feature in", "# Use a list not a set - it's important", "util.is_valid_hostname(self.host) @cachedproperty def is_public(self): ip = self.ip_address if ip: return", "port as an integer.\"\"\" return self._string('genesis_hash') @cachedproperty def ssl_port(self): \"\"\"Returns", "AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM,", "given a host name (or IP address as a string),", "bool(self.other_port_pairs) @cachedproperty def is_tor(self): return self.host.endswith('.onion') @cachedproperty def is_valid(self): ip", "0: return pruning return None def _protocol_version_string(self, key): version_str =", "int) else None def _string(self, key): result = self.features.get(key) return", "ip_addr=None, last_good=0, last_try=0, try_count=0): \"\"\"Create a peer given a host", "last_good self.last_try = last_try self.try_count = try_count # Transient, non-persisted", "shall be # included in all copies or substantial portions", "this Peer class. \"\"\" host = 'nohost' features = {}", "self.features.get(key) return result if isinstance(result, str) else None @cachedproperty def", "isinstance(features, dict): hosts = features.get('hosts') if isinstance(hosts, dict): peers =", "as \"erbium1.sytes.net v1.0 s t\" Returns an instance of this", "source): peers = [] if isinstance(features, dict): hosts = features.get('hosts')", "# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF", "d=None): d = d or self.features result = d.get(key) if", "port < 65536: return port return None def _integer(self, key,", "sell copies of the Software, and to # permit persons", "also to remember for a while.\"\"\" self.bad = True def", "portions of the Software. # # THE SOFTWARE IS PROVIDED", "typing import Dict class Peer: # Protocol version ATTRS =", "(self.host.lower(), self.ip_addr) return [peer for peer in peers if peer.host.lower()", "LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A", "successfully verified, at which point # try_count is set to", "a string if known, otherwise None.\"\"\" return self._string('server_version') @cachedproperty def", "features.copy() # Canonicalize / clean-up for feature in self.FEATURES: self.features[feature]", "for feature in self.FEATURES: setattr(self, feature, getattr(peer, feature)) def connection_port_pairs(self):", "part[1:] elif part[0] == 'p': features['pruning'] = part[1:] features.update(ports) features['hosts']", "WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND", "# # The above copyright notice and this permission notice", "from typing import Dict class Peer: # Protocol version ATTRS", "publish, # distribute, sublicense, and/or sell copies of the Software,", "of (kind, port) pairs to try when making a connection.\"\"\"", "return port return None def _integer(self, key, d=None): d =", "the pruning level as an integer. None indicates no pruning.\"\"\"", "return None def _integer(self, key, d=None): d = d or", "pass return result if isinstance(result, int) else None def _string(self,", "TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR", "@classmethod def from_real_name(cls, real_name, source): \"\"\"Real name is a real", "None if isinstance(result, str): try: result = int(result) except ValueError:", "\"\"\"Deserialize from a dictionary.\"\"\" return cls(**item) def matches(self, peers): \"\"\"Return", "a while.\"\"\" self.bad = True def check_ports(self, other): \"\"\"Remember differing", "string, e.g., 1.1\"\"\" return self._protocol_version_string('protocol_max') def to_tuple(self): \"\"\"The tuple ((ip,", "part continue if part[0] in ('s', 't'): if len(part) ==", "or failure to # verify increment the try_count. self.last_good =", "isinstance(result, str) else None @cachedproperty def genesis_hash(self): \"\"\"Returns None if", "use, copy, modify, merge, publish, # distribute, sublicense, and/or sell", "'ip_addr', 'last_good', 'last_try', 'try_count') FEATURES = ('pruning', 'server_version', 'protocol_min', 'protocol_max',", "dict): peers = [Peer(host, features, source=source) for host in hosts", "THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE", "dictionary.\"\"\" return cls(**item) def matches(self, peers): \"\"\"Return peers whose host", "port and 0 < port < 65536: return port return", "a real name as on IRC, such as \"erbium1.sytes.net v1.0", "verified, at which point # try_count is set to 0.", "NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS", "last_try self.try_count = try_count # Transient, non-persisted metadata self.bad =", "details = self.real_name().split()[1:] return (self.ip_addr or self.host, self.host, details) def", "as a string, e.g., 1.1\"\"\" return self._protocol_version_string('protocol_max') def to_tuple(self): \"\"\"The", "= [] if isinstance(features, dict): hosts = features.get('hosts') if isinstance(hosts,", "# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT", "the registered # ports first. pairs = [('SSL', self.ssl_port), ('TCP',", "modify, merge, publish, # distribute, sublicense, and/or sell copies of", "is_valid(self): ip = self.ip_address if ip: return ((ip.is_global or ip.is_private)", "= self.ip_address if ip: return ((ip.is_global or ip.is_private) and not", "return '' return tuple(self.ip_addr.split('.')[:2]) def serialize(self): \"\"\"Serialize to a dictionary.\"\"\"", "a string, e.g., 1.0\"\"\" return self._protocol_version_string('protocol_min') @cachedproperty def protocol_max(self): \"\"\"Maximum", "in enumerate(real_name.split()): if n == 0: host = part continue", "OR IN CONNECTION # WITH THE SOFTWARE OR THE USE", "self.features.get('hosts') if isinstance(hosts, dict): host = hosts.get(self.host) port = self._integer(key,", "of this peer as used on IRC.\"\"\" def port_text(letter, port):", "\"\"\"Return a list of (kind, port) pairs to try when", "protocol_min(self): \"\"\"Minimum protocol version as a string, e.g., 1.0\"\"\" return", "self.last_try = last_try self.try_count = try_count # Transient, non-persisted metadata", "other.ssl_port != self.ssl_port: self.other_port_pairs.add(('SSL', other.ssl_port)) if other.tcp_port != self.tcp_port: self.other_port_pairs.add(('TCP',", "to # the following conditions: # # The above copyright", "@classmethod def deserialize(cls, item): \"\"\"Deserialize from a dictionary.\"\"\" return cls(**item)", "self.FEATURES: self.features[feature] = getattr(self, feature) # Metadata self.source = source", "feature)) def connection_port_pairs(self): \"\"\"Return a list of (kind, port) pairs", "and not (ip.is_multicast or ip.is_unspecified)) return util.is_valid_hostname(self.host) @cachedproperty def is_public(self):", "(ip.is_multicast or ip.is_unspecified)) return util.is_valid_hostname(self.host) @cachedproperty def is_public(self): ip =", "if ip: return self.is_valid and not ip.is_private else: return self.is_valid", "key): version_str = self.features.get(key) ptuple = util.protocol_tuple(version_str) return util.version_string(ptuple) @cachedproperty", "expected in response to a peers subscription.\"\"\" details = self.real_name().split()[1:]", "+ self.protocol_max] if self.pruning: parts.append(f'p{self.pruning:d}') for letter, port in (('s',", "from lbry.wallet.server.util import cachedproperty from typing import Dict class Peer:", "{}) self.host = host self.features = features.copy() # Canonicalize /", "last connection that was # successful *and* successfully verified, at", "without restriction, including # without limitation the rights to use,", "was # successful *and* successfully verified, at which point #", "record of the source.\"\"\" assert isinstance(host, str) assert isinstance(features, dict)", "def from_real_name(cls, real_name, source): \"\"\"Real name is a real name", "None indicates no pruning.\"\"\" pruning = self._integer('pruning') if pruning and", "host, features, source='unknown', ip_addr=None, last_good=0, last_try=0, try_count=0): \"\"\"Create a peer", "Metadata self.source = source self.ip_addr = ip_addr # last_good represents", "@cachedproperty def ip_address(self): \"\"\"The host as a python ip_address object,", "for host in hosts if isinstance(host, str)] return peers @classmethod", "sublicense, and/or sell copies of the Software, and to #", "= [Peer(host, features, source=source) for host in hosts if isinstance(host,", "if self.pruning: parts.append(f'p{self.pruning:d}') for letter, port in (('s', self.ssl_port), ('t',", "in ('s', 't'): if len(part) == 1: port = cls.DEFAULT_PORTS[part[0]]", "__str__(self): return self.host def update_features(self, features): \"\"\"Update features in-place.\"\"\" try:", "version_str = self.features.get(key) ptuple = util.protocol_tuple(version_str) return util.version_string(ptuple) @cachedproperty def", "other.ssl_port)) if other.tcp_port != self.tcp_port: self.other_port_pairs.add(('TCP', other.tcp_port)) return bool(self.other_port_pairs) @cachedproperty", "\"\"\"Real name is a real name as on IRC, such", "real_name(self): \"\"\"Real name of this peer as used on IRC.\"\"\"", "self.other_port_pairs.add(('SSL', other.ssl_port)) if other.tcp_port != self.tcp_port: self.other_port_pairs.add(('TCP', other.tcp_port)) return bool(self.other_port_pairs)", "= {} def __init__(self, host, features, source='unknown', ip_addr=None, last_good=0, last_try=0,", "'protocol_max', 'ssl_port', 'tcp_port') # This should be set by the", "persons to whom the Software is furnished to do so,", "\"\"\"Serialize to a dictionary.\"\"\" return {attr: getattr(self, attr) for attr", "return self._string('genesis_hash') @cachedproperty def ssl_port(self): \"\"\"Returns None if no SSL", "t\" Returns an instance of this Peer class. \"\"\" host", "the Software. # # THE SOFTWARE IS PROVIDED \"AS IS\",", "parts.append(f'p{self.pruning:d}') for letter, port in (('s', self.ssl_port), ('t', self.tcp_port)): if", "but also to remember for a while.\"\"\" self.bad = True", "self.features = peer.features for feature in self.FEATURES: setattr(self, feature, getattr(peer,", "in response to a peers subscription.\"\"\" details = self.real_name().split()[1:] return", "genesis_hash(self): \"\"\"Returns None if no SSL port, otherwise the port", "port)) return ' '.join(parts) @classmethod def from_real_name(cls, real_name, source): \"\"\"Real", "dict) assert host in features.get('hosts', {}) self.host = host self.features", "self.last_good = last_good self.last_try = last_try self.try_count = try_count #", "enumerate(real_name.split()): if n == 0: host = part continue if", "server version as a string if known, otherwise None.\"\"\" return", "bad to avoid reconnects but also to remember for a", "all copies or substantial portions of the Software. # #", "util from lbry.wallet.server.util import cachedproperty from typing import Dict class", "host in hosts if isinstance(host, str)] return peers @classmethod def", "a dictionary.\"\"\" return {attr: getattr(self, attr) for attr in self.ATTRS}", "OR OTHER DEALINGS IN THE SOFTWARE. \"\"\"Representation of a peer", "server.\"\"\" from ipaddress import ip_address from lbry.wallet.server import util from", "1.1\"\"\" return self._protocol_version_string('protocol_max') def to_tuple(self): \"\"\"The tuple ((ip, host, details)", "port else: ports['tcp_port'] = port elif part[0] == 'v': features['protocol_max']", "= self.real_name().split()[1:] return (self.ip_addr or self.host, self.host, details) def real_name(self):", "reserved. # # The MIT License (MIT) # # Permission", "including # without limitation the rights to use, copy, modify,", "tuple(self.ip_addr.split('.')[:2]) def serialize(self): \"\"\"Serialize to a dictionary.\"\"\" return {attr: getattr(self,", "# without limitation the rights to use, copy, modify, merge,", "# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF", "otherwise the port as an integer.\"\"\" return self._string('genesis_hash') @cachedproperty def", "== self.DEFAULT_PORTS.get(letter): return letter else: return letter + str(port) parts", "s t\" Returns an instance of this Peer class. \"\"\"", "def ip_address(self): \"\"\"The host as a python ip_address object, or", "isinstance(result, str): try: result = int(result) except ValueError: pass return", "ipaddress import ip_address from lbry.wallet.server import util from lbry.wallet.server.util import", "Returns an instance of this Peer class. \"\"\" host =", "\"\"\"Returns None if no SSL port, otherwise the port as", "\"\"\"The host as a python ip_address object, or None.\"\"\" try:", "tmp = Peer(self.host, features) except Exception: pass else: self.update_features_from_peer(tmp) def", "or None.\"\"\" try: return ip_address(self.host) except ValueError: return None def", "= ('pruning', 'server_version', 'protocol_min', 'protocol_max', 'ssl_port', 'tcp_port') # This should", "self.ssl_port), ('TCP', self.tcp_port)] while self.other_port_pairs: pairs.append(self.other_port_pairs.pop()) return [pair for pair", "included in all copies or substantial portions of the Software.", "ip: return ((ip.is_global or ip.is_private) and not (ip.is_multicast or ip.is_unspecified))", "def real_name(self): \"\"\"Real name of this peer as used on", "update_features(self, features): \"\"\"Update features in-place.\"\"\" try: tmp = Peer(self.host, features)", "try: tmp = Peer(self.host, features) except Exception: pass else: self.update_features_from_peer(tmp)", "\"\"\" host = 'nohost' features = {} ports = {}", "if n == 0: host = part continue if part[0]", "as a string, e.g., 1.0\"\"\" return self._protocol_version_string('protocol_min') @cachedproperty def protocol_max(self):", "to do so, subject to # the following conditions: #", "notice shall be # included in all copies or substantial", "feature) # Metadata self.source = source self.ip_addr = ip_addr #", "= Peer(self.host, features) except Exception: pass else: self.update_features_from_peer(tmp) def update_features_from_peer(self,", "else: self.update_features_from_peer(tmp) def update_features_from_peer(self, peer): if peer != self: self.features", "it's important to try the registered # ports first. pairs", "self._port('ssl_port') @cachedproperty def tcp_port(self): \"\"\"Returns None if no TCP port,", "first. pairs = [('SSL', self.ssl_port), ('TCP', self.tcp_port)] while self.other_port_pairs: pairs.append(self.other_port_pairs.pop())", "mark_bad(self): \"\"\"Mark as bad to avoid reconnects but also to", "Software without restriction, including # without limitation the rights to", "should be set by the application DEFAULT_PORTS: Dict[str, int] =", "return util.version_string(ptuple) @cachedproperty def protocol_min(self): \"\"\"Minimum protocol version as a", "ports['ssl_port'] = port else: ports['tcp_port'] = port elif part[0] ==", "(the # \"Software\"), to deal in the Software without restriction,", "# The above copyright notice and this permission notice shall", "peers_from_features(cls, features, source): peers = [] if isinstance(features, dict): hosts", "return self._port('ssl_port') @cachedproperty def tcp_port(self): \"\"\"Returns None if no TCP", "= True def check_ports(self, other): \"\"\"Remember differing ports in case", "to 0. Failure to connect or failure to # verify", "port elif part[0] == 'v': features['protocol_max'] = features['protocol_min'] = part[1:]", "return self._protocol_version_string('protocol_min') @cachedproperty def protocol_max(self): \"\"\"Maximum protocol version as a", "in the Software without restriction, including # without limitation the", "# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT.", "EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES", "ssl_port(self): \"\"\"Returns None if no SSL port, otherwise the port", "letter, port in (('s', self.ssl_port), ('t', self.tcp_port)): if port: parts.append(port_text(letter,", "== 0: host = part continue if part[0] in ('s',", "IS\", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED,", "for pair in pairs if pair[1]] def mark_bad(self): \"\"\"Mark as", "in features.get('hosts', {}) self.host = host self.features = features.copy() #", "of this software and associated documentation files (the # \"Software\"),", "subject to # the following conditions: # # The above", "== 's': ports['ssl_port'] = port else: ports['tcp_port'] = port elif", "as on IRC, such as \"erbium1.sytes.net v1.0 s t\" Returns", "getattr(self, feature) # Metadata self.source = source self.ip_addr = ip_addr", "to # verify increment the try_count. self.last_good = last_good self.last_try", "+ str(port) parts = [self.host, 'v' + self.protocol_max] if self.pruning:", "attr) for attr in self.ATTRS} def _port(self, key): hosts =", "try_count=0): \"\"\"Create a peer given a host name (or IP", "host name (or IP address as a string), a dictionary", "our hostname or IP address. Additionally include all peers whose", "to use, copy, modify, merge, publish, # distribute, sublicense, and/or", "following conditions: # # The above copyright notice and this", "name is a real name as on IRC, such as", "else: ports['tcp_port'] = port elif part[0] == 'v': features['protocol_max'] =", "ValueError: pass return result if isinstance(result, int) else None def", "if isinstance(result, str): try: result = int(result) except ValueError: pass", "Additionally include all peers whose IP address matches our hostname", "that is an IP address. \"\"\" candidates = (self.host.lower(), self.ip_addr)", "= [self.host, 'v' + self.protocol_max] if self.pruning: parts.append(f'p{self.pruning:d}') for letter,", "conditions: # # The above copyright notice and this permission", "def __str__(self): return self.host def update_features(self, features): \"\"\"Update features in-place.\"\"\"", "part in enumerate(real_name.split()): if n == 0: host = part", "elif part[0] == 'p': features['pruning'] = part[1:] features.update(ports) features['hosts'] =", "License (MIT) # # Permission is hereby granted, free of", "return bool(self.other_port_pairs) @cachedproperty def is_tor(self): return self.host.endswith('.onion') @cachedproperty def is_valid(self):", "return ip_address(self.host) except ValueError: return None def bucket(self): if self.is_tor:", "ip.is_private else: return self.is_valid and self.host != 'localhost' @cachedproperty def", "name (or IP address as a string), a dictionary of", "{} for n, part in enumerate(real_name.split()): if n == 0:", "\"\"\"Returns the server version as a string if known, otherwise", "# # All rights reserved. # # The MIT License", "> 0: return pruning return None def _protocol_version_string(self, key): version_str", "pairs to try when making a connection.\"\"\" # Use a", "part[1:] if part[0] == 's': ports['ssl_port'] = port else: ports['tcp_port']", "self._protocol_version_string('protocol_max') def to_tuple(self): \"\"\"The tuple ((ip, host, details) expected in", "str(port) parts = [self.host, 'v' + self.protocol_max] if self.pruning: parts.append(f'p{self.pruning:d}')", "removed one.\"\"\" if other.ssl_port != self.ssl_port: self.other_port_pairs.add(('SSL', other.ssl_port)) if other.tcp_port", "if self.is_tor: return 'onion' if not self.ip_addr: return '' return", "THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY", "them or removed one.\"\"\" if other.ssl_port != self.ssl_port: self.other_port_pairs.add(('SSL', other.ssl_port))", "@cachedproperty def server_version(self): \"\"\"Returns the server version as a string", "if isinstance(result, int) else None def _string(self, key): result =", "def _string(self, key): result = self.features.get(key) return result if isinstance(result,", "obtaining # a copy of this software and associated documentation", "source.\"\"\" assert isinstance(host, str) assert isinstance(features, dict) assert host in", "on IRC.\"\"\" def port_text(letter, port): if port == self.DEFAULT_PORTS.get(letter): return", "level as an integer. None indicates no pruning.\"\"\" pruning =", "None @cachedproperty def genesis_hash(self): \"\"\"Returns None if no SSL port,", "is_public(self): ip = self.ip_address if ip: return self.is_valid and not", "!= self: self.features = peer.features for feature in self.FEATURES: setattr(self,", "source='unknown', ip_addr=None, last_good=0, last_try=0, try_count=0): \"\"\"Create a peer given a", "LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR", "try_count. self.last_good = last_good self.last_try = last_try self.try_count = try_count", "= part[1:] features.update(ports) features['hosts'] = {host: ports} return cls(host, features,", "free of charge, to any person obtaining # a copy", "key): result = self.features.get(key) return result if isinstance(result, str) else", "update_features_from_peer(self, peer): if peer != self: self.features = peer.features for", "set() self.status = 2 @classmethod def peers_from_features(cls, features, source): peers", "PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, # EXPRESS", "a string, e.g., 1.1\"\"\" return self._protocol_version_string('protocol_max') def to_tuple(self): \"\"\"The tuple", "features['protocol_min'] = part[1:] elif part[0] == 'p': features['pruning'] = part[1:]", "copy of this software and associated documentation files (the #", "d = d or self.features result = d.get(key) if isinstance(d,", "return self.host def update_features(self, features): \"\"\"Update features in-place.\"\"\" try: tmp", "(MIT) # # Permission is hereby granted, free of charge,", "copy, modify, merge, publish, # distribute, sublicense, and/or sell copies", "Transient, non-persisted metadata self.bad = False self.other_port_pairs = set() self.status", "else None @cachedproperty def genesis_hash(self): \"\"\"Returns None if no SSL", "that was # successful *and* successfully verified, at which point", "as a string if known, otherwise None.\"\"\" return self._string('server_version') @cachedproperty", "to remember for a while.\"\"\" self.bad = True def check_ports(self,", "TCP port, otherwise the port as an integer.\"\"\" return self._port('tcp_port')", "for n, part in enumerate(real_name.split()): if n == 0: host", "IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF #", "is hereby granted, free of charge, to any person obtaining", "('pruning', 'server_version', 'protocol_min', 'protocol_max', 'ssl_port', 'tcp_port') # This should be", "for attr in self.ATTRS} def _port(self, key): hosts = self.features.get('hosts')", "def to_tuple(self): \"\"\"The tuple ((ip, host, details) expected in response", "of charge, to any person obtaining # a copy of", "above copyright notice and this permission notice shall be #", "one.\"\"\" if other.ssl_port != self.ssl_port: self.other_port_pairs.add(('SSL', other.ssl_port)) if other.tcp_port !=", "host, details) expected in response to a peers subscription.\"\"\" details", "as an integer. None indicates no pruning.\"\"\" pruning = self._integer('pruning')", "2017, <NAME> # # All rights reserved. # # The", "self.pruning: parts.append(f'p{self.pruning:d}') for letter, port in (('s', self.ssl_port), ('t', self.tcp_port)):", "an IP address. \"\"\" candidates = (self.host.lower(), self.ip_addr) return [peer", "the source.\"\"\" assert isinstance(host, str) assert isinstance(features, dict) assert host", "self.ip_addr) return [peer for peer in peers if peer.host.lower() in", "= 'nohost' features = {} ports = {} for n,", "metadata self.bad = False self.other_port_pairs = set() self.status = 2", "else None def _string(self, key): result = self.features.get(key) return result", "point # try_count is set to 0. Failure to connect", "if pair[1]] def mark_bad(self): \"\"\"Mark as bad to avoid reconnects", "result if isinstance(result, int) else None def _string(self, key): result", "matches(self, peers): \"\"\"Return peers whose host matches our hostname or", "host matches our hostname or IP address. Additionally include all", "'localhost' @cachedproperty def ip_address(self): \"\"\"The host as a python ip_address", "str): try: result = int(result) except ValueError: pass return result", "known, otherwise None.\"\"\" return self._string('server_version') @cachedproperty def pruning(self): \"\"\"Returns the", "if pruning and pruning > 0: return pruning return None", "setattr(self, feature, getattr(peer, feature)) def connection_port_pairs(self): \"\"\"Return a list of", "ValueError: return None def bucket(self): if self.is_tor: return 'onion' if", "self._integer('pruning') if pruning and pruning > 0: return pruning return", "result = d.get(key) if isinstance(d, dict) else None if isinstance(result,", "= {} ports = {} for n, part in enumerate(real_name.split()):", "0 < port < 65536: return port return None def", "features in-place.\"\"\" try: tmp = Peer(self.host, features) except Exception: pass", "*and* successfully verified, at which point # try_count is set", "version as a string, e.g., 1.0\"\"\" return self._protocol_version_string('protocol_min') @cachedproperty def", "# # Permission is hereby granted, free of charge, to", "pruning level as an integer. None indicates no pruning.\"\"\" pruning", "port = cls.DEFAULT_PORTS[part[0]] else: port = part[1:] if part[0] ==", "!= self.tcp_port: self.other_port_pairs.add(('TCP', other.tcp_port)) return bool(self.other_port_pairs) @cachedproperty def is_tor(self): return", "self.is_tor: return 'onion' if not self.ip_addr: return '' return tuple(self.ip_addr.split('.')[:2])", "return tuple(self.ip_addr.split('.')[:2]) def serialize(self): \"\"\"Serialize to a dictionary.\"\"\" return {attr:", "def is_valid(self): ip = self.ip_address if ip: return ((ip.is_global or", "OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND #", "permit persons to whom the Software is furnished to do", "- it's important to try the registered # ports first.", "copies of the Software, and to # permit persons to", "import Dict class Peer: # Protocol version ATTRS = ('host',", "= ip_addr # last_good represents the last connection that was", "cls(**item) def matches(self, peers): \"\"\"Return peers whose host matches our", "e.g., 1.0\"\"\" return self._protocol_version_string('protocol_min') @cachedproperty def protocol_max(self): \"\"\"Maximum protocol version", "@cachedproperty def ssl_port(self): \"\"\"Returns None if no SSL port, otherwise", "port = part[1:] if part[0] == 's': ports['ssl_port'] = port", "integer.\"\"\" return self._port('tcp_port') @cachedproperty def server_version(self): \"\"\"Returns the server version", "ports in case server operator changed them or removed one.\"\"\"", "features, source): peers = [] if isinstance(features, dict): hosts =", "a list not a set - it's important to try", "('host', 'features', # metadata 'source', 'ip_addr', 'last_good', 'last_try', 'try_count') FEATURES", "part[0] == 'p': features['pruning'] = part[1:] features.update(ports) features['hosts'] = {host:", "string if known, otherwise None.\"\"\" return self._string('server_version') @cachedproperty def pruning(self):", "import cachedproperty from typing import Dict class Peer: # Protocol", "from_real_name(cls, real_name, source): \"\"\"Real name is a real name as", "rights reserved. # # The MIT License (MIT) # #", "= int(result) except ValueError: pass return result if isinstance(result, int)", "WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN", "_integer(self, key, d=None): d = d or self.features result =", "is_tor(self): return self.host.endswith('.onion') @cachedproperty def is_valid(self): ip = self.ip_address if", "ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT", "NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE #", "at which point # try_count is set to 0. Failure", "differing ports in case server operator changed them or removed", "THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE", "part[0] == 'v': features['protocol_max'] = features['protocol_min'] = part[1:] elif part[0]", "SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR", "letter + str(port) parts = [self.host, 'v' + self.protocol_max] if", "# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS", "otherwise None.\"\"\" return self._string('server_version') @cachedproperty def pruning(self): \"\"\"Returns the pruning", "and associated documentation files (the # \"Software\"), to deal in", "indicates no pruning.\"\"\" pruning = self._integer('pruning') if pruning and pruning", "or substantial portions of the Software. # # THE SOFTWARE", "'t'): if len(part) == 1: port = cls.DEFAULT_PORTS[part[0]] else: port", "in pairs if pair[1]] def mark_bad(self): \"\"\"Mark as bad to", "def deserialize(cls, item): \"\"\"Deserialize from a dictionary.\"\"\" return cls(**item) def", "OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT", "self: self.features = peer.features for feature in self.FEATURES: setattr(self, feature,", "by the application DEFAULT_PORTS: Dict[str, int] = {} def __init__(self,", "a list of (kind, port) pairs to try when making", "name as on IRC, such as \"erbium1.sytes.net v1.0 s t\"", "n == 0: host = part continue if part[0] in", "IP address. Additionally include all peers whose IP address matches", "be set by the application DEFAULT_PORTS: Dict[str, int] = {}", "return 'onion' if not self.ip_addr: return '' return tuple(self.ip_addr.split('.')[:2]) def", "'p': features['pruning'] = part[1:] features.update(ports) features['hosts'] = {host: ports} return", "def port_text(letter, port): if port == self.DEFAULT_PORTS.get(letter): return letter else:", "IN THE SOFTWARE. \"\"\"Representation of a peer server.\"\"\" from ipaddress", "python ip_address object, or None.\"\"\" try: return ip_address(self.host) except ValueError:", "== 'v': features['protocol_max'] = features['protocol_min'] = part[1:] elif part[0] ==", "of the source.\"\"\" assert isinstance(host, str) assert isinstance(features, dict) assert", "else: port = part[1:] if part[0] == 's': ports['ssl_port'] =", "{attr: getattr(self, attr) for attr in self.ATTRS} def _port(self, key):", "@cachedproperty def is_tor(self): return self.host.endswith('.onion') @cachedproperty def is_valid(self): ip =", "@cachedproperty def genesis_hash(self): \"\"\"Returns None if no SSL port, otherwise", "return pruning return None def _protocol_version_string(self, key): version_str = self.features.get(key)", "return cls(**item) def matches(self, peers): \"\"\"Return peers whose host matches", "pairs.append(self.other_port_pairs.pop()) return [pair for pair in pairs if pair[1]] def", "address matches our hostname if that is an IP address.", "def update_features(self, features): \"\"\"Update features in-place.\"\"\" try: tmp = Peer(self.host,", "ip = self.ip_address if ip: return ((ip.is_global or ip.is_private) and", "(self.ip_addr or self.host, self.host, details) def real_name(self): \"\"\"Real name of", "address as a string), a dictionary of features, and a", "Dict[str, int] = {} def __init__(self, host, features, source='unknown', ip_addr=None,", "def ssl_port(self): \"\"\"Returns None if no SSL port, otherwise the", "# Permission is hereby granted, free of charge, to any", "the port as an integer.\"\"\" return self._port('tcp_port') @cachedproperty def server_version(self):", "return self._string('server_version') @cachedproperty def pruning(self): \"\"\"Returns the pruning level as", "part[1:] features.update(ports) features['hosts'] = {host: ports} return cls(host, features, source)", "subscription.\"\"\" details = self.real_name().split()[1:] return (self.ip_addr or self.host, self.host, details)", "self.DEFAULT_PORTS.get(letter): return letter else: return letter + str(port) parts =", "False self.other_port_pairs = set() self.status = 2 @classmethod def peers_from_features(cls,", "the Software is furnished to do so, subject to #", "protocol version as a string, e.g., 1.1\"\"\" return self._protocol_version_string('protocol_max') def", "# # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY", "= ('host', 'features', # metadata 'source', 'ip_addr', 'last_good', 'last_try', 'try_count')", "last_good=0, last_try=0, try_count=0): \"\"\"Create a peer given a host name", "not ip.is_private else: return self.is_valid and self.host != 'localhost' @cachedproperty", "dict): host = hosts.get(self.host) port = self._integer(key, host) if port", "string, e.g., 1.0\"\"\" return self._protocol_version_string('protocol_min') @cachedproperty def protocol_max(self): \"\"\"Maximum protocol", "peer): if peer != self: self.features = peer.features for feature", "= hosts.get(self.host) port = self._integer(key, host) if port and 0", "if isinstance(d, dict) else None if isinstance(result, str): try: result", "def peers_from_features(cls, features, source): peers = [] if isinstance(features, dict):", "without limitation the rights to use, copy, modify, merge, publish,", "self.ip_addr = ip_addr # last_good represents the last connection that", "self._protocol_version_string('protocol_min') @cachedproperty def protocol_max(self): \"\"\"Maximum protocol version as a string,", "self._string('genesis_hash') @cachedproperty def ssl_port(self): \"\"\"Returns None if no SSL port,", "try: result = int(result) except ValueError: pass return result if", "self.ip_addr: return '' return tuple(self.ip_addr.split('.')[:2]) def serialize(self): \"\"\"Serialize to a", "if port == self.DEFAULT_PORTS.get(letter): return letter else: return letter +", "# verify increment the try_count. self.last_good = last_good self.last_try =", "# This should be set by the application DEFAULT_PORTS: Dict[str,", "if port and 0 < port < 65536: return port", "import ip_address from lbry.wallet.server import util from lbry.wallet.server.util import cachedproperty", "'.join(parts) @classmethod def from_real_name(cls, real_name, source): \"\"\"Real name is a", "if no TCP port, otherwise the port as an integer.\"\"\"", "self.try_count = try_count # Transient, non-persisted metadata self.bad = False", "dict): hosts = features.get('hosts') if isinstance(hosts, dict): peers = [Peer(host,", "from a dictionary.\"\"\" return cls(**item) def matches(self, peers): \"\"\"Return peers", "_port(self, key): hosts = self.features.get('hosts') if isinstance(hosts, dict): host =", "_protocol_version_string(self, key): version_str = self.features.get(key) ptuple = util.protocol_tuple(version_str) return util.version_string(ptuple)", "(('s', self.ssl_port), ('t', self.tcp_port)): if port: parts.append(port_text(letter, port)) return '", "= port else: ports['tcp_port'] = port elif part[0] == 'v':", "[Peer(host, features, source=source) for host in hosts if isinstance(host, str)]", "merge, publish, # distribute, sublicense, and/or sell copies of the", "limitation the rights to use, copy, modify, merge, publish, #", "or self.host, self.host, details) def real_name(self): \"\"\"Real name of this", "if other.ssl_port != self.ssl_port: self.other_port_pairs.add(('SSL', other.ssl_port)) if other.tcp_port != self.tcp_port:", "source): \"\"\"Real name is a real name as on IRC,", "@cachedproperty def pruning(self): \"\"\"Returns the pruning level as an integer.", "as a python ip_address object, or None.\"\"\" try: return ip_address(self.host)", "OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF", "return self._protocol_version_string('protocol_max') def to_tuple(self): \"\"\"The tuple ((ip, host, details) expected", "pairs = [('SSL', self.ssl_port), ('TCP', self.tcp_port)] while self.other_port_pairs: pairs.append(self.other_port_pairs.pop()) return", "{} def __init__(self, host, features, source='unknown', ip_addr=None, last_good=0, last_try=0, try_count=0):", "PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS", "a record of the source.\"\"\" assert isinstance(host, str) assert isinstance(features,", "hosts = features.get('hosts') if isinstance(hosts, dict): peers = [Peer(host, features,", "self.ssl_port: self.other_port_pairs.add(('SSL', other.ssl_port)) if other.tcp_port != self.tcp_port: self.other_port_pairs.add(('TCP', other.tcp_port)) return", "port, otherwise the port as an integer.\"\"\" return self._port('ssl_port') @cachedproperty", "return letter else: return letter + str(port) parts = [self.host,", "so, subject to # the following conditions: # # The", "in candidates or peer.ip_addr == self.host] def __str__(self): return self.host", "dict) else None if isinstance(result, str): try: result = int(result)", "to a peers subscription.\"\"\" details = self.real_name().split()[1:] return (self.ip_addr or", "FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO", "getattr(self, attr) for attr in self.ATTRS} def _port(self, key): hosts", "ip = self.ip_address if ip: return self.is_valid and not ip.is_private", "def connection_port_pairs(self): \"\"\"Return a list of (kind, port) pairs to", "letter else: return letter + str(port) parts = [self.host, 'v'", "do so, subject to # the following conditions: # #", "as bad to avoid reconnects but also to remember for", "0. Failure to connect or failure to # verify increment", "server_version(self): \"\"\"Returns the server version as a string if known,", "the rights to use, copy, modify, merge, publish, # distribute,", "\"\"\"Returns None if no TCP port, otherwise the port as", "remember for a while.\"\"\" self.bad = True def check_ports(self, other):", "/ clean-up for feature in self.FEATURES: self.features[feature] = getattr(self, feature)", "elif part[0] == 'v': features['protocol_max'] = features['protocol_min'] = part[1:] elif", "instance of this Peer class. \"\"\" host = 'nohost' features", "if isinstance(host, str)] return peers @classmethod def deserialize(cls, item): \"\"\"Deserialize", "set - it's important to try the registered # ports", "WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING", "self.bad = True def check_ports(self, other): \"\"\"Remember differing ports in", "self.source = source self.ip_addr = ip_addr # last_good represents the", "if peer.host.lower() in candidates or peer.ip_addr == self.host] def __str__(self):", "assert host in features.get('hosts', {}) self.host = host self.features =", "Software, and to # permit persons to whom the Software", "OTHER DEALINGS IN THE SOFTWARE. \"\"\"Representation of a peer server.\"\"\"", "peers subscription.\"\"\" details = self.real_name().split()[1:] return (self.ip_addr or self.host, self.host,", "if that is an IP address. \"\"\" candidates = (self.host.lower(),", "peer given a host name (or IP address as a", "to connect or failure to # verify increment the try_count.", "self.ssl_port), ('t', self.tcp_port)): if port: parts.append(port_text(letter, port)) return ' '.join(parts)", "the following conditions: # # The above copyright notice and", "a python ip_address object, or None.\"\"\" try: return ip_address(self.host) except", "address. \"\"\" candidates = (self.host.lower(), self.ip_addr) return [peer for peer", "candidates = (self.host.lower(), self.ip_addr) return [peer for peer in peers", "port) pairs to try when making a connection.\"\"\" # Use", "distribute, sublicense, and/or sell copies of the Software, and to", "the last connection that was # successful *and* successfully verified,", "parts = [self.host, 'v' + self.protocol_max] if self.pruning: parts.append(f'p{self.pruning:d}') for", "peer.host.lower() in candidates or peer.ip_addr == self.host] def __str__(self): return", "IP address as a string), a dictionary of features, and", "pair in pairs if pair[1]] def mark_bad(self): \"\"\"Mark as bad", "# \"Software\"), to deal in the Software without restriction, including", "Copyright (c) 2017, <NAME> # # All rights reserved. #", "MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN", "= (self.host.lower(), self.ip_addr) return [peer for peer in peers if", "@cachedproperty def protocol_max(self): \"\"\"Maximum protocol version as a string, e.g.,", "in (('s', self.ssl_port), ('t', self.tcp_port)): if port: parts.append(port_text(letter, port)) return", "part[0] in ('s', 't'): if len(part) == 1: port =", "peer server.\"\"\" from ipaddress import ip_address from lbry.wallet.server import util", "\"\"\"Mark as bad to avoid reconnects but also to remember", "def serialize(self): \"\"\"Serialize to a dictionary.\"\"\" return {attr: getattr(self, attr)", "The MIT License (MIT) # # Permission is hereby granted,", "this permission notice shall be # included in all copies", "if isinstance(features, dict): hosts = features.get('hosts') if isinstance(hosts, dict): peers", "'onion' if not self.ip_addr: return '' return tuple(self.ip_addr.split('.')[:2]) def serialize(self):", "features['protocol_max'] = features['protocol_min'] = part[1:] elif part[0] == 'p': features['pruning']", "feature in self.FEATURES: self.features[feature] = getattr(self, feature) # Metadata self.source", "self.bad = False self.other_port_pairs = set() self.status = 2 @classmethod", "features, source='unknown', ip_addr=None, last_good=0, last_try=0, try_count=0): \"\"\"Create a peer given", "def bucket(self): if self.is_tor: return 'onion' if not self.ip_addr: return", "= d or self.features result = d.get(key) if isinstance(d, dict)", "'server_version', 'protocol_min', 'protocol_max', 'ssl_port', 'tcp_port') # This should be set", "include all peers whose IP address matches our hostname if", "\"\"\"Remember differing ports in case server operator changed them or", "host as a python ip_address object, or None.\"\"\" try: return", "< port < 65536: return port return None def _integer(self,", "response to a peers subscription.\"\"\" details = self.real_name().split()[1:] return (self.ip_addr", "self.is_valid and not ip.is_private else: return self.is_valid and self.host !=", "matches our hostname or IP address. Additionally include all peers", "last_try=0, try_count=0): \"\"\"Create a peer given a host name (or", "real_name, source): \"\"\"Real name is a real name as on", "features['pruning'] = part[1:] features.update(ports) features['hosts'] = {host: ports} return cls(host,", "address. Additionally include all peers whose IP address matches our", "pass else: self.update_features_from_peer(tmp) def update_features_from_peer(self, peer): if peer != self:", "True def check_ports(self, other): \"\"\"Remember differing ports in case server", "1: port = cls.DEFAULT_PORTS[part[0]] else: port = part[1:] if part[0]", "our hostname if that is an IP address. \"\"\" candidates", "in self.FEATURES: self.features[feature] = getattr(self, feature) # Metadata self.source =", "to whom the Software is furnished to do so, subject", "= last_try self.try_count = try_count # Transient, non-persisted metadata self.bad", "details) expected in response to a peers subscription.\"\"\" details =", "@cachedproperty def is_valid(self): ip = self.ip_address if ip: return ((ip.is_global", "an integer.\"\"\" return self._string('genesis_hash') @cachedproperty def ssl_port(self): \"\"\"Returns None if", "notice and this permission notice shall be # included in", "ptuple = util.protocol_tuple(version_str) return util.version_string(ptuple) @cachedproperty def protocol_min(self): \"\"\"Minimum protocol", "# Canonicalize / clean-up for feature in self.FEATURES: self.features[feature] =", "OF OR IN CONNECTION # WITH THE SOFTWARE OR THE", "WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT", "'v': features['protocol_max'] = features['protocol_min'] = part[1:] elif part[0] == 'p':", "'tcp_port') # This should be set by the application DEFAULT_PORTS:", "# a copy of this software and associated documentation files", "to_tuple(self): \"\"\"The tuple ((ip, host, details) expected in response to", "return self.is_valid and not ip.is_private else: return self.is_valid and self.host", "\"\"\"Returns the pruning level as an integer. None indicates no", "class Peer: # Protocol version ATTRS = ('host', 'features', #", "an instance of this Peer class. \"\"\" host = 'nohost'", "check_ports(self, other): \"\"\"Remember differing ports in case server operator changed", "and a record of the source.\"\"\" assert isinstance(host, str) assert", "SSL port, otherwise the port as an integer.\"\"\" return self._port('ssl_port')", "Software. # # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT", "'last_good', 'last_try', 'try_count') FEATURES = ('pruning', 'server_version', 'protocol_min', 'protocol_max', 'ssl_port',", "Software is furnished to do so, subject to # the", "a host name (or IP address as a string), a", "util.protocol_tuple(version_str) return util.version_string(ptuple) @cachedproperty def protocol_min(self): \"\"\"Minimum protocol version as", "this peer as used on IRC.\"\"\" def port_text(letter, port): if", "except Exception: pass else: self.update_features_from_peer(tmp) def update_features_from_peer(self, peer): if peer", "if len(part) == 1: port = cls.DEFAULT_PORTS[part[0]] else: port =", "0: host = part continue if part[0] in ('s', 't'):", "IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, #", "< 65536: return port return None def _integer(self, key, d=None):", "deserialize(cls, item): \"\"\"Deserialize from a dictionary.\"\"\" return cls(**item) def matches(self,", "source=source) for host in hosts if isinstance(host, str)] return peers", "Protocol version ATTRS = ('host', 'features', # metadata 'source', 'ip_addr',", "= part continue if part[0] in ('s', 't'): if len(part)", "which point # try_count is set to 0. Failure to", "\"\"\"The tuple ((ip, host, details) expected in response to a", "((ip, host, details) expected in response to a peers subscription.\"\"\"", "port == self.DEFAULT_PORTS.get(letter): return letter else: return letter + str(port)", "host = part continue if part[0] in ('s', 't'): if", "ports = {} for n, part in enumerate(real_name.split()): if n", "or removed one.\"\"\" if other.ssl_port != self.ssl_port: self.other_port_pairs.add(('SSL', other.ssl_port)) if", "CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER", "person obtaining # a copy of this software and associated", "def is_public(self): ip = self.ip_address if ip: return self.is_valid and", "# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER", "= getattr(self, feature) # Metadata self.source = source self.ip_addr =", "Exception: pass else: self.update_features_from_peer(tmp) def update_features_from_peer(self, peer): if peer !=", "IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING", "set by the application DEFAULT_PORTS: Dict[str, int] = {} def", "MIT License (MIT) # # Permission is hereby granted, free", "# included in all copies or substantial portions of the", "operator changed them or removed one.\"\"\" if other.ssl_port != self.ssl_port:", "assert isinstance(host, str) assert isinstance(features, dict) assert host in features.get('hosts',", "protocol_max(self): \"\"\"Maximum protocol version as a string, e.g., 1.1\"\"\" return", "NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR", "65536: return port return None def _integer(self, key, d=None): d", "ip.is_private) and not (ip.is_multicast or ip.is_unspecified)) return util.is_valid_hostname(self.host) @cachedproperty def", "a peer given a host name (or IP address as", "\"\"\"Representation of a peer server.\"\"\" from ipaddress import ip_address from", "other): \"\"\"Remember differing ports in case server operator changed them", "THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY", "self.tcp_port: self.other_port_pairs.add(('TCP', other.tcp_port)) return bool(self.other_port_pairs) @cachedproperty def is_tor(self): return self.host.endswith('.onion')", "return result if isinstance(result, str) else None @cachedproperty def genesis_hash(self):", "if ip: return ((ip.is_global or ip.is_private) and not (ip.is_multicast or", "substantial portions of the Software. # # THE SOFTWARE IS", "version ATTRS = ('host', 'features', # metadata 'source', 'ip_addr', 'last_good',", "integer.\"\"\" return self._port('ssl_port') @cachedproperty def tcp_port(self): \"\"\"Returns None if no", "str) assert isinstance(features, dict) assert host in features.get('hosts', {}) self.host", "ports['tcp_port'] = port elif part[0] == 'v': features['protocol_max'] = features['protocol_min']", "to any person obtaining # a copy of this software", "set to 0. Failure to connect or failure to #", "lbry.wallet.server import util from lbry.wallet.server.util import cachedproperty from typing import", "whose host matches our hostname or IP address. Additionally include", "= self._integer('pruning') if pruning and pruning > 0: return pruning", "version as a string, e.g., 1.1\"\"\" return self._protocol_version_string('protocol_max') def to_tuple(self):", "'s': ports['ssl_port'] = port else: ports['tcp_port'] = port elif part[0]", "the Software, and to # permit persons to whom the", "= self.features.get('hosts') if isinstance(hosts, dict): host = hosts.get(self.host) port =", "return ' '.join(parts) @classmethod def from_real_name(cls, real_name, source): \"\"\"Real name", "[('SSL', self.ssl_port), ('TCP', self.tcp_port)] while self.other_port_pairs: pairs.append(self.other_port_pairs.pop()) return [pair for", "if isinstance(hosts, dict): host = hosts.get(self.host) port = self._integer(key, host)", "util.version_string(ptuple) @cachedproperty def protocol_min(self): \"\"\"Minimum protocol version as a string,", "source self.ip_addr = ip_addr # last_good represents the last connection", "a dictionary of features, and a record of the source.\"\"\"", "return self._port('tcp_port') @cachedproperty def server_version(self): \"\"\"Returns the server version as", "hostname if that is an IP address. \"\"\" candidates =", "\"AS IS\", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR", "= self.ip_address if ip: return self.is_valid and not ip.is_private else:", "' '.join(parts) @classmethod def from_real_name(cls, real_name, source): \"\"\"Real name is", "isinstance(hosts, dict): peers = [Peer(host, features, source=source) for host in", "server operator changed them or removed one.\"\"\" if other.ssl_port !=", "of the Software, and to # permit persons to whom", "SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,", "!= self.ssl_port: self.other_port_pairs.add(('SSL', other.ssl_port)) if other.tcp_port != self.tcp_port: self.other_port_pairs.add(('TCP', other.tcp_port))", "pairs if pair[1]] def mark_bad(self): \"\"\"Mark as bad to avoid", "self.ATTRS} def _port(self, key): hosts = self.features.get('hosts') if isinstance(hosts, dict):", "isinstance(d, dict) else None if isinstance(result, str): try: result =", "ip_address(self.host) except ValueError: return None def bucket(self): if self.is_tor: return", "if isinstance(hosts, dict): peers = [Peer(host, features, source=source) for host", "EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE", "1.0\"\"\" return self._protocol_version_string('protocol_min') @cachedproperty def protocol_max(self): \"\"\"Maximum protocol version as", "\"\"\"Maximum protocol version as a string, e.g., 1.1\"\"\" return self._protocol_version_string('protocol_max')", "USE OR OTHER DEALINGS IN THE SOFTWARE. \"\"\"Representation of a", "in self.FEATURES: setattr(self, feature, getattr(peer, feature)) def connection_port_pairs(self): \"\"\"Return a", "self.host] def __str__(self): return self.host def update_features(self, features): \"\"\"Update features", "= set() self.status = 2 @classmethod def peers_from_features(cls, features, source):", "= port elif part[0] == 'v': features['protocol_max'] = features['protocol_min'] =", "self.tcp_port)] while self.other_port_pairs: pairs.append(self.other_port_pairs.pop()) return [pair for pair in pairs", "host = hosts.get(self.host) port = self._integer(key, host) if port and", "as an integer.\"\"\" return self._port('tcp_port') @cachedproperty def server_version(self): \"\"\"Returns the", "= {} for n, part in enumerate(real_name.split()): if n ==", "hosts if isinstance(host, str)] return peers @classmethod def deserialize(cls, item):", "serialize(self): \"\"\"Serialize to a dictionary.\"\"\" return {attr: getattr(self, attr) for", "port: parts.append(port_text(letter, port)) return ' '.join(parts) @classmethod def from_real_name(cls, real_name,", "registered # ports first. pairs = [('SSL', self.ssl_port), ('TCP', self.tcp_port)]", "ip.is_unspecified)) return util.is_valid_hostname(self.host) @cachedproperty def is_public(self): ip = self.ip_address if", "= self.features.get(key) ptuple = util.protocol_tuple(version_str) return util.version_string(ptuple) @cachedproperty def protocol_min(self):", "2 @classmethod def peers_from_features(cls, features, source): peers = [] if", "in case server operator changed them or removed one.\"\"\" if", "such as \"erbium1.sytes.net v1.0 s t\" Returns an instance of", "int(result) except ValueError: pass return result if isinstance(result, int) else", "return {attr: getattr(self, attr) for attr in self.ATTRS} def _port(self,", "peers if peer.host.lower() in candidates or peer.ip_addr == self.host] def", "last_good represents the last connection that was # successful *and*", "SOFTWARE. \"\"\"Representation of a peer server.\"\"\" from ipaddress import ip_address", "try_count # Transient, non-persisted metadata self.bad = False self.other_port_pairs =", "getattr(peer, feature)) def connection_port_pairs(self): \"\"\"Return a list of (kind, port)", "self.tcp_port)): if port: parts.append(port_text(letter, port)) return ' '.join(parts) @classmethod def", "OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION #", "from ipaddress import ip_address from lbry.wallet.server import util from lbry.wallet.server.util", "= 2 @classmethod def peers_from_features(cls, features, source): peers = []", "a connection.\"\"\" # Use a list not a set -", "rights to use, copy, modify, merge, publish, # distribute, sublicense,", "verify increment the try_count. self.last_good = last_good self.last_try = last_try", "def server_version(self): \"\"\"Returns the server version as a string if", "pruning and pruning > 0: return pruning return None def", "isinstance(hosts, dict): host = hosts.get(self.host) port = self._integer(key, host) if", "pruning(self): \"\"\"Returns the pruning level as an integer. None indicates", "copyright notice and this permission notice shall be # included", "OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \"\"\"Representation", "result if isinstance(result, str) else None @cachedproperty def genesis_hash(self): \"\"\"Returns", "def pruning(self): \"\"\"Returns the pruning level as an integer. None", "on IRC, such as \"erbium1.sytes.net v1.0 s t\" Returns an", "@cachedproperty def is_public(self): ip = self.ip_address if ip: return self.is_valid", "self.host def update_features(self, features): \"\"\"Update features in-place.\"\"\" try: tmp =", "and/or sell copies of the Software, and to # permit", "self._string('server_version') @cachedproperty def pruning(self): \"\"\"Returns the pruning level as an", "class. \"\"\" host = 'nohost' features = {} ports =", "= self._integer(key, host) if port and 0 < port <", "of this Peer class. \"\"\" host = 'nohost' features =", "if known, otherwise None.\"\"\" return self._string('server_version') @cachedproperty def pruning(self): \"\"\"Returns", "tuple ((ip, host, details) expected in response to a peers", "= features.get('hosts') if isinstance(hosts, dict): peers = [Peer(host, features, source=source)", "assert isinstance(features, dict) assert host in features.get('hosts', {}) self.host =", "= host self.features = features.copy() # Canonicalize / clean-up for", "Use a list not a set - it's important to", "for a while.\"\"\" self.bad = True def check_ports(self, other): \"\"\"Remember", "and pruning > 0: return pruning return None def _protocol_version_string(self,", "if other.tcp_port != self.tcp_port: self.other_port_pairs.add(('TCP', other.tcp_port)) return bool(self.other_port_pairs) @cachedproperty def", "to # permit persons to whom the Software is furnished", "otherwise the port as an integer.\"\"\" return self._port('tcp_port') @cachedproperty def", "OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES", "used on IRC.\"\"\" def port_text(letter, port): if port == self.DEFAULT_PORTS.get(letter):", "self.host, self.host, details) def real_name(self): \"\"\"Real name of this peer", "WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE,", "peers = [Peer(host, features, source=source) for host in hosts if", "and not ip.is_private else: return self.is_valid and self.host != 'localhost'", "THE SOFTWARE. \"\"\"Representation of a peer server.\"\"\" from ipaddress import", "pruning.\"\"\" pruning = self._integer('pruning') if pruning and pruning > 0:", "def protocol_min(self): \"\"\"Minimum protocol version as a string, e.g., 1.0\"\"\"", "def __init__(self, host, features, source='unknown', ip_addr=None, last_good=0, last_try=0, try_count=0): \"\"\"Create", "for feature in self.FEATURES: self.features[feature] = getattr(self, feature) # Metadata", "this software and associated documentation files (the # \"Software\"), to", "def is_tor(self): return self.host.endswith('.onion') @cachedproperty def is_valid(self): ip = self.ip_address", "= source self.ip_addr = ip_addr # last_good represents the last", "hostname or IP address. Additionally include all peers whose IP", "@cachedproperty def tcp_port(self): \"\"\"Returns None if no TCP port, otherwise", "result = int(result) except ValueError: pass return result if isinstance(result,", "of the Software. # # THE SOFTWARE IS PROVIDED \"AS", "is furnished to do so, subject to # the following", "ip_address object, or None.\"\"\" try: return ip_address(self.host) except ValueError: return", "self.features result = d.get(key) if isinstance(d, dict) else None if", "if part[0] in ('s', 't'): if len(part) == 1: port", "('t', self.tcp_port)): if port: parts.append(port_text(letter, port)) return ' '.join(parts) @classmethod", "<NAME> # # All rights reserved. # # The MIT", "self.ip_address if ip: return self.is_valid and not ip.is_private else: return", "SSL port, otherwise the port as an integer.\"\"\" return self._string('genesis_hash')", "IP address matches our hostname if that is an IP", "[self.host, 'v' + self.protocol_max] if self.pruning: parts.append(f'p{self.pruning:d}') for letter, port", "whom the Software is furnished to do so, subject to", "= False self.other_port_pairs = set() self.status = 2 @classmethod def", "peer.features for feature in self.FEATURES: setattr(self, feature, getattr(peer, feature)) def", "hosts.get(self.host) port = self._integer(key, host) if port and 0 <", "in self.ATTRS} def _port(self, key): hosts = self.features.get('hosts') if isinstance(hosts,", "failure to # verify increment the try_count. self.last_good = last_good", "in hosts if isinstance(host, str)] return peers @classmethod def deserialize(cls,", "part[0] == 's': ports['ssl_port'] = port else: ports['tcp_port'] = port", "# permit persons to whom the Software is furnished to", "clean-up for feature in self.FEATURES: self.features[feature] = getattr(self, feature) #", "= try_count # Transient, non-persisted metadata self.bad = False self.other_port_pairs", "self.other_port_pairs.add(('TCP', other.tcp_port)) return bool(self.other_port_pairs) @cachedproperty def is_tor(self): return self.host.endswith('.onion') @cachedproperty", "self.is_valid and self.host != 'localhost' @cachedproperty def ip_address(self): \"\"\"The host", "v1.0 s t\" Returns an instance of this Peer class.", "d.get(key) if isinstance(d, dict) else None if isinstance(result, str): try:", "if part[0] == 's': ports['ssl_port'] = port else: ports['tcp_port'] =", "def protocol_max(self): \"\"\"Maximum protocol version as a string, e.g., 1.1\"\"\"", "= util.protocol_tuple(version_str) return util.version_string(ptuple) @cachedproperty def protocol_min(self): \"\"\"Minimum protocol version", "{} ports = {} for n, part in enumerate(real_name.split()): if", "whose IP address matches our hostname if that is an", "LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN", "'features', # metadata 'source', 'ip_addr', 'last_good', 'last_try', 'try_count') FEATURES =", "Peer class. \"\"\" host = 'nohost' features = {} ports", "continue if part[0] in ('s', 't'): if len(part) == 1:", "\"\"\"Update features in-place.\"\"\" try: tmp = Peer(self.host, features) except Exception:", "'last_try', 'try_count') FEATURES = ('pruning', 'server_version', 'protocol_min', 'protocol_max', 'ssl_port', 'tcp_port')", "tcp_port(self): \"\"\"Returns None if no TCP port, otherwise the port", "integer. None indicates no pruning.\"\"\" pruning = self._integer('pruning') if pruning", "'source', 'ip_addr', 'last_good', 'last_try', 'try_count') FEATURES = ('pruning', 'server_version', 'protocol_min',", "return None def _protocol_version_string(self, key): version_str = self.features.get(key) ptuple =", "a copy of this software and associated documentation files (the", "# the following conditions: # # The above copyright notice", "files (the # \"Software\"), to deal in the Software without", "# Transient, non-persisted metadata self.bad = False self.other_port_pairs = set()", "documentation files (the # \"Software\"), to deal in the Software", "None def bucket(self): if self.is_tor: return 'onion' if not self.ip_addr:", "('s', 't'): if len(part) == 1: port = cls.DEFAULT_PORTS[part[0]] else:", "key, d=None): d = d or self.features result = d.get(key)", "ports first. pairs = [('SSL', self.ssl_port), ('TCP', self.tcp_port)] while self.other_port_pairs:", "attr in self.ATTRS} def _port(self, key): hosts = self.features.get('hosts') if", "__init__(self, host, features, source='unknown', ip_addr=None, last_good=0, last_try=0, try_count=0): \"\"\"Create a", "# last_good represents the last connection that was # successful", "and this permission notice shall be # included in all", "self.real_name().split()[1:] return (self.ip_addr or self.host, self.host, details) def real_name(self): \"\"\"Real", "features.get('hosts') if isinstance(hosts, dict): peers = [Peer(host, features, source=source) for", "COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR", "OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT", "'ssl_port', 'tcp_port') # This should be set by the application", "if not self.ip_addr: return '' return tuple(self.ip_addr.split('.')[:2]) def serialize(self): \"\"\"Serialize", "return letter + str(port) parts = [self.host, 'v' + self.protocol_max]", "and to # permit persons to whom the Software is", "BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS", "port, otherwise the port as an integer.\"\"\" return self._string('genesis_hash') @cachedproperty", "return None def bucket(self): if self.is_tor: return 'onion' if not", "self.update_features_from_peer(tmp) def update_features_from_peer(self, peer): if peer != self: self.features =", "a dictionary.\"\"\" return cls(**item) def matches(self, peers): \"\"\"Return peers whose", "increment the try_count. self.last_good = last_good self.last_try = last_try self.try_count", "pair[1]] def mark_bad(self): \"\"\"Mark as bad to avoid reconnects but", "def matches(self, peers): \"\"\"Return peers whose host matches our hostname", "[peer for peer in peers if peer.host.lower() in candidates or", "def _integer(self, key, d=None): d = d or self.features result", "if no SSL port, otherwise the port as an integer.\"\"\"", "features = {} ports = {} for n, part in", "Peer: # Protocol version ATTRS = ('host', 'features', # metadata", "connect or failure to # verify increment the try_count. self.last_good", "feature, getattr(peer, feature)) def connection_port_pairs(self): \"\"\"Return a list of (kind,", "DEALINGS IN THE SOFTWARE. \"\"\"Representation of a peer server.\"\"\" from", "isinstance(result, int) else None def _string(self, key): result = self.features.get(key)", "is set to 0. Failure to connect or failure to", "return self.is_valid and self.host != 'localhost' @cachedproperty def ip_address(self): \"\"\"The", "self.ip_address if ip: return ((ip.is_global or ip.is_private) and not (ip.is_multicast", "no SSL port, otherwise the port as an integer.\"\"\" return", "Canonicalize / clean-up for feature in self.FEATURES: self.features[feature] = getattr(self,", "pruning = self._integer('pruning') if pruning and pruning > 0: return", "@classmethod def peers_from_features(cls, features, source): peers = [] if isinstance(features,", "CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION #", "CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN", "Failure to connect or failure to # verify increment the", "isinstance(host, str)] return peers @classmethod def deserialize(cls, item): \"\"\"Deserialize from", "to try when making a connection.\"\"\" # Use a list", "port as an integer.\"\"\" return self._port('tcp_port') @cachedproperty def server_version(self): \"\"\"Returns", "(kind, port) pairs to try when making a connection.\"\"\" #", "peer.ip_addr == self.host] def __str__(self): return self.host def update_features(self, features):", "except ValueError: return None def bucket(self): if self.is_tor: return 'onion'", "def update_features_from_peer(self, peer): if peer != self: self.features = peer.features", "self.host = host self.features = features.copy() # Canonicalize / clean-up", "or ip.is_private) and not (ip.is_multicast or ip.is_unspecified)) return util.is_valid_hostname(self.host) @cachedproperty", "AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR", "return ((ip.is_global or ip.is_private) and not (ip.is_multicast or ip.is_unspecified)) return", "# metadata 'source', 'ip_addr', 'last_good', 'last_try', 'try_count') FEATURES = ('pruning',", "== self.host] def __str__(self): return self.host def update_features(self, features): \"\"\"Update", "port): if port == self.DEFAULT_PORTS.get(letter): return letter else: return letter", "= cls.DEFAULT_PORTS[part[0]] else: port = part[1:] if part[0] == 's':", "not a set - it's important to try the registered", "('TCP', self.tcp_port)] while self.other_port_pairs: pairs.append(self.other_port_pairs.pop()) return [pair for pair in", "ip: return self.is_valid and not ip.is_private else: return self.is_valid and", "no pruning.\"\"\" pruning = self._integer('pruning') if pruning and pruning >", "changed them or removed one.\"\"\" if other.ssl_port != self.ssl_port: self.other_port_pairs.add(('SSL',", "# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE", "isinstance(features, dict) assert host in features.get('hosts', {}) self.host = host", "to avoid reconnects but also to remember for a while.\"\"\"", "non-persisted metadata self.bad = False self.other_port_pairs = set() self.status =", "not (ip.is_multicast or ip.is_unspecified)) return util.is_valid_hostname(self.host) @cachedproperty def is_public(self): ip", "to try the registered # ports first. pairs = [('SSL',", "def _port(self, key): hosts = self.features.get('hosts') if isinstance(hosts, dict): host", "peers whose host matches our hostname or IP address. Additionally", "None def _string(self, key): result = self.features.get(key) return result if", "a peers subscription.\"\"\" details = self.real_name().split()[1:] return (self.ip_addr or self.host,", "= part[1:] elif part[0] == 'p': features['pruning'] = part[1:] features.update(ports)", "list of (kind, port) pairs to try when making a", "ip_addr # last_good represents the last connection that was #", "associated documentation files (the # \"Software\"), to deal in the", "in all copies or substantial portions of the Software. #", "return [peer for peer in peers if peer.host.lower() in candidates", "copies or substantial portions of the Software. # # THE", "peers @classmethod def deserialize(cls, item): \"\"\"Deserialize from a dictionary.\"\"\" return", "from lbry.wallet.server import util from lbry.wallet.server.util import cachedproperty from typing", "parts.append(port_text(letter, port)) return ' '.join(parts) @classmethod def from_real_name(cls, real_name, source):", "host in features.get('hosts', {}) self.host = host self.features = features.copy()", "is an IP address. \"\"\" candidates = (self.host.lower(), self.ip_addr) return", "try_count is set to 0. Failure to connect or failure", "else: return self.is_valid and self.host != 'localhost' @cachedproperty def ip_address(self):", "try: return ip_address(self.host) except ValueError: return None def bucket(self): if", "name of this peer as used on IRC.\"\"\" def port_text(letter,", "to deal in the Software without restriction, including # without", "or peer.ip_addr == self.host] def __str__(self): return self.host def update_features(self,", "of a peer server.\"\"\" from ipaddress import ip_address from lbry.wallet.server", "ARISING FROM, OUT OF OR IN CONNECTION # WITH THE", "# The MIT License (MIT) # # Permission is hereby", "AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,", "connection that was # successful *and* successfully verified, at which", "self.status = 2 @classmethod def peers_from_features(cls, features, source): peers =", "a set - it's important to try the registered #", "try the registered # ports first. pairs = [('SSL', self.ssl_port),", "FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN", "if isinstance(result, str) else None @cachedproperty def genesis_hash(self): \"\"\"Returns None", "dictionary.\"\"\" return {attr: getattr(self, attr) for attr in self.ATTRS} def", "self.other_port_pairs: pairs.append(self.other_port_pairs.pop()) return [pair for pair in pairs if pair[1]]", "pruning return None def _protocol_version_string(self, key): version_str = self.features.get(key) ptuple", "FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE", "details) def real_name(self): \"\"\"Real name of this peer as used", "integer.\"\"\" return self._string('genesis_hash') @cachedproperty def ssl_port(self): \"\"\"Returns None if no", "host = 'nohost' features = {} ports = {} for", "self.protocol_max] if self.pruning: parts.append(f'p{self.pruning:d}') for letter, port in (('s', self.ssl_port),", "<reponame>snapperVibes/lbry-sdk # Copyright (c) 2017, <NAME> # # All rights", "or ip.is_unspecified)) return util.is_valid_hostname(self.host) @cachedproperty def is_public(self): ip = self.ip_address", "!= 'localhost' @cachedproperty def ip_address(self): \"\"\"The host as a python", "not self.ip_addr: return '' return tuple(self.ip_addr.split('.')[:2]) def serialize(self): \"\"\"Serialize to", "dictionary of features, and a record of the source.\"\"\" assert", "application DEFAULT_PORTS: Dict[str, int] = {} def __init__(self, host, features,", "the try_count. self.last_good = last_good self.last_try = last_try self.try_count =", "THE USE OR OTHER DEALINGS IN THE SOFTWARE. \"\"\"Representation of", "avoid reconnects but also to remember for a while.\"\"\" self.bad", "return (self.ip_addr or self.host, self.host, details) def real_name(self): \"\"\"Real name", "'nohost' features = {} ports = {} for n, part", "'' return tuple(self.ip_addr.split('.')[:2]) def serialize(self): \"\"\"Serialize to a dictionary.\"\"\" return", "[] if isinstance(features, dict): hosts = features.get('hosts') if isinstance(hosts, dict):", "def tcp_port(self): \"\"\"Returns None if no TCP port, otherwise the", "port, otherwise the port as an integer.\"\"\" return self._port('tcp_port') @cachedproperty", "self.host.endswith('.onion') @cachedproperty def is_valid(self): ip = self.ip_address if ip: return", "self._integer(key, host) if port and 0 < port < 65536:", "restriction, including # without limitation the rights to use, copy,", "str) else None @cachedproperty def genesis_hash(self): \"\"\"Returns None if no", "hereby granted, free of charge, to any person obtaining #", "ip_address(self): \"\"\"The host as a python ip_address object, or None.\"\"\"", "self.features[feature] = getattr(self, feature) # Metadata self.source = source self.ip_addr", "str)] return peers @classmethod def deserialize(cls, item): \"\"\"Deserialize from a", "no TCP port, otherwise the port as an integer.\"\"\" return", "hosts = self.features.get('hosts') if isinstance(hosts, dict): host = hosts.get(self.host) port", "version as a string if known, otherwise None.\"\"\" return self._string('server_version')", "the Software without restriction, including # without limitation the rights", "while self.other_port_pairs: pairs.append(self.other_port_pairs.pop()) return [pair for pair in pairs if", "key): hosts = self.features.get('hosts') if isinstance(hosts, dict): host = hosts.get(self.host)", "d or self.features result = d.get(key) if isinstance(d, dict) else", "an integer. None indicates no pruning.\"\"\" pruning = self._integer('pruning') if", "for peer in peers if peer.host.lower() in candidates or peer.ip_addr", "object, or None.\"\"\" try: return ip_address(self.host) except ValueError: return None", "FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT", "IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE", "= [('SSL', self.ssl_port), ('TCP', self.tcp_port)] while self.other_port_pairs: pairs.append(self.other_port_pairs.pop()) return [pair", "a string), a dictionary of features, and a record of", "= d.get(key) if isinstance(d, dict) else None if isinstance(result, str):", "furnished to do so, subject to # the following conditions:", "None def _protocol_version_string(self, key): version_str = self.features.get(key) ptuple = util.protocol_tuple(version_str)", "port_text(letter, port): if port == self.DEFAULT_PORTS.get(letter): return letter else: return", "@cachedproperty def protocol_min(self): \"\"\"Minimum protocol version as a string, e.g.,", "return self.host.endswith('.onion') @cachedproperty def is_valid(self): ip = self.ip_address if ip:", "= self.features.get(key) return result if isinstance(result, str) else None @cachedproperty", "SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.", "len(part) == 1: port = cls.DEFAULT_PORTS[part[0]] else: port = part[1:]", "= features.copy() # Canonicalize / clean-up for feature in self.FEATURES:", "when making a connection.\"\"\" # Use a list not a", "the application DEFAULT_PORTS: Dict[str, int] = {} def __init__(self, host,", "of features, and a record of the source.\"\"\" assert isinstance(host,", "and self.host != 'localhost' @cachedproperty def ip_address(self): \"\"\"The host as", "\"\"\"Create a peer given a host name (or IP address", "PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE", "OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR", "IRC.\"\"\" def port_text(letter, port): if port == self.DEFAULT_PORTS.get(letter): return letter", "self.FEATURES: setattr(self, feature, getattr(peer, feature)) def connection_port_pairs(self): \"\"\"Return a list", "any person obtaining # a copy of this software and", "# try_count is set to 0. Failure to connect or", "peers = [] if isinstance(features, dict): hosts = features.get('hosts') if", "# ports first. pairs = [('SSL', self.ssl_port), ('TCP', self.tcp_port)] while", "peer != self: self.features = peer.features for feature in self.FEATURES:", "ip_address from lbry.wallet.server import util from lbry.wallet.server.util import cachedproperty from", "features, and a record of the source.\"\"\" assert isinstance(host, str)", "OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH", "list not a set - it's important to try the", "peers): \"\"\"Return peers whose host matches our hostname or IP", "granted, free of charge, to any person obtaining # a", "other.tcp_port != self.tcp_port: self.other_port_pairs.add(('TCP', other.tcp_port)) return bool(self.other_port_pairs) @cachedproperty def is_tor(self):", "in peers if peer.host.lower() in candidates or peer.ip_addr == self.host]", "reconnects but also to remember for a while.\"\"\" self.bad =", "or self.features result = d.get(key) if isinstance(d, dict) else None", "self.other_port_pairs = set() self.status = 2 @classmethod def peers_from_features(cls, features,", "TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION", "matches our hostname if that is an IP address. \"\"\"", "'try_count') FEATURES = ('pruning', 'server_version', 'protocol_min', 'protocol_max', 'ssl_port', 'tcp_port') #", "\"Software\"), to deal in the Software without restriction, including #", "== 'p': features['pruning'] = part[1:] features.update(ports) features['hosts'] = {host: ports}", "else None if isinstance(result, str): try: result = int(result) except", "software and associated documentation files (the # \"Software\"), to deal", "features.get('hosts', {}) self.host = host self.features = features.copy() # Canonicalize", "the server version as a string if known, otherwise None.\"\"\"", "is a real name as on IRC, such as \"erbium1.sytes.net", "result = self.features.get(key) return result if isinstance(result, str) else None", "None.\"\"\" try: return ip_address(self.host) except ValueError: return None def bucket(self):", "an integer.\"\"\" return self._port('ssl_port') @cachedproperty def tcp_port(self): \"\"\"Returns None if", "(or IP address as a string), a dictionary of features,", "self.host != 'localhost' @cachedproperty def ip_address(self): \"\"\"The host as a", "def _protocol_version_string(self, key): version_str = self.features.get(key) ptuple = util.protocol_tuple(version_str) return", "# Metadata self.source = source self.ip_addr = ip_addr # last_good", "metadata 'source', 'ip_addr', 'last_good', 'last_try', 'try_count') FEATURES = ('pruning', 'server_version',", "self._port('tcp_port') @cachedproperty def server_version(self): \"\"\"Returns the server version as a", "\"\"\"Real name of this peer as used on IRC.\"\"\" def", "case server operator changed them or removed one.\"\"\" if other.ssl_port", "\"\"\" candidates = (self.host.lower(), self.ip_addr) return [peer for peer in", "DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF", "connection.\"\"\" # Use a list not a set - it's", "lbry.wallet.server.util import cachedproperty from typing import Dict class Peer: #", "successful *and* successfully verified, at which point # try_count is", "None def _integer(self, key, d=None): d = d or self.features", "e.g., 1.1\"\"\" return self._protocol_version_string('protocol_max') def to_tuple(self): \"\"\"The tuple ((ip, host,", "((ip.is_global or ip.is_private) and not (ip.is_multicast or ip.is_unspecified)) return util.is_valid_hostname(self.host)", "OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR", "self.features = features.copy() # Canonicalize / clean-up for feature in", "BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,", "deal in the Software without restriction, including # without limitation", "peers whose IP address matches our hostname if that is", "as a string), a dictionary of features, and a record", "return peers @classmethod def deserialize(cls, item): \"\"\"Deserialize from a dictionary.\"\"\"", "important to try the registered # ports first. pairs =", "port in (('s', self.ssl_port), ('t', self.tcp_port)): if port: parts.append(port_text(letter, port))", "OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT,", "'protocol_min', 'protocol_max', 'ssl_port', 'tcp_port') # This should be set by", "self.features.get(key) ptuple = util.protocol_tuple(version_str) return util.version_string(ptuple) @cachedproperty def protocol_min(self): \"\"\"Minimum", "All rights reserved. # # The MIT License (MIT) #", "None if no TCP port, otherwise the port as an", "connection_port_pairs(self): \"\"\"Return a list of (kind, port) pairs to try", "return result if isinstance(result, int) else None def _string(self, key):", "isinstance(host, str) assert isinstance(features, dict) assert host in features.get('hosts', {})", "cachedproperty from typing import Dict class Peer: # Protocol version", "Dict class Peer: # Protocol version ATTRS = ('host', 'features',", "IP address. \"\"\" candidates = (self.host.lower(), self.ip_addr) return [peer for", "protocol version as a string, e.g., 1.0\"\"\" return self._protocol_version_string('protocol_min') @cachedproperty", "return [pair for pair in pairs if pair[1]] def mark_bad(self):", "candidates or peer.ip_addr == self.host] def __str__(self): return self.host def", "# successful *and* successfully verified, at which point # try_count", "to a dictionary.\"\"\" return {attr: getattr(self, attr) for attr in", "# Copyright (c) 2017, <NAME> # # All rights reserved.", "# Protocol version ATTRS = ('host', 'features', # metadata 'source',", "peer as used on IRC.\"\"\" def port_text(letter, port): if port", "Permission is hereby granted, free of charge, to any person", "as an integer.\"\"\" return self._port('ssl_port') @cachedproperty def tcp_port(self): \"\"\"Returns None", "HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER", "DEFAULT_PORTS: Dict[str, int] = {} def __init__(self, host, features, source='unknown',", "= last_good self.last_try = last_try self.try_count = try_count # Transient,", "ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED", "port = self._integer(key, host) if port and 0 < port", "cls.DEFAULT_PORTS[part[0]] else: port = part[1:] if part[0] == 's': ports['ssl_port']", "self.host, details) def real_name(self): \"\"\"Real name of this peer as", "The above copyright notice and this permission notice shall be", "import util from lbry.wallet.server.util import cachedproperty from typing import Dict", "def check_ports(self, other): \"\"\"Remember differing ports in case server operator", "INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY,", "None if no SSL port, otherwise the port as an", "# # The MIT License (MIT) # # Permission is", "and 0 < port < 65536: return port return None", "other.tcp_port)) return bool(self.other_port_pairs) @cachedproperty def is_tor(self): return self.host.endswith('.onion') @cachedproperty def", "return util.is_valid_hostname(self.host) @cachedproperty def is_public(self): ip = self.ip_address if ip:", "as an integer.\"\"\" return self._string('genesis_hash') @cachedproperty def ssl_port(self): \"\"\"Returns None", "IRC, such as \"erbium1.sytes.net v1.0 s t\" Returns an instance", "= part[1:] if part[0] == 's': ports['ssl_port'] = port else:", "= peer.features for feature in self.FEATURES: setattr(self, feature, getattr(peer, feature))", "otherwise the port as an integer.\"\"\" return self._port('ssl_port') @cachedproperty def", "all peers whose IP address matches our hostname if that", "(c) 2017, <NAME> # # All rights reserved. # #", "# distribute, sublicense, and/or sell copies of the Software, and", "bucket(self): if self.is_tor: return 'onion' if not self.ip_addr: return ''", "string), a dictionary of features, and a record of the", "ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION", "the port as an integer.\"\"\" return self._string('genesis_hash') @cachedproperty def ssl_port(self):", "as used on IRC.\"\"\" def port_text(letter, port): if port ==", "n, part in enumerate(real_name.split()): if n == 0: host =", "def mark_bad(self): \"\"\"Mark as bad to avoid reconnects but also", "None.\"\"\" return self._string('server_version') @cachedproperty def pruning(self): \"\"\"Returns the pruning level", "= features['protocol_min'] = part[1:] elif part[0] == 'p': features['pruning'] =", "features): \"\"\"Update features in-place.\"\"\" try: tmp = Peer(self.host, features) except", "IN CONNECTION # WITH THE SOFTWARE OR THE USE OR", "or IP address. Additionally include all peers whose IP address", "while.\"\"\" self.bad = True def check_ports(self, other): \"\"\"Remember differing ports", "else: return letter + str(port) parts = [self.host, 'v' +", "FEATURES = ('pruning', 'server_version', 'protocol_min', 'protocol_max', 'ssl_port', 'tcp_port') # This", "host self.features = features.copy() # Canonicalize / clean-up for feature", "if port: parts.append(port_text(letter, port)) return ' '.join(parts) @classmethod def from_real_name(cls," ]
[ "[], }, \"events\": {}, \"alarm_systems\": {}, \"groups\": {}, \"lights\": {},", "\"home_assistant\": {\"get_system_info\": \"fake data\"}, \"config_entry\": dict(config_entry.data), \"deconz_config\": DECONZ_CONFIG, \"websocket_state\": STATE_RUNNING,", "unittest.mock import patch from pydeconz.websocket import STATE_RUNNING from homeassistant.const import", "\"\"\"Test deCONZ diagnostics.\"\"\" from unittest.mock import patch from pydeconz.websocket import", "tests.components.diagnostics import get_diagnostics_for_config_entry async def test_entry_diagnostics( hass, hass_client, aioclient_mock, mock_deconz_websocket", "from pydeconz.websocket import STATE_RUNNING from homeassistant.const import Platform from .test_gateway", "with patch( \"homeassistant.helpers.system_info.async_get_system_info\", return_value={\"get_system_info\": \"fake data\"}, ): assert await get_diagnostics_for_config_entry(", "str(Platform.FAN): [], str(Platform.LIGHT): [], str(Platform.LOCK): [], str(Platform.NUMBER): [], str(Platform.SENSOR): [],", "[], str(Platform.NUMBER): [], str(Platform.SENSOR): [], str(Platform.SIREN): [], str(Platform.SWITCH): [], },", "{\"get_system_info\": \"fake data\"}, \"config_entry\": dict(config_entry.data), \"deconz_config\": DECONZ_CONFIG, \"websocket_state\": STATE_RUNNING, \"deconz_ids\":", "homeassistant.const import Platform from .test_gateway import DECONZ_CONFIG, setup_deconz_integration from tests.components.diagnostics", "import STATE_RUNNING from homeassistant.const import Platform from .test_gateway import DECONZ_CONFIG,", "str(Platform.LOCK): [], str(Platform.NUMBER): [], str(Platform.SENSOR): [], str(Platform.SIREN): [], str(Platform.SWITCH): [],", "\"events\": {}, \"alarm_systems\": {}, \"groups\": {}, \"lights\": {}, \"scenes\": {},", "STATE_RUNNING, \"deconz_ids\": {}, \"entities\": { str(Platform.ALARM_CONTROL_PANEL): [], str(Platform.BINARY_SENSOR): [], str(Platform.CLIMATE):", "deCONZ diagnostics.\"\"\" from unittest.mock import patch from pydeconz.websocket import STATE_RUNNING", "[], str(Platform.CLIMATE): [], str(Platform.COVER): [], str(Platform.FAN): [], str(Platform.LIGHT): [], str(Platform.LOCK):", "diagnostics.\"\"\" from unittest.mock import patch from pydeconz.websocket import STATE_RUNNING from", "hass, hass_client, aioclient_mock, mock_deconz_websocket ): \"\"\"Test config entry diagnostics.\"\"\" config_entry", "await get_diagnostics_for_config_entry( hass, hass_client, config_entry ) == { \"home_assistant\": {\"get_system_info\":", "setup_deconz_integration(hass, aioclient_mock) await mock_deconz_websocket(state=STATE_RUNNING) await hass.async_block_till_done() with patch( \"homeassistant.helpers.system_info.async_get_system_info\", return_value={\"get_system_info\":", "[], str(Platform.SWITCH): [], }, \"events\": {}, \"alarm_systems\": {}, \"groups\": {},", "\"deconz_ids\": {}, \"entities\": { str(Platform.ALARM_CONTROL_PANEL): [], str(Platform.BINARY_SENSOR): [], str(Platform.CLIMATE): [],", "str(Platform.LIGHT): [], str(Platform.LOCK): [], str(Platform.NUMBER): [], str(Platform.SENSOR): [], str(Platform.SIREN): [],", "\"websocket_state\": STATE_RUNNING, \"deconz_ids\": {}, \"entities\": { str(Platform.ALARM_CONTROL_PANEL): [], str(Platform.BINARY_SENSOR): [],", "{}, \"groups\": {}, \"lights\": {}, \"scenes\": {}, \"sensors\": {}, }", "}, \"events\": {}, \"alarm_systems\": {}, \"groups\": {}, \"lights\": {}, \"scenes\":", "patch from pydeconz.websocket import STATE_RUNNING from homeassistant.const import Platform from", ") == { \"home_assistant\": {\"get_system_info\": \"fake data\"}, \"config_entry\": dict(config_entry.data), \"deconz_config\":", "= await setup_deconz_integration(hass, aioclient_mock) await mock_deconz_websocket(state=STATE_RUNNING) await hass.async_block_till_done() with patch(", "diagnostics.\"\"\" config_entry = await setup_deconz_integration(hass, aioclient_mock) await mock_deconz_websocket(state=STATE_RUNNING) await hass.async_block_till_done()", "setup_deconz_integration from tests.components.diagnostics import get_diagnostics_for_config_entry async def test_entry_diagnostics( hass, hass_client,", "str(Platform.SENSOR): [], str(Platform.SIREN): [], str(Platform.SWITCH): [], }, \"events\": {}, \"alarm_systems\":", "{ str(Platform.ALARM_CONTROL_PANEL): [], str(Platform.BINARY_SENSOR): [], str(Platform.CLIMATE): [], str(Platform.COVER): [], str(Platform.FAN):", "hass_client, aioclient_mock, mock_deconz_websocket ): \"\"\"Test config entry diagnostics.\"\"\" config_entry =", "def test_entry_diagnostics( hass, hass_client, aioclient_mock, mock_deconz_websocket ): \"\"\"Test config entry", "): \"\"\"Test config entry diagnostics.\"\"\" config_entry = await setup_deconz_integration(hass, aioclient_mock)", "{ \"home_assistant\": {\"get_system_info\": \"fake data\"}, \"config_entry\": dict(config_entry.data), \"deconz_config\": DECONZ_CONFIG, \"websocket_state\":", "data\"}, ): assert await get_diagnostics_for_config_entry( hass, hass_client, config_entry ) ==", "dict(config_entry.data), \"deconz_config\": DECONZ_CONFIG, \"websocket_state\": STATE_RUNNING, \"deconz_ids\": {}, \"entities\": { str(Platform.ALARM_CONTROL_PANEL):", "str(Platform.SIREN): [], str(Platform.SWITCH): [], }, \"events\": {}, \"alarm_systems\": {}, \"groups\":", "await setup_deconz_integration(hass, aioclient_mock) await mock_deconz_websocket(state=STATE_RUNNING) await hass.async_block_till_done() with patch( \"homeassistant.helpers.system_info.async_get_system_info\",", "[], str(Platform.SIREN): [], str(Platform.SWITCH): [], }, \"events\": {}, \"alarm_systems\": {},", "[], str(Platform.SENSOR): [], str(Platform.SIREN): [], str(Platform.SWITCH): [], }, \"events\": {},", "\"alarm_systems\": {}, \"groups\": {}, \"lights\": {}, \"scenes\": {}, \"sensors\": {},", "import DECONZ_CONFIG, setup_deconz_integration from tests.components.diagnostics import get_diagnostics_for_config_entry async def test_entry_diagnostics(", "{}, \"alarm_systems\": {}, \"groups\": {}, \"lights\": {}, \"scenes\": {}, \"sensors\":", "\"config_entry\": dict(config_entry.data), \"deconz_config\": DECONZ_CONFIG, \"websocket_state\": STATE_RUNNING, \"deconz_ids\": {}, \"entities\": {", "\"homeassistant.helpers.system_info.async_get_system_info\", return_value={\"get_system_info\": \"fake data\"}, ): assert await get_diagnostics_for_config_entry( hass, hass_client,", "str(Platform.NUMBER): [], str(Platform.SENSOR): [], str(Platform.SIREN): [], str(Platform.SWITCH): [], }, \"events\":", "DECONZ_CONFIG, \"websocket_state\": STATE_RUNNING, \"deconz_ids\": {}, \"entities\": { str(Platform.ALARM_CONTROL_PANEL): [], str(Platform.BINARY_SENSOR):", "DECONZ_CONFIG, setup_deconz_integration from tests.components.diagnostics import get_diagnostics_for_config_entry async def test_entry_diagnostics( hass,", "from .test_gateway import DECONZ_CONFIG, setup_deconz_integration from tests.components.diagnostics import get_diagnostics_for_config_entry async", "import patch from pydeconz.websocket import STATE_RUNNING from homeassistant.const import Platform", "hass.async_block_till_done() with patch( \"homeassistant.helpers.system_info.async_get_system_info\", return_value={\"get_system_info\": \"fake data\"}, ): assert await", "hass_client, config_entry ) == { \"home_assistant\": {\"get_system_info\": \"fake data\"}, \"config_entry\":", "STATE_RUNNING from homeassistant.const import Platform from .test_gateway import DECONZ_CONFIG, setup_deconz_integration", "\"fake data\"}, ): assert await get_diagnostics_for_config_entry( hass, hass_client, config_entry )", "import Platform from .test_gateway import DECONZ_CONFIG, setup_deconz_integration from tests.components.diagnostics import", "entry diagnostics.\"\"\" config_entry = await setup_deconz_integration(hass, aioclient_mock) await mock_deconz_websocket(state=STATE_RUNNING) await", "from unittest.mock import patch from pydeconz.websocket import STATE_RUNNING from homeassistant.const", "async def test_entry_diagnostics( hass, hass_client, aioclient_mock, mock_deconz_websocket ): \"\"\"Test config", "str(Platform.ALARM_CONTROL_PANEL): [], str(Platform.BINARY_SENSOR): [], str(Platform.CLIMATE): [], str(Platform.COVER): [], str(Platform.FAN): [],", "aioclient_mock) await mock_deconz_websocket(state=STATE_RUNNING) await hass.async_block_till_done() with patch( \"homeassistant.helpers.system_info.async_get_system_info\", return_value={\"get_system_info\": \"fake", "get_diagnostics_for_config_entry( hass, hass_client, config_entry ) == { \"home_assistant\": {\"get_system_info\": \"fake", "): assert await get_diagnostics_for_config_entry( hass, hass_client, config_entry ) == {", "[], str(Platform.LIGHT): [], str(Platform.LOCK): [], str(Platform.NUMBER): [], str(Platform.SENSOR): [], str(Platform.SIREN):", "config_entry = await setup_deconz_integration(hass, aioclient_mock) await mock_deconz_websocket(state=STATE_RUNNING) await hass.async_block_till_done() with", "\"fake data\"}, \"config_entry\": dict(config_entry.data), \"deconz_config\": DECONZ_CONFIG, \"websocket_state\": STATE_RUNNING, \"deconz_ids\": {},", "[], str(Platform.FAN): [], str(Platform.LIGHT): [], str(Platform.LOCK): [], str(Platform.NUMBER): [], str(Platform.SENSOR):", "\"\"\"Test config entry diagnostics.\"\"\" config_entry = await setup_deconz_integration(hass, aioclient_mock) await", "await hass.async_block_till_done() with patch( \"homeassistant.helpers.system_info.async_get_system_info\", return_value={\"get_system_info\": \"fake data\"}, ): assert", "config entry diagnostics.\"\"\" config_entry = await setup_deconz_integration(hass, aioclient_mock) await mock_deconz_websocket(state=STATE_RUNNING)", "import get_diagnostics_for_config_entry async def test_entry_diagnostics( hass, hass_client, aioclient_mock, mock_deconz_websocket ):", ".test_gateway import DECONZ_CONFIG, setup_deconz_integration from tests.components.diagnostics import get_diagnostics_for_config_entry async def", "{}, \"entities\": { str(Platform.ALARM_CONTROL_PANEL): [], str(Platform.BINARY_SENSOR): [], str(Platform.CLIMATE): [], str(Platform.COVER):", "get_diagnostics_for_config_entry async def test_entry_diagnostics( hass, hass_client, aioclient_mock, mock_deconz_websocket ): \"\"\"Test", "data\"}, \"config_entry\": dict(config_entry.data), \"deconz_config\": DECONZ_CONFIG, \"websocket_state\": STATE_RUNNING, \"deconz_ids\": {}, \"entities\":", "[], str(Platform.COVER): [], str(Platform.FAN): [], str(Platform.LIGHT): [], str(Platform.LOCK): [], str(Platform.NUMBER):", "from tests.components.diagnostics import get_diagnostics_for_config_entry async def test_entry_diagnostics( hass, hass_client, aioclient_mock,", "mock_deconz_websocket(state=STATE_RUNNING) await hass.async_block_till_done() with patch( \"homeassistant.helpers.system_info.async_get_system_info\", return_value={\"get_system_info\": \"fake data\"}, ):", "pydeconz.websocket import STATE_RUNNING from homeassistant.const import Platform from .test_gateway import", "assert await get_diagnostics_for_config_entry( hass, hass_client, config_entry ) == { \"home_assistant\":", "hass, hass_client, config_entry ) == { \"home_assistant\": {\"get_system_info\": \"fake data\"},", "[], str(Platform.LOCK): [], str(Platform.NUMBER): [], str(Platform.SENSOR): [], str(Platform.SIREN): [], str(Platform.SWITCH):", "mock_deconz_websocket ): \"\"\"Test config entry diagnostics.\"\"\" config_entry = await setup_deconz_integration(hass,", "str(Platform.COVER): [], str(Platform.FAN): [], str(Platform.LIGHT): [], str(Platform.LOCK): [], str(Platform.NUMBER): [],", "str(Platform.CLIMATE): [], str(Platform.COVER): [], str(Platform.FAN): [], str(Platform.LIGHT): [], str(Platform.LOCK): [],", "patch( \"homeassistant.helpers.system_info.async_get_system_info\", return_value={\"get_system_info\": \"fake data\"}, ): assert await get_diagnostics_for_config_entry( hass,", "== { \"home_assistant\": {\"get_system_info\": \"fake data\"}, \"config_entry\": dict(config_entry.data), \"deconz_config\": DECONZ_CONFIG,", "\"entities\": { str(Platform.ALARM_CONTROL_PANEL): [], str(Platform.BINARY_SENSOR): [], str(Platform.CLIMATE): [], str(Platform.COVER): [],", "from homeassistant.const import Platform from .test_gateway import DECONZ_CONFIG, setup_deconz_integration from", "config_entry ) == { \"home_assistant\": {\"get_system_info\": \"fake data\"}, \"config_entry\": dict(config_entry.data),", "await mock_deconz_websocket(state=STATE_RUNNING) await hass.async_block_till_done() with patch( \"homeassistant.helpers.system_info.async_get_system_info\", return_value={\"get_system_info\": \"fake data\"},", "aioclient_mock, mock_deconz_websocket ): \"\"\"Test config entry diagnostics.\"\"\" config_entry = await", "Platform from .test_gateway import DECONZ_CONFIG, setup_deconz_integration from tests.components.diagnostics import get_diagnostics_for_config_entry", "[], str(Platform.BINARY_SENSOR): [], str(Platform.CLIMATE): [], str(Platform.COVER): [], str(Platform.FAN): [], str(Platform.LIGHT):", "test_entry_diagnostics( hass, hass_client, aioclient_mock, mock_deconz_websocket ): \"\"\"Test config entry diagnostics.\"\"\"", "\"deconz_config\": DECONZ_CONFIG, \"websocket_state\": STATE_RUNNING, \"deconz_ids\": {}, \"entities\": { str(Platform.ALARM_CONTROL_PANEL): [],", "return_value={\"get_system_info\": \"fake data\"}, ): assert await get_diagnostics_for_config_entry( hass, hass_client, config_entry", "str(Platform.SWITCH): [], }, \"events\": {}, \"alarm_systems\": {}, \"groups\": {}, \"lights\":", "str(Platform.BINARY_SENSOR): [], str(Platform.CLIMATE): [], str(Platform.COVER): [], str(Platform.FAN): [], str(Platform.LIGHT): []," ]
[ "function `cell_list_fn(R, **kwargs)` that partitions positions, `R`, and side data", "maximum number of neighbors (along with additional space specified by", "axis=-2) cell_idx = cell_idx[..., jnp.newaxis, :, :] cell_idx = jnp.broadcast_to(cell_idx,", "2.0 (the \"License\"); # you may not use this file", "their own neighbors. fractional_coordinates: An optional boolean. Specifies whether positions", "= cell_list_candidate_fn(cl, R, **kwargs) else: idx = candidate_fn(R, **kwargs) if", "can be jit compiled; if the neighbor list capacity is", "for neighbor list.\"\"\" if is_sparse(neighbor.format): mask = neighbor.idx[0] < len(neighbor.reference_position)", "== 0: cell_count = cells_per_side ** spatial_dimension else: raise ValueError('Box", "> threshold_sq), (R, nbrs.did_buffer_overflow), neighbor_fn, nbrs, lambda x: x) return", "# Then when we copy data back from the grid,", "An optional boolean. Specifies whether positions will be supplied in", "to true to indicate that there was a buffer overflow.", "continue raise ValueError( 'Canonicalize displacement not implemented for spatial dimension", "R, neighbor_idx=nbrs.idx) >>> >>> def body_fn(i, state): >>> state, nbrs", "max_occupancy - occupancy if max_occupancy > occupancy: idx = jnp.concatenate(", ":-1]), axis=2) return arr def _vectorize(f: Callable, dim: int) ->", "mask = (dR < cutoff_sq) & (receiver_idx < N) if", "the cell-list. In # three-dimensions this seems to translate into", "& (receiver_idx < sender_idx) out_idx = N * jnp.ones(receiver_idx.shape, jnp.int32)", "= receivers[mask] senders = senders[mask] N = len(neighbor.reference_position) count =", "list, otherwise it allocates a new neighbor list. extra_capacity: Extra", "[spatial_dimension] specifying the size of the system. Note, this code", "float specifying the minimum side length of each cell. Cells", "# https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "partial from collections import namedtuple from enum import Enum from", "as pe import jax.numpy as jnp from jax_md import quantity,", "Array, Array, int]: \"\"\"Compute the number of cells-per-side and total", "then the function will construct a new neighbor list whose", "raise ValueError() def _neighboring_cells(dimension: int) -> Generator[onp.ndarray, None, None]: for", "lax.stop_gradient(dr_threshold) box_size = f32(box_size) cutoff = r_cutoff + dr_threshold cutoff_sq", "data specified by kwargs into a cell list. Returns a", ">>> init_fn, apply_fn = simulate.nve(energy_fn, shift, 1e-3) >>> exact_init_fn, exact_apply_fn", "for collections of points. Neighbor lists must balance the need", "box_size will be set to 1.0 and the cell size", "* _cell_capacity, dim), dtype=R.dtype) cell_id = N * jnp.ones((cell_count *", "box. cell_capacity_or_example_R: Either an integer specifying the size number of", "mask for neighbor list.\"\"\" if is_sparse(neighbor.format): mask = neighbor.idx[0] <", "want to check this in compute_fn as well? raise ValueError(", "into the grid. Here we use a trick to allow", "the calculation of example positions. Returns: A pair. The first", "number of cells in a box.\"\"\" if isinstance(box_size, int) or", "reference_position: Array did_buffer_overflow: Array max_occupancy: int = dataclasses.static_field() format: NeighborListFormat", "2 or 3. Found {}'.format(dim)) neighborhood_tile_count = 3 ** dim", "by shrinking the verlet list at the cost of #", "Array max_occupancy: int = dataclasses.static_field() format: NeighborListFormat = dataclasses.static_field() cell_list_fn:", "= int(occupancy * capacity_multiplier + _extra_capacity) if max_occupancy > R.shape[0]", "S + [...]. This contains side data placed into the", "space, dataclasses, util import jraph # Types Array = util.Array", "-> Callable[[Array], CellList]: r\"\"\"Returns a function that partitions point data", "box_size = onp.array(box_size) if len(box_size.shape) == 1: box_size = jnp.reshape(box_size,", "Optional[NeighborList], Optional[int]], NeighborList] def neighbor_list(displacement_or_metric: DisplacementOrMetricFn, box_size: Box, r_cutoff: float,", "allow for fluctuations in the maximum cell occupancy. Returns: A", "removed in a later version of JAX MD. ' 'Using", "**kwargs) -> NeighborList: \"\"\"A function for backward compatibility with previous", "be jit compiled; if the neighbor list capacity is not", "= box_size / cells_per_side cells_per_side = onp.array(cells_per_side, dtype=jnp.int64) if isinstance(box_size,", "unique. sort_map = jnp.argsort(hashes) sorted_R = R[sort_map] sorted_hash = hashes[sort_map]", "\\ _cell_dimensions(dim, box_size, minimum_cell_size) hash_multipliers = _compute_hash_constants(dim, cells_per_side) particle_index =", "= onp.array(box_size) if len(box_size.shape) == 1: box_size = jnp.reshape(box_size, (1,", "format: NeighborListFormat = dataclasses.static_field() cell_list_fn: Callable[[Array], CellList] = dataclasses.static_field() update_fn:", "= Callable[[Array, Optional[NeighborList], Optional[int]], NeighborList] def neighbor_list(displacement_or_metric: DisplacementOrMetricFn, box_size: Box,", "`neighbor_fn.update` updates an existing neighbor list. Neighbor lists themselves additionally", "None then the function will construct a new neighbor list", "cell_size: float, buffer_size_multiplier: float) -> int: # TODO(schsam): We might", "[cell_count_x, cell_count_y, cell_capacity]` * `S = [cell_count_x, cell_count_y, cell_count_z, cell_capacity]`", "dataclasses.static_field() cell_list_fn: Callable[[Array], CellList] = dataclasses.static_field() update_fn: Callable[[Array, 'NeighborList'], 'NeighborList']", "(dr_threshold / f32(2)) ** 2 metric_sq = _displacement_or_metric_to_metric_sq(displacement_or_metric) cell_size =", "if it comes up later. empty_kwarg_value = 10 ** 5", "= jnp.argsort(hashes) sorted_R = R[sort_map] sorted_hash = hashes[sort_map] sorted_id =", "box_size: Box, r_cutoff: float, dr_threshold: float, capacity_multiplier: float=1.25, disable_cell_list: bool=False,", "new neighbor list. This function cannot be compiled, since it", "0, 0), 0, 0) raise ValueError('Cell list only supports 2d", "step = 0 >>> for _ in range(20): >>> new_state,", "float) -> Array: \"\"\"Counts the number of particles per-cell in", "The first element is a NeighborList containing the current neighbor", "often we will do a mask for species that will", "to transform functions on individual tuples of particles to sets.\"\"\"", ">>> new_state, nbrs = lax.fori_loop(0, 100, body_fn, (state, nbrs)) >>>", "neighbor_list is None else neighbor_list.update_fn) return NeighborList( idx, R, jnp.logical_or(overflow,", "\"\"\" allocate: Callable[..., NeighborList] = dataclasses.static_field() update: Callable[[Array, NeighborList], NeighborList]", "= jnp.concatenate((arr[1:], arr[:1])) elif dx > 0: arr = jnp.concatenate((arr[-1:],", "must be specified per-particle (an ndarray with shape ' '(R.shape[0],", "return state, nbrs >>> >>> step = 0 >>> for", "cells_per_side) particle_index = jnp.array(R / cell_size, dtype=jnp.int64) particle_hash = jnp.sum(particle_index", "idx.shape) sender_idx = jnp.reshape(sender_idx, (-1,)) receiver_idx = jnp.reshape(idx, (-1,)) dR", "edges. Returns: A `jraph.GraphsTuple` that contains the topology of the", "# Copy the particle data into the grid. Here we", "or isinstance(box_size, float): box_size = float(box_size) # NOTE(schsam): Should we", "of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless", "if any particle has moved more than dr_threshold / 2.", "ndarrays of shape S + [...]. This contains side data", "this constant. spatial_dim = R.shape[-1] cell_capacity = onp.max(count_cell_filling(R, box_size, cell_size))", "jnp.concatenate((arr[:, :, -1:], arr[:, :, :-1]), axis=2) return arr def", "**kwargs) ** 2 else: return lambda Ra, Rb, **kwargs: space.square_distance(", "return lambda Ra, Rb, **kwargs: space.square_distance( displacement_or_metric(Ra, Rb, **kwargs)) except", "neighbor of particle i. reference_position: The positions of particles when", "len(receiver_idx) - 1) receiver_idx = out_idx.at[index].set(receiver_idx) sender_idx = out_idx.at[index].set(sender_idx) max_occupancy", "-1:], arr[:, :-1]), axis=1) if dz < 0: arr =", "neighbor_idx = jnp.zeros((N + 1,) + cell_idx.shape[-2:], jnp.int32) neighbor_idx =", "x: x) return NeighborListFns(lambda R, extra_capacity=0, **kwargs: neighbor_list_fn(R, extra_capacity=extra_capacity, **kwargs),", "License for the specific language governing permissions and # limitations", "Dict, Tuple, Generator, Union import math from operator import mul", "len(cells_per_side.shape) == 2: cells_per_side = tuple([int(x) for x in cells_per_side[0][::-1]])", "neighbor.idx != jnp.reshape(jnp.arange(N), (N, 1)) mask = mask & self_mask", "jnp.reshape(box_size, (1, -1)) if util.is_array(minimum_cell_size): minimum_cell_size = onp.array(minimum_cell_size) cell_capacity =", "`neighbor_list` returns a `NeighborListFns` object that contains two functions: 1)", "jnp.reshape(jnp.arange(idx.shape[0]), (idx.shape[0], 1)) return jnp.where(self_mask, idx.shape[0], idx) @jit def prune_neighbor_list_dense(R,", "id whereas particles empty slots have id = N. #", "cell_capacity. buffer_size_multiplier: A floating point multiplier that multiplies the estimated", "function that builds a list neighbors for collections of points.", "minimum side length of each cell. Cells are enlarged so", "data {k_i \\in R^m} it is often useful to partition", "positions of shape [particle_count, spatial_dimension] that is used to estimate", "and len(R.shape) == 2 and jnp.issubdtype(R.dtype, jnp.floating)): return True return", "all the neighbors, the `did_buffer_overflow` bit will be set to", ":-1]), axis=1) if dz < 0: arr = jnp.concatenate((arr[:, :,", "metric was provided.\"\"\" for dim in range(1, 4): try: R", "Array=None) -> jraph.GraphsTuple: \"\"\"Convert a sparse neighbor list to a", "be specified per-particle (an ndarray with shape ' '(R.shape[0], ...)).", "fractional_coordinates: cell_size = cutoff / box_size box_size = f32(1) use_cell_list", "(receiver_idx < N) if format is NeighborListFormat.OrderedSparse: mask = mask", "single lax.scatter call. To do # this we first sort", "neighbor list formats. Attributes: Dense: A dense neighbor list where", "== 1: box_size = jnp.reshape(box_size, (1, -1)) if util.is_array(minimum_cell_size): minimum_cell_size", "def _displacement_or_metric_to_metric_sq( displacement_or_metric: DisplacementOrMetricFn) -> MetricFn: \"\"\"Checks whether or not", "possibly less efficient than just # computing everything. neighbor_idx =", "neighbor list capacity is not sufficient to store all the", "whose capacity is inferred from R. If neighbor_list is given", "= mask & (receiver_idx < sender_idx) out_idx = N *", "cell_kwargs) # pytype: disable=wrong-arg-count return build_cells def _displacement_or_metric_to_metric_sq( displacement_or_metric: DisplacementOrMetricFn)", "cell list will be set to cutoff / box_size. format:", "{}'.format(k, type(v)))) if v.shape[0] != R.shape[0]: raise ValueError( ('Data must", "for now and revisit the issue if it comes up", "mask cumsum = jnp.cumsum(_mask) index = jnp.where(_mask, cumsum - 1,", "Generator[onp.ndarray, None, None]: for dindex in onp.ndindex(*([3] * dimension)): yield", "fractional_coordinates: bool=False, format: NeighborListFormat=NeighborListFormat.Dense, **static_kwargs) -> NeighborFn: \"\"\"Returns a function", "We might want to do something more sophisticated here or", "path to create / update neighbor ' 'lists. It will", "= partial(metric_sq, **kwargs) d = vmap(d) return lax.cond( jnp.any(d(R, nbrs.reference_position)", "mask & self_mask return mask def to_jraph(neighbor: NeighborList, mask: Array=None)", "+ _extra_capacity) if max_occupancy > R.shape[0] and not is_sparse(format): max_occupancy", "optional boolean. If set to True then the neighbor list", "number of particles that can be stored in each cell", "the groundwork for parallelizing simulations over different accelerators. Args: box_size:", "the fractional increase in maximum neighborhood occupancy we allocate compared", "max_occupancy=nbrs.max_occupancy) d = partial(metric_sq, **kwargs) d = vmap(d) return lax.cond(", "shift, 1e-3) >>> >>> nbrs = neighbor_fn.allocate(R) >>> state =", "N. # Then when we copy data back from the", "neighbor lists to dense ones.') receivers, senders = neighbor.idx mask", "is used to estimate the cell_capacity. buffer_size_multiplier: A floating point", ":] cell_idx = jnp.broadcast_to(cell_idx, idx.shape[:-1] + cell_idx.shape[-2:]) def copy_values_from_cell(value, cell_value,", "bool=False) -> Array: \"\"\"Compute a mask for neighbor list.\"\"\" if", "cell_idx = jnp.broadcast_to(cell_idx, idx.shape[:-1] + cell_idx.shape[-2:]) def copy_values_from_cell(value, cell_value, cell_id):", "slightly less efficient. minimum_cell_size: A float specifying the minimum side", "if nbrs.did_buffer_overflow: >>> nbrs = neighbor_fn.allocate(state.position) >>> else: >>> state", "cell_id, sorted_cell_id, sorted_id) cell_R = _unflatten_cell_buffer(cell_R, cells_per_side, dim) cell_id =", "An `(N, dim)` array of particle positions. neighbor_list: An optional", "to be rerun using a larger buffer. max_occupancy: A static", "neigh_R) mask = (dR < cutoff_sq) & (idx < N)", "receivers, senders = neighbor.idx mask = neighbor_list_mask(neighbor) receivers = receivers[mask]", "= N where N is the number of particles in", "-1:], arr[:, :, :-1]), axis=2) return arr def _vectorize(f: Callable,", "that get threaded through the calculation of example positions. Returns:", "of positions that will be used ' 'to estimate a", "is the number of particles in the system. kwarg_buffers: A", "simulate.nve(energy_fn, shift, 1e-3) >>> exact_init_fn, exact_apply_fn = simulate.nve(exact_energy_fn, shift, 1e-3)", "= jnp.reshape(box_size, (1, -1)) if util.is_array(minimum_cell_size): minimum_cell_size = onp.array(minimum_cell_size) cell_capacity", "from enum import Enum from typing import Any, Callable, Optional,", "**static_kwargs: kwargs that get threaded through the calculation of example", "mask is not None: _mask = _mask & mask cumsum", "this code is written for the case where the boundaries", "existing neighbor list. Neighbor lists themselves additionally have a convenience", "shape # [N + 1, output_dimension] and then truncate it", "copy data back from the grid, copy it to an", "list. Changing this will invoke a recompilation. format: A NeighborListFormat", "list. \"\"\" idx: Array reference_position: Array did_buffer_overflow: Array max_occupancy: int", "NeighborListFormat enum for details about the different choices for formats.", "len(dindex) == 2: dx, dy = dindex dz = 0", "XLA requires that shapes be statically specified, we allocate fixed", "be statically specified, we allocate fixed sized buffers for each", "max_occupancy: int = dataclasses.static_field() format: NeighborListFormat = dataclasses.static_field() cell_list_fn: Callable[[Array],", "space.map_neighbor(d) N = R.shape[0] neigh_R = R[idx] dR = d(R,", "supports 2d or 3d.') def cell_list(box_size: Box, minimum_cell_size: float, cell_capacity_or_example_R:", "a set of positions. Note, if the distribution of points", "sort. However, this seems possibly less efficient than just #", "!= R.shape[0]: raise ValueError( ('Data must be specified per-particle (an", "the neighbor list. cell_list_fn: A static python callable that is", "in each ' 'dimension.')) cell_count = reduce(mul, flat_cells_per_side, 1) elif", "sophisticated here or at # least expose this constant. spatial_dim", "' 'to estimate a cell capacity. Found {}.'.format(type(cell_capacity)) ) raise", "neighbor list given a new set of positions and a", "as there are # fewer than cell_capacity particles per cell,", "mask_id = jnp.ones((N,), jnp.int64) * N cell_R = jnp.zeros((cell_count *", "Sparse: A sparse neighbor list where the ids are a", "OF ANY KIND, either express or implied. # See the", "species that will include # an occupancy test. It seems", "See the License for the specific language governing permissions and", "individual tuples of particles to sets.\"\"\" from absl import logging", "dtype=jnp.int64) if isinstance(box_size, onp.ndarray): if box_size.ndim == 1 or box_size.ndim", "R.shape[0] dim = R.shape[1] _cell_capacity = cell_capacity + extra_capacity if", "Neighbor List. Attributes: idx: For an N particle system this", "elif util.is_array(cells_per_side) and len(cells_per_side.shape) == 2: cells_per_side = tuple([int(x) for", "sender_idx) out_idx = N * jnp.ones(receiver_idx.shape, jnp.int32) cumsum = jnp.cumsum(mask)", "None: cl = cell_list_fn(R) idx = cell_list_candidate_fn(cl, R, **kwargs) else:", "simulations over different accelerators. Args: box_size: A float or an", "1:], arr[:, :, :1]), axis=2) elif dz > 0: arr", "will be removed in a later version of JAX MD.", "j]` is the jth neighbor of particle i. reference_position: The", "to in writing, software # distributed under the License is", "since it uses the values of positions to infer the", "minimum_cell_size = onp.array(minimum_cell_size) cell_capacity = cell_capacity_or_example_R if _is_variable_compatible_with_positions(cell_capacity): cell_capacity =", "distance particles can move before rebuilding the neighbor list. capacity_multiplier:", "for spatial dimension larger' 'than 4.') class NeighborListFormat(Enum): \"\"\"An enum", "elif box_size.ndim == 0: cell_count = cells_per_side ** spatial_dimension else:", "list calculation. update_fn: A static python function used to update", "ValueError('Cannot convert a dense neighbor list to jraph format. '", "use either NeighborListFormat.Sparse or ' 'NeighborListFormat.OrderedSparse.') receivers, senders = neighbor.idx", "neighbor.idx[0] < len(neighbor.reference_position) if mask_self: mask = mask & (neighbor.idx[0]", "1: v = jnp.reshape(v, v.shape + (1,)) cell_kwargs[k] = ops.index_update(cell_kwargs[k],", "idx, R, jnp.logical_or(overflow, (max_occupancy < occupancy)), max_occupancy, format, cell_list_fn, update_fn)", "Args: displacement: A function `d(R_a, R_b)` that computes the displacement", "(N, 1)) mask = mask & self_mask return mask def", "= dataclasses.static_field() update_fn: Callable[[Array, 'NeighborList'], 'NeighborList'] = dataclasses.static_field() def update(self,", "make this more efficient by shrinking the verlet list at", "this in compute_fn as well? raise ValueError( 'Cell list spatial", "or agreed to in writing, software # distributed under the", "axis=2) return arr def _vectorize(f: Callable, dim: int) -> Callable:", "its size from the cell-list. In # three-dimensions this seems", "**kwargs)` that partitions positions, `R`, and side data specified by", "displacement not implemented for spatial dimension larger' 'than 4.') class", "if mask_self: idx = mask_self_fn(idx) if is_sparse(format): idx, occupancy =", "mask = neighbor_list_mask(neighbor) receivers = receivers[mask] senders = senders[mask] N", "a later version of JAX MD. ' 'Using `neighbor_fn.allocate` and", "`neighbor_fn.update` ' 'is preferred.') if neighbor_list is None: return self.allocate(R,", "elif len(dindex) == 3: dx, dy, dz = dindex if", "a float specifying the size of the box or an", "from absl import logging from functools import reduce, partial from", "= particle_id[sort_map] sorted_kwargs = {} for k, v in kwargs.items():", "max_occupancy]` array of integers such that `idx[i, j]` is the", "neighbor.idx mask = neighbor_list_mask(neighbor) receivers = receivers[mask] senders = senders[mask]", "2d or 3d.') def cell_list(box_size: Box, minimum_cell_size: float, cell_capacity_or_example_R: Union[int,", ">>> else: >>> state = new_state >>> step += 1", "dr_threshold: A scalar specifying the maximum distance particles can move", "displacement or metric was provided.\"\"\" for dim in range(1, 4):", "obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0", "to static shape requirements). To deal with this, our `neighbor_list`", "max_neighbors)` specifying the start / end particle of each neighbor", "self.update)) NeighborFn = Callable[[Array, Optional[NeighborList], Optional[int]], NeighborList] def neighbor_list(displacement_or_metric: DisplacementOrMetricFn,", ":, :] cell_idx = jnp.broadcast_to(cell_idx, idx.shape[:-1] + cell_idx.shape[-2:]) def copy_values_from_cell(value,", "* `S = [cell_count_x, cell_count_y, cell_capacity]` * `S = [cell_count_x,", "compliance with the License. # You may obtain a copy", "disable_cell_list @jit def candidate_fn(R, **kwargs): return jnp.broadcast_to(jnp.reshape(jnp.arange(R.shape[0]), (1, R.shape[0])), (R.shape[0],", "A pair. The first element is a NeighborList containing the", "if isinstance(box_size, int) or isinstance(box_size, float): box_size = float(box_size) #", "to # copy into all cells simultaneously using a single", "* jnp.ones(idx.shape, jnp.int32) cumsum = jnp.cumsum(mask, axis=1) index = jnp.where(mask,", "is larger than # needed since the idx buffer inherets", "= _compute_hash_constants(dim, cells_per_side) particle_index = jnp.array(R / cell_size, dtype=jnp.int64) particle_hash", "need to be reallocated. Here is a typical example of", "self_mask = neighbor.idx != jnp.reshape(jnp.arange(N), (N, 1)) mask = mask", "len(dR_or_dr.shape) == 0: return lambda Ra, Rb, **kwargs: \\ displacement_or_metric(Ra,", "jnp.array(jnp.cumprod(cells_per_side), dtype=jnp.int64) else: raise ValueError() def _neighboring_cells(dimension: int) -> Generator[onp.ndarray,", "+ (1,)) cell_kwargs[k] = ops.index_update(cell_kwargs[k], sorted_cell_id, v) cell_kwargs[k] = _unflatten_cell_buffer(", "into a cell list. See cell_list(...) for details on the", "= neighbor_list_mask(neighbor) if mask is not None: _mask = _mask", "= hashes[sort_map] sorted_id = particle_id[sort_map] sorted_kwargs = {} for k,", "out_idx.at[index].set(receiver_idx) sender_idx = out_idx.at[index].set(sender_idx) max_occupancy = cumsum[-1] return jnp.stack((receiver_idx[:-1], sender_idx[:-1])),", "compatable with the fact that under a jit the maximum", "R = cl.position_buffer idx = cl.id_buffer cell_idx = [idx] for", "can't imagine a case # in which the box_size would", "cells_per_side[::-1]]) elif util.is_array(cells_per_side) and len(cells_per_side.shape) == 2: cells_per_side = tuple([int(x)", "neighbor list. Neighbor lists themselves additionally have a convenience `update`", "\"\"\"A function for backward compatibility with previous neighbor lists. Attributes:", "size of this buffer can either be specified manually or", "Specifies whether positions will be supplied in fractional coordinates in", "jnp.ones((N * max_count,), jnp.int32) dense_idx = dense_idx.at[hashes].set(receivers).reshape((N, max_count)) return dense_idx", "cell_count = reduce(mul, flat_cells_per_side, 1) elif box_size.ndim == 0: cell_count", "not use this file except in compliance with the License.", "util.is_array(cells_per_side) and len(cells_per_side.shape) == 2: cells_per_side = tuple([int(x) for x", "jnp.where(self_mask, idx.shape[0], idx) @jit def prune_neighbor_list_dense(R, idx, **kwargs): d =", "under a jit the maximum number of neighbors cannot change", "the NeighborListFormat enum for details about the different choices for", "return CellList(cell_R, cell_id, cell_kwargs) # pytype: disable=wrong-arg-count return build_cells def", "cells_per_side ** spatial_dimension else: raise ValueError('Box must either be a", "def candidate_fn(R, **kwargs): return jnp.broadcast_to(jnp.reshape(jnp.arange(R.shape[0]), (1, R.shape[0])), (R.shape[0], R.shape[0])) @jit", "cell_value.shape[-2:]) return ops.index_update(value, scatter_indices, cell_value) # NOTE(schsam): Currently, this makes", "overflow = R_and_overflow N = R.shape[0] if cell_list_fn is not", "data placed into the cell list. \"\"\" position_buffer: Array id_buffer:", "flat_cells_per_side, 1) elif box_size.ndim == 0: cell_count = cells_per_side **", "store all the neighbors, the `did_buffer_overflow` bit will be set", "sender_idx[:-1])), max_occupancy def neighbor_list_fn(R: Array, neighbor_list: Optional[NeighborList]=None, extra_capacity: int=0, **kwargs)", "you may not use this file except in compliance with", "axis=2) elif dz > 0: arr = jnp.concatenate((arr[:, :, -1:],", "edges=None, receivers=receivers, senders=senders, globals=None, n_node=jnp.array([N, 1]), n_edge=jnp.array([jnp.sum(_mask), jnp.sum(~_mask)]), ) def", "nbrs, **kwargs: # pytype: disable=wrong-arg-count neighbor_list_fn(R, nbrs, **kwargs)) def neighbor_list_mask(neighbor:", "return iter((self.allocate, self.update)) NeighborFn = Callable[[Array, Optional[NeighborList], Optional[int]], NeighborList] def", "cell_list_candidate_fn(cl, R, **kwargs): N, dim = R.shape R = cl.position_buffer", "specifying the size of the box or an array of", "N particle system this is an `[N, max_occupancy]` array of", "= _mask & mask cumsum = jnp.cumsum(_mask) index = jnp.where(_mask,", "_displacement_or_metric_to_metric_sq( displacement_or_metric: DisplacementOrMetricFn) -> MetricFn: \"\"\"Checks whether or not a", "must be at least 3x the size of the grid", "cutoff if fractional_coordinates: cell_size = cutoff / box_size box_size =", "buffers all have a common shape, S, where * `S", "an ndarray of positions of shape [particle_count, spatial_dimension] that is", "be a member of NeighorListFormat' f' found {format}.')) @dataclasses.dataclass class", "cell_idx += [_shift_array(idx, dindex)] cell_idx = jnp.concatenate(cell_idx, axis=-2) cell_idx =", "= \\ _cell_dimensions(dim, box_size, minimum_cell_size) hash_multipliers = _compute_hash_constants(dim, cells_per_side) particle_index", "a dense partition into a uniform grid called a cell", "None else neighbor_list.update_fn) return NeighborList( idx, R, jnp.logical_or(overflow, (max_occupancy <", "lax.iota(jnp.int64, N) # NOTE(schsam): We use the convention that particles", "dimension larger' 'than 4.') class NeighborListFormat(Enum): \"\"\"An enum listing the", "lax.cond( jnp.any(d(R, nbrs.reference_position) > threshold_sq), (R, nbrs.did_buffer_overflow), neighbor_fn, nbrs, lambda", "list. This function cannot be compiled, since it uses the", "cells_per_side ** spatial_dimension return box_size, cell_size, cells_per_side, int(cell_count) def count_cell_filling(R:", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "dim != 2 and dim != 3: # NOTE(schsam): Do", "= jnp.reshape(cell_value, (-1,) + cell_value.shape[-2:]) return ops.index_update(value, scatter_indices, cell_value) #", "`NeighborListFns` object that contains two functions: 1) `neighbor_fn.allocate` create a", "means that the results of the simulation will be incorrect", "the different choices for formats. Defaults to `Dense`. **static_kwargs: kwargs", "is NeighborListFormat.Sparse or format is NeighborListFormat.OrderedSparse) def is_format_valid(format: NeighborListFormat): if", "easier to design around this empty_data_value # for now and", "a typical example of a simulation loop with neighbor lists:", "there are ever more neighbors than max_neighbors this is set", "typical example of a simulation loop with neighbor lists: >>>", "the maximum distance particles can move before rebuilding the neighbor", "R: Array, neighbor_list: Optional[NeighborList]=None, extra_capacity: int=0, **kwargs) -> NeighborList: \"\"\"A", "nbrs, **kwargs)) def neighbor_list_mask(neighbor: NeighborList, mask_self: bool=False) -> Array: \"\"\"Compute", "ops.segment_sum(jnp.ones(len(receivers), jnp.int32), receivers, N) max_count = jnp.max(count) offset = jnp.tile(jnp.arange(max_count),", "_is_variable_compatible_with_positions(cell_capacity): cell_capacity = _estimate_cell_capacity( cell_capacity, box_size, minimum_cell_size, buffer_size_multiplier) elif not", "util.is_array(minimum_cell_size): minimum_cell_size = onp.array(minimum_cell_size) cell_capacity = cell_capacity_or_example_R if _is_variable_compatible_with_positions(cell_capacity): cell_capacity", "list. If neighbor_list is None then the function will construct", "set to True then the box_size will be set to", "** 2 metric_sq = _displacement_or_metric_to_metric_sq(displacement_or_metric) cell_size = cutoff if fractional_coordinates:", "but should generally be left as False. mask_self: An optional", "Box, minimum_cell_size: float) -> Tuple[Box, Array, Array, int]: \"\"\"Compute the", "It might be worth adding an occupied mask. However, that", "R, nbrs, **kwargs: # pytype: disable=wrong-arg-count neighbor_list_fn(R, nbrs, **kwargs)) def", "jnp.newaxis, :, :] cell_idx = jnp.broadcast_to(cell_idx, idx.shape[:-1] + cell_idx.shape[-2:]) def", "neighbors cannot change (owing to static shape requirements). To deal", "2019 Google LLC # # Licensed under the Apache License,", "(1, R.shape[0])), (R.shape[0], R.shape[0])) @jit def cell_list_candidate_fn(cl, R, **kwargs): N,", "slots are specified by id = N where N is", "if dim != 2 and dim != 3: # NOTE(schsam):", "mask mask = neighbor.idx < len(neighbor.idx) if mask_self: N =", "a function that partitions point data spatially. Given a set", "it uses the positions to infer the maximum number of", "1)) mask = mask & self_mask return mask def to_jraph(neighbor:", "elif dz > 0: arr = jnp.concatenate((arr[:, :, -1:], arr[:,", "deal with this, our `neighbor_list` returns a `NeighborListFns` object that", "cell_capacity + extra_capacity if dim != 2 and dim !=", "bool: return (format is NeighborListFormat.Sparse or format is NeighborListFormat.OrderedSparse) def", "of example positions. Returns: A pair. The first element is", "in two- and three-dimensions respectively. It is assumed that each", "NOTE(schsam): Currently, this makes a verlet list that is larger", "# copy into all cells simultaneously using a single lax.scatter", "ndarray of floating point positions with shape S + [spatial_dimension].", "a system into a cell list. See cell_list(...) for details", "A floating point multiplier that multiplies the estimated cell capacity", "cells_per_side = tuple([int(x) for x in cells_per_side[::-1]]) elif util.is_array(cells_per_side) and", "A scalar specifying the maximum distance particles can move before", "empty slots are specified by id = N where N", "_mask = _mask & mask cumsum = jnp.cumsum(_mask) index =", "to infer the shapes. update: A function to update a", "jnp.sum(~_mask)]), ) def to_dense(neighbor: NeighborList) -> Array: \"\"\"Converts a sparse", "cell_list_fn is not None: cl = cell_list_fn(R) idx = cell_list_candidate_fn(cl,", "+ 1,), jnp.int32) receivers = ordered.at[index].set(receivers)[:-1] senders = ordered.at[index].set(senders)[:-1] mask", "dtype=jnp.int64) elif cells_per_side.size == spatial_dimension: one = jnp.array([[1]], dtype=jnp.int32) cells_per_side", "then the neighbor list is constructed using only distances. This", "cell_list(...) for details on the construction / specification. Cell list", "per-cell in a spatial partition.\"\"\" dim = int(R.shape[1]) box_size, cell_size,", "displacement_or_metric: DisplacementOrMetricFn) -> MetricFn: \"\"\"Checks whether or not a displacement", "# needed since the idx buffer inherets its size from", "is_sparse(neighbor.format): raise ValueError('Cannot convert a dense neighbor list to jraph", "for dindex in onp.ndindex(*([3] * dimension)): yield onp.array(dindex, dtype=jnp.int64) -", "buffer_size_multiplier: float) -> int: # TODO(schsam): We might want to", "idx[:, :max_occupancy] update_fn = (neighbor_list_fn if neighbor_list is None else", "Note, this code is written for the case where the", "(int(cells_per_side),) * dim elif util.is_array(cells_per_side) and len(cells_per_side.shape) == 1: cells_per_side", "of the system. Note, this code is written for the", "list will need to be reallocated. Here is a typical", "ops.index_update( cell_id, sorted_cell_id, sorted_id) cell_R = _unflatten_cell_buffer(cell_R, cells_per_side, dim) cell_id", "and not disable_cell_list @jit def candidate_fn(R, **kwargs): return jnp.broadcast_to(jnp.reshape(jnp.arange(R.shape[0]), (1,", "= d(R, neigh_R) mask = (dR < cutoff_sq) & (idx", "if dx < 0: arr = jnp.concatenate((arr[1:], arr[:1])) elif dx", "case # in which the box_size would not be accurately", "return vmap(vmap(vmap(f, 0, 0), 0, 0), 0, 0) raise ValueError('Cell", "jit compatable with the fact that under a jit the", "and 2) `neighbor_fn.update` updates an existing neighbor list. Neighbor lists", "computing everything. neighbor_idx = jnp.zeros((N + 1,) + cell_idx.shape[-2:], jnp.int32)", "the partition. \"\"\" if util.is_array(box_size): box_size = onp.array(box_size) if len(box_size.shape)", "< N return jraph.GraphsTuple( nodes=None, edges=None, receivers=receivers, senders=senders, globals=None, n_node=jnp.array([N,", "format must be a member of NeighorListFormat' f' found {format}.'))", "of particles to sets.\"\"\" from absl import logging from functools", "by an f32. if (isinstance(box_size, onp.ndarray) and (box_size.dtype == jnp.int32", "box or an array of shape [spatial_dim] specifying the box", "using only distances. This can be useful for debugging but", "of the box or an array of shape [spatial_dim] specifying", "NeighborFn: \"\"\"Returns a function that builds a list neighbors for", "and jnp.issubdtype(R.dtype, jnp.floating)): return True return False def _compute_hash_constants(spatial_dimension: int,", "senders = neighbor.idx N = len(neighbor.reference_position) _mask = neighbor_list_mask(neighbor) if", "construction / specification. Cell list buffers all have a common", "check this in compute_fn as well? raise ValueError( 'Cell list", "list that repeats 0, .., cell_capacity. So long as there", "the size number of particles that can be stored in", "functions to allocate and update neighbor lists. Attributes: allocate: A", "number of neighbors cannot change (owing to static shape requirements).", "neighbor ' 'lists. It will be removed in a later", "written for the case where the boundaries are periodic. If", "maximum size of the neighbor list. Changing this will invoke", "supplied in fractional coordinates in the unit cube, [0, 1]^d.", "0): continue cell_idx += [_shift_array(idx, dindex)] cell_idx = jnp.concatenate(cell_idx, axis=-2)", "mask = mask & (receiver_idx < sender_idx) out_idx = N", "be set to `True` and a new neighbor list will", "found {format}.')) @dataclasses.dataclass class NeighborList(object): \"\"\"A struct containing the state", "list whose capacity is inferred from R. If neighbor_list is", "each # particle to have a cell id = hash", "padding here is accomplished by adding a ficticious graph with", "ValueError() def _neighboring_cells(dimension: int) -> Generator[onp.ndarray, None, None]: for dindex", "False def _compute_hash_constants(spatial_dimension: int, cells_per_side: Array) -> Array: if cells_per_side.size", "(state, nbrs)) >>> if nbrs.did_buffer_overflow: >>> nbrs = neighbor_fn.allocate(state.position) >>>", "dim = int(R.shape[1]) box_size, cell_size, cells_per_side, cell_count = \\ _cell_dimensions(dim,", "\"\"\" if util.is_array(box_size): box_size = onp.array(box_size) if len(box_size.shape) == 1:", "jnp.array(R / cell_size, dtype=i32) hashes = jnp.sum(indices * hash_multipliers, axis=1)", "/ update neighbor ' 'lists. It will be removed in", "== 1: cells_per_side = tuple([int(x) for x in cells_per_side[::-1]]) elif", "ValueError(( 'Neighbor list format must be a member of NeighorListFormat'", "is constructed using only distances. This can be useful for", "+ sorted_cell_id cell_R = ops.index_update(cell_R, sorted_cell_id, sorted_R) sorted_id = jnp.reshape(sorted_id,", "at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "dense neighbor list to jraph format. ' 'Please use either", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "the case where the boundaries are periodic. If this is", ">>> step = 0 >>> for _ in range(20): >>>", "occupancy we allocate compared with the maximum in the example", "sets.\"\"\" from absl import logging from functools import reduce, partial", "to add if allocating the neighbor list. \"\"\" logging.warning('Using a", "the capacity of the neighbor list must scale with the", "can either be specified manually or it can be estimated", "if mask_self: mask = mask & (neighbor.idx[0] != neighbor.idx[1]) return", "element contains a function `neighbor_list_fn(R, neighbor_list=None)` that will update the", "_cell_capacity = cell_capacity + extra_capacity if dim != 2 and", "Currently, this makes a verlet list that is larger than", "flat_cells_per_side = onp.reshape(cells_per_side, (-1,)) for cells in flat_cells_per_side: if cells", "cell id that is unique. sort_map = jnp.argsort(hashes) sorted_R =", "* cell_capacity + grid_id where grid_id # is a flat", "of shape # [N + 1, output_dimension] and then truncate", "cell or an ndarray of positions of shape [particle_count, spatial_dimension]", "N * jnp.ones((idx.shape[0], padding), dtype=idx.dtype)], axis=1) idx = idx[:, :max_occupancy]", "will invoke a recompilation. format: A NeighborListFormat enum specifying the", "or not a displacement or metric was provided.\"\"\" for dim", "extra_capacity: Extra capacity to add if allocating the neighbor list.", "have a common shape, S, where * `S = [cell_count_x,", "index = jnp.where(mask, cumsum - 1, len(receiver_idx) - 1) receiver_idx", "util import jraph # Types Array = util.Array f32 =", "nbrs = neighbor_list def neighbor_fn(R_and_overflow, max_occupancy=None): R, overflow = R_and_overflow", "if cells < 3: raise ValueError( ('Box must be at", "displacement_or_metric(Ra, Rb, **kwargs)) except TypeError: continue except ValueError: continue raise", "if mask_self: N = len(neighbor.reference_position) self_mask = neighbor.idx != jnp.reshape(jnp.arange(N),", "allocate: Callable[..., NeighborList] = dataclasses.static_field() update: Callable[[Array, NeighborList], NeighborList] =", "jnp.reshape(idx, (-1,)) dR = d(R[sender_idx], R[receiver_idx]) mask = (dR <", "_ in range(20): >>> new_state, nbrs = lax.fori_loop(0, 100, body_fn,", "scalar specifying the fractional increase in maximum neighborhood occupancy we", "**kwargs)) def neighbor_list_mask(neighbor: NeighborList, mask_self: bool=False) -> Array: \"\"\"Compute a", "not be accurately represented by an f32. if (isinstance(box_size, onp.ndarray)", "convert to the jraph format. Must be sparse. mask: An", "flat_cells_per_side: if cells < 3: raise ValueError( ('Box must be", "https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "an integer specifying the size number of particles that can", "jax.abstract_arrays import ShapedArray from jax.interpreters import partial_eval as pe import", "it is likely the buffer the buffer sizes will have", "4.') class NeighborListFormat(Enum): \"\"\"An enum listing the different neighbor list", "eval_shape(displacement_or_metric, R, R, t=0) if len(dR_or_dr.shape) == 0: return lambda", "1) receiver_idx = out_idx.at[index].set(receiver_idx) sender_idx = out_idx.at[index].set(sender_idx) max_occupancy = cumsum[-1]", "assign each # particle to have a cell id =", "cell_capacity]` in two- and three-dimensions respectively. It is assumed that", "-> Array: if cells_per_side.size == 1: return jnp.array([[cells_per_side ** d", "bit will be set to `True` and a new neighbor", "efficient. minimum_cell_size: A float specifying the minimum side length of", "either be specified manually or it can be estimated automatically", "file except in compliance with the License. # You may", "jnp.int32) cumsum = jnp.cumsum(mask) index = jnp.where(mask, cumsum - 1,", "dimension. r_cutoff: A scalar specifying the neighborhood radius. dr_threshold: A", "max_occupancy = int(occupancy * capacity_multiplier + _extra_capacity) if max_occupancy >", "will be supplied in fractional coordinates in the unit cube,", "changes significantly it is likely the buffer the buffer sizes", "the grid spacing in each ' 'dimension.')) cell_count = reduce(mul,", "R.shape R = cl.position_buffer idx = cl.id_buffer cell_idx = [idx]", "simulation needs to be rerun using a larger buffer. max_occupancy:", "_, cell_size, cells_per_side, cell_count = \\ _cell_dimensions(dim, box_size, minimum_cell_size) hash_multipliers", "cutoff_sq) & (receiver_idx < N) if format is NeighborListFormat.OrderedSparse: mask", "Dict[str, Array] def _cell_dimensions(spatial_dimension: int, box_size: Box, minimum_cell_size: float) ->", "data spatially. Given a set of points {x_i \\in R^d}", "2 def is_sparse(format: NeighborListFormat) -> bool: return (format is NeighborListFormat.Sparse", "self, **kwargs) @dataclasses.dataclass class NeighborListFns: \"\"\"A struct containing functions to", "1.0 and the cell size used in the cell list", "the cell size used in the cell list will be", "mask: An optional mask on the edges. Returns: A `jraph.GraphsTuple`", "0 elif len(dindex) == 3: dx, dy, dz = dindex", "not None: _mask = _mask & mask cumsum = jnp.cumsum(_mask)", "continue except ValueError: continue raise ValueError( 'Canonicalize displacement not implemented", "i32 = util.i32 i64 = util.i64 Box = space.Box DisplacementOrMetricFn", "d(R[sender_idx], R[receiver_idx]) mask = (dR < cutoff_sq) & (receiver_idx <", "1 OrderedSparse = 2 def is_sparse(format: NeighborListFormat) -> bool: return", "not isinstance(cell_capacity, int): msg = ( 'cell_capacity_or_example_positions must either be", "= simulate.nve(energy_fn, shift, 1e-3) >>> exact_init_fn, exact_apply_fn = simulate.nve(exact_energy_fn, shift,", "neighbor_list_mask(neighbor) if mask is not None: _mask = _mask &", "details about the different choices for formats. Defaults to `Dense`.", "= jnp.cumsum(_mask) index = jnp.where(_mask, cumsum - 1, len(receivers)) ordered", "**kwargs) @dataclasses.dataclass class NeighborListFns: \"\"\"A struct containing functions to allocate", "N * jnp.ones((cell_count * _cell_capacity, 1), dtype=i32) # It might", "[cell_count_x, cell_count_y, cell_count_z, cell_capacity]` in two- and three-dimensions respectively. It", "# three-dimensions this seems to translate into an occupancy of", "NeighborListFns(lambda R, extra_capacity=0, **kwargs: neighbor_list_fn(R, extra_capacity=extra_capacity, **kwargs), lambda R, nbrs,", "= 0 Sparse = 1 OrderedSparse = 2 def is_sparse(format:", "into a uniform grid called a cell list. Since XLA", "of cells-per-side and total number of cells in a box.\"\"\"", "allocate: A function to allocate a new neighbor list. This", "be removed in a later version of JAX MD. '", "except TypeError: continue except ValueError: continue raise ValueError( 'Canonicalize displacement", "where N is the number of particles in the system.", "are successfully, # copied have their true id whereas particles", "use_cell_list else None) return neighbor_fn((R, False)) else: cell_list_fn = nbrs.cell_list_fn", "that under a jit the maximum number of neighbors cannot", "'Data must be specified as an ndarry. Found \"{}\" with", "receivers < N return jraph.GraphsTuple( nodes=None, edges=None, receivers=receivers, senders=senders, globals=None,", "'lists. It will be removed in a later version of", "= simulate.nve(exact_energy_fn, shift, 1e-3) >>> >>> nbrs = neighbor_fn.allocate(R) >>>", "was constructed. This is used to decide whether the neighbor", "= empty_kwarg_value * jnp.ones( (cell_count * _cell_capacity,) + kwarg_shape, v.dtype)", "not the case, then the current code will be slightly", "list. cell_list_fn: A static python callable that is used to", "displacement: A function `d(R_a, R_b)` that computes the displacement between", "either be a scalar or a vector.') else: cell_count =", "ids are a square matrix of shape `(N, max_neighbors_per_atom)`. Here", "!= 3: # NOTE(schsam): Do we want to check this", "< occupancy)), max_occupancy, format, cell_list_fn, update_fn) # pytype: disable=wrong-arg-count if", "the box_size will be set to 1.0 and the cell", "the neighbor list (with fixed capacity) if any particle has", "a CellList containing the partition. \"\"\" if util.is_array(box_size): box_size =", "it allocates a new neighbor list. extra_capacity: Extra capacity to", "Do we want to check this in compute_fn as well?", "A dictionary of ndarrays of shape S + [...]. This", "struct containing the state of a Neighbor List. Attributes: idx:", "cell_list(box_size: Box, minimum_cell_size: float, cell_capacity_or_example_R: Union[int, Array], buffer_size_multiplier: float=1.1 )", "KIND, either express or implied. # See the License for", "-1)) if util.is_array(minimum_cell_size): minimum_cell_size = onp.array(minimum_cell_size) cell_capacity = cell_capacity_or_example_R if", "< j are included. \"\"\" Dense = 0 Sparse =", "MD. ' 'Using `neighbor_fn.allocate` and `neighbor_fn.update` ' 'is preferred.') if", "positions, `R`, and side data specified by kwargs into a", "estimated cell capacity to allow for fluctuations in the maximum", "new_state, nbrs = lax.fori_loop(0, 100, body_fn, (state, nbrs)) >>> if", "1, len(receivers)) ordered = N * jnp.ones((len(receivers) + 1,), jnp.int32)", "code path to create / update neighbor ' 'lists. It", "Neighbor lists themselves additionally have a convenience `update` member function.", "first sort particles by their cell hash. We then assign", "new neighbor list whose capacity is inferred from R. If", "dr_threshold / 2. Note that only `neighbor_list_fn(R, neighbor_list)` can be", "allocate a new neighbor list. This function cannot be compiled,", "change (owing to static shape requirements). To deal with this,", "jnp.ones((len(receivers) + 1,), jnp.int32) receivers = ordered.at[index].set(receivers)[:-1] senders = ordered.at[index].set(senders)[:-1]", "each ' 'dimension.')) cell_count = reduce(mul, flat_cells_per_side, 1) elif box_size.ndim", "disable_cell_list: An optional boolean. If set to True then the", "be adjusted. This partitioning will likely form the groundwork for", "buffer_size_multiplier) def _unflatten_cell_buffer(arr: Array, cells_per_side: Array, dim: int) -> Array:", "\"\"\" logging.warning('Using a depricated code path to create / update", "with neighbor lists: >>> init_fn, apply_fn = simulate.nve(energy_fn, shift, 1e-3)", "box_size: Either a float specifying the size of the box", "or 3d.') def cell_list(box_size: Box, minimum_cell_size: float, cell_capacity_or_example_R: Union[int, Array],", "3: return vmap(vmap(vmap(f, 0, 0), 0, 0), 0, 0) raise", "' 'specifying the cell capacity or a set of positions", "box_size, cell_size, cells_per_side, int(cell_count) def count_cell_filling(R: Array, box_size: Box, minimum_cell_size:", "a new neighbor list will need to be reallocated. Here", "least 3x the size of the grid spacing in each", "neighbors, the `did_buffer_overflow` bit will be set to `True` and", "list can be jit compiled; if the neighbor list capacity", "max_count = jnp.max(count) offset = jnp.tile(jnp.arange(max_count), N)[:len(senders)] hashes = senders", "boolean. Specifies whether positions will be supplied in fractional coordinates", "from typing import Any, Callable, Optional, Dict, Tuple, Generator, Union", "collections import namedtuple from enum import Enum from typing import", "(the \"License\"); # you may not use this file except", "= util.i32 i64 = util.i64 Box = space.Box DisplacementOrMetricFn =", "1: cells_per_side = tuple([int(x) for x in cells_per_side[::-1]]) elif util.is_array(cells_per_side)", "cell_size, dtype=i32) hashes = jnp.sum(indices * hash_multipliers, axis=1) # Copy", "cell id = hash * cell_capacity + grid_id where grid_id", "each cell. The size of this buffer can either be", "there was a buffer overflow. If this happens, it means", "= neighbor_fn.allocate(R) >>> state = init_fn(random.PRNGKey(0), R, neighbor_idx=nbrs.idx) >>> >>>", "= v[sort_map] sorted_cell_id = jnp.mod(lax.iota(jnp.int64, N), _cell_capacity) sorted_cell_id = sorted_hash", "\"\"\"Compute a mask for neighbor list.\"\"\" if is_sparse(neighbor.format): mask =", "f64 = util.f64 i32 = util.i32 i64 = util.i64 Box", "+ cell_value.shape[-2:]) return ops.index_update(value, scatter_indices, cell_value) # NOTE(schsam): Currently, this", "cannot change (owing to static shape requirements). To deal with", "list given a new set of positions and a new", "n_node=jnp.array([N, 1]), n_edge=jnp.array([jnp.sum(_mask), jnp.sum(~_mask)]), ) def to_dense(neighbor: NeighborList) -> Array:", "is an `[N, max_occupancy]` array of integers such that `idx[i,", "step of the neighbor list calculation. update_fn: A static python", "cell_idx.shape[-2:]) def copy_values_from_cell(value, cell_value, cell_id): scatter_indices = jnp.reshape(cell_id, (-1,)) cell_value", "contains the topology of the neighbor list. \"\"\" if not", "receivers=receivers, senders=senders, globals=None, n_node=jnp.array([N, 1]), n_edge=jnp.array([jnp.sum(_mask), jnp.sum(~_mask)]), ) def to_dense(neighbor:", "namedtuple from enum import Enum from typing import Any, Callable,", "consider themselves to be their own neighbors. fractional_coordinates: An optional", "is NeighborListFormat.OrderedSparse) def is_format_valid(format: NeighborListFormat): if not format in list(NeighborListFormat):", "To deal with this, our `neighbor_list` returns a `NeighborListFns` object", "R, capacity_multiplier) if use_cell_list else None) return neighbor_fn((R, False)) else:", "spatial_dimension: one = jnp.array([[1]], dtype=jnp.int32) cells_per_side = jnp.concatenate((one, cells_per_side[:, :-1]),", "box_size = f32(1) use_cell_list = jnp.all(cell_size < box_size / 3.)", "whether points can consider themselves to be their own neighbors.", "1, idx.shape[1] - 1) p_index = jnp.arange(idx.shape[0])[:, None] out_idx =", "len(neighbor.reference_position) self_mask = neighbor.idx != jnp.reshape(jnp.arange(N), (N, 1)) mask =", "# # Unless required by applicable law or agreed to", "0, .., cell_capacity. So long as there are # fewer", "= init_fn(random.PRNGKey(0), R, neighbor_idx=nbrs.idx) >>> >>> def body_fn(i, state): >>>", "d = partial(metric_sq, **kwargs) d = space.map_neighbor(d) N = R.shape[0]", "from jax.abstract_arrays import ShapedArray from jax.interpreters import partial_eval as pe", "Optional[NeighborList]=None, extra_capacity: int=0, **kwargs) -> NeighborList: \"\"\"A function for backward", "receivers = ordered.at[index].set(receivers)[:-1] senders = ordered.at[index].set(senders)[:-1] mask = receivers <", "else: return lambda Ra, Rb, **kwargs: space.square_distance( displacement_or_metric(Ra, Rb, **kwargs))", "if (util.is_array(R) and len(R.shape) == 2 and jnp.issubdtype(R.dtype, jnp.floating)): return", "if fractional_coordinates: cell_size = cutoff / box_size box_size = f32(1)", "neighbor_list_fn(R: Array, neighbor_list: Optional[NeighborList]=None, extra_capacity: int=0, **kwargs) -> NeighborList: nbrs", "= receivers < N return jraph.GraphsTuple( nodes=None, edges=None, receivers=receivers, senders=senders,", "then the function updates the neighbor list, otherwise it allocates", "scatter_indices = jnp.reshape(cell_id, (-1,)) cell_value = jnp.reshape(cell_value, (-1,) + cell_value.shape[-2:])", "with this, our `neighbor_list` returns a `NeighborListFns` object that contains", "= R.shape[0] dim = R.shape[1] _cell_capacity = cell_capacity + extra_capacity", "have id = N. # Then when we copy data", "NeighborListFormat(Enum): \"\"\"An enum listing the different neighbor list formats. Attributes:", "case, then the current code will be slightly less efficient.", "partitioning that can be implemented efficiently within XLA is a", "dataclasses.static_field() format: NeighborListFormat = dataclasses.static_field() cell_list_fn: Callable[[Array], CellList] = dataclasses.static_field()", "v.dtype) indices = jnp.array(R / cell_size, dtype=i32) hashes = jnp.sum(indices", "spatial_dimension flat_cells_per_side = onp.reshape(cells_per_side, (-1,)) for cells in flat_cells_per_side: if", "shape requirements). To deal with this, our `neighbor_list` returns a", "TODO return jnp.reshape(arr, cells_per_side + (-1,) + arr.shape[1:]) def _shift_array(arr:", "particles empty slots have id = N. # Then when", "- 1 def _estimate_cell_capacity(R: Array, box_size: Box, cell_size: float, buffer_size_multiplier:", "space.square_distance( displacement_or_metric(Ra, Rb, **kwargs)) except TypeError: continue except ValueError: continue", "will be used ' 'to estimate a cell capacity. Found", "def is_format_valid(format: NeighborListFormat): if not format in list(NeighborListFormat): raise ValueError((", "own neighbors. fractional_coordinates: An optional boolean. Specifies whether positions will", "jraph.GraphsTuple( nodes=None, edges=None, receivers=receivers, senders=senders, globals=None, n_node=jnp.array([N, 1]), n_edge=jnp.array([jnp.sum(_mask), jnp.sum(~_mask)]),", "cutoff_sq = cutoff ** 2 threshold_sq = (dr_threshold / f32(2))", "be set to cutoff / box_size. format: The format of", "the spatial partition of a system into a cell list.", "`[N, max_occupancy]` array of integers such that `idx[i, j]` is", "candidate_fn(R, **kwargs) if mask_self: idx = mask_self_fn(idx) if is_sparse(format): idx,", "implied. # See the License for the specific language governing", "\"{}\" with ' 'type {}'.format(k, type(v)))) if v.shape[0] != R.shape[0]:", "= jnp.all(cell_size < box_size / 3.) and not disable_cell_list @jit", "Any, Callable, Optional, Dict, Tuple, Generator, Union import math from", "Callable[..., NeighborList] = dataclasses.static_field() update: Callable[[Array, NeighborList], NeighborList] = dataclasses.static_field()", "convert a dense neighbor list to jraph format. ' 'Please", "or an ndarray of shape [spatial_dimension] specifying the size of", "neighor list object. If it is provided then the function", "N return jraph.GraphsTuple( nodes=None, edges=None, receivers=receivers, senders=senders, globals=None, n_node=jnp.array([N, 1]),", "seems easier to design around this empty_data_value # for now", "contains two functions: 1) `neighbor_fn.allocate` create a new neighbor list", "dx > 0: arr = jnp.concatenate((arr[-1:], arr[:-1])) if dy <", "nbrs = nbrs.update(state.position) >>> state = apply_fn(state, neighbor_idx=nbrs.idx) >>> return", "highest connectivity neighbor. Sparse: A sparse neighbor list where the", "{}'.format(dim)) neighborhood_tile_count = 3 ** dim _, cell_size, cells_per_side, cell_count", "new neighbor list. \"\"\" allocate: Callable[..., NeighborList] = dataclasses.static_field() update:", "if neighbor_list is None else neighbor_list.update_fn) return NeighborList( idx, R,", "for details on the construction / specification. Cell list buffers", "shape [spatial_dimension] specifying the size of the system. Note, this", "in compute_fn as well? raise ValueError( 'Cell list spatial dimension", "cumsum - 1, len(receiver_idx) - 1) receiver_idx = out_idx.at[index].set(receiver_idx) sender_idx", "python callable that is used to construct a cell list", "jnp.issubdtype(R.dtype, jnp.floating)): return True return False def _compute_hash_constants(spatial_dimension: int, cells_per_side:", "0, 0) elif dim == 3: return vmap(vmap(vmap(f, 0, 0),", "specifying the size number of particles that can be stored", "buffer_size_multiplier: A floating point multiplier that multiplies the estimated cell", "dtype=jnp.int64) particle_hash = jnp.sum(particle_index * hash_multipliers, axis=1) filling = ops.segment_sum(jnp.ones_like(particle_hash),", "arr[:, :-1]), axis=1) if dz < 0: arr = jnp.concatenate((arr[:,", "simulation loop with neighbor lists: >>> init_fn, apply_fn = simulate.nve(energy_fn,", "r_cutoff: float, dr_threshold: float, capacity_multiplier: float=1.25, disable_cell_list: bool=False, mask_self: bool=True,", "ignores the empty slots. mask_id = jnp.ones((N,), jnp.int64) * N", "NeighborList containing the current neighbor list. The second element contains", "@jit def prune_neighbor_list_dense(R, idx, **kwargs): d = partial(metric_sq, **kwargs) d", "A float or an ndarray of shape [spatial_dimension] specifying the", "of the neighbor list must scale with the highest connectivity", "return arr def _vectorize(f: Callable, dim: int) -> Callable: if", "can consider themselves to be their own neighbors. fractional_coordinates: An", "is None then the function will construct a new neighbor", "this makes a verlet list that is larger than #", "box_size / cells_per_side cells_per_side = onp.array(cells_per_side, dtype=jnp.int64) if isinstance(box_size, onp.ndarray):", "f32(1) use_cell_list = jnp.all(cell_size < box_size / 3.) and not", "if len(dR_or_dr.shape) == 0: return lambda Ra, Rb, **kwargs: \\", "given a new set of positions and a new neighbor", "int) or isinstance(box_size, float): box_size = float(box_size) # NOTE(schsam): Should", "within XLA is a dense partition into a uniform grid", "Updating the neighbor list can be jit compiled; if the", "set to `True` and a new neighbor list will need", "= onp.array(minimum_cell_size) cell_capacity = cell_capacity_or_example_R if _is_variable_compatible_with_positions(cell_capacity): cell_capacity = _estimate_cell_capacity(", "box_size? I can't imagine a case # in which the", "= space.map_bond(d) N = R.shape[0] sender_idx = jnp.broadcast_to(jnp.arange(N)[:, None], idx.shape)", "Copyright 2019 Google LLC # # Licensed under the Apache", "list. The second element contains a function `neighbor_list_fn(R, neighbor_list=None)` that", "onp.array(minimum_cell_size) cell_capacity = cell_capacity_or_example_R if _is_variable_compatible_with_positions(cell_capacity): cell_capacity = _estimate_cell_capacity( cell_capacity,", "N = R.shape[0] sender_idx = jnp.broadcast_to(jnp.arange(N)[:, None], idx.shape) sender_idx =", "None: cell_list_fn = (cell_list(box_size, cell_size, R, capacity_multiplier) if use_cell_list else", "update(self, R, **kwargs): return self.update_fn(R, self, **kwargs) @dataclasses.dataclass class NeighborListFns:", "neighbor_idx=nbrs.idx) >>> >>> def body_fn(i, state): >>> state, nbrs =", "jnp.stack((receiver_idx[:-1], sender_idx[:-1])), max_occupancy def neighbor_list_fn(R: Array, neighbor_list: Optional[NeighborList]=None, extra_capacity: int=0,", "`(N, dim)` array of particle positions. neighbor_list: An optional neighor", "= partial(neighbor_fn, max_occupancy=nbrs.max_occupancy) d = partial(metric_sq, **kwargs) d = vmap(d)", "cell_capacity. So long as there are # fewer than cell_capacity", "= cutoff / box_size box_size = f32(1) use_cell_list = jnp.all(cell_size", "list must scale with the highest connectivity neighbor. Sparse: A", "@dataclasses.dataclass class CellList: \"\"\"Stores the spatial partition of a system", "R_b)` that computes the displacement between pairs of points. box_size:", "= partial(metric_sq, **kwargs) d = space.map_bond(d) N = R.shape[0] sender_idx", "the unit cube, [0, 1]^d. If this is set to", "!= neighbor.idx[1]) return mask mask = neighbor.idx < len(neighbor.idx) if", "reduce(mul, flat_cells_per_side, 1) elif box_size.ndim == 0: cell_count = cells_per_side", "list whose format is the same as `Sparse` where only", "cell_capacity = cell_capacity_or_example_R if _is_variable_compatible_with_positions(cell_capacity): cell_capacity = _estimate_cell_capacity( cell_capacity, box_size,", "continue cell_idx += [_shift_array(idx, dindex)] cell_idx = jnp.concatenate(cell_idx, axis=-2) cell_idx", "cell_capacity, box_size, minimum_cell_size, buffer_size_multiplier) elif not isinstance(cell_capacity, int): msg =", "number of particles in the system. kwarg_buffers: A dictionary of", "Unless required by applicable law or agreed to in writing,", "or a set of positions that will be used '", "NeighborFn = Callable[[Array, Optional[NeighborList], Optional[int]], NeighborList] def neighbor_list(displacement_or_metric: DisplacementOrMetricFn, box_size:", "list will be set to cutoff / box_size. format: The", "the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "accelerators. Args: box_size: A float or an ndarray of shape", "list is constructed using only distances. This can be useful", "prune_neighbor_list_dense(R, idx, **kwargs): d = partial(metric_sq, **kwargs) d = space.map_neighbor(d)", "OrderedSparse: A sparse neighbor list whose format is the same", "/ minimum_cell_size) cell_size = box_size / cells_per_side cells_per_side = onp.array(cells_per_side,", "specified by id = N where N is the number", ") raise ValueError(msg) def build_cells(R: Array, extra_capacity: int=0, **kwargs) ->", "cutoff / box_size box_size = f32(1) use_cell_list = jnp.all(cell_size <", "the specific language governing permissions and # limitations under the", "cell list. Returns a CellList containing the partition. \"\"\" if", "constructed. This is used to decide whether the neighbor list", "disable=wrong-arg-count return build_cells def _displacement_or_metric_to_metric_sq( displacement_or_metric: DisplacementOrMetricFn) -> MetricFn: \"\"\"Checks", "of each cell. Cells are enlarged so that they exactly", "cell_id = _unflatten_cell_buffer(cell_id, cells_per_side, dim) for k, v in sorted_kwargs.items():", "updated. did_buffer_overflow: A boolean that starts out False. If there", ":, 0] @jit def mask_self_fn(idx): self_mask = idx == jnp.reshape(jnp.arange(idx.shape[0]),", "Union import math from operator import mul import numpy as", "Rb, **kwargs: \\ displacement_or_metric(Ra, Rb, **kwargs) ** 2 else: return", "f32 = util.f32 f64 = util.f64 i32 = util.i32 i64", "space specified by the `capacity_multiplier`). Updating the neighbor list can", "particle_id[sort_map] sorted_kwargs = {} for k, v in kwargs.items(): sorted_kwargs[k]", "arr = jnp.concatenate((arr[:, :, 1:], arr[:, :, :1]), axis=2) elif", "dense neighbor list where the ids are a square matrix", "import ShapedArray from jax.interpreters import partial_eval as pe import jax.numpy", "cell_size = cutoff if fractional_coordinates: cell_size = cutoff / box_size", "**kwargs) if max_occupancy is None: _extra_capacity = (extra_capacity if not", "onp.array(dindex, dtype=jnp.int64) - 1 def _estimate_cell_capacity(R: Array, box_size: Box, cell_size:", "different choices for formats. Defaults to `Dense`. **static_kwargs: kwargs that", "each neighbor pair. OrderedSparse: A sparse neighbor list whose format", "= cl.position_buffer idx = cl.id_buffer cell_idx = [idx] for dindex", "= cells_per_side ** spatial_dimension else: raise ValueError('Box must either be", "-> bool: if (util.is_array(R) and len(R.shape) == 2 and jnp.issubdtype(R.dtype,", "the buffer the buffer sizes will have to be adjusted.", "neighbor list. Changing this will invoke a recompilation. format: A", "more than dr_threshold / 2. Note that only `neighbor_list_fn(R, neighbor_list)`", "in cells_per_side[0][::-1]]) else: raise ValueError() # TODO return jnp.reshape(arr, cells_per_side", "int=0, **kwargs) -> NeighborList: nbrs = neighbor_list def neighbor_fn(R_and_overflow, max_occupancy=None):", "None, None]: for dindex in onp.ndindex(*([3] * dimension)): yield onp.array(dindex,", "format. ' 'Please use either NeighborListFormat.Sparse or ' 'NeighborListFormat.OrderedSparse.') receivers,", "neighbor list whose format is the same as `Sparse` where", "cells < 3: raise ValueError( ('Box must be at least", "if dim == 2: return vmap(vmap(f, 0, 0), 0, 0)", "list. capacity_multiplier: A floating point scalar specifying the fractional increase", "onp.all(dindex == 0): continue cell_idx += [_shift_array(idx, dindex)] cell_idx =", "optional boolean. Specifies whether positions will be supplied in fractional", "See cell_list(...) for details on the construction / specification. Cell", "the same capacity. Attributes: position_buffer: An ndarray of floating point", "= util.Array f32 = util.f32 f64 = util.f64 i32 =", "len(R.shape) == 2 and jnp.issubdtype(R.dtype, jnp.floating)): return True return False", "neighbor_list.update_fn) return NeighborList( idx, R, jnp.logical_or(overflow, (max_occupancy < occupancy)), max_occupancy,", "jax_md import quantity, space, dataclasses, util import jraph # Types", "cells_per_side) # Create cell list data. particle_id = lax.iota(jnp.int64, N)", "that are successfully, # copied have their true id whereas", "the size of the system. Note, this code is written", "data back from the grid, copy it to an array", "< N) if format is NeighborListFormat.OrderedSparse: mask = mask &", "see the NeighborListFormat enum for details about the different choices", "box_size = lax.stop_gradient(box_size) r_cutoff = lax.stop_gradient(r_cutoff) dr_threshold = lax.stop_gradient(dr_threshold) box_size", "dz > 0: arr = jnp.concatenate((arr[:, :, -1:], arr[:, :,", "dr_threshold = lax.stop_gradient(dr_threshold) box_size = f32(box_size) cutoff = r_cutoff +", "axis=1) filling = ops.segment_sum(jnp.ones_like(particle_hash), particle_hash, cell_count) return filling def _is_variable_compatible_with_positions(R:", "Ra, Rb, **kwargs: \\ displacement_or_metric(Ra, Rb, **kwargs) ** 2 else:", "# NOTE(schsam): Should we auto-cast based on box_size? I can't", "particle is guarenteed # to get a cell id that", "`Dense`. **static_kwargs: kwargs that get threaded through the calculation of", "is set to True then the box_size will be set", "the empty slots. mask_id = jnp.ones((N,), jnp.int64) * N cell_R", "on the edges. Returns: A `jraph.GraphsTuple` that contains the topology", "int(R.shape[1]) box_size, cell_size, cells_per_side, cell_count = \\ _cell_dimensions(dim, box_size, minimum_cell_size)", "= reduce(mul, flat_cells_per_side, 1) elif box_size.ndim == 0: cell_count =", "cells_per_side = (int(cells_per_side),) * dim elif util.is_array(cells_per_side) and len(cells_per_side.shape) ==", "where the ids are a square matrix of shape `(N,", "i. reference_position: The positions of particles when the neighbor list", "= len(neighbor.reference_position) count = ops.segment_sum(jnp.ones(len(receivers), jnp.int32), receivers, N) max_count =", "* jnp.ones((N * max_count,), jnp.int32) dense_idx = dense_idx.at[hashes].set(receivers).reshape((N, max_count)) return", "cell_value) # NOTE(schsam): Currently, this makes a verlet list that", "with the highest connectivity neighbor. Sparse: A sparse neighbor list", "position_buffer: Array id_buffer: Array kwarg_buffers: Dict[str, Array] def _cell_dimensions(spatial_dimension: int,", "likely form the groundwork for parallelizing simulations over different accelerators.", "@dataclasses.dataclass class NeighborList(object): \"\"\"A struct containing the state of a", "cell_kwargs[k], cells_per_side, dim) return CellList(cell_R, cell_id, cell_kwargs) # pytype: disable=wrong-arg-count", "is_sparse(format): max_occupancy = R.shape[0] padding = max_occupancy - occupancy if", "mask_self: mask = mask & (neighbor.idx[0] != neighbor.idx[1]) return mask", "dim _, cell_size, cells_per_side, cell_count = \\ _cell_dimensions(dim, box_size, minimum_cell_size)", "in range(1, 4): try: R = ShapedArray((dim,), f32) dR_or_dr =", "* jnp.ones((cell_count * _cell_capacity, 1), dtype=i32) # It might be", "0) raise ValueError('Cell list only supports 2d or 3d.') def", "is the jth neighbor of particle i. reference_position: The positions", "' 'type {}'.format(k, type(v)))) if v.shape[0] != R.shape[0]: raise ValueError(", "will be slightly less efficient. minimum_cell_size: A float specifying the", "x in cells_per_side[0][::-1]]) else: raise ValueError() # TODO return jnp.reshape(arr,", "mask = neighbor.idx[0] < len(neighbor.reference_position) if mask_self: mask = mask", "jraph.GraphsTuple: \"\"\"Convert a sparse neighbor list to a `jraph.GraphsTuple`. As", "collections of points. Neighbor lists must balance the need to", "index = jnp.where(mask, cumsum - 1, idx.shape[1] - 1) p_index", "at # least expose this constant. spatial_dim = R.shape[-1] cell_capacity", "if v.ndim > 1 else (1,) cell_kwargs[k] = empty_kwarg_value *", "that will update the neighbor list. If neighbor_list is None", "cells_per_side cells_per_side = onp.array(cells_per_side, dtype=jnp.int64) if isinstance(box_size, onp.ndarray): if box_size.ndim", "def _cell_dimensions(spatial_dimension: int, box_size: Box, minimum_cell_size: float) -> Tuple[Box, Array,", "dx < 0: arr = jnp.concatenate((arr[1:], arr[:1])) elif dx >", "to estimate the cell_capacity. buffer_size_multiplier: A floating point multiplier that", "if util.is_array(box_size): box_size = onp.array(box_size) if len(box_size.shape) == 1: box_size", "\"\"\"Converts a sparse neighbor list to dense ids. Cannot be", "state, nbrs >>> >>> step = 0 >>> for _", "update_fn) # pytype: disable=wrong-arg-count if nbrs is None: cell_list_fn =", "containing the current neighbor list. The second element contains a", "= jnp.arange(idx.shape[0])[:, None] out_idx = out_idx.at[p_index, index].set(idx) max_occupancy = jnp.max(cumsum[:,", "particles that are successfully, # copied have their true id", "axis=1) if dz < 0: arr = jnp.concatenate((arr[:, :, 1:],", "the edges. Returns: A `jraph.GraphsTuple` that contains the topology of", "estimate a cell capacity. Found {}.'.format(type(cell_capacity)) ) raise ValueError(msg) def", "list(NeighborListFormat): raise ValueError(( 'Neighbor list format must be a member", "neighbor list. \"\"\" logging.warning('Using a depricated code path to create", "== 0): continue cell_idx += [_shift_array(idx, dindex)] cell_idx = jnp.concatenate(cell_idx,", "* _cell_capacity, 1), dtype=i32) # It might be worth adding", "new set of positions and a new neighbor list. \"\"\"", "cells_per_side = tuple([int(x) for x in cells_per_side[0][::-1]]) else: raise ValueError()", "compute since often we will do a mask for species", "= nbrs.cell_list_fn neighbor_fn = partial(neighbor_fn, max_occupancy=nbrs.max_occupancy) d = partial(metric_sq, **kwargs)", "will do a mask for species that will include #", "_is_variable_compatible_with_positions(R: Array) -> bool: if (util.is_array(R) and len(R.shape) == 2", "from the grid, copy it to an array of shape", "jnp.max(count) offset = jnp.tile(jnp.arange(max_count), N)[:len(senders)] hashes = senders * max_count", "unit cube, [0, 1]^d. If this is set to True", "is inferred from R. If neighbor_list is given then it", "specified, we allocate fixed sized buffers for each cell. The", "the results of the simulation will be incorrect and the", "max_occupancy def neighbor_list_fn(R: Array, neighbor_list: Optional[NeighborList]=None, extra_capacity: int=0, **kwargs) ->", "spatial_dim = R.shape[-1] cell_capacity = onp.max(count_cell_filling(R, box_size, cell_size)) return int(cell_capacity", "in the unit cube, [0, 1]^d. If this is set", "neighbor list (with fixed capacity) if any particle has moved", "when we copy data back from the grid, copy it", "are included. \"\"\" Dense = 0 Sparse = 1 OrderedSparse", "the grid. Here we use a trick to allow us", "arr = jnp.concatenate((arr[:, 1:], arr[:, :1]), axis=1) elif dy >", "update the neighbor list. \"\"\" idx: Array reference_position: Array did_buffer_overflow:", "A function to allocate a new neighbor list. This function", "Ra, Rb, **kwargs: space.square_distance( displacement_or_metric(Ra, Rb, **kwargs)) except TypeError: continue", "radius. dr_threshold: A scalar specifying the maximum distance particles can", "_displacement_or_metric_to_metric_sq(displacement_or_metric) cell_size = cutoff if fractional_coordinates: cell_size = cutoff /", "cell_capacity particles per cell, each particle is guarenteed # to", "= R.shape[-1] cell_capacity = onp.max(count_cell_filling(R, box_size, cell_size)) return int(cell_capacity *", "NeighborList, mask: Array=None) -> jraph.GraphsTuple: \"\"\"Convert a sparse neighbor list", "float(box_size) cells_per_side = onp.floor(box_size / minimum_cell_size) cell_size = box_size /", "def cell_list(box_size: Box, minimum_cell_size: float, cell_capacity_or_example_R: Union[int, Array], buffer_size_multiplier: float=1.1", "then the current code will be slightly less efficient. minimum_cell_size:", "typing import Any, Callable, Optional, Dict, Tuple, Generator, Union import", "is often useful to partition the points / data spatially.", "R: An `(N, dim)` array of particle positions. neighbor_list: An", "import reduce, partial from collections import namedtuple from enum import", "< 0: arr = jnp.concatenate((arr[:, 1:], arr[:, :1]), axis=1) elif", "ValueError( 'Cell list spatial dimension must be 2 or 3.", "an existing neighbor list. Neighbor lists themselves additionally have a", "ids are a rectangular matrix of shape `(2, max_neighbors)` specifying", "-> NeighborList: \"\"\"A function for backward compatibility with previous neighbor", "( 'cell_capacity_or_example_positions must either be an integer ' 'specifying the", "list. See cell_list(...) for details on the construction / specification.", "jnp.reshape(sorted_id, (N, 1)) cell_id = ops.index_update( cell_id, sorted_cell_id, sorted_id) cell_R", "neighbor list ought to be updated. did_buffer_overflow: A boolean that", "# It might be worth adding an occupied mask. However,", "adding an occupied mask. However, that will involve # more", "dtype=jnp.int32) cells_per_side = jnp.concatenate((one, cells_per_side[:, :-1]), axis=1) return jnp.array(jnp.cumprod(cells_per_side), dtype=jnp.int64)", "ValueError() # TODO return jnp.reshape(arr, cells_per_side + (-1,) + arr.shape[1:])", "= copy_values_from_cell(neighbor_idx, cell_idx, idx) return neighbor_idx[:-1, :, 0] @jit def", "[particle_count, spatial_dimension] that is used to estimate the cell_capacity. buffer_size_multiplier:", "A function to update a neighbor list given a new", "is not sufficient to store all the neighbors, the `did_buffer_overflow`", "+ arr.shape[1:]) def _shift_array(arr: onp.ndarray, dindex: Array) -> Array: if", "\"\"\"Convert a sparse neighbor list to a `jraph.GraphsTuple`. As in", "return self.allocate(R, extra_capacity, **kwargs) return self.update(R, neighbor_list, **kwargs) def __iter__(self):", "Array) -> Array: if cells_per_side.size == 1: return jnp.array([[cells_per_side **", "bool=False, format: NeighborListFormat=NeighborListFormat.Dense, **static_kwargs) -> NeighborFn: \"\"\"Returns a function that", "< 0: arr = jnp.concatenate((arr[:, :, 1:], arr[:, :, :1]),", "[spatial_dimension]. id_buffer: An ndarray of int32 particle ids of shape", "cells_per_side: Array) -> Array: if cells_per_side.size == 1: return jnp.array([[cells_per_side", "NOTE(schsam): Do we want to check this in compute_fn as", "10 ** 5 cell_kwargs = {} for k, v in", "starts out False. If there are ever more neighbors than", "of the grid spacing in each ' 'dimension.')) cell_count =", "of shape `(N, max_neighbors_per_atom)`. Here the capacity of the neighbor", "grid called a cell list. Since XLA requires that shapes", "We use the convention that particles that are successfully, #", "import jax.numpy as jnp from jax_md import quantity, space, dataclasses,", "N cell_R = jnp.zeros((cell_count * _cell_capacity, dim), dtype=R.dtype) cell_id =", "pytype: disable=wrong-arg-count if nbrs is None: cell_list_fn = (cell_list(box_size, cell_size,", ":-1]), axis=1) return jnp.array(jnp.cumprod(cells_per_side), dtype=jnp.int64) else: raise ValueError() def _neighboring_cells(dimension:", "is a NeighborList containing the current neighbor list. The second", "**kwargs) else: idx, occupancy = prune_neighbor_list_dense(R, idx, **kwargs) if max_occupancy", "update a neighbor list given a new set of positions", "Array, box_size: Box, cell_size: float, buffer_size_multiplier: float) -> int: #", "senders = neighbor.idx mask = neighbor_list_mask(neighbor) receivers = receivers[mask] senders", "will include # an occupancy test. It seems easier to", "TODO(schsam): We might want to do something more sophisticated here", "enum for details about the different choices for formats. Defaults", "it to an array of shape # [N + 1,", "max_occupancy @jit def prune_neighbor_list_sparse(R, idx, **kwargs): d = partial(metric_sq, **kwargs)", "a case # in which the box_size would not be", "Create cell list data. particle_id = lax.iota(jnp.int64, N) # NOTE(schsam):", "of shape `(2, max_neighbors)` specifying the start / end particle", "extra_capacity: int=0, **kwargs) -> NeighborList: \"\"\"A function for backward compatibility", "need to be jit compatable with the fact that under", "box_size, cell_size, cells_per_side, cell_count = \\ _cell_dimensions(dim, box_size, minimum_cell_size) hash_multipliers", "get threaded through the calculation of example positions. Returns: A", "# [N, output_dimension] which ignores the empty slots. mask_id =", "for dim in range(1, 4): try: R = ShapedArray((dim,), f32)", "'NeighborListFormat.OrderedSparse.') receivers, senders = neighbor.idx N = len(neighbor.reference_position) _mask =", "ordered.at[index].set(senders)[:-1] mask = receivers < N return jraph.GraphsTuple( nodes=None, edges=None,", "where * `S = [cell_count_x, cell_count_y, cell_capacity]` * `S =", "format in list(NeighborListFormat): raise ValueError(( 'Neighbor list format must be", "particles when the neighbor list was constructed. This is used", "jnp.where(_mask, cumsum - 1, len(receivers)) ordered = N * jnp.ones((len(receivers)", "body_fn, (state, nbrs)) >>> if nbrs.did_buffer_overflow: >>> nbrs = neighbor_fn.allocate(state.position)", "minimum_cell_size) hash_multipliers = _compute_hash_constants(dim, cells_per_side) particle_index = jnp.array(R / cell_size,", "buffer sizes will have to be adjusted. This partitioning will", "are specified by id = N where N is the", "You may obtain a copy of the License at #", "will update the neighbor list (with fixed capacity) if any", "true to indicate that there was a buffer overflow. If", "else: cell_count = cells_per_side ** spatial_dimension return box_size, cell_size, cells_per_side,", "a recompilation. format: A NeighborListFormat enum specifying the format of", "> 0: arr = jnp.concatenate((arr[:, :, -1:], arr[:, :, :-1]),", "idx.shape[:-1] + cell_idx.shape[-2:]) def copy_values_from_cell(value, cell_value, cell_id): scatter_indices = jnp.reshape(cell_id,", "the grid, copy it to an array of shape #", "return dense_idx Dense = NeighborListFormat.Dense Sparse = NeighborListFormat.Sparse OrderedSparse =", "capacity_multiplier: float=1.25, disable_cell_list: bool=False, mask_self: bool=True, fractional_coordinates: bool=False, format: NeighborListFormat=NeighborListFormat.Dense,", "a simulation loop with neighbor lists: >>> init_fn, apply_fn =", "util.is_array(v): raise ValueError(( 'Data must be specified as an ndarry.", "def _vectorize(f: Callable, dim: int) -> Callable: if dim ==", "seems possibly less efficient than just # computing everything. neighbor_idx", "be an integer ' 'specifying the cell capacity or a", "(neighbor.idx[0] != neighbor.idx[1]) return mask mask = neighbor.idx < len(neighbor.idx)", "util.is_array(box_size): box_size = onp.array(box_size) if len(box_size.shape) == 1: box_size =", "cell_size)) return int(cell_capacity * buffer_size_multiplier) def _unflatten_cell_buffer(arr: Array, cells_per_side: Array,", "NeighborList] = dataclasses.static_field() update: Callable[[Array, NeighborList], NeighborList] = dataclasses.static_field() def", "NeighborListFormat.OrderedSparse: mask = mask & (receiver_idx < sender_idx) out_idx =", "= R.shape[0] if cell_list_fn is not None: cl = cell_list_fn(R)", "sparse. mask: An optional mask on the edges. Returns: A", "cell_count_y, cell_count_z, cell_capacity]` in two- and three-dimensions respectively. It is", "raise ValueError() # TODO return jnp.reshape(arr, cells_per_side + (-1,) +", "of positions of shape [particle_count, spatial_dimension] that is used to", "successfully, # copied have their true id whereas particles empty", "construct a new neighbor list whose capacity is inferred from", "Optional[int]], NeighborList] def neighbor_list(displacement_or_metric: DisplacementOrMetricFn, box_size: Box, r_cutoff: float, dr_threshold:", "1:], arr[:, :1]), axis=1) elif dy > 0: arr =", "this will invoke a recompilation. format: A NeighborListFormat enum specifying", "jnp.int32) neighbor_idx = copy_values_from_cell(neighbor_idx, cell_idx, idx) return neighbor_idx[:-1, :, 0]", "copied have their true id whereas particles empty slots have", "max_occupancy > occupancy: idx = jnp.concatenate( [idx, N * jnp.ones((idx.shape[0],", "position_buffer: An ndarray of floating point positions with shape S", "= tuple([int(x) for x in cells_per_side[::-1]]) elif util.is_array(cells_per_side) and len(cells_per_side.shape)", "neighbor_list def neighbor_fn(R_and_overflow, max_occupancy=None): R, overflow = R_and_overflow N =", "neighborhood occupancy we allocate compared with the maximum in the", "'specifying the cell capacity or a set of positions that", "partitioning will likely form the groundwork for parallelizing simulations over", "integer ' 'specifying the cell capacity or a set of", "cell_capacity_or_example_R: Either an integer specifying the size number of particles", "if use_cell_list else None) return neighbor_fn((R, False)) else: cell_list_fn =", "cells_per_side.size == spatial_dimension: one = jnp.array([[1]], dtype=jnp.int32) cells_per_side = jnp.concatenate((one,", "set of positions that will be used ' 'to estimate", "of shape # [N, output_dimension] which ignores the empty slots.", "called a cell list. Since XLA requires that shapes be", "to 1.0 and the cell size used in the cell", "cutoff = r_cutoff + dr_threshold cutoff_sq = cutoff ** 2", "def _neighboring_cells(dimension: int) -> Generator[onp.ndarray, None, None]: for dindex in", "= (int(cells_per_side),) * dim elif util.is_array(cells_per_side) and len(cells_per_side.shape) == 1:", "= dindex dz = 0 elif len(dindex) == 3: dx,", "float or an ndarray of shape [spatial_dimension] specifying the size", "of the simulation will be incorrect and the simulation needs", "== jnp.reshape(jnp.arange(idx.shape[0]), (idx.shape[0], 1)) return jnp.where(self_mask, idx.shape[0], idx) @jit def", "def copy_values_from_cell(value, cell_value, cell_id): scatter_indices = jnp.reshape(cell_id, (-1,)) cell_value =", "partition. \"\"\" if util.is_array(box_size): box_size = onp.array(box_size) if len(box_size.shape) ==", "this is set to true to indicate that there was", "function for backward compatibility with previous neighbor lists. Attributes: R:", "of points. Neighbor lists must balance the need to be", "= [cell_count_x, cell_count_y, cell_capacity]` * `S = [cell_count_x, cell_count_y, cell_count_z,", "where the boundaries are periodic. If this is not the", "neighbor list to jraph format. ' 'Please use either NeighborListFormat.Sparse", "= jnp.reshape(sorted_id, (N, 1)) cell_id = ops.index_update( cell_id, sorted_cell_id, sorted_id)", "be rerun using a larger buffer. max_occupancy: A static integer", "where grid_id # is a flat list that repeats 0,", "larger buffer. max_occupancy: A static integer specifying the maximum size", "dindex: Array) -> Array: if len(dindex) == 2: dx, dy", "cell. Cells are enlarged so that they exactly fill the", "only supports 2d or 3d.') def cell_list(box_size: Box, minimum_cell_size: float,", "ShapedArray((dim,), f32) dR_or_dr = eval_shape(displacement_or_metric, R, R, t=0) if len(dR_or_dr.shape)", "worth adding an occupied mask. However, that will involve #", "of neighbors (along with additional space specified by the `capacity_multiplier`).", "index = jnp.where(_mask, cumsum - 1, len(receivers)) ordered = N", "/ cell_size, dtype=i32) hashes = jnp.sum(indices * hash_multipliers, axis=1) #", "TypeError: continue except ValueError: continue raise ValueError( 'Canonicalize displacement not", "N = len(neighbor.reference_position) _mask = neighbor_list_mask(neighbor) if mask is not", "_compute_hash_constants(dim, cells_per_side) particle_index = jnp.array(R / cell_size, dtype=jnp.int64) particle_hash =", "= cell_list_fn(R) idx = cell_list_candidate_fn(cl, R, **kwargs) else: idx =", "format is NeighborListFormat.OrderedSparse: mask = mask & (receiver_idx < sender_idx)", "list data. particle_id = lax.iota(jnp.int64, N) # NOTE(schsam): We use", "{}.'.format(type(cell_capacity)) ) raise ValueError(msg) def build_cells(R: Array, extra_capacity: int=0, **kwargs)", "* jnp.ones( (cell_count * _cell_capacity,) + kwarg_shape, v.dtype) indices =", "k, v in kwargs.items(): if not util.is_array(v): raise ValueError(( 'Data", "we allocate fixed sized buffers for each cell. The size", "particles that can be stored in each cell or an", "positions that will be used ' 'to estimate a cell", "box_size / 3.) and not disable_cell_list @jit def candidate_fn(R, **kwargs):", "a verlet list that is larger than # needed since", "neighbors. fractional_coordinates: An optional boolean. Specifies whether positions will be", "dim), dtype=R.dtype) cell_id = N * jnp.ones((cell_count * _cell_capacity, 1),", "integers such that `idx[i, j]` is the jth neighbor of", "with i < j are included. \"\"\" Dense = 0", "jnp.floating)): return True return False def _compute_hash_constants(spatial_dimension: int, cells_per_side: Array)", "jnp.tile(jnp.arange(max_count), N)[:len(senders)] hashes = senders * max_count + offset dense_idx", "groundwork for parallelizing simulations over different accelerators. Args: box_size: A", "License. # You may obtain a copy of the License", "ndarray of shape [spatial_dimension] specifying the size of the system.", "static python function used to update the neighbor list. \"\"\"", "sparse neighbor list to dense ids. Cannot be JIT.\"\"\" if", "nbrs, lambda x: x) return NeighborListFns(lambda R, extra_capacity=0, **kwargs: neighbor_list_fn(R,", "set to true to indicate that there was a buffer", "in fractional coordinates in the unit cube, [0, 1]^d. If", "or ' 'NeighborListFormat.OrderedSparse.') receivers, senders = neighbor.idx N = len(neighbor.reference_position)", "side data placed into the cell list. \"\"\" position_buffer: Array", "list cannot be jit compiled since it uses the positions", "def to_jraph(neighbor: NeighborList, mask: Array=None) -> jraph.GraphsTuple: \"\"\"Convert a sparse", "hash_multipliers, axis=1) # Copy the particle data into the grid.", "the neighbor list is constructed using only distances. This can", "receivers = receivers[mask] senders = senders[mask] N = len(neighbor.reference_position) count", "if _is_variable_compatible_with_positions(cell_capacity): cell_capacity = _estimate_cell_capacity( cell_capacity, box_size, minimum_cell_size, buffer_size_multiplier) elif", "max_occupancy = jnp.max(cumsum[:, -1]) return out_idx[:, :-1], max_occupancy @jit def", "and not is_sparse(format): max_occupancy = R.shape[0] padding = max_occupancy -", "= (cell_list(box_size, cell_size, R, capacity_multiplier) if use_cell_list else None) return", "neighbor list that we will convert to the jraph format.", "hash_multipliers, axis=1) filling = ops.segment_sum(jnp.ones_like(particle_hash), particle_hash, cell_count) return filling def", "expose this constant. spatial_dim = R.shape[-1] cell_capacity = onp.max(count_cell_filling(R, box_size,", "into a cell list. Returns a CellList containing the partition.", "mask = mask & (neighbor.idx[0] != neighbor.idx[1]) return mask mask", "buffer overflow. If this happens, it means that the results", "use a trick to allow us to # copy into", "In # three-dimensions this seems to translate into an occupancy", "if isinstance(box_size, onp.ndarray): if box_size.ndim == 1 or box_size.ndim ==", "R, **kwargs) else: idx = candidate_fn(R, **kwargs) if mask_self: idx", "Box, minimum_cell_size: float, cell_capacity_or_example_R: Union[int, Array], buffer_size_multiplier: float=1.1 ) ->", "of # another sort. However, this seems possibly less efficient", "(-1,)) dR = d(R[sender_idx], R[receiver_idx]) mask = (dR < cutoff_sq)", "> R.shape[0] and not is_sparse(format): max_occupancy = R.shape[0] padding =", "('Box must be at least 3x the size of the", "dimension must be 2 or 3. Found {}'.format(dim)) neighborhood_tile_count =", "hashes[sort_map] sorted_id = particle_id[sort_map] sorted_kwargs = {} for k, v", "struct containing functions to allocate and update neighbor lists. Attributes:", "partition of a system into a cell list. See cell_list(...)", "dense ones.') receivers, senders = neighbor.idx mask = neighbor_list_mask(neighbor) receivers", "it is often useful to partition the points / data", "system. kwarg_buffers: A dictionary of ndarrays of shape S +", "shape `(2, max_neighbors)` specifying the start / end particle of", "= f32(box_size) cutoff = r_cutoff + dr_threshold cutoff_sq = cutoff", "Box, cell_size: float, buffer_size_multiplier: float) -> int: # TODO(schsam): We", "this more efficient by shrinking the verlet list at the", "2 and jnp.issubdtype(R.dtype, jnp.floating)): return True return False def _compute_hash_constants(spatial_dimension:", "an array of shape # [N + 1, output_dimension] and", "'Please use either NeighborListFormat.Sparse or ' 'NeighborListFormat.OrderedSparse.') receivers, senders =", "box_size. format: The format of the neighbor list; see the", "from jax import ops from jax import jit, vmap, eval_shape", "Array reference_position: Array did_buffer_overflow: Array max_occupancy: int = dataclasses.static_field() format:", "exact_apply_fn = simulate.nve(exact_energy_fn, shift, 1e-3) >>> >>> nbrs = neighbor_fn.allocate(R)", "* extra_capacity) max_occupancy = int(occupancy * capacity_multiplier + _extra_capacity) if", "Array, int]: \"\"\"Compute the number of cells-per-side and total number", "used in the cell list will be set to cutoff", "** dim _, cell_size, cells_per_side, cell_count = \\ _cell_dimensions(dim, box_size,", "onp.ndarray): if box_size.ndim == 1 or box_size.ndim == 2: assert", "partial(metric_sq, **kwargs) d = vmap(d) return lax.cond( jnp.any(d(R, nbrs.reference_position) >", "max_occupancy, format, cell_list_fn, update_fn) # pytype: disable=wrong-arg-count if nbrs is", "particles in the system. kwarg_buffers: A dictionary of ndarrays of", "None) return neighbor_fn((R, False)) else: cell_list_fn = nbrs.cell_list_fn neighbor_fn =", "at least 3x the size of the grid spacing in", "new neighbor list and 2) `neighbor_fn.update` updates an existing neighbor", "d = space.map_bond(d) N = R.shape[0] sender_idx = jnp.broadcast_to(jnp.arange(N)[:, None],", "estimated automatically from a set of positions. Note, if the", "= mask & self_mask return mask def to_jraph(neighbor: NeighborList, mask:", "sorted_cell_id cell_R = ops.index_update(cell_R, sorted_cell_id, sorted_R) sorted_id = jnp.reshape(sorted_id, (N,", "and total number of cells in a box.\"\"\" if isinstance(box_size,", "dense_idx = dense_idx.at[hashes].set(receivers).reshape((N, max_count)) return dense_idx Dense = NeighborListFormat.Dense Sparse", "Callable[[Array, Optional[NeighborList], Optional[int]], NeighborList] def neighbor_list(displacement_or_metric: DisplacementOrMetricFn, box_size: Box, r_cutoff:", "in the system. kwarg_buffers: A dictionary of ndarrays of shape", "reference_position: The positions of particles when the neighbor list was", "count = ops.segment_sum(jnp.ones(len(receivers), jnp.int32), receivers, N) max_count = jnp.max(count) offset", "particle to have a cell id = hash * cell_capacity", "id = hash * cell_capacity + grid_id where grid_id #", "max_occupancy = R.shape[0] padding = max_occupancy - occupancy if max_occupancy", "This contains side data placed into the cell list. \"\"\"", "[idx] for dindex in _neighboring_cells(dim): if onp.all(dindex == 0): continue", "neighbor list and 2) `neighbor_fn.update` updates an existing neighbor list.", "= jnp.reshape(idx, (-1,)) dR = d(R[sender_idx], R[receiver_idx]) mask = (dR", "a Neighbor List. Attributes: idx: For an N particle system", "= lax.fori_loop(0, 100, body_fn, (state, nbrs)) >>> if nbrs.did_buffer_overflow: >>>", "# another sort. However, this seems possibly less efficient than", "< cutoff_sq) & (receiver_idx < N) if format is NeighborListFormat.OrderedSparse:", "~70%. We # can make this more efficient by shrinking", "An ndarray of floating point positions with shape S +", "= senders * max_count + offset dense_idx = N *", "hash_multipliers = _compute_hash_constants(dim, cells_per_side) particle_index = jnp.array(R / cell_size, dtype=jnp.int64)", "that `idx[i, j]` is the jth neighbor of particle i.", "ndarray with shape ' '(R.shape[0], ...)). Found \"{}\" with shape", "False. If there are ever more neighbors than max_neighbors this", "neighbor list where the ids are a square matrix of", "of neighbors cannot change (owing to static shape requirements). To", "update_fn: A static python function used to update the neighbor", "statically specified, we allocate fixed sized buffers for each cell.", "== 2 and jnp.issubdtype(R.dtype, jnp.floating)): return True return False def", "sender_idx = jnp.reshape(sender_idx, (-1,)) receiver_idx = jnp.reshape(idx, (-1,)) dR =", "_compute_hash_constants(dim, cells_per_side) # Create cell list data. particle_id = lax.iota(jnp.int64,", "= (dR < cutoff_sq) & (receiver_idx < N) if format", "be a scalar or a vector.') else: cell_count = cells_per_side", "So long as there are # fewer than cell_capacity particles", "return False def _compute_hash_constants(spatial_dimension: int, cells_per_side: Array) -> Array: if", "positions with shape S + [spatial_dimension]. id_buffer: An ndarray of", "box.\"\"\" if isinstance(box_size, int) or isinstance(box_size, float): box_size = float(box_size)", "def prune_neighbor_list_sparse(R, idx, **kwargs): d = partial(metric_sq, **kwargs) d =", "len(cells_per_side.shape) == 1: cells_per_side = tuple([int(x) for x in cells_per_side[::-1]])", "is NeighborListFormat.OrderedSparse: mask = mask & (receiver_idx < sender_idx) out_idx", "get a cell id that is unique. sort_map = jnp.argsort(hashes)", "lax.stop_gradient(r_cutoff) dr_threshold = lax.stop_gradient(dr_threshold) box_size = f32(box_size) cutoff = r_cutoff", "dim == 3: return vmap(vmap(vmap(f, 0, 0), 0, 0), 0,", "k, v in kwargs.items(): sorted_kwargs[k] = v[sort_map] sorted_cell_id = jnp.mod(lax.iota(jnp.int64,", "import partial_eval as pe import jax.numpy as jnp from jax_md", "cell_size, R, capacity_multiplier) if use_cell_list else None) return neighbor_fn((R, False))", "_estimate_cell_capacity(R: Array, box_size: Box, cell_size: float, buffer_size_multiplier: float) -> int:", "sparse neighbor list where the ids are a rectangular matrix", "if mask is not None: _mask = _mask & mask", "which ignores the empty slots. mask_id = jnp.ones((N,), jnp.int64) *", "_extra_capacity = (extra_capacity if not is_sparse(format) else N * extra_capacity)", "we will convert to the jraph format. Must be sparse.", "# pytype: disable=wrong-arg-count if nbrs is None: cell_list_fn = (cell_list(box_size,", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "box_size: Box, cell_size: float, buffer_size_multiplier: float) -> int: # TODO(schsam):", "A static python callable that is used to construct a", "the neighbor list. If neighbor_list is None then the function", "if util.is_array(minimum_cell_size): minimum_cell_size = onp.array(minimum_cell_size) cell_capacity = cell_capacity_or_example_R if _is_variable_compatible_with_positions(cell_capacity):", "whether the neighbor list ought to be updated. did_buffer_overflow: A", "0), 0, 0) elif dim == 3: return vmap(vmap(vmap(f, 0,", "dataclasses.static_field() def update(self, R, **kwargs): return self.update_fn(R, self, **kwargs) @dataclasses.dataclass", "== 0: return lambda Ra, Rb, **kwargs: \\ displacement_or_metric(Ra, Rb,", "such that `idx[i, j]` is the jth neighbor of particle", "to `True` and a new neighbor list will need to", "for the specific language governing permissions and # limitations under", "0), 0, 0), 0, 0) raise ValueError('Cell list only supports", "NOTE(schsam): We use the convention that particles that are successfully,", "to True then the box_size will be set to 1.0", "jnp.int32) cumsum = jnp.cumsum(mask, axis=1) index = jnp.where(mask, cumsum -", "cells_per_side[0][::-1]]) else: raise ValueError() # TODO return jnp.reshape(arr, cells_per_side +", "MetricFn: \"\"\"Checks whether or not a displacement or metric was", "dy > 0: arr = jnp.concatenate((arr[:, -1:], arr[:, :-1]), axis=1)", "An optional boolean. If set to True then the neighbor", "r_cutoff = lax.stop_gradient(r_cutoff) dr_threshold = lax.stop_gradient(dr_threshold) box_size = f32(box_size) cutoff", "a dense neighbor list to jraph format. ' 'Please use", "specified by the `capacity_multiplier`). Updating the neighbor list can be", "jax import jit, vmap, eval_shape from jax.abstract_arrays import ShapedArray from", "infer the maximum number of neighbors (along with additional space", "cell_size = cutoff / box_size box_size = f32(1) use_cell_list =", "that each cell has the same capacity. Attributes: position_buffer: An", "the number of particles per-cell in a spatial partition.\"\"\" dim", "if not format in list(NeighborListFormat): raise ValueError(( 'Neighbor list format", "cumsum[-1] return jnp.stack((receiver_idx[:-1], sender_idx[:-1])), max_occupancy def neighbor_list_fn(R: Array, neighbor_list: Optional[NeighborList]=None,", "* dim elif util.is_array(cells_per_side) and len(cells_per_side.shape) == 1: cells_per_side =", "required by applicable law or agreed to in writing, software", "@dataclasses.dataclass class NeighborListFns: \"\"\"A struct containing functions to allocate and", "function to update a neighbor list given a new set", "== 3: return vmap(vmap(vmap(f, 0, 0), 0, 0), 0, 0)", "bonds with i < j are included. \"\"\" Dense =", ":1]), axis=2) elif dz > 0: arr = jnp.concatenate((arr[:, :,", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "nbrs = neighbor_fn.allocate(R) >>> state = init_fn(random.PRNGKey(0), R, neighbor_idx=nbrs.idx) >>>", "x) return NeighborListFns(lambda R, extra_capacity=0, **kwargs: neighbor_list_fn(R, extra_capacity=extra_capacity, **kwargs), lambda", "shapes be statically specified, we allocate fixed sized buffers for", "format is the same as `Sparse` where only bonds with", "- 1, len(receivers)) ordered = N * jnp.ones((len(receivers) + 1,),", "a scalar or a vector.') else: cell_count = cells_per_side **", "hash_multipliers = _compute_hash_constants(dim, cells_per_side) # Create cell list data. particle_id", "k, v in sorted_kwargs.items(): if v.ndim == 1: v =", "neighbor. Sparse: A sparse neighbor list where the ids are", "idx: For an N particle system this is an `[N,", "& (receiver_idx < N) if format is NeighborListFormat.OrderedSparse: mask =", "jit the maximum number of neighbors cannot change (owing to", "1,) + cell_idx.shape[-2:], jnp.int32) neighbor_idx = copy_values_from_cell(neighbor_idx, cell_idx, idx) return", "the size of the box or an array of shape", "cube, [0, 1]^d. If this is set to True then", "the number of cells-per-side and total number of cells in", "is unique. sort_map = jnp.argsort(hashes) sorted_R = R[sort_map] sorted_hash =", "capacity. Attributes: position_buffer: An ndarray of floating point positions with", "output_dimension] which ignores the empty slots. mask_id = jnp.ones((N,), jnp.int64)", "-> Generator[onp.ndarray, None, None]: for dindex in onp.ndindex(*([3] * dimension)):", "(an ndarray with shape ' '(R.shape[0], ...)). Found \"{}\" with", "== jnp.int32 or box_size.dtype == jnp.int64)): box_size = float(box_size) cells_per_side", "box_size.size == spatial_dimension flat_cells_per_side = onp.reshape(cells_per_side, (-1,)) for cells in", "functools import reduce, partial from collections import namedtuple from enum", "raise ValueError(( 'Data must be specified as an ndarry. Found", "boolean that starts out False. If there are ever more", "float, capacity_multiplier: float=1.25, disable_cell_list: bool=False, mask_self: bool=True, fractional_coordinates: bool=False, format:", "the highest connectivity neighbor. Sparse: A sparse neighbor list where", "\"\"\" Dense = 0 Sparse = 1 OrderedSparse = 2", "agreed to in writing, software # distributed under the License", "included. \"\"\" Dense = 0 Sparse = 1 OrderedSparse =", "floating point scalar specifying the fractional increase in maximum neighborhood", "senders = ordered.at[index].set(senders)[:-1] mask = receivers < N return jraph.GraphsTuple(", "in each spatial dimension. r_cutoff: A scalar specifying the neighborhood", "to dense ones.') receivers, senders = neighbor.idx mask = neighbor_list_mask(neighbor)", "distributed under the License is distributed on an \"AS IS\"", "nbrs = neighbor_fn.allocate(state.position) >>> else: >>> state = new_state >>>", "list. Since XLA requires that shapes be statically specified, we", "a jit the maximum number of neighbors cannot change (owing", "Cannot be JIT.\"\"\" if neighbor.format is not Sparse: raise ValueError('Can", "out_idx = out_idx.at[p_index, index].set(idx) max_occupancy = jnp.max(cumsum[:, -1]) return out_idx[:,", "of a Neighbor List. Attributes: idx: For an N particle", "@jit def prune_neighbor_list_sparse(R, idx, **kwargs): d = partial(metric_sq, **kwargs) d", "v) cell_kwargs[k] = _unflatten_cell_buffer( cell_kwargs[k], cells_per_side, dim) return CellList(cell_R, cell_id,", "= N * jnp.ones(idx.shape, jnp.int32) cumsum = jnp.cumsum(mask, axis=1) index", "cell_size = box_size / cells_per_side cells_per_side = onp.array(cells_per_side, dtype=jnp.int64) if", "neighbor_idx=nbrs.idx) >>> return state, nbrs >>> >>> step = 0", "return (format is NeighborListFormat.Sparse or format is NeighborListFormat.OrderedSparse) def is_format_valid(format:", "# Cell List @dataclasses.dataclass class CellList: \"\"\"Stores the spatial partition", "A static python function used to update the neighbor list.", "(extra_capacity if not is_sparse(format) else N * extra_capacity) max_occupancy =", "(box_size.dtype == jnp.int32 or box_size.dtype == jnp.int64)): box_size = float(box_size)", "to be adjusted. This partitioning will likely form the groundwork", "**kwargs) return self.update(R, neighbor_list, **kwargs) def __iter__(self): return iter((self.allocate, self.update))", "if cells_per_side.size == 1: return jnp.array([[cells_per_side ** d for d", "return jnp.broadcast_to(jnp.reshape(jnp.arange(R.shape[0]), (1, R.shape[0])), (R.shape[0], R.shape[0])) @jit def cell_list_candidate_fn(cl, R,", "1 def _estimate_cell_capacity(R: Array, box_size: Box, cell_size: float, buffer_size_multiplier: float)", "length of each cell. Cells are enlarged so that they", "= dataclasses.static_field() def update(self, R, **kwargs): return self.update_fn(R, self, **kwargs)", "raise ValueError( 'Cell list spatial dimension must be 2 or", "0, 0), 0, 0), 0, 0) raise ValueError('Cell list only", "= space.MetricFn # Cell List @dataclasses.dataclass class CellList: \"\"\"Stores the", "list format must be a member of NeighorListFormat' f' found", "a buffer overflow. If this happens, it means that the", "CellList] = dataclasses.static_field() update_fn: Callable[[Array, 'NeighborList'], 'NeighborList'] = dataclasses.static_field() def", "** 2 threshold_sq = (dr_threshold / f32(2)) ** 2 metric_sq", "+ cell_idx.shape[-2:], jnp.int32) neighbor_idx = copy_values_from_cell(neighbor_idx, cell_idx, idx) return neighbor_idx[:-1,", "= jnp.concatenate( [idx, N * jnp.ones((idx.shape[0], padding), dtype=idx.dtype)], axis=1) idx", "cell has the same capacity. Attributes: position_buffer: An ndarray of", "rectangular matrix of shape `(2, max_neighbors)` specifying the start /", "a `jraph.GraphsTuple`. As in jraph, padding here is accomplished by", "or at # least expose this constant. spatial_dim = R.shape[-1]", "= new_state >>> step += 1 Args: displacement: A function", "def neighbor_fn(R_and_overflow, max_occupancy=None): R, overflow = R_and_overflow N = R.shape[0]", "compiled since it uses the positions to infer the maximum", ">>> state = new_state >>> step += 1 Args: displacement:", "R, overflow = R_and_overflow N = R.shape[0] if cell_list_fn is", "it can be estimated automatically from a set of positions.", "Dense = 0 Sparse = 1 OrderedSparse = 2 def", "translate into an occupancy of ~70%. We # can make", "return mask def to_jraph(neighbor: NeighborList, mask: Array=None) -> jraph.GraphsTuple: \"\"\"Convert", "associated data {k_i \\in R^m} it is often useful to", "node. Args: neighbor: A neighbor list that we will convert", "& mask cumsum = jnp.cumsum(_mask) index = jnp.where(_mask, cumsum -", "(-1,)) cell_value = jnp.reshape(cell_value, (-1,) + cell_value.shape[-2:]) return ops.index_update(value, scatter_indices,", "if (isinstance(box_size, onp.ndarray) and (box_size.dtype == jnp.int32 or box_size.dtype ==", "set of positions and a new neighbor list. \"\"\" allocate:", "set to cutoff / box_size. format: The format of the", "idx, occupancy = prune_neighbor_list_dense(R, idx, **kwargs) if max_occupancy is None:", "Array, dim: int) -> Array: if (isinstance(cells_per_side, int) or isinstance(cells_per_side,", "new neighbor list. extra_capacity: Extra capacity to add if allocating", "out_idx.at[p_index, index].set(idx) max_occupancy = jnp.max(cumsum[:, -1]) return out_idx[:, :-1], max_occupancy", "a uniform grid called a cell list. Since XLA requires", "to indicate that there was a buffer overflow. If this", "dim: int) -> Array: if (isinstance(cells_per_side, int) or isinstance(cells_per_side, float)", "cell_idx.shape[-2:], jnp.int32) neighbor_idx = copy_values_from_cell(neighbor_idx, cell_idx, idx) return neighbor_idx[:-1, :,", "dim) return CellList(cell_R, cell_id, cell_kwargs) # pytype: disable=wrong-arg-count return build_cells", "'(R.shape[0], ...)). Found \"{}\" with shape {}'.format(k, v.shape))) kwarg_shape =", "point data spatially. Given a set of points {x_i \\in", "can be implemented efficiently within XLA is a dense partition", "estimate the cell_capacity. buffer_size_multiplier: A floating point multiplier that multiplies", "arr[:1])) elif dx > 0: arr = jnp.concatenate((arr[-1:], arr[:-1])) if", "if not is_sparse(format) else N * extra_capacity) max_occupancy = int(occupancy", "j are included. \"\"\" Dense = 0 Sparse = 1", "whether positions will be supplied in fractional coordinates in the", "dim) for k, v in sorted_kwargs.items(): if v.ndim == 1:", "to get a cell id that is unique. sort_map =", "nbrs.did_buffer_overflow), neighbor_fn, nbrs, lambda x: x) return NeighborListFns(lambda R, extra_capacity=0,", "allow us to # copy into all cells simultaneously using", "max_occupancy is None: _extra_capacity = (extra_capacity if not is_sparse(format) else", "NeighorListFormat' f' found {format}.')) @dataclasses.dataclass class NeighborList(object): \"\"\"A struct containing", "mask = receivers < N return jraph.GraphsTuple( nodes=None, edges=None, receivers=receivers,", "dx, dy, dz = dindex if dx < 0: arr", "-> Array: if len(dindex) == 2: dx, dy = dindex", "function that partitions point data spatially. Given a set of", "onp.array(cells_per_side, dtype=jnp.int64) if isinstance(box_size, onp.ndarray): if box_size.ndim == 1 or", "useful for debugging but should generally be left as False.", "[idx, N * jnp.ones((idx.shape[0], padding), dtype=idx.dtype)], axis=1) idx = idx[:,", "= jnp.tile(jnp.arange(max_count), N)[:len(senders)] hashes = senders * max_count + offset", "to_dense(neighbor: NeighborList) -> Array: \"\"\"Converts a sparse neighbor list to", "receiver_idx = jnp.reshape(idx, (-1,)) dR = d(R[sender_idx], R[receiver_idx]) mask =", "jnp.concatenate((arr[:, -1:], arr[:, :-1]), axis=1) if dz < 0: arr", "else neighbor_list.update_fn) return NeighborList( idx, R, jnp.logical_or(overflow, (max_occupancy < occupancy)),", "use the convention that particles that are successfully, # copied", "partial(metric_sq, **kwargs) d = space.map_neighbor(d) N = R.shape[0] neigh_R =", "jnp.arange(idx.shape[0])[:, None] out_idx = out_idx.at[p_index, index].set(idx) max_occupancy = jnp.max(cumsum[:, -1])", "must be a member of NeighorListFormat' f' found {format}.')) @dataclasses.dataclass", "= onp.array(cells_per_side, dtype=jnp.int64) if isinstance(box_size, onp.ndarray): if box_size.ndim == 1", "N * jnp.ones((len(receivers) + 1,), jnp.int32) receivers = ordered.at[index].set(receivers)[:-1] senders", "neighbor list. The second element contains a function `neighbor_list_fn(R, neighbor_list=None)`", "fractional increase in maximum neighborhood occupancy we allocate compared with", "we first sort particles by their cell hash. We then", "not cells_per_side.shape)): cells_per_side = (int(cells_per_side),) * dim elif util.is_array(cells_per_side) and", "for debugging but should generally be left as False. mask_self:", "inferred from R. If neighbor_list is given then it will", "cells_per_side: Array, dim: int) -> Array: if (isinstance(cells_per_side, int) or", "= \\ _cell_dimensions(dim, box_size, minimum_cell_size) hash_multipliers = _compute_hash_constants(dim, cells_per_side) #", "a sparse neighbor list to dense ids. Cannot be JIT.\"\"\"", "want to do something more sophisticated here or at #", "('Data must be specified per-particle (an ndarray with shape '", "cl.id_buffer cell_idx = [idx] for dindex in _neighboring_cells(dim): if onp.all(dindex", "OR CONDITIONS OF ANY KIND, either express or implied. #", "vector.') else: cell_count = cells_per_side ** spatial_dimension return box_size, cell_size,", "dimension)): yield onp.array(dindex, dtype=jnp.int64) - 1 def _estimate_cell_capacity(R: Array, box_size:", "dz < 0: arr = jnp.concatenate((arr[:, :, 1:], arr[:, :,", "used in an intermediate step of the neighbor list calculation.", "points. box_size: Either a float specifying the size of the", "either be an integer ' 'specifying the cell capacity or", "neighbor_list=None)` that will update the neighbor list. If neighbor_list is", "will construct a new neighbor list whose capacity is inferred", "the License is distributed on an \"AS IS\" BASIS, #", "Note, if the distribution of points changes significantly it is", "is not the case, then the current code will be", "if dy < 0: arr = jnp.concatenate((arr[:, 1:], arr[:, :1]),", "displacement_or_metric(Ra, Rb, **kwargs) ** 2 else: return lambda Ra, Rb,", "the idx buffer inherets its size from the cell-list. In", "jraph format. ' 'Please use either NeighborListFormat.Sparse or ' 'NeighborListFormat.OrderedSparse.')", "raise ValueError( ('Box must be at least 3x the size", "end particle of each neighbor pair. OrderedSparse: A sparse neighbor", "that will involve # more compute since often we will", "def __iter__(self): return iter((self.allocate, self.update)) NeighborFn = Callable[[Array, Optional[NeighborList], Optional[int]],", "Callable[[Array], CellList] = dataclasses.static_field() update_fn: Callable[[Array, 'NeighborList'], 'NeighborList'] = dataclasses.static_field()", "= out_idx.at[index].set(sender_idx) max_occupancy = cumsum[-1] return jnp.stack((receiver_idx[:-1], sender_idx[:-1])), max_occupancy def", "for k, v in kwargs.items(): if not util.is_array(v): raise ValueError((", "3: # NOTE(schsam): Do we want to check this in", "float, buffer_size_multiplier: float) -> int: # TODO(schsam): We might want", "idx == jnp.reshape(jnp.arange(idx.shape[0]), (idx.shape[0], 1)) return jnp.where(self_mask, idx.shape[0], idx) @jit", "else (1,) cell_kwargs[k] = empty_kwarg_value * jnp.ones( (cell_count * _cell_capacity,)", "have a cell id = hash * cell_capacity + grid_id", "**kwargs) d = space.map_neighbor(d) N = R.shape[0] neigh_R = R[idx]", "dim = R.shape[1] _cell_capacity = cell_capacity + extra_capacity if dim", "will be incorrect and the simulation needs to be rerun", "R, t=0) if len(dR_or_dr.shape) == 0: return lambda Ra, Rb,", ">>> state = apply_fn(state, neighbor_idx=nbrs.idx) >>> return state, nbrs >>>", "= lax.stop_gradient(r_cutoff) dr_threshold = lax.stop_gradient(dr_threshold) box_size = f32(box_size) cutoff =", "(format is NeighborListFormat.Sparse or format is NeighborListFormat.OrderedSparse) def is_format_valid(format: NeighborListFormat):", "positions. disable_cell_list: An optional boolean. If set to True then", "_cell_capacity,) + kwarg_shape, v.dtype) indices = jnp.array(R / cell_size, dtype=i32)", "or a vector.') else: cell_count = cells_per_side ** spatial_dimension return", "adjusted. This partitioning will likely form the groundwork for parallelizing", "jnp.concatenate((arr[1:], arr[:1])) elif dx > 0: arr = jnp.concatenate((arr[-1:], arr[:-1]))", "law or agreed to in writing, software # distributed under", "import mul import numpy as onp from jax import lax", "sort particles by their cell hash. We then assign each", "cells_per_side, dim) cell_id = _unflatten_cell_buffer(cell_id, cells_per_side, dim) for k, v", "(idx.shape[0], 1)) return jnp.where(self_mask, idx.shape[0], idx) @jit def prune_neighbor_list_dense(R, idx,", "1) elif box_size.ndim == 0: cell_count = cells_per_side ** spatial_dimension", "cell list. See cell_list(...) for details on the construction /", "ValueError( ('Box must be at least 3x the size of", "jnp.sum(particle_index * hash_multipliers, axis=1) filling = ops.segment_sum(jnp.ones_like(particle_hash), particle_hash, cell_count) return", "Returns: A function `cell_list_fn(R, **kwargs)` that partitions positions, `R`, and", "with additional space specified by the `capacity_multiplier`). Updating the neighbor", "neighbor_list is given then it will update the neighbor list", "f32(2)) ** 2 metric_sq = _displacement_or_metric_to_metric_sq(displacement_or_metric) cell_size = cutoff if", "and the cell size used in the cell list will", "is not None: _mask = _mask & mask cumsum =", "= partial(metric_sq, **kwargs) d = space.map_neighbor(d) N = R.shape[0] neigh_R", "exactly fill the box. cell_capacity_or_example_R: Either an integer specifying the", "jnp.mod(lax.iota(jnp.int64, N), _cell_capacity) sorted_cell_id = sorted_hash * _cell_capacity + sorted_cell_id", "positions of particles when the neighbor list was constructed. This", "cell_value, cell_id): scatter_indices = jnp.reshape(cell_id, (-1,)) cell_value = jnp.reshape(cell_value, (-1,)", "disable=wrong-arg-count neighbor_list_fn(R, nbrs, **kwargs)) def neighbor_list_mask(neighbor: NeighborList, mask_self: bool=False) ->", "update the neighbor list (with fixed capacity) if any particle", "extra_capacity=0, **kwargs: neighbor_list_fn(R, extra_capacity=extra_capacity, **kwargs), lambda R, nbrs, **kwargs: #", "since it uses the positions to infer the maximum number", "capacity_multiplier: A floating point scalar specifying the fractional increase in", "dim != 3: # NOTE(schsam): Do we want to check", "the maximum size of the neighbor list. Changing this will", "just # computing everything. neighbor_idx = jnp.zeros((N + 1,) +", "that contains two functions: 1) `neighbor_fn.allocate` create a new neighbor", "neighbor_list_mask(neighbor) receivers = receivers[mask] senders = senders[mask] N = len(neighbor.reference_position)", "in a box.\"\"\" if isinstance(box_size, int) or isinstance(box_size, float): box_size", "occupancy. Returns: A function `cell_list_fn(R, **kwargs)` that partitions positions, `R`,", "if not is_sparse(neighbor.format): raise ValueError('Cannot convert a dense neighbor list", "(owing to static shape requirements). To deal with this, our", "may obtain a copy of the License at # #", "isinstance(box_size, int) or isinstance(box_size, float): box_size = float(box_size) # NOTE(schsam):", "occupancy: idx = jnp.concatenate( [idx, N * jnp.ones((idx.shape[0], padding), dtype=idx.dtype)],", "neighbor_list_mask(neighbor: NeighborList, mask_self: bool=False) -> Array: \"\"\"Compute a mask for", "Args: box_size: A float or an ndarray of shape [spatial_dimension]", "flat list that repeats 0, .., cell_capacity. So long as", "- 1, idx.shape[1] - 1) p_index = jnp.arange(idx.shape[0])[:, None] out_idx", "JIT.\"\"\" if neighbor.format is not Sparse: raise ValueError('Can only convert", "in _neighboring_cells(dim): if onp.all(dindex == 0): continue cell_idx += [_shift_array(idx,", "i64 = util.i64 Box = space.Box DisplacementOrMetricFn = space.DisplacementOrMetricFn MetricFn", "the topology of the neighbor list. \"\"\" if not is_sparse(neighbor.format):", "revisit the issue if it comes up later. empty_kwarg_value =", "= (dr_threshold / f32(2)) ** 2 metric_sq = _displacement_or_metric_to_metric_sq(displacement_or_metric) cell_size", "neighbor list calculation. update_fn: A static python function used to", "I can't imagine a case # in which the box_size", "are a rectangular matrix of shape `(2, max_neighbors)` specifying the", "the ids are a square matrix of shape `(N, max_neighbors_per_atom)`.", "ought to be updated. did_buffer_overflow: A boolean that starts out", "between pairs of points. box_size: Either a float specifying the", ">>> return state, nbrs >>> >>> step = 0 >>>", "**kwargs): return jnp.broadcast_to(jnp.reshape(jnp.arange(R.shape[0]), (1, R.shape[0])), (R.shape[0], R.shape[0])) @jit def cell_list_candidate_fn(cl,", "it keeps array shapes fixed. \"\"\" is_format_valid(format) box_size = lax.stop_gradient(box_size)", "particles per-cell in a spatial partition.\"\"\" dim = int(R.shape[1]) box_size,", "Array) -> bool: if (util.is_array(R) and len(R.shape) == 2 and", "3: dx, dy, dz = dindex if dx < 0:", "the box. cell_capacity_or_example_R: Either an integer specifying the size number", "may not use this file except in compliance with the", "_unflatten_cell_buffer(cell_R, cells_per_side, dim) cell_id = _unflatten_cell_buffer(cell_id, cells_per_side, dim) for k,", "sizes will have to be adjusted. This partitioning will likely", "language governing permissions and # limitations under the License. \"\"\"Code", "None] out_idx = out_idx.at[p_index, index].set(idx) max_occupancy = jnp.max(cumsum[:, -1]) return", "**kwargs) def __iter__(self): return iter((self.allocate, self.update)) NeighborFn = Callable[[Array, Optional[NeighborList],", "assert box_size.size == spatial_dimension flat_cells_per_side = onp.reshape(cells_per_side, (-1,)) for cells", "'than 4.') class NeighborListFormat(Enum): \"\"\"An enum listing the different neighbor", "be supplied in fractional coordinates in the unit cube, [0,", "receivers, N) max_count = jnp.max(count) offset = jnp.tile(jnp.arange(max_count), N)[:len(senders)] hashes", "copy_values_from_cell(value, cell_value, cell_id): scatter_indices = jnp.reshape(cell_id, (-1,)) cell_value = jnp.reshape(cell_value,", "state): >>> state, nbrs = state >>> nbrs = nbrs.update(state.position)", "this file except in compliance with the License. # You", "if is_sparse(neighbor.format): mask = neighbor.idx[0] < len(neighbor.reference_position) if mask_self: mask", "code is written for the case where the boundaries are", "Rb, **kwargs)) except TypeError: continue except ValueError: continue raise ValueError(", "mask & (neighbor.idx[0] != neighbor.idx[1]) return mask mask = neighbor.idx", "ValueError('Can only convert sparse neighbor lists to dense ones.') receivers,", "list used in an intermediate step of the neighbor list", "2: assert box_size.size == spatial_dimension flat_cells_per_side = onp.reshape(cells_per_side, (-1,)) for", "arr[:, :, :1]), axis=2) elif dz > 0: arr =", "convert sparse neighbor lists to dense ones.') receivers, senders =", "allocates a new neighbor list. extra_capacity: Extra capacity to add", "do # this we first sort particles by their cell", "from jax import lax from jax import ops from jax", "cells simultaneously using a single lax.scatter call. To do #", "# # Licensed under the Apache License, Version 2.0 (the", "array of integers such that `idx[i, j]` is the jth", "= cutoff if fractional_coordinates: cell_size = cutoff / box_size box_size", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "to be reallocated. Here is a typical example of a", "will be set to cutoff / box_size. format: The format", "we want to check this in compute_fn as well? raise", "jraph format. Must be sparse. mask: An optional mask on", "neighbor list. \"\"\" if not is_sparse(neighbor.format): raise ValueError('Cannot convert a", "is_sparse(format) else N * extra_capacity) max_occupancy = int(occupancy * capacity_multiplier", "bool=True, fractional_coordinates: bool=False, format: NeighborListFormat=NeighborListFormat.Dense, **static_kwargs) -> NeighborFn: \"\"\"Returns a", "three-dimensions this seems to translate into an occupancy of ~70%.", "backward compatibility with previous neighbor lists. Attributes: R: An `(N,", "idx.shape[1] - 1) p_index = jnp.arange(idx.shape[0])[:, None] out_idx = out_idx.at[p_index,", "the case, then the current code will be slightly less", "the box or an array of shape [spatial_dim] specifying the", "sorted_kwargs = {} for k, v in kwargs.items(): sorted_kwargs[k] =", "buffers for each cell. The size of this buffer can", "call. To do # this we first sort particles by", "based on box_size? I can't imagine a case # in", "copy it to an array of shape # [N +", "def neighbor_list(displacement_or_metric: DisplacementOrMetricFn, box_size: Box, r_cutoff: float, dr_threshold: float, capacity_multiplier:", "cells_per_side = onp.floor(box_size / minimum_cell_size) cell_size = box_size / cells_per_side", "{}'.format(k, v.shape))) kwarg_shape = v.shape[1:] if v.ndim > 1 else", "of particles in the system. kwarg_buffers: A dictionary of ndarrays", "= onp.max(count_cell_filling(R, box_size, cell_size)) return int(cell_capacity * buffer_size_multiplier) def _unflatten_cell_buffer(arr:", "None], idx.shape) sender_idx = jnp.reshape(sender_idx, (-1,)) receiver_idx = jnp.reshape(idx, (-1,))", "larger than # needed since the idx buffer inherets its", "is_sparse(format: NeighborListFormat) -> bool: return (format is NeighborListFormat.Sparse or format", "list neighbors for collections of points. Neighbor lists must balance", "be their own neighbors. fractional_coordinates: An optional boolean. Specifies whether", "ids of shape S. Note that empty slots are specified", "lambda R, nbrs, **kwargs: # pytype: disable=wrong-arg-count neighbor_list_fn(R, nbrs, **kwargs))", "An optional mask on the edges. Returns: A `jraph.GraphsTuple` that", "R.shape[0] if cell_list_fn is not None: cl = cell_list_fn(R) idx", "NeighborList) -> Array: \"\"\"Converts a sparse neighbor list to dense", "2: return vmap(vmap(f, 0, 0), 0, 0) elif dim ==", "function. Note that allocation of a new neighbor list cannot", "kwarg_shape, v.dtype) indices = jnp.array(R / cell_size, dtype=i32) hashes =", "0: arr = jnp.concatenate((arr[:, -1:], arr[:, :-1]), axis=1) if dz", "= r_cutoff + dr_threshold cutoff_sq = cutoff ** 2 threshold_sq", "int) -> Generator[onp.ndarray, None, None]: for dindex in onp.ndindex(*([3] *", "fluctuations in the maximum cell occupancy. Returns: A function `cell_list_fn(R,", "uniform grid called a cell list. Since XLA requires that", "state >>> nbrs = nbrs.update(state.position) >>> state = apply_fn(state, neighbor_idx=nbrs.idx)", "computes the displacement between pairs of points. box_size: Either a", "about the different choices for formats. Defaults to `Dense`. **static_kwargs:", "list to a `jraph.GraphsTuple`. As in jraph, padding here is", "= lax.iota(jnp.int64, N) # NOTE(schsam): We use the convention that", "add if allocating the neighbor list. \"\"\" logging.warning('Using a depricated", "of the neighbor list. \"\"\" if not is_sparse(neighbor.format): raise ValueError('Cannot", "containing the state of a Neighbor List. Attributes: idx: For", "arr.shape[1:]) def _shift_array(arr: onp.ndarray, dindex: Array) -> Array: if len(dindex)", "neighbor.idx N = len(neighbor.reference_position) _mask = neighbor_list_mask(neighbor) if mask is", "\\ displacement_or_metric(Ra, Rb, **kwargs) ** 2 else: return lambda Ra,", "slots. mask_id = jnp.ones((N,), jnp.int64) * N cell_R = jnp.zeros((cell_count", "NOTE(schsam): Should we auto-cast based on box_size? I can't imagine", "else: raise ValueError('Box must either be a scalar or a", "capacity is not sufficient to store all the neighbors, the", "# particle to have a cell id = hash *", "self.update(R, neighbor_list, **kwargs) def __iter__(self): return iter((self.allocate, self.update)) NeighborFn =", "R.shape[0] sender_idx = jnp.broadcast_to(jnp.arange(N)[:, None], idx.shape) sender_idx = jnp.reshape(sender_idx, (-1,))", "(R.shape[0], R.shape[0])) @jit def cell_list_candidate_fn(cl, R, **kwargs): N, dim =", "the neighbor list. \"\"\" idx: Array reference_position: Array did_buffer_overflow: Array", "be used ' 'to estimate a cell capacity. Found {}.'.format(type(cell_capacity))", "pytype: disable=wrong-arg-count return build_cells def _displacement_or_metric_to_metric_sq( displacement_or_metric: DisplacementOrMetricFn) -> MetricFn:", "values of positions to infer the shapes. update: A function", "or implied. # See the License for the specific language", "v.shape[1:] if v.ndim > 1 else (1,) cell_kwargs[k] = empty_kwarg_value", "and revisit the issue if it comes up later. empty_kwarg_value", "updates the neighbor list, otherwise it allocates a new neighbor", "to construct a cell list used in an intermediate step", "a NeighborList containing the current neighbor list. The second element", "Rb, **kwargs) ** 2 else: return lambda Ra, Rb, **kwargs:", "_cell_capacity + sorted_cell_id cell_R = ops.index_update(cell_R, sorted_cell_id, sorted_R) sorted_id =", "containing functions to allocate and update neighbor lists. Attributes: allocate:", "Array, neighbor_list: Optional[NeighborList]=None, extra_capacity: int=0, **kwargs) -> NeighborList: nbrs =", "= dense_idx.at[hashes].set(receivers).reshape((N, max_count)) return dense_idx Dense = NeighborListFormat.Dense Sparse =", "the cell list. \"\"\" position_buffer: Array id_buffer: Array kwarg_buffers: Dict[str,", "a new neighbor list and 2) `neighbor_fn.update` updates an existing", "sorted_id = jnp.reshape(sorted_id, (N, 1)) cell_id = ops.index_update( cell_id, sorted_cell_id,", "/ data spatially. A simple partitioning that can be implemented", "jnp.concatenate((one, cells_per_side[:, :-1]), axis=1) return jnp.array(jnp.cumprod(cells_per_side), dtype=jnp.int64) else: raise ValueError()", "partial_eval as pe import jax.numpy as jnp from jax_md import", "return vmap(vmap(f, 0, 0), 0, 0) elif dim == 3:", "point multiplier that multiplies the estimated cell capacity to allow", "ValueError(msg) def build_cells(R: Array, extra_capacity: int=0, **kwargs) -> CellList: N", "box_size box_size = f32(1) use_cell_list = jnp.all(cell_size < box_size /", "side length of each cell. Cells are enlarged so that", "= d(R[sender_idx], R[receiver_idx]) mask = (dR < cutoff_sq) & (receiver_idx", "an occupancy of ~70%. We # can make this more", "<filename>jax_md/partition.py # Copyright 2019 Google LLC # # Licensed under", "hash. We then assign each # particle to have a", "= {} for k, v in kwargs.items(): sorted_kwargs[k] = v[sort_map]", "lambda Ra, Rb, **kwargs: \\ displacement_or_metric(Ra, Rb, **kwargs) ** 2", "the neighbor list, otherwise it allocates a new neighbor list.", "d = vmap(d) return lax.cond( jnp.any(d(R, nbrs.reference_position) > threshold_sq), (R,", "_mask & mask cumsum = jnp.cumsum(_mask) index = jnp.where(_mask, cumsum", "accomplished by adding a ficticious graph with a single node.", "dr_threshold cutoff_sq = cutoff ** 2 threshold_sq = (dr_threshold /", "cost of # another sort. However, this seems possibly less", "cell_id): scatter_indices = jnp.reshape(cell_id, (-1,)) cell_value = jnp.reshape(cell_value, (-1,) +", "is guarenteed # to get a cell id that is", "start / end particle of each neighbor pair. OrderedSparse: A", "tuple([int(x) for x in cells_per_side[::-1]]) elif util.is_array(cells_per_side) and len(cells_per_side.shape) ==", "it to an array of shape # [N, output_dimension] which", "the cell capacity or a set of positions that will", "# can make this more efficient by shrinking the verlet", "Tuple[Box, Array, Array, int]: \"\"\"Compute the number of cells-per-side and", "onp.max(count_cell_filling(R, box_size, cell_size)) return int(cell_capacity * buffer_size_multiplier) def _unflatten_cell_buffer(arr: Array,", "+ [spatial_dimension]. id_buffer: An ndarray of int32 particle ids of", "since the idx buffer inherets its size from the cell-list.", "create a new neighbor list and 2) `neighbor_fn.update` updates an", "static integer specifying the maximum size of the neighbor list.", "sized buffers for each cell. The size of this buffer", "Note that allocation of a new neighbor list cannot be", "Cell List @dataclasses.dataclass class CellList: \"\"\"Stores the spatial partition of", "neighbor_list(displacement_or_metric: DisplacementOrMetricFn, box_size: Box, r_cutoff: float, dr_threshold: float, capacity_multiplier: float=1.25,", "list spatial dimension must be 2 or 3. Found {}'.format(dim))", "< N) out_idx = N * jnp.ones(idx.shape, jnp.int32) cumsum =", "= cells_per_side ** spatial_dimension return box_size, cell_size, cells_per_side, int(cell_count) def", "the state of a Neighbor List. Attributes: idx: For an", "int) -> Callable: if dim == 2: return vmap(vmap(f, 0,", "of integers such that `idx[i, j]` is the jth neighbor", "= sorted_hash * _cell_capacity + sorted_cell_id cell_R = ops.index_update(cell_R, sorted_cell_id,", "dim) cell_id = _unflatten_cell_buffer(cell_id, cells_per_side, dim) for k, v in", "i < j are included. \"\"\" Dense = 0 Sparse", "enum specifying the format of the neighbor list. cell_list_fn: A", "not None: cl = cell_list_fn(R) idx = cell_list_candidate_fn(cl, R, **kwargs)", ") def to_dense(neighbor: NeighborList) -> Array: \"\"\"Converts a sparse neighbor", "pair. The first element is a NeighborList containing the current", "senders[mask] N = len(neighbor.reference_position) count = ops.segment_sum(jnp.ones(len(receivers), jnp.int32), receivers, N)", "cell list used in an intermediate step of the neighbor", "= jnp.sum(indices * hash_multipliers, axis=1) # Copy the particle data", "a cell list used in an intermediate step of the", "== 2: cells_per_side = tuple([int(x) for x in cells_per_side[0][::-1]]) else:", "a larger buffer. max_occupancy: A static integer specifying the maximum", "= out_idx.at[index].set(receiver_idx) sender_idx = out_idx.at[index].set(sender_idx) max_occupancy = cumsum[-1] return jnp.stack((receiver_idx[:-1],", "reduce, partial from collections import namedtuple from enum import Enum", "the box size in each spatial dimension. r_cutoff: A scalar", "the neighbor list. capacity_multiplier: A floating point scalar specifying the", "# more compute since often we will do a mask", "shapes fixed. \"\"\" is_format_valid(format) box_size = lax.stop_gradient(box_size) r_cutoff = lax.stop_gradient(r_cutoff)", "3 ** dim _, cell_size, cells_per_side, cell_count = \\ _cell_dimensions(dim,", "and len(cells_per_side.shape) == 1: cells_per_side = tuple([int(x) for x in", "raise ValueError(( 'Neighbor list format must be a member of", "since often we will do a mask for species that", "an array of shape [spatial_dim] specifying the box size in", "and # limitations under the License. \"\"\"Code to transform functions", "_unflatten_cell_buffer(arr: Array, cells_per_side: Array, dim: int) -> Array: if (isinstance(cells_per_side,", "is assumed that each cell has the same capacity. Attributes:", "v.shape[0] != R.shape[0]: raise ValueError( ('Data must be specified per-particle", "Here we use a trick to allow us to #", "= _estimate_cell_capacity( cell_capacity, box_size, minimum_cell_size, buffer_size_multiplier) elif not isinstance(cell_capacity, int):", "of particle i. reference_position: The positions of particles when the", "= jnp.concatenate((arr[-1:], arr[:-1])) if dy < 0: arr = jnp.concatenate((arr[:,", "did_buffer_overflow: A boolean that starts out False. If there are", "ever more neighbors than max_neighbors this is set to true", "1: return jnp.array([[cells_per_side ** d for d in range(spatial_dimension)]], dtype=jnp.int64)", "Array: \"\"\"Converts a sparse neighbor list to dense ids. Cannot", "jnp.ones(receiver_idx.shape, jnp.int32) cumsum = jnp.cumsum(mask) index = jnp.where(mask, cumsum -", "in the example positions. disable_cell_list: An optional boolean. If set", "to be updated. did_buffer_overflow: A boolean that starts out False.", "lists. Attributes: allocate: A function to allocate a new neighbor", "three-dimensions respectively. It is assumed that each cell has the", "' '(R.shape[0], ...)). Found \"{}\" with shape {}'.format(k, v.shape))) kwarg_shape", "parallelizing simulations over different accelerators. Args: box_size: A float or", "has the same capacity. Attributes: position_buffer: An ndarray of floating", "with the fact that under a jit the maximum number", "offset dense_idx = N * jnp.ones((N * max_count,), jnp.int32) dense_idx", "can be useful for debugging but should generally be left", "d = partial(metric_sq, **kwargs) d = vmap(d) return lax.cond( jnp.any(d(R,", "system into a cell list. See cell_list(...) for details on", "particle_id = lax.iota(jnp.int64, N) # NOTE(schsam): We use the convention", "= N. # Then when we copy data back from", "r_cutoff + dr_threshold cutoff_sq = cutoff ** 2 threshold_sq =", "msg = ( 'cell_capacity_or_example_positions must either be an integer '", "= (neighbor_list_fn if neighbor_list is None else neighbor_list.update_fn) return NeighborList(", "range(1, 4): try: R = ShapedArray((dim,), f32) dR_or_dr = eval_shape(displacement_or_metric,", "_cell_dimensions(spatial_dimension: int, box_size: Box, minimum_cell_size: float) -> Tuple[Box, Array, Array,", "ValueError( ('Data must be specified per-particle (an ndarray with shape", "= dataclasses.static_field() format: NeighborListFormat = dataclasses.static_field() cell_list_fn: Callable[[Array], CellList] =", "used to construct a cell list used in an intermediate", "**kwargs): return self.update_fn(R, self, **kwargs) @dataclasses.dataclass class NeighborListFns: \"\"\"A struct", "occupancy of ~70%. We # can make this more efficient", "S, where * `S = [cell_count_x, cell_count_y, cell_capacity]` * `S", "that repeats 0, .., cell_capacity. So long as there are", "assumed that each cell has the same capacity. Attributes: position_buffer:", "build_cells def _displacement_or_metric_to_metric_sq( displacement_or_metric: DisplacementOrMetricFn) -> MetricFn: \"\"\"Checks whether or", "list and 2) `neighbor_fn.update` updates an existing neighbor list. Neighbor", "** spatial_dimension else: raise ValueError('Box must either be a scalar", "each cell or an ndarray of positions of shape [particle_count,", "cells_per_side = jnp.concatenate((one, cells_per_side[:, :-1]), axis=1) return jnp.array(jnp.cumprod(cells_per_side), dtype=jnp.int64) else:", "to True then the neighbor list is constructed using only", "is used to decide whether the neighbor list ought to", "neighbor lists: >>> init_fn, apply_fn = simulate.nve(energy_fn, shift, 1e-3) >>>", "static python callable that is used to construct a cell", "minimum_cell_size) hash_multipliers = _compute_hash_constants(dim, cells_per_side) # Create cell list data.", "The size of this buffer can either be specified manually", "Sparse = 1 OrderedSparse = 2 def is_sparse(format: NeighborListFormat) ->", "the shapes. update: A function to update a neighbor list", "is written for the case where the boundaries are periodic.", "import quantity, space, dataclasses, util import jraph # Types Array", "(-1,)) receiver_idx = jnp.reshape(idx, (-1,)) dR = d(R[sender_idx], R[receiver_idx]) mask", "float specifying the size of the box or an array", "that multiplies the estimated cell capacity to allow for fluctuations", "if allocating the neighbor list. \"\"\" logging.warning('Using a depricated code", "simple partitioning that can be implemented efficiently within XLA is", "cutoff_sq) & (idx < N) out_idx = N * jnp.ones(idx.shape,", "Callable, dim: int) -> Callable: if dim == 2: return", "neighbor: A neighbor list that we will convert to the", ":, :1]), axis=2) elif dz > 0: arr = jnp.concatenate((arr[:,", "logging from functools import reduce, partial from collections import namedtuple", "out_idx = N * jnp.ones(receiver_idx.shape, jnp.int32) cumsum = jnp.cumsum(mask) index", "the neighbor list was constructed. This is used to decide", "It will be removed in a later version of JAX", "element is a NeighborList containing the current neighbor list. The", "+ (-1,) + arr.shape[1:]) def _shift_array(arr: onp.ndarray, dindex: Array) ->", "return int(cell_capacity * buffer_size_multiplier) def _unflatten_cell_buffer(arr: Array, cells_per_side: Array, dim:", "to cutoff / box_size. format: The format of the neighbor", "specifying the start / end particle of each neighbor pair.", "'dimension.')) cell_count = reduce(mul, flat_cells_per_side, 1) elif box_size.ndim == 0:", "We # can make this more efficient by shrinking the", "dictionary of ndarrays of shape S + [...]. This contains", "N) max_count = jnp.max(count) offset = jnp.tile(jnp.arange(max_count), N)[:len(senders)] hashes =", "box_size.ndim == 0: cell_count = cells_per_side ** spatial_dimension else: raise", "** spatial_dimension return box_size, cell_size, cells_per_side, int(cell_count) def count_cell_filling(R: Array,", "have to be adjusted. This partitioning will likely form the", "{format}.')) @dataclasses.dataclass class NeighborList(object): \"\"\"A struct containing the state of", "A sparse neighbor list whose format is the same as", "jraph # Types Array = util.Array f32 = util.f32 f64", "= max_occupancy - occupancy if max_occupancy > occupancy: idx =", "int=0, **kwargs) -> NeighborList: \"\"\"A function for backward compatibility with", "mask_self_fn(idx): self_mask = idx == jnp.reshape(jnp.arange(idx.shape[0]), (idx.shape[0], 1)) return jnp.where(self_mask,", "This function cannot be compiled, since it uses the values", "= N * jnp.ones(receiver_idx.shape, jnp.int32) cumsum = jnp.cumsum(mask) index =", "neighbor_list, **kwargs) def __iter__(self): return iter((self.allocate, self.update)) NeighborFn = Callable[[Array,", "init_fn(random.PRNGKey(0), R, neighbor_idx=nbrs.idx) >>> >>> def body_fn(i, state): >>> state,", "As in jraph, padding here is accomplished by adding a", "N = R.shape[0] dim = R.shape[1] _cell_capacity = cell_capacity +", "= neighbor.idx != jnp.reshape(jnp.arange(N), (N, 1)) mask = mask &", "(dR < cutoff_sq) & (idx < N) out_idx = N", "specifying the maximum size of the neighbor list. Changing this", "kwargs.items(): if not util.is_array(v): raise ValueError(( 'Data must be specified", "example positions. Returns: A pair. The first element is a", "is given then it will update the neighbor list (with", "-> jraph.GraphsTuple: \"\"\"Convert a sparse neighbor list to a `jraph.GraphsTuple`.", "1,), jnp.int32) receivers = ordered.at[index].set(receivers)[:-1] senders = ordered.at[index].set(senders)[:-1] mask =", "Found \"{}\" with ' 'type {}'.format(k, type(v)))) if v.shape[0] !=", "out False. If there are ever more neighbors than max_neighbors", "* max_count,), jnp.int32) dense_idx = dense_idx.at[hashes].set(receivers).reshape((N, max_count)) return dense_idx Dense", "import jit, vmap, eval_shape from jax.abstract_arrays import ShapedArray from jax.interpreters", "empty_kwarg_value * jnp.ones( (cell_count * _cell_capacity,) + kwarg_shape, v.dtype) indices", "with shape ' '(R.shape[0], ...)). Found \"{}\" with shape {}'.format(k,", "Box, r_cutoff: float, dr_threshold: float, capacity_multiplier: float=1.25, disable_cell_list: bool=False, mask_self:", "in kwargs.items(): if not util.is_array(v): raise ValueError(( 'Data must be", "= jnp.concatenate((one, cells_per_side[:, :-1]), axis=1) return jnp.array(jnp.cumprod(cells_per_side), dtype=jnp.int64) else: raise", "< box_size / 3.) and not disable_cell_list @jit def candidate_fn(R,", "around this empty_data_value # for now and revisit the issue", "connectivity neighbor. Sparse: A sparse neighbor list where the ids", "system. Note, this code is written for the case where", "@jit def cell_list_candidate_fn(cl, R, **kwargs): N, dim = R.shape R", "this empty_data_value # for now and revisit the issue if", "= len(neighbor.reference_position) self_mask = neighbor.idx != jnp.reshape(jnp.arange(N), (N, 1)) mask", "to allocate and update neighbor lists. Attributes: allocate: A function", "uses the values of positions to infer the shapes. update:", "of positions and a new neighbor list. \"\"\" allocate: Callable[...,", "the convention that particles that are successfully, # copied have", "CellList(cell_R, cell_id, cell_kwargs) # pytype: disable=wrong-arg-count return build_cells def _displacement_or_metric_to_metric_sq(", "5 cell_kwargs = {} for k, v in kwargs.items(): if", "{k_i \\in R^m} it is often useful to partition the", "/ cell_size, dtype=jnp.int64) particle_hash = jnp.sum(particle_index * hash_multipliers, axis=1) filling", "= _compute_hash_constants(dim, cells_per_side) # Create cell list data. particle_id =", "in jraph, padding here is accomplished by adding a ficticious", "verlet list at the cost of # another sort. However,", "sorted_R = R[sort_map] sorted_hash = hashes[sort_map] sorted_id = particle_id[sort_map] sorted_kwargs", "box size in each spatial dimension. r_cutoff: A scalar specifying", "over different accelerators. Args: box_size: A float or an ndarray", "neighbor list can be jit compiled; if the neighbor list", "-1]) return out_idx[:, :-1], max_occupancy @jit def prune_neighbor_list_sparse(R, idx, **kwargs):", "the neighbor list ought to be updated. did_buffer_overflow: A boolean", "box_size.ndim == 2: assert box_size.size == spatial_dimension flat_cells_per_side = onp.reshape(cells_per_side,", "copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # #", "Google LLC # # Licensed under the Apache License, Version", "`neighbor_fn.allocate` and `neighbor_fn.update` ' 'is preferred.') if neighbor_list is None:", "in writing, software # distributed under the License is distributed", "3d.') def cell_list(box_size: Box, minimum_cell_size: float, cell_capacity_or_example_R: Union[int, Array], buffer_size_multiplier:", "Array: if len(dindex) == 2: dx, dy = dindex dz", "for formats. Defaults to `Dense`. **static_kwargs: kwargs that get threaded", "= jnp.where(_mask, cumsum - 1, len(receivers)) ordered = N *", "Array, extra_capacity: int=0, **kwargs) -> CellList: N = R.shape[0] dim", "= idx[:, :max_occupancy] update_fn = (neighbor_list_fn if neighbor_list is None", "to create / update neighbor ' 'lists. It will be", "R, jnp.logical_or(overflow, (max_occupancy < occupancy)), max_occupancy, format, cell_list_fn, update_fn) #", "NeighborList(object): \"\"\"A struct containing the state of a Neighbor List.", "idx = mask_self_fn(idx) if is_sparse(format): idx, occupancy = prune_neighbor_list_sparse(R, idx,", "an array of shape # [N, output_dimension] which ignores the", "+ dr_threshold cutoff_sq = cutoff ** 2 threshold_sq = (dr_threshold", "box_size: A float or an ndarray of shape [spatial_dimension] specifying", "will involve # more compute since often we will do", "To do # this we first sort particles by their", "an integer ' 'specifying the cell capacity or a set", "update_fn = (neighbor_list_fn if neighbor_list is None else neighbor_list.update_fn) return", "neighbors for collections of points. Neighbor lists must balance the", "two functions: 1) `neighbor_fn.allocate` create a new neighbor list and", "_extra_capacity) if max_occupancy > R.shape[0] and not is_sparse(format): max_occupancy =", "def body_fn(i, state): >>> state, nbrs = state >>> nbrs", "was a buffer overflow. If this happens, it means that", "cutoff ** 2 threshold_sq = (dr_threshold / f32(2)) ** 2", "= N * jnp.ones((cell_count * _cell_capacity, 1), dtype=i32) # It", "True then the box_size will be set to 1.0 and", "License is distributed on an \"AS IS\" BASIS, # WITHOUT", "dtype=R.dtype) cell_id = N * jnp.ones((cell_count * _cell_capacity, 1), dtype=i32)", "License, Version 2.0 (the \"License\"); # you may not use", "R.shape[0])) @jit def cell_list_candidate_fn(cl, R, **kwargs): N, dim = R.shape", "update: A function to update a neighbor list given a", "sufficient to store all the neighbors, the `did_buffer_overflow` bit will", "f32(box_size) cutoff = r_cutoff + dr_threshold cutoff_sq = cutoff **", "= f32(1) use_cell_list = jnp.all(cell_size < box_size / 3.) and", "N = R.shape[0] if cell_list_fn is not None: cl =", "1), dtype=i32) # It might be worth adding an occupied", "'type {}'.format(k, type(v)))) if v.shape[0] != R.shape[0]: raise ValueError( ('Data", "range(20): >>> new_state, nbrs = lax.fori_loop(0, 100, body_fn, (state, nbrs))", "jth neighbor of particle i. reference_position: The positions of particles", "+ [...]. This contains side data placed into the cell", "idx: Array reference_position: Array did_buffer_overflow: Array max_occupancy: int = dataclasses.static_field()", "= neighbor.idx mask = neighbor_list_mask(neighbor) receivers = receivers[mask] senders =", "or box_size.dtype == jnp.int64)): box_size = float(box_size) cells_per_side = onp.floor(box_size", "pairs of points. box_size: Either a float specifying the size", "If this is not the case, then the current code", "single node. Args: neighbor: A neighbor list that we will", "n_edge=jnp.array([jnp.sum(_mask), jnp.sum(~_mask)]), ) def to_dense(neighbor: NeighborList) -> Array: \"\"\"Converts a", "= jnp.concatenate((arr[:, -1:], arr[:, :-1]), axis=1) if dz < 0:", "return self.update(R, neighbor_list, **kwargs) def __iter__(self): return iter((self.allocate, self.update)) NeighborFn", "a mask for species that will include # an occupancy", "is a flat list that repeats 0, .., cell_capacity. So", "dim in range(1, 4): try: R = ShapedArray((dim,), f32) dR_or_dr", "v.shape + (1,)) cell_kwargs[k] = ops.index_update(cell_kwargs[k], sorted_cell_id, v) cell_kwargs[k] =", "N) if format is NeighborListFormat.OrderedSparse: mask = mask & (receiver_idx", "the cost of # another sort. However, this seems possibly", "later version of JAX MD. ' 'Using `neighbor_fn.allocate` and `neighbor_fn.update`", "return out_idx[:, :-1], max_occupancy @jit def prune_neighbor_list_sparse(R, idx, **kwargs): d", "the License for the specific language governing permissions and #", "dim = R.shape R = cl.position_buffer idx = cl.id_buffer cell_idx", "ops.index_update(cell_R, sorted_cell_id, sorted_R) sorted_id = jnp.reshape(sorted_id, (N, 1)) cell_id =", ">>> step += 1 Args: displacement: A function `d(R_a, R_b)`", "(-1,) + cell_value.shape[-2:]) return ops.index_update(value, scatter_indices, cell_value) # NOTE(schsam): Currently,", "If neighbor_list is given then it will update the neighbor", "cell list. \"\"\" position_buffer: Array id_buffer: Array kwarg_buffers: Dict[str, Array]", "init_fn, apply_fn = simulate.nve(energy_fn, shift, 1e-3) >>> exact_init_fn, exact_apply_fn =", "sorted_id = particle_id[sort_map] sorted_kwargs = {} for k, v in", "that computes the displacement between pairs of points. box_size: Either", "else N * extra_capacity) max_occupancy = int(occupancy * capacity_multiplier +", "cell_list_fn = (cell_list(box_size, cell_size, R, capacity_multiplier) if use_cell_list else None)", "provided.\"\"\" for dim in range(1, 4): try: R = ShapedArray((dim,),", "max_count)) return dense_idx Dense = NeighborListFormat.Dense Sparse = NeighborListFormat.Sparse OrderedSparse", "absl import logging from functools import reduce, partial from collections", "format of the neighbor list. cell_list_fn: A static python callable", "format: A NeighborListFormat enum specifying the format of the neighbor", "float) -> Tuple[Box, Array, Array, int]: \"\"\"Compute the number of", "before rebuilding the neighbor list. capacity_multiplier: A floating point scalar", "mask = (dR < cutoff_sq) & (idx < N) out_idx", "format, cell_list_fn, update_fn) # pytype: disable=wrong-arg-count if nbrs is None:", "or isinstance(cells_per_side, float) or (util.is_array(cells_per_side) and not cells_per_side.shape)): cells_per_side =", "size of the grid spacing in each ' 'dimension.')) cell_count", "R.shape[0] neigh_R = R[idx] dR = d(R, neigh_R) mask =", "int]: \"\"\"Compute the number of cells-per-side and total number of", "- occupancy if max_occupancy > occupancy: idx = jnp.concatenate( [idx,", "if format is NeighborListFormat.OrderedSparse: mask = mask & (receiver_idx <", "shape {}'.format(k, v.shape))) kwarg_shape = v.shape[1:] if v.ndim > 1", "that is used to construct a cell list used in", "jnp.reshape(cell_id, (-1,)) cell_value = jnp.reshape(cell_value, (-1,) + cell_value.shape[-2:]) return ops.index_update(value,", "!= 2 and dim != 3: # NOTE(schsam): Do we", "format. Must be sparse. mask: An optional mask on the", "often useful to partition the points / data spatially. A", "be jit compatable with the fact that under a jit", "def prune_neighbor_list_dense(R, idx, **kwargs): d = partial(metric_sq, **kwargs) d =", "= cell_idx[..., jnp.newaxis, :, :] cell_idx = jnp.broadcast_to(cell_idx, idx.shape[:-1] +", "box_size = float(box_size) cells_per_side = onp.floor(box_size / minimum_cell_size) cell_size =", "dy < 0: arr = jnp.concatenate((arr[:, 1:], arr[:, :1]), axis=1)", "jnp.ones((cell_count * _cell_capacity, 1), dtype=i32) # It might be worth", "be estimated automatically from a set of positions. Note, if", "raise ValueError( ('Data must be specified per-particle (an ndarray with", "the function will construct a new neighbor list whose capacity", "represented by an f32. if (isinstance(box_size, onp.ndarray) and (box_size.dtype ==", "points / data spatially. A simple partitioning that can be", "specifying the box size in each spatial dimension. r_cutoff: A", "1]), n_edge=jnp.array([jnp.sum(_mask), jnp.sum(~_mask)]), ) def to_dense(neighbor: NeighborList) -> Array: \"\"\"Converts", "axis=1) # Copy the particle data into the grid. Here", "& self_mask return mask def to_jraph(neighbor: NeighborList, mask: Array=None) ->", "len(neighbor.idx) if mask_self: N = len(neighbor.reference_position) self_mask = neighbor.idx !=", "Array], buffer_size_multiplier: float=1.1 ) -> Callable[[Array], CellList]: r\"\"\"Returns a function", ">>> state = init_fn(random.PRNGKey(0), R, neighbor_idx=nbrs.idx) >>> >>> def body_fn(i,", "R^d} with associated data {k_i \\in R^m} it is often", "buffer. max_occupancy: A static integer specifying the maximum size of", "partial(metric_sq, **kwargs) d = space.map_bond(d) N = R.shape[0] sender_idx =", "elif dx > 0: arr = jnp.concatenate((arr[-1:], arr[:-1])) if dy", "calculation. update_fn: A static python function used to update the", "Note that empty slots are specified by id = N", "self.allocate(R, extra_capacity, **kwargs) return self.update(R, neighbor_list, **kwargs) def __iter__(self): return", "a mask for neighbor list.\"\"\" if is_sparse(neighbor.format): mask = neighbor.idx[0]", "= float(box_size) # NOTE(schsam): Should we auto-cast based on box_size?", "the neighbor list. Changing this will invoke a recompilation. format:", "len(dindex) == 3: dx, dy, dz = dindex if dx", "format: NeighborListFormat=NeighborListFormat.Dense, **static_kwargs) -> NeighborFn: \"\"\"Returns a function that builds", "_shift_array(arr: onp.ndarray, dindex: Array) -> Array: if len(dindex) == 2:", "implemented efficiently within XLA is a dense partition into a", "neighbors than max_neighbors this is set to true to indicate", "mask = neighbor.idx < len(neighbor.idx) if mask_self: N = len(neighbor.reference_position)", "shift, 1e-3) >>> exact_init_fn, exact_apply_fn = simulate.nve(exact_energy_fn, shift, 1e-3) >>>", "common shape, S, where * `S = [cell_count_x, cell_count_y, cell_capacity]`", "class NeighborListFormat(Enum): \"\"\"An enum listing the different neighbor list formats.", "None]: for dindex in onp.ndindex(*([3] * dimension)): yield onp.array(dindex, dtype=jnp.int64)", "Given a set of points {x_i \\in R^d} with associated", "dR_or_dr = eval_shape(displacement_or_metric, R, R, t=0) if len(dR_or_dr.shape) == 0:", "shape S + [...]. This contains side data placed into", "cells_per_side + (-1,) + arr.shape[1:]) def _shift_array(arr: onp.ndarray, dindex: Array)", "the values of positions to infer the shapes. update: A", "capacity is inferred from R. If neighbor_list is given then", "that allocation of a new neighbor list cannot be jit", "sparse neighbor list whose format is the same as `Sparse`", "particle positions. neighbor_list: An optional neighor list object. If it", "occupancy = prune_neighbor_list_dense(R, idx, **kwargs) if max_occupancy is None: _extra_capacity", "pair. OrderedSparse: A sparse neighbor list whose format is the", "list that we will convert to the jraph format. Must", "# Copyright 2019 Google LLC # # Licensed under the", "the system. kwarg_buffers: A dictionary of ndarrays of shape S", "cells_per_side, int(cell_count) def count_cell_filling(R: Array, box_size: Box, minimum_cell_size: float) ->", "comes up later. empty_kwarg_value = 10 ** 5 cell_kwargs =", "# to get a cell id that is unique. sort_map", "return lambda Ra, Rb, **kwargs: \\ displacement_or_metric(Ra, Rb, **kwargs) **", "# distributed under the License is distributed on an \"AS", "d in range(spatial_dimension)]], dtype=jnp.int64) elif cells_per_side.size == spatial_dimension: one =", "# NOTE(schsam): Do we want to check this in compute_fn", "cell_idx[..., jnp.newaxis, :, :] cell_idx = jnp.broadcast_to(cell_idx, idx.shape[:-1] + cell_idx.shape[-2:])", "size from the cell-list. In # three-dimensions this seems to", ">>> def body_fn(i, state): >>> state, nbrs = state >>>", "# Unless required by applicable law or agreed to in", "Found {}.'.format(type(cell_capacity)) ) raise ValueError(msg) def build_cells(R: Array, extra_capacity: int=0,", "jnp.int32 or box_size.dtype == jnp.int64)): box_size = float(box_size) cells_per_side =", "v in sorted_kwargs.items(): if v.ndim == 1: v = jnp.reshape(v,", "guarenteed # to get a cell id that is unique.", "cell_count_y, cell_capacity]` * `S = [cell_count_x, cell_count_y, cell_count_z, cell_capacity]` in", "be stored in each cell or an ndarray of positions", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "= jnp.zeros((cell_count * _cell_capacity, dim), dtype=R.dtype) cell_id = N *", "threaded through the calculation of example positions. Returns: A pair.", "list. \"\"\" position_buffer: Array id_buffer: Array kwarg_buffers: Dict[str, Array] def", "float) or (util.is_array(cells_per_side) and not cells_per_side.shape)): cells_per_side = (int(cells_per_side),) *", "of positions to infer the shapes. update: A function to", "idx, **kwargs): d = partial(metric_sq, **kwargs) d = space.map_neighbor(d) N", "**kwargs): N, dim = R.shape R = cl.position_buffer idx =", "= idx == jnp.reshape(jnp.arange(idx.shape[0]), (idx.shape[0], 1)) return jnp.where(self_mask, idx.shape[0], idx)", "be jit compiled since it uses the positions to infer", ":, :-1]), axis=2) return arr def _vectorize(f: Callable, dim: int)", "axis=1) idx = idx[:, :max_occupancy] update_fn = (neighbor_list_fn if neighbor_list", "A sparse neighbor list where the ids are a rectangular", "Extra capacity to add if allocating the neighbor list. \"\"\"", "then it will update the neighbor list (with fixed capacity)", "Since XLA requires that shapes be statically specified, we allocate", "dR = d(R[sender_idx], R[receiver_idx]) mask = (dR < cutoff_sq) &", "a square matrix of shape `(N, max_neighbors_per_atom)`. Here the capacity", "by kwargs into a cell list. Returns a CellList containing", "cells-per-side and total number of cells in a box.\"\"\" if", "each cell has the same capacity. Attributes: position_buffer: An ndarray", "copy into all cells simultaneously using a single lax.scatter call.", "positions. neighbor_list: An optional neighor list object. If it is", "= ops.index_update(cell_R, sorted_cell_id, sorted_R) sorted_id = jnp.reshape(sorted_id, (N, 1)) cell_id", "the Apache License, Version 2.0 (the \"License\"); # you may", "at the cost of # another sort. However, this seems", "array of shape # [N + 1, output_dimension] and then", "cell_idx = [idx] for dindex in _neighboring_cells(dim): if onp.all(dindex ==", "senders * max_count + offset dense_idx = N * jnp.ones((N", "then assign each # particle to have a cell id", ":max_occupancy] update_fn = (neighbor_list_fn if neighbor_list is None else neighbor_list.update_fn)", "cell_id = N * jnp.ones((cell_count * _cell_capacity, 1), dtype=i32) #", "neighbor_fn.allocate(state.position) >>> else: >>> state = new_state >>> step +=", "sorted_cell_id = sorted_hash * _cell_capacity + sorted_cell_id cell_R = ops.index_update(cell_R,", "(receiver_idx < sender_idx) out_idx = N * jnp.ones(receiver_idx.shape, jnp.int32) cumsum", "v in kwargs.items(): if not util.is_array(v): raise ValueError(( 'Data must", "into an occupancy of ~70%. We # can make this", "box_size, minimum_cell_size, buffer_size_multiplier) elif not isinstance(cell_capacity, int): msg = (", "of a new neighbor list cannot be jit compiled since", "arr = jnp.concatenate((arr[:, -1:], arr[:, :-1]), axis=1) if dz <", "= cell_capacity + extra_capacity if dim != 2 and dim", "particles by their cell hash. We then assign each #", "= 2 def is_sparse(format: NeighborListFormat) -> bool: return (format is", "capacity to add if allocating the neighbor list. \"\"\" logging.warning('Using", "Determines whether points can consider themselves to be their own", "list. \"\"\" allocate: Callable[..., NeighborList] = dataclasses.static_field() update: Callable[[Array, NeighborList],", "lax.fori_loop(0, 100, body_fn, (state, nbrs)) >>> if nbrs.did_buffer_overflow: >>> nbrs", "ValueError('Box must either be a scalar or a vector.') else:", "neighbor_fn = partial(neighbor_fn, max_occupancy=nbrs.max_occupancy) d = partial(metric_sq, **kwargs) d =", "cutoff / box_size. format: The format of the neighbor list;", "fewer than cell_capacity particles per cell, each particle is guarenteed", "**kwargs) if mask_self: idx = mask_self_fn(idx) if is_sparse(format): idx, occupancy", "(max_occupancy < occupancy)), max_occupancy, format, cell_list_fn, update_fn) # pytype: disable=wrong-arg-count", "of the neighbor list. Changing this will invoke a recompilation.", "kwarg_buffers: A dictionary of ndarrays of shape S + [...].", "disable_cell_list: bool=False, mask_self: bool=True, fractional_coordinates: bool=False, format: NeighborListFormat=NeighborListFormat.Dense, **static_kwargs) ->", "import ops from jax import jit, vmap, eval_shape from jax.abstract_arrays", "can move before rebuilding the neighbor list. capacity_multiplier: A floating", "particles per cell, each particle is guarenteed # to get", "apply_fn = simulate.nve(energy_fn, shift, 1e-3) >>> exact_init_fn, exact_apply_fn = simulate.nve(exact_energy_fn,", "= (extra_capacity if not is_sparse(format) else N * extra_capacity) max_occupancy", "this seems possibly less efficient than just # computing everything.", "is accomplished by adding a ficticious graph with a single", "particle i. reference_position: The positions of particles when the neighbor", "mask_self: idx = mask_self_fn(idx) if is_sparse(format): idx, occupancy = prune_neighbor_list_sparse(R,", "if not util.is_array(v): raise ValueError(( 'Data must be specified as", "for details about the different choices for formats. Defaults to", "from collections import namedtuple from enum import Enum from typing", "* max_count + offset dense_idx = N * jnp.ones((N *", "dataclasses, util import jraph # Types Array = util.Array f32", "by their cell hash. We then assign each # particle", "partitions point data spatially. Given a set of points {x_i", "that partitions positions, `R`, and side data specified by kwargs", "a `NeighborListFns` object that contains two functions: 1) `neighbor_fn.allocate` create", "Rb, **kwargs: space.square_distance( displacement_or_metric(Ra, Rb, **kwargs)) except TypeError: continue except", "DisplacementOrMetricFn) -> MetricFn: \"\"\"Checks whether or not a displacement or", "import logging from functools import reduce, partial from collections import", "not a displacement or metric was provided.\"\"\" for dim in", "space.MetricFn # Cell List @dataclasses.dataclass class CellList: \"\"\"Stores the spatial", "indices = jnp.array(R / cell_size, dtype=i32) hashes = jnp.sum(indices *", "a cell id = hash * cell_capacity + grid_id where", "sort_map = jnp.argsort(hashes) sorted_R = R[sort_map] sorted_hash = hashes[sort_map] sorted_id", "cells in flat_cells_per_side: if cells < 3: raise ValueError( ('Box", "NeighborListFormat = dataclasses.static_field() cell_list_fn: Callable[[Array], CellList] = dataclasses.static_field() update_fn: Callable[[Array,", "state, nbrs = state >>> nbrs = nbrs.update(state.position) >>> state", "of particles per-cell in a spatial partition.\"\"\" dim = int(R.shape[1])", "+ grid_id where grid_id # is a flat list that", "jnp.concatenate((arr[-1:], arr[:-1])) if dy < 0: arr = jnp.concatenate((arr[:, 1:],", "== 2: dx, dy = dindex dz = 0 elif", "significantly it is likely the buffer the buffer sizes will", "an ndarray of shape [spatial_dimension] specifying the size of the", "ValueError( 'Canonicalize displacement not implemented for spatial dimension larger' 'than", "axis=1) index = jnp.where(mask, cumsum - 1, idx.shape[1] - 1)", "the estimated cell capacity to allow for fluctuations in the", "positions. Note, if the distribution of points changes significantly it", "their cell hash. We then assign each # particle to", "a new neighbor list. This function cannot be compiled, since", "jraph, padding here is accomplished by adding a ficticious graph", "scalar or a vector.') else: cell_count = cells_per_side ** spatial_dimension", "{} for k, v in kwargs.items(): if not util.is_array(v): raise", "**kwargs) d = vmap(d) return lax.cond( jnp.any(d(R, nbrs.reference_position) > threshold_sq),", "dy = dindex dz = 0 elif len(dindex) == 3:", "1 else (1,) cell_kwargs[k] = empty_kwarg_value * jnp.ones( (cell_count *", "under the License is distributed on an \"AS IS\" BASIS,", "verlet list that is larger than # needed since the", "NeighborListFns: \"\"\"A struct containing functions to allocate and update neighbor", "N * extra_capacity) max_occupancy = int(occupancy * capacity_multiplier + _extra_capacity)", "for x in cells_per_side[0][::-1]]) else: raise ValueError() # TODO return", "optional neighor list object. If it is provided then the", "= jnp.max(cumsum[:, -1]) return out_idx[:, :-1], max_occupancy @jit def prune_neighbor_list_sparse(R,", "scale with the highest connectivity neighbor. Sparse: A sparse neighbor", "example of a simulation loop with neighbor lists: >>> init_fn,", "is_sparse(neighbor.format): mask = neighbor.idx[0] < len(neighbor.reference_position) if mask_self: mask =", "N) # NOTE(schsam): We use the convention that particles that", "a trick to allow us to # copy into all", "List. Attributes: idx: For an N particle system this is", "1)) cell_id = ops.index_update( cell_id, sorted_cell_id, sorted_id) cell_R = _unflatten_cell_buffer(cell_R,", "set to 1.0 and the cell size used in the", "set of positions. Note, if the distribution of points changes", "fixed capacity) if any particle has moved more than dr_threshold", "== 2: return vmap(vmap(f, 0, 0), 0, 0) elif dim", "be specified as an ndarry. Found \"{}\" with ' 'type", "jit compiled since it uses the positions to infer the", "used to estimate the cell_capacity. buffer_size_multiplier: A floating point multiplier", "same capacity. Attributes: position_buffer: An ndarray of floating point positions", "= jnp.mod(lax.iota(jnp.int64, N), _cell_capacity) sorted_cell_id = sorted_hash * _cell_capacity +", "from jax.interpreters import partial_eval as pe import jax.numpy as jnp", "MetricFn = space.MetricFn # Cell List @dataclasses.dataclass class CellList: \"\"\"Stores", "# [N + 1, output_dimension] and then truncate it to", "with the maximum in the example positions. disable_cell_list: An optional", ":-1], max_occupancy @jit def prune_neighbor_list_sparse(R, idx, **kwargs): d = partial(metric_sq,", "jax import ops from jax import jit, vmap, eval_shape from", "might want to do something more sophisticated here or at", "and not cells_per_side.shape)): cells_per_side = (int(cells_per_side),) * dim elif util.is_array(cells_per_side)", "occupancy = prune_neighbor_list_sparse(R, idx, **kwargs) else: idx, occupancy = prune_neighbor_list_dense(R,", "function `neighbor_list_fn(R, neighbor_list=None)` that will update the neighbor list. If", "@jit def candidate_fn(R, **kwargs): return jnp.broadcast_to(jnp.reshape(jnp.arange(R.shape[0]), (1, R.shape[0])), (R.shape[0], R.shape[0]))", "* _cell_capacity,) + kwarg_shape, v.dtype) indices = jnp.array(R / cell_size,", "are enlarged so that they exactly fill the box. cell_capacity_or_example_R:", ">>> nbrs = neighbor_fn.allocate(R) >>> state = init_fn(random.PRNGKey(0), R, neighbor_idx=nbrs.idx)", "`R`, and side data specified by kwargs into a cell", "updates an existing neighbor list. Neighbor lists themselves additionally have", "form the groundwork for parallelizing simulations over different accelerators. Args:", "1) p_index = jnp.arange(idx.shape[0])[:, None] out_idx = out_idx.at[p_index, index].set(idx) max_occupancy", "if is_sparse(format): idx, occupancy = prune_neighbor_list_sparse(R, idx, **kwargs) else: idx,", "a ficticious graph with a single node. Args: neighbor: A", "threshold_sq), (R, nbrs.did_buffer_overflow), neighbor_fn, nbrs, lambda x: x) return NeighborListFns(lambda", "v.shape))) kwarg_shape = v.shape[1:] if v.ndim > 1 else (1,)", "cell_list_fn: Callable[[Array], CellList] = dataclasses.static_field() update_fn: Callable[[Array, 'NeighborList'], 'NeighborList'] =", "Sparse: raise ValueError('Can only convert sparse neighbor lists to dense", "max_count + offset dense_idx = N * jnp.ones((N * max_count,),", "a new neighbor list whose capacity is inferred from R.", "and three-dimensions respectively. It is assumed that each cell has", "If this happens, it means that the results of the", "is a dense partition into a uniform grid called a", "partition into a uniform grid called a cell list. Since", "cell_kwargs[k] = ops.index_update(cell_kwargs[k], sorted_cell_id, v) cell_kwargs[k] = _unflatten_cell_buffer( cell_kwargs[k], cells_per_side,", "in an intermediate step of the neighbor list calculation. update_fn:", "this is set to True then the box_size will be", "code will be slightly less efficient. minimum_cell_size: A float specifying", "nbrs is None: cell_list_fn = (cell_list(box_size, cell_size, R, capacity_multiplier) if", "limitations under the License. \"\"\"Code to transform functions on individual", "= ( 'cell_capacity_or_example_positions must either be an integer ' 'specifying", "all cells simultaneously using a single lax.scatter call. To do", "lists. Attributes: R: An `(N, dim)` array of particle positions.", "particle has moved more than dr_threshold / 2. Note that", "if neighbor.format is not Sparse: raise ValueError('Can only convert sparse", "Array] def _cell_dimensions(spatial_dimension: int, box_size: Box, minimum_cell_size: float) -> Tuple[Box,", "It seems easier to design around this empty_data_value # for", "f32) dR_or_dr = eval_shape(displacement_or_metric, R, R, t=0) if len(dR_or_dr.shape) ==", "math from operator import mul import numpy as onp from", "= dataclasses.static_field() def __call__(self, R: Array, neighbor_list: Optional[NeighborList]=None, extra_capacity: int=0,", "(R, nbrs.did_buffer_overflow), neighbor_fn, nbrs, lambda x: x) return NeighborListFns(lambda R,", "for k, v in kwargs.items(): sorted_kwargs[k] = v[sort_map] sorted_cell_id =", "not sufficient to store all the neighbors, the `did_buffer_overflow` bit", "this, our `neighbor_list` returns a `NeighborListFns` object that contains two", "here or at # least expose this constant. spatial_dim =", "particles can move before rebuilding the neighbor list. capacity_multiplier: A", "N * jnp.ones(idx.shape, jnp.int32) cumsum = jnp.cumsum(mask, axis=1) index =", "== 2: assert box_size.size == spatial_dimension flat_cells_per_side = onp.reshape(cells_per_side, (-1,))", "if v.ndim == 1: v = jnp.reshape(v, v.shape + (1,))", "idx, occupancy = prune_neighbor_list_sparse(R, idx, **kwargs) else: idx, occupancy =", "optional mask on the edges. Returns: A `jraph.GraphsTuple` that contains", "stored in each cell or an ndarray of positions of", "return self.update_fn(R, self, **kwargs) @dataclasses.dataclass class NeighborListFns: \"\"\"A struct containing", "a neighbor list given a new set of positions and", "cell_count_z, cell_capacity]` in two- and three-dimensions respectively. It is assumed", "otherwise it allocates a new neighbor list. extra_capacity: Extra capacity", ">>> if nbrs.did_buffer_overflow: >>> nbrs = neighbor_fn.allocate(state.position) >>> else: >>>", "ANY KIND, either express or implied. # See the License", "0: arr = jnp.concatenate((arr[:, 1:], arr[:, :1]), axis=1) elif dy", "neighbor list to a `jraph.GraphsTuple`. As in jraph, padding here", "cell_count = cells_per_side ** spatial_dimension return box_size, cell_size, cells_per_side, int(cell_count)", "spatial dimension. r_cutoff: A scalar specifying the neighborhood radius. dr_threshold:", "the License. # You may obtain a copy of the", "else: idx = candidate_fn(R, **kwargs) if mask_self: idx = mask_self_fn(idx)", "= [cell_count_x, cell_count_y, cell_count_z, cell_capacity]` in two- and three-dimensions respectively.", "2: cells_per_side = tuple([int(x) for x in cells_per_side[0][::-1]]) else: raise", "jnp.broadcast_to(cell_idx, idx.shape[:-1] + cell_idx.shape[-2:]) def copy_values_from_cell(value, cell_value, cell_id): scatter_indices =", "Array, cells_per_side: Array, dim: int) -> Array: if (isinstance(cells_per_side, int)", "the system. Note, this code is written for the case", "max_occupancy: A static integer specifying the maximum size of the", "& (neighbor.idx[0] != neighbor.idx[1]) return mask mask = neighbor.idx <", "on individual tuples of particles to sets.\"\"\" from absl import", "# See the License for the specific language governing permissions", "more sophisticated here or at # least expose this constant.", "idx = cell_list_candidate_fn(cl, R, **kwargs) else: idx = candidate_fn(R, **kwargs)", "allocate fixed sized buffers for each cell. The size of", "Attributes: allocate: A function to allocate a new neighbor list.", "might be worth adding an occupied mask. However, that will", "specified by kwargs into a cell list. Returns a CellList", "be slightly less efficient. minimum_cell_size: A float specifying the minimum", "in kwargs.items(): sorted_kwargs[k] = v[sort_map] sorted_cell_id = jnp.mod(lax.iota(jnp.int64, N), _cell_capacity)", "only bonds with i < j are included. \"\"\" Dense", "* _cell_capacity + sorted_cell_id cell_R = ops.index_update(cell_R, sorted_cell_id, sorted_R) sorted_id", ">>> >>> step = 0 >>> for _ in range(20):", "t=0) if len(dR_or_dr.shape) == 0: return lambda Ra, Rb, **kwargs:", "positions. Returns: A pair. The first element is a NeighborList", "= lax.stop_gradient(dr_threshold) box_size = f32(box_size) cutoff = r_cutoff + dr_threshold", "globals=None, n_node=jnp.array([N, 1]), n_edge=jnp.array([jnp.sum(_mask), jnp.sum(~_mask)]), ) def to_dense(neighbor: NeighborList) ->", "callable that is used to construct a cell list used", "Callable[[Array, 'NeighborList'], 'NeighborList'] = dataclasses.static_field() def update(self, R, **kwargs): return", "padding = max_occupancy - occupancy if max_occupancy > occupancy: idx", "update the neighbor list. If neighbor_list is None then the", "partition.\"\"\" dim = int(R.shape[1]) box_size, cell_size, cells_per_side, cell_count = \\", "= jnp.reshape(cell_id, (-1,)) cell_value = jnp.reshape(cell_value, (-1,) + cell_value.shape[-2:]) return", "0: return lambda Ra, Rb, **kwargs: \\ displacement_or_metric(Ra, Rb, **kwargs)", "vmap(d) return lax.cond( jnp.any(d(R, nbrs.reference_position) > threshold_sq), (R, nbrs.did_buffer_overflow), neighbor_fn,", "Types Array = util.Array f32 = util.f32 f64 = util.f64", "4): try: R = ShapedArray((dim,), f32) dR_or_dr = eval_shape(displacement_or_metric, R,", "A NeighborListFormat enum specifying the format of the neighbor list.", "This can be useful for debugging but should generally be", "the box_size would not be accurately represented by an f32.", "construct a cell list used in an intermediate step of", "is None: return self.allocate(R, extra_capacity, **kwargs) return self.update(R, neighbor_list, **kwargs)", "under the License. \"\"\"Code to transform functions on individual tuples", "id = N where N is the number of particles", "True return False def _compute_hash_constants(spatial_dimension: int, cells_per_side: Array) -> Array:", "the neighbor list capacity is not sufficient to store all", "displacement between pairs of points. box_size: Either a float specifying", "shrinking the verlet list at the cost of # another", "R.shape[0])), (R.shape[0], R.shape[0])) @jit def cell_list_candidate_fn(cl, R, **kwargs): N, dim", "'is preferred.') if neighbor_list is None: return self.allocate(R, extra_capacity, **kwargs)", "except ValueError: continue raise ValueError( 'Canonicalize displacement not implemented for", "different neighbor list formats. Attributes: Dense: A dense neighbor list", "formats. Defaults to `Dense`. **static_kwargs: kwargs that get threaded through", "format of the neighbor list; see the NeighborListFormat enum for", "of points changes significantly it is likely the buffer the", "to `Dense`. **static_kwargs: kwargs that get threaded through the calculation", "`idx[i, j]` is the jth neighbor of particle i. reference_position:", "0: arr = jnp.concatenate((arr[-1:], arr[:-1])) if dy < 0: arr", "it is provided then the function updates the neighbor list,", "_compute_hash_constants(spatial_dimension: int, cells_per_side: Array) -> Array: if cells_per_side.size == 1:", "auto-cast based on box_size? I can't imagine a case #", "'Neighbor list format must be a member of NeighorListFormat' f'", "2. Note that only `neighbor_list_fn(R, neighbor_list)` can be `jit` since", "ficticious graph with a single node. Args: neighbor: A neighbor", "sorted_kwargs[k] = v[sort_map] sorted_cell_id = jnp.mod(lax.iota(jnp.int64, N), _cell_capacity) sorted_cell_id =", "mask: Array=None) -> jraph.GraphsTuple: \"\"\"Convert a sparse neighbor list to", "jnp.array([[cells_per_side ** d for d in range(spatial_dimension)]], dtype=jnp.int64) elif cells_per_side.size", "this we first sort particles by their cell hash. We", "Licensed under the Apache License, Version 2.0 (the \"License\"); #", "has moved more than dr_threshold / 2. Note that only", "cell. The size of this buffer can either be specified", "== 1 or box_size.ndim == 2: assert box_size.size == spatial_dimension", "a new neighbor list. \"\"\" allocate: Callable[..., NeighborList] = dataclasses.static_field()", "placed into the cell list. \"\"\" position_buffer: Array id_buffer: Array", "only convert sparse neighbor lists to dense ones.') receivers, senders", "util.Array f32 = util.f32 f64 = util.f64 i32 = util.i32", "case where the boundaries are periodic. If this is not", "ValueError(( 'Data must be specified as an ndarry. Found \"{}\"", "cell_list_candidate_fn(cl, R, **kwargs) else: idx = candidate_fn(R, **kwargs) if mask_self:", "writing, software # distributed under the License is distributed on", "and dim != 3: # NOTE(schsam): Do we want to", "from R. If neighbor_list is given then it will update", "return mask mask = neighbor.idx < len(neighbor.idx) if mask_self: N", "R, extra_capacity=0, **kwargs: neighbor_list_fn(R, extra_capacity=extra_capacity, **kwargs), lambda R, nbrs, **kwargs:", "> 0: arr = jnp.concatenate((arr[:, -1:], arr[:, :-1]), axis=1) if", "cell_id, cell_kwargs) # pytype: disable=wrong-arg-count return build_cells def _displacement_or_metric_to_metric_sq( displacement_or_metric:", "will have to be adjusted. This partitioning will likely form", "have a convenience `update` member function. Note that allocation of", "lax.stop_gradient(box_size) r_cutoff = lax.stop_gradient(r_cutoff) dr_threshold = lax.stop_gradient(dr_threshold) box_size = f32(box_size)", "idx) return neighbor_idx[:-1, :, 0] @jit def mask_self_fn(idx): self_mask =", "> occupancy: idx = jnp.concatenate( [idx, N * jnp.ones((idx.shape[0], padding),", "len(neighbor.reference_position) count = ops.segment_sum(jnp.ones(len(receivers), jnp.int32), receivers, N) max_count = jnp.max(count)", "cell list data. particle_id = lax.iota(jnp.int64, N) # NOTE(schsam): We", "spatially. Given a set of points {x_i \\in R^d} with", "must be specified as an ndarry. Found \"{}\" with '", "2: dx, dy = dindex dz = 0 elif len(dindex)", "0, 0), 0, 0) elif dim == 3: return vmap(vmap(vmap(f,", "dz = 0 elif len(dindex) == 3: dx, dy, dz", "format is NeighborListFormat.OrderedSparse) def is_format_valid(format: NeighborListFormat): if not format in", "spatial dimension larger' 'than 4.') class NeighborListFormat(Enum): \"\"\"An enum listing", "with previous neighbor lists. Attributes: R: An `(N, dim)` array", "* `S = [cell_count_x, cell_count_y, cell_count_z, cell_capacity]` in two- and", "a set of points {x_i \\in R^d} with associated data", "be useful for debugging but should generally be left as", "if max_occupancy is None: _extra_capacity = (extra_capacity if not is_sparse(format)", "ops.index_update(value, scatter_indices, cell_value) # NOTE(schsam): Currently, this makes a verlet", "extra_capacity, **kwargs) return self.update(R, neighbor_list, **kwargs) def __iter__(self): return iter((self.allocate,", "_unflatten_cell_buffer( cell_kwargs[k], cells_per_side, dim) return CellList(cell_R, cell_id, cell_kwargs) # pytype:", "Tuple, Generator, Union import math from operator import mul import", "this is not the case, then the current code will", "sorted_cell_id, v) cell_kwargs[k] = _unflatten_cell_buffer( cell_kwargs[k], cells_per_side, dim) return CellList(cell_R,", "+ 1,) + cell_idx.shape[-2:], jnp.int32) neighbor_idx = copy_values_from_cell(neighbor_idx, cell_idx, idx)", "from functools import reduce, partial from collections import namedtuple from", "def count_cell_filling(R: Array, box_size: Box, minimum_cell_size: float) -> Array: \"\"\"Counts", "neighbor list must scale with the highest connectivity neighbor. Sparse:", "Array, neighbor_list: Optional[NeighborList]=None, extra_capacity: int=0, **kwargs) -> NeighborList: \"\"\"A function", "useful to partition the points / data spatially. A simple", "size of the neighbor list. Changing this will invoke a", "cell_count = cells_per_side ** spatial_dimension else: raise ValueError('Box must either", "is None: _extra_capacity = (extra_capacity if not is_sparse(format) else N", "raise ValueError('Cell list only supports 2d or 3d.') def cell_list(box_size:", "fact that under a jit the maximum number of neighbors", "= _displacement_or_metric_to_metric_sq(displacement_or_metric) cell_size = cutoff if fractional_coordinates: cell_size = cutoff", "= senders[mask] N = len(neighbor.reference_position) count = ops.segment_sum(jnp.ones(len(receivers), jnp.int32), receivers,", "the cell list will be set to cutoff / box_size.", "arr[:, :, :-1]), axis=2) return arr def _vectorize(f: Callable, dim:", "dindex in _neighboring_cells(dim): if onp.all(dindex == 0): continue cell_idx +=", "-> CellList: N = R.shape[0] dim = R.shape[1] _cell_capacity =", "= apply_fn(state, neighbor_idx=nbrs.idx) >>> return state, nbrs >>> >>> step", "a list neighbors for collections of points. Neighbor lists must", "shape [particle_count, spatial_dimension] that is used to estimate the cell_capacity.", "0 >>> for _ in range(20): >>> new_state, nbrs =", "Cells are enlarged so that they exactly fill the box.", "prune_neighbor_list_sparse(R, idx, **kwargs) else: idx, occupancy = prune_neighbor_list_dense(R, idx, **kwargs)", "id = N. # Then when we copy data back", "neighbor_list)` can be `jit` since it keeps array shapes fixed.", "logging.warning('Using a depricated code path to create / update neighbor", "more neighbors than max_neighbors this is set to true to", "util.i32 i64 = util.i64 Box = space.Box DisplacementOrMetricFn = space.DisplacementOrMetricFn", "int(cell_count) def count_cell_filling(R: Array, box_size: Box, minimum_cell_size: float) -> Array:", "v[sort_map] sorted_cell_id = jnp.mod(lax.iota(jnp.int64, N), _cell_capacity) sorted_cell_id = sorted_hash *", "from the cell-list. In # three-dimensions this seems to translate", "generally be left as False. mask_self: An optional boolean. Determines", "sorted_id) cell_R = _unflatten_cell_buffer(cell_R, cells_per_side, dim) cell_id = _unflatten_cell_buffer(cell_id, cells_per_side,", "second element contains a function `neighbor_list_fn(R, neighbor_list=None)` that will update", "side data specified by kwargs into a cell list. Returns", "- 1) receiver_idx = out_idx.at[index].set(receiver_idx) sender_idx = out_idx.at[index].set(sender_idx) max_occupancy =", "jnp.int64) * N cell_R = jnp.zeros((cell_count * _cell_capacity, dim), dtype=R.dtype)", "int(occupancy * capacity_multiplier + _extra_capacity) if max_occupancy > R.shape[0] and", "= 3 ** dim _, cell_size, cells_per_side, cell_count = \\", "+ cell_idx.shape[-2:]) def copy_values_from_cell(value, cell_value, cell_id): scatter_indices = jnp.reshape(cell_id, (-1,))", "= neighbor.idx N = len(neighbor.reference_position) _mask = neighbor_list_mask(neighbor) if mask", "Neighbor lists must balance the need to be jit compatable", "the boundaries are periodic. If this is not the case,", "a single lax.scatter call. To do # this we first", "allocate compared with the maximum in the example positions. disable_cell_list:", "jnp.int32), receivers, N) max_count = jnp.max(count) offset = jnp.tile(jnp.arange(max_count), N)[:len(senders)]", "later. empty_kwarg_value = 10 ** 5 cell_kwargs = {} for", "neighbor_idx[:-1, :, 0] @jit def mask_self_fn(idx): self_mask = idx ==", "is likely the buffer the buffer sizes will have to", "compiled; if the neighbor list capacity is not sufficient to", "- 1, len(receiver_idx) - 1) receiver_idx = out_idx.at[index].set(receiver_idx) sender_idx =", "`neighbor_list_fn(R, neighbor_list=None)` that will update the neighbor list. If neighbor_list", "def mask_self_fn(idx): self_mask = idx == jnp.reshape(jnp.arange(idx.shape[0]), (idx.shape[0], 1)) return", "R^m} it is often useful to partition the points /", "cell_kwargs = {} for k, v in kwargs.items(): if not", "details on the construction / specification. Cell list buffers all", "\"\"\"Compute the number of cells-per-side and total number of cells", "as jnp from jax_md import quantity, space, dataclasses, util import", "= cell_capacity_or_example_R if _is_variable_compatible_with_positions(cell_capacity): cell_capacity = _estimate_cell_capacity( cell_capacity, box_size, minimum_cell_size,", "trick to allow us to # copy into all cells", "cell capacity to allow for fluctuations in the maximum cell", "list. \"\"\" if not is_sparse(neighbor.format): raise ValueError('Cannot convert a dense", "create / update neighbor ' 'lists. It will be removed", "NeighborList( idx, R, jnp.logical_or(overflow, (max_occupancy < occupancy)), max_occupancy, format, cell_list_fn,", "= ordered.at[index].set(receivers)[:-1] senders = ordered.at[index].set(senders)[:-1] mask = receivers < N", "-> Array: \"\"\"Converts a sparse neighbor list to dense ids.", "# is a flat list that repeats 0, .., cell_capacity.", "Here is a typical example of a simulation loop with", "dim == 2: return vmap(vmap(f, 0, 0), 0, 0) elif", "this happens, it means that the results of the simulation", "/ cells_per_side cells_per_side = onp.array(cells_per_side, dtype=jnp.int64) if isinstance(box_size, onp.ndarray): if", "0, 0) raise ValueError('Cell list only supports 2d or 3d.')", "receiver_idx = out_idx.at[index].set(receiver_idx) sender_idx = out_idx.at[index].set(sender_idx) max_occupancy = cumsum[-1] return", "the current code will be slightly less efficient. minimum_cell_size: A", "imagine a case # in which the box_size would not", "function to allocate a new neighbor list. This function cannot", "specifying the neighborhood radius. dr_threshold: A scalar specifying the maximum", "calculation of example positions. Returns: A pair. The first element", "cannot be jit compiled since it uses the positions to", "+= [_shift_array(idx, dindex)] cell_idx = jnp.concatenate(cell_idx, axis=-2) cell_idx = cell_idx[...,", "-> Callable: if dim == 2: return vmap(vmap(f, 0, 0),", "vmap, eval_shape from jax.abstract_arrays import ShapedArray from jax.interpreters import partial_eval", "the size of the grid spacing in each ' 'dimension.'))", "**kwargs: # pytype: disable=wrong-arg-count neighbor_list_fn(R, nbrs, **kwargs)) def neighbor_list_mask(neighbor: NeighborList,", "ndarry. Found \"{}\" with ' 'type {}'.format(k, type(v)))) if v.shape[0]", "minimum_cell_size: float) -> Array: \"\"\"Counts the number of particles per-cell", "= R[sort_map] sorted_hash = hashes[sort_map] sorted_id = particle_id[sort_map] sorted_kwargs =", "by adding a ficticious graph with a single node. Args:", "function cannot be compiled, since it uses the values of", "= prune_neighbor_list_sparse(R, idx, **kwargs) else: idx, occupancy = prune_neighbor_list_dense(R, idx,", "floating point positions with shape S + [spatial_dimension]. id_buffer: An", "[_shift_array(idx, dindex)] cell_idx = jnp.concatenate(cell_idx, axis=-2) cell_idx = cell_idx[..., jnp.newaxis,", "are a square matrix of shape `(N, max_neighbors_per_atom)`. Here the", "neighbor_list is None then the function will construct a new", "specifying the fractional increase in maximum neighborhood occupancy we allocate", "we copy data back from the grid, copy it to", "the maximum number of neighbors cannot change (owing to static", "rebuilding the neighbor list. capacity_multiplier: A floating point scalar specifying", "N * jnp.ones(receiver_idx.shape, jnp.int32) cumsum = jnp.cumsum(mask) index = jnp.where(mask,", "1e-3) >>> >>> nbrs = neighbor_fn.allocate(R) >>> state = init_fn(random.PRNGKey(0),", "that partitions point data spatially. Given a set of points", "the same as `Sparse` where only bonds with i <", "onp.floor(box_size / minimum_cell_size) cell_size = box_size / cells_per_side cells_per_side =", "Attributes: idx: For an N particle system this is an", "neigh_R = R[idx] dR = d(R, neigh_R) mask = (dR", ":, 1:], arr[:, :, :1]), axis=2) elif dz > 0:", "neighbor_list: Optional[NeighborList]=None, extra_capacity: int=0, **kwargs) -> NeighborList: \"\"\"A function for", "index].set(idx) max_occupancy = jnp.max(cumsum[:, -1]) return out_idx[:, :-1], max_occupancy @jit", "0 Sparse = 1 OrderedSparse = 2 def is_sparse(format: NeighborListFormat)", "@jit def mask_self_fn(idx): self_mask = idx == jnp.reshape(jnp.arange(idx.shape[0]), (idx.shape[0], 1))", "\\ _cell_dimensions(dim, box_size, minimum_cell_size) hash_multipliers = _compute_hash_constants(dim, cells_per_side) # Create", "intermediate step of the neighbor list calculation. update_fn: A static", "else: raise ValueError() # TODO return jnp.reshape(arr, cells_per_side + (-1,)", "are periodic. If this is not the case, then the", "mask. However, that will involve # more compute since often", "mask for species that will include # an occupancy test.", "specified per-particle (an ndarray with shape ' '(R.shape[0], ...)). Found", "cell_list_fn = nbrs.cell_list_fn neighbor_fn = partial(neighbor_fn, max_occupancy=nbrs.max_occupancy) d = partial(metric_sq,", "seems to translate into an occupancy of ~70%. We #", "neighbor.format is not Sparse: raise ValueError('Can only convert sparse neighbor", "import Any, Callable, Optional, Dict, Tuple, Generator, Union import math", "shape ' '(R.shape[0], ...)). Found \"{}\" with shape {}'.format(k, v.shape)))", "neighbor pair. OrderedSparse: A sparse neighbor list whose format is", "to infer the maximum number of neighbors (along with additional", "out_idx.at[index].set(sender_idx) max_occupancy = cumsum[-1] return jnp.stack((receiver_idx[:-1], sender_idx[:-1])), max_occupancy def neighbor_list_fn(R:", "jnp.max(cumsum[:, -1]) return out_idx[:, :-1], max_occupancy @jit def prune_neighbor_list_sparse(R, idx,", "OrderedSparse = 2 def is_sparse(format: NeighborListFormat) -> bool: return (format", ">>> >>> def body_fn(i, state): >>> state, nbrs = state", "A scalar specifying the neighborhood radius. dr_threshold: A scalar specifying", "on box_size? I can't imagine a case # in which", "of this buffer can either be specified manually or it", "jit, vmap, eval_shape from jax.abstract_arrays import ShapedArray from jax.interpreters import", "N, dim = R.shape R = cl.position_buffer idx = cl.id_buffer", "reallocated. Here is a typical example of a simulation loop", "jnp.concatenate(cell_idx, axis=-2) cell_idx = cell_idx[..., jnp.newaxis, :, :] cell_idx =", "not Sparse: raise ValueError('Can only convert sparse neighbor lists to", "any particle has moved more than dr_threshold / 2. Note", "neighbor list. This function cannot be compiled, since it uses", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "our `neighbor_list` returns a `NeighborListFns` object that contains two functions:", "False. mask_self: An optional boolean. Determines whether points can consider", "float=1.1 ) -> Callable[[Array], CellList]: r\"\"\"Returns a function that partitions", "isinstance(box_size, onp.ndarray): if box_size.ndim == 1 or box_size.ndim == 2:", "body_fn(i, state): >>> state, nbrs = state >>> nbrs =", "return filling def _is_variable_compatible_with_positions(R: Array) -> bool: if (util.is_array(R) and", "< sender_idx) out_idx = N * jnp.ones(receiver_idx.shape, jnp.int32) cumsum =", "positions to infer the maximum number of neighbors (along with", "_neighboring_cells(dimension: int) -> Generator[onp.ndarray, None, None]: for dindex in onp.ndindex(*([3]", "'NeighborList'] = dataclasses.static_field() def update(self, R, **kwargs): return self.update_fn(R, self,", "util.f32 f64 = util.f64 i32 = util.i32 i64 = util.i64", "to an array of shape # [N, output_dimension] which ignores", "cell_kwargs[k] = empty_kwarg_value * jnp.ones( (cell_count * _cell_capacity,) + kwarg_shape,", "tuple([int(x) for x in cells_per_side[0][::-1]]) else: raise ValueError() # TODO", "same as `Sparse` where only bonds with i < j", "accurately represented by an f32. if (isinstance(box_size, onp.ndarray) and (box_size.dtype", "sender_idx = jnp.broadcast_to(jnp.arange(N)[:, None], idx.shape) sender_idx = jnp.reshape(sender_idx, (-1,)) receiver_idx", "onp from jax import lax from jax import ops from", "== spatial_dimension flat_cells_per_side = onp.reshape(cells_per_side, (-1,)) for cells in flat_cells_per_side:", "or it can be estimated automatically from a set of", "is_format_valid(format: NeighborListFormat): if not format in list(NeighborListFormat): raise ValueError(( 'Neighbor", "The positions of particles when the neighbor list was constructed.", "class NeighborListFns: \"\"\"A struct containing functions to allocate and update", "not util.is_array(v): raise ValueError(( 'Data must be specified as an", "float=1.25, disable_cell_list: bool=False, mask_self: bool=True, fractional_coordinates: bool=False, format: NeighborListFormat=NeighborListFormat.Dense, **static_kwargs)", "new_state >>> step += 1 Args: displacement: A function `d(R_a,", "list. Neighbor lists themselves additionally have a convenience `update` member", "' 'Using `neighbor_fn.allocate` and `neighbor_fn.update` ' 'is preferred.') if neighbor_list", "must either be an integer ' 'specifying the cell capacity", "number of cells-per-side and total number of cells in a", "neighbor_list: Optional[NeighborList]=None, extra_capacity: int=0, **kwargs) -> NeighborList: nbrs = neighbor_list", "' 'Please use either NeighborListFormat.Sparse or ' 'NeighborListFormat.OrderedSparse.') receivers, senders", "point scalar specifying the fractional increase in maximum neighborhood occupancy", "NeighborList: nbrs = neighbor_list def neighbor_fn(R_and_overflow, max_occupancy=None): R, overflow =", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "0: arr = jnp.concatenate((arr[:, :, 1:], arr[:, :, :1]), axis=2)", "NeighborListFormat.Sparse or ' 'NeighborListFormat.OrderedSparse.') receivers, senders = neighbor.idx N =", "compatibility with previous neighbor lists. Attributes: R: An `(N, dim)`", "list buffers all have a common shape, S, where *", "shape `(N, max_neighbors_per_atom)`. Here the capacity of the neighbor list", "def update(self, R, **kwargs): return self.update_fn(R, self, **kwargs) @dataclasses.dataclass class", "{} for k, v in kwargs.items(): sorted_kwargs[k] = v[sort_map] sorted_cell_id", "R, R, t=0) if len(dR_or_dr.shape) == 0: return lambda Ra,", "\"\"\" is_format_valid(format) box_size = lax.stop_gradient(box_size) r_cutoff = lax.stop_gradient(r_cutoff) dr_threshold =", "so that they exactly fill the box. cell_capacity_or_example_R: Either an", "util.f64 i32 = util.i32 i64 = util.i64 Box = space.Box", "Array) -> Array: if len(dindex) == 2: dx, dy =", "= tuple([int(x) for x in cells_per_side[0][::-1]]) else: raise ValueError() #", "with associated data {k_i \\in R^m} it is often useful", "an `[N, max_occupancy]` array of integers such that `idx[i, j]`", "If set to True then the neighbor list is constructed", "cumsum - 1, idx.shape[1] - 1) p_index = jnp.arange(idx.shape[0])[:, None]", "in range(spatial_dimension)]], dtype=jnp.int64) elif cells_per_side.size == spatial_dimension: one = jnp.array([[1]],", "elif util.is_array(cells_per_side) and len(cells_per_side.shape) == 1: cells_per_side = tuple([int(x) for", "we will do a mask for species that will include", "= N * jnp.ones((N * max_count,), jnp.int32) dense_idx = dense_idx.at[hashes].set(receivers).reshape((N,", "Either an integer specifying the size number of particles that", "invoke a recompilation. format: A NeighborListFormat enum specifying the format", ":1]), axis=1) elif dy > 0: arr = jnp.concatenate((arr[:, -1:],", "None: return self.allocate(R, extra_capacity, **kwargs) return self.update(R, neighbor_list, **kwargs) def", "Defaults to `Dense`. **static_kwargs: kwargs that get threaded through the", "using a larger buffer. max_occupancy: A static integer specifying the", "cell_R = ops.index_update(cell_R, sorted_cell_id, sorted_R) sorted_id = jnp.reshape(sorted_id, (N, 1))", "neighbor list. \"\"\" idx: Array reference_position: Array did_buffer_overflow: Array max_occupancy:", "DisplacementOrMetricFn = space.DisplacementOrMetricFn MetricFn = space.MetricFn # Cell List @dataclasses.dataclass", "the number of particles in the system. kwarg_buffers: A dictionary", "not implemented for spatial dimension larger' 'than 4.') class NeighborListFormat(Enum):", "shape [spatial_dim] specifying the box size in each spatial dimension.", "the start / end particle of each neighbor pair. OrderedSparse:", "This partitioning will likely form the groundwork for parallelizing simulations", "cell_count = \\ _cell_dimensions(dim, box_size, minimum_cell_size) hash_multipliers = _compute_hash_constants(dim, cells_per_side)", "v in kwargs.items(): sorted_kwargs[k] = v[sort_map] sorted_cell_id = jnp.mod(lax.iota(jnp.int64, N),", "XLA is a dense partition into a uniform grid called", "# in which the box_size would not be accurately represented", "onp.reshape(cells_per_side, (-1,)) for cells in flat_cells_per_side: if cells < 3:", "spatial dimension must be 2 or 3. Found {}'.format(dim)) neighborhood_tile_count", "moved more than dr_threshold / 2. Note that only `neighbor_list_fn(R,", "we allocate compared with the maximum in the example positions.", "where only bonds with i < j are included. \"\"\"", "current neighbor list. The second element contains a function `neighbor_list_fn(R,", "this is an `[N, max_occupancy]` array of integers such that", "box_size: Box, minimum_cell_size: float) -> Array: \"\"\"Counts the number of", "if neighbor_list is None: return self.allocate(R, extra_capacity, **kwargs) return self.update(R,", "the construction / specification. Cell list buffers all have a", "if len(dindex) == 2: dx, dy = dindex dz =", "Note that only `neighbor_list_fn(R, neighbor_list)` can be `jit` since it", "each particle is guarenteed # to get a cell id", "box_size, cell_size)) return int(cell_capacity * buffer_size_multiplier) def _unflatten_cell_buffer(arr: Array, cells_per_side:", "particles to sets.\"\"\" from absl import logging from functools import", "CellList containing the partition. \"\"\" if util.is_array(box_size): box_size = onp.array(box_size)", "= 0 >>> for _ in range(20): >>> new_state, nbrs", "first element is a NeighborList containing the current neighbor list.", "jnp.reshape(arr, cells_per_side + (-1,) + arr.shape[1:]) def _shift_array(arr: onp.ndarray, dindex:", "each cell. Cells are enlarged so that they exactly fill", "cell_count) return filling def _is_variable_compatible_with_positions(R: Array) -> bool: if (util.is_array(R)", "dim)` array of particle positions. neighbor_list: An optional neighor list", "= _unflatten_cell_buffer(cell_id, cells_per_side, dim) for k, v in sorted_kwargs.items(): if", "kwargs that get threaded through the calculation of example positions.", "specific language governing permissions and # limitations under the License.", "since it keeps array shapes fixed. \"\"\" is_format_valid(format) box_size =", "'NeighborList'], 'NeighborList'] = dataclasses.static_field() def update(self, R, **kwargs): return self.update_fn(R,", "Generator, Union import math from operator import mul import numpy", "function updates the neighbor list, otherwise it allocates a new", "If neighbor_list is None then the function will construct a", "manually or it can be estimated automatically from a set", "def neighbor_list_mask(neighbor: NeighborList, mask_self: bool=False) -> Array: \"\"\"Compute a mask", "list only supports 2d or 3d.') def cell_list(box_size: Box, minimum_cell_size:", "return NeighborListFns(lambda R, extra_capacity=0, **kwargs: neighbor_list_fn(R, extra_capacity=extra_capacity, **kwargs), lambda R,", "lax.scatter call. To do # this we first sort particles", "return jnp.stack((receiver_idx[:-1], sender_idx[:-1])), max_occupancy def neighbor_list_fn(R: Array, neighbor_list: Optional[NeighborList]=None, extra_capacity:", "their true id whereas particles empty slots have id =", "static shape requirements). To deal with this, our `neighbor_list` returns", "R, **kwargs): N, dim = R.shape R = cl.position_buffer idx", "0) elif dim == 3: return vmap(vmap(vmap(f, 0, 0), 0,", "whereas particles empty slots have id = N. # Then", "neighbor list. cell_list_fn: A static python callable that is used", "for x in cells_per_side[::-1]]) elif util.is_array(cells_per_side) and len(cells_per_side.shape) == 2:", "class NeighborList(object): \"\"\"A struct containing the state of a Neighbor", "state of a Neighbor List. Attributes: idx: For an N", "capacity of the neighbor list must scale with the highest", "def to_dense(neighbor: NeighborList) -> Array: \"\"\"Converts a sparse neighbor list", "bool: if (util.is_array(R) and len(R.shape) == 2 and jnp.issubdtype(R.dtype, jnp.floating)):", "jnp.reshape(cell_value, (-1,) + cell_value.shape[-2:]) return ops.index_update(value, scatter_indices, cell_value) # NOTE(schsam):", "box_size, minimum_cell_size) hash_multipliers = _compute_hash_constants(dim, cells_per_side) particle_index = jnp.array(R /", "# TODO(schsam): We might want to do something more sophisticated", "# you may not use this file except in compliance", "util.i64 Box = space.Box DisplacementOrMetricFn = space.DisplacementOrMetricFn MetricFn = space.MetricFn", "to be their own neighbors. fractional_coordinates: An optional boolean. Specifies", "shape S + [spatial_dimension]. id_buffer: An ndarray of int32 particle", "dataclasses.static_field() def __call__(self, R: Array, neighbor_list: Optional[NeighborList]=None, extra_capacity: int=0, **kwargs)", "cell_idx, idx) return neighbor_idx[:-1, :, 0] @jit def mask_self_fn(idx): self_mask", "be 2 or 3. Found {}'.format(dim)) neighborhood_tile_count = 3 **", "is provided then the function updates the neighbor list, otherwise", "grid spacing in each ' 'dimension.')) cell_count = reduce(mul, flat_cells_per_side,", "grid, copy it to an array of shape # [N", "= util.f64 i32 = util.i32 i64 = util.i64 Box =", "if len(box_size.shape) == 1: box_size = jnp.reshape(box_size, (1, -1)) if", "Then when we copy data back from the grid, copy", "version of JAX MD. ' 'Using `neighbor_fn.allocate` and `neighbor_fn.update` '", "= jnp.where(mask, cumsum - 1, idx.shape[1] - 1) p_index =", "is_sparse(format): idx, occupancy = prune_neighbor_list_sparse(R, idx, **kwargs) else: idx, occupancy", "sparse neighbor lists to dense ones.') receivers, senders = neighbor.idx", "or (util.is_array(cells_per_side) and not cells_per_side.shape)): cells_per_side = (int(cells_per_side),) * dim", "will likely form the groundwork for parallelizing simulations over different", "empty slots have id = N. # Then when we", "* hash_multipliers, axis=1) # Copy the particle data into the", "the buffer sizes will have to be adjusted. This partitioning", "3.) and not disable_cell_list @jit def candidate_fn(R, **kwargs): return jnp.broadcast_to(jnp.reshape(jnp.arange(R.shape[0]),", "either NeighborListFormat.Sparse or ' 'NeighborListFormat.OrderedSparse.') receivers, senders = neighbor.idx N", "[spatial_dim] specifying the box size in each spatial dimension. r_cutoff:", "list ought to be updated. did_buffer_overflow: A boolean that starts", "cl.position_buffer idx = cl.id_buffer cell_idx = [idx] for dindex in", "lists must balance the need to be jit compatable with", "int) or isinstance(cells_per_side, float) or (util.is_array(cells_per_side) and not cells_per_side.shape)): cells_per_side", "the License. \"\"\"Code to transform functions on individual tuples of", "of NeighorListFormat' f' found {format}.')) @dataclasses.dataclass class NeighborList(object): \"\"\"A struct", "partitions positions, `R`, and side data specified by kwargs into", "a function `neighbor_list_fn(R, neighbor_list=None)` that will update the neighbor list.", "the fact that under a jit the maximum number of", "be incorrect and the simulation needs to be rerun using", "_mask = neighbor_list_mask(neighbor) if mask is not None: _mask =", "NeighborListFormat): if not format in list(NeighborListFormat): raise ValueError(( 'Neighbor list", "and then truncate it to an array of shape #", "data into the grid. Here we use a trick to", "License. \"\"\"Code to transform functions on individual tuples of particles", "import numpy as onp from jax import lax from jax", "of shape [spatial_dim] specifying the box size in each spatial", "jnp.all(cell_size < box_size / 3.) and not disable_cell_list @jit def", "float, cell_capacity_or_example_R: Union[int, Array], buffer_size_multiplier: float=1.1 ) -> Callable[[Array], CellList]:", "= R.shape[1] _cell_capacity = cell_capacity + extra_capacity if dim !=", "neighbor_fn.allocate(R) >>> state = init_fn(random.PRNGKey(0), R, neighbor_idx=nbrs.idx) >>> >>> def", "under the Apache License, Version 2.0 (the \"License\"); # you", "if the distribution of points changes significantly it is likely", "util.is_array(cells_per_side) and len(cells_per_side.shape) == 1: cells_per_side = tuple([int(x) for x", "A boolean that starts out False. If there are ever", "grid_id where grid_id # is a flat list that repeats", "Attributes: R: An `(N, dim)` array of particle positions. neighbor_list:", "dim: int) -> Callable: if dim == 2: return vmap(vmap(f,", "Found \"{}\" with shape {}'.format(k, v.shape))) kwarg_shape = v.shape[1:] if", "dense_idx Dense = NeighborListFormat.Dense Sparse = NeighborListFormat.Sparse OrderedSparse = NeighborListFormat.OrderedSparse", "points changes significantly it is likely the buffer the buffer", "per-particle (an ndarray with shape ' '(R.shape[0], ...)). Found \"{}\"", "efficient than just # computing everything. neighbor_idx = jnp.zeros((N +", "whose format is the same as `Sparse` where only bonds", "boolean. Determines whether points can consider themselves to be their", "if (isinstance(cells_per_side, int) or isinstance(cells_per_side, float) or (util.is_array(cells_per_side) and not", "test. It seems easier to design around this empty_data_value #", "arr[:, :1]), axis=1) elif dy > 0: arr = jnp.concatenate((arr[:,", "Args: neighbor: A neighbor list that we will convert to", "lists to dense ones.') receivers, senders = neighbor.idx mask =", "import Enum from typing import Any, Callable, Optional, Dict, Tuple,", "ops.index_update(cell_kwargs[k], sorted_cell_id, v) cell_kwargs[k] = _unflatten_cell_buffer( cell_kwargs[k], cells_per_side, dim) return", "of the neighbor list; see the NeighborListFormat enum for details", "kwarg_shape = v.shape[1:] if v.ndim > 1 else (1,) cell_kwargs[k]", "be at least 3x the size of the grid spacing", "returns a `NeighborListFns` object that contains two functions: 1) `neighbor_fn.allocate`", "that shapes be statically specified, we allocate fixed sized buffers", "a cell list. Since XLA requires that shapes be statically", "cumsum = jnp.cumsum(mask, axis=1) index = jnp.where(mask, cumsum - 1,", "are # fewer than cell_capacity particles per cell, each particle", "and `neighbor_fn.update` ' 'is preferred.') if neighbor_list is None: return", "cumsum = jnp.cumsum(_mask) index = jnp.where(_mask, cumsum - 1, len(receivers))", "to sets.\"\"\" from absl import logging from functools import reduce,", "the maximum in the example positions. disable_cell_list: An optional boolean.", "cl = cell_list_fn(R) idx = cell_list_candidate_fn(cl, R, **kwargs) else: idx", "'to estimate a cell capacity. Found {}.'.format(type(cell_capacity)) ) raise ValueError(msg)", "else: idx, occupancy = prune_neighbor_list_dense(R, idx, **kwargs) if max_occupancy is", "must scale with the highest connectivity neighbor. Sparse: A sparse", "`jit` since it keeps array shapes fixed. \"\"\" is_format_valid(format) box_size", "points {x_i \\in R^d} with associated data {k_i \\in R^m}", "that they exactly fill the box. cell_capacity_or_example_R: Either an integer", "results of the simulation will be incorrect and the simulation", "(1,)) cell_kwargs[k] = ops.index_update(cell_kwargs[k], sorted_cell_id, v) cell_kwargs[k] = _unflatten_cell_buffer( cell_kwargs[k],", "for fluctuations in the maximum cell occupancy. Returns: A function", "The format of the neighbor list; see the NeighborListFormat enum", "is not Sparse: raise ValueError('Can only convert sparse neighbor lists", "neighbor list will need to be reallocated. Here is a", "[N + 1, output_dimension] and then truncate it to an", "design around this empty_data_value # for now and revisit the", "indicate that there was a buffer overflow. If this happens,", "the simulation needs to be rerun using a larger buffer.", "occupancy test. It seems easier to design around this empty_data_value", "idx = cl.id_buffer cell_idx = [idx] for dindex in _neighboring_cells(dim):", "cell_list_fn(R) idx = cell_list_candidate_fn(cl, R, **kwargs) else: idx = candidate_fn(R,", "will need to be reallocated. Here is a typical example", "NeighborListFormat.Sparse or format is NeighborListFormat.OrderedSparse) def is_format_valid(format: NeighborListFormat): if not", "do a mask for species that will include # an", "partial(neighbor_fn, max_occupancy=nbrs.max_occupancy) d = partial(metric_sq, **kwargs) d = vmap(d) return", "list to jraph format. ' 'Please use either NeighborListFormat.Sparse or", "List @dataclasses.dataclass class CellList: \"\"\"Stores the spatial partition of a", "= R.shape[0] padding = max_occupancy - occupancy if max_occupancy >", "cannot be compiled, since it uses the values of positions", "prune_neighbor_list_dense(R, idx, **kwargs) if max_occupancy is None: _extra_capacity = (extra_capacity", "compute_fn as well? raise ValueError( 'Cell list spatial dimension must", "square matrix of shape `(N, max_neighbors_per_atom)`. Here the capacity of", "__iter__(self): return iter((self.allocate, self.update)) NeighborFn = Callable[[Array, Optional[NeighborList], Optional[int]], NeighborList]", "sorted_cell_id, sorted_R) sorted_id = jnp.reshape(sorted_id, (N, 1)) cell_id = ops.index_update(", "or metric was provided.\"\"\" for dim in range(1, 4): try:", "a displacement or metric was provided.\"\"\" for dim in range(1,", "R.shape[1] _cell_capacity = cell_capacity + extra_capacity if dim != 2", "type(v)))) if v.shape[0] != R.shape[0]: raise ValueError( ('Data must be", "A dense neighbor list where the ids are a square", "+ extra_capacity if dim != 2 and dim != 3:", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "must either be a scalar or a vector.') else: cell_count", "mask on the edges. Returns: A `jraph.GraphsTuple` that contains the", "candidate_fn(R, **kwargs): return jnp.broadcast_to(jnp.reshape(jnp.arange(R.shape[0]), (1, R.shape[0])), (R.shape[0], R.shape[0])) @jit def", "& (idx < N) out_idx = N * jnp.ones(idx.shape, jnp.int32)", "nodes=None, edges=None, receivers=receivers, senders=senders, globals=None, n_node=jnp.array([N, 1]), n_edge=jnp.array([jnp.sum(_mask), jnp.sum(~_mask)]), )", "** 5 cell_kwargs = {} for k, v in kwargs.items():", "range(spatial_dimension)]], dtype=jnp.int64) elif cells_per_side.size == spatial_dimension: one = jnp.array([[1]], dtype=jnp.int32)", "cells_per_side[:, :-1]), axis=1) return jnp.array(jnp.cumprod(cells_per_side), dtype=jnp.int64) else: raise ValueError() def", "will update the neighbor list. If neighbor_list is None then", "p_index = jnp.arange(idx.shape[0])[:, None] out_idx = out_idx.at[p_index, index].set(idx) max_occupancy =", "self_mask return mask def to_jraph(neighbor: NeighborList, mask: Array=None) -> jraph.GraphsTuple:", "try: R = ShapedArray((dim,), f32) dR_or_dr = eval_shape(displacement_or_metric, R, R,", "id that is unique. sort_map = jnp.argsort(hashes) sorted_R = R[sort_map]", "shape, S, where * `S = [cell_count_x, cell_count_y, cell_capacity]` *", "v = jnp.reshape(v, v.shape + (1,)) cell_kwargs[k] = ops.index_update(cell_kwargs[k], sorted_cell_id,", "particle_hash, cell_count) return filling def _is_variable_compatible_with_positions(R: Array) -> bool: if", "return jnp.where(self_mask, idx.shape[0], idx) @jit def prune_neighbor_list_dense(R, idx, **kwargs): d", "spatial_dimension] that is used to estimate the cell_capacity. buffer_size_multiplier: A", "0: arr = jnp.concatenate((arr[:, :, -1:], arr[:, :, :-1]), axis=2)", "a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 #", "a cell list. See cell_list(...) for details on the construction", "id_buffer: An ndarray of int32 particle ids of shape S.", "data spatially. A simple partitioning that can be implemented efficiently", "with ' 'type {}'.format(k, type(v)))) if v.shape[0] != R.shape[0]: raise", "(idx < N) out_idx = N * jnp.ones(idx.shape, jnp.int32) cumsum", "0), 0, 0) raise ValueError('Cell list only supports 2d or", "neighbor lists. Attributes: allocate: A function to allocate a new", "convenience `update` member function. Note that allocation of a new", "multiplier that multiplies the estimated cell capacity to allow for", "capacity to allow for fluctuations in the maximum cell occupancy.", "ids. Cannot be JIT.\"\"\" if neighbor.format is not Sparse: raise", "lambda Ra, Rb, **kwargs: space.square_distance( displacement_or_metric(Ra, Rb, **kwargs)) except TypeError:", "box_size, minimum_cell_size) hash_multipliers = _compute_hash_constants(dim, cells_per_side) # Create cell list", "jax.interpreters import partial_eval as pe import jax.numpy as jnp from", "state = new_state >>> step += 1 Args: displacement: A", "= prune_neighbor_list_dense(R, idx, **kwargs) if max_occupancy is None: _extra_capacity =", ") -> Callable[[Array], CellList]: r\"\"\"Returns a function that partitions point", "cell capacity or a set of positions that will be", "number of neighbors (along with additional space specified by the", "raise ValueError( 'Canonicalize displacement not implemented for spatial dimension larger'", "# least expose this constant. spatial_dim = R.shape[-1] cell_capacity =", "box_size = f32(box_size) cutoff = r_cutoff + dr_threshold cutoff_sq =", "box_size: Box, minimum_cell_size: float) -> Tuple[Box, Array, Array, int]: \"\"\"Compute", "S. Note that empty slots are specified by id =", "set of points {x_i \\in R^d} with associated data {k_i", "class CellList: \"\"\"Stores the spatial partition of a system into", "particle_hash = jnp.sum(particle_index * hash_multipliers, axis=1) filling = ops.segment_sum(jnp.ones_like(particle_hash), particle_hash,", "repeats 0, .., cell_capacity. So long as there are #", "additionally have a convenience `update` member function. Note that allocation", "and a new neighbor list will need to be reallocated.", "new neighbor list will need to be reallocated. Here is", "from operator import mul import numpy as onp from jax", "function used to update the neighbor list. \"\"\" idx: Array", "r_cutoff: A scalar specifying the neighborhood radius. dr_threshold: A scalar", "member of NeighorListFormat' f' found {format}.')) @dataclasses.dataclass class NeighborList(object): \"\"\"A", "used ' 'to estimate a cell capacity. Found {}.'.format(type(cell_capacity)) )", "mask & (receiver_idx < sender_idx) out_idx = N * jnp.ones(receiver_idx.shape,", "of positions. Note, if the distribution of points changes significantly", "dr_threshold: float, capacity_multiplier: float=1.25, disable_cell_list: bool=False, mask_self: bool=True, fractional_coordinates: bool=False,", "in range(20): >>> new_state, nbrs = lax.fori_loop(0, 100, body_fn, (state,", "to allow for fluctuations in the maximum cell occupancy. Returns:", "None: _extra_capacity = (extra_capacity if not is_sparse(format) else N *", "return True return False def _compute_hash_constants(spatial_dimension: int, cells_per_side: Array) ->", "/ specification. Cell list buffers all have a common shape,", "= R.shape[0] neigh_R = R[idx] dR = d(R, neigh_R) mask", "we use a trick to allow us to # copy", "jax.numpy as jnp from jax_md import quantity, space, dataclasses, util", "= R_and_overflow N = R.shape[0] if cell_list_fn is not None:", "which the box_size would not be accurately represented by an", "mul import numpy as onp from jax import lax from", "The second element contains a function `neighbor_list_fn(R, neighbor_list=None)` that will", "extra_capacity: int=0, **kwargs) -> CellList: N = R.shape[0] dim =", "can be estimated automatically from a set of positions. Note,", "= util.f32 f64 = util.f64 i32 = util.i32 i64 =", "def _shift_array(arr: onp.ndarray, dindex: Array) -> Array: if len(dindex) ==", "cumsum - 1, len(receivers)) ordered = N * jnp.ones((len(receivers) +", "that is larger than # needed since the idx buffer", "neighbor list where the ids are a rectangular matrix of", "to a `jraph.GraphsTuple`. As in jraph, padding here is accomplished", "a rectangular matrix of shape `(2, max_neighbors)` specifying the start", "(-1,)) for cells in flat_cells_per_side: if cells < 3: raise", "def __call__(self, R: Array, neighbor_list: Optional[NeighborList]=None, extra_capacity: int=0, **kwargs) ->", "dim elif util.is_array(cells_per_side) and len(cells_per_side.shape) == 1: cells_per_side = tuple([int(x)", "on the construction / specification. Cell list buffers all have", "the neighborhood radius. dr_threshold: A scalar specifying the maximum distance", "permissions and # limitations under the License. \"\"\"Code to transform", "return lax.cond( jnp.any(d(R, nbrs.reference_position) > threshold_sq), (R, nbrs.did_buffer_overflow), neighbor_fn, nbrs,", "less efficient. minimum_cell_size: A float specifying the minimum side length", "dy, dz = dindex if dx < 0: arr =", "(N, 1)) cell_id = ops.index_update( cell_id, sorted_cell_id, sorted_id) cell_R =", "in flat_cells_per_side: if cells < 3: raise ValueError( ('Box must", "slots have id = N. # Then when we copy", "= _unflatten_cell_buffer( cell_kwargs[k], cells_per_side, dim) return CellList(cell_R, cell_id, cell_kwargs) #", "needed since the idx buffer inherets its size from the", "N * jnp.ones((N * max_count,), jnp.int32) dense_idx = dense_idx.at[hashes].set(receivers).reshape((N, max_count))", "arr[:-1])) if dy < 0: arr = jnp.concatenate((arr[:, 1:], arr[:,", "NeighborListFormat=NeighborListFormat.Dense, **static_kwargs) -> NeighborFn: \"\"\"Returns a function that builds a", "filling def _is_variable_compatible_with_positions(R: Array) -> bool: if (util.is_array(R) and len(R.shape)", "Apache License, Version 2.0 (the \"License\"); # you may not", "int=0, **kwargs) -> CellList: N = R.shape[0] dim = R.shape[1]", "there are # fewer than cell_capacity particles per cell, each", "either express or implied. # See the License for the", "elif dy > 0: arr = jnp.concatenate((arr[:, -1:], arr[:, :-1]),", "convention that particles that are successfully, # copied have their", "License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "for the case where the boundaries are periodic. If this", "jnp.reshape(jnp.arange(N), (N, 1)) mask = mask & self_mask return mask", "'Canonicalize displacement not implemented for spatial dimension larger' 'than 4.')", "neighborhood radius. dr_threshold: A scalar specifying the maximum distance particles", "box_size.ndim == 1 or box_size.ndim == 2: assert box_size.size ==", "something more sophisticated here or at # least expose this", "in list(NeighborListFormat): raise ValueError(( 'Neighbor list format must be a", "# computing everything. neighbor_idx = jnp.zeros((N + 1,) + cell_idx.shape[-2:],", "(with fixed capacity) if any particle has moved more than", "size in each spatial dimension. r_cutoff: A scalar specifying the", "cell_value = jnp.reshape(cell_value, (-1,) + cell_value.shape[-2:]) return ops.index_update(value, scatter_indices, cell_value)", "or an array of shape [spatial_dim] specifying the box size", "depricated code path to create / update neighbor ' 'lists.", "space.DisplacementOrMetricFn MetricFn = space.MetricFn # Cell List @dataclasses.dataclass class CellList:", "= int(R.shape[1]) box_size, cell_size, cells_per_side, cell_count = \\ _cell_dimensions(dim, box_size,", "be implemented efficiently within XLA is a dense partition into", "Array: \"\"\"Compute a mask for neighbor list.\"\"\" if is_sparse(neighbor.format): mask", "DisplacementOrMetricFn, box_size: Box, r_cutoff: float, dr_threshold: float, capacity_multiplier: float=1.25, disable_cell_list:", "sparse neighbor list to a `jraph.GraphsTuple`. As in jraph, padding", "= 10 ** 5 cell_kwargs = {} for k, v", "constant. spatial_dim = R.shape[-1] cell_capacity = onp.max(count_cell_filling(R, box_size, cell_size)) return", "jit compiled; if the neighbor list capacity is not sufficient", "constructed using only distances. This can be useful for debugging", "will be set to 1.0 and the cell size used", "\"\"\"Checks whether or not a displacement or metric was provided.\"\"\"", "to update a neighbor list given a new set of", "empty slots. mask_id = jnp.ones((N,), jnp.int64) * N cell_R =", "the neighbor list. \"\"\" if not is_sparse(neighbor.format): raise ValueError('Cannot convert", "occupancy if max_occupancy > occupancy: idx = jnp.concatenate( [idx, N", "len(box_size.shape) == 1: box_size = jnp.reshape(box_size, (1, -1)) if util.is_array(minimum_cell_size):", "filling = ops.segment_sum(jnp.ones_like(particle_hash), particle_hash, cell_count) return filling def _is_variable_compatible_with_positions(R: Array)", "cells_per_side, dim) return CellList(cell_R, cell_id, cell_kwargs) # pytype: disable=wrong-arg-count return", "jnp.cumsum(_mask) index = jnp.where(_mask, cumsum - 1, len(receivers)) ordered =", "R[idx] dR = d(R, neigh_R) mask = (dR < cutoff_sq)", "(1,) cell_kwargs[k] = empty_kwarg_value * jnp.ones( (cell_count * _cell_capacity,) +", "buffer inherets its size from the cell-list. In # three-dimensions", "A `jraph.GraphsTuple` that contains the topology of the neighbor list.", "_cell_capacity, dim), dtype=R.dtype) cell_id = N * jnp.ones((cell_count * _cell_capacity,", "to jraph format. ' 'Please use either NeighborListFormat.Sparse or '", "build_cells(R: Array, extra_capacity: int=0, **kwargs) -> CellList: N = R.shape[0]", "= space.Box DisplacementOrMetricFn = space.DisplacementOrMetricFn MetricFn = space.MetricFn # Cell", "a single node. Args: neighbor: A neighbor list that we", "spatial partition.\"\"\" dim = int(R.shape[1]) box_size, cell_size, cells_per_side, cell_count =", "# an occupancy test. It seems easier to design around", "box_size.dtype == jnp.int64)): box_size = float(box_size) cells_per_side = onp.floor(box_size /", "Enum from typing import Any, Callable, Optional, Dict, Tuple, Generator,", "of JAX MD. ' 'Using `neighbor_fn.allocate` and `neighbor_fn.update` ' 'is", "= jnp.concatenate(cell_idx, axis=-2) cell_idx = cell_idx[..., jnp.newaxis, :, :] cell_idx", "in onp.ndindex(*([3] * dimension)): yield onp.array(dindex, dtype=jnp.int64) - 1 def", "minimum_cell_size, buffer_size_multiplier) elif not isinstance(cell_capacity, int): msg = ( 'cell_capacity_or_example_positions", "Array = util.Array f32 = util.f32 f64 = util.f64 i32", "idx = idx[:, :max_occupancy] update_fn = (neighbor_list_fn if neighbor_list is", "list. \"\"\" logging.warning('Using a depricated code path to create /", "format: The format of the neighbor list; see the NeighborListFormat", "size number of particles that can be stored in each", "Must be sparse. mask: An optional mask on the edges.", "\"\"\"A struct containing the state of a Neighbor List. Attributes:", "left as False. mask_self: An optional boolean. Determines whether points", "kwarg_buffers: Dict[str, Array] def _cell_dimensions(spatial_dimension: int, box_size: Box, minimum_cell_size: float)", "NeighborListFormat.OrderedSparse) def is_format_valid(format: NeighborListFormat): if not format in list(NeighborListFormat): raise", "bool=False, mask_self: bool=True, fractional_coordinates: bool=False, format: NeighborListFormat=NeighborListFormat.Dense, **static_kwargs) -> NeighborFn:", "be reallocated. Here is a typical example of a simulation", "update: Callable[[Array, NeighborList], NeighborList] = dataclasses.static_field() def __call__(self, R: Array,", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "NeighborList] = dataclasses.static_field() def __call__(self, R: Array, neighbor_list: Optional[NeighborList]=None, extra_capacity:", "positions and a new neighbor list. \"\"\" allocate: Callable[..., NeighborList]", "empty_kwarg_value = 10 ** 5 cell_kwargs = {} for k,", "cell_idx = jnp.concatenate(cell_idx, axis=-2) cell_idx = cell_idx[..., jnp.newaxis, :, :]", "then truncate it to an array of shape # [N,", "be sparse. mask: An optional mask on the edges. Returns:", "arr def _vectorize(f: Callable, dim: int) -> Callable: if dim", "using a single lax.scatter call. To do # this we", "be `jit` since it keeps array shapes fixed. \"\"\" is_format_valid(format)", "`S = [cell_count_x, cell_count_y, cell_capacity]` * `S = [cell_count_x, cell_count_y,", "topology of the neighbor list. \"\"\" if not is_sparse(neighbor.format): raise", "* N cell_R = jnp.zeros((cell_count * _cell_capacity, dim), dtype=R.dtype) cell_id", "they exactly fill the box. cell_capacity_or_example_R: Either an integer specifying", "of shape S + [...]. This contains side data placed", "inherets its size from the cell-list. In # three-dimensions this", "idx = candidate_fn(R, **kwargs) if mask_self: idx = mask_self_fn(idx) if", "return neighbor_fn((R, False)) else: cell_list_fn = nbrs.cell_list_fn neighbor_fn = partial(neighbor_fn,", "`True` and a new neighbor list will need to be", "into the cell list. \"\"\" position_buffer: Array id_buffer: Array kwarg_buffers:", "jnp.where(mask, cumsum - 1, idx.shape[1] - 1) p_index = jnp.arange(idx.shape[0])[:,", "' 'dimension.')) cell_count = reduce(mul, flat_cells_per_side, 1) elif box_size.ndim ==", "a member of NeighorListFormat' f' found {format}.')) @dataclasses.dataclass class NeighborList(object):", "truncate it to an array of shape # [N, output_dimension]", "cumsum = jnp.cumsum(mask) index = jnp.where(mask, cumsum - 1, len(receiver_idx)", "for dindex in _neighboring_cells(dim): if onp.all(dindex == 0): continue cell_idx", "well? raise ValueError( 'Cell list spatial dimension must be 2", "return neighbor_idx[:-1, :, 0] @jit def mask_self_fn(idx): self_mask = idx", "apply_fn(state, neighbor_idx=nbrs.idx) >>> return state, nbrs >>> >>> step =", "x in cells_per_side[::-1]]) elif util.is_array(cells_per_side) and len(cells_per_side.shape) == 2: cells_per_side", "Array kwarg_buffers: Dict[str, Array] def _cell_dimensions(spatial_dimension: int, box_size: Box, minimum_cell_size:", "hash * cell_capacity + grid_id where grid_id # is a", "+ kwarg_shape, v.dtype) indices = jnp.array(R / cell_size, dtype=i32) hashes", "with shape S + [spatial_dimension]. id_buffer: An ndarray of int32", "[N, output_dimension] which ignores the empty slots. mask_id = jnp.ones((N,),", "jnp.ones((idx.shape[0], padding), dtype=idx.dtype)], axis=1) idx = idx[:, :max_occupancy] update_fn =", "used to update the neighbor list. \"\"\" idx: Array reference_position:", "a convenience `update` member function. Note that allocation of a", "the format of the neighbor list. cell_list_fn: A static python", "= jnp.broadcast_to(jnp.arange(N)[:, None], idx.shape) sender_idx = jnp.reshape(sender_idx, (-1,)) receiver_idx =", "particle ids of shape S. Note that empty slots are", "cells_per_side, cell_count = \\ _cell_dimensions(dim, box_size, minimum_cell_size) hash_multipliers = _compute_hash_constants(dim,", "1, output_dimension] and then truncate it to an array of", "= N * jnp.ones((len(receivers) + 1,), jnp.int32) receivers = ordered.at[index].set(receivers)[:-1]", "jnp.int32) receivers = ordered.at[index].set(receivers)[:-1] senders = ordered.at[index].set(senders)[:-1] mask = receivers", "float(box_size) # NOTE(schsam): Should we auto-cast based on box_size? I", "Array, box_size: Box, minimum_cell_size: float) -> Array: \"\"\"Counts the number", "...)). Found \"{}\" with shape {}'.format(k, v.shape))) kwarg_shape = v.shape[1:]", "shapes. update: A function to update a neighbor list given", "**kwargs) -> CellList: N = R.shape[0] dim = R.shape[1] _cell_capacity", "`did_buffer_overflow` bit will be set to `True` and a new", "only `neighbor_list_fn(R, neighbor_list)` can be `jit` since it keeps array", "graph with a single node. Args: neighbor: A neighbor list", "neighbor list is constructed using only distances. This can be", "def is_sparse(format: NeighborListFormat) -> bool: return (format is NeighborListFormat.Sparse or", "list where the ids are a rectangular matrix of shape", "to allow us to # copy into all cells simultaneously", "exact_init_fn, exact_apply_fn = simulate.nve(exact_energy_fn, shift, 1e-3) >>> >>> nbrs =", "if the neighbor list capacity is not sufficient to store", "1]^d. If this is set to True then the box_size", "less efficient than just # computing everything. neighbor_idx = jnp.zeros((N", "isinstance(cells_per_side, float) or (util.is_array(cells_per_side) and not cells_per_side.shape)): cells_per_side = (int(cells_per_side),)", "return jnp.array([[cells_per_side ** d for d in range(spatial_dimension)]], dtype=jnp.int64) elif", "is None else neighbor_list.update_fn) return NeighborList( idx, R, jnp.logical_or(overflow, (max_occupancy", "of int32 particle ids of shape S. Note that empty", "= jnp.sum(particle_index * hash_multipliers, axis=1) filling = ops.segment_sum(jnp.ones_like(particle_hash), particle_hash, cell_count)", "= util.i64 Box = space.Box DisplacementOrMetricFn = space.DisplacementOrMetricFn MetricFn =", "> 1 else (1,) cell_kwargs[k] = empty_kwarg_value * jnp.ones( (cell_count", "= ordered.at[index].set(senders)[:-1] mask = receivers < N return jraph.GraphsTuple( nodes=None,", "Found {}'.format(dim)) neighborhood_tile_count = 3 ** dim _, cell_size, cells_per_side,", "simulate.nve(exact_energy_fn, shift, 1e-3) >>> >>> nbrs = neighbor_fn.allocate(R) >>> state", "return jraph.GraphsTuple( nodes=None, edges=None, receivers=receivers, senders=senders, globals=None, n_node=jnp.array([N, 1]), n_edge=jnp.array([jnp.sum(_mask),", "extra_capacity if dim != 2 and dim != 3: #", "state = init_fn(random.PRNGKey(0), R, neighbor_idx=nbrs.idx) >>> >>> def body_fn(i, state):", "function will construct a new neighbor list whose capacity is", "arr = jnp.concatenate((arr[1:], arr[:1])) elif dx > 0: arr =", "into all cells simultaneously using a single lax.scatter call. To", "total number of cells in a box.\"\"\" if isinstance(box_size, int)", "`update` member function. Note that allocation of a new neighbor", "neighbor list. capacity_multiplier: A floating point scalar specifying the fractional", "A neighbor list that we will convert to the jraph", "= cl.id_buffer cell_idx = [idx] for dindex in _neighboring_cells(dim): if", "d = space.map_neighbor(d) N = R.shape[0] neigh_R = R[idx] dR", "maximum number of neighbors cannot change (owing to static shape", "A floating point scalar specifying the fractional increase in maximum", "maximum neighborhood occupancy we allocate compared with the maximum in", "len(receivers)) ordered = N * jnp.ones((len(receivers) + 1,), jnp.int32) receivers", "preferred.') if neighbor_list is None: return self.allocate(R, extra_capacity, **kwargs) return", "else None) return neighbor_fn((R, False)) else: cell_list_fn = nbrs.cell_list_fn neighbor_fn", "us to # copy into all cells simultaneously using a", "senders = senders[mask] N = len(neighbor.reference_position) count = ops.segment_sum(jnp.ones(len(receivers), jnp.int32),", "loop with neighbor lists: >>> init_fn, apply_fn = simulate.nve(energy_fn, shift,", "the maximum cell occupancy. Returns: A function `cell_list_fn(R, **kwargs)` that", "enum listing the different neighbor list formats. Attributes: Dense: A", "and a new neighbor list. \"\"\" allocate: Callable[..., NeighborList] =", "= dataclasses.static_field() cell_list_fn: Callable[[Array], CellList] = dataclasses.static_field() update_fn: Callable[[Array, 'NeighborList'],", "in each cell or an ndarray of positions of shape", "# NOTE(schsam): We use the convention that particles that are", "in the maximum cell occupancy. Returns: A function `cell_list_fn(R, **kwargs)`", "matrix of shape `(N, max_neighbors_per_atom)`. Here the capacity of the", "list.\"\"\" if is_sparse(neighbor.format): mask = neighbor.idx[0] < len(neighbor.reference_position) if mask_self:", "the cell_capacity. buffer_size_multiplier: A floating point multiplier that multiplies the", "include # an occupancy test. It seems easier to design", "a cell capacity. Found {}.'.format(type(cell_capacity)) ) raise ValueError(msg) def build_cells(R:", "cell_size, cells_per_side, int(cell_count) def count_cell_filling(R: Array, box_size: Box, minimum_cell_size: float)", "# NOTE(schsam): Currently, this makes a verlet list that is", "ordered.at[index].set(receivers)[:-1] senders = ordered.at[index].set(senders)[:-1] mask = receivers < N return", "neighbor list; see the NeighborListFormat enum for details about the", "# TODO return jnp.reshape(arr, cells_per_side + (-1,) + arr.shape[1:]) def", "N = len(neighbor.reference_position) self_mask = neighbor.idx != jnp.reshape(jnp.arange(N), (N, 1))", "by the `capacity_multiplier`). Updating the neighbor list can be jit", "_cell_capacity) sorted_cell_id = sorted_hash * _cell_capacity + sorted_cell_id cell_R =", "-> NeighborFn: \"\"\"Returns a function that builds a list neighbors", "capacity or a set of positions that will be used", "-> int: # TODO(schsam): We might want to do something", "padding), dtype=idx.dtype)], axis=1) idx = idx[:, :max_occupancy] update_fn = (neighbor_list_fn", "if cell_list_fn is not None: cl = cell_list_fn(R) idx =", "for _ in range(20): >>> new_state, nbrs = lax.fori_loop(0, 100,", "int32 particle ids of shape S. Note that empty slots", "neighbor list, otherwise it allocates a new neighbor list. extra_capacity:", ":, -1:], arr[:, :, :-1]), axis=2) return arr def _vectorize(f:", "def cell_list_candidate_fn(cl, R, **kwargs): N, dim = R.shape R =", "as onp from jax import lax from jax import ops", "Array id_buffer: Array kwarg_buffers: Dict[str, Array] def _cell_dimensions(spatial_dimension: int, box_size:", "can be stored in each cell or an ndarray of", "larger' 'than 4.') class NeighborListFormat(Enum): \"\"\"An enum listing the different", "is the same as `Sparse` where only bonds with i", "requirements). To deal with this, our `neighbor_list` returns a `NeighborListFns`", "be left as False. mask_self: An optional boolean. Determines whether", "than dr_threshold / 2. Note that only `neighbor_list_fn(R, neighbor_list)` can", "_neighboring_cells(dim): if onp.all(dindex == 0): continue cell_idx += [_shift_array(idx, dindex)]", "idx, **kwargs) if max_occupancy is None: _extra_capacity = (extra_capacity if", "= dataclasses.static_field() update: Callable[[Array, NeighborList], NeighborList] = dataclasses.static_field() def __call__(self,", "and len(cells_per_side.shape) == 2: cells_per_side = tuple([int(x) for x in", "yield onp.array(dindex, dtype=jnp.int64) - 1 def _estimate_cell_capacity(R: Array, box_size: Box,", "== 1: v = jnp.reshape(v, v.shape + (1,)) cell_kwargs[k] =", ">>> state, nbrs = state >>> nbrs = nbrs.update(state.position) >>>", "sorted_cell_id, sorted_id) cell_R = _unflatten_cell_buffer(cell_R, cells_per_side, dim) cell_id = _unflatten_cell_buffer(cell_id,", "sorted_cell_id = jnp.mod(lax.iota(jnp.int64, N), _cell_capacity) sorted_cell_id = sorted_hash * _cell_capacity", "list. Returns a CellList containing the partition. \"\"\" if util.is_array(box_size):", "= ops.segment_sum(jnp.ones_like(particle_hash), particle_hash, cell_count) return filling def _is_variable_compatible_with_positions(R: Array) ->", "space.Box DisplacementOrMetricFn = space.DisplacementOrMetricFn MetricFn = space.MetricFn # Cell List", "raise ValueError('Box must either be a scalar or a vector.')", "use this file except in compliance with the License. #", "__call__(self, R: Array, neighbor_list: Optional[NeighborList]=None, extra_capacity: int=0, **kwargs) -> NeighborList:", "jnp.zeros((cell_count * _cell_capacity, dim), dtype=R.dtype) cell_id = N * jnp.ones((cell_count", "or 3. Found {}'.format(dim)) neighborhood_tile_count = 3 ** dim _,", "Returns a CellList containing the partition. \"\"\" if util.is_array(box_size): box_size", "-> Array: \"\"\"Counts the number of particles per-cell in a", "minimum_cell_size: float, cell_capacity_or_example_R: Union[int, Array], buffer_size_multiplier: float=1.1 ) -> Callable[[Array],", "would not be accurately represented by an f32. if (isinstance(box_size,", "1e-3) >>> exact_init_fn, exact_apply_fn = simulate.nve(exact_energy_fn, shift, 1e-3) >>> >>>", "boundaries are periodic. If this is not the case, then", "== jnp.int64)): box_size = float(box_size) cells_per_side = onp.floor(box_size / minimum_cell_size)", "float, dr_threshold: float, capacity_multiplier: float=1.25, disable_cell_list: bool=False, mask_self: bool=True, fractional_coordinates:", "an N particle system this is an `[N, max_occupancy]` array", "** 2 else: return lambda Ra, Rb, **kwargs: space.square_distance( displacement_or_metric(Ra,", "dense partition into a uniform grid called a cell list.", "_cell_capacity, 1), dtype=i32) # It might be worth adding an", "have their true id whereas particles empty slots have id", "floating point multiplier that multiplies the estimated cell capacity to", "periodic. If this is not the case, then the current", "spacing in each ' 'dimension.')) cell_count = reduce(mul, flat_cells_per_side, 1)", "metric_sq = _displacement_or_metric_to_metric_sq(displacement_or_metric) cell_size = cutoff if fractional_coordinates: cell_size =", "points can consider themselves to be their own neighbors. fractional_coordinates:", "to decide whether the neighbor list ought to be updated.", "However, this seems possibly less efficient than just # computing", "return build_cells def _displacement_or_metric_to_metric_sq( displacement_or_metric: DisplacementOrMetricFn) -> MetricFn: \"\"\"Checks whether", "= onp.floor(box_size / minimum_cell_size) cell_size = box_size / cells_per_side cells_per_side", "that will include # an occupancy test. It seems easier", "import lax from jax import ops from jax import jit,", "cell_capacity = _estimate_cell_capacity( cell_capacity, box_size, minimum_cell_size, buffer_size_multiplier) elif not isinstance(cell_capacity,", "R[sort_map] sorted_hash = hashes[sort_map] sorted_id = particle_id[sort_map] sorted_kwargs = {}", "extra_capacity=extra_capacity, **kwargs), lambda R, nbrs, **kwargs: # pytype: disable=wrong-arg-count neighbor_list_fn(R,", "raise ValueError('Can only convert sparse neighbor lists to dense ones.')", "ValueError: continue raise ValueError( 'Canonicalize displacement not implemented for spatial", "issue if it comes up later. empty_kwarg_value = 10 **", "_cell_dimensions(dim, box_size, minimum_cell_size) hash_multipliers = _compute_hash_constants(dim, cells_per_side) # Create cell", "enum import Enum from typing import Any, Callable, Optional, Dict,", "1)) return jnp.where(self_mask, idx.shape[0], idx) @jit def prune_neighbor_list_dense(R, idx, **kwargs):", "spatial_dimension else: raise ValueError('Box must either be a scalar or", "def build_cells(R: Array, extra_capacity: int=0, **kwargs) -> CellList: N =", "# Types Array = util.Array f32 = util.f32 f64 =", "**kwargs)) except TypeError: continue except ValueError: continue raise ValueError( 'Canonicalize", "**kwargs: neighbor_list_fn(R, extra_capacity=extra_capacity, **kwargs), lambda R, nbrs, **kwargs: # pytype:", "_unflatten_cell_buffer(cell_id, cells_per_side, dim) for k, v in sorted_kwargs.items(): if v.ndim", "NeighborList, mask_self: bool=False) -> Array: \"\"\"Compute a mask for neighbor", "= jnp.cumsum(mask, axis=1) index = jnp.where(mask, cumsum - 1, idx.shape[1]", "If this is set to True then the box_size will", "For an N particle system this is an `[N, max_occupancy]`", "nbrs.cell_list_fn neighbor_fn = partial(neighbor_fn, max_occupancy=nbrs.max_occupancy) d = partial(metric_sq, **kwargs) d", "disable=wrong-arg-count if nbrs is None: cell_list_fn = (cell_list(box_size, cell_size, R,", "3x the size of the grid spacing in each '", "dindex dz = 0 elif len(dindex) == 3: dx, dy,", "it comes up later. empty_kwarg_value = 10 ** 5 cell_kwargs", "jnp.int64)): box_size = float(box_size) cells_per_side = onp.floor(box_size / minimum_cell_size) cell_size", "arr = jnp.concatenate((arr[-1:], arr[:-1])) if dy < 0: arr =", "`(2, max_neighbors)` specifying the start / end particle of each", "= jnp.array(R / cell_size, dtype=jnp.int64) particle_hash = jnp.sum(particle_index * hash_multipliers,", "extra_capacity: int=0, **kwargs) -> NeighborList: nbrs = neighbor_list def neighbor_fn(R_and_overflow,", "dz = dindex if dx < 0: arr = jnp.concatenate((arr[1:],", "in compliance with the License. # You may obtain a", "None: _mask = _mask & mask cumsum = jnp.cumsum(_mask) index", "\"{}\" with shape {}'.format(k, v.shape))) kwarg_shape = v.shape[1:] if v.ndim", "size used in the cell list will be set to", "software # distributed under the License is distributed on an", "neighbor_list_fn(R, nbrs, **kwargs)) def neighbor_list_mask(neighbor: NeighborList, mask_self: bool=False) -> Array:", "uses the positions to infer the maximum number of neighbors", "number of particles per-cell in a spatial partition.\"\"\" dim =", "= neighbor_fn.allocate(state.position) >>> else: >>> state = new_state >>> step", "import math from operator import mul import numpy as onp", "/ f32(2)) ** 2 metric_sq = _displacement_or_metric_to_metric_sq(displacement_or_metric) cell_size = cutoff", "jnp.concatenate((arr[:, :, 1:], arr[:, :, :1]), axis=2) elif dz >", "of shape [particle_count, spatial_dimension] that is used to estimate the", "dtype=i32) # It might be worth adding an occupied mask.", "of a system into a cell list. See cell_list(...) for", "of the neighbor list calculation. update_fn: A static python function", "will convert to the jraph format. Must be sparse. mask:", "nbrs)) >>> if nbrs.did_buffer_overflow: >>> nbrs = neighbor_fn.allocate(state.position) >>> else:", "= jnp.broadcast_to(cell_idx, idx.shape[:-1] + cell_idx.shape[-2:]) def copy_values_from_cell(value, cell_value, cell_id): scatter_indices", "jnp.zeros((N + 1,) + cell_idx.shape[-2:], jnp.int32) neighbor_idx = copy_values_from_cell(neighbor_idx, cell_idx,", "-> Tuple[Box, Array, Array, int]: \"\"\"Compute the number of cells-per-side", "particle system this is an `[N, max_occupancy]` array of integers", "partition the points / data spatially. A simple partitioning that", "cells_per_side = onp.array(cells_per_side, dtype=jnp.int64) if isinstance(box_size, onp.ndarray): if box_size.ndim ==", "will be set to `True` and a new neighbor list", "jnp.reshape(sender_idx, (-1,)) receiver_idx = jnp.reshape(idx, (-1,)) dR = d(R[sender_idx], R[receiver_idx])", "Union[int, Array], buffer_size_multiplier: float=1.1 ) -> Callable[[Array], CellList]: r\"\"\"Returns a", "two- and three-dimensions respectively. It is assumed that each cell", "ndarray of positions of shape [particle_count, spatial_dimension] that is used", "member function. Note that allocation of a new neighbor list", "= jnp.array(R / cell_size, dtype=i32) hashes = jnp.sum(indices * hash_multipliers,", "another sort. However, this seems possibly less efficient than just", "a box.\"\"\" if isinstance(box_size, int) or isinstance(box_size, float): box_size =", "if dz < 0: arr = jnp.concatenate((arr[:, :, 1:], arr[:,", "`d(R_a, R_b)` that computes the displacement between pairs of points.", "buffer_size_multiplier: float=1.1 ) -> Callable[[Array], CellList]: r\"\"\"Returns a function that", "a depricated code path to create / update neighbor '", "the example positions. disable_cell_list: An optional boolean. If set to", ">>> nbrs = neighbor_fn.allocate(state.position) >>> else: >>> state = new_state", "d(R, neigh_R) mask = (dR < cutoff_sq) & (idx <", "# Create cell list data. particle_id = lax.iota(jnp.int64, N) #", "only distances. This can be useful for debugging but should", "eval_shape from jax.abstract_arrays import ShapedArray from jax.interpreters import partial_eval as", "the neighbor list must scale with the highest connectivity neighbor.", "CellList]: r\"\"\"Returns a function that partitions point data spatially. Given", "(neighbor_list_fn if neighbor_list is None else neighbor_list.update_fn) return NeighborList( idx,", "= float(box_size) cells_per_side = onp.floor(box_size / minimum_cell_size) cell_size = box_size", "object. If it is provided then the function updates the", "-> MetricFn: \"\"\"Checks whether or not a displacement or metric", "to allocate a new neighbor list. This function cannot be", ">>> >>> nbrs = neighbor_fn.allocate(R) >>> state = init_fn(random.PRNGKey(0), R,", "{x_i \\in R^d} with associated data {k_i \\in R^m} it", "True then the neighbor list is constructed using only distances.", "# # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "an occupancy test. It seems easier to design around this", "needs to be rerun using a larger buffer. max_occupancy: A", "the displacement between pairs of points. box_size: Either a float", "and side data specified by kwargs into a cell list.", "# pytype: disable=wrong-arg-count return build_cells def _displacement_or_metric_to_metric_sq( displacement_or_metric: DisplacementOrMetricFn) ->", "If it is provided then the function updates the neighbor", "An optional boolean. Determines whether points can consider themselves to", "* jnp.ones((idx.shape[0], padding), dtype=idx.dtype)], axis=1) idx = idx[:, :max_occupancy] update_fn", "shape # [N, output_dimension] which ignores the empty slots. mask_id", "involve # more compute since often we will do a", "neighbor.idx < len(neighbor.idx) if mask_self: N = len(neighbor.reference_position) self_mask =", "is a typical example of a simulation loop with neighbor", "new neighbor list cannot be jit compiled since it uses", "the `capacity_multiplier`). Updating the neighbor list can be jit compiled;", "jnp.ones(idx.shape, jnp.int32) cumsum = jnp.cumsum(mask, axis=1) index = jnp.where(mask, cumsum", "cell_list_fn, update_fn) # pytype: disable=wrong-arg-count if nbrs is None: cell_list_fn", "of particles when the neighbor list was constructed. This is", "in the cell list will be set to cutoff /", "to_jraph(neighbor: NeighborList, mask: Array=None) -> jraph.GraphsTuple: \"\"\"Convert a sparse neighbor", "cell size used in the cell list will be set", "sender_idx = out_idx.at[index].set(sender_idx) max_occupancy = cumsum[-1] return jnp.stack((receiver_idx[:-1], sender_idx[:-1])), max_occupancy", "' 'NeighborListFormat.OrderedSparse.') receivers, senders = neighbor.idx N = len(neighbor.reference_position) _mask", "= space.map_neighbor(d) N = R.shape[0] neigh_R = R[idx] dR =", "A simple partitioning that can be implemented efficiently within XLA", "= len(neighbor.reference_position) _mask = neighbor_list_mask(neighbor) if mask is not None:", "specification. Cell list buffers all have a common shape, S,", "be compiled, since it uses the values of positions to", "spatial partition of a system into a cell list. See", "particle of each neighbor pair. OrderedSparse: A sparse neighbor list", "list object. If it is provided then the function updates", "the distribution of points changes significantly it is likely the", "of shape S. Note that empty slots are specified by", "for backward compatibility with previous neighbor lists. Attributes: R: An", "1, len(receiver_idx) - 1) receiver_idx = out_idx.at[index].set(receiver_idx) sender_idx = out_idx.at[index].set(sender_idx)", "minimum_cell_size: A float specifying the minimum side length of each", "list capacity is not sufficient to store all the neighbors,", "with the License. # You may obtain a copy of", "dense_idx.at[hashes].set(receivers).reshape((N, max_count)) return dense_idx Dense = NeighborListFormat.Dense Sparse = NeighborListFormat.Sparse", "of particles that can be stored in each cell or", "the positions to infer the maximum number of neighbors (along", "mask = mask & self_mask return mask def to_jraph(neighbor: NeighborList,", "axis=1) elif dy > 0: arr = jnp.concatenate((arr[:, -1:], arr[:,", "jnp from jax_md import quantity, space, dataclasses, util import jraph", "recompilation. format: A NeighborListFormat enum specifying the format of the", "cell_R = jnp.zeros((cell_count * _cell_capacity, dim), dtype=R.dtype) cell_id = N", "is_format_valid(format) box_size = lax.stop_gradient(box_size) r_cutoff = lax.stop_gradient(r_cutoff) dr_threshold = lax.stop_gradient(dr_threshold)", "len(neighbor.reference_position) if mask_self: mask = mask & (neighbor.idx[0] != neighbor.idx[1])", "max_occupancy=None): R, overflow = R_and_overflow N = R.shape[0] if cell_list_fn", "Callable, Optional, Dict, Tuple, Generator, Union import math from operator", "1: box_size = jnp.reshape(box_size, (1, -1)) if util.is_array(minimum_cell_size): minimum_cell_size =", "- 1) p_index = jnp.arange(idx.shape[0])[:, None] out_idx = out_idx.at[p_index, index].set(idx)", "enlarged so that they exactly fill the box. cell_capacity_or_example_R: Either", "copy_values_from_cell(neighbor_idx, cell_idx, idx) return neighbor_idx[:-1, :, 0] @jit def mask_self_fn(idx):", "the minimum side length of each cell. Cells are enlarged", "prune_neighbor_list_sparse(R, idx, **kwargs): d = partial(metric_sq, **kwargs) d = space.map_bond(d)", "It is assumed that each cell has the same capacity.", "Array: if cells_per_side.size == 1: return jnp.array([[cells_per_side ** d for", "LLC # # Licensed under the Apache License, Version 2.0", "return box_size, cell_size, cells_per_side, int(cell_count) def count_cell_filling(R: Array, box_size: Box,", "pe import jax.numpy as jnp from jax_md import quantity, space,", "cells_per_side.size == 1: return jnp.array([[cells_per_side ** d for d in", "(util.is_array(R) and len(R.shape) == 2 and jnp.issubdtype(R.dtype, jnp.floating)): return True", "specified as an ndarry. Found \"{}\" with ' 'type {}'.format(k,", "= dindex if dx < 0: arr = jnp.concatenate((arr[1:], arr[:1]))", "more efficient by shrinking the verlet list at the cost", "cell_capacity_or_example_R if _is_variable_compatible_with_positions(cell_capacity): cell_capacity = _estimate_cell_capacity( cell_capacity, box_size, minimum_cell_size, buffer_size_multiplier)", "**kwargs): d = partial(metric_sq, **kwargs) d = space.map_bond(d) N =", "len(neighbor.reference_position) _mask = neighbor_list_mask(neighbor) if mask is not None: _mask", "the simulation will be incorrect and the simulation needs to", "mask_self: An optional boolean. Determines whether points can consider themselves", "2 else: return lambda Ra, Rb, **kwargs: space.square_distance( displacement_or_metric(Ra, Rb,", "neighbor_list: An optional neighor list object. If it is provided", "the particle data into the grid. Here we use a", "neighbor list whose capacity is inferred from R. If neighbor_list", "if max_occupancy > R.shape[0] and not is_sparse(format): max_occupancy = R.shape[0]", "functions: 1) `neighbor_fn.allocate` create a new neighbor list and 2)", "express or implied. # See the License for the specific", "except in compliance with the License. # You may obtain", "up later. empty_kwarg_value = 10 ** 5 cell_kwargs = {}", "empty_data_value # for now and revisit the issue if it", "idx, **kwargs): d = partial(metric_sq, **kwargs) d = space.map_bond(d) N", "idx = jnp.concatenate( [idx, N * jnp.ones((idx.shape[0], padding), dtype=idx.dtype)], axis=1)", "receivers, senders = neighbor.idx N = len(neighbor.reference_position) _mask = neighbor_list_mask(neighbor)", "dense ids. Cannot be JIT.\"\"\" if neighbor.format is not Sparse:", "debugging but should generally be left as False. mask_self: An", "offset = jnp.tile(jnp.arange(max_count), N)[:len(senders)] hashes = senders * max_count +", "mask_self: bool=True, fractional_coordinates: bool=False, format: NeighborListFormat=NeighborListFormat.Dense, **static_kwargs) -> NeighborFn: \"\"\"Returns", "2) `neighbor_fn.update` updates an existing neighbor list. Neighbor lists themselves", "efficient by shrinking the verlet list at the cost of", "cell_capacity + grid_id where grid_id # is a flat list", "Callable: if dim == 2: return vmap(vmap(f, 0, 0), 0,", "that the results of the simulation will be incorrect and", "multiplies the estimated cell capacity to allow for fluctuations in", "100, body_fn, (state, nbrs)) >>> if nbrs.did_buffer_overflow: >>> nbrs =", "out_idx[:, :-1], max_occupancy @jit def prune_neighbor_list_sparse(R, idx, **kwargs): d =", "neighbor.idx[1]) return mask mask = neighbor.idx < len(neighbor.idx) if mask_self:", "= jnp.array([[1]], dtype=jnp.int32) cells_per_side = jnp.concatenate((one, cells_per_side[:, :-1]), axis=1) return", "onp.ndarray, dindex: Array) -> Array: if len(dindex) == 2: dx,", "Box = space.Box DisplacementOrMetricFn = space.DisplacementOrMetricFn MetricFn = space.MetricFn #", "shape S. Note that empty slots are specified by id", "idx.shape[0], idx) @jit def prune_neighbor_list_dense(R, idx, **kwargs): d = partial(metric_sq,", "grid_id # is a flat list that repeats 0, ..,", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "`(N, max_neighbors_per_atom)`. Here the capacity of the neighbor list must", "to the jraph format. Must be sparse. mask: An optional", "minimum_cell_size: float) -> Tuple[Box, Array, Array, int]: \"\"\"Compute the number", "array of shape [spatial_dim] specifying the box size in each", "capacity. Found {}.'.format(type(cell_capacity)) ) raise ValueError(msg) def build_cells(R: Array, extra_capacity:", "< cutoff_sq) & (idx < N) out_idx = N *", "-> NeighborList: nbrs = neighbor_list def neighbor_fn(R_and_overflow, max_occupancy=None): R, overflow", "= vmap(d) return lax.cond( jnp.any(d(R, nbrs.reference_position) > threshold_sq), (R, nbrs.did_buffer_overflow),", "onp.ndindex(*([3] * dimension)): yield onp.array(dindex, dtype=jnp.int64) - 1 def _estimate_cell_capacity(R:", "> 0: arr = jnp.concatenate((arr[-1:], arr[:-1])) if dy < 0:", "true id whereas particles empty slots have id = N.", "kwargs into a cell list. Returns a CellList containing the", "is set to true to indicate that there was a", "return jnp.array(jnp.cumprod(cells_per_side), dtype=jnp.int64) else: raise ValueError() def _neighboring_cells(dimension: int) ->", "jnp.broadcast_to(jnp.arange(N)[:, None], idx.shape) sender_idx = jnp.reshape(sender_idx, (-1,)) receiver_idx = jnp.reshape(idx,", "= 0 elif len(dindex) == 3: dx, dy, dz =", "= _unflatten_cell_buffer(cell_R, cells_per_side, dim) cell_id = _unflatten_cell_buffer(cell_id, cells_per_side, dim) for", "compiled, since it uses the values of positions to infer", "neighborhood_tile_count = 3 ** dim _, cell_size, cells_per_side, cell_count =", "CONDITIONS OF ANY KIND, either express or implied. # See", "neighbor lists. Attributes: R: An `(N, dim)` array of particle", "happens, it means that the results of the simulation will", "infer the shapes. update: A function to update a neighbor", "= state >>> nbrs = nbrs.update(state.position) >>> state = apply_fn(state,", "compared with the maximum in the example positions. disable_cell_list: An", "def _compute_hash_constants(spatial_dimension: int, cells_per_side: Array) -> Array: if cells_per_side.size ==", "dataclasses.static_field() update: Callable[[Array, NeighborList], NeighborList] = dataclasses.static_field() def __call__(self, R:", "a common shape, S, where * `S = [cell_count_x, cell_count_y,", "function `d(R_a, R_b)` that computes the displacement between pairs of", "rerun using a larger buffer. max_occupancy: A static integer specifying", "jnp.concatenate((arr[:, 1:], arr[:, :1]), axis=1) elif dy > 0: arr", "* jnp.ones(receiver_idx.shape, jnp.int32) cumsum = jnp.cumsum(mask) index = jnp.where(mask, cumsum", "in which the box_size would not be accurately represented by", "* capacity_multiplier + _extra_capacity) if max_occupancy > R.shape[0] and not", "An ndarray of int32 particle ids of shape S. Note", "of a simulation loop with neighbor lists: >>> init_fn, apply_fn", "N = R.shape[0] neigh_R = R[idx] dR = d(R, neigh_R)", "\"\"\" idx: Array reference_position: Array did_buffer_overflow: Array max_occupancy: int =", "one = jnp.array([[1]], dtype=jnp.int32) cells_per_side = jnp.concatenate((one, cells_per_side[:, :-1]), axis=1)", "jnp.ones( (cell_count * _cell_capacity,) + kwarg_shape, v.dtype) indices = jnp.array(R", "< 3: raise ValueError( ('Box must be at least 3x", "hashes = jnp.sum(indices * hash_multipliers, axis=1) # Copy the particle", "allocate and update neighbor lists. Attributes: allocate: A function to", "contains side data placed into the cell list. \"\"\" position_buffer:", "= jnp.reshape(v, v.shape + (1,)) cell_kwargs[k] = ops.index_update(cell_kwargs[k], sorted_cell_id, v)", "2 threshold_sq = (dr_threshold / f32(2)) ** 2 metric_sq =", "vmap(vmap(vmap(f, 0, 0), 0, 0), 0, 0) raise ValueError('Cell list", "import namedtuple from enum import Enum from typing import Any,", "threshold_sq = (dr_threshold / f32(2)) ** 2 metric_sq = _displacement_or_metric_to_metric_sq(displacement_or_metric)", "int: # TODO(schsam): We might want to do something more", "the neighbor list. \"\"\" logging.warning('Using a depricated code path to", "quantity, space, dataclasses, util import jraph # Types Array =", "# limitations under the License. \"\"\"Code to transform functions on", "additional space specified by the `capacity_multiplier`). Updating the neighbor list", "If there are ever more neighbors than max_neighbors this is", "given then it will update the neighbor list (with fixed", "this buffer can either be specified manually or it can", "extra_capacity) max_occupancy = int(occupancy * capacity_multiplier + _extra_capacity) if max_occupancy", "not is_sparse(format): max_occupancy = R.shape[0] padding = max_occupancy - occupancy", "system this is an `[N, max_occupancy]` array of integers such", "= R.shape[0] sender_idx = jnp.broadcast_to(jnp.arange(N)[:, None], idx.shape) sender_idx = jnp.reshape(sender_idx,", "likely the buffer the buffer sizes will have to be", "\"\"\"A struct containing functions to allocate and update neighbor lists.", "a spatial partition.\"\"\" dim = int(R.shape[1]) box_size, cell_size, cells_per_side, cell_count", "N is the number of particles in the system. kwarg_buffers:", "an ndarry. Found \"{}\" with ' 'type {}'.format(k, type(v)))) if", "cell capacity. Found {}.'.format(type(cell_capacity)) ) raise ValueError(msg) def build_cells(R: Array,", "cells_per_side.shape)): cells_per_side = (int(cells_per_side),) * dim elif util.is_array(cells_per_side) and len(cells_per_side.shape)", "cells_per_side, dim) for k, v in sorted_kwargs.items(): if v.ndim ==", "int): msg = ( 'cell_capacity_or_example_positions must either be an integer", "for species that will include # an occupancy test. It", "if onp.all(dindex == 0): continue cell_idx += [_shift_array(idx, dindex)] cell_idx", "with a single node. Args: neighbor: A neighbor list that", "jnp.array(R / cell_size, dtype=jnp.int64) particle_hash = jnp.sum(particle_index * hash_multipliers, axis=1)", "# fewer than cell_capacity particles per cell, each particle is", "vmap(vmap(f, 0, 0), 0, 0) elif dim == 3: return", "A static integer specifying the maximum size of the neighbor", "Array: if (isinstance(cells_per_side, int) or isinstance(cells_per_side, float) or (util.is_array(cells_per_side) and", ">>> nbrs = nbrs.update(state.position) >>> state = apply_fn(state, neighbor_idx=nbrs.idx) >>>", "def neighbor_list_fn(R: Array, neighbor_list: Optional[NeighborList]=None, extra_capacity: int=0, **kwargs) -> NeighborList:", "= cumsum[-1] return jnp.stack((receiver_idx[:-1], sender_idx[:-1])), max_occupancy def neighbor_list_fn(R: Array, neighbor_list:", "to update the neighbor list. \"\"\" idx: Array reference_position: Array", "the neighbors, the `did_buffer_overflow` bit will be set to `True`", "\"\"\"Counts the number of particles per-cell in a spatial partition.\"\"\"", "* hash_multipliers, axis=1) filling = ops.segment_sum(jnp.ones_like(particle_hash), particle_hash, cell_count) return filling", "are ever more neighbors than max_neighbors this is set to", "if v.shape[0] != R.shape[0]: raise ValueError( ('Data must be specified", "cell_capacity = onp.max(count_cell_filling(R, box_size, cell_size)) return int(cell_capacity * buffer_size_multiplier) def", "list where the ids are a square matrix of shape", "R.shape[0] padding = max_occupancy - occupancy if max_occupancy > occupancy:", "R. If neighbor_list is given then it will update the", "in sorted_kwargs.items(): if v.ndim == 1: v = jnp.reshape(v, v.shape", "max_neighbors_per_atom)`. Here the capacity of the neighbor list must scale", "points. Neighbor lists must balance the need to be jit", "the points / data spatially. A simple partitioning that can", "An optional neighor list object. If it is provided then", "makes a verlet list that is larger than # needed", "elif cells_per_side.size == spatial_dimension: one = jnp.array([[1]], dtype=jnp.int32) cells_per_side =", "not is_sparse(neighbor.format): raise ValueError('Cannot convert a dense neighbor list to", "increase in maximum neighborhood occupancy we allocate compared with the", "of points {x_i \\in R^d} with associated data {k_i \\in", "as `Sparse` where only bonds with i < j are", "NeighborList] def neighbor_list(displacement_or_metric: DisplacementOrMetricFn, box_size: Box, r_cutoff: float, dr_threshold: float,", "list that is larger than # needed since the idx", "to check this in compute_fn as well? raise ValueError( 'Cell", "return ops.index_update(value, scatter_indices, cell_value) # NOTE(schsam): Currently, this makes a", "then the box_size will be set to 1.0 and the", "fill the box. cell_capacity_or_example_R: Either an integer specifying the size", "1) `neighbor_fn.allocate` create a new neighbor list and 2) `neighbor_fn.update`", "operator import mul import numpy as onp from jax import", "(dR < cutoff_sq) & (receiver_idx < N) if format is", "the neighbor list calculation. update_fn: A static python function used", "0: cell_count = cells_per_side ** spatial_dimension else: raise ValueError('Box must", "overflow. If this happens, it means that the results of", "state = apply_fn(state, neighbor_idx=nbrs.idx) >>> return state, nbrs >>> >>>", "choices for formats. Defaults to `Dense`. **static_kwargs: kwargs that get", "idx buffer inherets its size from the cell-list. In #", "= jnp.reshape(sender_idx, (-1,)) receiver_idx = jnp.reshape(idx, (-1,)) dR = d(R[sender_idx],", "for k, v in sorted_kwargs.items(): if v.ndim == 1: v", "move before rebuilding the neighbor list. capacity_multiplier: A floating point", "to an array of shape # [N + 1, output_dimension]", "than # needed since the idx buffer inherets its size", "listing the different neighbor list formats. Attributes: Dense: A dense", "buffer can either be specified manually or it can be", "A function `cell_list_fn(R, **kwargs)` that partitions positions, `R`, and side", "lax from jax import ops from jax import jit, vmap,", "else: >>> state = new_state >>> step += 1 Args:", "used to decide whether the neighbor list ought to be", "= ops.segment_sum(jnp.ones(len(receivers), jnp.int32), receivers, N) max_count = jnp.max(count) offset =", "and the simulation needs to be rerun using a larger", "hashes = senders * max_count + offset dense_idx = N", "count_cell_filling(R: Array, box_size: Box, minimum_cell_size: float) -> Array: \"\"\"Counts the", "= ops.index_update( cell_id, sorted_cell_id, sorted_id) cell_R = _unflatten_cell_buffer(cell_R, cells_per_side, dim)", "the function updates the neighbor list, otherwise it allocates a", "maximum cell occupancy. Returns: A function `cell_list_fn(R, **kwargs)` that partitions", "Here the capacity of the neighbor list must scale with", "a sparse neighbor list to a `jraph.GraphsTuple`. As in jraph,", "= cutoff ** 2 threshold_sq = (dr_threshold / f32(2)) **", "update neighbor ' 'lists. It will be removed in a", "and (box_size.dtype == jnp.int32 or box_size.dtype == jnp.int64)): box_size =", "if nbrs is None: cell_list_fn = (cell_list(box_size, cell_size, R, capacity_multiplier)", "This is used to decide whether the neighbor list ought", "1 or box_size.ndim == 2: assert box_size.size == spatial_dimension flat_cells_per_side", "cell, each particle is guarenteed # to get a cell", "(isinstance(cells_per_side, int) or isinstance(cells_per_side, float) or (util.is_array(cells_per_side) and not cells_per_side.shape)):", "be JIT.\"\"\" if neighbor.format is not Sparse: raise ValueError('Can only", "the jraph format. Must be sparse. mask: An optional mask", "functions on individual tuples of particles to sets.\"\"\" from absl", "out_idx = N * jnp.ones(idx.shape, jnp.int32) cumsum = jnp.cumsum(mask, axis=1)", "dindex if dx < 0: arr = jnp.concatenate((arr[1:], arr[:1])) elif", "cell_id = ops.index_update( cell_id, sorted_cell_id, sorted_id) cell_R = _unflatten_cell_buffer(cell_R, cells_per_side,", "**kwargs: \\ displacement_or_metric(Ra, Rb, **kwargs) ** 2 else: return lambda", "f' found {format}.')) @dataclasses.dataclass class NeighborList(object): \"\"\"A struct containing the", "d for d in range(spatial_dimension)]], dtype=jnp.int64) elif cells_per_side.size == spatial_dimension:", "jnp.concatenate( [idx, N * jnp.ones((idx.shape[0], padding), dtype=idx.dtype)], axis=1) idx =", "a new neighbor list. extra_capacity: Extra capacity to add if", "[0, 1]^d. If this is set to True then the", "int(cell_capacity * buffer_size_multiplier) def _unflatten_cell_buffer(arr: Array, cells_per_side: Array, dim: int)", "not disable_cell_list @jit def candidate_fn(R, **kwargs): return jnp.broadcast_to(jnp.reshape(jnp.arange(R.shape[0]), (1, R.shape[0])),", "-> Array: if (isinstance(cells_per_side, int) or isinstance(cells_per_side, float) or (util.is_array(cells_per_side)", "respectively. It is assumed that each cell has the same", "do something more sophisticated here or at # least expose", "\"\"\" if not is_sparse(neighbor.format): raise ValueError('Cannot convert a dense neighbor", "lambda x: x) return NeighborListFns(lambda R, extra_capacity=0, **kwargs: neighbor_list_fn(R, extra_capacity=extra_capacity,", "ops.segment_sum(jnp.ones_like(particle_hash), particle_hash, cell_count) return filling def _is_variable_compatible_with_positions(R: Array) -> bool:", "' 'is preferred.') if neighbor_list is None: return self.allocate(R, extra_capacity,", "decide whether the neighbor list ought to be updated. did_buffer_overflow:", "that there was a buffer overflow. If this happens, it", "of floating point positions with shape S + [spatial_dimension]. id_buffer:", "R, **kwargs): return self.update_fn(R, self, **kwargs) @dataclasses.dataclass class NeighborListFns: \"\"\"A", "**kwargs) -> NeighborList: nbrs = neighbor_list def neighbor_fn(R_and_overflow, max_occupancy=None): R,", "be specified manually or it can be estimated automatically from", "= jnp.concatenate((arr[:, :, 1:], arr[:, :, :1]), axis=2) elif dz", "was provided.\"\"\" for dim in range(1, 4): try: R =", "fractional_coordinates: An optional boolean. Specifies whether positions will be supplied", "== spatial_dimension: one = jnp.array([[1]], dtype=jnp.int32) cells_per_side = jnp.concatenate((one, cells_per_side[:,", "= (dR < cutoff_sq) & (idx < N) out_idx =", "neighbor list. extra_capacity: Extra capacity to add if allocating the", "< 0: arr = jnp.concatenate((arr[1:], arr[:1])) elif dx > 0:", "/ 2. Note that only `neighbor_list_fn(R, neighbor_list)` can be `jit`", "float) -> int: # TODO(schsam): We might want to do", "where the ids are a rectangular matrix of shape `(2,", "capacity) if any particle has moved more than dr_threshold /", "fixed sized buffers for each cell. The size of this", "list formats. Attributes: Dense: A dense neighbor list where the", "specifying the maximum distance particles can move before rebuilding the", "example positions. disable_cell_list: An optional boolean. If set to True", "jnp.any(d(R, nbrs.reference_position) > threshold_sq), (R, nbrs.did_buffer_overflow), neighbor_fn, nbrs, lambda x:", "NeighborListFormat) -> bool: return (format is NeighborListFormat.Sparse or format is", "here is accomplished by adding a ficticious graph with a", "dx, dy = dindex dz = 0 elif len(dindex) ==", "or box_size.ndim == 2: assert box_size.size == spatial_dimension flat_cells_per_side =", "for each cell. The size of this buffer can either", "lists themselves additionally have a convenience `update` member function. Note", "/ 3.) and not disable_cell_list @jit def candidate_fn(R, **kwargs): return", "positions to infer the shapes. update: A function to update", "N where N is the number of particles in the", "`cell_list_fn(R, **kwargs)` that partitions positions, `R`, and side data specified", "# for now and revisit the issue if it comes", "int = dataclasses.static_field() format: NeighborListFormat = dataclasses.static_field() cell_list_fn: Callable[[Array], CellList]", "nbrs >>> >>> step = 0 >>> for _ in", "id_buffer: Array kwarg_buffers: Dict[str, Array] def _cell_dimensions(spatial_dimension: int, box_size: Box,", "box_size = float(box_size) # NOTE(schsam): Should we auto-cast based on", "list (with fixed capacity) if any particle has moved more", "'Cell list spatial dimension must be 2 or 3. Found", "0] @jit def mask_self_fn(idx): self_mask = idx == jnp.reshape(jnp.arange(idx.shape[0]), (idx.shape[0],", "as well? raise ValueError( 'Cell list spatial dimension must be", "`neighbor_list_fn(R, neighbor_list)` can be `jit` since it keeps array shapes", "dtype=idx.dtype)], axis=1) idx = idx[:, :max_occupancy] update_fn = (neighbor_list_fn if", "governing permissions and # limitations under the License. \"\"\"Code to", "+ 1, output_dimension] and then truncate it to an array", "jnp.ones((N,), jnp.int64) * N cell_R = jnp.zeros((cell_count * _cell_capacity, dim),", "sorted_R) sorted_id = jnp.reshape(sorted_id, (N, 1)) cell_id = ops.index_update( cell_id,", "python function used to update the neighbor list. \"\"\" idx:", "it uses the values of positions to infer the shapes.", ".., cell_capacity. So long as there are # fewer than", "incorrect and the simulation needs to be rerun using a", "specifying the size of the system. Note, this code is", "that empty slots are specified by id = N where", "long as there are # fewer than cell_capacity particles per", "kwargs.items(): sorted_kwargs[k] = v[sort_map] sorted_cell_id = jnp.mod(lax.iota(jnp.int64, N), _cell_capacity) sorted_cell_id", "implemented for spatial dimension larger' 'than 4.') class NeighborListFormat(Enum): \"\"\"An", "= jnp.max(count) offset = jnp.tile(jnp.arange(max_count), N)[:len(senders)] hashes = senders *", "= v.shape[1:] if v.ndim > 1 else (1,) cell_kwargs[k] =", "jnp.sum(indices * hash_multipliers, axis=1) # Copy the particle data into", "cell-list. In # three-dimensions this seems to translate into an", "However, that will involve # more compute since often we", "coordinates in the unit cube, [0, 1]^d. If this is", "NeighborListFormat enum specifying the format of the neighbor list. cell_list_fn:", "buffer the buffer sizes will have to be adjusted. This", "keeps array shapes fixed. \"\"\" is_format_valid(format) box_size = lax.stop_gradient(box_size) r_cutoff", "jax import lax from jax import ops from jax import", "cell hash. We then assign each # particle to have", "jnp.cumsum(mask, axis=1) index = jnp.where(mask, cumsum - 1, idx.shape[1] -", "the verlet list at the cost of # another sort.", "ValueError('Cell list only supports 2d or 3d.') def cell_list(box_size: Box,", "list at the cost of # another sort. However, this", "a set of positions that will be used ' 'to", "neighbor list.\"\"\" if is_sparse(neighbor.format): mask = neighbor.idx[0] < len(neighbor.reference_position) if", "that starts out False. If there are ever more neighbors", "the maximum number of neighbors (along with additional space specified", "dR = d(R, neigh_R) mask = (dR < cutoff_sq) &", "raise ValueError(msg) def build_cells(R: Array, extra_capacity: int=0, **kwargs) -> CellList:", "step += 1 Args: displacement: A function `d(R_a, R_b)` that", "boolean. If set to True then the neighbor list is", "NeighborList: \"\"\"A function for backward compatibility with previous neighbor lists.", "specifying the minimum side length of each cell. Cells are", "specified manually or it can be estimated automatically from a", "allocating the neighbor list. \"\"\" logging.warning('Using a depricated code path", "= space.DisplacementOrMetricFn MetricFn = space.MetricFn # Cell List @dataclasses.dataclass class", "back from the grid, copy it to an array of", "in a later version of JAX MD. ' 'Using `neighbor_fn.allocate`", "update neighbor lists. Attributes: allocate: A function to allocate a", "sorted_hash = hashes[sort_map] sorted_id = particle_id[sort_map] sorted_kwargs = {} for", "float): box_size = float(box_size) # NOTE(schsam): Should we auto-cast based", "different accelerators. Args: box_size: A float or an ndarray of", "than max_neighbors this is set to true to indicate that", "the neighbor list can be jit compiled; if the neighbor", "from a set of positions. Note, if the distribution of", "mask def to_jraph(neighbor: NeighborList, mask: Array=None) -> jraph.GraphsTuple: \"\"\"Convert a", "* buffer_size_multiplier) def _unflatten_cell_buffer(arr: Array, cells_per_side: Array, dim: int) ->", "(cell_list(box_size, cell_size, R, capacity_multiplier) if use_cell_list else None) return neighbor_fn((R,", "!= jnp.reshape(jnp.arange(N), (N, 1)) mask = mask & self_mask return", "an occupied mask. However, that will involve # more compute", "# copied have their true id whereas particles empty slots", "provided then the function updates the neighbor list, otherwise it", "= jnp.zeros((N + 1,) + cell_idx.shape[-2:], jnp.int32) neighbor_idx = copy_values_from_cell(neighbor_idx,", "capacity_multiplier + _extra_capacity) if max_occupancy > R.shape[0] and not is_sparse(format):", "efficiently within XLA is a dense partition into a uniform", "False)) else: cell_list_fn = nbrs.cell_list_fn neighbor_fn = partial(neighbor_fn, max_occupancy=nbrs.max_occupancy) d", "of shape [spatial_dimension] specifying the size of the system. Note,", "= ShapedArray((dim,), f32) dR_or_dr = eval_shape(displacement_or_metric, R, R, t=0) if", "than cell_capacity particles per cell, each particle is guarenteed #", "by id = N where N is the number of", "ordered = N * jnp.ones((len(receivers) + 1,), jnp.int32) receivers =", "N) out_idx = N * jnp.ones(idx.shape, jnp.int32) cumsum = jnp.cumsum(mask,", "+ offset dense_idx = N * jnp.ones((N * max_count,), jnp.int32)", "it means that the results of the simulation will be", "scatter_indices, cell_value) # NOTE(schsam): Currently, this makes a verlet list", "neighbor_list is None: return self.allocate(R, extra_capacity, **kwargs) return self.update(R, neighbor_list,", "== 3: dx, dy, dz = dindex if dx <", "scalar specifying the maximum distance particles can move before rebuilding", "`jraph.GraphsTuple`. As in jraph, padding here is accomplished by adding", "(isinstance(box_size, onp.ndarray) and (box_size.dtype == jnp.int32 or box_size.dtype == jnp.int64)):", "axis=1) return jnp.array(jnp.cumprod(cells_per_side), dtype=jnp.int64) else: raise ValueError() def _neighboring_cells(dimension: int)", "nbrs = lax.fori_loop(0, 100, body_fn, (state, nbrs)) >>> if nbrs.did_buffer_overflow:", "of ndarrays of shape S + [...]. This contains side", "automatically from a set of positions. Note, if the distribution", "int, box_size: Box, minimum_cell_size: float) -> Tuple[Box, Array, Array, int]:", "the current neighbor list. The second element contains a function", "neighbor list to dense ids. Cannot be JIT.\"\"\" if neighbor.format", "particle data into the grid. Here we use a trick", "def _estimate_cell_capacity(R: Array, box_size: Box, cell_size: float, buffer_size_multiplier: float) ->", "grid. Here we use a trick to allow us to", "Copy the particle data into the grid. Here we use", ">>> exact_init_fn, exact_apply_fn = simulate.nve(exact_energy_fn, shift, 1e-3) >>> >>> nbrs", "= mask_self_fn(idx) if is_sparse(format): idx, occupancy = prune_neighbor_list_sparse(R, idx, **kwargs)", "and update neighbor lists. Attributes: allocate: A function to allocate", "neighbor list was constructed. This is used to decide whether", "* jnp.ones((len(receivers) + 1,), jnp.int32) receivers = ordered.at[index].set(receivers)[:-1] senders =", "in a spatial partition.\"\"\" dim = int(R.shape[1]) box_size, cell_size, cells_per_side,", "= jnp.concatenate((arr[:, 1:], arr[:, :1]), axis=1) elif dy > 0:", "arr = jnp.concatenate((arr[:, :, -1:], arr[:, :, :-1]), axis=2) return", "Array did_buffer_overflow: Array max_occupancy: int = dataclasses.static_field() format: NeighborListFormat =", "occupancy)), max_occupancy, format, cell_list_fn, update_fn) # pytype: disable=wrong-arg-count if nbrs", "cell occupancy. Returns: A function `cell_list_fn(R, **kwargs)` that partitions positions,", "pytype: disable=wrong-arg-count neighbor_list_fn(R, nbrs, **kwargs)) def neighbor_list_mask(neighbor: NeighborList, mask_self: bool=False)", "import jraph # Types Array = util.Array f32 = util.f32", "of ~70%. We # can make this more efficient by", "the different neighbor list formats. Attributes: Dense: A dense neighbor", "= hash * cell_capacity + grid_id where grid_id # is", "of each neighbor pair. OrderedSparse: A sparse neighbor list whose", "the `did_buffer_overflow` bit will be set to `True` and a", "to do something more sophisticated here or at # least", "neighbor list. If neighbor_list is None then the function will", "for cells in flat_cells_per_side: if cells < 3: raise ValueError(", "* dimension)): yield onp.array(dindex, dtype=jnp.int64) - 1 def _estimate_cell_capacity(R: Array,", "ShapedArray from jax.interpreters import partial_eval as pe import jax.numpy as", "cell_R = _unflatten_cell_buffer(cell_R, cells_per_side, dim) cell_id = _unflatten_cell_buffer(cell_id, cells_per_side, dim)", "= eval_shape(displacement_or_metric, R, R, t=0) if len(dR_or_dr.shape) == 0: return", "simultaneously using a single lax.scatter call. To do # this", "ops from jax import jit, vmap, eval_shape from jax.abstract_arrays import", "\\in R^m} it is often useful to partition the points", "each spatial dimension. r_cutoff: A scalar specifying the neighborhood radius.", "Version 2.0 (the \"License\"); # you may not use this", "of the neighbor list. cell_list_fn: A static python callable that", "previous neighbor lists. Attributes: R: An `(N, dim)` array of", "a function that builds a list neighbors for collections of", "= jnp.where(mask, cumsum - 1, len(receiver_idx) - 1) receiver_idx =", "maximum in the example positions. disable_cell_list: An optional boolean. If", "transform functions on individual tuples of particles to sets.\"\"\" from", "as False. mask_self: An optional boolean. Determines whether points can", "** d for d in range(spatial_dimension)]], dtype=jnp.int64) elif cells_per_side.size ==", "tuples of particles to sets.\"\"\" from absl import logging from", "Attributes: position_buffer: An ndarray of floating point positions with shape", "R.shape[-1] cell_capacity = onp.max(count_cell_filling(R, box_size, cell_size)) return int(cell_capacity * buffer_size_multiplier)", "cells in a box.\"\"\" if isinstance(box_size, int) or isinstance(box_size, float):", "least expose this constant. spatial_dim = R.shape[-1] cell_capacity = onp.max(count_cell_filling(R,", "dataclasses.static_field() update_fn: Callable[[Array, 'NeighborList'], 'NeighborList'] = dataclasses.static_field() def update(self, R,", "balance the need to be jit compatable with the fact", "sorted_hash * _cell_capacity + sorted_cell_id cell_R = ops.index_update(cell_R, sorted_cell_id, sorted_R)", "cell_idx = cell_idx[..., jnp.newaxis, :, :] cell_idx = jnp.broadcast_to(cell_idx, idx.shape[:-1]", "2 metric_sq = _displacement_or_metric_to_metric_sq(displacement_or_metric) cell_size = cutoff if fractional_coordinates: cell_size", "v.ndim > 1 else (1,) cell_kwargs[k] = empty_kwarg_value * jnp.ones(", "< len(neighbor.idx) if mask_self: N = len(neighbor.reference_position) self_mask = neighbor.idx", "capacity_multiplier) if use_cell_list else None) return neighbor_fn((R, False)) else: cell_list_fn", "R.shape[0] and not is_sparse(format): max_occupancy = R.shape[0] padding = max_occupancy", "return NeighborList( idx, R, jnp.logical_or(overflow, (max_occupancy < occupancy)), max_occupancy, format,", "a cell id that is unique. sort_map = jnp.argsort(hashes) sorted_R", "`jraph.GraphsTuple` that contains the topology of the neighbor list. \"\"\"", "mask_self_fn(idx) if is_sparse(format): idx, occupancy = prune_neighbor_list_sparse(R, idx, **kwargs) else:", "elif dim == 3: return vmap(vmap(vmap(f, 0, 0), 0, 0),", "iter((self.allocate, self.update)) NeighborFn = Callable[[Array, Optional[NeighborList], Optional[int]], NeighborList] def neighbor_list(displacement_or_metric:", "should generally be left as False. mask_self: An optional boolean.", "mask_self: bool=False) -> Array: \"\"\"Compute a mask for neighbor list.\"\"\"", "a cell list. Returns a CellList containing the partition. \"\"\"", "isinstance(cell_capacity, int): msg = ( 'cell_capacity_or_example_positions must either be an", "box_size would not be accurately represented by an f32. if", "Array: \"\"\"Counts the number of particles per-cell in a spatial", "be set to 1.0 and the cell size used in", "by applicable law or agreed to in writing, software #", "this seems to translate into an occupancy of ~70%. We", "point positions with shape S + [spatial_dimension]. id_buffer: An ndarray", "nbrs.update(state.position) >>> state = apply_fn(state, neighbor_idx=nbrs.idx) >>> return state, nbrs", "of particle positions. neighbor_list: An optional neighor list object. If", "fixed. \"\"\" is_format_valid(format) box_size = lax.stop_gradient(box_size) r_cutoff = lax.stop_gradient(r_cutoff) dr_threshold", "< len(neighbor.reference_position) if mask_self: mask = mask & (neighbor.idx[0] !=", "data. particle_id = lax.iota(jnp.int64, N) # NOTE(schsam): We use the", "from jax import jit, vmap, eval_shape from jax.abstract_arrays import ShapedArray", "simulation will be incorrect and the simulation needs to be", "= onp.reshape(cells_per_side, (-1,)) for cells in flat_cells_per_side: if cells <", "distribution of points changes significantly it is likely the buffer", "builds a list neighbors for collections of points. Neighbor lists", "fractional coordinates in the unit cube, [0, 1]^d. If this", "_estimate_cell_capacity( cell_capacity, box_size, minimum_cell_size, buffer_size_multiplier) elif not isinstance(cell_capacity, int): msg", "dtype=jnp.int64) - 1 def _estimate_cell_capacity(R: Array, box_size: Box, cell_size: float,", "current code will be slightly less efficient. minimum_cell_size: A float", "(util.is_array(cells_per_side) and not cells_per_side.shape)): cells_per_side = (int(cells_per_side),) * dim elif", "spatially. A simple partitioning that can be implemented efficiently within", "numpy as onp from jax import lax from jax import", "\\in R^d} with associated data {k_i \\in R^m} it is", "list to dense ids. Cannot be JIT.\"\"\" if neighbor.format is", "that we will convert to the jraph format. Must be", "all have a common shape, S, where * `S =", "N), _cell_capacity) sorted_cell_id = sorted_hash * _cell_capacity + sorted_cell_id cell_R", "a new neighbor list cannot be jit compiled since it", "'Using `neighbor_fn.allocate` and `neighbor_fn.update` ' 'is preferred.') if neighbor_list is", "= ops.index_update(cell_kwargs[k], sorted_cell_id, v) cell_kwargs[k] = _unflatten_cell_buffer( cell_kwargs[k], cells_per_side, dim)", "array shapes fixed. \"\"\" is_format_valid(format) box_size = lax.stop_gradient(box_size) r_cutoff =", "= candidate_fn(R, **kwargs) if mask_self: idx = mask_self_fn(idx) if is_sparse(format):", "NeighborList], NeighborList] = dataclasses.static_field() def __call__(self, R: Array, neighbor_list: Optional[NeighborList]=None,", "more compute since often we will do a mask for", "nbrs.reference_position) > threshold_sq), (R, nbrs.did_buffer_overflow), neighbor_fn, nbrs, lambda x: x)", "we auto-cast based on box_size? I can't imagine a case", "that can be stored in each cell or an ndarray", "or format is NeighborListFormat.OrderedSparse) def is_format_valid(format: NeighborListFormat): if not format", "cell_list_fn: A static python callable that is used to construct", "\"\"\"Returns a function that builds a list neighbors for collections", "neighbor list cannot be jit compiled since it uses the", "dtype=i32) hashes = jnp.sum(indices * hash_multipliers, axis=1) # Copy the", "= R[idx] dR = d(R, neigh_R) mask = (dR <", "Should we auto-cast based on box_size? I can't imagine a", "be accurately represented by an f32. if (isinstance(box_size, onp.ndarray) and", "N)[:len(senders)] hashes = senders * max_count + offset dense_idx =", "Returns: A `jraph.GraphsTuple` that contains the topology of the neighbor", "int) -> Array: if (isinstance(cells_per_side, int) or isinstance(cells_per_side, float) or", "in cells_per_side[::-1]]) elif util.is_array(cells_per_side) and len(cells_per_side.shape) == 2: cells_per_side =", "jnp.where(mask, cumsum - 1, len(receiver_idx) - 1) receiver_idx = out_idx.at[index].set(receiver_idx)", "**kwargs) d = space.map_bond(d) N = R.shape[0] sender_idx = jnp.broadcast_to(jnp.arange(N)[:,", "if box_size.ndim == 1 or box_size.ndim == 2: assert box_size.size", "an f32. if (isinstance(box_size, onp.ndarray) and (box_size.dtype == jnp.int32 or", "cell_kwargs[k] = _unflatten_cell_buffer( cell_kwargs[k], cells_per_side, dim) return CellList(cell_R, cell_id, cell_kwargs)", "= jnp.ones((N,), jnp.int64) * N cell_R = jnp.zeros((cell_count * _cell_capacity,", "must be 2 or 3. Found {}'.format(dim)) neighborhood_tile_count = 3", "def _unflatten_cell_buffer(arr: Array, cells_per_side: Array, dim: int) -> Array: if", "occupied mask. However, that will involve # more compute since", "list. extra_capacity: Extra capacity to add if allocating the neighbor", "onp.array(box_size) if len(box_size.shape) == 1: box_size = jnp.reshape(box_size, (1, -1))", "is not None: cl = cell_list_fn(R) idx = cell_list_candidate_fn(cl, R,", "an intermediate step of the neighbor list calculation. update_fn: A", "r\"\"\"Returns a function that partitions point data spatially. Given a", "2 and dim != 3: # NOTE(schsam): Do we want", "dense_idx = N * jnp.ones((N * max_count,), jnp.int32) dense_idx =", "\"\"\"An enum listing the different neighbor list formats. Attributes: Dense:", "**kwargs), lambda R, nbrs, **kwargs: # pytype: disable=wrong-arg-count neighbor_list_fn(R, nbrs,", "a flat list that repeats 0, .., cell_capacity. So long", "= R.shape R = cl.position_buffer idx = cl.id_buffer cell_idx =", "max_occupancy = cumsum[-1] return jnp.stack((receiver_idx[:-1], sender_idx[:-1])), max_occupancy def neighbor_list_fn(R: Array,", "senders=senders, globals=None, n_node=jnp.array([N, 1]), n_edge=jnp.array([jnp.sum(_mask), jnp.sum(~_mask)]), ) def to_dense(neighbor: NeighborList)", "= jnp.cumsum(mask) index = jnp.where(mask, cumsum - 1, len(receiver_idx) -", "1 Args: displacement: A function `d(R_a, R_b)` that computes the", "can make this more efficient by shrinking the verlet list", "max_occupancy > R.shape[0] and not is_sparse(format): max_occupancy = R.shape[0] padding", "else: cell_list_fn = nbrs.cell_list_fn neighbor_fn = partial(neighbor_fn, max_occupancy=nbrs.max_occupancy) d =", "cell_size, dtype=jnp.int64) particle_hash = jnp.sum(particle_index * hash_multipliers, axis=1) filling =", "that only `neighbor_list_fn(R, neighbor_list)` can be `jit` since it keeps", "max_neighbors this is set to true to indicate that there", "3: raise ValueError( ('Box must be at least 3x the", "receivers[mask] senders = senders[mask] N = len(neighbor.reference_position) count = ops.segment_sum(jnp.ones(len(receivers),", "nbrs.did_buffer_overflow: >>> nbrs = neighbor_fn.allocate(state.position) >>> else: >>> state =", "matrix of shape `(2, max_neighbors)` specifying the start / end", "# this we first sort particles by their cell hash.", "size of the box or an array of shape [spatial_dim]", "applicable law or agreed to in writing, software # distributed", "v.ndim == 1: v = jnp.reshape(v, v.shape + (1,)) cell_kwargs[k]", "list was constructed. This is used to decide whether the", "through the calculation of example positions. Returns: A pair. The", "cell_size, cells_per_side, cell_count = \\ _cell_dimensions(dim, box_size, minimum_cell_size) hash_multipliers =", "(-1,) + arr.shape[1:]) def _shift_array(arr: onp.ndarray, dindex: Array) -> Array:", "did_buffer_overflow: Array max_occupancy: int = dataclasses.static_field() format: NeighborListFormat = dataclasses.static_field()", "-> bool: return (format is NeighborListFormat.Sparse or format is NeighborListFormat.OrderedSparse)", "that particles that are successfully, # copied have their true", "Either a float specifying the size of the box or", "dindex)] cell_idx = jnp.concatenate(cell_idx, axis=-2) cell_idx = cell_idx[..., jnp.newaxis, :,", "**static_kwargs) -> NeighborFn: \"\"\"Returns a function that builds a list", "Box, minimum_cell_size: float) -> Array: \"\"\"Counts the number of particles", "jnp.logical_or(overflow, (max_occupancy < occupancy)), max_occupancy, format, cell_list_fn, update_fn) # pytype:", "neighbor_list_fn(R, extra_capacity=extra_capacity, **kwargs), lambda R, nbrs, **kwargs: # pytype: disable=wrong-arg-count", "from jax_md import quantity, space, dataclasses, util import jraph #", "that will be used ' 'to estimate a cell capacity.", "to have a cell id = hash * cell_capacity +", "particle_index = jnp.array(R / cell_size, dtype=jnp.int64) particle_hash = jnp.sum(particle_index *", "**kwargs: space.square_distance( displacement_or_metric(Ra, Rb, **kwargs)) except TypeError: continue except ValueError:", "themselves additionally have a convenience `update` member function. Note that", "jnp.argsort(hashes) sorted_R = R[sort_map] sorted_hash = hashes[sort_map] sorted_id = particle_id[sort_map]", "neighbor list. \"\"\" allocate: Callable[..., NeighborList] = dataclasses.static_field() update: Callable[[Array,", "= out_idx.at[p_index, index].set(idx) max_occupancy = jnp.max(cumsum[:, -1]) return out_idx[:, :-1],", "Callable[[Array, NeighborList], NeighborList] = dataclasses.static_field() def __call__(self, R: Array, neighbor_list:", "not is_sparse(format) else N * extra_capacity) max_occupancy = int(occupancy *", "Callable[[Array], CellList]: r\"\"\"Returns a function that partitions point data spatially.", "self.update_fn(R, self, **kwargs) @dataclasses.dataclass class NeighborListFns: \"\"\"A struct containing functions", "= neighbor.idx < len(neighbor.idx) if mask_self: N = len(neighbor.reference_position) self_mask", "S + [spatial_dimension]. id_buffer: An ndarray of int32 particle ids", "for d in range(spatial_dimension)]], dtype=jnp.int64) elif cells_per_side.size == spatial_dimension: one", "neighbor_fn((R, False)) else: cell_list_fn = nbrs.cell_list_fn neighbor_fn = partial(neighbor_fn, max_occupancy=nbrs.max_occupancy)", "jnp.int32) dense_idx = dense_idx.at[hashes].set(receivers).reshape((N, max_count)) return dense_idx Dense = NeighborListFormat.Dense", "isinstance(box_size, float): box_size = float(box_size) # NOTE(schsam): Should we auto-cast", "cell_capacity_or_example_R: Union[int, Array], buffer_size_multiplier: float=1.1 ) -> Callable[[Array], CellList]: r\"\"\"Returns", "to design around this empty_data_value # for now and revisit", "or an ndarray of positions of shape [particle_count, spatial_dimension] that", "\"\"\"Stores the spatial partition of a system into a cell", "[...]. This contains side data placed into the cell list.", "' 'lists. It will be removed in a later version", "allocation of a new neighbor list cannot be jit compiled", "of points. box_size: Either a float specifying the size of", "R[receiver_idx]) mask = (dR < cutoff_sq) & (receiver_idx < N)", "as an ndarry. Found \"{}\" with ' 'type {}'.format(k, type(v))))", "it will update the neighbor list (with fixed capacity) if", "use_cell_list = jnp.all(cell_size < box_size / 3.) and not disable_cell_list", "neighbor_idx = copy_values_from_cell(neighbor_idx, cell_idx, idx) return neighbor_idx[:-1, :, 0] @jit", "# You may obtain a copy of the License at", "= jnp.concatenate((arr[:, :, -1:], arr[:, :, :-1]), axis=2) return arr", "jnp.reshape(v, v.shape + (1,)) cell_kwargs[k] = ops.index_update(cell_kwargs[k], sorted_cell_id, v) cell_kwargs[k]", "when the neighbor list was constructed. This is used to", "with shape {}'.format(k, v.shape))) kwarg_shape = v.shape[1:] if v.ndim >", "= [idx] for dindex in _neighboring_cells(dim): if onp.all(dindex == 0):", "that is used to estimate the cell_capacity. buffer_size_multiplier: A floating", "spatial_dimension return box_size, cell_size, cells_per_side, int(cell_count) def count_cell_filling(R: Array, box_size:", "Returns: A pair. The first element is a NeighborList containing", "elif not isinstance(cell_capacity, int): msg = ( 'cell_capacity_or_example_positions must either", "can be `jit` since it keeps array shapes fixed. \"\"\"", "in maximum neighborhood occupancy we allocate compared with the maximum", "than just # computing everything. neighbor_idx = jnp.zeros((N + 1,)", "containing the partition. \"\"\" if util.is_array(box_size): box_size = onp.array(box_size) if", "the jth neighbor of particle i. reference_position: The positions of", "object that contains two functions: 1) `neighbor_fn.allocate` create a new", "the issue if it comes up later. empty_kwarg_value = 10", "+= 1 Args: displacement: A function `d(R_a, R_b)` that computes", "jnp.broadcast_to(jnp.reshape(jnp.arange(R.shape[0]), (1, R.shape[0])), (R.shape[0], R.shape[0])) @jit def cell_list_candidate_fn(cl, R, **kwargs):", "max_count,), jnp.int32) dense_idx = dense_idx.at[hashes].set(receivers).reshape((N, max_count)) return dense_idx Dense =", "JAX MD. ' 'Using `neighbor_fn.allocate` and `neighbor_fn.update` ' 'is preferred.')", "the ids are a rectangular matrix of shape `(2, max_neighbors)`", "positions will be supplied in fractional coordinates in the unit", "else: raise ValueError() def _neighboring_cells(dimension: int) -> Generator[onp.ndarray, None, None]:", "Changing this will invoke a recompilation. format: A NeighborListFormat enum", "**kwargs) else: idx = candidate_fn(R, **kwargs) if mask_self: idx =", "maximum distance particles can move before rebuilding the neighbor list.", "scalar specifying the neighborhood radius. dr_threshold: A scalar specifying the", "raise ValueError('Cannot convert a dense neighbor list to jraph format.", "that is unique. sort_map = jnp.argsort(hashes) sorted_R = R[sort_map] sorted_hash", "lists: >>> init_fn, apply_fn = simulate.nve(energy_fn, shift, 1e-3) >>> exact_init_fn,", "box_size = jnp.reshape(box_size, (1, -1)) if util.is_array(minimum_cell_size): minimum_cell_size = onp.array(minimum_cell_size)", "be worth adding an occupied mask. However, that will involve", "3. Found {}'.format(dim)) neighborhood_tile_count = 3 ** dim _, cell_size,", "Optional[NeighborList]=None, extra_capacity: int=0, **kwargs) -> NeighborList: nbrs = neighbor_list def", "that can be implemented efficiently within XLA is a dense", "d = partial(metric_sq, **kwargs) d = space.map_bond(d) N = R.shape[0]", "f32. if (isinstance(box_size, onp.ndarray) and (box_size.dtype == jnp.int32 or box_size.dtype", "that contains the topology of the neighbor list. \"\"\" if", "= neighbor_list def neighbor_fn(R_and_overflow, max_occupancy=None): R, overflow = R_and_overflow N", "= neighbor.idx[0] < len(neighbor.reference_position) if mask_self: mask = mask &", "list; see the NeighborListFormat enum for details about the different", "Dense: A dense neighbor list where the ids are a", "self_mask = idx == jnp.reshape(jnp.arange(idx.shape[0]), (idx.shape[0], 1)) return jnp.where(self_mask, idx.shape[0],", "sorted_kwargs.items(): if v.ndim == 1: v = jnp.reshape(v, v.shape +", "R = ShapedArray((dim,), f32) dR_or_dr = eval_shape(displacement_or_metric, R, R, t=0)", "A float specifying the minimum side length of each cell.", "themselves to be their own neighbors. fractional_coordinates: An optional boolean.", "integer specifying the size number of particles that can be", "CellList: N = R.shape[0] dim = R.shape[1] _cell_capacity = cell_capacity", "to partition the points / data spatially. A simple partitioning", "cell list. Since XLA requires that shapes be statically specified,", "space.map_bond(d) N = R.shape[0] sender_idx = jnp.broadcast_to(jnp.arange(N)[:, None], idx.shape) sender_idx", "neighbor_fn(R_and_overflow, max_occupancy=None): R, overflow = R_and_overflow N = R.shape[0] if", "= mask & (neighbor.idx[0] != neighbor.idx[1]) return mask mask =", "(1, -1)) if util.is_array(minimum_cell_size): minimum_cell_size = onp.array(minimum_cell_size) cell_capacity = cell_capacity_or_example_R", "= {} for k, v in kwargs.items(): if not util.is_array(v):", "def _is_variable_compatible_with_positions(R: Array) -> bool: if (util.is_array(R) and len(R.shape) ==", "(cell_count * _cell_capacity,) + kwarg_shape, v.dtype) indices = jnp.array(R /", "_cell_dimensions(dim, box_size, minimum_cell_size) hash_multipliers = _compute_hash_constants(dim, cells_per_side) particle_index = jnp.array(R", "not format in list(NeighborListFormat): raise ValueError(( 'Neighbor list format must", "`S = [cell_count_x, cell_count_y, cell_count_z, cell_capacity]` in two- and three-dimensions", "to dense ids. Cannot be JIT.\"\"\" if neighbor.format is not", "/ end particle of each neighbor pair. OrderedSparse: A sparse", "ndarray of int32 particle ids of shape S. Note that", "/ box_size box_size = f32(1) use_cell_list = jnp.all(cell_size < box_size", "neighbors (along with additional space specified by the `capacity_multiplier`). Updating", "nbrs = state >>> nbrs = nbrs.update(state.position) >>> state =", "that builds a list neighbors for collections of points. Neighbor", "array of particle positions. neighbor_list: An optional neighor list object.", "contains a function `neighbor_list_fn(R, neighbor_list=None)` that will update the neighbor", "a new set of positions and a new neighbor list.", "= lax.stop_gradient(box_size) r_cutoff = lax.stop_gradient(r_cutoff) dr_threshold = lax.stop_gradient(dr_threshold) box_size =", "\"\"\" position_buffer: Array id_buffer: Array kwarg_buffers: Dict[str, Array] def _cell_dimensions(spatial_dimension:", "idx) @jit def prune_neighbor_list_dense(R, idx, **kwargs): d = partial(metric_sq, **kwargs)", "per cell, each particle is guarenteed # to get a", "must balance the need to be jit compatable with the", "idx, **kwargs) else: idx, occupancy = prune_neighbor_list_dense(R, idx, **kwargs) if", "Optional, Dict, Tuple, Generator, Union import math from operator import", "of cells in a box.\"\"\" if isinstance(box_size, int) or isinstance(box_size,", "dindex in onp.ndindex(*([3] * dimension)): yield onp.array(dindex, dtype=jnp.int64) - 1", "'cell_capacity_or_example_positions must either be an integer ' 'specifying the cell", "0: arr = jnp.concatenate((arr[1:], arr[:1])) elif dx > 0: arr", "be updated. did_buffer_overflow: A boolean that starts out False. If", "is used to construct a cell list used in an", "We then assign each # particle to have a cell", "to be jit compatable with the fact that under a", "\"\"\"Code to transform functions on individual tuples of particles to", "int, cells_per_side: Array) -> Array: if cells_per_side.size == 1: return", "specifying the format of the neighbor list. cell_list_fn: A static", "/ box_size. format: The format of the neighbor list; see", "array of shape # [N, output_dimension] which ignores the empty", "set to True then the neighbor list is constructed using", "= neighbor_list_mask(neighbor) receivers = receivers[mask] senders = senders[mask] N =", "dtype=jnp.int64) else: raise ValueError() def _neighboring_cells(dimension: int) -> Generator[onp.ndarray, None,", "-> Array: \"\"\"Compute a mask for neighbor list.\"\"\" if is_sparse(neighbor.format):", "buffer_size_multiplier) elif not isinstance(cell_capacity, int): msg = ( 'cell_capacity_or_example_positions must", "integer specifying the maximum size of the neighbor list. Changing", "\"License\"); # you may not use this file except in", "_vectorize(f: Callable, dim: int) -> Callable: if dim == 2:", "everything. neighbor_idx = jnp.zeros((N + 1,) + cell_idx.shape[-2:], jnp.int32) neighbor_idx", "ones.') receivers, senders = neighbor.idx mask = neighbor_list_mask(neighbor) receivers =", "return jnp.reshape(arr, cells_per_side + (-1,) + arr.shape[1:]) def _shift_array(arr: onp.ndarray,", "N = len(neighbor.reference_position) count = ops.segment_sum(jnp.ones(len(receivers), jnp.int32), receivers, N) max_count", "Attributes: Dense: A dense neighbor list where the ids are", "R_and_overflow N = R.shape[0] if cell_list_fn is not None: cl", "`capacity_multiplier`). Updating the neighbor list can be jit compiled; if", "**kwargs): d = partial(metric_sq, **kwargs) d = space.map_neighbor(d) N =", "is None: cell_list_fn = (cell_list(box_size, cell_size, R, capacity_multiplier) if use_cell_list", "R.shape[0]: raise ValueError( ('Data must be specified per-particle (an ndarray", "# pytype: disable=wrong-arg-count neighbor_list_fn(R, nbrs, **kwargs)) def neighbor_list_mask(neighbor: NeighborList, mask_self:", "`neighbor_fn.allocate` create a new neighbor list and 2) `neighbor_fn.update` updates", "to translate into an occupancy of ~70%. We # can", "jnp.cumsum(mask) index = jnp.where(mask, cumsum - 1, len(receiver_idx) - 1)", "now and revisit the issue if it comes up later.", "mask_self: N = len(neighbor.reference_position) self_mask = neighbor.idx != jnp.reshape(jnp.arange(N), (N,", "A function `d(R_a, R_b)` that computes the displacement between pairs", "onp.ndarray) and (box_size.dtype == jnp.int32 or box_size.dtype == jnp.int64)): box_size", "minimum_cell_size) cell_size = box_size / cells_per_side cells_per_side = onp.array(cells_per_side, dtype=jnp.int64)", "a vector.') else: cell_count = cells_per_side ** spatial_dimension return box_size,", "distances. This can be useful for debugging but should generally", "jnp.array([[1]], dtype=jnp.int32) cells_per_side = jnp.concatenate((one, cells_per_side[:, :-1]), axis=1) return jnp.array(jnp.cumprod(cells_per_side),", "(along with additional space specified by the `capacity_multiplier`). Updating the", "the need to be jit compatable with the fact that", "the neighbor list; see the NeighborListFormat enum for details about", "if max_occupancy > occupancy: idx = jnp.concatenate( [idx, N *", "== 1: return jnp.array([[cells_per_side ** d for d in range(spatial_dimension)]],", "Cell list buffers all have a common shape, S, where", "neighbor_fn, nbrs, lambda x: x) return NeighborListFns(lambda R, extra_capacity=0, **kwargs:", "output_dimension] and then truncate it to an array of shape", "requires that shapes be statically specified, we allocate fixed sized", "`Sparse` where only bonds with i < j are included.", "to store all the neighbors, the `did_buffer_overflow` bit will be", "adding a ficticious graph with a single node. Args: neighbor:", "whether or not a displacement or metric was provided.\"\"\" for", "update_fn: Callable[[Array, 'NeighborList'], 'NeighborList'] = dataclasses.static_field() def update(self, R, **kwargs):", "CellList: \"\"\"Stores the spatial partition of a system into a", "optional boolean. Determines whether points can consider themselves to be", "for parallelizing simulations over different accelerators. Args: box_size: A float", ">>> for _ in range(20): >>> new_state, nbrs = lax.fori_loop(0,", "size of the system. Note, this code is written for", "formats. Attributes: Dense: A dense neighbor list where the ids", "= 1 OrderedSparse = 2 def is_sparse(format: NeighborListFormat) -> bool:", "= nbrs.update(state.position) >>> state = apply_fn(state, neighbor_idx=nbrs.idx) >>> return state,", "cell_capacity]` * `S = [cell_count_x, cell_count_y, cell_count_z, cell_capacity]` in two-" ]
[ "rhucrl_experiments.evaluate.utilities import ENVIRONMENTS RARL_DIR = \"../../runs/RARLAgent\" ZERO_SUM_DIR = \"../../runs/ZeroSumAgent\" SCRIPT", "\"RHUCRL\", \"base-dir\": ZERO_SUM_DIR}, \"lazy\": {\"algorithm\": \"HUCRL\", \"base-dir\": RARL_DIR}, }.get(socket.gethostname(), {\"algorithm\":", "RARL_DIR}, }.get(socket.gethostname(), {\"algorithm\": \"RARL\", \"base-dir\": RARL_DIR}) runner = init_runner(\"EvaluateMassChange.\", num_threads=4)", "EXPERIMENTS = { \"supermodularity\": {\"algorithm\": \"RARL_MF\", \"base-dir\": RARL_DIR}, \"shallow\": {\"algorithm\":", "base_args.update(**EXPERIMENTS) commands = make_commands( SCRIPT, base_args=base_args, common_hyper_args={\"environment\": ENVIRONMENTS} ) runner.run_batch(commands)", "<filename>rhucrl_experiments/evaluate/launch_evaluate_mass.py<gh_stars>1-10 \"\"\"Run from rhucrl_experiments.evaluate folder.\"\"\" import socket from lsf_runner import", "}.get(socket.gethostname(), {\"algorithm\": \"RARL\", \"base-dir\": RARL_DIR}) runner = init_runner(\"EvaluateMassChange.\", num_threads=4) for", "\"seed\": seed} base_args.update(**EXPERIMENTS) commands = make_commands( SCRIPT, base_args=base_args, common_hyper_args={\"environment\": ENVIRONMENTS}", "\"supermodularity\": {\"algorithm\": \"RARL_MF\", \"base-dir\": RARL_DIR}, \"shallow\": {\"algorithm\": \"RHUCRL\", \"base-dir\": ZERO_SUM_DIR},", "= \"evaluate_mass_change.py\" EXPERIMENTS = { \"supermodularity\": {\"algorithm\": \"RARL_MF\", \"base-dir\": RARL_DIR},", "import init_runner, make_commands from rhucrl_experiments.evaluate.utilities import ENVIRONMENTS RARL_DIR = \"../../runs/RARLAgent\"", "\"../../runs/RARLAgent\" ZERO_SUM_DIR = \"../../runs/ZeroSumAgent\" SCRIPT = \"evaluate_mass_change.py\" EXPERIMENTS = {", "\"HUCRL\", \"base-dir\": RARL_DIR}, }.get(socket.gethostname(), {\"algorithm\": \"RARL\", \"base-dir\": RARL_DIR}) runner =", "ZERO_SUM_DIR}, \"greedy\": {\"algorithm\": \"RHUCRL\", \"base-dir\": ZERO_SUM_DIR}, \"lazy\": {\"algorithm\": \"HUCRL\", \"base-dir\":", "= {\"num-runs\": 10, \"seed\": seed} base_args.update(**EXPERIMENTS) commands = make_commands( SCRIPT,", "ZERO_SUM_DIR = \"../../runs/ZeroSumAgent\" SCRIPT = \"evaluate_mass_change.py\" EXPERIMENTS = { \"supermodularity\":", "RARL_DIR = \"../../runs/RARLAgent\" ZERO_SUM_DIR = \"../../runs/ZeroSumAgent\" SCRIPT = \"evaluate_mass_change.py\" EXPERIMENTS", "init_runner, make_commands from rhucrl_experiments.evaluate.utilities import ENVIRONMENTS RARL_DIR = \"../../runs/RARLAgent\" ZERO_SUM_DIR", "= init_runner(\"EvaluateMassChange.\", num_threads=4) for seed in [0, 1, 2, 3,", "2, 3, 4]: base_args = {\"num-runs\": 10, \"seed\": seed} base_args.update(**EXPERIMENTS)", "{\"num-runs\": 10, \"seed\": seed} base_args.update(**EXPERIMENTS) commands = make_commands( SCRIPT, base_args=base_args,", "from rhucrl_experiments.evaluate folder.\"\"\" import socket from lsf_runner import init_runner, make_commands", "num_threads=4) for seed in [0, 1, 2, 3, 4]: base_args", "ENVIRONMENTS RARL_DIR = \"../../runs/RARLAgent\" ZERO_SUM_DIR = \"../../runs/ZeroSumAgent\" SCRIPT = \"evaluate_mass_change.py\"", "= \"../../runs/RARLAgent\" ZERO_SUM_DIR = \"../../runs/ZeroSumAgent\" SCRIPT = \"evaluate_mass_change.py\" EXPERIMENTS =", "{\"algorithm\": \"RARL_MF\", \"base-dir\": RARL_DIR}, \"shallow\": {\"algorithm\": \"RHUCRL\", \"base-dir\": ZERO_SUM_DIR}, \"greedy\":", "\"RHUCRL\", \"base-dir\": ZERO_SUM_DIR}, \"greedy\": {\"algorithm\": \"RHUCRL\", \"base-dir\": ZERO_SUM_DIR}, \"lazy\": {\"algorithm\":", "runner = init_runner(\"EvaluateMassChange.\", num_threads=4) for seed in [0, 1, 2,", "from rhucrl_experiments.evaluate.utilities import ENVIRONMENTS RARL_DIR = \"../../runs/RARLAgent\" ZERO_SUM_DIR = \"../../runs/ZeroSumAgent\"", "{ \"supermodularity\": {\"algorithm\": \"RARL_MF\", \"base-dir\": RARL_DIR}, \"shallow\": {\"algorithm\": \"RHUCRL\", \"base-dir\":", "make_commands from rhucrl_experiments.evaluate.utilities import ENVIRONMENTS RARL_DIR = \"../../runs/RARLAgent\" ZERO_SUM_DIR =", "from lsf_runner import init_runner, make_commands from rhucrl_experiments.evaluate.utilities import ENVIRONMENTS RARL_DIR", "import socket from lsf_runner import init_runner, make_commands from rhucrl_experiments.evaluate.utilities import", "in [0, 1, 2, 3, 4]: base_args = {\"num-runs\": 10,", "1, 2, 3, 4]: base_args = {\"num-runs\": 10, \"seed\": seed}", "base_args = {\"num-runs\": 10, \"seed\": seed} base_args.update(**EXPERIMENTS) commands = make_commands(", "\"base-dir\": RARL_DIR}, }.get(socket.gethostname(), {\"algorithm\": \"RARL\", \"base-dir\": RARL_DIR}) runner = init_runner(\"EvaluateMassChange.\",", "seed} base_args.update(**EXPERIMENTS) commands = make_commands( SCRIPT, base_args=base_args, common_hyper_args={\"environment\": ENVIRONMENTS} )", "folder.\"\"\" import socket from lsf_runner import init_runner, make_commands from rhucrl_experiments.evaluate.utilities", "{\"algorithm\": \"RARL\", \"base-dir\": RARL_DIR}) runner = init_runner(\"EvaluateMassChange.\", num_threads=4) for seed", "\"../../runs/ZeroSumAgent\" SCRIPT = \"evaluate_mass_change.py\" EXPERIMENTS = { \"supermodularity\": {\"algorithm\": \"RARL_MF\",", "{\"algorithm\": \"RHUCRL\", \"base-dir\": ZERO_SUM_DIR}, \"lazy\": {\"algorithm\": \"HUCRL\", \"base-dir\": RARL_DIR}, }.get(socket.gethostname(),", "\"base-dir\": RARL_DIR}) runner = init_runner(\"EvaluateMassChange.\", num_threads=4) for seed in [0,", "= \"../../runs/ZeroSumAgent\" SCRIPT = \"evaluate_mass_change.py\" EXPERIMENTS = { \"supermodularity\": {\"algorithm\":", "seed in [0, 1, 2, 3, 4]: base_args = {\"num-runs\":", "\"base-dir\": ZERO_SUM_DIR}, \"lazy\": {\"algorithm\": \"HUCRL\", \"base-dir\": RARL_DIR}, }.get(socket.gethostname(), {\"algorithm\": \"RARL\",", "socket from lsf_runner import init_runner, make_commands from rhucrl_experiments.evaluate.utilities import ENVIRONMENTS", "4]: base_args = {\"num-runs\": 10, \"seed\": seed} base_args.update(**EXPERIMENTS) commands =", "{\"algorithm\": \"HUCRL\", \"base-dir\": RARL_DIR}, }.get(socket.gethostname(), {\"algorithm\": \"RARL\", \"base-dir\": RARL_DIR}) runner", "\"evaluate_mass_change.py\" EXPERIMENTS = { \"supermodularity\": {\"algorithm\": \"RARL_MF\", \"base-dir\": RARL_DIR}, \"shallow\":", "\"base-dir\": RARL_DIR}, \"shallow\": {\"algorithm\": \"RHUCRL\", \"base-dir\": ZERO_SUM_DIR}, \"greedy\": {\"algorithm\": \"RHUCRL\",", "{\"algorithm\": \"RHUCRL\", \"base-dir\": ZERO_SUM_DIR}, \"greedy\": {\"algorithm\": \"RHUCRL\", \"base-dir\": ZERO_SUM_DIR}, \"lazy\":", "\"\"\"Run from rhucrl_experiments.evaluate folder.\"\"\" import socket from lsf_runner import init_runner,", "\"RARL_MF\", \"base-dir\": RARL_DIR}, \"shallow\": {\"algorithm\": \"RHUCRL\", \"base-dir\": ZERO_SUM_DIR}, \"greedy\": {\"algorithm\":", "RARL_DIR}, \"shallow\": {\"algorithm\": \"RHUCRL\", \"base-dir\": ZERO_SUM_DIR}, \"greedy\": {\"algorithm\": \"RHUCRL\", \"base-dir\":", "\"lazy\": {\"algorithm\": \"HUCRL\", \"base-dir\": RARL_DIR}, }.get(socket.gethostname(), {\"algorithm\": \"RARL\", \"base-dir\": RARL_DIR})", "\"greedy\": {\"algorithm\": \"RHUCRL\", \"base-dir\": ZERO_SUM_DIR}, \"lazy\": {\"algorithm\": \"HUCRL\", \"base-dir\": RARL_DIR},", "\"RARL\", \"base-dir\": RARL_DIR}) runner = init_runner(\"EvaluateMassChange.\", num_threads=4) for seed in", "init_runner(\"EvaluateMassChange.\", num_threads=4) for seed in [0, 1, 2, 3, 4]:", "10, \"seed\": seed} base_args.update(**EXPERIMENTS) commands = make_commands( SCRIPT, base_args=base_args, common_hyper_args={\"environment\":", "[0, 1, 2, 3, 4]: base_args = {\"num-runs\": 10, \"seed\":", "SCRIPT = \"evaluate_mass_change.py\" EXPERIMENTS = { \"supermodularity\": {\"algorithm\": \"RARL_MF\", \"base-dir\":", "= { \"supermodularity\": {\"algorithm\": \"RARL_MF\", \"base-dir\": RARL_DIR}, \"shallow\": {\"algorithm\": \"RHUCRL\",", "for seed in [0, 1, 2, 3, 4]: base_args =", "import ENVIRONMENTS RARL_DIR = \"../../runs/RARLAgent\" ZERO_SUM_DIR = \"../../runs/ZeroSumAgent\" SCRIPT =", "\"base-dir\": ZERO_SUM_DIR}, \"greedy\": {\"algorithm\": \"RHUCRL\", \"base-dir\": ZERO_SUM_DIR}, \"lazy\": {\"algorithm\": \"HUCRL\",", "ZERO_SUM_DIR}, \"lazy\": {\"algorithm\": \"HUCRL\", \"base-dir\": RARL_DIR}, }.get(socket.gethostname(), {\"algorithm\": \"RARL\", \"base-dir\":", "rhucrl_experiments.evaluate folder.\"\"\" import socket from lsf_runner import init_runner, make_commands from", "3, 4]: base_args = {\"num-runs\": 10, \"seed\": seed} base_args.update(**EXPERIMENTS) commands", "lsf_runner import init_runner, make_commands from rhucrl_experiments.evaluate.utilities import ENVIRONMENTS RARL_DIR =", "RARL_DIR}) runner = init_runner(\"EvaluateMassChange.\", num_threads=4) for seed in [0, 1,", "\"shallow\": {\"algorithm\": \"RHUCRL\", \"base-dir\": ZERO_SUM_DIR}, \"greedy\": {\"algorithm\": \"RHUCRL\", \"base-dir\": ZERO_SUM_DIR}," ]
[ "TagKeyStatus class ProjectTagsEndpoint(ProjectEndpoint): def get(self, request, project): tag_keys = TagKey.objects.filter(", ") data = [] for tag_key in tag_keys: data.append({ 'id':", "status=TagKeyStatus.VISIBLE, ) data = [] for tag_key in tag_keys: data.append({", "six from rest_framework.response import Response from sentry.api.bases.project import ProjectEndpoint from", "tag_key in tag_keys: data.append({ 'id': six.text_type(tag_key.id), 'key': TagKey.get_standardized_key(tag_key.key), 'name': tag_key.get_label(),", "ProjectTagsEndpoint(ProjectEndpoint): def get(self, request, project): tag_keys = TagKey.objects.filter( project=project, status=TagKeyStatus.VISIBLE,", "[] for tag_key in tag_keys: data.append({ 'id': six.text_type(tag_key.id), 'key': TagKey.get_standardized_key(tag_key.key),", "from __future__ import absolute_import import six from rest_framework.response import Response", "<filename>src/sentry/api/endpoints/project_tags.py from __future__ import absolute_import import six from rest_framework.response import", "get(self, request, project): tag_keys = TagKey.objects.filter( project=project, status=TagKeyStatus.VISIBLE, ) data", "TagKey.objects.filter( project=project, status=TagKeyStatus.VISIBLE, ) data = [] for tag_key in", "class ProjectTagsEndpoint(ProjectEndpoint): def get(self, request, project): tag_keys = TagKey.objects.filter( project=project,", "from rest_framework.response import Response from sentry.api.bases.project import ProjectEndpoint from sentry.models", "request, project): tag_keys = TagKey.objects.filter( project=project, status=TagKeyStatus.VISIBLE, ) data =", "project=project, status=TagKeyStatus.VISIBLE, ) data = [] for tag_key in tag_keys:", "data = [] for tag_key in tag_keys: data.append({ 'id': six.text_type(tag_key.id),", "import TagKey, TagKeyStatus class ProjectTagsEndpoint(ProjectEndpoint): def get(self, request, project): tag_keys", "project): tag_keys = TagKey.objects.filter( project=project, status=TagKeyStatus.VISIBLE, ) data = []", "import absolute_import import six from rest_framework.response import Response from sentry.api.bases.project", "six.text_type(tag_key.id), 'key': TagKey.get_standardized_key(tag_key.key), 'name': tag_key.get_label(), 'uniqueValues': tag_key.values_seen, }) return Response(data)", "data.append({ 'id': six.text_type(tag_key.id), 'key': TagKey.get_standardized_key(tag_key.key), 'name': tag_key.get_label(), 'uniqueValues': tag_key.values_seen, })", "from sentry.models import TagKey, TagKeyStatus class ProjectTagsEndpoint(ProjectEndpoint): def get(self, request,", "tag_keys: data.append({ 'id': six.text_type(tag_key.id), 'key': TagKey.get_standardized_key(tag_key.key), 'name': tag_key.get_label(), 'uniqueValues': tag_key.values_seen,", "'id': six.text_type(tag_key.id), 'key': TagKey.get_standardized_key(tag_key.key), 'name': tag_key.get_label(), 'uniqueValues': tag_key.values_seen, }) return", "import six from rest_framework.response import Response from sentry.api.bases.project import ProjectEndpoint", "TagKey, TagKeyStatus class ProjectTagsEndpoint(ProjectEndpoint): def get(self, request, project): tag_keys =", "sentry.models import TagKey, TagKeyStatus class ProjectTagsEndpoint(ProjectEndpoint): def get(self, request, project):", "ProjectEndpoint from sentry.models import TagKey, TagKeyStatus class ProjectTagsEndpoint(ProjectEndpoint): def get(self,", "import ProjectEndpoint from sentry.models import TagKey, TagKeyStatus class ProjectTagsEndpoint(ProjectEndpoint): def", "__future__ import absolute_import import six from rest_framework.response import Response from", "tag_keys = TagKey.objects.filter( project=project, status=TagKeyStatus.VISIBLE, ) data = [] for", "= TagKey.objects.filter( project=project, status=TagKeyStatus.VISIBLE, ) data = [] for tag_key", "Response from sentry.api.bases.project import ProjectEndpoint from sentry.models import TagKey, TagKeyStatus", "import Response from sentry.api.bases.project import ProjectEndpoint from sentry.models import TagKey,", "sentry.api.bases.project import ProjectEndpoint from sentry.models import TagKey, TagKeyStatus class ProjectTagsEndpoint(ProjectEndpoint):", "rest_framework.response import Response from sentry.api.bases.project import ProjectEndpoint from sentry.models import", "in tag_keys: data.append({ 'id': six.text_type(tag_key.id), 'key': TagKey.get_standardized_key(tag_key.key), 'name': tag_key.get_label(), 'uniqueValues':", "= [] for tag_key in tag_keys: data.append({ 'id': six.text_type(tag_key.id), 'key':", "def get(self, request, project): tag_keys = TagKey.objects.filter( project=project, status=TagKeyStatus.VISIBLE, )", "for tag_key in tag_keys: data.append({ 'id': six.text_type(tag_key.id), 'key': TagKey.get_standardized_key(tag_key.key), 'name':", "from sentry.api.bases.project import ProjectEndpoint from sentry.models import TagKey, TagKeyStatus class", "absolute_import import six from rest_framework.response import Response from sentry.api.bases.project import" ]
[ "try: async_eel.init('web') await async_eel.start('callbacks.html', size=(400, 300)) # Call Javascript function,", "function, and pass explicit callback function await async_eel.js_random()(print_num) # Do", "asyncio loop = asyncio.get_event_loop() @async_eel.expose async def py_random(): return random.random()", "import random import asyncio loop = asyncio.get_event_loop() @async_eel.expose async def", "Py2/3 compatibility import async_eel import random import asyncio loop =", "print_num(n): \"\"\"callback of js_random\"\"\" print('Got this from Javascript:', n) async", "size=(400, 300)) # Call Javascript function, and pass explicit callback", "loop = asyncio.get_event_loop() @async_eel.expose async def py_random(): return random.random() async", "await async_eel.start('callbacks.html', size=(400, 300)) # Call Javascript function, and pass", "def main(): try: async_eel.init('web') await async_eel.start('callbacks.html', size=(400, 300)) # Call", "random.random() async def print_num(n): \"\"\"callback of js_random\"\"\" print('Got this from", "from Javascript:', n) async def main(): try: async_eel.init('web') await async_eel.start('callbacks.html',", "300)) # Call Javascript function, and pass explicit callback function", "n)) except Exception: import traceback traceback.print_exc() if __name__ == '__main__':", "callback await async_eel.js_random()(lambda n: print('2Got this from Javascript:', n)) except", "# Do the same with an inline callback await async_eel.js_random()(lambda", "compatibility import async_eel import random import asyncio loop = asyncio.get_event_loop()", "asyncio.get_event_loop() @async_eel.expose async def py_random(): return random.random() async def print_num(n):", "the same with an inline callback await async_eel.js_random()(lambda n: print('2Got", "Javascript function, and pass explicit callback function await async_eel.js_random()(print_num) #", "this from Javascript:', n)) except Exception: import traceback traceback.print_exc() if", "await async_eel.js_random()(lambda n: print('2Got this from Javascript:', n)) except Exception:", "await async_eel.js_random()(print_num) # Do the same with an inline callback", "Call Javascript function, and pass explicit callback function await async_eel.js_random()(print_num)", "async_eel.js_random()(lambda n: print('2Got this from Javascript:', n)) except Exception: import", "def print_num(n): \"\"\"callback of js_random\"\"\" print('Got this from Javascript:', n)", "def py_random(): return random.random() async def print_num(n): \"\"\"callback of js_random\"\"\"", "function await async_eel.js_random()(print_num) # Do the same with an inline", "js_random\"\"\" print('Got this from Javascript:', n) async def main(): try:", "# For Py2/3 compatibility import async_eel import random import asyncio", "n: print('2Got this from Javascript:', n)) except Exception: import traceback", "with an inline callback await async_eel.js_random()(lambda n: print('2Got this from", "Do the same with an inline callback await async_eel.js_random()(lambda n:", "an inline callback await async_eel.js_random()(lambda n: print('2Got this from Javascript:',", "async_eel.init('web') await async_eel.start('callbacks.html', size=(400, 300)) # Call Javascript function, and", "import asyncio loop = asyncio.get_event_loop() @async_eel.expose async def py_random(): return", "from Javascript:', n)) except Exception: import traceback traceback.print_exc() if __name__", "and pass explicit callback function await async_eel.js_random()(print_num) # Do the", "same with an inline callback await async_eel.js_random()(lambda n: print('2Got this", "Javascript:', n)) except Exception: import traceback traceback.print_exc() if __name__ ==", "For Py2/3 compatibility import async_eel import random import asyncio loop", "this from Javascript:', n) async def main(): try: async_eel.init('web') await", "import async_eel import random import asyncio loop = asyncio.get_event_loop() @async_eel.expose", "of js_random\"\"\" print('Got this from Javascript:', n) async def main():", "__future__ import print_function # For Py2/3 compatibility import async_eel import", "import print_function # For Py2/3 compatibility import async_eel import random", "async def main(): try: async_eel.init('web') await async_eel.start('callbacks.html', size=(400, 300)) #", "async_eel.start('callbacks.html', size=(400, 300)) # Call Javascript function, and pass explicit", "callback function await async_eel.js_random()(print_num) # Do the same with an", "Exception: import traceback traceback.print_exc() if __name__ == '__main__': asyncio.run_coroutine_threadsafe(main(), loop)", "print('Got this from Javascript:', n) async def main(): try: async_eel.init('web')", "= asyncio.get_event_loop() @async_eel.expose async def py_random(): return random.random() async def", "return random.random() async def print_num(n): \"\"\"callback of js_random\"\"\" print('Got this", "print_function # For Py2/3 compatibility import async_eel import random import", "main(): try: async_eel.init('web') await async_eel.start('callbacks.html', size=(400, 300)) # Call Javascript", "# Call Javascript function, and pass explicit callback function await", "@async_eel.expose async def py_random(): return random.random() async def print_num(n): \"\"\"callback", "async_eel.js_random()(print_num) # Do the same with an inline callback await", "print('2Got this from Javascript:', n)) except Exception: import traceback traceback.print_exc()", "except Exception: import traceback traceback.print_exc() if __name__ == '__main__': asyncio.run_coroutine_threadsafe(main(),", "pass explicit callback function await async_eel.js_random()(print_num) # Do the same", "n) async def main(): try: async_eel.init('web') await async_eel.start('callbacks.html', size=(400, 300))", "inline callback await async_eel.js_random()(lambda n: print('2Got this from Javascript:', n))", "py_random(): return random.random() async def print_num(n): \"\"\"callback of js_random\"\"\" print('Got", "async_eel import random import asyncio loop = asyncio.get_event_loop() @async_eel.expose async", "async def py_random(): return random.random() async def print_num(n): \"\"\"callback of", "Javascript:', n) async def main(): try: async_eel.init('web') await async_eel.start('callbacks.html', size=(400,", "\"\"\"callback of js_random\"\"\" print('Got this from Javascript:', n) async def", "explicit callback function await async_eel.js_random()(print_num) # Do the same with", "import traceback traceback.print_exc() if __name__ == '__main__': asyncio.run_coroutine_threadsafe(main(), loop) loop.run_forever()", "from __future__ import print_function # For Py2/3 compatibility import async_eel", "random import asyncio loop = asyncio.get_event_loop() @async_eel.expose async def py_random():", "async def print_num(n): \"\"\"callback of js_random\"\"\" print('Got this from Javascript:'," ]
[ "is available. :param application_name: A short, alphanumeric name to identify", "logging from datacube.config import LocalConfig from datacube.drivers import index_driver_by_name, index_drivers", "%r. %s available: %s\" % ( driver_name, len(index_drivers()), ', '.join(index_drivers())", "for indexing datasets & products. \"\"\" import logging from datacube.config", "methods for indexing datasets & products. \"\"\" import logging from", "indexing datasets & products. \"\"\" import logging from datacube.config import", ":rtype: datacube.index.index.Index :raises datacube.drivers.postgres._connections.IndexSetupError: \"\"\" if local_config is None: local_config", "a Data Cube Index that can connect to a PostgreSQL", "( driver_name, len(index_drivers()), ', '.join(index_drivers()) ) ) return index_driver.connect_to_index(local_config, application_name=application_name,", "can connect to a PostgreSQL server It contains all the", ".index import Index _LOG = logging.getLogger(__name__) def index_connect(local_config=None, application_name=None, validate_connection=True):", "coding=utf-8 \"\"\" Access methods for indexing datasets & products. \"\"\"", "for %r. %s available: %s\" % ( driver_name, len(index_drivers()), ',", "use. (optional) :param validate_connection: Validate database connection and schema immediately", "if local_config is None: local_config = LocalConfig.find() driver_name = local_config.get('index_driver',", "(optional) :param validate_connection: Validate database connection and schema immediately :rtype:", "server is available. :param application_name: A short, alphanumeric name to", "and schema immediately :rtype: datacube.index.index.Index :raises datacube.drivers.postgres._connections.IndexSetupError: \"\"\" if local_config", "local_config = LocalConfig.find() driver_name = local_config.get('index_driver', 'default') index_driver = index_driver_by_name(driver_name)", "driver found for %r. %s available: %s\" % ( driver_name,", "check that the server is available. :param application_name: A short,", "from datacube.drivers import index_driver_by_name, index_drivers from .index import Index _LOG", "index_driver_by_name, index_drivers from .index import Index _LOG = logging.getLogger(__name__) def", "alphanumeric name to identify this application. :param datacube.config.LocalConfig local_config: Config", "datasets & products. \"\"\" import logging from datacube.config import LocalConfig", "connect to a PostgreSQL server It contains all the required", "\"No index driver found for %r. %s available: %s\" %", "connection parameters, but doesn't actually check that the server is", "not index_driver: raise RuntimeError( \"No index driver found for %r.", "local_config: Config object to use. (optional) :param validate_connection: Validate database", "logging.getLogger(__name__) def index_connect(local_config=None, application_name=None, validate_connection=True): # type: (LocalConfig, str, bool)", "products. \"\"\" import logging from datacube.config import LocalConfig from datacube.drivers", "str, bool) -> Index \"\"\" Create a Data Cube Index", "the required connection parameters, but doesn't actually check that the", "LocalConfig.find() driver_name = local_config.get('index_driver', 'default') index_driver = index_driver_by_name(driver_name) if not", "datacube.drivers.postgres._connections.IndexSetupError: \"\"\" if local_config is None: local_config = LocalConfig.find() driver_name", "\"\"\" Access methods for indexing datasets & products. \"\"\" import", "contains all the required connection parameters, but doesn't actually check", "server It contains all the required connection parameters, but doesn't", "type: (LocalConfig, str, bool) -> Index \"\"\" Create a Data", "schema immediately :rtype: datacube.index.index.Index :raises datacube.drivers.postgres._connections.IndexSetupError: \"\"\" if local_config is", "Cube Index that can connect to a PostgreSQL server It", "It contains all the required connection parameters, but doesn't actually", "A short, alphanumeric name to identify this application. :param datacube.config.LocalConfig", "-> Index \"\"\" Create a Data Cube Index that can", "the server is available. :param application_name: A short, alphanumeric name", "RuntimeError( \"No index driver found for %r. %s available: %s\"", ":param application_name: A short, alphanumeric name to identify this application.", "actually check that the server is available. :param application_name: A", "validate_connection=True): # type: (LocalConfig, str, bool) -> Index \"\"\" Create", "that the server is available. :param application_name: A short, alphanumeric", "import logging from datacube.config import LocalConfig from datacube.drivers import index_driver_by_name,", "required connection parameters, but doesn't actually check that the server", "Index \"\"\" Create a Data Cube Index that can connect", "datacube.drivers import index_driver_by_name, index_drivers from .index import Index _LOG =", "local_config is None: local_config = LocalConfig.find() driver_name = local_config.get('index_driver', 'default')", "Data Cube Index that can connect to a PostgreSQL server", "from datacube.config import LocalConfig from datacube.drivers import index_driver_by_name, index_drivers from", "'default') index_driver = index_driver_by_name(driver_name) if not index_driver: raise RuntimeError( \"No", "(LocalConfig, str, bool) -> Index \"\"\" Create a Data Cube", "to identify this application. :param datacube.config.LocalConfig local_config: Config object to", "def index_connect(local_config=None, application_name=None, validate_connection=True): # type: (LocalConfig, str, bool) ->", "Validate database connection and schema immediately :rtype: datacube.index.index.Index :raises datacube.drivers.postgres._connections.IndexSetupError:", "index_drivers from .index import Index _LOG = logging.getLogger(__name__) def index_connect(local_config=None,", "& products. \"\"\" import logging from datacube.config import LocalConfig from", "None: local_config = LocalConfig.find() driver_name = local_config.get('index_driver', 'default') index_driver =", "Create a Data Cube Index that can connect to a", "Config object to use. (optional) :param validate_connection: Validate database connection", "all the required connection parameters, but doesn't actually check that", "application_name=None, validate_connection=True): # type: (LocalConfig, str, bool) -> Index \"\"\"", "validate_connection: Validate database connection and schema immediately :rtype: datacube.index.index.Index :raises", "doesn't actually check that the server is available. :param application_name:", "application_name: A short, alphanumeric name to identify this application. :param", "if not index_driver: raise RuntimeError( \"No index driver found for", "raise RuntimeError( \"No index driver found for %r. %s available:", "# type: (LocalConfig, str, bool) -> Index \"\"\" Create a", "_LOG = logging.getLogger(__name__) def index_connect(local_config=None, application_name=None, validate_connection=True): # type: (LocalConfig,", "Access methods for indexing datasets & products. \"\"\" import logging", "database connection and schema immediately :rtype: datacube.index.index.Index :raises datacube.drivers.postgres._connections.IndexSetupError: \"\"\"", "local_config.get('index_driver', 'default') index_driver = index_driver_by_name(driver_name) if not index_driver: raise RuntimeError(", "= index_driver_by_name(driver_name) if not index_driver: raise RuntimeError( \"No index driver", "bool) -> Index \"\"\" Create a Data Cube Index that", "Index that can connect to a PostgreSQL server It contains", "\"\"\" Create a Data Cube Index that can connect to", "parameters, but doesn't actually check that the server is available.", "index driver found for %r. %s available: %s\" % (", "name to identify this application. :param datacube.config.LocalConfig local_config: Config object", "that can connect to a PostgreSQL server It contains all", "\"\"\" import logging from datacube.config import LocalConfig from datacube.drivers import", "is None: local_config = LocalConfig.find() driver_name = local_config.get('index_driver', 'default') index_driver", "PostgreSQL server It contains all the required connection parameters, but", "to use. (optional) :param validate_connection: Validate database connection and schema", "= LocalConfig.find() driver_name = local_config.get('index_driver', 'default') index_driver = index_driver_by_name(driver_name) if", "connection and schema immediately :rtype: datacube.index.index.Index :raises datacube.drivers.postgres._connections.IndexSetupError: \"\"\" if", "object to use. (optional) :param validate_connection: Validate database connection and", "identify this application. :param datacube.config.LocalConfig local_config: Config object to use.", "index_driver_by_name(driver_name) if not index_driver: raise RuntimeError( \"No index driver found", "= local_config.get('index_driver', 'default') index_driver = index_driver_by_name(driver_name) if not index_driver: raise", "index_driver = index_driver_by_name(driver_name) if not index_driver: raise RuntimeError( \"No index", "found for %r. %s available: %s\" % ( driver_name, len(index_drivers()),", ":param validate_connection: Validate database connection and schema immediately :rtype: datacube.index.index.Index", "index_connect(local_config=None, application_name=None, validate_connection=True): # type: (LocalConfig, str, bool) -> Index", "import index_driver_by_name, index_drivers from .index import Index _LOG = logging.getLogger(__name__)", "datacube.config import LocalConfig from datacube.drivers import index_driver_by_name, index_drivers from .index", "a PostgreSQL server It contains all the required connection parameters,", "short, alphanumeric name to identify this application. :param datacube.config.LocalConfig local_config:", "# coding=utf-8 \"\"\" Access methods for indexing datasets & products.", "import LocalConfig from datacube.drivers import index_driver_by_name, index_drivers from .index import", "driver_name, len(index_drivers()), ', '.join(index_drivers()) ) ) return index_driver.connect_to_index(local_config, application_name=application_name, validate_connection=validate_connection)", "application. :param datacube.config.LocalConfig local_config: Config object to use. (optional) :param", "import Index _LOG = logging.getLogger(__name__) def index_connect(local_config=None, application_name=None, validate_connection=True): #", "Index _LOG = logging.getLogger(__name__) def index_connect(local_config=None, application_name=None, validate_connection=True): # type:", "driver_name = local_config.get('index_driver', 'default') index_driver = index_driver_by_name(driver_name) if not index_driver:", "index_driver: raise RuntimeError( \"No index driver found for %r. %s", "%s available: %s\" % ( driver_name, len(index_drivers()), ', '.join(index_drivers()) )", "LocalConfig from datacube.drivers import index_driver_by_name, index_drivers from .index import Index", "datacube.index.index.Index :raises datacube.drivers.postgres._connections.IndexSetupError: \"\"\" if local_config is None: local_config =", "= logging.getLogger(__name__) def index_connect(local_config=None, application_name=None, validate_connection=True): # type: (LocalConfig, str,", "datacube.config.LocalConfig local_config: Config object to use. (optional) :param validate_connection: Validate", ":raises datacube.drivers.postgres._connections.IndexSetupError: \"\"\" if local_config is None: local_config = LocalConfig.find()", "\"\"\" if local_config is None: local_config = LocalConfig.find() driver_name =", "% ( driver_name, len(index_drivers()), ', '.join(index_drivers()) ) ) return index_driver.connect_to_index(local_config,", "immediately :rtype: datacube.index.index.Index :raises datacube.drivers.postgres._connections.IndexSetupError: \"\"\" if local_config is None:", "%s\" % ( driver_name, len(index_drivers()), ', '.join(index_drivers()) ) ) return", "<reponame>AMA-AC/datacube-core # coding=utf-8 \"\"\" Access methods for indexing datasets &", "this application. :param datacube.config.LocalConfig local_config: Config object to use. (optional)", "available: %s\" % ( driver_name, len(index_drivers()), ', '.join(index_drivers()) ) )", ":param datacube.config.LocalConfig local_config: Config object to use. (optional) :param validate_connection:", "to a PostgreSQL server It contains all the required connection", "available. :param application_name: A short, alphanumeric name to identify this", "from .index import Index _LOG = logging.getLogger(__name__) def index_connect(local_config=None, application_name=None,", "but doesn't actually check that the server is available. :param" ]
[ "specified\") optparser.print_usage() sys.exit(1) if opt.directory and opt.mbox: print(\"Can't specify both", "{ 'list': opt.list }) r = curs.fetchall() if len(r) !=", "reads it into the database. # import os import sys", "lib.exception import IgnorableException from lib.log import log, opstatus from lib.varnish", "listid we're working on curs.execute(\"SELECT listid FROM lists WHERE listname=%(list)s\",", "conn.close() sys.exit(1) listid = r[0][0] purges = set() if opt.directory:", "mbox formatted # file on stdin or in a file", "msgid = \"<unknown>\" log.error(\"Failed to load message (msgid %s) from", "ap.store(conn, listid) purges.update(ap.purges) if opstatus.stored: log.log(\"Stored message with message-id %s\"", "process message with given msgid') (opt, args) = optparser.parse_args() if", "'replace'), }) if __name__ == \"__main__\": optparser = OptionParser() optparser.add_option('-l',", "dies, it goes away... conn.cursor().execute(\"INSERT INTO loaderrors (listid, msgid, srctype,", "= r[0][0] purges = set() if opt.directory: # Parse all", "# import os import sys from optparse import OptionParser from", "arguments accepted\") optparser.print_usage() sys.exit(1) if not opt.list: print(\"List must be", "e) opstatus.failed += 1 continue ap.store(conn, listid) purges.update(ap.purges) if mboxparser.returncode():", "= 'need_connstr' conn = psycopg2.connect(connstr) curs = conn.cursor() # Take", "try: ap.analyze(date_override=opt.force_date) except IgnorableException as e: log_failed_message(listid, \"stdin\", \"\", ap,", "dest='filter_msgid', help='Only process message with given msgid') (opt, args) =", "'srctype': srctype, 'src': src, 'err': str(str(err), 'us-ascii', 'replace'), }) if", "except IgnorableException as e: log_failed_message(listid, \"mbox\", opt.mbox, ap, e) opstatus.failed", "ap = ArchivesParserStorage() msg = next(mboxparser) if not msg: break", "opt.directory and opt.mbox: print(\"Can't specify both directory and mbox!\") optparser.print_usage()", "connstr = 'need_connstr' conn = psycopg2.connect(connstr) curs = conn.cursor() #", "# Parse single message on stdin ap = ArchivesParserStorage() ap.parse(sys.stdin.buffer)", "ap.analyze(date_override=opt.force_date) except IgnorableException as e: log_failed_message(listid, \"stdin\", \"\", ap, e)", "- only individual messages\") optparser.print_usage() sys.exit(1) if opt.filter_msgid and not", "ArchivesParserStorage() ap.parse(sys.stdin.buffer) try: ap.analyze(date_override=opt.force_date) except IgnorableException as e: log_failed_message(listid, \"stdin\",", "is not that important and this is easier... try: curs.execute(\"SET", "of list to load message for') optparser.add_option('-d', '--directory', dest='directory', help='Load", "be parsed)') optparser.add_option('--filter-msgid', dest='filter_msgid', help='Only process message with given msgid')", "or opt.mbox) and not opt.filter_msgid: print(\"Can't use force_date with directory", "import psycopg2 from lib.storage import ArchivesParserStorage from lib.mbox import MailboxBreakupParser", "if opt.directory and opt.mbox: print(\"Can't specify both directory and mbox!\")", "\"mbox\", opt.mbox, ap, e) opstatus.failed += 1 continue ap.store(conn, listid)", "it into the database. # import os import sys from", "message with message-id %s\" % ap.msgid) conn.commit() conn.close() opstatus.print_status() VarnishPurger(cfg).purge(purges)", "sys.exit(1) ap.store(conn, listid) purges.update(ap.purges) if opstatus.stored: log.log(\"Stored message with message-id", "accepted\") optparser.print_usage() sys.exit(1) if not opt.list: print(\"List must be specified\")", "= ArchivesParserStorage() ap.parse(f) if opt.filter_msgid and not ap.is_msgid(opt.filter_msgid): continue try:", "put the data in the db. This happens in the", "psycopg2 from lib.storage import ArchivesParserStorage from lib.mbox import MailboxBreakupParser from", "as e: print((\"Failed to wait on advisory lock: %s\" %", "'msgid': msgid, 'srctype': srctype, 'src': src, 'err': str(str(err), 'us-ascii', 'replace'),", "set() if opt.directory: # Parse all files in directory for", "if not msg: break ap.parse(msg) if opt.filter_msgid and not ap.is_msgid(opt.filter_msgid):", "curs = conn.cursor() # Take an advisory lock to force", "ap.store(conn, listid) purges.update(ap.purges) if opt.interactive: print(\"Interactive mode, committing transaction\") conn.commit()", "lock: %s\" % e)) sys.exit(1) # Get the listid we're", "<filename>pgarchives/loader/load_message.py #!/usr/bin/env python3 # # load_message.py - takes a single", "ap = ArchivesParserStorage() ap.parse(sys.stdin.buffer) try: ap.analyze(date_override=opt.force_date) except IgnorableException as e:", "single email or mbox formatted # file on stdin or", "%s does not exist\" % opt.mbox) sys.exit(1) mboxparser = MailboxBreakupParser(opt.mbox)", "This happens in the main transaction # so if the", "optparser.add_option('-d', '--directory', dest='directory', help='Load all messages in directory') optparser.add_option('-m', '--mbox',", "or mbox formatted # file on stdin or in a", "'list': opt.list }) r = curs.fetchall() if len(r) != 1:", "committing transaction\") conn.commit() print(\"Proceed to next message with Enter, or", "conn = psycopg2.connect(connstr) curs = conn.cursor() # Take an advisory", "opt.filter_msgid and not ap.is_msgid(opt.filter_msgid): continue try: ap.analyze(date_override=opt.force_date) except IgnorableException as", "in the db. This happens in the main transaction #", "\"__main__\": optparser = OptionParser() optparser.add_option('-l', '--list', dest='list', help='Name of list", "listname=%(list)s\", { 'list': opt.list }) r = curs.fetchall() if len(r)", "opt.list) conn.close() sys.exit(1) listid = r[0][0] purges = set() if", "1: log.error(\"List %s not found\" % opt.list) conn.close() sys.exit(1) listid", "in directory for x in os.listdir(opt.directory): log.status(\"Parsing file %s\" %", "conn.cursor() # Take an advisory lock to force serialization. #", "import MailboxBreakupParser from lib.exception import IgnorableException from lib.log import log,", "print(\"File %s does not exist\" % opt.mbox) sys.exit(1) mboxparser =", "reordering operations and using ON CONFLICT, # but concurrency is", "= conn.cursor() # Take an advisory lock to force serialization.", "curs.fetchall() if len(r) != 1: log.error(\"List %s not found\" %", "a period (.) to stop processing\") x = input() if", "lib.varnish import VarnishPurger def log_failed_message(listid, srctype, src, msg, err): try:", "try: msgid = msg.msgid except Exception: msgid = \"<unknown>\" log.error(\"Failed", "1 continue ap.store(conn, listid) purges.update(ap.purges) if mboxparser.returncode(): log.error(\"Failed to parse", "statement_timeout='30s'\") curs.execute(\"SELECT pg_advisory_xact_lock(8059944559669076)\") except Exception as e: print((\"Failed to wait", "%(err)s)\", { 'listid': listid, 'msgid': msgid, 'srctype': srctype, 'src': src,", "e)) sys.exit(1) # Get the listid we're working on curs.execute(\"SELECT", "if __name__ == \"__main__\": optparser = OptionParser() optparser.add_option('-l', '--list', dest='list',", "lib.storage import ArchivesParserStorage from lib.mbox import MailboxBreakupParser from lib.exception import", "concurrency is not that important and this is easier... try:", "CONFLICT, # but concurrency is not that important and this", "help='Only process message with given msgid') (opt, args) = optparser.parse_args()", "data in the db. This happens in the main transaction", "srctype, src, err)) # We also put the data in", "optparser.print_usage() sys.exit(1) if opt.directory and opt.mbox: print(\"Can't specify both directory", "and mbox!\") optparser.print_usage() sys.exit(1) if opt.force_date and (opt.directory or opt.mbox)", "ap, e) conn.close() sys.exit(1) ap.store(conn, listid) purges.update(ap.purges) if opstatus.stored: log.log(\"Stored", "to force serialization. # We could do this \"properly\" by", "for') optparser.add_option('-d', '--directory', dest='directory', help='Load all messages in directory') optparser.add_option('-m',", "the whole script dies, it goes away... conn.cursor().execute(\"INSERT INTO loaderrors", "without directory or mbox!\") optparser.print_usage() sys.exit(1) log.set(opt.verbose) cfg = ConfigParser()", "given msgid') (opt, args) = optparser.parse_args() if (len(args)): print(\"No bare", "e) opstatus.failed += 1 continue ap.store(conn, listid) purges.update(ap.purges) if opt.interactive:", "1 continue ap.store(conn, listid) purges.update(ap.purges) if opt.interactive: print(\"Interactive mode, committing", "could do this \"properly\" by reordering operations and using ON", "to wait on advisory lock: %s\" % e)) sys.exit(1) #", "sys.exit(1) listid = r[0][0] purges = set() if opt.directory: #", "if opstatus.stored: log.log(\"Stored message with message-id %s\" % ap.msgid) conn.commit()", "a file and reads it into the database. # import", "%(srctype)s, %(src)s, %(err)s)\", { 'listid': listid, 'msgid': msgid, 'srctype': srctype,", "to parse mbox:\") log.error(mboxparser.stderr_output()) sys.exit(1) else: # Parse single message", "ap.parse(f) if opt.filter_msgid and not ap.is_msgid(opt.filter_msgid): continue try: ap.analyze(date_override=opt.force_date) except", "or opt.mbox): print(\"filter_msgid makes no sense without directory or mbox!\")", "not (opt.directory or opt.mbox): print(\"filter_msgid makes no sense without directory", "%s: %s\" % (msgid, srctype, src, err)) # We also", "VarnishPurger def log_failed_message(listid, srctype, src, msg, err): try: msgid =", "processing\") x = input() if x == '.': print(\"Ok, aborting!\")", "continue try: ap.analyze(date_override=opt.force_date) except IgnorableException as e: log_failed_message(listid, \"mbox\", opt.mbox,", "purges.update(ap.purges) if opstatus.stored: log.log(\"Stored message with message-id %s\" % ap.msgid)", "log.error(\"Failed to parse mbox:\") log.error(mboxparser.stderr_output()) sys.exit(1) else: # Parse single", "help='Override date (used for dates that can\\'t be parsed)') optparser.add_option('--filter-msgid',", "sys from optparse import OptionParser from configparser import ConfigParser import", "cfg = ConfigParser() cfg.read('%s/archives.ini' % os.path.realpath(os.path.dirname(sys.argv[0]))) try: connstr = cfg.get('db',", "'--verbose', dest='verbose', action='store_true', help='Verbose output') optparser.add_option('--force-date', dest='force_date', help='Override date (used", "IgnorableException as e: log_failed_message(listid, \"stdin\", \"\", ap, e) conn.close() sys.exit(1)", "# # load_message.py - takes a single email or mbox", "e: print((\"Failed to wait on advisory lock: %s\" % e))", "if the whole script dies, it goes away... conn.cursor().execute(\"INSERT INTO", "lib.log import log, opstatus from lib.varnish import VarnishPurger def log_failed_message(listid,", "src, err)) # We also put the data in the", "the data in the db. This happens in the main", "dest='directory', help='Load all messages in directory') optparser.add_option('-m', '--mbox', dest='mbox', help='Load", "ArchivesParserStorage() ap.parse(f) if opt.filter_msgid and not ap.is_msgid(opt.filter_msgid): continue try: ap.analyze(date_override=opt.force_date)", "using ON CONFLICT, # but concurrency is not that important", "(listid, msgid, srctype, src, err) VALUES (%(listid)s, %(msgid)s, %(srctype)s, %(src)s,", "if mboxparser.returncode(): log.error(\"Failed to parse mbox:\") log.error(mboxparser.stderr_output()) sys.exit(1) else: #", "listid) purges.update(ap.purges) if mboxparser.returncode(): log.error(\"Failed to parse mbox:\") log.error(mboxparser.stderr_output()) sys.exit(1)", "and opt.mbox: print(\"Can't specify both directory and mbox!\") optparser.print_usage() sys.exit(1)", "opt.directory: # Parse all files in directory for x in", "opstatus from lib.varnish import VarnishPurger def log_failed_message(listid, srctype, src, msg,", "log.log(\"Stored message with message-id %s\" % ap.msgid) conn.commit() conn.close() opstatus.print_status()", "messages in directory') optparser.add_option('-m', '--mbox', dest='mbox', help='Load all messages in", "Enter, or input a period (.) to stop processing\") x", "+= 1 continue ap.store(conn, listid) purges.update(ap.purges) if mboxparser.returncode(): log.error(\"Failed to", "print(\"No bare arguments accepted\") optparser.print_usage() sys.exit(1) if not opt.list: print(\"List", "and not ap.is_msgid(opt.filter_msgid): continue try: ap.analyze(date_override=opt.force_date) except IgnorableException as e:", "purges.update(ap.purges) if mboxparser.returncode(): log.error(\"Failed to parse mbox:\") log.error(mboxparser.stderr_output()) sys.exit(1) else:", "be specified\") optparser.print_usage() sys.exit(1) if opt.directory and opt.mbox: print(\"Can't specify", "database. # import os import sys from optparse import OptionParser", "dest='force_date', help='Override date (used for dates that can\\'t be parsed)')", "= ArchivesParserStorage() msg = next(mboxparser) if not msg: break ap.parse(msg)", "force serialization. # We could do this \"properly\" by reordering", "while not mboxparser.EOF: ap = ArchivesParserStorage() msg = next(mboxparser) if", "from %s, spec %s: %s\" % (msgid, srctype, src, err))", "== '.': print(\"Ok, aborting!\") break print(\"---------------------------------\") elif opt.mbox: if not", "%(msgid)s, %(srctype)s, %(src)s, %(err)s)\", { 'listid': listid, 'msgid': msgid, 'srctype':", "try: curs.execute(\"SET statement_timeout='30s'\") curs.execute(\"SELECT pg_advisory_xact_lock(8059944559669076)\") except Exception as e: print((\"Failed", "= MailboxBreakupParser(opt.mbox) while not mboxparser.EOF: ap = ArchivesParserStorage() msg =", "err): try: msgid = msg.msgid except Exception: msgid = \"<unknown>\"", "from configparser import ConfigParser import psycopg2 from lib.storage import ArchivesParserStorage", "print((\"Failed to wait on advisory lock: %s\" % e)) sys.exit(1)", "log_failed_message(listid, \"directory\", os.path.join(opt.directory, x), ap, e) opstatus.failed += 1 continue", "msgid, srctype, src, err) VALUES (%(listid)s, %(msgid)s, %(srctype)s, %(src)s, %(err)s)\",", "in directory') optparser.add_option('-m', '--mbox', dest='mbox', help='Load all messages in mbox')", "= cfg.get('db', 'connstr') except Exception: connstr = 'need_connstr' conn =", "- takes a single email or mbox formatted # file", "with directory or mbox - only individual messages\") optparser.print_usage() sys.exit(1)", "except IgnorableException as e: log_failed_message(listid, \"stdin\", \"\", ap, e) conn.close()", "all messages in directory') optparser.add_option('-m', '--mbox', dest='mbox', help='Load all messages", "optparser.add_option('-l', '--list', dest='list', help='Name of list to load message for')", "messages\") optparser.print_usage() sys.exit(1) if opt.filter_msgid and not (opt.directory or opt.mbox):", "= curs.fetchall() if len(r) != 1: log.error(\"List %s not found\"", "with Enter, or input a period (.) to stop processing\")", "optparser.add_option('-i', '--interactive', dest='interactive', action='store_true', help='Prompt after each message') optparser.add_option('-v', '--verbose',", "transaction\") conn.commit() print(\"Proceed to next message with Enter, or input", "def log_failed_message(listid, srctype, src, msg, err): try: msgid = msg.msgid", "goes away... conn.cursor().execute(\"INSERT INTO loaderrors (listid, msgid, srctype, src, err)", "'us-ascii', 'replace'), }) if __name__ == \"__main__\": optparser = OptionParser()", "not found\" % opt.list) conn.close() sys.exit(1) listid = r[0][0] purges", "to next message with Enter, or input a period (.)", "message with given msgid') (opt, args) = optparser.parse_args() if (len(args)):", "msg.msgid except Exception: msgid = \"<unknown>\" log.error(\"Failed to load message", "x), ap, e) opstatus.failed += 1 continue ap.store(conn, listid) purges.update(ap.purges)", "Parse all files in directory for x in os.listdir(opt.directory): log.status(\"Parsing", "conn.cursor().execute(\"INSERT INTO loaderrors (listid, msgid, srctype, src, err) VALUES (%(listid)s,", "stop processing\") x = input() if x == '.': print(\"Ok,", "%s\" % (msgid, srctype, src, err)) # We also put", "but concurrency is not that important and this is easier...", "os.listdir(opt.directory): log.status(\"Parsing file %s\" % x) with open(os.path.join(opt.directory, x)) as", "Get the listid we're working on curs.execute(\"SELECT listid FROM lists", "print(\"List must be specified\") optparser.print_usage() sys.exit(1) if opt.directory and opt.mbox:", "dest='list', help='Name of list to load message for') optparser.add_option('-d', '--directory',", "do this \"properly\" by reordering operations and using ON CONFLICT,", "listid = r[0][0] purges = set() if opt.directory: # Parse", "transaction # so if the whole script dies, it goes", "listid FROM lists WHERE listname=%(list)s\", { 'list': opt.list }) r", "after each message') optparser.add_option('-v', '--verbose', dest='verbose', action='store_true', help='Verbose output') optparser.add_option('--force-date',", "to load message for') optparser.add_option('-d', '--directory', dest='directory', help='Load all messages", "opt.list: print(\"List must be specified\") optparser.print_usage() sys.exit(1) if opt.directory and", "INTO loaderrors (listid, msgid, srctype, src, err) VALUES (%(listid)s, %(msgid)s,", "message (msgid %s) from %s, spec %s: %s\" % (msgid,", "optparser.add_option('-m', '--mbox', dest='mbox', help='Load all messages in mbox') optparser.add_option('-i', '--interactive',", "log.status(\"Parsing file %s\" % x) with open(os.path.join(opt.directory, x)) as f:", "% e)) sys.exit(1) # Get the listid we're working on", "away... conn.cursor().execute(\"INSERT INTO loaderrors (listid, msgid, srctype, src, err) VALUES", "We also put the data in the db. This happens", "msgid, 'srctype': srctype, 'src': src, 'err': str(str(err), 'us-ascii', 'replace'), })", "not mboxparser.EOF: ap = ArchivesParserStorage() msg = next(mboxparser) if not", "directory or mbox!\") optparser.print_usage() sys.exit(1) log.set(opt.verbose) cfg = ConfigParser() cfg.read('%s/archives.ini'", "psycopg2.connect(connstr) curs = conn.cursor() # Take an advisory lock to", "input a period (.) to stop processing\") x = input()", "ArchivesParserStorage from lib.mbox import MailboxBreakupParser from lib.exception import IgnorableException from", "}) if __name__ == \"__main__\": optparser = OptionParser() optparser.add_option('-l', '--list',", "optparser.add_option('--filter-msgid', dest='filter_msgid', help='Only process message with given msgid') (opt, args)", "optparser.print_usage() sys.exit(1) if opt.force_date and (opt.directory or opt.mbox) and not", "ap.parse(msg) if opt.filter_msgid and not ap.is_msgid(opt.filter_msgid): continue try: ap.analyze(date_override=opt.force_date) except", "= psycopg2.connect(connstr) curs = conn.cursor() # Take an advisory lock", "spec %s: %s\" % (msgid, srctype, src, err)) # We", "import ArchivesParserStorage from lib.mbox import MailboxBreakupParser from lib.exception import IgnorableException", "os.path.isfile(opt.mbox): print(\"File %s does not exist\" % opt.mbox) sys.exit(1) mboxparser", "+= 1 continue ap.store(conn, listid) purges.update(ap.purges) if opt.interactive: print(\"Interactive mode,", "opt.list }) r = curs.fetchall() if len(r) != 1: log.error(\"List", "%s\" % e)) sys.exit(1) # Get the listid we're working", "happens in the main transaction # so if the whole", "and reads it into the database. # import os import", "%(src)s, %(err)s)\", { 'listid': listid, 'msgid': msgid, 'srctype': srctype, 'src':", "help='Name of list to load message for') optparser.add_option('-d', '--directory', dest='directory',", "file on stdin or in a file and reads it", "to load message (msgid %s) from %s, spec %s: %s\"", "must be specified\") optparser.print_usage() sys.exit(1) if opt.directory and opt.mbox: print(\"Can't", "ap.store(conn, listid) purges.update(ap.purges) if mboxparser.returncode(): log.error(\"Failed to parse mbox:\") log.error(mboxparser.stderr_output())", "directory and mbox!\") optparser.print_usage() sys.exit(1) if opt.force_date and (opt.directory or", "opt.mbox): print(\"filter_msgid makes no sense without directory or mbox!\") optparser.print_usage()", "dest='verbose', action='store_true', help='Verbose output') optparser.add_option('--force-date', dest='force_date', help='Override date (used for", "load_message.py - takes a single email or mbox formatted #", "msgid') (opt, args) = optparser.parse_args() if (len(args)): print(\"No bare arguments", "listid) purges.update(ap.purges) if opt.interactive: print(\"Interactive mode, committing transaction\") conn.commit() print(\"Proceed", "period (.) to stop processing\") x = input() if x", "bare arguments accepted\") optparser.print_usage() sys.exit(1) if not opt.list: print(\"List must", "ON CONFLICT, # but concurrency is not that important and", "\"properly\" by reordering operations and using ON CONFLICT, # but", "not exist\" % opt.mbox) sys.exit(1) mboxparser = MailboxBreakupParser(opt.mbox) while not", "= input() if x == '.': print(\"Ok, aborting!\") break print(\"---------------------------------\")", "message on stdin ap = ArchivesParserStorage() ap.parse(sys.stdin.buffer) try: ap.analyze(date_override=opt.force_date) except", "optparser.print_usage() sys.exit(1) log.set(opt.verbose) cfg = ConfigParser() cfg.read('%s/archives.ini' % os.path.realpath(os.path.dirname(sys.argv[0]))) try:", "srctype, src, err) VALUES (%(listid)s, %(msgid)s, %(srctype)s, %(src)s, %(err)s)\", {", "cfg.read('%s/archives.ini' % os.path.realpath(os.path.dirname(sys.argv[0]))) try: connstr = cfg.get('db', 'connstr') except Exception:", "(used for dates that can\\'t be parsed)') optparser.add_option('--filter-msgid', dest='filter_msgid', help='Only", "MailboxBreakupParser(opt.mbox) while not mboxparser.EOF: ap = ArchivesParserStorage() msg = next(mboxparser)", "!= 1: log.error(\"List %s not found\" % opt.list) conn.close() sys.exit(1)", "listid, 'msgid': msgid, 'srctype': srctype, 'src': src, 'err': str(str(err), 'us-ascii',", "as f: ap = ArchivesParserStorage() ap.parse(f) if opt.filter_msgid and not", "log.error(\"List %s not found\" % opt.list) conn.close() sys.exit(1) listid =", "lists WHERE listname=%(list)s\", { 'list': opt.list }) r = curs.fetchall()", "from lib.varnish import VarnishPurger def log_failed_message(listid, srctype, src, msg, err):", "if opt.filter_msgid and not (opt.directory or opt.mbox): print(\"filter_msgid makes no", "ap.analyze(date_override=opt.force_date) except IgnorableException as e: log_failed_message(listid, \"directory\", os.path.join(opt.directory, x), ap,", "print(\"Proceed to next message with Enter, or input a period", "directory') optparser.add_option('-m', '--mbox', dest='mbox', help='Load all messages in mbox') optparser.add_option('-i',", "the database. # import os import sys from optparse import", "= msg.msgid except Exception: msgid = \"<unknown>\" log.error(\"Failed to load", "aborting!\") break print(\"---------------------------------\") elif opt.mbox: if not os.path.isfile(opt.mbox): print(\"File %s", "if not opt.list: print(\"List must be specified\") optparser.print_usage() sys.exit(1) if", "individual messages\") optparser.print_usage() sys.exit(1) if opt.filter_msgid and not (opt.directory or", "not os.path.isfile(opt.mbox): print(\"File %s does not exist\" % opt.mbox) sys.exit(1)", "curs.execute(\"SET statement_timeout='30s'\") curs.execute(\"SELECT pg_advisory_xact_lock(8059944559669076)\") except Exception as e: print((\"Failed to", "exist\" % opt.mbox) sys.exit(1) mboxparser = MailboxBreakupParser(opt.mbox) while not mboxparser.EOF:", "curs.execute(\"SELECT listid FROM lists WHERE listname=%(list)s\", { 'list': opt.list })", "'.': print(\"Ok, aborting!\") break print(\"---------------------------------\") elif opt.mbox: if not os.path.isfile(opt.mbox):", "not ap.is_msgid(opt.filter_msgid): continue try: ap.analyze(date_override=opt.force_date) except IgnorableException as e: log_failed_message(listid,", "into the database. # import os import sys from optparse", "if (len(args)): print(\"No bare arguments accepted\") optparser.print_usage() sys.exit(1) if not", "whole script dies, it goes away... conn.cursor().execute(\"INSERT INTO loaderrors (listid,", "found\" % opt.list) conn.close() sys.exit(1) listid = r[0][0] purges =", "advisory lock: %s\" % e)) sys.exit(1) # Get the listid", "optparse import OptionParser from configparser import ConfigParser import psycopg2 from", "msg: break ap.parse(msg) if opt.filter_msgid and not ap.is_msgid(opt.filter_msgid): continue try:", "operations and using ON CONFLICT, # but concurrency is not", "= set() if opt.directory: # Parse all files in directory", "# We also put the data in the db. This", "not msg: break ap.parse(msg) if opt.filter_msgid and not ap.is_msgid(opt.filter_msgid): continue", "from lib.storage import ArchivesParserStorage from lib.mbox import MailboxBreakupParser from lib.exception", "log.error(\"Failed to load message (msgid %s) from %s, spec %s:", "also put the data in the db. This happens in", "and using ON CONFLICT, # but concurrency is not that", "== \"__main__\": optparser = OptionParser() optparser.add_option('-l', '--list', dest='list', help='Name of", "x) with open(os.path.join(opt.directory, x)) as f: ap = ArchivesParserStorage() ap.parse(f)", "# file on stdin or in a file and reads", "except Exception as e: print((\"Failed to wait on advisory lock:", "parsed)') optparser.add_option('--filter-msgid', dest='filter_msgid', help='Only process message with given msgid') (opt,", "on curs.execute(\"SELECT listid FROM lists WHERE listname=%(list)s\", { 'list': opt.list", "src, err) VALUES (%(listid)s, %(msgid)s, %(srctype)s, %(src)s, %(err)s)\", { 'listid':", "(opt.directory or opt.mbox) and not opt.filter_msgid: print(\"Can't use force_date with", "mbox!\") optparser.print_usage() sys.exit(1) if opt.force_date and (opt.directory or opt.mbox) and", "working on curs.execute(\"SELECT listid FROM lists WHERE listname=%(list)s\", { 'list':", "is easier... try: curs.execute(\"SET statement_timeout='30s'\") curs.execute(\"SELECT pg_advisory_xact_lock(8059944559669076)\") except Exception as", "important and this is easier... try: curs.execute(\"SET statement_timeout='30s'\") curs.execute(\"SELECT pg_advisory_xact_lock(8059944559669076)\")", "sys.exit(1) if opt.force_date and (opt.directory or opt.mbox) and not opt.filter_msgid:", "single message on stdin ap = ArchivesParserStorage() ap.parse(sys.stdin.buffer) try: ap.analyze(date_override=opt.force_date)", "'src': src, 'err': str(str(err), 'us-ascii', 'replace'), }) if __name__ ==", "ConfigParser() cfg.read('%s/archives.ini' % os.path.realpath(os.path.dirname(sys.argv[0]))) try: connstr = cfg.get('db', 'connstr') except", "connstr = cfg.get('db', 'connstr') except Exception: connstr = 'need_connstr' conn", "We could do this \"properly\" by reordering operations and using", "'--interactive', dest='interactive', action='store_true', help='Prompt after each message') optparser.add_option('-v', '--verbose', dest='verbose',", "if opt.force_date and (opt.directory or opt.mbox) and not opt.filter_msgid: print(\"Can't", "with open(os.path.join(opt.directory, x)) as f: ap = ArchivesParserStorage() ap.parse(f) if", "sys.exit(1) mboxparser = MailboxBreakupParser(opt.mbox) while not mboxparser.EOF: ap = ArchivesParserStorage()", "specify both directory and mbox!\") optparser.print_usage() sys.exit(1) if opt.force_date and", "src, msg, err): try: msgid = msg.msgid except Exception: msgid", "pg_advisory_xact_lock(8059944559669076)\") except Exception as e: print((\"Failed to wait on advisory", "in os.listdir(opt.directory): log.status(\"Parsing file %s\" % x) with open(os.path.join(opt.directory, x))", "for dates that can\\'t be parsed)') optparser.add_option('--filter-msgid', dest='filter_msgid', help='Only process", "print(\"Ok, aborting!\") break print(\"---------------------------------\") elif opt.mbox: if not os.path.isfile(opt.mbox): print(\"File", "%s, spec %s: %s\" % (msgid, srctype, src, err)) #", "'err': str(str(err), 'us-ascii', 'replace'), }) if __name__ == \"__main__\": optparser", "dates that can\\'t be parsed)') optparser.add_option('--filter-msgid', dest='filter_msgid', help='Only process message", "IgnorableException as e: log_failed_message(listid, \"directory\", os.path.join(opt.directory, x), ap, e) opstatus.failed", "curs.execute(\"SELECT pg_advisory_xact_lock(8059944559669076)\") except Exception as e: print((\"Failed to wait on", "x)) as f: ap = ArchivesParserStorage() ap.parse(f) if opt.filter_msgid and", "sys.exit(1) if not opt.list: print(\"List must be specified\") optparser.print_usage() sys.exit(1)", "help='Prompt after each message') optparser.add_option('-v', '--verbose', dest='verbose', action='store_true', help='Verbose output')", "help='Load all messages in mbox') optparser.add_option('-i', '--interactive', dest='interactive', action='store_true', help='Prompt", "for x in os.listdir(opt.directory): log.status(\"Parsing file %s\" % x) with", "purges.update(ap.purges) if opt.interactive: print(\"Interactive mode, committing transaction\") conn.commit() print(\"Proceed to", "opstatus.failed += 1 continue ap.store(conn, listid) purges.update(ap.purges) if mboxparser.returncode(): log.error(\"Failed", "or in a file and reads it into the database.", "continue ap.store(conn, listid) purges.update(ap.purges) if mboxparser.returncode(): log.error(\"Failed to parse mbox:\")", "input() if x == '.': print(\"Ok, aborting!\") break print(\"---------------------------------\") elif", "sys.exit(1) if opt.filter_msgid and not (opt.directory or opt.mbox): print(\"filter_msgid makes", "log, opstatus from lib.varnish import VarnishPurger def log_failed_message(listid, srctype, src,", "ap.is_msgid(opt.filter_msgid): continue try: ap.analyze(date_override=opt.force_date) except IgnorableException as e: log_failed_message(listid, \"mbox\",", "ap.analyze(date_override=opt.force_date) except IgnorableException as e: log_failed_message(listid, \"mbox\", opt.mbox, ap, e)", "stdin or in a file and reads it into the", "import OptionParser from configparser import ConfigParser import psycopg2 from lib.storage", "OptionParser() optparser.add_option('-l', '--list', dest='list', help='Name of list to load message", "r = curs.fetchall() if len(r) != 1: log.error(\"List %s not", "by reordering operations and using ON CONFLICT, # but concurrency", "try: ap.analyze(date_override=opt.force_date) except IgnorableException as e: log_failed_message(listid, \"mbox\", opt.mbox, ap,", "or input a period (.) to stop processing\") x =", "list to load message for') optparser.add_option('-d', '--directory', dest='directory', help='Load all", "with given msgid') (opt, args) = optparser.parse_args() if (len(args)): print(\"No", "srctype, 'src': src, 'err': str(str(err), 'us-ascii', 'replace'), }) if __name__", "% (msgid, srctype, src, err)) # We also put the", "x == '.': print(\"Ok, aborting!\") break print(\"---------------------------------\") elif opt.mbox: if", "IgnorableException as e: log_failed_message(listid, \"mbox\", opt.mbox, ap, e) opstatus.failed +=", "% x) with open(os.path.join(opt.directory, x)) as f: ap = ArchivesParserStorage()", "continue try: ap.analyze(date_override=opt.force_date) except IgnorableException as e: log_failed_message(listid, \"directory\", os.path.join(opt.directory,", "load message for') optparser.add_option('-d', '--directory', dest='directory', help='Load all messages in", "opt.filter_msgid and not (opt.directory or opt.mbox): print(\"filter_msgid makes no sense", "all messages in mbox') optparser.add_option('-i', '--interactive', dest='interactive', action='store_true', help='Prompt after", "import sys from optparse import OptionParser from configparser import ConfigParser", "'--mbox', dest='mbox', help='Load all messages in mbox') optparser.add_option('-i', '--interactive', dest='interactive',", "mode, committing transaction\") conn.commit() print(\"Proceed to next message with Enter,", "# so if the whole script dies, it goes away...", "force_date with directory or mbox - only individual messages\") optparser.print_usage()", "except IgnorableException as e: log_failed_message(listid, \"directory\", os.path.join(opt.directory, x), ap, e)", "stdin ap = ArchivesParserStorage() ap.parse(sys.stdin.buffer) try: ap.analyze(date_override=opt.force_date) except IgnorableException as", "easier... try: curs.execute(\"SET statement_timeout='30s'\") curs.execute(\"SELECT pg_advisory_xact_lock(8059944559669076)\") except Exception as e:", "Parse single message on stdin ap = ArchivesParserStorage() ap.parse(sys.stdin.buffer) try:", "both directory and mbox!\") optparser.print_usage() sys.exit(1) if opt.force_date and (opt.directory", "and this is easier... try: curs.execute(\"SET statement_timeout='30s'\") curs.execute(\"SELECT pg_advisory_xact_lock(8059944559669076)\") except", "(%(listid)s, %(msgid)s, %(srctype)s, %(src)s, %(err)s)\", { 'listid': listid, 'msgid': msgid,", "as e: log_failed_message(listid, \"directory\", os.path.join(opt.directory, x), ap, e) opstatus.failed +=", "as e: log_failed_message(listid, \"stdin\", \"\", ap, e) conn.close() sys.exit(1) ap.store(conn,", "str(str(err), 'us-ascii', 'replace'), }) if __name__ == \"__main__\": optparser =", "the listid we're working on curs.execute(\"SELECT listid FROM lists WHERE", "it goes away... conn.cursor().execute(\"INSERT INTO loaderrors (listid, msgid, srctype, src,", "sys.exit(1) log.set(opt.verbose) cfg = ConfigParser() cfg.read('%s/archives.ini' % os.path.realpath(os.path.dirname(sys.argv[0]))) try: connstr", "conn.commit() print(\"Proceed to next message with Enter, or input a", "a single email or mbox formatted # file on stdin", "conn.close() sys.exit(1) ap.store(conn, listid) purges.update(ap.purges) if opstatus.stored: log.log(\"Stored message with", "not opt.filter_msgid: print(\"Can't use force_date with directory or mbox -", "# Parse all files in directory for x in os.listdir(opt.directory):", "if len(r) != 1: log.error(\"List %s not found\" % opt.list)", "and (opt.directory or opt.mbox) and not opt.filter_msgid: print(\"Can't use force_date", "e: log_failed_message(listid, \"mbox\", opt.mbox, ap, e) opstatus.failed += 1 continue", "action='store_true', help='Verbose output') optparser.add_option('--force-date', dest='force_date', help='Override date (used for dates", "opt.mbox: if not os.path.isfile(opt.mbox): print(\"File %s does not exist\" %", "Exception: msgid = \"<unknown>\" log.error(\"Failed to load message (msgid %s)", "mbox - only individual messages\") optparser.print_usage() sys.exit(1) if opt.filter_msgid and", "#!/usr/bin/env python3 # # load_message.py - takes a single email", "opt.mbox) sys.exit(1) mboxparser = MailboxBreakupParser(opt.mbox) while not mboxparser.EOF: ap =", "msgid = msg.msgid except Exception: msgid = \"<unknown>\" log.error(\"Failed to", "continue ap.store(conn, listid) purges.update(ap.purges) if opt.interactive: print(\"Interactive mode, committing transaction\")", "(len(args)): print(\"No bare arguments accepted\") optparser.print_usage() sys.exit(1) if not opt.list:", "file and reads it into the database. # import os", "lib.mbox import MailboxBreakupParser from lib.exception import IgnorableException from lib.log import", "opstatus.stored: log.log(\"Stored message with message-id %s\" % ap.msgid) conn.commit() conn.close()", "if opt.interactive: print(\"Interactive mode, committing transaction\") conn.commit() print(\"Proceed to next", "output') optparser.add_option('--force-date', dest='force_date', help='Override date (used for dates that can\\'t", "len(r) != 1: log.error(\"List %s not found\" % opt.list) conn.close()", "# Get the listid we're working on curs.execute(\"SELECT listid FROM", "VALUES (%(listid)s, %(msgid)s, %(srctype)s, %(src)s, %(err)s)\", { 'listid': listid, 'msgid':", "e: log_failed_message(listid, \"stdin\", \"\", ap, e) conn.close() sys.exit(1) ap.store(conn, listid)", "import ConfigParser import psycopg2 from lib.storage import ArchivesParserStorage from lib.mbox", "if x == '.': print(\"Ok, aborting!\") break print(\"---------------------------------\") elif opt.mbox:", "msg, err): try: msgid = msg.msgid except Exception: msgid =", "from optparse import OptionParser from configparser import ConfigParser import psycopg2", "sys.exit(1) else: # Parse single message on stdin ap =", "that important and this is easier... try: curs.execute(\"SET statement_timeout='30s'\") curs.execute(\"SELECT", "dest='mbox', help='Load all messages in mbox') optparser.add_option('-i', '--interactive', dest='interactive', action='store_true',", "args) = optparser.parse_args() if (len(args)): print(\"No bare arguments accepted\") optparser.print_usage()", "= OptionParser() optparser.add_option('-l', '--list', dest='list', help='Name of list to load", "x = input() if x == '.': print(\"Ok, aborting!\") break", "ConfigParser import psycopg2 from lib.storage import ArchivesParserStorage from lib.mbox import", "os.path.realpath(os.path.dirname(sys.argv[0]))) try: connstr = cfg.get('db', 'connstr') except Exception: connstr =", "opt.force_date and (opt.directory or opt.mbox) and not opt.filter_msgid: print(\"Can't use", "e) conn.close() sys.exit(1) ap.store(conn, listid) purges.update(ap.purges) if opstatus.stored: log.log(\"Stored message", "\"directory\", os.path.join(opt.directory, x), ap, e) opstatus.failed += 1 continue ap.store(conn,", "db. This happens in the main transaction # so if", "else: # Parse single message on stdin ap = ArchivesParserStorage()", "action='store_true', help='Prompt after each message') optparser.add_option('-v', '--verbose', dest='verbose', action='store_true', help='Verbose", "mbox') optparser.add_option('-i', '--interactive', dest='interactive', action='store_true', help='Prompt after each message') optparser.add_option('-v',", "to stop processing\") x = input() if x == '.':", "next message with Enter, or input a period (.) to", "ap.is_msgid(opt.filter_msgid): continue try: ap.analyze(date_override=opt.force_date) except IgnorableException as e: log_failed_message(listid, \"directory\",", "%s not found\" % opt.list) conn.close() sys.exit(1) listid = r[0][0]", "print(\"Can't specify both directory and mbox!\") optparser.print_usage() sys.exit(1) if opt.force_date", "__name__ == \"__main__\": optparser = OptionParser() optparser.add_option('-l', '--list', dest='list', help='Name", "advisory lock to force serialization. # We could do this", "this is easier... try: curs.execute(\"SET statement_timeout='30s'\") curs.execute(\"SELECT pg_advisory_xact_lock(8059944559669076)\") except Exception", "f: ap = ArchivesParserStorage() ap.parse(f) if opt.filter_msgid and not ap.is_msgid(opt.filter_msgid):", "= next(mboxparser) if not msg: break ap.parse(msg) if opt.filter_msgid and", "r[0][0] purges = set() if opt.directory: # Parse all files", "\"stdin\", \"\", ap, e) conn.close() sys.exit(1) ap.store(conn, listid) purges.update(ap.purges) if", "on stdin or in a file and reads it into", "OptionParser from configparser import ConfigParser import psycopg2 from lib.storage import", "only individual messages\") optparser.print_usage() sys.exit(1) if opt.filter_msgid and not (opt.directory", "optparser.print_usage() sys.exit(1) if not opt.list: print(\"List must be specified\") optparser.print_usage()", "print(\"Can't use force_date with directory or mbox - only individual", "we're working on curs.execute(\"SELECT listid FROM lists WHERE listname=%(list)s\", {", "directory for x in os.listdir(opt.directory): log.status(\"Parsing file %s\" % x)", "break ap.parse(msg) if opt.filter_msgid and not ap.is_msgid(opt.filter_msgid): continue try: ap.analyze(date_override=opt.force_date)", "(opt, args) = optparser.parse_args() if (len(args)): print(\"No bare arguments accepted\")", "so if the whole script dies, it goes away... conn.cursor().execute(\"INSERT", "'--directory', dest='directory', help='Load all messages in directory') optparser.add_option('-m', '--mbox', dest='mbox',", "Exception as e: print((\"Failed to wait on advisory lock: %s\"", "break print(\"---------------------------------\") elif opt.mbox: if not os.path.isfile(opt.mbox): print(\"File %s does", "'--list', dest='list', help='Name of list to load message for') optparser.add_option('-d',", "e: log_failed_message(listid, \"directory\", os.path.join(opt.directory, x), ap, e) opstatus.failed += 1", "log_failed_message(listid, \"mbox\", opt.mbox, ap, e) opstatus.failed += 1 continue ap.store(conn,", "optparser.add_option('--force-date', dest='force_date', help='Override date (used for dates that can\\'t be", "log_failed_message(listid, srctype, src, msg, err): try: msgid = msg.msgid except", "import log, opstatus from lib.varnish import VarnishPurger def log_failed_message(listid, srctype,", "not opt.list: print(\"List must be specified\") optparser.print_usage() sys.exit(1) if opt.directory", "optparser.print_usage() sys.exit(1) if opt.filter_msgid and not (opt.directory or opt.mbox): print(\"filter_msgid", "os import sys from optparse import OptionParser from configparser import", "files in directory for x in os.listdir(opt.directory): log.status(\"Parsing file %s\"", "'connstr') except Exception: connstr = 'need_connstr' conn = psycopg2.connect(connstr) curs", "mboxparser = MailboxBreakupParser(opt.mbox) while not mboxparser.EOF: ap = ArchivesParserStorage() msg", "mboxparser.EOF: ap = ArchivesParserStorage() msg = next(mboxparser) if not msg:", "(msgid, srctype, src, err)) # We also put the data", "takes a single email or mbox formatted # file on", "import VarnishPurger def log_failed_message(listid, srctype, src, msg, err): try: msgid", "wait on advisory lock: %s\" % e)) sys.exit(1) # Get", "%s\" % x) with open(os.path.join(opt.directory, x)) as f: ap =", "ArchivesParserStorage() msg = next(mboxparser) if not msg: break ap.parse(msg) if", "listid) purges.update(ap.purges) if opstatus.stored: log.log(\"Stored message with message-id %s\" %", "help='Verbose output') optparser.add_option('--force-date', dest='force_date', help='Override date (used for dates that", "from lib.log import log, opstatus from lib.varnish import VarnishPurger def", "optparser.add_option('-v', '--verbose', dest='verbose', action='store_true', help='Verbose output') optparser.add_option('--force-date', dest='force_date', help='Override date", "if not os.path.isfile(opt.mbox): print(\"File %s does not exist\" % opt.mbox)", "mbox!\") optparser.print_usage() sys.exit(1) log.set(opt.verbose) cfg = ConfigParser() cfg.read('%s/archives.ini' % os.path.realpath(os.path.dirname(sys.argv[0])))", "open(os.path.join(opt.directory, x)) as f: ap = ArchivesParserStorage() ap.parse(f) if opt.filter_msgid", "import IgnorableException from lib.log import log, opstatus from lib.varnish import", "try: connstr = cfg.get('db', 'connstr') except Exception: connstr = 'need_connstr'", "as e: log_failed_message(listid, \"mbox\", opt.mbox, ap, e) opstatus.failed += 1", "from lib.exception import IgnorableException from lib.log import log, opstatus from", "all files in directory for x in os.listdir(opt.directory): log.status(\"Parsing file", "ap = ArchivesParserStorage() ap.parse(f) if opt.filter_msgid and not ap.is_msgid(opt.filter_msgid): continue", "loaderrors (listid, msgid, srctype, src, err) VALUES (%(listid)s, %(msgid)s, %(srctype)s,", "(.) to stop processing\") x = input() if x ==", "makes no sense without directory or mbox!\") optparser.print_usage() sys.exit(1) log.set(opt.verbose)", "print(\"Interactive mode, committing transaction\") conn.commit() print(\"Proceed to next message with", "\"<unknown>\" log.error(\"Failed to load message (msgid %s) from %s, spec", "help='Load all messages in directory') optparser.add_option('-m', '--mbox', dest='mbox', help='Load all", "this \"properly\" by reordering operations and using ON CONFLICT, #", "{ 'listid': listid, 'msgid': msgid, 'srctype': srctype, 'src': src, 'err':", "date (used for dates that can\\'t be parsed)') optparser.add_option('--filter-msgid', dest='filter_msgid',", "or mbox!\") optparser.print_usage() sys.exit(1) log.set(opt.verbose) cfg = ConfigParser() cfg.read('%s/archives.ini' %", "message with Enter, or input a period (.) to stop", "sense without directory or mbox!\") optparser.print_usage() sys.exit(1) log.set(opt.verbose) cfg =", "can\\'t be parsed)') optparser.add_option('--filter-msgid', dest='filter_msgid', help='Only process message with given", "load message (msgid %s) from %s, spec %s: %s\" %", "err) VALUES (%(listid)s, %(msgid)s, %(srctype)s, %(src)s, %(err)s)\", { 'listid': listid,", "in the main transaction # so if the whole script", "ap, e) opstatus.failed += 1 continue ap.store(conn, listid) purges.update(ap.purges) if", "sys.exit(1) if opt.directory and opt.mbox: print(\"Can't specify both directory and", "opt.mbox) and not opt.filter_msgid: print(\"Can't use force_date with directory or", "and not (opt.directory or opt.mbox): print(\"filter_msgid makes no sense without", "%s) from %s, spec %s: %s\" % (msgid, srctype, src,", "main transaction # so if the whole script dies, it", "does not exist\" % opt.mbox) sys.exit(1) mboxparser = MailboxBreakupParser(opt.mbox) while", "% opt.mbox) sys.exit(1) mboxparser = MailboxBreakupParser(opt.mbox) while not mboxparser.EOF: ap", "on stdin ap = ArchivesParserStorage() ap.parse(sys.stdin.buffer) try: ap.analyze(date_override=opt.force_date) except IgnorableException", "the main transaction # so if the whole script dies,", "mbox:\") log.error(mboxparser.stderr_output()) sys.exit(1) else: # Parse single message on stdin", "# but concurrency is not that important and this is", "not that important and this is easier... try: curs.execute(\"SET statement_timeout='30s'\")", "formatted # file on stdin or in a file and", "or mbox - only individual messages\") optparser.print_usage() sys.exit(1) if opt.filter_msgid", "(opt.directory or opt.mbox): print(\"filter_msgid makes no sense without directory or", "IgnorableException from lib.log import log, opstatus from lib.varnish import VarnishPurger", "= ConfigParser() cfg.read('%s/archives.ini' % os.path.realpath(os.path.dirname(sys.argv[0]))) try: connstr = cfg.get('db', 'connstr')", "dest='interactive', action='store_true', help='Prompt after each message') optparser.add_option('-v', '--verbose', dest='verbose', action='store_true',", "WHERE listname=%(list)s\", { 'list': opt.list }) r = curs.fetchall() if", "cfg.get('db', 'connstr') except Exception: connstr = 'need_connstr' conn = psycopg2.connect(connstr)", "except Exception: connstr = 'need_connstr' conn = psycopg2.connect(connstr) curs =", "= ArchivesParserStorage() ap.parse(sys.stdin.buffer) try: ap.analyze(date_override=opt.force_date) except IgnorableException as e: log_failed_message(listid,", "try: ap.analyze(date_override=opt.force_date) except IgnorableException as e: log_failed_message(listid, \"directory\", os.path.join(opt.directory, x),", "an advisory lock to force serialization. # We could do", "python3 # # load_message.py - takes a single email or", "'listid': listid, 'msgid': msgid, 'srctype': srctype, 'src': src, 'err': str(str(err),", "# We could do this \"properly\" by reordering operations and", "opt.mbox: print(\"Can't specify both directory and mbox!\") optparser.print_usage() sys.exit(1) if", "ap.parse(sys.stdin.buffer) try: ap.analyze(date_override=opt.force_date) except IgnorableException as e: log_failed_message(listid, \"stdin\", \"\",", "if opt.filter_msgid and not ap.is_msgid(opt.filter_msgid): continue try: ap.analyze(date_override=opt.force_date) except IgnorableException", "the db. This happens in the main transaction # so", "directory or mbox - only individual messages\") optparser.print_usage() sys.exit(1) if", "except Exception: msgid = \"<unknown>\" log.error(\"Failed to load message (msgid", "log.error(mboxparser.stderr_output()) sys.exit(1) else: # Parse single message on stdin ap", "script dies, it goes away... conn.cursor().execute(\"INSERT INTO loaderrors (listid, msgid,", "from lib.mbox import MailboxBreakupParser from lib.exception import IgnorableException from lib.log", "in a file and reads it into the database. #", "configparser import ConfigParser import psycopg2 from lib.storage import ArchivesParserStorage from", "messages in mbox') optparser.add_option('-i', '--interactive', dest='interactive', action='store_true', help='Prompt after each", "print(\"filter_msgid makes no sense without directory or mbox!\") optparser.print_usage() sys.exit(1)", "message for') optparser.add_option('-d', '--directory', dest='directory', help='Load all messages in directory')", "import os import sys from optparse import OptionParser from configparser", "opt.mbox, ap, e) opstatus.failed += 1 continue ap.store(conn, listid) purges.update(ap.purges)", "MailboxBreakupParser from lib.exception import IgnorableException from lib.log import log, opstatus", "src, 'err': str(str(err), 'us-ascii', 'replace'), }) if __name__ == \"__main__\":", "os.path.join(opt.directory, x), ap, e) opstatus.failed += 1 continue ap.store(conn, listid)", "message') optparser.add_option('-v', '--verbose', dest='verbose', action='store_true', help='Verbose output') optparser.add_option('--force-date', dest='force_date', help='Override", "email or mbox formatted # file on stdin or in", "on advisory lock: %s\" % e)) sys.exit(1) # Get the", "parse mbox:\") log.error(mboxparser.stderr_output()) sys.exit(1) else: # Parse single message on", "\"\", ap, e) conn.close() sys.exit(1) ap.store(conn, listid) purges.update(ap.purges) if opstatus.stored:", "Take an advisory lock to force serialization. # We could", "print(\"---------------------------------\") elif opt.mbox: if not os.path.isfile(opt.mbox): print(\"File %s does not", "purges = set() if opt.directory: # Parse all files in", "(msgid %s) from %s, spec %s: %s\" % (msgid, srctype,", "FROM lists WHERE listname=%(list)s\", { 'list': opt.list }) r =", "no sense without directory or mbox!\") optparser.print_usage() sys.exit(1) log.set(opt.verbose) cfg", "log.set(opt.verbose) cfg = ConfigParser() cfg.read('%s/archives.ini' % os.path.realpath(os.path.dirname(sys.argv[0]))) try: connstr =", "% os.path.realpath(os.path.dirname(sys.argv[0]))) try: connstr = cfg.get('db', 'connstr') except Exception: connstr", "next(mboxparser) if not msg: break ap.parse(msg) if opt.filter_msgid and not", "= optparser.parse_args() if (len(args)): print(\"No bare arguments accepted\") optparser.print_usage() sys.exit(1)", "optparser.parse_args() if (len(args)): print(\"No bare arguments accepted\") optparser.print_usage() sys.exit(1) if", "opt.filter_msgid: print(\"Can't use force_date with directory or mbox - only", "Exception: connstr = 'need_connstr' conn = psycopg2.connect(connstr) curs = conn.cursor()", "# Take an advisory lock to force serialization. # We", "in mbox') optparser.add_option('-i', '--interactive', dest='interactive', action='store_true', help='Prompt after each message')", "optparser = OptionParser() optparser.add_option('-l', '--list', dest='list', help='Name of list to", "sys.exit(1) # Get the listid we're working on curs.execute(\"SELECT listid", "srctype, src, msg, err): try: msgid = msg.msgid except Exception:", "msg = next(mboxparser) if not msg: break ap.parse(msg) if opt.filter_msgid", "# load_message.py - takes a single email or mbox formatted", "that can\\'t be parsed)') optparser.add_option('--filter-msgid', dest='filter_msgid', help='Only process message with", "if opt.directory: # Parse all files in directory for x", "= \"<unknown>\" log.error(\"Failed to load message (msgid %s) from %s,", "'need_connstr' conn = psycopg2.connect(connstr) curs = conn.cursor() # Take an", "each message') optparser.add_option('-v', '--verbose', dest='verbose', action='store_true', help='Verbose output') optparser.add_option('--force-date', dest='force_date',", "and not opt.filter_msgid: print(\"Can't use force_date with directory or mbox", "lock to force serialization. # We could do this \"properly\"", "}) r = curs.fetchall() if len(r) != 1: log.error(\"List %s", "x in os.listdir(opt.directory): log.status(\"Parsing file %s\" % x) with open(os.path.join(opt.directory,", "log_failed_message(listid, \"stdin\", \"\", ap, e) conn.close() sys.exit(1) ap.store(conn, listid) purges.update(ap.purges)", "file %s\" % x) with open(os.path.join(opt.directory, x)) as f: ap", "opstatus.failed += 1 continue ap.store(conn, listid) purges.update(ap.purges) if opt.interactive: print(\"Interactive", "serialization. # We could do this \"properly\" by reordering operations", "err)) # We also put the data in the db.", "elif opt.mbox: if not os.path.isfile(opt.mbox): print(\"File %s does not exist\"", "% opt.list) conn.close() sys.exit(1) listid = r[0][0] purges = set()", "opt.interactive: print(\"Interactive mode, committing transaction\") conn.commit() print(\"Proceed to next message", "mboxparser.returncode(): log.error(\"Failed to parse mbox:\") log.error(mboxparser.stderr_output()) sys.exit(1) else: # Parse", "use force_date with directory or mbox - only individual messages\")" ]
[ "models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('shop', '0008_auto_20200310_1134'),", "from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies", "-*- coding: utf-8 -*- # Generated by Django 1.11.29 on", "= [ ('shop', '0008_auto_20200310_1134'), ] operations = [ migrations.RemoveField( model_name='category',", "import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('shop', '0008_auto_20200310_1134'), ]", "[ ('shop', '0008_auto_20200310_1134'), ] operations = [ migrations.RemoveField( model_name='category', name='id',", "by Django 1.11.29 on 2020-03-10 14:30 from __future__ import unicode_literals", "1.11.29 on 2020-03-10 14:30 from __future__ import unicode_literals from django.db", "Generated by Django 1.11.29 on 2020-03-10 14:30 from __future__ import", "= [ migrations.RemoveField( model_name='category', name='id', ), migrations.AlterField( model_name='category', name='name', field=models.CharField(db_index=True,", "migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('shop',", "class Migration(migrations.Migration): dependencies = [ ('shop', '0008_auto_20200310_1134'), ] operations =", "# Generated by Django 1.11.29 on 2020-03-10 14:30 from __future__", "2020-03-10 14:30 from __future__ import unicode_literals from django.db import migrations,", "14:30 from __future__ import unicode_literals from django.db import migrations, models", "Migration(migrations.Migration): dependencies = [ ('shop', '0008_auto_20200310_1134'), ] operations = [", "), migrations.AlterField( model_name='category', name='name', field=models.CharField(db_index=True, max_length=200, primary_key=True, serialize=False), ), migrations.AlterField(", "on 2020-03-10 14:30 from __future__ import unicode_literals from django.db import", "'0008_auto_20200310_1134'), ] operations = [ migrations.RemoveField( model_name='category', name='id', ), migrations.AlterField(", "('shop', '0008_auto_20200310_1134'), ] operations = [ migrations.RemoveField( model_name='category', name='id', ),", "operations = [ migrations.RemoveField( model_name='category', name='id', ), migrations.AlterField( model_name='category', name='name',", "migrations.AlterField( model_name='category', name='name', field=models.CharField(db_index=True, max_length=200, primary_key=True, serialize=False), ), migrations.AlterField( model_name='product',", "# -*- coding: utf-8 -*- # Generated by Django 1.11.29", "utf-8 -*- # Generated by Django 1.11.29 on 2020-03-10 14:30", "django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies =", "from __future__ import unicode_literals from django.db import migrations, models import", "model_name='category', name='name', field=models.CharField(db_index=True, max_length=200, primary_key=True, serialize=False), ), migrations.AlterField( model_name='product', name='type1',", "name='name', field=models.CharField(db_index=True, max_length=200, primary_key=True, serialize=False), ), migrations.AlterField( model_name='product', name='type1', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,", "import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [", "dependencies = [ ('shop', '0008_auto_20200310_1134'), ] operations = [ migrations.RemoveField(", "migrations.RemoveField( model_name='category', name='id', ), migrations.AlterField( model_name='category', name='name', field=models.CharField(db_index=True, max_length=200, primary_key=True,", "max_length=200, primary_key=True, serialize=False), ), migrations.AlterField( model_name='product', name='type1', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='products', to='shop.Type1'),", "field=models.CharField(db_index=True, max_length=200, primary_key=True, serialize=False), ), migrations.AlterField( model_name='product', name='type1', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='products',", "__future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion", "-*- # Generated by Django 1.11.29 on 2020-03-10 14:30 from", "primary_key=True, serialize=False), ), migrations.AlterField( model_name='product', name='type1', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='products', to='shop.Type1'), ),", "] operations = [ migrations.RemoveField( model_name='category', name='id', ), migrations.AlterField( model_name='category',", "serialize=False), ), migrations.AlterField( model_name='product', name='type1', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='products', to='shop.Type1'), ), ]", "model_name='category', name='id', ), migrations.AlterField( model_name='category', name='name', field=models.CharField(db_index=True, max_length=200, primary_key=True, serialize=False),", "Django 1.11.29 on 2020-03-10 14:30 from __future__ import unicode_literals from", "<filename>shop/migrations/0009_auto_20200310_1430.py # -*- coding: utf-8 -*- # Generated by Django", "unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration):", "name='id', ), migrations.AlterField( model_name='category', name='name', field=models.CharField(db_index=True, max_length=200, primary_key=True, serialize=False), ),", "import unicode_literals from django.db import migrations, models import django.db.models.deletion class", "django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('shop', '0008_auto_20200310_1134'), ] operations", "coding: utf-8 -*- # Generated by Django 1.11.29 on 2020-03-10", "[ migrations.RemoveField( model_name='category', name='id', ), migrations.AlterField( model_name='category', name='name', field=models.CharField(db_index=True, max_length=200," ]
[ "sample_class = np.random.choice(np.arange(self.num_classes), p=self.progress_p) sample_indexes = self.class_dict[sample_class] index = random.choice(sample_indexes)", "super(iNaturalist, self).__init__(mode, cfg, transform) random.seed(0) self.class_dict = self._get_class_dict() def __getitem__(self,", "class iNaturalist(BaseSet): def __init__(self, mode='train', cfg=None, transform=None): super(iNaturalist, self).__init__(mode, cfg,", "'train': assert self.cfg.TRAIN.SAMPLER.WEIGHTED_SAMPLER.TYPE in [\"balance\", 'square', 'progressive'] if self.cfg.TRAIN.SAMPLER.WEIGHTED_SAMPLER.TYPE ==", "dict() image_label = now_info['category_id'] # 0-index return image, image_label, meta", "as np class iNaturalist(BaseSet): def __init__(self, mode='train', cfg=None, transform=None): super(iNaturalist,", "dataset.baseset import BaseSet import random, cv2 import numpy as np", "= self.class_dict[sample_class] index = random.choice(sample_indexes) now_info = self.data[index] img =", "[\"balance\", 'square', 'progressive'] if self.cfg.TRAIN.SAMPLER.WEIGHTED_SAMPLER.TYPE == \"balance\": sample_class = random.randint(0,", "self.class_dict[sample_class] index = random.choice(sample_indexes) now_info = self.data[index] img = self._get_image(now_info)", "== \"balance\": sample_class = random.randint(0, self.num_classes - 1) elif self.cfg.TRAIN.SAMPLER.WEIGHTED_SAMPLER.TYPE", "sample_class = random.randint(0, self.num_classes - 1) elif self.cfg.TRAIN.SAMPLER.WEIGHTED_SAMPLER.TYPE == \"square\":", "import numpy as np class iNaturalist(BaseSet): def __init__(self, mode='train', cfg=None,", "self.cfg.TRAIN.SAMPLER.WEIGHTED_SAMPLER.TYPE == \"balance\": sample_class = random.randint(0, self.num_classes - 1) elif", "== \"square\": sample_class = np.random.choice(np.arange(self.num_classes), p=self.square_p) else: sample_class = np.random.choice(np.arange(self.num_classes),", "== \"weighted sampler\" and self.mode == 'train': assert self.cfg.TRAIN.SAMPLER.WEIGHTED_SAMPLER.TYPE in", "\"weighted sampler\" and self.mode == 'train': assert self.cfg.TRAIN.SAMPLER.WEIGHTED_SAMPLER.TYPE in [\"balance\",", "import BaseSet import random, cv2 import numpy as np class", "numpy as np class iNaturalist(BaseSet): def __init__(self, mode='train', cfg=None, transform=None):", "cfg=None, transform=None): super(iNaturalist, self).__init__(mode, cfg, transform) random.seed(0) self.class_dict = self._get_class_dict()", "else: sample_class = np.random.choice(np.arange(self.num_classes), p=self.progress_p) sample_indexes = self.class_dict[sample_class] index =", "now_info = self.data[index] img = self._get_image(now_info) image = self.transform(img) meta", "p=self.progress_p) sample_indexes = self.class_dict[sample_class] index = random.choice(sample_indexes) now_info = self.data[index]", "1) elif self.cfg.TRAIN.SAMPLER.WEIGHTED_SAMPLER.TYPE == \"square\": sample_class = np.random.choice(np.arange(self.num_classes), p=self.square_p) else:", "= self.transform(img) meta = dict() image_label = now_info['category_id'] # 0-index", "== 'train': assert self.cfg.TRAIN.SAMPLER.WEIGHTED_SAMPLER.TYPE in [\"balance\", 'square', 'progressive'] if self.cfg.TRAIN.SAMPLER.WEIGHTED_SAMPLER.TYPE", "\"square\": sample_class = np.random.choice(np.arange(self.num_classes), p=self.square_p) else: sample_class = np.random.choice(np.arange(self.num_classes), p=self.progress_p)", "self.cfg.TRAIN.SAMPLER.TYPE == \"weighted sampler\" and self.mode == 'train': assert self.cfg.TRAIN.SAMPLER.WEIGHTED_SAMPLER.TYPE", "= np.random.choice(np.arange(self.num_classes), p=self.square_p) else: sample_class = np.random.choice(np.arange(self.num_classes), p=self.progress_p) sample_indexes =", "sample_class = np.random.choice(np.arange(self.num_classes), p=self.square_p) else: sample_class = np.random.choice(np.arange(self.num_classes), p=self.progress_p) sample_indexes", "iNaturalist(BaseSet): def __init__(self, mode='train', cfg=None, transform=None): super(iNaturalist, self).__init__(mode, cfg, transform)", "\"balance\": sample_class = random.randint(0, self.num_classes - 1) elif self.cfg.TRAIN.SAMPLER.WEIGHTED_SAMPLER.TYPE ==", "random.choice(sample_indexes) now_info = self.data[index] img = self._get_image(now_info) image = self.transform(img)", "= self._get_class_dict() def __getitem__(self, index): if self.cfg.TRAIN.SAMPLER.TYPE == \"weighted sampler\"", "random.randint(0, self.num_classes - 1) elif self.cfg.TRAIN.SAMPLER.WEIGHTED_SAMPLER.TYPE == \"square\": sample_class =", "in [\"balance\", 'square', 'progressive'] if self.cfg.TRAIN.SAMPLER.WEIGHTED_SAMPLER.TYPE == \"balance\": sample_class =", "self.cfg.TRAIN.SAMPLER.WEIGHTED_SAMPLER.TYPE == \"square\": sample_class = np.random.choice(np.arange(self.num_classes), p=self.square_p) else: sample_class =", "self).__init__(mode, cfg, transform) random.seed(0) self.class_dict = self._get_class_dict() def __getitem__(self, index):", "import random, cv2 import numpy as np class iNaturalist(BaseSet): def", "p=self.square_p) else: sample_class = np.random.choice(np.arange(self.num_classes), p=self.progress_p) sample_indexes = self.class_dict[sample_class] index", "= dict() image_label = now_info['category_id'] # 0-index return image, image_label,", "= self._get_image(now_info) image = self.transform(img) meta = dict() image_label =", "- 1) elif self.cfg.TRAIN.SAMPLER.WEIGHTED_SAMPLER.TYPE == \"square\": sample_class = np.random.choice(np.arange(self.num_classes), p=self.square_p)", "index): if self.cfg.TRAIN.SAMPLER.TYPE == \"weighted sampler\" and self.mode == 'train':", "random.seed(0) self.class_dict = self._get_class_dict() def __getitem__(self, index): if self.cfg.TRAIN.SAMPLER.TYPE ==", "from dataset.baseset import BaseSet import random, cv2 import numpy as", "self.cfg.TRAIN.SAMPLER.WEIGHTED_SAMPLER.TYPE in [\"balance\", 'square', 'progressive'] if self.cfg.TRAIN.SAMPLER.WEIGHTED_SAMPLER.TYPE == \"balance\": sample_class", "elif self.cfg.TRAIN.SAMPLER.WEIGHTED_SAMPLER.TYPE == \"square\": sample_class = np.random.choice(np.arange(self.num_classes), p=self.square_p) else: sample_class", "if self.cfg.TRAIN.SAMPLER.TYPE == \"weighted sampler\" and self.mode == 'train': assert", "np class iNaturalist(BaseSet): def __init__(self, mode='train', cfg=None, transform=None): super(iNaturalist, self).__init__(mode,", "= self.data[index] img = self._get_image(now_info) image = self.transform(img) meta =", "mode='train', cfg=None, transform=None): super(iNaturalist, self).__init__(mode, cfg, transform) random.seed(0) self.class_dict =", "BaseSet import random, cv2 import numpy as np class iNaturalist(BaseSet):", "transform=None): super(iNaturalist, self).__init__(mode, cfg, transform) random.seed(0) self.class_dict = self._get_class_dict() def", "meta = dict() image_label = now_info['category_id'] # 0-index return image,", "def __getitem__(self, index): if self.cfg.TRAIN.SAMPLER.TYPE == \"weighted sampler\" and self.mode", "'square', 'progressive'] if self.cfg.TRAIN.SAMPLER.WEIGHTED_SAMPLER.TYPE == \"balance\": sample_class = random.randint(0, self.num_classes", "self.num_classes - 1) elif self.cfg.TRAIN.SAMPLER.WEIGHTED_SAMPLER.TYPE == \"square\": sample_class = np.random.choice(np.arange(self.num_classes),", "'progressive'] if self.cfg.TRAIN.SAMPLER.WEIGHTED_SAMPLER.TYPE == \"balance\": sample_class = random.randint(0, self.num_classes -", "= random.randint(0, self.num_classes - 1) elif self.cfg.TRAIN.SAMPLER.WEIGHTED_SAMPLER.TYPE == \"square\": sample_class", "__getitem__(self, index): if self.cfg.TRAIN.SAMPLER.TYPE == \"weighted sampler\" and self.mode ==", "and self.mode == 'train': assert self.cfg.TRAIN.SAMPLER.WEIGHTED_SAMPLER.TYPE in [\"balance\", 'square', 'progressive']", "assert self.cfg.TRAIN.SAMPLER.WEIGHTED_SAMPLER.TYPE in [\"balance\", 'square', 'progressive'] if self.cfg.TRAIN.SAMPLER.WEIGHTED_SAMPLER.TYPE == \"balance\":", "sample_indexes = self.class_dict[sample_class] index = random.choice(sample_indexes) now_info = self.data[index] img", "random, cv2 import numpy as np class iNaturalist(BaseSet): def __init__(self,", "cfg, transform) random.seed(0) self.class_dict = self._get_class_dict() def __getitem__(self, index): if", "self._get_image(now_info) image = self.transform(img) meta = dict() image_label = now_info['category_id']", "if self.cfg.TRAIN.SAMPLER.WEIGHTED_SAMPLER.TYPE == \"balance\": sample_class = random.randint(0, self.num_classes - 1)", "index = random.choice(sample_indexes) now_info = self.data[index] img = self._get_image(now_info) image", "sampler\" and self.mode == 'train': assert self.cfg.TRAIN.SAMPLER.WEIGHTED_SAMPLER.TYPE in [\"balance\", 'square',", "self.data[index] img = self._get_image(now_info) image = self.transform(img) meta = dict()", "self.mode == 'train': assert self.cfg.TRAIN.SAMPLER.WEIGHTED_SAMPLER.TYPE in [\"balance\", 'square', 'progressive'] if", "img = self._get_image(now_info) image = self.transform(img) meta = dict() image_label", "__init__(self, mode='train', cfg=None, transform=None): super(iNaturalist, self).__init__(mode, cfg, transform) random.seed(0) self.class_dict", "np.random.choice(np.arange(self.num_classes), p=self.square_p) else: sample_class = np.random.choice(np.arange(self.num_classes), p=self.progress_p) sample_indexes = self.class_dict[sample_class]", "def __init__(self, mode='train', cfg=None, transform=None): super(iNaturalist, self).__init__(mode, cfg, transform) random.seed(0)", "np.random.choice(np.arange(self.num_classes), p=self.progress_p) sample_indexes = self.class_dict[sample_class] index = random.choice(sample_indexes) now_info =", "self._get_class_dict() def __getitem__(self, index): if self.cfg.TRAIN.SAMPLER.TYPE == \"weighted sampler\" and", "= np.random.choice(np.arange(self.num_classes), p=self.progress_p) sample_indexes = self.class_dict[sample_class] index = random.choice(sample_indexes) now_info", "transform) random.seed(0) self.class_dict = self._get_class_dict() def __getitem__(self, index): if self.cfg.TRAIN.SAMPLER.TYPE", "cv2 import numpy as np class iNaturalist(BaseSet): def __init__(self, mode='train',", "self.class_dict = self._get_class_dict() def __getitem__(self, index): if self.cfg.TRAIN.SAMPLER.TYPE == \"weighted", "image = self.transform(img) meta = dict() image_label = now_info['category_id'] #", "self.transform(img) meta = dict() image_label = now_info['category_id'] # 0-index return", "= random.choice(sample_indexes) now_info = self.data[index] img = self._get_image(now_info) image =" ]
[ "parsed_second) def create_fake_conference_nodes(n, conference): nodes = [] for i in", "else '', conference.endpoint, ) res = self.app.post( api_url_for('meeting_hook'), { 'X-Mailgun-Sscore':", "# Create conference nodes n_conference_nodes = 3 create_fake_conference_nodes( n_conference_nodes, conference,", "n_conference_nodes_bad = 1 create_fake_conference_nodes_bad_data( conference, n_conference_nodes, n_conference_nodes_bad, conference, ) #", "mock_get_url.assert_called_with( self.node._id, 'osfstorage', _internal=True, base_url=self.node.osfstorage_region.waterbutler_url, cookie=self.user.get_or_create_cookie(), name=file_name ) mock_put.assert_called_with( mock_get_url.return_value,", "else '') with self.make_context(data={'recipient': recipient}): self.app.app.preprocess_request() msg = message.ConferenceMessage() with", "a non-conference node ProjectFactory() url = api_url_for('conference_data', meeting=conference.endpoint.upper()) res =", "'1', 'attachment-1': (self.attachment, 'attachment-1'), 'X-Mailgun-Sscore': 0, 'recipient': self.recipient, 'stripped-text': self.body,", "i in range(n): node = ProjectFactory(is_public=True) conference.submissions.add(node) node.save() nodes.append(node) return", "def test_attachments_count_one(self): content = 'slightly mad' sio = StringIO(content) ctx", "ctx: msg = message.ConferenceMessage() assert msg.is_spam def test_is_spam_true_spf(self): ctx =", "assert_equal(nodes.count(), 1) node = nodes[0] assert_equal(WikiVersion.objects.get_for_node(node, 'home').content, body) assert_true(mock_send_mail.called) call_args,", "class TestConferenceUtils(OsfTestCase): def test_get_or_create_user_exists(self): user = UserFactory() fetched, created =", "utf-8 -*- import mock from nose.tools import * # noqa", "names: with self.make_context(data={'from': name[0]}): msg = message.ConferenceMessage() assert_equal(msg.sender_name, name[1]) def", "test_alternate_route_invalid(self): recipient = '{0}<EMAIL>'.format('test-' if settings.DEV_MODE else '') with self.make_context(data={'recipient':", "= '<EMAIL>' with assert_raises(BlacklistedEmailError) as e: get_or_create_user(fullname, username, is_spam=True) assert_equal(e.exception.message,", "not msg.is_spam def test_is_spam_false_all_headers(self): ctx = self.make_context( method='POST', data={ 'X-Mailgun-Sscore':", "= message.ConferenceMessage() with assert_raises(message.ConferenceError): msg.route def test_attachments_count_zero(self): with self.make_context(data={'attachment-count': '0'}):", "from django.db import IntegrityError import furl from framework.auth import get_or_create_user", "created = get_or_create_user(fullname, username, is_spam=False) fetched.save() # in order to", "assert_false('is_spam' in fetched.system_tags) def test_get_or_create_user_is_spam(self): fullname = '<NAME>' username =", "'secret'), digestmod=hashlib.sha256, ).hexdigest(), } data.update(kwargs.pop('data', {})) data = { key:", ") self.app.post( api_url_for('meeting_hook'), { 'X-Mailgun-Sscore': 0, 'timestamp': '123', 'token': 'secret',", "conf) # Deleted node added deleted_node = ProjectFactory(is_public=True) deleted_node.is_deleted =", "data.update(kwargs.pop('data', {})) return super(TestProvisionNode, self).make_context(data=data, **kwargs) def test_provision(self): with self.make_context():", "def test_upload_no_file_name(self, mock_put, mock_get_url): mock_get_url.return_value = 'http://queen.com/' self.attachment.filename = ''", "user = UserFactory() title = 'Long Live Greg' ProjectFactory(creator=user, title=title)", "data={'X-Mailgun-Sscore': message.SSCORE_MAX_VALUE + 1}, ) with ctx: msg = message.ConferenceMessage()", "message.ConferenceMessage() assert msg.is_spam def test_is_spam_true_dkim(self): ctx = self.make_context( method='POST', data={'X-Mailgun-Dkim-Check-Result':", "msg = message.ConferenceMessage() assert not msg.is_spam def test_is_spam_true_sscore(self): ctx =", "] for email in emails: with self.make_context(data={'from': email[0]}): msg =", "is_spam=True) assert_false(created) assert_equal(user._id, fetched._id) assert_false('is_spam' in fetched.system_tags) def test_get_or_create_user_not_exists(self): fullname", "good plant' content = 'Long may they reign.' recipient =", "self.node.system_tags) assert_in(self.conference.endpoint, self.node.system_tags) assert self.node in self.conference.submissions.all() assert_not_in('spam', self.node.system_tags) def", "in fetched.system_tags) def test_get_or_create_user_with_blacklisted_domain(self): fullname = 'Kanye West' username =", "mad' sio = StringIO(content) ctx = self.make_context( method='POST', data={ 'attachment-count':", "fields, e.g. tags assert_true(created) assert_equal(fetched.fullname, fullname) assert_equal(fetched.username, username) assert_false('is_spam' in", "data = { 'attachment-count': '1', 'attachment-1': (self.attachment, 'attachment-1'), 'X-Mailgun-Sscore': 0,", "node = nodes[0] assert_equal(WikiVersion.objects.get_for_node(node, 'home').content, body) assert_true(mock_send_mail.called) call_args, call_kwargs =", "bad_n: # Delete only contributor node.contributor_set.filter(user=node.contributors.first()).delete() node.save() nodes.append(node) return nodes", "user = UserFactory() fetched, created = get_or_create_user(user.fullname, user.username, is_spam=True) assert_false(created)", "if i < bad_n: # Delete only contributor node.contributor_set.filter(user=node.contributors.first()).delete() node.save()", "assert_equal(msg.conference_name, 'chocolate') assert_equal(msg.conference_category, 'data') conf.__class__.delete(conf) def test_route_valid_b(self): recipient = '{0}<EMAIL>'.format('test-'", "'X-Mailgun-Sscore': 0, 'from': username, 'recipient': recipient, 'subject': title, 'stripped-text': body,", "is_spam=True) assert_equal(e.exception.message, 'Invalid Email') class ContextTestCase(OsfTestCase): MAILGUN_API_KEY = 'mailkimp' @classmethod", "'stage-') with self.make_context(data={'recipient': recipient}): self.app.app.preprocess_request() msg = message.ConferenceMessage() with assert_raises(message.ConferenceError):", "is_spam=False) fetched.save() # in order to access m2m fields, e.g.", "= '<EMAIL>' fetched, created = get_or_create_user(fullname, username, is_spam=False) fetched.save() #", "StringIO(self.content) self.recipient = '{0}{1}-<EMAIL>'.format( 'test-' if settings.DEV_MODE else '', self.conference.endpoint,", "= 'dragon attack' self.attachment = StringIO(self.content) self.recipient = '{0}{1}-<EMAIL>'.format( 'test-'", "mock_upload, mock_send_mail): fullname = '<NAME>' username = '<EMAIL>' title =", "mock_send_mail): username = '<EMAIL>' title = 'no full name only", "- 1}, ) with ctx: msg = message.ConferenceMessage() assert not", "private_node = ProjectFactory(is_public=False) conf.submissions.add(private_node) assert_equal(conf.submissions.count(), 5) assert_equal(conf.valid_submissions.count(), 3) class TestConferenceIntegration(ContextTestCase):", ") url = api_url_for('conference_submissions') res = self.app.get(url) assert_equal(res.json['success'], True) def", "back' content = 'dragon attack' recipient = '{0}{1}-<EMAIL>'.format( 'test-' if", "- 1, 'X-Mailgun-Dkim-Check-Result': message.DKIM_PASS_VALUES[0], 'X-Mailgun-Spf': message.SPF_PASS_VALUES[0], }, ) with ctx:", "'attachment-1'), 'X-Mailgun-Sscore': 0, 'recipient': self.recipient, 'stripped-text': self.body, } data.update(kwargs.pop('data', {}))", "self.attachment.filename = file_name self.attachment.content_type = 'application/json' utils.upload_attachment(self.user, self.node, self.attachment) mock_get_url.assert_called_with(", "= self.make_context( method='POST', data={ 'X-Mailgun-Sscore': message.SSCORE_MAX_VALUE - 1, 'X-Mailgun-Dkim-Check-Result': message.DKIM_PASS_VALUES[0],", ") @mock.patch('website.conferences.utils.waterbutler_api_url_for') @mock.patch('website.conferences.utils.requests.put') def test_upload_no_file_name(self, mock_put, mock_get_url): mock_get_url.return_value = 'http://queen.com/'", "res = res.follow() assert_equal(res.request.path, '/meetings/') def test_conference_submissions(self): AbstractNode.objects.all().delete() conference1 =", "= 'Long Live Greg' ProjectFactory(creator=user, title=title) body = 'Greg is", "tags assert_true(created) assert_equal(fetched.fullname, fullname) assert_equal(fetched.username, username) assert_true('is_spam' in fetched.system_tags) def", "'<EMAIL>' title = 'good songs' body = 'dragon on my", ") with ctx: msg = message.ConferenceMessage() assert_equal(msg.recipient, address) def test_text(self):", "with self.make_context(): msg = message.ConferenceMessage() utils.provision_node(self.conference, msg, self.node, self.user) assert_true(self.node.is_public)", "songs' conference = ConferenceFactory() body = 'dragon on my back'", "def setUpClass(cls): super(ContextTestCase, cls).setUpClass() settings.MAILGUN_API_KEY, cls._MAILGUN_API_KEY = cls.MAILGUN_API_KEY, settings.MAILGUN_API_KEY @classmethod", "1 create_fake_conference_nodes_bad_data( conference, n_conference_nodes, n_conference_nodes_bad, conference, ) # Create a", "nuclear family' ctx = self.make_context( method='POST', data={'stripped-text': text}, ) with", "assert_raises(message.ConferenceError): msg.route def test_route_invalid_test(self): recipient = '{0}<EMAIL>'.format('' if settings.DEV_MODE else", "inject bad data if i < bad_n: # Delete only", "assert_equal(WikiVersion.objects.get_for_node(node, 'home').content, body) assert_true(mock_send_mail.called) call_args, call_kwargs = mock_send_mail.call_args assert_absolute(call_kwargs['conf_view_url']) assert_absolute(call_kwargs['set_password_url'])", "'good songs' body = 'dragon on my back' recipient =", "-*- import mock from nose.tools import * # noqa (PEP8", "fullname) assert_equal(fetched.username, username) assert_true('is_spam' in fetched.system_tags) def test_get_or_create_user_with_blacklisted_domain(self): fullname =", "ConferenceFactory() user = UserFactory() title = 'Long Live Greg' ProjectFactory(creator=user,", "= mock_send_mail.call_args assert_equal(call_args, (username, views.CONFERENCE_INACTIVE)) assert_equal(call_kwargs['fullname'], fullname) assert_equal_urls( call_kwargs['presentations_url'], web_url_for('conference_view',", "'from': '{0} <{1}>'.format(fullname, username), 'recipient': recipient, 'subject': title, 'stripped-text': body,", "assert_absolute(call_kwargs['profile_url']) assert_absolute(call_kwargs['file_url']) assert_absolute(call_kwargs['node_url']) @mock.patch('website.conferences.views.send_mail') @mock.patch('website.conferences.utils.upload_attachments') def test_create_conference_node_with_same_name_as_existing_node(self, mock_upload, mock_send_mail): conference", "as e: get_or_create_user(fullname, username, is_spam=True) assert_equal(e.exception.message, 'Invalid Email') class ContextTestCase(OsfTestCase):", "mock_get_url): mock_get_url.return_value = 'http://queen.com/' file_name = 'hammer-to-fall' self.attachment.filename = file_name", "self.node.contributors) assert_in('emailed', self.node.system_tags) assert_in('spam', self.node.system_tags) @mock.patch('website.conferences.utils.waterbutler_api_url_for') @mock.patch('website.conferences.utils.requests.put') def test_upload(self, mock_put,", "self.user = self.node.creator self.conference = ConferenceFactory() self.body = 'dragon on", "assert_equal(len(msg.attachments), 1) assert_equal(msg.attachments[0].read(), content) class TestConferenceEmailViews(OsfTestCase): def test_redirect_to_meetings_url(self): url =", "= mock_send_mail.call_args assert_absolute(call_kwargs['conf_view_url']) assert_absolute(call_kwargs['set_password_url']) assert_absolute(call_kwargs['profile_url']) assert_absolute(call_kwargs['file_url']) assert_absolute(call_kwargs['node_url']) @mock.patch('website.conferences.views.send_mail') def test_integration_inactive(self,", "assert_equal(call_args, (username, views.CONFERENCE_INACTIVE)) assert_equal(call_kwargs['fullname'], fullname) assert_equal_urls( call_kwargs['presentations_url'], web_url_for('conference_view', _absolute=True), )", "tearDownClass(cls): super(ContextTestCase, cls).tearDownClass() settings.MAILGUN_API_KEY = cls._MAILGUN_API_KEY def make_context(self, method='POST', **kwargs):", "n_conference_nodes = 3 create_fake_conference_nodes( n_conference_nodes, conference, ) # Create a", "title = 'good songs' body = 'dragon on my back'", "'1', 'X-Mailgun-Sscore': 0, 'from': '{0} <{1}>'.format(user.fullname, user.username), 'recipient': recipient, 'subject':", "mock_upload_attachments): conference = ConferenceFactory() with self.make_context(data={'from': '<EMAIL>', 'subject': 'It\\'s PARTY", "data=self.content, ) @mock.patch('website.conferences.utils.waterbutler_api_url_for') @mock.patch('website.conferences.utils.requests.put') def test_upload_no_file_name(self, mock_put, mock_get_url): mock_get_url.return_value =", "assert_true('is_spam' in fetched.system_tags) def test_get_or_create_user_with_blacklisted_domain(self): fullname = 'Kanye West' username", "@mock.patch('website.conferences.views.send_mail') @mock.patch('website.conferences.utils.upload_attachments') def test_create_conference_node_with_same_name_as_existing_node(self, mock_upload, mock_send_mail): conference = ConferenceFactory() user", "BlacklistedEmailError from website import settings from website.conferences import views from", "assert_in(self.conference.admins.first(), self.node.contributors) assert_in('emailed', self.node.system_tags) assert_in('spam', self.node.system_tags) @mock.patch('website.conferences.utils.waterbutler_api_url_for') @mock.patch('website.conferences.utils.requests.put') def test_upload(self,", "name in names: with self.make_context(data={'from': name[0]}): msg = message.ConferenceMessage() assert_equal(msg.sender_name,", "in fetched.system_tags) def test_get_or_create_user_not_exists(self): fullname = '<NAME>' username = '<EMAIL>'", "def test_subject(self): ctx = self.make_context( method='POST', data={'subject': 'RE: Hip Hopera'},", "], ) assert AbstractNode.objects.filter(title=title, creator=user).count() == 2 assert mock_upload.called assert", "= '{0}{1}-<EMAIL>'.format( 'test-' if settings.DEV_MODE else '', self.conference.endpoint, ) def", "conference nodes n_conference_nodes = 3 create_fake_conference_nodes( n_conference_nodes, conference, ) #", "'/meetings/') def test_conference_submissions(self): AbstractNode.objects.all().delete() conference1 = ConferenceFactory() conference2 = ConferenceFactory()", "def test_provision_spam(self): with self.make_context(data={'X-Mailgun-Sscore': message.SSCORE_MAX_VALUE + 1}): msg = message.ConferenceMessage()", "get_or_create_user(user.fullname, user.username, is_spam=True) assert_false(created) assert_equal(user._id, fetched._id) assert_false('is_spam' in fetched.system_tags) def", "'<EMAIL>'}): self.app.app.preprocess_request() msg = message.ConferenceMessage() with assert_raises(message.ConferenceError): msg.route def test_route_invalid_test(self):", "for OSF-8864 to confirm bad project data does not make", "i < bad_n: # Delete only contributor node.contributor_set.filter(user=node.contributors.first()).delete() node.save() nodes.append(node)", "= ConferenceFactory() body = 'dragon on my back' content =", "api_url_for, web_url_for from tests.base import OsfTestCase, fake from osf_tests.factories import", "= message.ConferenceMessage() assert_equal(msg.attachments, []) def test_attachments_count_one(self): content = 'slightly mad'", "'/presentations/' res = self.app.get(url) assert_equal(res.status_code, 302) res = res.follow() assert_equal(res.request.path,", "e.g. tags assert_true(created) assert_equal(fetched.fullname, fullname) assert_equal(fetched.username, username) assert_true('is_spam' in fetched.system_tags)", "username = '<EMAIL>' fetched, created = get_or_create_user(fullname, username, is_spam=True) fetched.save()", "utils.upload_attachment(self.user, self.node, self.attachment) mock_get_url.assert_called_with( self.node._id, 'osfstorage', _internal=True, base_url=self.node.osfstorage_region.waterbutler_url, cookie=self.user.get_or_create_cookie(), name=settings.MISSING_FILE_NAME,", "= '{0}{1}-<EMAIL>'.format( 'test-' if settings.DEV_MODE else '', conference.endpoint, ) self.app.post(", "self.make_context( method='POST', data={'recipient': address}, ) with ctx: msg = message.ConferenceMessage()", "content = 'slightly mad' sio = StringIO(content) ctx = self.make_context(", "osf.models import OSFUser, AbstractNode from addons.wiki.models import WikiVersion from osf.exceptions", "they reign.' recipient = '{0}{1}-<EMAIL>'.format( 'test-' if settings.DEV_MODE else '',", "res = self.app.get(url) assert_equal(res.status_code, 200) assert_equal(len(res.json), n_conference_nodes) def test_conference_data_tag_upper(self): conference", "assert_false('is_spam' in fetched.system_tags) def test_get_or_create_user_not_exists(self): fullname = '<NAME>' username =", "self.user) assert_false(self.node.is_public) assert_in(self.conference.admins.first(), self.node.contributors) assert_in('emailed', self.node.system_tags) assert_in('spam', self.node.system_tags) @mock.patch('website.conferences.utils.waterbutler_api_url_for') @mock.patch('website.conferences.utils.requests.put')", "res.follow() assert_equal(res.request.path, '/meetings/') def test_conference_submissions(self): AbstractNode.objects.all().delete() conference1 = ConferenceFactory() conference2", "to confirm bad project data does not make whole conference", "conference2 = ConferenceFactory() # Create conference nodes create_fake_conference_nodes( 3, conference1,", "asserts) import hmac import hashlib from StringIO import StringIO from", "cls).setUpClass() settings.MAILGUN_API_KEY, cls._MAILGUN_API_KEY = cls.MAILGUN_API_KEY, settings.MAILGUN_API_KEY @classmethod def tearDownClass(cls): super(ContextTestCase,", "assert_true(self.node.is_public) assert_in(self.conference.admins.first(), self.node.contributors) assert_in('emailed', self.node.system_tags) assert_in(self.conference.endpoint, self.node.system_tags) assert self.node in", "= 'good songs' conference = ConferenceFactory() body = 'dragon on", "= 'no full name only email' conference = ConferenceFactory() body", "'0'}): msg = message.ConferenceMessage() assert_equal(msg.attachments, []) def test_attachments_count_one(self): content =", "test_is_spam_true_sscore(self): ctx = self.make_context( method='POST', data={'X-Mailgun-Sscore': message.SSCORE_MAX_VALUE + 1}, )", "conference.endpoint, ) self.app.post( api_url_for('meeting_hook'), { 'X-Mailgun-Sscore': 0, 'timestamp': '123', 'token':", "res = self.app.get(url) assert_equal(res.status_code, 200) assert_equal(len(res.json), n_conference_nodes - n_conference_nodes_bad) def", "message.SPF_PASS_VALUES[0], }, ) with ctx: msg = message.ConferenceMessage() assert not", "'Hip Hopera') def test_recipient(self): address = '<EMAIL>' ctx = self.make_context(", "parsed_second = furl.furl(second) parsed_second.port = None assert_equal(parsed_first, parsed_second) def create_fake_conference_nodes(n,", "'It\\'s PARTY TIME!'}): msg = message.ConferenceMessage() views.add_poster_by_email(conference, msg) user =", "= ConferenceFactory() # Create conference nodes n_conference_nodes = 3 n_conference_nodes_bad", "1, 'X-Mailgun-Dkim-Check-Result': message.DKIM_PASS_VALUES[0], 'X-Mailgun-Spf': message.SPF_PASS_VALUES[0], }, ) with ctx: msg", "import WikiVersion from osf.exceptions import BlacklistedEmailError from website import settings", "= cls.MAILGUN_API_KEY, settings.MAILGUN_API_KEY @classmethod def tearDownClass(cls): super(ContextTestCase, cls).tearDownClass() settings.MAILGUN_API_KEY =", "recipient, 'subject': title, 'stripped-text': body, }, expect_errors=True, ) assert_equal(res.status_code, 406)", "mock_get_url.return_value = 'http://queen.com/' file_name = 'hammer-to-fall' self.attachment.filename = file_name self.attachment.content_type", "msg = message.ConferenceMessage() utils.provision_node(self.conference, msg, self.node, self.user) assert_false(self.node.is_public) assert_in(self.conference.admins.first(), self.node.contributors)", "self.make_context(data={'from': '<EMAIL>', 'subject': 'It\\'s PARTY TIME!'}): msg = message.ConferenceMessage() views.add_poster_by_email(conference,", "key: value for key, value in data.items() if value is", "test_endpoint_is_required(self): with assert_raises(IntegrityError): ConferenceFactory(endpoint=None, name=fake.company()).save() def test_name_is_required(self): with assert_raises(IntegrityError): ConferenceFactory(endpoint='spsp2014',", "= api_url_for('conference_submissions') res = self.app.get(url) assert_equal(res.json['success'], True) def test_conference_plain_returns_200(self): conference", "plant' content = 'Long may they reign.' recipient = '{0}{1}-<EMAIL>'.format(", "msg='{}{}'.format('123', 'secret'), digestmod=hashlib.sha256, ).hexdigest(), } data.update(kwargs.pop('data', {})) data = {", "for i in range(n): node = ProjectFactory(is_public=True) conference.submissions.add(node) node.save() nodes.append(node)", "0, 'timestamp': '123', 'token': 'secret', 'signature': hmac.new( key=settings.MAILGUN_API_KEY, msg='{}{}'.format('123', 'secret'),", "assert_in(self.conference.endpoint, self.node.system_tags) assert self.node in self.conference.submissions.all() assert_not_in('spam', self.node.system_tags) def test_provision_private(self):", "self.make_context(data={'recipient': '<EMAIL>'}): self.app.app.preprocess_request() msg = message.ConferenceMessage() with assert_raises(message.ConferenceError): msg.route def", "test_conference_valid_submissions(self): conf = ConferenceFactory(endpoint='Hamburgers', name='Hamburger conference') conf.save() # 3 good", "is a good plant' content = 'Long may they reign.'", "= res.follow() assert_equal(res.request.path, '/meetings/') def test_conference_submissions(self): AbstractNode.objects.all().delete() conference1 = ConferenceFactory()", "m2m fields, e.g. tags assert_true(created) assert_equal(fetched.fullname, fullname) assert_equal(fetched.username, username) assert_false('is_spam'", "node.contributor_set.filter(user=node.contributors.first()).delete() node.save() nodes.append(node) return nodes class TestConferenceUtils(OsfTestCase): def test_get_or_create_user_exists(self): user", "mock_get_url.assert_called_with( self.node._id, 'osfstorage', _internal=True, base_url=self.node.osfstorage_region.waterbutler_url, cookie=self.user.get_or_create_cookie(), name=settings.MISSING_FILE_NAME, ) mock_put.assert_called_with( mock_get_url.return_value,", "assert_equal(len(res.json), n_conference_nodes) def test_conference_results(self): conference = ConferenceFactory() url = web_url_for('conference_results',", "shouldn't be able to use email as fullname, so we", "assert_equal(fetched.username, username) assert_true('is_spam' in fetched.system_tags) def test_get_or_create_user_with_blacklisted_domain(self): fullname = 'Kanye", "title, 'stripped-text': body, }, expect_errors=True, ) assert_equal(res.status_code, 406) call_args, call_kwargs", "assert_equal(users.count(), 1) nodes = AbstractNode.objects.filter(title=title) assert_equal(nodes.count(), 1) node = nodes[0]", "else '', self.conference.endpoint, ) def make_context(self, **kwargs): data = {", "msg = message.ConferenceMessage() assert_equal(msg.recipient, address) def test_text(self): text = 'welcome", "def make_context(self, **kwargs): data = { 'attachment-count': '1', 'attachment-1': (self.attachment,", "api_url_for('conference_data', meeting=conference.endpoint.upper()) res = self.app.get(url) assert_equal(res.status_code, 200) assert_equal(len(res.json), n_conference_nodes) def", "ProjectFactory() self.user = self.node.creator self.conference = ConferenceFactory() self.body = 'dragon", "assert msg.is_spam def test_is_spam_true_spf(self): ctx = self.make_context( method='POST', data={'X-Mailgun-Spf': message.SPF_PASS_VALUES[0][::-1]},", "def test_route_valid_alternate(self): conf = ConferenceFactory(endpoint='chocolate', active=True) conf.name = 'Chocolate Conference'", "== user._id # user's shouldn't be able to use email", "created = get_or_create_user(fullname, username, is_spam=True) fetched.save() # in order to", "is_spam=True) fetched.save() # in order to access m2m fields, e.g.", "message.DKIM_PASS_VALUES[0][::-1]}, ) with ctx: msg = message.ConferenceMessage() assert msg.is_spam def", "data does not make whole conference break def test_conference_bad_data(self): conference", "'X-Mailgun-Sscore': 0, 'recipient': self.recipient, 'stripped-text': self.body, } data.update(kwargs.pop('data', {})) return", "test_route_valid_b(self): recipient = '{0}<EMAIL>'.format('test-' if settings.DEV_MODE else '') with self.make_context(data={'recipient':", "= { 'attachment-count': '1', 'attachment-1': (self.attachment, 'attachment-1'), 'X-Mailgun-Sscore': 0, 'recipient':", "ctx = self.make_context( method='POST', data={'stripped-text': text}, ) with ctx: msg", "method='POST', data={'X-Mailgun-Sscore': message.SSCORE_MAX_VALUE - 1}, ) with ctx: msg =", "back' self.content = 'dragon attack' self.attachment = StringIO(self.content) self.recipient =", "test_provision_private(self): self.conference.public_projects = False self.conference.save() with self.make_context(): msg = message.ConferenceMessage()", "views.add_poster_by_email(conference, msg) user = OSFUser.objects.get(username='<EMAIL>') assert user.email == '<EMAIL>' assert", "import Auth from osf.models import OSFUser, AbstractNode from addons.wiki.models import", "'Kanye West' username = '<EMAIL>' with assert_raises(BlacklistedEmailError) as e: get_or_create_user(fullname,", "True) def test_conference_plain_returns_200(self): conference = ConferenceFactory() url = web_url_for('conference_results__plain', meeting=conference.endpoint)", "'') with self.make_context(data={'recipient': recipient}): self.app.app.preprocess_request() msg = message.ConferenceMessage() with assert_raises(message.ConferenceError):", "meeting=conference.endpoint) res = self.app.get(url) assert_equal(res.status_code, 200) def test_confererence_results_endpoint_is_case_insensitive(self): ConferenceFactory(endpoint='StudySwap') url", "@mock.patch('website.conferences.utils.upload_attachments') def test_integration_wo_full_name(self, mock_upload, mock_send_mail): username = '<EMAIL>' title =", "self.node.contributors) assert_in('emailed', self.node.system_tags) assert_not_in('spam', self.node.system_tags) def test_provision_spam(self): with self.make_context(data={'X-Mailgun-Sscore': message.SSCORE_MAX_VALUE", "self.node.system_tags) def test_provision_private(self): self.conference.public_projects = False self.conference.save() with self.make_context(): msg", "a good plant' content = 'Long may they reign.' recipient", "'stripped-text': body, }, upload_files=[ ('attachment-1', 'attachment-1', content), ], ) assert", "conference, ) # Create a non-conference node ProjectFactory() url =", "def make_context(self, method='POST', **kwargs): data = { 'X-Mailgun-Sscore': 0, 'timestamp':", "assert_equal(msg.conference_category, 'poster') def test_alternate_route_invalid(self): recipient = '{0}<EMAIL>'.format('test-' if settings.DEV_MODE else", "nodes create_fake_conference_nodes( 3, conference1, ) create_fake_conference_nodes( 2, conference2, ) url", "ConferenceFactory() url = web_url_for('conference_results', meeting=conference.endpoint) res = self.app.get(url) assert_equal(res.status_code, 200)", "= 3 n_conference_nodes_bad = 1 create_fake_conference_nodes_bad_data( conference, n_conference_nodes, n_conference_nodes_bad, conference,", ") assert_true(mock_upload.called) users = OSFUser.objects.filter(username=username) assert_equal(users.count(), 1) nodes = AbstractNode.objects.filter(title=title)", "url = api_url_for('conference_data', meeting=conference.endpoint) res = self.app.get(url) assert_equal(res.status_code, 200) assert_equal(len(res.json),", "test_route_valid_alternate(self): conf = ConferenceFactory(endpoint='chocolate', active=True) conf.name = 'Chocolate Conference' conf.field_names['submission2']", "test_conference_plain_returns_200(self): conference = ConferenceFactory() url = web_url_for('conference_results__plain', meeting=conference.endpoint) res =", "UserFactory() fetched, created = get_or_create_user(user.fullname, user.username, is_spam=True) assert_false(created) assert_equal(user._id, fetched._id)", "= 'dragon on my back' self.content = 'dragon attack' self.attachment", ") mock_put.assert_called_with( mock_get_url.return_value, data=self.content, ) @mock.patch('website.conferences.utils.waterbutler_api_url_for') @mock.patch('website.conferences.utils.requests.put') def test_upload_no_file_name(self, mock_put,", "conference, n_conference_nodes, n_conference_nodes_bad, conference, ) # Create a non-conference node", "as fullname, so we use the guid. class TestMessage(ContextTestCase): PUSH_CONTEXT", "(u'<EMAIL>', u'<EMAIL>') ] for email in emails: with self.make_context(data={'from': email[0]}):", "upload_files=[ ('attachment-1', 'attachment-1', content), ], ) assert AbstractNode.objects.filter(title=title, creator=user).count() ==", "= AbstractNode.objects.filter(title=title) assert_equal(nodes.count(), 1) node = nodes[0] assert_equal(WikiVersion.objects.get_for_node(node, 'home').content, body)", "ContextTestCase(OsfTestCase): MAILGUN_API_KEY = 'mailkimp' @classmethod def setUpClass(cls): super(ContextTestCase, cls).setUpClass() settings.MAILGUN_API_KEY,", "full name only email' conference = ConferenceFactory() body = 'dragon", "test_confererence_results_endpoint_is_case_insensitive(self): ConferenceFactory(endpoint='StudySwap') url = web_url_for('conference_results', meeting='studyswap') res = self.app.get(url) assert_equal(res.status_code,", "added private_node = ProjectFactory(is_public=False) conf.submissions.add(private_node) assert_equal(conf.submissions.count(), 5) assert_equal(conf.valid_submissions.count(), 3) class", "= api_url_for('conference_data', meeting=conference.endpoint.upper()) res = self.app.get(url) assert_equal(res.status_code, 200) assert_equal(len(res.json), n_conference_nodes)", "data.update(kwargs.pop('data', {})) data = { key: value for key, value", "msg = message.ConferenceMessage() with assert_raises(message.ConferenceError): msg.route def test_route_valid_alternate(self): conf =", "= message.ConferenceMessage() assert_equal(len(msg.attachments), 1) assert_equal(msg.attachments[0].read(), content) class TestConferenceEmailViews(OsfTestCase): def test_redirect_to_meetings_url(self):", "conference break def test_conference_bad_data(self): conference = ConferenceFactory() # Create conference", "= [ (' Fred', 'Fred'), (u'Me䬟', u'Me䬟'), (u'<EMAIL>', u'<EMAIL>'), (u'Fred", "from django.core.exceptions import ValidationError from django.db import IntegrityError import furl", "assert not msg.is_spam def test_is_spam_true_sscore(self): ctx = self.make_context( method='POST', data={'X-Mailgun-Sscore':", "assert user.fullname == user._id # user's shouldn't be able to", "with self.make_context(data={'recipient': '<EMAIL>'}): self.app.app.preprocess_request() msg = message.ConferenceMessage() with assert_raises(message.ConferenceError): msg.route", "(u'\"Fred\" <<EMAIL>>', u'Fred'), ] for name in names: with self.make_context(data={'from':", "'attachment-count': '1', 'X-Mailgun-Sscore': 0, 'from': '{0} <{1}>'.format(fullname, username), 'recipient': recipient,", ") @mock.patch('website.conferences.utils.upload_attachments') def test_add_poster_by_email(self, mock_upload_attachments): conference = ConferenceFactory() with self.make_context(data={'from':", "parsed_second.port = None assert_equal(parsed_first, parsed_second) def create_fake_conference_nodes(n, conference): nodes =", "n_conference_nodes_bad) def test_conference_data_url_upper(self): conference = ConferenceFactory() # Create conference nodes", "assert_in('spam', self.node.system_tags) @mock.patch('website.conferences.utils.waterbutler_api_url_for') @mock.patch('website.conferences.utils.requests.put') def test_upload(self, mock_put, mock_get_url): mock_get_url.return_value =", "def create_fake_conference_nodes_bad_data(conference, n, bad_n, endpoint): nodes = [] for i", "ProjectFactory(is_public=False) conf.submissions.add(private_node) assert_equal(conf.submissions.count(), 5) assert_equal(conf.valid_submissions.count(), 3) class TestConferenceIntegration(ContextTestCase): @mock.patch('website.conferences.views.send_mail') @mock.patch('website.conferences.utils.upload_attachments')", "'slightly mad' sio = StringIO(content) ctx = self.make_context( method='POST', data={", "}, expect_errors=True, ) assert_equal(res.status_code, 406) call_args, call_kwargs = mock_send_mail.call_args assert_equal(call_args,", "msg = message.ConferenceMessage() assert_equal(msg.sender_name, name[1]) def test_sender_email(self): emails = [", "self.conference.submissions.all() assert_not_in('spam', self.node.system_tags) def test_provision_private(self): self.conference.public_projects = False self.conference.save() with", "if value is not None } return self.app.app.test_request_context(method=method, data=data, **kwargs)", "node.save() nodes.append(node) return nodes class TestConferenceUtils(OsfTestCase): def test_get_or_create_user_exists(self): user =", "name=settings.MISSING_FILE_NAME, ) mock_put.assert_called_with( mock_get_url.return_value, data=self.content, ) @mock.patch('website.conferences.utils.upload_attachments') def test_add_poster_by_email(self, mock_upload_attachments):", "conference = ConferenceFactory() user = UserFactory() title = 'Long Live", "name='Hamburger conference') conf.save() # 3 good nodes added create_fake_conference_nodes(3, conf)", "def test_verify_signature_invalid(self): with self.make_context(data={'signature': 'fake'}): self.app.app.preprocess_request() msg = message.ConferenceMessage() with", "ConferenceFactory(endpoint='StudySwap') url = web_url_for('conference_results', meeting='studyswap') res = self.app.get(url) assert_equal(res.status_code, 200)", "TIME!'}): msg = message.ConferenceMessage() views.add_poster_by_email(conference, msg) user = OSFUser.objects.get(username='<EMAIL>') assert", "msg = message.ConferenceMessage() assert_equal(msg.conference_name, 'chocolate') assert_equal(msg.conference_category, 'data') conf.__class__.delete(conf) def test_route_valid_b(self):", "= furl.furl(settings.DOMAIN) parsed_url = furl.furl(url) assert_equal(parsed_domain.host, parsed_url.host) def assert_equal_urls(first, second):", "self.app.get(url) assert_equal(res.status_code, 200) assert_equal(len(res.json), n_conference_nodes) # Regression for OSF-8864 to", "= True deleted_node.save() conf.submissions.add(deleted_node) # Private node added private_node =", "'X-Mailgun-Dkim-Check-Result': message.DKIM_PASS_VALUES[0], 'X-Mailgun-Spf': message.SPF_PASS_VALUES[0], }, ) with ctx: msg =", "message.ConferenceMessage() assert_equal(msg.text, text) def test_sender_name(self): names = [ (' Fred',", "self.user) assert_false(self.node.is_public) assert_in(self.conference.admins.first(), self.node.contributors) assert_in('emailed', self.node.system_tags) assert_not_in('spam', self.node.system_tags) def test_provision_spam(self):", "fake from osf_tests.factories import ConferenceFactory, ProjectFactory, UserFactory def assert_absolute(url): parsed_domain", "email[0]}): msg = message.ConferenceMessage() assert_equal(msg.sender_email, email[1]) def test_route_invalid_pattern(self): with self.make_context(data={'recipient':", "'data') conf.__class__.delete(conf) def test_route_valid_b(self): recipient = '{0}<EMAIL>'.format('test-' if settings.DEV_MODE else", "utils, message from website.util import api_url_for, web_url_for from tests.base import", "n_conference_nodes) # Regression for OSF-8864 to confirm bad project data", "digestmod=hashlib.sha256, ).hexdigest(), 'attachment-count': '1', 'X-Mailgun-Sscore': 0, 'from': '{0} <{1}>'.format(user.fullname, user.username),", "url = web_url_for('conference_results', meeting='studyswap') res = self.app.get(url) assert_equal(res.status_code, 200) class", "test_get_or_create_user_with_blacklisted_domain(self): fullname = 'Kanye West' username = '<EMAIL>' with assert_raises(BlacklistedEmailError)", "u'<EMAIL>') ] for email in emails: with self.make_context(data={'from': email[0]}): msg", "= ConferenceFactory(endpoint='Hamburgers', name='Hamburger conference') conf.save() # 3 good nodes added", "call_args, call_kwargs = mock_send_mail.call_args assert_absolute(call_kwargs['conf_view_url']) assert_absolute(call_kwargs['set_password_url']) assert_absolute(call_kwargs['profile_url']) assert_absolute(call_kwargs['file_url']) assert_absolute(call_kwargs['node_url']) @mock.patch('website.conferences.views.send_mail')", "200) assert_equal(len(res.json), n_conference_nodes) # Regression for OSF-8864 to confirm bad", "def test_conference_data_url_upper(self): conference = ConferenceFactory() # Create conference nodes n_conference_nodes", "cls.MAILGUN_API_KEY, settings.MAILGUN_API_KEY @classmethod def tearDownClass(cls): super(ContextTestCase, cls).tearDownClass() settings.MAILGUN_API_KEY = cls._MAILGUN_API_KEY", "msg.is_spam def test_is_spam_true_dkim(self): ctx = self.make_context( method='POST', data={'X-Mailgun-Dkim-Check-Result': message.DKIM_PASS_VALUES[0][::-1]}, )", "test_create_conference_node_with_same_name_as_existing_node(self, mock_upload, mock_send_mail): conference = ConferenceFactory() user = UserFactory() title", "msg = message.ConferenceMessage() assert not msg.is_spam def test_is_spam_false_all_headers(self): ctx =", "'<EMAIL>' ctx = self.make_context( method='POST', data={'recipient': address}, ) with ctx:", "= message.ConferenceMessage() assert_equal(msg.conference_name, 'conf') assert_equal(msg.conference_category, 'poster') def test_alternate_route_invalid(self): recipient =", "base_url=self.node.osfstorage_region.waterbutler_url, cookie=self.user.get_or_create_cookie(), name=settings.MISSING_FILE_NAME, ) mock_put.assert_called_with( mock_get_url.return_value, data=self.content, ) @mock.patch('website.conferences.utils.upload_attachments') def", "TestConferenceIntegration(ContextTestCase): @mock.patch('website.conferences.views.send_mail') @mock.patch('website.conferences.utils.upload_attachments') def test_integration(self, mock_upload, mock_send_mail): fullname = '<NAME>'", "my back' recipient = '{0}{1}-<EMAIL>'.format( 'test-' if settings.DEV_MODE else '',", "test_is_spam_true_dkim(self): ctx = self.make_context( method='POST', data={'X-Mailgun-Dkim-Check-Result': message.DKIM_PASS_VALUES[0][::-1]}, ) with ctx:", "= ProjectFactory() self.user = self.node.creator self.conference = ConferenceFactory() self.body =", "user.username), 'recipient': recipient, 'subject': title, 'stripped-text': body, }, upload_files=[ ('attachment-1',", "create_fake_conference_nodes( 2, conference2, ) url = api_url_for('conference_submissions') res = self.app.get(url)", "nodes n_conference_nodes = 3 create_fake_conference_nodes( n_conference_nodes, conference, ) # Create", "test_upload(self, mock_put, mock_get_url): mock_get_url.return_value = 'http://queen.com/' file_name = 'hammer-to-fall' self.attachment.filename", "we use the guid. class TestMessage(ContextTestCase): PUSH_CONTEXT = False def", "'fake'}): self.app.app.preprocess_request() msg = message.ConferenceMessage() with assert_raises(message.ConferenceError): msg.verify_signature() def test_is_spam_false_missing_headers(self):", "self.node._id, 'osfstorage', _internal=True, base_url=self.node.osfstorage_region.waterbutler_url, cookie=self.user.get_or_create_cookie(), name=settings.MISSING_FILE_NAME, ) mock_put.assert_called_with( mock_get_url.return_value, data=self.content,", "= 'dragon attack' recipient = '{0}{1}-<EMAIL>'.format( 'test-' if settings.DEV_MODE else", "msg = message.ConferenceMessage() assert msg.is_spam def test_subject(self): ctx = self.make_context(", "self.node.creator self.conference = ConferenceFactory() self.body = 'dragon on my back'", "conf.save() recipient = '{0}<EMAIL>'.format('test-' if settings.DEV_MODE else '') with self.make_context(data={'recipient':", "create_fake_conference_nodes(n, conference): nodes = [] for i in range(n): node", "message.ConferenceMessage() assert_equal(len(msg.attachments), 1) assert_equal(msg.attachments[0].read(), content) class TestConferenceEmailViews(OsfTestCase): def test_redirect_to_meetings_url(self): url", "def test_conference_data_tag_upper(self): conference = ConferenceFactory() # Create conference nodes n_conference_nodes", "test_attachments_count_zero(self): with self.make_context(data={'attachment-count': '0'}): msg = message.ConferenceMessage() assert_equal(msg.attachments, []) def", "url = api_url_for('conference_submissions') res = self.app.get(url) assert_equal(res.json['success'], True) def test_conference_plain_returns_200(self):", "self).make_context(data=data, **kwargs) def test_provision(self): with self.make_context(): msg = message.ConferenceMessage() utils.provision_node(self.conference,", "names = [ (' Fred', 'Fred'), (u'Me䬟', u'Me䬟'), (u'<EMAIL>', u'<EMAIL>'),", "node = ProjectFactory(is_public=True) conference.submissions.add(node) node.save() nodes.append(node) return nodes def create_fake_conference_nodes_bad_data(conference,", "self.conference.public_projects = False self.conference.save() with self.make_context(): msg = message.ConferenceMessage() utils.provision_node(self.conference,", "def test_get_or_create_user_with_blacklisted_domain(self): fullname = 'Kanye West' username = '<EMAIL>' with", "= message.ConferenceMessage() assert_equal(msg.text, text) def test_sender_name(self): names = [ ('", "OSF-8864 to confirm bad project data does not make whole", "username), 'recipient': recipient, 'subject': title, 'stripped-text': body, }, upload_files=[ ('attachment-1',", "= message.ConferenceMessage() assert msg.is_spam def test_subject(self): ctx = self.make_context( method='POST',", "3) class TestConferenceIntegration(ContextTestCase): @mock.patch('website.conferences.views.send_mail') @mock.patch('website.conferences.utils.upload_attachments') def test_integration(self, mock_upload, mock_send_mail): fullname", "'secret', 'signature': hmac.new( key=settings.MAILGUN_API_KEY, msg='{}{}'.format('123', 'secret'), digestmod=hashlib.sha256, ).hexdigest(), } data.update(kwargs.pop('data',", "_absolute=True), ) @mock.patch('website.conferences.views.send_mail') @mock.patch('website.conferences.utils.upload_attachments') def test_integration_wo_full_name(self, mock_upload, mock_send_mail): username =", "conf = ConferenceFactory(endpoint='chocolate', active=True) conf.name = 'Chocolate Conference' conf.field_names['submission2'] =", "name only email' conference = ConferenceFactory() body = 'dragon on", "0, 'recipient': self.recipient, 'stripped-text': self.body, } data.update(kwargs.pop('data', {})) return super(TestProvisionNode,", "added create_fake_conference_nodes(3, conf) # Deleted node added deleted_node = ProjectFactory(is_public=True)", "self.make_context( method='POST', data={'stripped-text': text}, ) with ctx: msg = message.ConferenceMessage()", "msg.route def test_attachments_count_zero(self): with self.make_context(data={'attachment-count': '0'}): msg = message.ConferenceMessage() assert_equal(msg.attachments,", "test_default_field_names(self): conf = ConferenceFactory(endpoint='cookie', name='Cookies Conference') conf.save() assert_equal(conf.field_names['submission1'], 'poster') assert_equal(conf.field_names['mail_subject'],", "digestmod=hashlib.sha256, ).hexdigest(), 'attachment-count': '1', 'X-Mailgun-Sscore': 0, 'from': '{0} <{1}>'.format(fullname, username),", "IntegrityError import furl from framework.auth import get_or_create_user from framework.auth.core import", "assert_equal(conf.submissions.count(), 5) assert_equal(conf.valid_submissions.count(), 3) class TestConferenceIntegration(ContextTestCase): @mock.patch('website.conferences.views.send_mail') @mock.patch('website.conferences.utils.upload_attachments') def test_integration(self,", "msg.is_spam def test_subject(self): ctx = self.make_context( method='POST', data={'subject': 'RE: Hip", "200) assert_equal(len(res.json), n_conference_nodes - n_conference_nodes_bad) def test_conference_data_url_upper(self): conference = ConferenceFactory()", "- n_conference_nodes_bad) def test_conference_data_url_upper(self): conference = ConferenceFactory() # Create conference", "OSFUser.objects.filter(username=username) assert_equal(users.count(), 1) nodes = AbstractNode.objects.filter(title=title) assert_equal(nodes.count(), 1) node =", "email' conference = ConferenceFactory() body = 'dragon on my back'", "assert_raises(BlacklistedEmailError) as e: get_or_create_user(fullname, username, is_spam=True) assert_equal(e.exception.message, 'Invalid Email') class", "u'Me䬟'), (u'<EMAIL>', u'<EMAIL>'), (u'Fred <<EMAIL>>', u'Fred'), (u'\"Fred\" <<EMAIL>>', u'Fred'), ]", "200) assert_equal(len(res.json), n_conference_nodes) def test_conference_results(self): conference = ConferenceFactory() url =", "msg = message.ConferenceMessage() assert_equal(msg.sender_email, email[1]) def test_route_invalid_pattern(self): with self.make_context(data={'recipient': '<EMAIL>'}):", "import get_or_create_user from framework.auth.core import Auth from osf.models import OSFUser,", "= 3 create_fake_conference_nodes( n_conference_nodes, conference, ) # Create a non-conference", "**kwargs) class TestProvisionNode(ContextTestCase): def setUp(self): super(TestProvisionNode, self).setUp() self.node = ProjectFactory()", "to access m2m fields, e.g. tags assert_true(created) assert_equal(fetched.fullname, fullname) assert_equal(fetched.username,", "3 create_fake_conference_nodes( n_conference_nodes, conference, ) # Create a non-conference node", "= [ (u'<EMAIL>', u'<EMAIL>'), (u'<EMAIL>', u'<EMAIL>') ] for email in", "fullname = 'Kanye West' username = '<EMAIL>' with assert_raises(BlacklistedEmailError) as", "= 'welcome to my nuclear family' ctx = self.make_context( method='POST',", "self.node, self.user) assert_false(self.node.is_public) assert_in(self.conference.admins.first(), self.node.contributors) assert_in('emailed', self.node.system_tags) assert_not_in('spam', self.node.system_tags) def", "with self.make_context(): msg = message.ConferenceMessage() utils.provision_node(self.conference, msg, self.node, self.user) assert_false(self.node.is_public)", "WikiVersion from osf.exceptions import BlacklistedEmailError from website import settings from", "ConferenceFactory(endpoint='Hamburgers', name='Hamburger conference') conf.save() # 3 good nodes added create_fake_conference_nodes(3,", "value for key, value in data.items() if value is not", "def test_conference_plain_returns_200(self): conference = ConferenceFactory() url = web_url_for('conference_results__plain', meeting=conference.endpoint) res", "data = { key: value for key, value in data.items()", "conference = ConferenceFactory() body = 'dragon on my back' content", "def test_conference_submissions(self): AbstractNode.objects.all().delete() conference1 = ConferenceFactory() conference2 = ConferenceFactory() #", "method='POST', data={'stripped-text': text}, ) with ctx: msg = message.ConferenceMessage() assert_equal(msg.text,", "'attachment-1', content), ], ) assert AbstractNode.objects.filter(title=title, creator=user).count() == 2 assert", "'home').content, body) assert_true(mock_send_mail.called) call_args, call_kwargs = mock_send_mail.call_args assert_absolute(call_kwargs['conf_view_url']) assert_absolute(call_kwargs['set_password_url']) assert_absolute(call_kwargs['profile_url'])", "call_args, call_kwargs = mock_send_mail.call_args assert_equal(call_args, (username, views.CONFERENCE_INACTIVE)) assert_equal(call_kwargs['fullname'], fullname) assert_equal_urls(", "self.content = 'dragon attack' self.attachment = StringIO(self.content) self.recipient = '{0}{1}-<EMAIL>'.format(", "= file_name self.attachment.content_type = 'application/json' utils.upload_attachment(self.user, self.node, self.attachment) mock_get_url.assert_called_with( self.node._id,", "self.node, self.user) assert_false(self.node.is_public) assert_in(self.conference.admins.first(), self.node.contributors) assert_in('emailed', self.node.system_tags) assert_in('spam', self.node.system_tags) @mock.patch('website.conferences.utils.waterbutler_api_url_for')", "test_is_spam_false_missing_headers(self): ctx = self.make_context( method='POST', data={'X-Mailgun-Sscore': message.SSCORE_MAX_VALUE - 1}, )", "nodes[0] assert_equal(WikiVersion.objects.get_for_node(node, 'home').content, body) assert_true(mock_send_mail.called) call_args, call_kwargs = mock_send_mail.call_args assert_absolute(call_kwargs['conf_view_url'])", "message.ConferenceMessage() with assert_raises(message.ConferenceError): msg.route def test_attachments_count_zero(self): with self.make_context(data={'attachment-count': '0'}): msg", "<{1}>'.format(fullname, username), 'recipient': recipient, 'subject': title, 'stripped-text': body, }, upload_files=[", "conf.field_names['submission2'] = 'data' conf.save() recipient = '{0}<EMAIL>'.format('test-' if settings.DEV_MODE else", "call_kwargs = mock_send_mail.call_args assert_equal(call_args, (username, views.CONFERENCE_INACTIVE)) assert_equal(call_kwargs['fullname'], fullname) assert_equal_urls( call_kwargs['presentations_url'],", "@mock.patch('website.conferences.utils.upload_attachments') def test_integration(self, mock_upload, mock_send_mail): fullname = '<NAME>' username =", "the guid. class TestMessage(ContextTestCase): PUSH_CONTEXT = False def test_verify_signature_valid(self): with", "= self.app.get(url) assert_equal(res.status_code, 302) res = res.follow() assert_equal(res.request.path, '/meetings/') def", "mock_send_mail.call_args assert_absolute(call_kwargs['conf_view_url']) assert_absolute(call_kwargs['set_password_url']) assert_absolute(call_kwargs['profile_url']) assert_absolute(call_kwargs['file_url']) assert_absolute(call_kwargs['node_url']) @mock.patch('website.conferences.views.send_mail') @mock.patch('website.conferences.utils.upload_attachments') def test_create_conference_node_with_same_name_as_existing_node(self,", "parsed_url.host) def assert_equal_urls(first, second): parsed_first = furl.furl(first) parsed_first.port = None", ") with ctx: msg = message.ConferenceMessage() assert msg.is_spam def test_subject(self):", "# Deleted node added deleted_node = ProjectFactory(is_public=True) deleted_node.is_deleted = True", "self.make_context( method='POST', data={ 'X-Mailgun-Sscore': message.SSCORE_MAX_VALUE - 1, 'X-Mailgun-Dkim-Check-Result': message.DKIM_PASS_VALUES[0], 'X-Mailgun-Spf':", "'{0}<EMAIL>'.format('' if settings.DEV_MODE else 'stage-') with self.make_context(data={'recipient': recipient}): self.app.app.preprocess_request() msg", "mock_send_mail): conference = ConferenceFactory() user = UserFactory() title = 'Long", "# Create a non-conference node ProjectFactory() url = api_url_for('conference_data', meeting=conference.endpoint.upper())", "assert_raises(IntegrityError): ConferenceFactory(endpoint=None, name=fake.company()).save() def test_name_is_required(self): with assert_raises(IntegrityError): ConferenceFactory(endpoint='spsp2014', name=None).save() def", "self.make_context(data={'from': name[0]}): msg = message.ConferenceMessage() assert_equal(msg.sender_name, name[1]) def test_sender_email(self): emails", "may they reign.' recipient = '{0}{1}-<EMAIL>'.format( 'test-' if settings.DEV_MODE else", "assert_absolute(call_kwargs['node_url']) @mock.patch('website.conferences.views.send_mail') @mock.patch('website.conferences.utils.upload_attachments') def test_create_conference_node_with_same_name_as_existing_node(self, mock_upload, mock_send_mail): conference = ConferenceFactory()", "Email') class ContextTestCase(OsfTestCase): MAILGUN_API_KEY = 'mailkimp' @classmethod def setUpClass(cls): super(ContextTestCase,", "import OsfTestCase, fake from osf_tests.factories import ConferenceFactory, ProjectFactory, UserFactory def", "conference nodes create_fake_conference_nodes( 3, conference1, ) create_fake_conference_nodes( 2, conference2, )", "nodes.append(node) return nodes class TestConferenceUtils(OsfTestCase): def test_get_or_create_user_exists(self): user = UserFactory()", "for email in emails: with self.make_context(data={'from': email[0]}): msg = message.ConferenceMessage()", "ConferenceFactory() # Create conference nodes n_conference_nodes = 3 create_fake_conference_nodes( n_conference_nodes,", "assert_equal(res.status_code, 200) def test_confererence_results_endpoint_is_case_insensitive(self): ConferenceFactory(endpoint='StudySwap') url = web_url_for('conference_results', meeting='studyswap') res", "use email as fullname, so we use the guid. class", "ConferenceFactory(endpoint='chocolate', active=True) conf.name = 'Chocolate Conference' conf.field_names['submission2'] = 'data' conf.save()", "test_route_invalid_pattern(self): with self.make_context(data={'recipient': '<EMAIL>'}): self.app.app.preprocess_request() msg = message.ConferenceMessage() with assert_raises(message.ConferenceError):", "username), 'recipient': recipient, 'subject': title, 'stripped-text': body, }, expect_errors=True, )", "_internal=True, base_url=self.node.osfstorage_region.waterbutler_url, cookie=self.user.get_or_create_cookie(), name=settings.MISSING_FILE_NAME, ) mock_put.assert_called_with( mock_get_url.return_value, data=self.content, ) @mock.patch('website.conferences.utils.upload_attachments')", "import hmac import hashlib from StringIO import StringIO from django.core.exceptions", "'Presentation title') def test_conference_valid_submissions(self): conf = ConferenceFactory(endpoint='Hamburgers', name='Hamburger conference') conf.save()", "class TestConferenceModel(OsfTestCase): def test_endpoint_is_required(self): with assert_raises(IntegrityError): ConferenceFactory(endpoint=None, name=fake.company()).save() def test_name_is_required(self):", "import api_url_for, web_url_for from tests.base import OsfTestCase, fake from osf_tests.factories", "self.app.app.preprocess_request() msg = message.ConferenceMessage() with assert_raises(message.ConferenceError): msg.route def test_attachments_count_zero(self): with", "# inject bad data if i < bad_n: # Delete", "ctx = self.make_context( method='POST', data={ 'attachment-count': 1, 'attachment-1': (sio, 'attachment-1'),", "MAILGUN_API_KEY = 'mailkimp' @classmethod def setUpClass(cls): super(ContextTestCase, cls).setUpClass() settings.MAILGUN_API_KEY, cls._MAILGUN_API_KEY", "= ConferenceFactory() self.body = 'dragon on my back' self.content =", "from osf.models import OSFUser, AbstractNode from addons.wiki.models import WikiVersion from", "username) assert_false('is_spam' in fetched.system_tags) def test_get_or_create_user_is_spam(self): fullname = '<NAME>' username", "title, 'stripped-text': body, }, upload_files=[ ('attachment-1', 'attachment-1', content), ], )", "message.SSCORE_MAX_VALUE + 1}): msg = message.ConferenceMessage() utils.provision_node(self.conference, msg, self.node, self.user)", "only email' conference = ConferenceFactory() body = 'dragon on my", "on my back' recipient = '{0}{1}-<EMAIL>'.format( 'test-' if settings.DEV_MODE else", "= UserFactory() fetched, created = get_or_create_user(user.fullname, user.username, is_spam=True) assert_false(created) assert_equal(user._id,", "self.conference = ConferenceFactory() self.body = 'dragon on my back' self.content", "assert_in(self.conference.admins.first(), self.node.contributors) assert_in('emailed', self.node.system_tags) assert_not_in('spam', self.node.system_tags) def test_provision_spam(self): with self.make_context(data={'X-Mailgun-Sscore':", "def test_route_invalid_pattern(self): with self.make_context(data={'recipient': '<EMAIL>'}): self.app.app.preprocess_request() msg = message.ConferenceMessage() with", "= mock_send_mail.call_args assert_absolute(call_kwargs['conf_view_url']) assert_absolute(call_kwargs['set_password_url']) assert_absolute(call_kwargs['profile_url']) assert_absolute(call_kwargs['file_url']) assert_absolute(call_kwargs['node_url']) @mock.patch('website.conferences.views.send_mail') @mock.patch('website.conferences.utils.upload_attachments') def", "fetched.system_tags) def test_get_or_create_user_with_blacklisted_domain(self): fullname = 'Kanye West' username = '<EMAIL>'", "conf.__class__.delete(conf) def test_route_valid_b(self): recipient = '{0}<EMAIL>'.format('test-' if settings.DEV_MODE else '')", "'Chocolate Conference' conf.field_names['submission2'] = 'data' conf.save() recipient = '{0}<EMAIL>'.format('test-' if", "body = 'dragon on my back' recipient = '{0}{1}-<EMAIL>'.format( 'test-'", "self.node.system_tags) assert self.node in self.conference.submissions.all() assert_not_in('spam', self.node.system_tags) def test_provision_private(self): self.conference.public_projects", "self.attachment = StringIO(self.content) self.recipient = '{0}{1}-<EMAIL>'.format( 'test-' if settings.DEV_MODE else", "TestMessage(ContextTestCase): PUSH_CONTEXT = False def test_verify_signature_valid(self): with self.make_context(): msg =", "back' recipient = '{0}{1}-<EMAIL>'.format( 'test-' if settings.DEV_MODE else '', conference.endpoint,", "msg = message.ConferenceMessage() with assert_raises(message.ConferenceError): msg.verify_signature() def test_is_spam_false_missing_headers(self): ctx =", "to my nuclear family' ctx = self.make_context( method='POST', data={'stripped-text': text},", "conference = ConferenceFactory(active=False) fullname = '<NAME>' username = '<EMAIL>' title", "'poster') def test_alternate_route_invalid(self): recipient = '{0}<EMAIL>'.format('test-' if settings.DEV_MODE else '')", "from addons.wiki.models import WikiVersion from osf.exceptions import BlacklistedEmailError from website", "= 'data' conf.save() recipient = '{0}<EMAIL>'.format('test-' if settings.DEV_MODE else '')", "u'<EMAIL>'), (u'<EMAIL>', u'<EMAIL>') ] for email in emails: with self.make_context(data={'from':", "deleted_node = ProjectFactory(is_public=True) deleted_node.is_deleted = True deleted_node.save() conf.submissions.add(deleted_node) # Private", "self.make_context(): msg = message.ConferenceMessage() utils.provision_node(self.conference, msg, self.node, self.user) assert_true(self.node.is_public) assert_in(self.conference.admins.first(),", "call_kwargs = mock_send_mail.call_args assert_absolute(call_kwargs['conf_view_url']) assert_absolute(call_kwargs['set_password_url']) assert_absolute(call_kwargs['profile_url']) assert_absolute(call_kwargs['file_url']) assert_absolute(call_kwargs['node_url']) @mock.patch('website.conferences.views.send_mail') def", "'timestamp': '123', 'token': 'secret', 'signature': hmac.new( key=settings.MAILGUN_API_KEY, msg='{}{}'.format('123', 'secret'), digestmod=hashlib.sha256,", "'<EMAIL>' fetched, created = get_or_create_user(fullname, username, is_spam=True) fetched.save() # in", "1) node = nodes[0] assert_equal(WikiVersion.objects.get_for_node(node, 'home').content, body) assert_true(mock_send_mail.called) call_args, call_kwargs", "class TestMessage(ContextTestCase): PUSH_CONTEXT = False def test_verify_signature_valid(self): with self.make_context(): msg", "def test_redirect_to_meetings_url(self): url = '/presentations/' res = self.app.get(url) assert_equal(res.status_code, 302)", "'conf') assert_equal(msg.conference_category, 'poster') def test_alternate_route_invalid(self): recipient = '{0}<EMAIL>'.format('test-' if settings.DEV_MODE", "ConferenceFactory() # Create conference nodes create_fake_conference_nodes( 3, conference1, ) create_fake_conference_nodes(", "message.SPF_PASS_VALUES[0][::-1]}, ) with ctx: msg = message.ConferenceMessage() assert msg.is_spam def", "message.ConferenceMessage() views.add_poster_by_email(conference, msg) user = OSFUser.objects.get(username='<EMAIL>') assert user.email == '<EMAIL>'", "n_conference_nodes, conference, ) # Create a non-conference node ProjectFactory() url", "self.app.app.preprocess_request() msg = message.ConferenceMessage() with assert_raises(message.ConferenceError): msg.route def test_route_valid_alternate(self): conf", "# Create conference nodes n_conference_nodes = 3 n_conference_nodes_bad = 1", "Greg' ProjectFactory(creator=user, title=title) body = 'Greg is a good plant'", "test_subject(self): ctx = self.make_context( method='POST', data={'subject': 'RE: Hip Hopera'}, )", "'welcome to my nuclear family' ctx = self.make_context( method='POST', data={'stripped-text':", "200) assert_equal(len(res.json), n_conference_nodes) def test_conference_data_tag_upper(self): conference = ConferenceFactory() # Create", "'<NAME>' username = '<EMAIL>' fetched, created = get_or_create_user(fullname, username, is_spam=False)", "assert_equal(res.status_code, 200) assert_equal(len(res.json), n_conference_nodes) # Regression for OSF-8864 to confirm", "test_conference_submissions(self): AbstractNode.objects.all().delete() conference1 = ConferenceFactory() conference2 = ConferenceFactory() # Create", "self.node.system_tags) assert_in('spam', self.node.system_tags) @mock.patch('website.conferences.utils.waterbutler_api_url_for') @mock.patch('website.conferences.utils.requests.put') def test_upload(self, mock_put, mock_get_url): mock_get_url.return_value", "api_url_for('conference_data', meeting=conference.endpoint) res = self.app.get(url) assert_equal(res.status_code, 200) assert_equal(len(res.json), n_conference_nodes) #", "1) assert_equal(msg.attachments[0].read(), content) class TestConferenceEmailViews(OsfTestCase): def test_redirect_to_meetings_url(self): url = '/presentations/'", "= self.make_context( method='POST', data={'stripped-text': text}, ) with ctx: msg =", "nodes.append(node) return nodes def create_fake_conference_nodes_bad_data(conference, n, bad_n, endpoint): nodes =", "osf_tests.factories import ConferenceFactory, ProjectFactory, UserFactory def assert_absolute(url): parsed_domain = furl.furl(settings.DOMAIN)", "mock_upload, mock_send_mail): conference = ConferenceFactory() user = UserFactory() title =", "'dragon attack' recipient = '{0}{1}-<EMAIL>'.format( 'test-' if settings.DEV_MODE else '',", "} return self.app.app.test_request_context(method=method, data=data, **kwargs) class TestProvisionNode(ContextTestCase): def setUp(self): super(TestProvisionNode,", "attack' self.attachment = StringIO(self.content) self.recipient = '{0}{1}-<EMAIL>'.format( 'test-' if settings.DEV_MODE", "if settings.DEV_MODE else '', conference.endpoint, ) res = self.app.post( api_url_for('meeting_hook'),", "not None } return self.app.app.test_request_context(method=method, data=data, **kwargs) class TestProvisionNode(ContextTestCase): def", "method='POST', data={'X-Mailgun-Sscore': message.SSCORE_MAX_VALUE + 1}, ) with ctx: msg =", "upload_files=[ ('attachment-1', 'attachment-1', content), ], ) assert_true(mock_upload.called) users = OSFUser.objects.filter(username=username)", "create_fake_conference_nodes_bad_data( conference, n_conference_nodes, n_conference_nodes_bad, conference, ) # Create a non-conference", "self.app.get(url) assert_equal(res.status_code, 200) def test_conference_data(self): conference = ConferenceFactory() # Create", "def test_conference_data(self): conference = ConferenceFactory() # Create conference nodes n_conference_nodes", "with self.make_context(data={'X-Mailgun-Sscore': message.SSCORE_MAX_VALUE + 1}): msg = message.ConferenceMessage() utils.provision_node(self.conference, msg,", "data={'recipient': address}, ) with ctx: msg = message.ConferenceMessage() assert_equal(msg.recipient, address)", "bad data if i < bad_n: # Delete only contributor", "fetched, created = get_or_create_user(fullname, username, is_spam=True) fetched.save() # in order", "# Regression for OSF-8864 to confirm bad project data does", "def test_route_invalid_test(self): recipient = '{0}<EMAIL>'.format('' if settings.DEV_MODE else 'stage-') with", "= ProjectFactory(is_public=True) deleted_node.is_deleted = True deleted_node.save() conf.submissions.add(deleted_node) # Private node", "url = api_url_for('conference_data', meeting=conference.endpoint.upper()) res = self.app.get(url) assert_equal(res.status_code, 200) assert_equal(len(res.json),", "mock_put, mock_get_url): mock_get_url.return_value = 'http://queen.com/' file_name = 'hammer-to-fall' self.attachment.filename =", "with assert_raises(message.ConferenceError): msg.route def test_attachments_count_zero(self): with self.make_context(data={'attachment-count': '0'}): msg =", ") assert_equal(res.status_code, 406) call_args, call_kwargs = mock_send_mail.call_args assert_equal(call_args, (username, views.CONFERENCE_INACTIVE))", "@mock.patch('website.conferences.utils.waterbutler_api_url_for') @mock.patch('website.conferences.utils.requests.put') def test_upload_no_file_name(self, mock_put, mock_get_url): mock_get_url.return_value = 'http://queen.com/' self.attachment.filename", "assert_equal(conf.field_names['mail_subject'], 'Presentation title') def test_conference_valid_submissions(self): conf = ConferenceFactory(endpoint='Hamburgers', name='Hamburger conference')", "def test_is_spam_true_sscore(self): ctx = self.make_context( method='POST', data={'X-Mailgun-Sscore': message.SSCORE_MAX_VALUE + 1},", "= ConferenceFactory() # Create conference nodes create_fake_conference_nodes( 3, conference1, )", "self.node._id, 'osfstorage', _internal=True, base_url=self.node.osfstorage_region.waterbutler_url, cookie=self.user.get_or_create_cookie(), name=file_name ) mock_put.assert_called_with( mock_get_url.return_value, data=self.content,", "n_conference_nodes) def test_conference_results(self): conference = ConferenceFactory() url = web_url_for('conference_results', meeting=conference.endpoint)", "break def test_conference_bad_data(self): conference = ConferenceFactory() # Create conference nodes", "assert_equal(msg.sender_name, name[1]) def test_sender_email(self): emails = [ (u'<EMAIL>', u'<EMAIL>'), (u'<EMAIL>',", "5) assert_equal(conf.valid_submissions.count(), 3) class TestConferenceIntegration(ContextTestCase): @mock.patch('website.conferences.views.send_mail') @mock.patch('website.conferences.utils.upload_attachments') def test_integration(self, mock_upload,", "'no full name only email' conference = ConferenceFactory() body =", "assert_equal(e.exception.message, 'Invalid Email') class ContextTestCase(OsfTestCase): MAILGUN_API_KEY = 'mailkimp' @classmethod def", "UserFactory() title = 'Long Live Greg' ProjectFactory(creator=user, title=title) body =", "@classmethod def tearDownClass(cls): super(ContextTestCase, cls).tearDownClass() settings.MAILGUN_API_KEY = cls._MAILGUN_API_KEY def make_context(self,", "self.conference.endpoint, ) def make_context(self, **kwargs): data = { 'attachment-count': '1',", "Create conference nodes n_conference_nodes = 3 n_conference_nodes_bad = 1 create_fake_conference_nodes_bad_data(", "'<EMAIL>' assert user.fullname == user._id # user's shouldn't be able", "assert_absolute(call_kwargs['set_password_url']) assert_absolute(call_kwargs['profile_url']) assert_absolute(call_kwargs['file_url']) assert_absolute(call_kwargs['node_url']) @mock.patch('website.conferences.views.send_mail') def test_integration_inactive(self, mock_send_mail): conference =", "username, 'recipient': recipient, 'subject': title, 'stripped-text': body, }, upload_files=[ ('attachment-1',", "ProjectFactory(is_public=True) deleted_node.is_deleted = True deleted_node.save() conf.submissions.add(deleted_node) # Private node added", "whole conference break def test_conference_bad_data(self): conference = ConferenceFactory() # Create", ") res = self.app.post( api_url_for('meeting_hook'), { 'X-Mailgun-Sscore': 0, 'timestamp': '123',", "fetched._id) assert_false('is_spam' in fetched.system_tags) def test_get_or_create_user_not_exists(self): fullname = '<NAME>' username", "return nodes class TestConferenceUtils(OsfTestCase): def test_get_or_create_user_exists(self): user = UserFactory() fetched,", "msg = message.ConferenceMessage() utils.provision_node(self.conference, msg, self.node, self.user) assert_true(self.node.is_public) assert_in(self.conference.admins.first(), self.node.contributors)", "message.ConferenceMessage() utils.provision_node(self.conference, msg, self.node, self.user) assert_false(self.node.is_public) assert_in(self.conference.admins.first(), self.node.contributors) assert_in('emailed', self.node.system_tags)", "self.user) assert_true(self.node.is_public) assert_in(self.conference.admins.first(), self.node.contributors) assert_in('emailed', self.node.system_tags) assert_in(self.conference.endpoint, self.node.system_tags) assert self.node", "assert_equal(msg.recipient, address) def test_text(self): text = 'welcome to my nuclear", "assert_equal(call_kwargs['fullname'], fullname) assert_equal_urls( call_kwargs['presentations_url'], web_url_for('conference_view', _absolute=True), ) @mock.patch('website.conferences.views.send_mail') @mock.patch('website.conferences.utils.upload_attachments') def", "msg.verify_signature() def test_verify_signature_invalid(self): with self.make_context(data={'signature': 'fake'}): self.app.app.preprocess_request() msg = message.ConferenceMessage()", "create_fake_conference_nodes_bad_data(conference, n, bad_n, endpoint): nodes = [] for i in", "self.app.app.test_request_context(method=method, data=data, **kwargs) class TestProvisionNode(ContextTestCase): def setUp(self): super(TestProvisionNode, self).setUp() self.node", "get_or_create_user(fullname, username, is_spam=True) assert_equal(e.exception.message, 'Invalid Email') class ContextTestCase(OsfTestCase): MAILGUN_API_KEY =", "settings.DEV_MODE else '', conference.endpoint, ) self.app.post( api_url_for('meeting_hook'), { 'X-Mailgun-Sscore': 0,", "= 1 create_fake_conference_nodes_bad_data( conference, n_conference_nodes, n_conference_nodes_bad, conference, ) # Create", "def test_is_spam_true_dkim(self): ctx = self.make_context( method='POST', data={'X-Mailgun-Dkim-Check-Result': message.DKIM_PASS_VALUES[0][::-1]}, ) with", "with assert_raises(IntegrityError): ConferenceFactory(endpoint=None, name=fake.company()).save() def test_name_is_required(self): with assert_raises(IntegrityError): ConferenceFactory(endpoint='spsp2014', name=None).save()", "username, is_spam=True) fetched.save() # in order to access m2m fields,", "assert_raises(IntegrityError): ConferenceFactory(endpoint='spsp2014', name=None).save() def test_default_field_names(self): conf = ConferenceFactory(endpoint='cookie', name='Cookies Conference')", "self.body = 'dragon on my back' self.content = 'dragon attack'", "'test-' if settings.DEV_MODE else '', self.conference.endpoint, ) def make_context(self, **kwargs):", "in emails: with self.make_context(data={'from': email[0]}): msg = message.ConferenceMessage() assert_equal(msg.sender_email, email[1])", "def assert_absolute(url): parsed_domain = furl.furl(settings.DOMAIN) parsed_url = furl.furl(url) assert_equal(parsed_domain.host, parsed_url.host)", "ProjectFactory() url = api_url_for('conference_data', meeting=conference.endpoint.upper()) res = self.app.get(url) assert_equal(res.status_code, 200)", "self.attachment.filename = '' self.attachment.content_type = 'application/json' utils.upload_attachment(self.user, self.node, self.attachment) mock_get_url.assert_called_with(", "StringIO import StringIO from django.core.exceptions import ValidationError from django.db import", "assert_true(created) assert_equal(fetched.fullname, fullname) assert_equal(fetched.username, username) assert_true('is_spam' in fetched.system_tags) def test_get_or_create_user_with_blacklisted_domain(self):", "test_is_spam_true_spf(self): ctx = self.make_context( method='POST', data={'X-Mailgun-Spf': message.SPF_PASS_VALUES[0][::-1]}, ) with ctx:", "@mock.patch('website.conferences.utils.requests.put') def test_upload_no_file_name(self, mock_put, mock_get_url): mock_get_url.return_value = 'http://queen.com/' self.attachment.filename =", "= message.ConferenceMessage() assert_equal(msg.conference_name, 'chocolate') assert_equal(msg.conference_category, 'data') conf.__class__.delete(conf) def test_route_valid_b(self): recipient", "test_upload_no_file_name(self, mock_put, mock_get_url): mock_get_url.return_value = 'http://queen.com/' self.attachment.filename = '' self.attachment.content_type", "test_integration_wo_full_name(self, mock_upload, mock_send_mail): username = '<EMAIL>' title = 'no full", "'{0}{1}-<EMAIL>'.format( 'test-' if settings.DEV_MODE else '', self.conference.endpoint, ) def make_context(self,", "method='POST', data={'recipient': address}, ) with ctx: msg = message.ConferenceMessage() assert_equal(msg.recipient,", "Create conference nodes create_fake_conference_nodes( 3, conference1, ) create_fake_conference_nodes( 2, conference2,", "web_url_for('conference_results__plain', meeting=conference.endpoint) res = self.app.get(url) assert_equal(res.status_code, 200) def test_conference_data(self): conference", "file_name = 'hammer-to-fall' self.attachment.filename = file_name self.attachment.content_type = 'application/json' utils.upload_attachment(self.user,", "good nodes added create_fake_conference_nodes(3, conf) # Deleted node added deleted_node", "res = self.app.post( api_url_for('meeting_hook'), { 'X-Mailgun-Sscore': 0, 'timestamp': '123', 'token':", "msg = message.ConferenceMessage() assert_equal(msg.subject, 'Hip Hopera') def test_recipient(self): address =", "}, upload_files=[ ('attachment-1', 'attachment-1', content), ], ) assert_true(mock_upload.called) users =", "import hashlib from StringIO import StringIO from django.core.exceptions import ValidationError", ") # Create a non-conference node ProjectFactory() url = api_url_for('conference_data',", "'Fred'), (u'Me䬟', u'Me䬟'), (u'<EMAIL>', u'<EMAIL>'), (u'Fred <<EMAIL>>', u'Fred'), (u'\"Fred\" <<EMAIL>>',", "assert not msg.is_spam def test_is_spam_false_all_headers(self): ctx = self.make_context( method='POST', data={", "# noqa (PEP8 asserts) import hmac import hashlib from StringIO", "**kwargs): data = { 'X-Mailgun-Sscore': 0, 'timestamp': '123', 'token': 'secret',", "message.ConferenceMessage() assert_equal(msg.conference_name, 'chocolate') assert_equal(msg.conference_category, 'data') conf.__class__.delete(conf) def test_route_valid_b(self): recipient =", "self.attachment) mock_get_url.assert_called_with( self.node._id, 'osfstorage', _internal=True, base_url=self.node.osfstorage_region.waterbutler_url, cookie=self.user.get_or_create_cookie(), name=settings.MISSING_FILE_NAME, ) mock_put.assert_called_with(", "PARTY TIME!'}): msg = message.ConferenceMessage() views.add_poster_by_email(conference, msg) user = OSFUser.objects.get(username='<EMAIL>')", "'<EMAIL>' title = 'good songs' conference = ConferenceFactory() body =", "'') with self.make_context(data={'recipient': recipient}): self.app.app.preprocess_request() msg = message.ConferenceMessage() assert_equal(msg.conference_name, 'chocolate')", "= message.ConferenceMessage() assert not msg.is_spam def test_is_spam_true_sscore(self): ctx = self.make_context(", "name[1]) def test_sender_email(self): emails = [ (u'<EMAIL>', u'<EMAIL>'), (u'<EMAIL>', u'<EMAIL>')", "res = self.app.get(url) assert_equal(res.status_code, 200) assert_equal(len(res.json), n_conference_nodes) # Regression for", "def test_recipient(self): address = '<EMAIL>' ctx = self.make_context( method='POST', data={'recipient':", "furl.furl(settings.DOMAIN) parsed_url = furl.furl(url) assert_equal(parsed_domain.host, parsed_url.host) def assert_equal_urls(first, second): parsed_first", "test_integration_inactive(self, mock_send_mail): conference = ConferenceFactory(active=False) fullname = '<NAME>' username =", "self.app.app.preprocess_request() msg = message.ConferenceMessage() assert_equal(msg.conference_name, 'conf') assert_equal(msg.conference_category, 'poster') def test_alternate_route_invalid(self):", "= '<EMAIL>' title = 'good songs' body = 'dragon on", "added deleted_node = ProjectFactory(is_public=True) deleted_node.is_deleted = True deleted_node.save() conf.submissions.add(deleted_node) #", "message from website.util import api_url_for, web_url_for from tests.base import OsfTestCase,", "msg='{}{}'.format('123', 'secret'), digestmod=hashlib.sha256, ).hexdigest(), 'attachment-count': '1', 'X-Mailgun-Sscore': 0, 'from': '{0}", "Deleted node added deleted_node = ProjectFactory(is_public=True) deleted_node.is_deleted = True deleted_node.save()", "assert_equal(fetched.username, username) assert_false('is_spam' in fetched.system_tags) def test_get_or_create_user_is_spam(self): fullname = '<NAME>'", "key, value in data.items() if value is not None }", "(self.attachment, 'attachment-1'), 'X-Mailgun-Sscore': 0, 'recipient': self.recipient, 'stripped-text': self.body, } data.update(kwargs.pop('data',", "user._id # user's shouldn't be able to use email as", "1}): msg = message.ConferenceMessage() utils.provision_node(self.conference, msg, self.node, self.user) assert_false(self.node.is_public) assert_in(self.conference.admins.first(),", "def test_conference_results(self): conference = ConferenceFactory() url = web_url_for('conference_results', meeting=conference.endpoint) res", "'<EMAIL>', 'subject': 'It\\'s PARTY TIME!'}): msg = message.ConferenceMessage() views.add_poster_by_email(conference, msg)", "node ProjectFactory() url = api_url_for('conference_data', meeting=conference.endpoint.upper()) res = self.app.get(url) assert_equal(res.status_code,", "test_conference_data(self): conference = ConferenceFactory() # Create conference nodes n_conference_nodes =", "= message.ConferenceMessage() with assert_raises(message.ConferenceError): msg.verify_signature() def test_is_spam_false_missing_headers(self): ctx = self.make_context(", "m2m fields, e.g. tags assert_true(created) assert_equal(fetched.fullname, fullname) assert_equal(fetched.username, username) assert_true('is_spam'", "res = self.app.get(url) assert_equal(res.status_code, 200) class TestConferenceModel(OsfTestCase): def test_endpoint_is_required(self): with", "msg = message.ConferenceMessage() with assert_raises(message.ConferenceError): msg.route def test_attachments_count_zero(self): with self.make_context(data={'attachment-count':", "ConferenceFactory, ProjectFactory, UserFactory def assert_absolute(url): parsed_domain = furl.furl(settings.DOMAIN) parsed_url =", "assert msg.is_spam def test_is_spam_true_dkim(self): ctx = self.make_context( method='POST', data={'X-Mailgun-Dkim-Check-Result': message.DKIM_PASS_VALUES[0][::-1]},", "'X-Mailgun-Sscore': message.SSCORE_MAX_VALUE - 1, 'X-Mailgun-Dkim-Check-Result': message.DKIM_PASS_VALUES[0], 'X-Mailgun-Spf': message.SPF_PASS_VALUES[0], }, )", "'from': '{0} <{1}>'.format(user.fullname, user.username), 'recipient': recipient, 'subject': title, 'stripped-text': body,", "with self.make_context(data={'recipient': recipient}): self.app.app.preprocess_request() msg = message.ConferenceMessage() assert_equal(msg.conference_name, 'conf') assert_equal(msg.conference_category,", "None } return self.app.app.test_request_context(method=method, data=data, **kwargs) class TestProvisionNode(ContextTestCase): def setUp(self):", "fetched.system_tags) def test_get_or_create_user_is_spam(self): fullname = '<NAME>' username = '<EMAIL>' fetched,", "data={ 'attachment-count': 1, 'attachment-1': (sio, 'attachment-1'), }, ) with ctx:", "with ctx: msg = message.ConferenceMessage() assert_equal(len(msg.attachments), 1) assert_equal(msg.attachments[0].read(), content) class", "test_add_poster_by_email(self, mock_upload_attachments): conference = ConferenceFactory() with self.make_context(data={'from': '<EMAIL>', 'subject': 'It\\'s", "'test-' if settings.DEV_MODE else '', conference.endpoint, ) self.app.post( api_url_for('meeting_hook'), {", "utils.provision_node(self.conference, msg, self.node, self.user) assert_false(self.node.is_public) assert_in(self.conference.admins.first(), self.node.contributors) assert_in('emailed', self.node.system_tags) assert_in('spam',", ").hexdigest(), } data.update(kwargs.pop('data', {})) data = { key: value for", "assert_in('emailed', self.node.system_tags) assert_not_in('spam', self.node.system_tags) def test_provision_spam(self): with self.make_context(data={'X-Mailgun-Sscore': message.SSCORE_MAX_VALUE +", "Create a non-conference node ProjectFactory() url = api_url_for('conference_data', meeting=conference.endpoint.upper()) res", "test_conference_bad_data(self): conference = ConferenceFactory() # Create conference nodes n_conference_nodes =", "def tearDownClass(cls): super(ContextTestCase, cls).tearDownClass() settings.MAILGUN_API_KEY = cls._MAILGUN_API_KEY def make_context(self, method='POST',", "self.node = ProjectFactory() self.user = self.node.creator self.conference = ConferenceFactory() self.body", "ConferenceFactory() conference2 = ConferenceFactory() # Create conference nodes create_fake_conference_nodes( 3,", "import views from website.conferences import utils, message from website.util import", "= StringIO(self.content) self.recipient = '{0}{1}-<EMAIL>'.format( 'test-' if settings.DEV_MODE else '',", "def test_attachments_count_zero(self): with self.make_context(data={'attachment-count': '0'}): msg = message.ConferenceMessage() assert_equal(msg.attachments, [])", "use the guid. class TestMessage(ContextTestCase): PUSH_CONTEXT = False def test_verify_signature_valid(self):", "url = '/presentations/' res = self.app.get(url) assert_equal(res.status_code, 302) res =", "meeting='studyswap') res = self.app.get(url) assert_equal(res.status_code, 200) class TestConferenceModel(OsfTestCase): def test_endpoint_is_required(self):", "message.ConferenceMessage() assert not msg.is_spam def test_is_spam_true_sscore(self): ctx = self.make_context( method='POST',", "n, bad_n, endpoint): nodes = [] for i in range(n):", "from tests.base import OsfTestCase, fake from osf_tests.factories import ConferenceFactory, ProjectFactory,", "fetched, created = get_or_create_user(user.fullname, user.username, is_spam=True) assert_false(created) assert_equal(user._id, fetched._id) assert_false('is_spam'", "nodes n_conference_nodes = 3 n_conference_nodes_bad = 1 create_fake_conference_nodes_bad_data( conference, n_conference_nodes,", "assert_equal(res.status_code, 200) assert_equal(len(res.json), n_conference_nodes) def test_conference_data_tag_upper(self): conference = ConferenceFactory() #", "ctx: msg = message.ConferenceMessage() assert not msg.is_spam def test_is_spam_false_all_headers(self): ctx", "= ConferenceFactory() user = UserFactory() title = 'Long Live Greg'", "('attachment-1', 'attachment-1', content), ], ) assert_true(mock_upload.called) users = OSFUser.objects.filter(username=username) assert_equal(users.count(),", "@mock.patch('website.conferences.utils.waterbutler_api_url_for') @mock.patch('website.conferences.utils.requests.put') def test_upload(self, mock_put, mock_get_url): mock_get_url.return_value = 'http://queen.com/' file_name", "'', conference.endpoint, ) self.app.post( api_url_for('meeting_hook'), { 'X-Mailgun-Sscore': 0, 'timestamp': '123',", "assert_equal(user._id, fetched._id) assert_false('is_spam' in fetched.system_tags) def test_get_or_create_user_not_exists(self): fullname = '<NAME>'", "assert_equal(msg.attachments, []) def test_attachments_count_one(self): content = 'slightly mad' sio =", "ConferenceFactory(endpoint='cookie', name='Cookies Conference') conf.save() assert_equal(conf.field_names['submission1'], 'poster') assert_equal(conf.field_names['mail_subject'], 'Presentation title') def", "= '' self.attachment.content_type = 'application/json' utils.upload_attachment(self.user, self.node, self.attachment) mock_get_url.assert_called_with( self.node._id,", "with ctx: msg = message.ConferenceMessage() assert_equal(msg.subject, 'Hip Hopera') def test_recipient(self):", "web_url_for('conference_view', _absolute=True), ) @mock.patch('website.conferences.views.send_mail') @mock.patch('website.conferences.utils.upload_attachments') def test_integration_wo_full_name(self, mock_upload, mock_send_mail): username", "order to access m2m fields, e.g. tags assert_true(created) assert_equal(fetched.fullname, fullname)", "msg.is_spam def test_is_spam_true_spf(self): ctx = self.make_context( method='POST', data={'X-Mailgun-Spf': message.SPF_PASS_VALUES[0][::-1]}, )", "title = 'Long Live Greg' ProjectFactory(creator=user, title=title) body = 'Greg", "tests.base import OsfTestCase, fake from osf_tests.factories import ConferenceFactory, ProjectFactory, UserFactory", "conf = ConferenceFactory(endpoint='Hamburgers', name='Hamburger conference') conf.save() # 3 good nodes", "OsfTestCase, fake from osf_tests.factories import ConferenceFactory, ProjectFactory, UserFactory def assert_absolute(url):", "with assert_raises(IntegrityError): ConferenceFactory(endpoint='spsp2014', name=None).save() def test_default_field_names(self): conf = ConferenceFactory(endpoint='cookie', name='Cookies", "url = web_url_for('conference_results', meeting=conference.endpoint) res = self.app.get(url) assert_equal(res.status_code, 200) def", "= 'Greg is a good plant' content = 'Long may", "StringIO from django.core.exceptions import ValidationError from django.db import IntegrityError import", "node added deleted_node = ProjectFactory(is_public=True) deleted_node.is_deleted = True deleted_node.save() conf.submissions.add(deleted_node)", "{ 'attachment-count': '1', 'attachment-1': (self.attachment, 'attachment-1'), 'X-Mailgun-Sscore': 0, 'recipient': self.recipient,", "n_conference_nodes = 3 n_conference_nodes_bad = 1 create_fake_conference_nodes_bad_data( conference, n_conference_nodes, n_conference_nodes_bad,", "_internal=True, base_url=self.node.osfstorage_region.waterbutler_url, cookie=self.user.get_or_create_cookie(), name=file_name ) mock_put.assert_called_with( mock_get_url.return_value, data=self.content, ) @mock.patch('website.conferences.utils.waterbutler_api_url_for')", "make whole conference break def test_conference_bad_data(self): conference = ConferenceFactory() #", "range(n): node = ProjectFactory(is_public=True) conference.submissions.add(node) node.save() nodes.append(node) return nodes def", ").hexdigest(), 'attachment-count': '1', 'X-Mailgun-Sscore': 0, 'from': '{0} <{1}>'.format(fullname, username), 'recipient':", "conference = ConferenceFactory() # Create conference nodes n_conference_nodes = 3", "= '{0}<EMAIL>'.format('test-' if settings.DEV_MODE else '') with self.make_context(data={'recipient': recipient}): self.app.app.preprocess_request()", "(' Fred', 'Fred'), (u'Me䬟', u'Me䬟'), (u'<EMAIL>', u'<EMAIL>'), (u'Fred <<EMAIL>>', u'Fred'),", "emails: with self.make_context(data={'from': email[0]}): msg = message.ConferenceMessage() assert_equal(msg.sender_email, email[1]) def", "'<EMAIL>' with assert_raises(BlacklistedEmailError) as e: get_or_create_user(fullname, username, is_spam=True) assert_equal(e.exception.message, 'Invalid", "self).setUp() self.node = ProjectFactory() self.user = self.node.creator self.conference = ConferenceFactory()", "with assert_raises(BlacklistedEmailError) as e: get_or_create_user(fullname, username, is_spam=True) assert_equal(e.exception.message, 'Invalid Email')", "msg = message.ConferenceMessage() assert_equal(msg.text, text) def test_sender_name(self): names = [", "web_url_for('conference_results', meeting=conference.endpoint) res = self.app.get(url) assert_equal(res.status_code, 200) def test_confererence_results_endpoint_is_case_insensitive(self): ConferenceFactory(endpoint='StudySwap')", "with assert_raises(message.ConferenceError): msg.verify_signature() def test_is_spam_false_missing_headers(self): ctx = self.make_context( method='POST', data={'X-Mailgun-Sscore':", "res = self.app.get(url) assert_equal(res.status_code, 200) def test_confererence_results_endpoint_is_case_insensitive(self): ConferenceFactory(endpoint='StudySwap') url =", "in range(n): node = ProjectFactory(is_public=True) conference.submissions.add(node) # inject bad data", "def test_add_poster_by_email(self, mock_upload_attachments): conference = ConferenceFactory() with self.make_context(data={'from': '<EMAIL>', 'subject':", "conference1 = ConferenceFactory() conference2 = ConferenceFactory() # Create conference nodes", "parsed_url = furl.furl(url) assert_equal(parsed_domain.host, parsed_url.host) def assert_equal_urls(first, second): parsed_first =", "recipient = '{0}{1}-<EMAIL>'.format( 'test-' if settings.DEV_MODE else '', conference.endpoint, )", "= '{0}{1}-<EMAIL>'.format( 'test-' if settings.DEV_MODE else '', conference.endpoint, ) res", "'<EMAIL>' fetched, created = get_or_create_user(fullname, username, is_spam=False) fetched.save() # in", "# Create a non-conference node ProjectFactory() url = api_url_for('conference_data', meeting=conference.endpoint)", "ctx: msg = message.ConferenceMessage() assert msg.is_spam def test_subject(self): ctx =", "not msg.is_spam def test_is_spam_true_sscore(self): ctx = self.make_context( method='POST', data={'X-Mailgun-Sscore': message.SSCORE_MAX_VALUE", "endpoint): nodes = [] for i in range(n): node =", "text = 'welcome to my nuclear family' ctx = self.make_context(", "def create_fake_conference_nodes(n, conference): nodes = [] for i in range(n):", "reign.' recipient = '{0}{1}-<EMAIL>'.format( 'test-' if settings.DEV_MODE else '', conference.endpoint,", "django.db import IntegrityError import furl from framework.auth import get_or_create_user from", "base_url=self.node.osfstorage_region.waterbutler_url, cookie=self.user.get_or_create_cookie(), name=file_name ) mock_put.assert_called_with( mock_get_url.return_value, data=self.content, ) @mock.patch('website.conferences.utils.waterbutler_api_url_for') @mock.patch('website.conferences.utils.requests.put')", "cookie=self.user.get_or_create_cookie(), name=settings.MISSING_FILE_NAME, ) mock_put.assert_called_with( mock_get_url.return_value, data=self.content, ) @mock.patch('website.conferences.utils.upload_attachments') def test_add_poster_by_email(self,", "mock_get_url.return_value, data=self.content, ) @mock.patch('website.conferences.utils.upload_attachments') def test_add_poster_by_email(self, mock_upload_attachments): conference = ConferenceFactory()", "value in data.items() if value is not None } return", "u'Fred'), ] for name in names: with self.make_context(data={'from': name[0]}): msg", "assert msg.is_spam def test_subject(self): ctx = self.make_context( method='POST', data={'subject': 'RE:", "'attachment-1', content), ], ) assert_true(mock_upload.called) users = OSFUser.objects.filter(username=username) assert_equal(users.count(), 1)", "3, conference1, ) create_fake_conference_nodes( 2, conference2, ) url = api_url_for('conference_submissions')", "email[1]) def test_route_invalid_pattern(self): with self.make_context(data={'recipient': '<EMAIL>'}): self.app.app.preprocess_request() msg = message.ConferenceMessage()", "] for name in names: with self.make_context(data={'from': name[0]}): msg =", "1, 'attachment-1': (sio, 'attachment-1'), }, ) with ctx: msg =", "'', conference.endpoint, ) res = self.app.post( api_url_for('meeting_hook'), { 'X-Mailgun-Sscore': 0,", "assert_equal(res.status_code, 302) res = res.follow() assert_equal(res.request.path, '/meetings/') def test_conference_submissions(self): AbstractNode.objects.all().delete()", "= 'http://queen.com/' file_name = 'hammer-to-fall' self.attachment.filename = file_name self.attachment.content_type =", "return super(TestProvisionNode, self).make_context(data=data, **kwargs) def test_provision(self): with self.make_context(): msg =", "method='POST', data={ 'X-Mailgun-Sscore': message.SSCORE_MAX_VALUE - 1, 'X-Mailgun-Dkim-Check-Result': message.DKIM_PASS_VALUES[0], 'X-Mailgun-Spf': message.SPF_PASS_VALUES[0],", "'{0}<EMAIL>'.format('test-' if settings.DEV_MODE else '') with self.make_context(data={'recipient': recipient}): self.app.app.preprocess_request() msg", "'Invalid Email') class ContextTestCase(OsfTestCase): MAILGUN_API_KEY = 'mailkimp' @classmethod def setUpClass(cls):", "data={'X-Mailgun-Dkim-Check-Result': message.DKIM_PASS_VALUES[0][::-1]}, ) with ctx: msg = message.ConferenceMessage() assert msg.is_spam", "class TestConferenceEmailViews(OsfTestCase): def test_redirect_to_meetings_url(self): url = '/presentations/' res = self.app.get(url)", "my nuclear family' ctx = self.make_context( method='POST', data={'stripped-text': text}, )", "settings.MAILGUN_API_KEY, cls._MAILGUN_API_KEY = cls.MAILGUN_API_KEY, settings.MAILGUN_API_KEY @classmethod def tearDownClass(cls): super(ContextTestCase, cls).tearDownClass()", "res = self.app.get(url) assert_equal(res.status_code, 302) res = res.follow() assert_equal(res.request.path, '/meetings/')", "key=settings.MAILGUN_API_KEY, msg='{}{}'.format('123', 'secret'), digestmod=hashlib.sha256, ).hexdigest(), 'attachment-count': '1', 'X-Mailgun-Sscore': 0, 'from':", "Fred', 'Fred'), (u'Me䬟', u'Me䬟'), (u'<EMAIL>', u'<EMAIL>'), (u'Fred <<EMAIL>>', u'Fred'), (u'\"Fred\"", "'mailkimp' @classmethod def setUpClass(cls): super(ContextTestCase, cls).setUpClass() settings.MAILGUN_API_KEY, cls._MAILGUN_API_KEY = cls.MAILGUN_API_KEY,", "'{0} <{1}>'.format(fullname, username), 'recipient': recipient, 'subject': title, 'stripped-text': body, },", "'attachment-1': (self.attachment, 'attachment-1'), 'X-Mailgun-Sscore': 0, 'recipient': self.recipient, 'stripped-text': self.body, }", "StringIO(content) ctx = self.make_context( method='POST', data={ 'attachment-count': 1, 'attachment-1': (sio,", "utils.upload_attachment(self.user, self.node, self.attachment) mock_get_url.assert_called_with( self.node._id, 'osfstorage', _internal=True, base_url=self.node.osfstorage_region.waterbutler_url, cookie=self.user.get_or_create_cookie(), name=file_name", "text) def test_sender_name(self): names = [ (' Fred', 'Fred'), (u'Me䬟',", "'recipient': self.recipient, 'stripped-text': self.body, } data.update(kwargs.pop('data', {})) return super(TestProvisionNode, self).make_context(data=data,", "assert_not_in('spam', self.node.system_tags) def test_provision_private(self): self.conference.public_projects = False self.conference.save() with self.make_context():", "digestmod=hashlib.sha256, ).hexdigest(), 'attachment-count': '1', 'X-Mailgun-Sscore': 0, 'from': username, 'recipient': recipient,", "furl.furl(first) parsed_first.port = None parsed_second = furl.furl(second) parsed_second.port = None", "= { 'X-Mailgun-Sscore': 0, 'timestamp': '123', 'token': 'secret', 'signature': hmac.new(", "'subject': title, 'stripped-text': body, }, upload_files=[ ('attachment-1', 'attachment-1', content), ],", "= ConferenceFactory() url = web_url_for('conference_results', meeting=conference.endpoint) res = self.app.get(url) assert_equal(res.status_code,", "address) def test_text(self): text = 'welcome to my nuclear family'", "= message.ConferenceMessage() assert_equal(msg.sender_email, email[1]) def test_route_invalid_pattern(self): with self.make_context(data={'recipient': '<EMAIL>'}): self.app.app.preprocess_request()", "'signature': hmac.new( key=settings.MAILGUN_API_KEY, msg='{}{}'.format('123', 'secret'), digestmod=hashlib.sha256, ).hexdigest(), 'attachment-count': '1', 'X-Mailgun-Sscore':", "settings.DEV_MODE else 'stage-') with self.make_context(data={'recipient': recipient}): self.app.app.preprocess_request() msg = message.ConferenceMessage()", ") with ctx: msg = message.ConferenceMessage() assert not msg.is_spam def", "assert_equal(res.status_code, 406) call_args, call_kwargs = mock_send_mail.call_args assert_equal(call_args, (username, views.CONFERENCE_INACTIVE)) assert_equal(call_kwargs['fullname'],", "< bad_n: # Delete only contributor node.contributor_set.filter(user=node.contributors.first()).delete() node.save() nodes.append(node) return", "test_get_or_create_user_not_exists(self): fullname = '<NAME>' username = '<EMAIL>' fetched, created =", "== '<EMAIL>' assert user.fullname == user._id # user's shouldn't be", "email as fullname, so we use the guid. class TestMessage(ContextTestCase):", "recipient, 'subject': title, 'stripped-text': body, }, upload_files=[ ('attachment-1', 'attachment-1', content),", "= '/presentations/' res = self.app.get(url) assert_equal(res.status_code, 302) res = res.follow()", "settings.DEV_MODE else '') with self.make_context(data={'recipient': recipient}): self.app.app.preprocess_request() msg = message.ConferenceMessage()", "username = '<EMAIL>' title = 'good songs' body = 'dragon", "mock_send_mail): fullname = '<NAME>' username = '<EMAIL>' title = 'good", "AbstractNode.objects.filter(title=title) assert_equal(nodes.count(), 1) node = nodes[0] assert_equal(WikiVersion.objects.get_for_node(node, 'home').content, body) assert_true(mock_send_mail.called)", "'secret'), digestmod=hashlib.sha256, ).hexdigest(), 'attachment-count': '1', 'X-Mailgun-Sscore': 0, 'from': '{0} <{1}>'.format(user.fullname,", "conference = ConferenceFactory() url = web_url_for('conference_results', meeting=conference.endpoint) res = self.app.get(url)", "msg, self.node, self.user) assert_false(self.node.is_public) assert_in(self.conference.admins.first(), self.node.contributors) assert_in('emailed', self.node.system_tags) assert_not_in('spam', self.node.system_tags)", "conf.save() assert_equal(conf.field_names['submission1'], 'poster') assert_equal(conf.field_names['mail_subject'], 'Presentation title') def test_conference_valid_submissions(self): conf =", "with ctx: msg = message.ConferenceMessage() assert msg.is_spam def test_subject(self): ctx", "msg.is_spam def test_is_spam_true_sscore(self): ctx = self.make_context( method='POST', data={'X-Mailgun-Sscore': message.SSCORE_MAX_VALUE +", "self.make_context(data={'recipient': recipient}): self.app.app.preprocess_request() msg = message.ConferenceMessage() assert_equal(msg.conference_name, 'chocolate') assert_equal(msg.conference_category, 'data')", "assert_equal(res.status_code, 200) assert_equal(len(res.json), n_conference_nodes) def test_conference_results(self): conference = ConferenceFactory() url", "= self.app.get(url) assert_equal(res.status_code, 200) assert_equal(len(res.json), n_conference_nodes) def test_conference_data_tag_upper(self): conference =", "'application/json' utils.upload_attachment(self.user, self.node, self.attachment) mock_get_url.assert_called_with( self.node._id, 'osfstorage', _internal=True, base_url=self.node.osfstorage_region.waterbutler_url, cookie=self.user.get_or_create_cookie(),", "nodes = AbstractNode.objects.filter(title=title) assert_equal(nodes.count(), 1) node = nodes[0] assert_equal(WikiVersion.objects.get_for_node(node, 'home').content,", "username, is_spam=False) fetched.save() # in order to access m2m fields,", "assert_equal(res.json['success'], True) def test_conference_plain_returns_200(self): conference = ConferenceFactory() url = web_url_for('conference_results__plain',", "conf.submissions.add(deleted_node) # Private node added private_node = ProjectFactory(is_public=False) conf.submissions.add(private_node) assert_equal(conf.submissions.count(),", "text}, ) with ctx: msg = message.ConferenceMessage() assert_equal(msg.text, text) def", "utils.provision_node(self.conference, msg, self.node, self.user) assert_true(self.node.is_public) assert_in(self.conference.admins.first(), self.node.contributors) assert_in('emailed', self.node.system_tags) assert_in(self.conference.endpoint,", "msg = message.ConferenceMessage() views.add_poster_by_email(conference, msg) user = OSFUser.objects.get(username='<EMAIL>') assert user.email", "self.make_context( method='POST', data={'X-Mailgun-Sscore': message.SSCORE_MAX_VALUE + 1}, ) with ctx: msg", "= message.ConferenceMessage() views.add_poster_by_email(conference, msg) user = OSFUser.objects.get(username='<EMAIL>') assert user.email ==", "ConferenceFactory() # Create conference nodes n_conference_nodes = 3 n_conference_nodes_bad =", "msg='{}{}'.format('123', 'secret'), digestmod=hashlib.sha256, ).hexdigest(), 'attachment-count': '1', 'X-Mailgun-Sscore': 0, 'from': username,", "super(TestProvisionNode, self).make_context(data=data, **kwargs) def test_provision(self): with self.make_context(): msg = message.ConferenceMessage()", "ctx = self.make_context( method='POST', data={ 'X-Mailgun-Sscore': message.SSCORE_MAX_VALUE - 1, 'X-Mailgun-Dkim-Check-Result':", "assert_equal(fetched.fullname, fullname) assert_equal(fetched.username, username) assert_false('is_spam' in fetched.system_tags) def test_get_or_create_user_is_spam(self): fullname", "= message.ConferenceMessage() assert msg.is_spam def test_is_spam_true_spf(self): ctx = self.make_context( method='POST',", "= 'dragon on my back' recipient = '{0}{1}-<EMAIL>'.format( 'test-' if", "users = OSFUser.objects.filter(username=username) assert_equal(users.count(), 1) nodes = AbstractNode.objects.filter(title=title) assert_equal(nodes.count(), 1)", "'attachment-count': '1', 'X-Mailgun-Sscore': 0, 'from': '{0} <{1}>'.format(user.fullname, user.username), 'recipient': recipient,", "assert_equal(fetched.fullname, fullname) assert_equal(fetched.username, username) assert_true('is_spam' in fetched.system_tags) def test_get_or_create_user_with_blacklisted_domain(self): fullname", "with ctx: msg = message.ConferenceMessage() assert_equal(msg.text, text) def test_sender_name(self): names", "True deleted_node.save() conf.submissions.add(deleted_node) # Private node added private_node = ProjectFactory(is_public=False)", "[ (u'<EMAIL>', u'<EMAIL>'), (u'<EMAIL>', u'<EMAIL>') ] for email in emails:", "message.ConferenceMessage() assert_equal(msg.attachments, []) def test_attachments_count_one(self): content = 'slightly mad' sio", "'osfstorage', _internal=True, base_url=self.node.osfstorage_region.waterbutler_url, cookie=self.user.get_or_create_cookie(), name=file_name ) mock_put.assert_called_with( mock_get_url.return_value, data=self.content, )", "Live Greg' ProjectFactory(creator=user, title=title) body = 'Greg is a good", "data=self.content, ) @mock.patch('website.conferences.utils.upload_attachments') def test_add_poster_by_email(self, mock_upload_attachments): conference = ConferenceFactory() with", "}, upload_files=[ ('attachment-1', 'attachment-1', content), ], ) assert AbstractNode.objects.filter(title=title, creator=user).count()", "def test_get_or_create_user_is_spam(self): fullname = '<NAME>' username = '<EMAIL>' fetched, created", "} data.update(kwargs.pop('data', {})) return super(TestProvisionNode, self).make_context(data=data, **kwargs) def test_provision(self): with", "for key, value in data.items() if value is not None", "setUp(self): super(TestProvisionNode, self).setUp() self.node = ProjectFactory() self.user = self.node.creator self.conference", "conference.endpoint, ) res = self.app.post( api_url_for('meeting_hook'), { 'X-Mailgun-Sscore': 0, 'timestamp':", "= self.make_context( method='POST', data={'recipient': address}, ) with ctx: msg =", "with self.make_context(data={'from': email[0]}): msg = message.ConferenceMessage() assert_equal(msg.sender_email, email[1]) def test_route_invalid_pattern(self):", "ConferenceFactory() self.body = 'dragon on my back' self.content = 'dragon", "test_attachments_count_one(self): content = 'slightly mad' sio = StringIO(content) ctx =", "def test_sender_name(self): names = [ (' Fred', 'Fred'), (u'Me䬟', u'Me䬟'),", "framework.auth import get_or_create_user from framework.auth.core import Auth from osf.models import", "conference): nodes = [] for i in range(n): node =", "get_or_create_user from framework.auth.core import Auth from osf.models import OSFUser, AbstractNode", "assert_equal_urls(first, second): parsed_first = furl.furl(first) parsed_first.port = None parsed_second =", "'attachment-count': 1, 'attachment-1': (sio, 'attachment-1'), }, ) with ctx: msg", "body) assert_true(mock_send_mail.called) call_args, call_kwargs = mock_send_mail.call_args assert_absolute(call_kwargs['conf_view_url']) assert_absolute(call_kwargs['set_password_url']) assert_absolute(call_kwargs['profile_url']) assert_absolute(call_kwargs['file_url'])", "for i in range(n): node = ProjectFactory(is_public=True) conference.submissions.add(node) # inject", "= self.app.get(url) assert_equal(res.json['success'], True) def test_conference_plain_returns_200(self): conference = ConferenceFactory() url", "self.recipient, 'stripped-text': self.body, } data.update(kwargs.pop('data', {})) return super(TestProvisionNode, self).make_context(data=data, **kwargs)", "def test_create_conference_node_with_same_name_as_existing_node(self, mock_upload, mock_send_mail): conference = ConferenceFactory() user = UserFactory()", "furl.furl(second) parsed_second.port = None assert_equal(parsed_first, parsed_second) def create_fake_conference_nodes(n, conference): nodes", "node ProjectFactory() url = api_url_for('conference_data', meeting=conference.endpoint) res = self.app.get(url) assert_equal(res.status_code,", "content = 'dragon attack' recipient = '{0}{1}-<EMAIL>'.format( 'test-' if settings.DEV_MODE", "settings.DEV_MODE else '', conference.endpoint, ) res = self.app.post( api_url_for('meeting_hook'), {", "# in order to access m2m fields, e.g. tags assert_true(created)", "= None parsed_second = furl.furl(second) parsed_second.port = None assert_equal(parsed_first, parsed_second)", "assert_equal(msg.subject, 'Hip Hopera') def test_recipient(self): address = '<EMAIL>' ctx =", ") @mock.patch('website.conferences.views.send_mail') @mock.patch('website.conferences.utils.upload_attachments') def test_integration_wo_full_name(self, mock_upload, mock_send_mail): username = '<EMAIL>'", "TestConferenceEmailViews(OsfTestCase): def test_redirect_to_meetings_url(self): url = '/presentations/' res = self.app.get(url) assert_equal(res.status_code,", "in order to access m2m fields, e.g. tags assert_true(created) assert_equal(fetched.fullname,", "message.ConferenceMessage() with assert_raises(message.ConferenceError): msg.verify_signature() def test_is_spam_false_missing_headers(self): ctx = self.make_context( method='POST',", "<{1}>'.format(fullname, username), 'recipient': recipient, 'subject': title, 'stripped-text': body, }, expect_errors=True,", "mock_put, mock_get_url): mock_get_url.return_value = 'http://queen.com/' self.attachment.filename = '' self.attachment.content_type =", "n_conference_nodes - n_conference_nodes_bad) def test_conference_data_url_upper(self): conference = ConferenceFactory() # Create", "self.node in self.conference.submissions.all() assert_not_in('spam', self.node.system_tags) def test_provision_private(self): self.conference.public_projects = False", "assert_equal(res.status_code, 200) def test_conference_data(self): conference = ConferenceFactory() # Create conference", "assert_equal(msg.conference_category, 'data') conf.__class__.delete(conf) def test_route_valid_b(self): recipient = '{0}<EMAIL>'.format('test-' if settings.DEV_MODE", ").hexdigest(), 'attachment-count': '1', 'X-Mailgun-Sscore': 0, 'from': username, 'recipient': recipient, 'subject':", "= get_or_create_user(fullname, username, is_spam=False) fetched.save() # in order to access", "assert_absolute(url): parsed_domain = furl.furl(settings.DOMAIN) parsed_url = furl.furl(url) assert_equal(parsed_domain.host, parsed_url.host) def", "'token': 'secret', 'signature': hmac.new( key=settings.MAILGUN_API_KEY, msg='{}{}'.format('123', 'secret'), digestmod=hashlib.sha256, ).hexdigest(), 'attachment-count':", "assert_absolute(call_kwargs['file_url']) assert_absolute(call_kwargs['node_url']) @mock.patch('website.conferences.views.send_mail') def test_integration_inactive(self, mock_send_mail): conference = ConferenceFactory(active=False) fullname", "data={'stripped-text': text}, ) with ctx: msg = message.ConferenceMessage() assert_equal(msg.text, text)", "message.ConferenceMessage() assert_equal(msg.subject, 'Hip Hopera') def test_recipient(self): address = '<EMAIL>' ctx", "'') with self.make_context(data={'recipient': recipient}): self.app.app.preprocess_request() msg = message.ConferenceMessage() assert_equal(msg.conference_name, 'conf')", "if settings.DEV_MODE else '', self.conference.endpoint, ) def make_context(self, **kwargs): data", "= ConferenceFactory(endpoint='cookie', name='Cookies Conference') conf.save() assert_equal(conf.field_names['submission1'], 'poster') assert_equal(conf.field_names['mail_subject'], 'Presentation title')", "], ) assert_true(mock_upload.called) users = OSFUser.objects.filter(username=username) assert_equal(users.count(), 1) nodes =", "fullname) assert_equal_urls( call_kwargs['presentations_url'], web_url_for('conference_view', _absolute=True), ) @mock.patch('website.conferences.views.send_mail') @mock.patch('website.conferences.utils.upload_attachments') def test_integration_wo_full_name(self,", "self.node.system_tags) @mock.patch('website.conferences.utils.waterbutler_api_url_for') @mock.patch('website.conferences.utils.requests.put') def test_upload(self, mock_put, mock_get_url): mock_get_url.return_value = 'http://queen.com/'", "nodes class TestConferenceUtils(OsfTestCase): def test_get_or_create_user_exists(self): user = UserFactory() fetched, created", "= api_url_for('conference_data', meeting=conference.endpoint) res = self.app.get(url) assert_equal(res.status_code, 200) assert_equal(len(res.json), n_conference_nodes", "api_url_for('conference_data', meeting=conference.endpoint) res = self.app.get(url) assert_equal(res.status_code, 200) assert_equal(len(res.json), n_conference_nodes -", "= web_url_for('conference_results', meeting='studyswap') res = self.app.get(url) assert_equal(res.status_code, 200) class TestConferenceModel(OsfTestCase):", "= 'good songs' body = 'dragon on my back' recipient", "{ key: value for key, value in data.items() if value", "@mock.patch('website.conferences.utils.requests.put') def test_upload(self, mock_put, mock_get_url): mock_get_url.return_value = 'http://queen.com/' file_name =", "get_or_create_user(fullname, username, is_spam=False) fetched.save() # in order to access m2m", "# Delete only contributor node.contributor_set.filter(user=node.contributors.first()).delete() node.save() nodes.append(node) return nodes class", "msg = message.ConferenceMessage() assert msg.is_spam def test_is_spam_true_dkim(self): ctx = self.make_context(", "'good songs' conference = ConferenceFactory() body = 'dragon on my", "message.ConferenceMessage() assert msg.is_spam def test_is_spam_true_spf(self): ctx = self.make_context( method='POST', data={'X-Mailgun-Spf':", "'{0}{1}-<EMAIL>'.format( 'test-' if settings.DEV_MODE else '', conference.endpoint, ) self.app.post( api_url_for('meeting_hook'),", "ctx = self.make_context( method='POST', data={'subject': 'RE: Hip Hopera'}, ) with", "self.app.get(url) assert_equal(res.status_code, 200) class TestConferenceModel(OsfTestCase): def test_endpoint_is_required(self): with assert_raises(IntegrityError): ConferenceFactory(endpoint=None,", "def test_alternate_route_invalid(self): recipient = '{0}<EMAIL>'.format('test-' if settings.DEV_MODE else '') with", "message.ConferenceMessage() with assert_raises(message.ConferenceError): msg.route def test_route_invalid_test(self): recipient = '{0}<EMAIL>'.format('' if", "assert_equal(len(res.json), n_conference_nodes) # Regression for OSF-8864 to confirm bad project", "assert_equal(msg.conference_name, 'conf') assert_equal(msg.conference_category, 'poster') def test_alternate_route_invalid(self): recipient = '{0}<EMAIL>'.format('test-' if", "api_url_for('conference_submissions') res = self.app.get(url) assert_equal(res.json['success'], True) def test_conference_plain_returns_200(self): conference =", "active=True) conf.name = 'Chocolate Conference' conf.field_names['submission2'] = 'data' conf.save() recipient", "assert_not_in('spam', self.node.system_tags) def test_provision_spam(self): with self.make_context(data={'X-Mailgun-Sscore': message.SSCORE_MAX_VALUE + 1}): msg", "'subject': 'It\\'s PARTY TIME!'}): msg = message.ConferenceMessage() views.add_poster_by_email(conference, msg) user", "from website.util import api_url_for, web_url_for from tests.base import OsfTestCase, fake", "def test_name_is_required(self): with assert_raises(IntegrityError): ConferenceFactory(endpoint='spsp2014', name=None).save() def test_default_field_names(self): conf =", "assert_equal(msg.attachments[0].read(), content) class TestConferenceEmailViews(OsfTestCase): def test_redirect_to_meetings_url(self): url = '/presentations/' res", "self.app.get(url) assert_equal(res.status_code, 200) assert_equal(len(res.json), n_conference_nodes) def test_conference_results(self): conference = ConferenceFactory()", "[] for i in range(n): node = ProjectFactory(is_public=True) conference.submissions.add(node) #", "import StringIO from django.core.exceptions import ValidationError from django.db import IntegrityError", "def test_is_spam_false_missing_headers(self): ctx = self.make_context( method='POST', data={'X-Mailgun-Sscore': message.SSCORE_MAX_VALUE - 1},", "fetched.save() # in order to access m2m fields, e.g. tags", "file_name self.attachment.content_type = 'application/json' utils.upload_attachment(self.user, self.node, self.attachment) mock_get_url.assert_called_with( self.node._id, 'osfstorage',", "assert_equal(msg.text, text) def test_sender_name(self): names = [ (' Fred', 'Fred'),", "'attachment-count': '1', 'X-Mailgun-Sscore': 0, 'from': username, 'recipient': recipient, 'subject': title,", "node = ProjectFactory(is_public=True) conference.submissions.add(node) # inject bad data if i", "conf.name = 'Chocolate Conference' conf.field_names['submission2'] = 'data' conf.save() recipient =", "from nose.tools import * # noqa (PEP8 asserts) import hmac", "'recipient': recipient, 'subject': title, 'stripped-text': body, }, upload_files=[ ('attachment-1', 'attachment-1',", "message.ConferenceMessage() assert msg.is_spam def test_subject(self): ctx = self.make_context( method='POST', data={'subject':", "import ValidationError from django.db import IntegrityError import furl from framework.auth", "method='POST', data={'X-Mailgun-Spf': message.SPF_PASS_VALUES[0][::-1]}, ) with ctx: msg = message.ConferenceMessage() assert", "'1', 'X-Mailgun-Sscore': 0, 'from': username, 'recipient': recipient, 'subject': title, 'stripped-text':", "res = self.app.get(url) assert_equal(res.status_code, 200) assert_equal(len(res.json), n_conference_nodes) def test_conference_results(self): conference", "ctx: msg = message.ConferenceMessage() assert_equal(msg.text, text) def test_sender_name(self): names =", "from StringIO import StringIO from django.core.exceptions import ValidationError from django.db", "able to use email as fullname, so we use the", "name=file_name ) mock_put.assert_called_with( mock_get_url.return_value, data=self.content, ) @mock.patch('website.conferences.utils.waterbutler_api_url_for') @mock.patch('website.conferences.utils.requests.put') def test_upload_no_file_name(self,", "assert_absolute(call_kwargs['set_password_url']) assert_absolute(call_kwargs['profile_url']) assert_absolute(call_kwargs['file_url']) assert_absolute(call_kwargs['node_url']) @mock.patch('website.conferences.views.send_mail') @mock.patch('website.conferences.utils.upload_attachments') def test_create_conference_node_with_same_name_as_existing_node(self, mock_upload, mock_send_mail):", "* # noqa (PEP8 asserts) import hmac import hashlib from", "<<EMAIL>>', u'Fred'), (u'\"Fred\" <<EMAIL>>', u'Fred'), ] for name in names:", "assert_in('emailed', self.node.system_tags) assert_in(self.conference.endpoint, self.node.system_tags) assert self.node in self.conference.submissions.all() assert_not_in('spam', self.node.system_tags)", "= message.ConferenceMessage() assert msg.is_spam def test_is_spam_true_dkim(self): ctx = self.make_context( method='POST',", "msg = message.ConferenceMessage() assert_equal(msg.conference_name, 'conf') assert_equal(msg.conference_category, 'poster') def test_alternate_route_invalid(self): recipient", "e: get_or_create_user(fullname, username, is_spam=True) assert_equal(e.exception.message, 'Invalid Email') class ContextTestCase(OsfTestCase): MAILGUN_API_KEY", "= message.ConferenceMessage() with assert_raises(message.ConferenceError): msg.route def test_route_valid_alternate(self): conf = ConferenceFactory(endpoint='chocolate',", "value is not None } return self.app.app.test_request_context(method=method, data=data, **kwargs) class", "address}, ) with ctx: msg = message.ConferenceMessage() assert_equal(msg.recipient, address) def", "ConferenceFactory(endpoint=None, name=fake.company()).save() def test_name_is_required(self): with assert_raises(IntegrityError): ConferenceFactory(endpoint='spsp2014', name=None).save() def test_default_field_names(self):", "website import settings from website.conferences import views from website.conferences import", "= self.make_context( method='POST', data={'X-Mailgun-Sscore': message.SSCORE_MAX_VALUE + 1}, ) with ctx:", "return nodes def create_fake_conference_nodes_bad_data(conference, n, bad_n, endpoint): nodes = []", "osf.exceptions import BlacklistedEmailError from website import settings from website.conferences import", "i in range(n): node = ProjectFactory(is_public=True) conference.submissions.add(node) # inject bad", "'osfstorage', _internal=True, base_url=self.node.osfstorage_region.waterbutler_url, cookie=self.user.get_or_create_cookie(), name=settings.MISSING_FILE_NAME, ) mock_put.assert_called_with( mock_get_url.return_value, data=self.content, )", "body, }, expect_errors=True, ) assert_equal(res.status_code, 406) call_args, call_kwargs = mock_send_mail.call_args", "message.ConferenceMessage() utils.provision_node(self.conference, msg, self.node, self.user) assert_true(self.node.is_public) assert_in(self.conference.admins.first(), self.node.contributors) assert_in('emailed', self.node.system_tags)", "fullname) assert_equal(fetched.username, username) assert_false('is_spam' in fetched.system_tags) def test_get_or_create_user_is_spam(self): fullname =", "False self.conference.save() with self.make_context(): msg = message.ConferenceMessage() utils.provision_node(self.conference, msg, self.node,", "Hopera'}, ) with ctx: msg = message.ConferenceMessage() assert_equal(msg.subject, 'Hip Hopera')", "mock_put.assert_called_with( mock_get_url.return_value, data=self.content, ) @mock.patch('website.conferences.utils.waterbutler_api_url_for') @mock.patch('website.conferences.utils.requests.put') def test_upload_no_file_name(self, mock_put, mock_get_url):", "def assert_equal_urls(first, second): parsed_first = furl.furl(first) parsed_first.port = None parsed_second", "ConferenceFactory(endpoint='spsp2014', name=None).save() def test_default_field_names(self): conf = ConferenceFactory(endpoint='cookie', name='Cookies Conference') conf.save()", "in self.conference.submissions.all() assert_not_in('spam', self.node.system_tags) def test_provision_private(self): self.conference.public_projects = False self.conference.save()", "= self.node.creator self.conference = ConferenceFactory() self.body = 'dragon on my", "website.conferences import utils, message from website.util import api_url_for, web_url_for from", "res = self.app.get(url) assert_equal(res.status_code, 200) def test_conference_data(self): conference = ConferenceFactory()", "self.make_context(): msg = message.ConferenceMessage() utils.provision_node(self.conference, msg, self.node, self.user) assert_false(self.node.is_public) assert_in(self.conference.admins.first(),", "'data' conf.save() recipient = '{0}<EMAIL>'.format('test-' if settings.DEV_MODE else '') with", "confirm bad project data does not make whole conference break", "ctx: msg = message.ConferenceMessage() assert_equal(msg.subject, 'Hip Hopera') def test_recipient(self): address", "'attachment-count': '1', 'attachment-1': (self.attachment, 'attachment-1'), 'X-Mailgun-Sscore': 0, 'recipient': self.recipient, 'stripped-text':", "OSFUser.objects.get(username='<EMAIL>') assert user.email == '<EMAIL>' assert user.fullname == user._id #", "assert_true(mock_upload.called) users = OSFUser.objects.filter(username=username) assert_equal(users.count(), 1) nodes = AbstractNode.objects.filter(title=title) assert_equal(nodes.count(),", "cls._MAILGUN_API_KEY def make_context(self, method='POST', **kwargs): data = { 'X-Mailgun-Sscore': 0,", "expect_errors=True, ) assert_equal(res.status_code, 406) call_args, call_kwargs = mock_send_mail.call_args assert_equal(call_args, (username,", "assert_absolute(call_kwargs['profile_url']) assert_absolute(call_kwargs['file_url']) assert_absolute(call_kwargs['node_url']) @mock.patch('website.conferences.views.send_mail') def test_integration_inactive(self, mock_send_mail): conference = ConferenceFactory(active=False)", "'Long Live Greg' ProjectFactory(creator=user, title=title) body = 'Greg is a", "= ProjectFactory(is_public=True) conference.submissions.add(node) node.save() nodes.append(node) return nodes def create_fake_conference_nodes_bad_data(conference, n,", "views.CONFERENCE_INACTIVE)) assert_equal(call_kwargs['fullname'], fullname) assert_equal_urls( call_kwargs['presentations_url'], web_url_for('conference_view', _absolute=True), ) @mock.patch('website.conferences.views.send_mail') @mock.patch('website.conferences.utils.upload_attachments')", "ProjectFactory(creator=user, title=title) body = 'Greg is a good plant' content", "'from': username, 'recipient': recipient, 'subject': title, 'stripped-text': body, }, upload_files=[", "self.make_context(data={'X-Mailgun-Sscore': message.SSCORE_MAX_VALUE + 1}): msg = message.ConferenceMessage() utils.provision_node(self.conference, msg, self.node,", "'stripped-text': body, }, expect_errors=True, ) assert_equal(res.status_code, 406) call_args, call_kwargs =", "create_fake_conference_nodes( n_conference_nodes, conference, ) # Create a non-conference node ProjectFactory()", "username, is_spam=True) assert_equal(e.exception.message, 'Invalid Email') class ContextTestCase(OsfTestCase): MAILGUN_API_KEY = 'mailkimp'", "= self.app.get(url) assert_equal(res.status_code, 200) assert_equal(len(res.json), n_conference_nodes - n_conference_nodes_bad) def test_conference_data_url_upper(self):", "data = { 'X-Mailgun-Sscore': 0, 'timestamp': '123', 'token': 'secret', 'signature':", "= ProjectFactory(is_public=True) conference.submissions.add(node) # inject bad data if i <", "mock_upload, mock_send_mail): username = '<EMAIL>' title = 'no full name", "self.make_context(data={'attachment-count': '0'}): msg = message.ConferenceMessage() assert_equal(msg.attachments, []) def test_attachments_count_one(self): content", "message.DKIM_PASS_VALUES[0], 'X-Mailgun-Spf': message.SPF_PASS_VALUES[0], }, ) with ctx: msg = message.ConferenceMessage()", "u'Fred'), (u'\"Fred\" <<EMAIL>>', u'Fred'), ] for name in names: with", "= message.ConferenceMessage() assert_equal(msg.subject, 'Hip Hopera') def test_recipient(self): address = '<EMAIL>'", "= self.app.get(url) assert_equal(res.status_code, 200) class TestConferenceModel(OsfTestCase): def test_endpoint_is_required(self): with assert_raises(IntegrityError):", "self.make_context( method='POST', data={'X-Mailgun-Sscore': message.SSCORE_MAX_VALUE - 1}, ) with ctx: msg", "assert_equal(res.request.path, '/meetings/') def test_conference_submissions(self): AbstractNode.objects.all().delete() conference1 = ConferenceFactory() conference2 =", "conference nodes n_conference_nodes = 3 n_conference_nodes_bad = 1 create_fake_conference_nodes_bad_data( conference,", "def test_provision(self): with self.make_context(): msg = message.ConferenceMessage() utils.provision_node(self.conference, msg, self.node,", "assert user.email == '<EMAIL>' assert user.fullname == user._id # user's", "assert_equal(len(res.json), n_conference_nodes) def test_conference_data_tag_upper(self): conference = ConferenceFactory() # Create conference", "= [] for i in range(n): node = ProjectFactory(is_public=True) conference.submissions.add(node)", "mock_get_url): mock_get_url.return_value = 'http://queen.com/' self.attachment.filename = '' self.attachment.content_type = 'application/json'", "test_sender_email(self): emails = [ (u'<EMAIL>', u'<EMAIL>'), (u'<EMAIL>', u'<EMAIL>') ] for", "assert_absolute(call_kwargs['file_url']) assert_absolute(call_kwargs['node_url']) @mock.patch('website.conferences.views.send_mail') @mock.patch('website.conferences.utils.upload_attachments') def test_create_conference_node_with_same_name_as_existing_node(self, mock_upload, mock_send_mail): conference =", "= message.ConferenceMessage() assert not msg.is_spam def test_is_spam_false_all_headers(self): ctx = self.make_context(", "Conference' conf.field_names['submission2'] = 'data' conf.save() recipient = '{0}<EMAIL>'.format('test-' if settings.DEV_MODE", "data={ 'X-Mailgun-Sscore': message.SSCORE_MAX_VALUE - 1, 'X-Mailgun-Dkim-Check-Result': message.DKIM_PASS_VALUES[0], 'X-Mailgun-Spf': message.SPF_PASS_VALUES[0], },", "'RE: Hip Hopera'}, ) with ctx: msg = message.ConferenceMessage() assert_equal(msg.subject,", "ctx: msg = message.ConferenceMessage() assert not msg.is_spam def test_is_spam_true_sscore(self): ctx", "if settings.DEV_MODE else '', conference.endpoint, ) self.app.post( api_url_for('meeting_hook'), { 'X-Mailgun-Sscore':", "title=title) body = 'Greg is a good plant' content =", "@classmethod def setUpClass(cls): super(ContextTestCase, cls).setUpClass() settings.MAILGUN_API_KEY, cls._MAILGUN_API_KEY = cls.MAILGUN_API_KEY, settings.MAILGUN_API_KEY", "not make whole conference break def test_conference_bad_data(self): conference = ConferenceFactory()", "= '<EMAIL>' title = 'no full name only email' conference", "[]) def test_attachments_count_one(self): content = 'slightly mad' sio = StringIO(content)", "conference2, ) url = api_url_for('conference_submissions') res = self.app.get(url) assert_equal(res.json['success'], True)", "= web_url_for('conference_results', meeting=conference.endpoint) res = self.app.get(url) assert_equal(res.status_code, 200) def test_confererence_results_endpoint_is_case_insensitive(self):", "access m2m fields, e.g. tags assert_true(created) assert_equal(fetched.fullname, fullname) assert_equal(fetched.username, username)", "(PEP8 asserts) import hmac import hashlib from StringIO import StringIO", "assert_false(created) assert_equal(user._id, fetched._id) assert_false('is_spam' in fetched.system_tags) def test_get_or_create_user_not_exists(self): fullname =", "= 'application/json' utils.upload_attachment(self.user, self.node, self.attachment) mock_get_url.assert_called_with( self.node._id, 'osfstorage', _internal=True, base_url=self.node.osfstorage_region.waterbutler_url,", "assert_equal(len(res.json), n_conference_nodes - n_conference_nodes_bad) def test_conference_data_url_upper(self): conference = ConferenceFactory() #", "attack' recipient = '{0}{1}-<EMAIL>'.format( 'test-' if settings.DEV_MODE else '', conference.endpoint,", "= furl.furl(first) parsed_first.port = None parsed_second = furl.furl(second) parsed_second.port =", "songs' body = 'dragon on my back' recipient = '{0}{1}-<EMAIL>'.format(", "node.save() nodes.append(node) return nodes def create_fake_conference_nodes_bad_data(conference, n, bad_n, endpoint): nodes", "message.ConferenceMessage() with assert_raises(message.ConferenceError): msg.route def test_route_valid_alternate(self): conf = ConferenceFactory(endpoint='chocolate', active=True)", "= 'Chocolate Conference' conf.field_names['submission2'] = 'data' conf.save() recipient = '{0}<EMAIL>'.format('test-'", "msg = message.ConferenceMessage() assert_equal(msg.attachments, []) def test_attachments_count_one(self): content = 'slightly", "= message.ConferenceMessage() with assert_raises(message.ConferenceError): msg.route def test_route_invalid_test(self): recipient = '{0}<EMAIL>'.format(''", "= '<NAME>' username = '<EMAIL>' fetched, created = get_or_create_user(fullname, username,", "import mock from nose.tools import * # noqa (PEP8 asserts)", "settings from website.conferences import views from website.conferences import utils, message", "msg = message.ConferenceMessage() msg.verify_signature() def test_verify_signature_invalid(self): with self.make_context(data={'signature': 'fake'}): self.app.app.preprocess_request()", "[ (' Fred', 'Fred'), (u'Me䬟', u'Me䬟'), (u'<EMAIL>', u'<EMAIL>'), (u'Fred <<EMAIL>>',", "tags assert_true(created) assert_equal(fetched.fullname, fullname) assert_equal(fetched.username, username) assert_false('is_spam' in fetched.system_tags) def", "assert_equal(res.status_code, 200) class TestConferenceModel(OsfTestCase): def test_endpoint_is_required(self): with assert_raises(IntegrityError): ConferenceFactory(endpoint=None, name=fake.company()).save()", "test_provision(self): with self.make_context(): msg = message.ConferenceMessage() utils.provision_node(self.conference, msg, self.node, self.user)", "= web_url_for('conference_results__plain', meeting=conference.endpoint) res = self.app.get(url) assert_equal(res.status_code, 200) def test_conference_data(self):", "test_sender_name(self): names = [ (' Fred', 'Fred'), (u'Me䬟', u'Me䬟'), (u'<EMAIL>',", "name='Cookies Conference') conf.save() assert_equal(conf.field_names['submission1'], 'poster') assert_equal(conf.field_names['mail_subject'], 'Presentation title') def test_conference_valid_submissions(self):", "nodes added create_fake_conference_nodes(3, conf) # Deleted node added deleted_node =", "key=settings.MAILGUN_API_KEY, msg='{}{}'.format('123', 'secret'), digestmod=hashlib.sha256, ).hexdigest(), } data.update(kwargs.pop('data', {})) data =", "self.node, self.user) assert_true(self.node.is_public) assert_in(self.conference.admins.first(), self.node.contributors) assert_in('emailed', self.node.system_tags) assert_in(self.conference.endpoint, self.node.system_tags) assert", "fullname, so we use the guid. class TestMessage(ContextTestCase): PUSH_CONTEXT =", "'Greg is a good plant' content = 'Long may they", "msg.verify_signature() def test_is_spam_false_missing_headers(self): ctx = self.make_context( method='POST', data={'X-Mailgun-Sscore': message.SSCORE_MAX_VALUE -", "framework.auth.core import Auth from osf.models import OSFUser, AbstractNode from addons.wiki.models", "= False self.conference.save() with self.make_context(): msg = message.ConferenceMessage() utils.provision_node(self.conference, msg,", "self.node.system_tags) assert_not_in('spam', self.node.system_tags) def test_provision_spam(self): with self.make_context(data={'X-Mailgun-Sscore': message.SSCORE_MAX_VALUE + 1}):", "user.email == '<EMAIL>' assert user.fullname == user._id # user's shouldn't", "'subject': title, 'stripped-text': body, }, expect_errors=True, ) assert_equal(res.status_code, 406) call_args,", "= self.app.get(url) assert_equal(res.status_code, 200) def test_conference_data(self): conference = ConferenceFactory() #", "on my back' content = 'dragon attack' recipient = '{0}{1}-<EMAIL>'.format(", "Hopera') def test_recipient(self): address = '<EMAIL>' ctx = self.make_context( method='POST',", "assert_equal(conf.valid_submissions.count(), 3) class TestConferenceIntegration(ContextTestCase): @mock.patch('website.conferences.views.send_mail') @mock.patch('website.conferences.utils.upload_attachments') def test_integration(self, mock_upload, mock_send_mail):", "assert_true(mock_send_mail.called) call_args, call_kwargs = mock_send_mail.call_args assert_absolute(call_kwargs['conf_view_url']) assert_absolute(call_kwargs['set_password_url']) assert_absolute(call_kwargs['profile_url']) assert_absolute(call_kwargs['file_url']) assert_absolute(call_kwargs['node_url'])", "hashlib from StringIO import StringIO from django.core.exceptions import ValidationError from", "from osf.exceptions import BlacklistedEmailError from website import settings from website.conferences", "self.node.contributors) assert_in('emailed', self.node.system_tags) assert_in(self.conference.endpoint, self.node.system_tags) assert self.node in self.conference.submissions.all() assert_not_in('spam',", "fullname = '<NAME>' username = '<EMAIL>' fetched, created = get_or_create_user(fullname,", "0, 'from': username, 'recipient': recipient, 'subject': title, 'stripped-text': body, },", "assert_raises(message.ConferenceError): msg.route def test_route_valid_alternate(self): conf = ConferenceFactory(endpoint='chocolate', active=True) conf.name =", "test_conference_results(self): conference = ConferenceFactory() url = web_url_for('conference_results', meeting=conference.endpoint) res =", "api_url_for('conference_data', meeting=conference.endpoint) res = self.app.get(url) assert_equal(res.status_code, 200) assert_equal(len(res.json), n_conference_nodes) def", "def test_integration_wo_full_name(self, mock_upload, mock_send_mail): username = '<EMAIL>' title = 'no", "self.make_context( method='POST', data={ 'attachment-count': 1, 'attachment-1': (sio, 'attachment-1'), }, )", "conference') conf.save() # 3 good nodes added create_fake_conference_nodes(3, conf) #", "furl from framework.auth import get_or_create_user from framework.auth.core import Auth from", "= ProjectFactory(is_public=False) conf.submissions.add(private_node) assert_equal(conf.submissions.count(), 5) assert_equal(conf.valid_submissions.count(), 3) class TestConferenceIntegration(ContextTestCase): @mock.patch('website.conferences.views.send_mail')", "res = self.app.get(url) assert_equal(res.json['success'], True) def test_conference_plain_returns_200(self): conference = ConferenceFactory()", "'{0} <{1}>'.format(user.fullname, user.username), 'recipient': recipient, 'subject': title, 'stripped-text': body, },", "test_verify_signature_invalid(self): with self.make_context(data={'signature': 'fake'}): self.app.app.preprocess_request() msg = message.ConferenceMessage() with assert_raises(message.ConferenceError):", "def test_confererence_results_endpoint_is_case_insensitive(self): ConferenceFactory(endpoint='StudySwap') url = web_url_for('conference_results', meeting='studyswap') res = self.app.get(url)", "def test_is_spam_false_all_headers(self): ctx = self.make_context( method='POST', data={ 'X-Mailgun-Sscore': message.SSCORE_MAX_VALUE -", "def test_is_spam_true_spf(self): ctx = self.make_context( method='POST', data={'X-Mailgun-Spf': message.SPF_PASS_VALUES[0][::-1]}, ) with", "ConferenceFactory() with self.make_context(data={'from': '<EMAIL>', 'subject': 'It\\'s PARTY TIME!'}): msg =", ") with ctx: msg = message.ConferenceMessage() assert_equal(len(msg.attachments), 1) assert_equal(msg.attachments[0].read(), content)", "'X-Mailgun-Sscore': 0, 'timestamp': '123', 'token': 'secret', 'signature': hmac.new( key=settings.MAILGUN_API_KEY, msg='{}{}'.format('123',", "Create a non-conference node ProjectFactory() url = api_url_for('conference_data', meeting=conference.endpoint) res", "None parsed_second = furl.furl(second) parsed_second.port = None assert_equal(parsed_first, parsed_second) def", ").hexdigest(), 'attachment-count': '1', 'X-Mailgun-Sscore': 0, 'from': '{0} <{1}>'.format(user.fullname, user.username), 'recipient':", "mock_send_mail): conference = ConferenceFactory(active=False) fullname = '<NAME>' username = '<EMAIL>'", "msg = message.ConferenceMessage() assert msg.is_spam def test_is_spam_true_spf(self): ctx = self.make_context(", "from framework.auth import get_or_create_user from framework.auth.core import Auth from osf.models", "assert_in(self.conference.admins.first(), self.node.contributors) assert_in('emailed', self.node.system_tags) assert_in(self.conference.endpoint, self.node.system_tags) assert self.node in self.conference.submissions.all()", "mock_get_url.return_value, data=self.content, ) @mock.patch('website.conferences.utils.waterbutler_api_url_for') @mock.patch('website.conferences.utils.requests.put') def test_upload_no_file_name(self, mock_put, mock_get_url): mock_get_url.return_value", "with ctx: msg = message.ConferenceMessage() assert msg.is_spam def test_is_spam_true_dkim(self): ctx", "Hip Hopera'}, ) with ctx: msg = message.ConferenceMessage() assert_equal(msg.subject, 'Hip", "import OSFUser, AbstractNode from addons.wiki.models import WikiVersion from osf.exceptions import", "assert_equal(parsed_first, parsed_second) def create_fake_conference_nodes(n, conference): nodes = [] for i", "self.make_context(data={'signature': 'fake'}): self.app.app.preprocess_request() msg = message.ConferenceMessage() with assert_raises(message.ConferenceError): msg.verify_signature() def", "= message.ConferenceMessage() assert_equal(msg.sender_name, name[1]) def test_sender_email(self): emails = [ (u'<EMAIL>',", "TestConferenceUtils(OsfTestCase): def test_get_or_create_user_exists(self): user = UserFactory() fetched, created = get_or_create_user(user.fullname,", "<<EMAIL>>', u'Fred'), ] for name in names: with self.make_context(data={'from': name[0]}):", "test_get_or_create_user_exists(self): user = UserFactory() fetched, created = get_or_create_user(user.fullname, user.username, is_spam=True)", "family' ctx = self.make_context( method='POST', data={'stripped-text': text}, ) with ctx:", "meeting=conference.endpoint.upper()) res = self.app.get(url) assert_equal(res.status_code, 200) assert_equal(len(res.json), n_conference_nodes) def test_conference_data_tag_upper(self):", "method='POST', data={'subject': 'RE: Hip Hopera'}, ) with ctx: msg =", "self.node, self.attachment) mock_get_url.assert_called_with( self.node._id, 'osfstorage', _internal=True, base_url=self.node.osfstorage_region.waterbutler_url, cookie=self.user.get_or_create_cookie(), name=file_name )", "msg = message.ConferenceMessage() with assert_raises(message.ConferenceError): msg.route def test_route_invalid_test(self): recipient =", "meeting=conference.endpoint) res = self.app.get(url) assert_equal(res.status_code, 200) assert_equal(len(res.json), n_conference_nodes) def test_conference_results(self):", "'recipient': recipient, 'subject': title, 'stripped-text': body, }, expect_errors=True, ) assert_equal(res.status_code,", "ProjectFactory(is_public=True) conference.submissions.add(node) # inject bad data if i < bad_n:", "self.body, } data.update(kwargs.pop('data', {})) return super(TestProvisionNode, self).make_context(data=data, **kwargs) def test_provision(self):", "non-conference node ProjectFactory() url = api_url_for('conference_data', meeting=conference.endpoint) res = self.app.get(url)", "self.app.get(url) assert_equal(res.json['success'], True) def test_conference_plain_returns_200(self): conference = ConferenceFactory() url =", "ctx = self.make_context( method='POST', data={'X-Mailgun-Sscore': message.SSCORE_MAX_VALUE + 1}, ) with", "deleted_node.is_deleted = True deleted_node.save() conf.submissions.add(deleted_node) # Private node added private_node", "= UserFactory() title = 'Long Live Greg' ProjectFactory(creator=user, title=title) body", "emails = [ (u'<EMAIL>', u'<EMAIL>'), (u'<EMAIL>', u'<EMAIL>') ] for email", "# -*- coding: utf-8 -*- import mock from nose.tools import", "'' self.attachment.content_type = 'application/json' utils.upload_attachment(self.user, self.node, self.attachment) mock_get_url.assert_called_with( self.node._id, 'osfstorage',", "else '', conference.endpoint, ) self.app.post( api_url_for('meeting_hook'), { 'X-Mailgun-Sscore': 0, 'timestamp':", "setUpClass(cls): super(ContextTestCase, cls).setUpClass() settings.MAILGUN_API_KEY, cls._MAILGUN_API_KEY = cls.MAILGUN_API_KEY, settings.MAILGUN_API_KEY @classmethod def", "}, ) with ctx: msg = message.ConferenceMessage() assert_equal(len(msg.attachments), 1) assert_equal(msg.attachments[0].read(),", "for name in names: with self.make_context(data={'from': name[0]}): msg = message.ConferenceMessage()", "2, conference2, ) url = api_url_for('conference_submissions') res = self.app.get(url) assert_equal(res.json['success'],", "= self.make_context( method='POST', data={'X-Mailgun-Dkim-Check-Result': message.DKIM_PASS_VALUES[0][::-1]}, ) with ctx: msg =", "TestProvisionNode(ContextTestCase): def setUp(self): super(TestProvisionNode, self).setUp() self.node = ProjectFactory() self.user =", "test_is_spam_false_all_headers(self): ctx = self.make_context( method='POST', data={ 'X-Mailgun-Sscore': message.SSCORE_MAX_VALUE - 1,", "# Private node added private_node = ProjectFactory(is_public=False) conf.submissions.add(private_node) assert_equal(conf.submissions.count(), 5)", "conf.submissions.add(private_node) assert_equal(conf.submissions.count(), 5) assert_equal(conf.valid_submissions.count(), 3) class TestConferenceIntegration(ContextTestCase): @mock.patch('website.conferences.views.send_mail') @mock.patch('website.conferences.utils.upload_attachments') def", "3 good nodes added create_fake_conference_nodes(3, conf) # Deleted node added", "= cls._MAILGUN_API_KEY def make_context(self, method='POST', **kwargs): data = { 'X-Mailgun-Sscore':", "def test_conference_valid_submissions(self): conf = ConferenceFactory(endpoint='Hamburgers', name='Hamburger conference') conf.save() # 3", "conference = ConferenceFactory() url = web_url_for('conference_results__plain', meeting=conference.endpoint) res = self.app.get(url)", "msg = message.ConferenceMessage() assert_equal(len(msg.attachments), 1) assert_equal(msg.attachments[0].read(), content) class TestConferenceEmailViews(OsfTestCase): def", "content) class TestConferenceEmailViews(OsfTestCase): def test_redirect_to_meetings_url(self): url = '/presentations/' res =", "'attachment-1'), }, ) with ctx: msg = message.ConferenceMessage() assert_equal(len(msg.attachments), 1)", "Regression for OSF-8864 to confirm bad project data does not", "# user's shouldn't be able to use email as fullname,", "= '<EMAIL>' ctx = self.make_context( method='POST', data={'recipient': address}, ) with", "assert_equal(msg.sender_email, email[1]) def test_route_invalid_pattern(self): with self.make_context(data={'recipient': '<EMAIL>'}): self.app.app.preprocess_request() msg =", "'test-' if settings.DEV_MODE else '', conference.endpoint, ) res = self.app.post(", "OSFUser, AbstractNode from addons.wiki.models import WikiVersion from osf.exceptions import BlacklistedEmailError", "ctx = self.make_context( method='POST', data={'X-Mailgun-Sscore': message.SSCORE_MAX_VALUE - 1}, ) with", "self.node, self.attachment) mock_get_url.assert_called_with( self.node._id, 'osfstorage', _internal=True, base_url=self.node.osfstorage_region.waterbutler_url, cookie=self.user.get_or_create_cookie(), name=settings.MISSING_FILE_NAME, )", "assert_false(self.node.is_public) assert_in(self.conference.admins.first(), self.node.contributors) assert_in('emailed', self.node.system_tags) assert_in('spam', self.node.system_tags) @mock.patch('website.conferences.utils.waterbutler_api_url_for') @mock.patch('website.conferences.utils.requests.put') def", "if settings.DEV_MODE else 'stage-') with self.make_context(data={'recipient': recipient}): self.app.app.preprocess_request() msg =", "title = 'no full name only email' conference = ConferenceFactory()", "title') def test_conference_valid_submissions(self): conf = ConferenceFactory(endpoint='Hamburgers', name='Hamburger conference') conf.save() #", "def test_text(self): text = 'welcome to my nuclear family' ctx", "test_get_or_create_user_is_spam(self): fullname = '<NAME>' username = '<EMAIL>' fetched, created =", "assert_equal(conf.field_names['submission1'], 'poster') assert_equal(conf.field_names['mail_subject'], 'Presentation title') def test_conference_valid_submissions(self): conf = ConferenceFactory(endpoint='Hamburgers',", ") def make_context(self, **kwargs): data = { 'attachment-count': '1', 'attachment-1':", "range(n): node = ProjectFactory(is_public=True) conference.submissions.add(node) # inject bad data if", "get_or_create_user(fullname, username, is_spam=True) fetched.save() # in order to access m2m", "meeting=conference.endpoint) res = self.app.get(url) assert_equal(res.status_code, 200) assert_equal(len(res.json), n_conference_nodes) # Regression", "mock_send_mail.call_args assert_absolute(call_kwargs['conf_view_url']) assert_absolute(call_kwargs['set_password_url']) assert_absolute(call_kwargs['profile_url']) assert_absolute(call_kwargs['file_url']) assert_absolute(call_kwargs['node_url']) @mock.patch('website.conferences.views.send_mail') def test_integration_inactive(self, mock_send_mail):", "ctx: msg = message.ConferenceMessage() assert_equal(msg.recipient, address) def test_text(self): text =", "fullname = '<NAME>' username = '<EMAIL>' title = 'good songs'", "= StringIO(content) ctx = self.make_context( method='POST', data={ 'attachment-count': 1, 'attachment-1':", "'<NAME>' username = '<EMAIL>' title = 'good songs' body =", "conference1, ) create_fake_conference_nodes( 2, conference2, ) url = api_url_for('conference_submissions') res", "assert_true(created) assert_equal(fetched.fullname, fullname) assert_equal(fetched.username, username) assert_false('is_spam' in fetched.system_tags) def test_get_or_create_user_is_spam(self):", "with self.make_context(data={'signature': 'fake'}): self.app.app.preprocess_request() msg = message.ConferenceMessage() with assert_raises(message.ConferenceError): msg.verify_signature()", "def test_sender_email(self): emails = [ (u'<EMAIL>', u'<EMAIL>'), (u'<EMAIL>', u'<EMAIL>') ]", "assert_in('emailed', self.node.system_tags) assert_in('spam', self.node.system_tags) @mock.patch('website.conferences.utils.waterbutler_api_url_for') @mock.patch('website.conferences.utils.requests.put') def test_upload(self, mock_put, mock_get_url):", "msg.route def test_route_valid_alternate(self): conf = ConferenceFactory(endpoint='chocolate', active=True) conf.name = 'Chocolate", "created = get_or_create_user(user.fullname, user.username, is_spam=True) assert_false(created) assert_equal(user._id, fetched._id) assert_false('is_spam' in", "self.app.get(url) assert_equal(res.status_code, 302) res = res.follow() assert_equal(res.request.path, '/meetings/') def test_conference_submissions(self):", "'chocolate') assert_equal(msg.conference_category, 'data') conf.__class__.delete(conf) def test_route_valid_b(self): recipient = '{0}<EMAIL>'.format('test-' if", "with assert_raises(message.ConferenceError): msg.route def test_route_invalid_test(self): recipient = '{0}<EMAIL>'.format('' if settings.DEV_MODE", "contributor node.contributor_set.filter(user=node.contributors.first()).delete() node.save() nodes.append(node) return nodes class TestConferenceUtils(OsfTestCase): def test_get_or_create_user_exists(self):", "mock_put.assert_called_with( mock_get_url.return_value, data=self.content, ) @mock.patch('website.conferences.utils.upload_attachments') def test_add_poster_by_email(self, mock_upload_attachments): conference =", "body = 'Greg is a good plant' content = 'Long", "digestmod=hashlib.sha256, ).hexdigest(), } data.update(kwargs.pop('data', {})) data = { key: value", "furl.furl(url) assert_equal(parsed_domain.host, parsed_url.host) def assert_equal_urls(first, second): parsed_first = furl.furl(first) parsed_first.port", "recipient}): self.app.app.preprocess_request() msg = message.ConferenceMessage() assert_equal(msg.conference_name, 'chocolate') assert_equal(msg.conference_category, 'data') conf.__class__.delete(conf)", "0, 'from': '{0} <{1}>'.format(fullname, username), 'recipient': recipient, 'subject': title, 'stripped-text':", "super(TestProvisionNode, self).setUp() self.node = ProjectFactory() self.user = self.node.creator self.conference =", "= ConferenceFactory(active=False) fullname = '<NAME>' username = '<EMAIL>' title =", "(u'Fred <<EMAIL>>', u'Fred'), (u'\"Fred\" <<EMAIL>>', u'Fred'), ] for name in", "= self.make_context( method='POST', data={ 'attachment-count': 1, 'attachment-1': (sio, 'attachment-1'), },", "noqa (PEP8 asserts) import hmac import hashlib from StringIO import", "to use email as fullname, so we use the guid.", "e.g. tags assert_true(created) assert_equal(fetched.fullname, fullname) assert_equal(fetched.username, username) assert_false('is_spam' in fetched.system_tags)", "'Long may they reign.' recipient = '{0}{1}-<EMAIL>'.format( 'test-' if settings.DEV_MODE", "def test_endpoint_is_required(self): with assert_raises(IntegrityError): ConferenceFactory(endpoint=None, name=fake.company()).save() def test_name_is_required(self): with assert_raises(IntegrityError):", ") with ctx: msg = message.ConferenceMessage() assert msg.is_spam def test_is_spam_true_spf(self):", "= message.ConferenceMessage() msg.verify_signature() def test_verify_signature_invalid(self): with self.make_context(data={'signature': 'fake'}): self.app.app.preprocess_request() msg", "'stripped-text': self.body, } data.update(kwargs.pop('data', {})) return super(TestProvisionNode, self).make_context(data=data, **kwargs) def", "def test_upload(self, mock_put, mock_get_url): mock_get_url.return_value = 'http://queen.com/' file_name = 'hammer-to-fall'", "('attachment-1', 'attachment-1', content), ], ) assert AbstractNode.objects.filter(title=title, creator=user).count() == 2", "body, }, upload_files=[ ('attachment-1', 'attachment-1', content), ], ) assert AbstractNode.objects.filter(title=title,", "import settings from website.conferences import views from website.conferences import utils,", "hmac import hashlib from StringIO import StringIO from django.core.exceptions import", "def test_integration_inactive(self, mock_send_mail): conference = ConferenceFactory(active=False) fullname = '<NAME>' username", "+ 1}): msg = message.ConferenceMessage() utils.provision_node(self.conference, msg, self.node, self.user) assert_false(self.node.is_public)", "def test_route_valid_b(self): recipient = '{0}<EMAIL>'.format('test-' if settings.DEV_MODE else '') with", "test_conference_data_tag_upper(self): conference = ConferenceFactory() # Create conference nodes n_conference_nodes =", "'dragon on my back' recipient = '{0}{1}-<EMAIL>'.format( 'test-' if settings.DEV_MODE", "'token': 'secret', 'signature': hmac.new( key=settings.MAILGUN_API_KEY, msg='{}{}'.format('123', 'secret'), digestmod=hashlib.sha256, ).hexdigest(), }", "message.SSCORE_MAX_VALUE - 1, 'X-Mailgun-Dkim-Check-Result': message.DKIM_PASS_VALUES[0], 'X-Mailgun-Spf': message.SPF_PASS_VALUES[0], }, ) with", "conference.submissions.add(node) node.save() nodes.append(node) return nodes def create_fake_conference_nodes_bad_data(conference, n, bad_n, endpoint):", "user.fullname == user._id # user's shouldn't be able to use", "assert_absolute(call_kwargs['conf_view_url']) assert_absolute(call_kwargs['set_password_url']) assert_absolute(call_kwargs['profile_url']) assert_absolute(call_kwargs['file_url']) assert_absolute(call_kwargs['node_url']) @mock.patch('website.conferences.views.send_mail') def test_integration_inactive(self, mock_send_mail): conference", "recipient}): self.app.app.preprocess_request() msg = message.ConferenceMessage() with assert_raises(message.ConferenceError): msg.route def test_attachments_count_zero(self):", "= ConferenceFactory(endpoint='chocolate', active=True) conf.name = 'Chocolate Conference' conf.field_names['submission2'] = 'data'", "in data.items() if value is not None } return self.app.app.test_request_context(method=method,", "meeting=conference.endpoint) res = self.app.get(url) assert_equal(res.status_code, 200) def test_conference_data(self): conference =", ") with ctx: msg = message.ConferenceMessage() assert_equal(msg.text, text) def test_sender_name(self):", "'{0}{1}-<EMAIL>'.format( 'test-' if settings.DEV_MODE else '', conference.endpoint, ) res =", "test_provision_spam(self): with self.make_context(data={'X-Mailgun-Sscore': message.SSCORE_MAX_VALUE + 1}): msg = message.ConferenceMessage() utils.provision_node(self.conference,", "@mock.patch('website.conferences.utils.upload_attachments') def test_add_poster_by_email(self, mock_upload_attachments): conference = ConferenceFactory() with self.make_context(data={'from': '<EMAIL>',", "test_integration(self, mock_upload, mock_send_mail): fullname = '<NAME>' username = '<EMAIL>' title", "super(ContextTestCase, cls).tearDownClass() settings.MAILGUN_API_KEY = cls._MAILGUN_API_KEY def make_context(self, method='POST', **kwargs): data", "method='POST', **kwargs): data = { 'X-Mailgun-Sscore': 0, 'timestamp': '123', 'token':", "(u'<EMAIL>', u'<EMAIL>'), (u'Fred <<EMAIL>>', u'Fred'), (u'\"Fred\" <<EMAIL>>', u'Fred'), ] for", "West' username = '<EMAIL>' with assert_raises(BlacklistedEmailError) as e: get_or_create_user(fullname, username,", "(sio, 'attachment-1'), }, ) with ctx: msg = message.ConferenceMessage() assert_equal(len(msg.attachments),", "= self.make_context( method='POST', data={'subject': 'RE: Hip Hopera'}, ) with ctx:", "{})) data = { key: value for key, value in", "= 'Long may they reign.' recipient = '{0}{1}-<EMAIL>'.format( 'test-' if", "with self.make_context(data={'from': name[0]}): msg = message.ConferenceMessage() assert_equal(msg.sender_name, name[1]) def test_sender_email(self):", "mock from nose.tools import * # noqa (PEP8 asserts) import", "with self.make_context(data={'recipient': recipient}): self.app.app.preprocess_request() msg = message.ConferenceMessage() assert_equal(msg.conference_name, 'chocolate') assert_equal(msg.conference_category,", "from website.conferences import views from website.conferences import utils, message from", "= api_url_for('conference_data', meeting=conference.endpoint) res = self.app.get(url) assert_equal(res.status_code, 200) assert_equal(len(res.json), n_conference_nodes)", "message.ConferenceMessage() assert not msg.is_spam def test_is_spam_false_all_headers(self): ctx = self.make_context( method='POST',", "# 3 good nodes added create_fake_conference_nodes(3, conf) # Deleted node", "parsed_first = furl.furl(first) parsed_first.port = None parsed_second = furl.furl(second) parsed_second.port", "with self.make_context(data={'attachment-count': '0'}): msg = message.ConferenceMessage() assert_equal(msg.attachments, []) def test_attachments_count_one(self):", "message.ConferenceMessage() assert_equal(msg.sender_email, email[1]) def test_route_invalid_pattern(self): with self.make_context(data={'recipient': '<EMAIL>'}): self.app.app.preprocess_request() msg", "'dragon attack' self.attachment = StringIO(self.content) self.recipient = '{0}{1}-<EMAIL>'.format( 'test-' if", "test_name_is_required(self): with assert_raises(IntegrityError): ConferenceFactory(endpoint='spsp2014', name=None).save() def test_default_field_names(self): conf = ConferenceFactory(endpoint='cookie',", "u'<EMAIL>'), (u'Fred <<EMAIL>>', u'Fred'), (u'\"Fred\" <<EMAIL>>', u'Fred'), ] for name", "name[0]}): msg = message.ConferenceMessage() assert_equal(msg.sender_name, name[1]) def test_sender_email(self): emails =", "with ctx: msg = message.ConferenceMessage() assert msg.is_spam def test_is_spam_true_spf(self): ctx", "project data does not make whole conference break def test_conference_bad_data(self):", "username = '<EMAIL>' fetched, created = get_or_create_user(fullname, username, is_spam=False) fetched.save()", "with self.make_context(): msg = message.ConferenceMessage() msg.verify_signature() def test_verify_signature_invalid(self): with self.make_context(data={'signature':", "**kwargs) def test_provision(self): with self.make_context(): msg = message.ConferenceMessage() utils.provision_node(self.conference, msg,", "= '<NAME>' username = '<EMAIL>' title = 'good songs' body", "= '<NAME>' username = '<EMAIL>' title = 'good songs' conference", "username = '<EMAIL>' title = 'good songs' conference = ConferenceFactory()", "ProjectFactory() url = api_url_for('conference_data', meeting=conference.endpoint) res = self.app.get(url) assert_equal(res.status_code, 200)", "conf.save() # 3 good nodes added create_fake_conference_nodes(3, conf) # Deleted", "PUSH_CONTEXT = False def test_verify_signature_valid(self): with self.make_context(): msg = message.ConferenceMessage()", "title = 'good songs' conference = ConferenceFactory() body = 'dragon", "content), ], ) assert AbstractNode.objects.filter(title=title, creator=user).count() == 2 assert mock_upload.called", "website.util import api_url_for, web_url_for from tests.base import OsfTestCase, fake from", "ConferenceFactory(active=False) fullname = '<NAME>' username = '<EMAIL>' title = 'good", "user's shouldn't be able to use email as fullname, so", "= '<EMAIL>' title = 'good songs' conference = ConferenceFactory() body", "ProjectFactory(is_public=True) conference.submissions.add(node) node.save() nodes.append(node) return nodes def create_fake_conference_nodes_bad_data(conference, n, bad_n,", "website.conferences import views from website.conferences import utils, message from website.util", "my back' content = 'dragon attack' recipient = '{0}{1}-<EMAIL>'.format( 'test-'", "msg) user = OSFUser.objects.get(username='<EMAIL>') assert user.email == '<EMAIL>' assert user.fullname", "in range(n): node = ProjectFactory(is_public=True) conference.submissions.add(node) node.save() nodes.append(node) return nodes", "create_fake_conference_nodes(3, conf) # Deleted node added deleted_node = ProjectFactory(is_public=True) deleted_node.is_deleted", "my back' self.content = 'dragon attack' self.attachment = StringIO(self.content) self.recipient", "= message.ConferenceMessage() assert_equal(msg.recipient, address) def test_text(self): text = 'welcome to", "views from website.conferences import utils, message from website.util import api_url_for,", "recipient}): self.app.app.preprocess_request() msg = message.ConferenceMessage() assert_equal(msg.conference_name, 'conf') assert_equal(msg.conference_category, 'poster') def", "assert_raises(message.ConferenceError): msg.route def test_attachments_count_zero(self): with self.make_context(data={'attachment-count': '0'}): msg = message.ConferenceMessage()", "meeting=conference.endpoint) res = self.app.get(url) assert_equal(res.status_code, 200) assert_equal(len(res.json), n_conference_nodes - n_conference_nodes_bad)", "'X-Mailgun-Spf': message.SPF_PASS_VALUES[0], }, ) with ctx: msg = message.ConferenceMessage() assert", "= None assert_equal(parsed_first, parsed_second) def create_fake_conference_nodes(n, conference): nodes = []", "'X-Mailgun-Sscore': 0, 'from': '{0} <{1}>'.format(fullname, username), 'recipient': recipient, 'subject': title,", "# Create conference nodes create_fake_conference_nodes( 3, conference1, ) create_fake_conference_nodes( 2,", ") with ctx: msg = message.ConferenceMessage() assert msg.is_spam def test_is_spam_true_dkim(self):", "= message.ConferenceMessage() utils.provision_node(self.conference, msg, self.node, self.user) assert_true(self.node.is_public) assert_in(self.conference.admins.first(), self.node.contributors) assert_in('emailed',", "= nodes[0] assert_equal(WikiVersion.objects.get_for_node(node, 'home').content, body) assert_true(mock_send_mail.called) call_args, call_kwargs = mock_send_mail.call_args", "nodes = [] for i in range(n): node = ProjectFactory(is_public=True)", "conf = ConferenceFactory(endpoint='cookie', name='Cookies Conference') conf.save() assert_equal(conf.field_names['submission1'], 'poster') assert_equal(conf.field_names['mail_subject'], 'Presentation", "self.attachment.content_type = 'application/json' utils.upload_attachment(self.user, self.node, self.attachment) mock_get_url.assert_called_with( self.node._id, 'osfstorage', _internal=True,", "bad_n, endpoint): nodes = [] for i in range(n): node", "with ctx: msg = message.ConferenceMessage() assert not msg.is_spam def test_is_spam_true_sscore(self):", "self.recipient = '{0}{1}-<EMAIL>'.format( 'test-' if settings.DEV_MODE else '', self.conference.endpoint, )", "in names: with self.make_context(data={'from': name[0]}): msg = message.ConferenceMessage() assert_equal(msg.sender_name, name[1])", "recipient = '{0}<EMAIL>'.format('test-' if settings.DEV_MODE else '') with self.make_context(data={'recipient': recipient}):", "= self.make_context( method='POST', data={'X-Mailgun-Sscore': message.SSCORE_MAX_VALUE - 1}, ) with ctx:", "assert_absolute(call_kwargs['node_url']) @mock.patch('website.conferences.views.send_mail') def test_integration_inactive(self, mock_send_mail): conference = ConferenceFactory(active=False) fullname =", "def test_default_field_names(self): conf = ConferenceFactory(endpoint='cookie', name='Cookies Conference') conf.save() assert_equal(conf.field_names['submission1'], 'poster')", "= ConferenceFactory() with self.make_context(data={'from': '<EMAIL>', 'subject': 'It\\'s PARTY TIME!'}): msg", "= False def test_verify_signature_valid(self): with self.make_context(): msg = message.ConferenceMessage() msg.verify_signature()", "self.make_context(data={'from': email[0]}): msg = message.ConferenceMessage() assert_equal(msg.sender_email, email[1]) def test_route_invalid_pattern(self): with", "on my back' self.content = 'dragon attack' self.attachment = StringIO(self.content)", "'secret', 'signature': hmac.new( key=settings.MAILGUN_API_KEY, msg='{}{}'.format('123', 'secret'), digestmod=hashlib.sha256, ).hexdigest(), 'attachment-count': '1',", "test_redirect_to_meetings_url(self): url = '/presentations/' res = self.app.get(url) assert_equal(res.status_code, 302) res", "import ConferenceFactory, ProjectFactory, UserFactory def assert_absolute(url): parsed_domain = furl.furl(settings.DOMAIN) parsed_url", "self.make_context(data={'recipient': recipient}): self.app.app.preprocess_request() msg = message.ConferenceMessage() assert_equal(msg.conference_name, 'conf') assert_equal(msg.conference_category, 'poster')", "assert self.node in self.conference.submissions.all() assert_not_in('spam', self.node.system_tags) def test_provision_private(self): self.conference.public_projects =", "406) call_args, call_kwargs = mock_send_mail.call_args assert_equal(call_args, (username, views.CONFERENCE_INACTIVE)) assert_equal(call_kwargs['fullname'], fullname)", "def test_verify_signature_valid(self): with self.make_context(): msg = message.ConferenceMessage() msg.verify_signature() def test_verify_signature_invalid(self):", "= furl.furl(url) assert_equal(parsed_domain.host, parsed_url.host) def assert_equal_urls(first, second): parsed_first = furl.furl(first)", "a non-conference node ProjectFactory() url = api_url_for('conference_data', meeting=conference.endpoint) res =", "conference.submissions.add(node) # inject bad data if i < bad_n: #", "Delete only contributor node.contributor_set.filter(user=node.contributors.first()).delete() node.save() nodes.append(node) return nodes class TestConferenceUtils(OsfTestCase):", "= 'Kanye West' username = '<EMAIL>' with assert_raises(BlacklistedEmailError) as e:", "} data.update(kwargs.pop('data', {})) data = { key: value for key,", "class TestConferenceIntegration(ContextTestCase): @mock.patch('website.conferences.views.send_mail') @mock.patch('website.conferences.utils.upload_attachments') def test_integration(self, mock_upload, mock_send_mail): fullname =", "user = OSFUser.objects.get(username='<EMAIL>') assert user.email == '<EMAIL>' assert user.fullname ==", "= get_or_create_user(user.fullname, user.username, is_spam=True) assert_false(created) assert_equal(user._id, fetched._id) assert_false('is_spam' in fetched.system_tags)", "recipient}): self.app.app.preprocess_request() msg = message.ConferenceMessage() with assert_raises(message.ConferenceError): msg.route def test_route_valid_alternate(self):", "def test_provision_private(self): self.conference.public_projects = False self.conference.save() with self.make_context(): msg =", "name=None).save() def test_default_field_names(self): conf = ConferenceFactory(endpoint='cookie', name='Cookies Conference') conf.save() assert_equal(conf.field_names['submission1'],", "from website import settings from website.conferences import views from website.conferences", "import utils, message from website.util import api_url_for, web_url_for from tests.base", "test_route_invalid_test(self): recipient = '{0}<EMAIL>'.format('' if settings.DEV_MODE else 'stage-') with self.make_context(data={'recipient':", "[] for i in range(n): node = ProjectFactory(is_public=True) conference.submissions.add(node) node.save()", "data={'subject': 'RE: Hip Hopera'}, ) with ctx: msg = message.ConferenceMessage()", "= '{0}<EMAIL>'.format('' if settings.DEV_MODE else 'stage-') with self.make_context(data={'recipient': recipient}): self.app.app.preprocess_request()", "class ContextTestCase(OsfTestCase): MAILGUN_API_KEY = 'mailkimp' @classmethod def setUpClass(cls): super(ContextTestCase, cls).setUpClass()", "3 n_conference_nodes_bad = 1 create_fake_conference_nodes_bad_data( conference, n_conference_nodes, n_conference_nodes_bad, conference, )", "import furl from framework.auth import get_or_create_user from framework.auth.core import Auth", "msg, self.node, self.user) assert_false(self.node.is_public) assert_in(self.conference.admins.first(), self.node.contributors) assert_in('emailed', self.node.system_tags) assert_in('spam', self.node.system_tags)", "user.username, is_spam=True) assert_false(created) assert_equal(user._id, fetched._id) assert_false('is_spam' in fetched.system_tags) def test_get_or_create_user_not_exists(self):", "'X-Mailgun-Sscore': 0, 'from': '{0} <{1}>'.format(user.fullname, user.username), 'recipient': recipient, 'subject': title,", "guid. class TestMessage(ContextTestCase): PUSH_CONTEXT = False def test_verify_signature_valid(self): with self.make_context():", "'attachment-1': (sio, 'attachment-1'), }, ) with ctx: msg = message.ConferenceMessage()", "= self.app.get(url) assert_equal(res.status_code, 200) assert_equal(len(res.json), n_conference_nodes) # Regression for OSF-8864", "+ 1}, ) with ctx: msg = message.ConferenceMessage() assert msg.is_spam", "from website.conferences import utils, message from website.util import api_url_for, web_url_for", "AbstractNode.objects.all().delete() conference1 = ConferenceFactory() conference2 = ConferenceFactory() # Create conference", "self.conference.save() with self.make_context(): msg = message.ConferenceMessage() utils.provision_node(self.conference, msg, self.node, self.user)", "assert_absolute(call_kwargs['conf_view_url']) assert_absolute(call_kwargs['set_password_url']) assert_absolute(call_kwargs['profile_url']) assert_absolute(call_kwargs['file_url']) assert_absolute(call_kwargs['node_url']) @mock.patch('website.conferences.views.send_mail') @mock.patch('website.conferences.utils.upload_attachments') def test_create_conference_node_with_same_name_as_existing_node(self, mock_upload,", "@mock.patch('website.conferences.views.send_mail') def test_integration_inactive(self, mock_send_mail): conference = ConferenceFactory(active=False) fullname = '<NAME>'", "1}, ) with ctx: msg = message.ConferenceMessage() assert msg.is_spam def", "self.make_context( method='POST', data={'subject': 'RE: Hip Hopera'}, ) with ctx: msg", "'1', 'X-Mailgun-Sscore': 0, 'from': '{0} <{1}>'.format(fullname, username), 'recipient': recipient, 'subject':", "self.app.post( api_url_for('meeting_hook'), { 'X-Mailgun-Sscore': 0, 'timestamp': '123', 'token': 'secret', 'signature':", "self.make_context( method='POST', data={'X-Mailgun-Dkim-Check-Result': message.DKIM_PASS_VALUES[0][::-1]}, ) with ctx: msg = message.ConferenceMessage()", "so we use the guid. class TestMessage(ContextTestCase): PUSH_CONTEXT = False", "n_conference_nodes) def test_conference_data_tag_upper(self): conference = ConferenceFactory() # Create conference nodes", "Create conference nodes n_conference_nodes = 3 create_fake_conference_nodes( n_conference_nodes, conference, )", "from framework.auth.core import Auth from osf.models import OSFUser, AbstractNode from", "with ctx: msg = message.ConferenceMessage() assert not msg.is_spam def test_is_spam_false_all_headers(self):", "ctx = self.make_context( method='POST', data={'X-Mailgun-Spf': message.SPF_PASS_VALUES[0][::-1]}, ) with ctx: msg", "'dragon on my back' content = 'dragon attack' recipient =", "def setUp(self): super(TestProvisionNode, self).setUp() self.node = ProjectFactory() self.user = self.node.creator", "self.app.get(url) assert_equal(res.status_code, 200) assert_equal(len(res.json), n_conference_nodes) def test_conference_data_tag_upper(self): conference = ConferenceFactory()", "message.ConferenceMessage() assert_equal(msg.recipient, address) def test_text(self): text = 'welcome to my", "mock_get_url.return_value = 'http://queen.com/' self.attachment.filename = '' self.attachment.content_type = 'application/json' utils.upload_attachment(self.user,", "n_conference_nodes, n_conference_nodes_bad, conference, ) # Create a non-conference node ProjectFactory()", "data={'X-Mailgun-Spf': message.SPF_PASS_VALUES[0][::-1]}, ) with ctx: msg = message.ConferenceMessage() assert msg.is_spam", "return self.app.app.test_request_context(method=method, data=data, **kwargs) class TestProvisionNode(ContextTestCase): def setUp(self): super(TestProvisionNode, self).setUp()", "be able to use email as fullname, so we use", "body, }, upload_files=[ ('attachment-1', 'attachment-1', content), ], ) assert_true(mock_upload.called) users", "second): parsed_first = furl.furl(first) parsed_first.port = None parsed_second = furl.furl(second)", "= 'http://queen.com/' self.attachment.filename = '' self.attachment.content_type = 'application/json' utils.upload_attachment(self.user, self.node,", "data={'X-Mailgun-Sscore': message.SSCORE_MAX_VALUE - 1}, ) with ctx: msg = message.ConferenceMessage()", "def test_conference_bad_data(self): conference = ConferenceFactory() # Create conference nodes n_conference_nodes", "self.app.app.preprocess_request() msg = message.ConferenceMessage() with assert_raises(message.ConferenceError): msg.verify_signature() def test_is_spam_false_missing_headers(self): ctx", "make_context(self, **kwargs): data = { 'attachment-count': '1', 'attachment-1': (self.attachment, 'attachment-1'),", "= ConferenceFactory() conference2 = ConferenceFactory() # Create conference nodes create_fake_conference_nodes(", "'http://queen.com/' file_name = 'hammer-to-fall' self.attachment.filename = file_name self.attachment.content_type = 'application/json'", "'stripped-text': body, }, upload_files=[ ('attachment-1', 'attachment-1', content), ], ) assert_true(mock_upload.called)", "address = '<EMAIL>' ctx = self.make_context( method='POST', data={'recipient': address}, )", "self.app.app.preprocess_request() msg = message.ConferenceMessage() with assert_raises(message.ConferenceError): msg.route def test_route_invalid_test(self): recipient", "import IntegrityError import furl from framework.auth import get_or_create_user from framework.auth.core", "1}, ) with ctx: msg = message.ConferenceMessage() assert not msg.is_spam", "else 'stage-') with self.make_context(data={'recipient': recipient}): self.app.app.preprocess_request() msg = message.ConferenceMessage() with", "self.make_context(data={'recipient': recipient}): self.app.app.preprocess_request() msg = message.ConferenceMessage() with assert_raises(message.ConferenceError): msg.route def", "message.ConferenceMessage() msg.verify_signature() def test_verify_signature_invalid(self): with self.make_context(data={'signature': 'fake'}): self.app.app.preprocess_request() msg =", "Conference') conf.save() assert_equal(conf.field_names['submission1'], 'poster') assert_equal(conf.field_names['mail_subject'], 'Presentation title') def test_conference_valid_submissions(self): conf", "method='POST', data={'X-Mailgun-Dkim-Check-Result': message.DKIM_PASS_VALUES[0][::-1]}, ) with ctx: msg = message.ConferenceMessage() assert", "call_kwargs = mock_send_mail.call_args assert_absolute(call_kwargs['conf_view_url']) assert_absolute(call_kwargs['set_password_url']) assert_absolute(call_kwargs['profile_url']) assert_absolute(call_kwargs['file_url']) assert_absolute(call_kwargs['node_url']) @mock.patch('website.conferences.views.send_mail') @mock.patch('website.conferences.utils.upload_attachments')", "ValidationError from django.db import IntegrityError import furl from framework.auth import", "= 'mailkimp' @classmethod def setUpClass(cls): super(ContextTestCase, cls).setUpClass() settings.MAILGUN_API_KEY, cls._MAILGUN_API_KEY =", "(u'Me䬟', u'Me䬟'), (u'<EMAIL>', u'<EMAIL>'), (u'Fred <<EMAIL>>', u'Fred'), (u'\"Fred\" <<EMAIL>>', u'Fred'),", "msg.route def test_route_invalid_test(self): recipient = '{0}<EMAIL>'.format('' if settings.DEV_MODE else 'stage-')", "non-conference node ProjectFactory() url = api_url_for('conference_data', meeting=conference.endpoint.upper()) res = self.app.get(url)", "assert_false(self.node.is_public) assert_in(self.conference.admins.first(), self.node.contributors) assert_in('emailed', self.node.system_tags) assert_not_in('spam', self.node.system_tags) def test_provision_spam(self): with", "sio = StringIO(content) ctx = self.make_context( method='POST', data={ 'attachment-count': 1,", "data=data, **kwargs) class TestProvisionNode(ContextTestCase): def setUp(self): super(TestProvisionNode, self).setUp() self.node =", "username) assert_true('is_spam' in fetched.system_tags) def test_get_or_create_user_with_blacklisted_domain(self): fullname = 'Kanye West'", "settings.DEV_MODE else '', self.conference.endpoint, ) def make_context(self, **kwargs): data =", "200) def test_conference_data(self): conference = ConferenceFactory() # Create conference nodes", "with assert_raises(message.ConferenceError): msg.route def test_route_valid_alternate(self): conf = ConferenceFactory(endpoint='chocolate', active=True) conf.name", "assert_equal_urls( call_kwargs['presentations_url'], web_url_for('conference_view', _absolute=True), ) @mock.patch('website.conferences.views.send_mail') @mock.patch('website.conferences.utils.upload_attachments') def test_integration_wo_full_name(self, mock_upload,", "body = 'dragon on my back' content = 'dragon attack'", "addons.wiki.models import WikiVersion from osf.exceptions import BlacklistedEmailError from website import", "nose.tools import * # noqa (PEP8 asserts) import hmac import", "make_context(self, method='POST', **kwargs): data = { 'X-Mailgun-Sscore': 0, 'timestamp': '123',", "ctx: msg = message.ConferenceMessage() assert_equal(len(msg.attachments), 1) assert_equal(msg.attachments[0].read(), content) class TestConferenceEmailViews(OsfTestCase):", "test_verify_signature_valid(self): with self.make_context(): msg = message.ConferenceMessage() msg.verify_signature() def test_verify_signature_invalid(self): with", "fields, e.g. tags assert_true(created) assert_equal(fetched.fullname, fullname) assert_equal(fetched.username, username) assert_true('is_spam' in", "fetched.system_tags) def test_get_or_create_user_not_exists(self): fullname = '<NAME>' username = '<EMAIL>' fetched,", "ConferenceFactory() body = 'dragon on my back' content = 'dragon", "(username, views.CONFERENCE_INACTIVE)) assert_equal(call_kwargs['fullname'], fullname) assert_equal_urls( call_kwargs['presentations_url'], web_url_for('conference_view', _absolute=True), ) @mock.patch('website.conferences.views.send_mail')", "call_kwargs['presentations_url'], web_url_for('conference_view', _absolute=True), ) @mock.patch('website.conferences.views.send_mail') @mock.patch('website.conferences.utils.upload_attachments') def test_integration_wo_full_name(self, mock_upload, mock_send_mail):", "data.items() if value is not None } return self.app.app.test_request_context(method=method, data=data,", "n_conference_nodes_bad, conference, ) # Create a non-conference node ProjectFactory() url", "content = 'Long may they reign.' recipient = '{0}{1}-<EMAIL>'.format( 'test-'", "= ConferenceFactory() url = web_url_for('conference_results__plain', meeting=conference.endpoint) res = self.app.get(url) assert_equal(res.status_code,", "'signature': hmac.new( key=settings.MAILGUN_API_KEY, msg='{}{}'.format('123', 'secret'), digestmod=hashlib.sha256, ).hexdigest(), } data.update(kwargs.pop('data', {}))", "cls).tearDownClass() settings.MAILGUN_API_KEY = cls._MAILGUN_API_KEY def make_context(self, method='POST', **kwargs): data =", "does not make whole conference break def test_conference_bad_data(self): conference =", "test_recipient(self): address = '<EMAIL>' ctx = self.make_context( method='POST', data={'recipient': address},", "coding: utf-8 -*- import mock from nose.tools import * #", "= '<EMAIL>' fetched, created = get_or_create_user(fullname, username, is_spam=True) fetched.save() #", "-*- coding: utf-8 -*- import mock from nose.tools import *", "url = web_url_for('conference_results__plain', meeting=conference.endpoint) res = self.app.get(url) assert_equal(res.status_code, 200) def", "= self.make_context( method='POST', data={'X-Mailgun-Spf': message.SPF_PASS_VALUES[0][::-1]}, ) with ctx: msg =", "parsed_domain = furl.furl(settings.DOMAIN) parsed_url = furl.furl(url) assert_equal(parsed_domain.host, parsed_url.host) def assert_equal_urls(first,", "self.make_context(): msg = message.ConferenceMessage() msg.verify_signature() def test_verify_signature_invalid(self): with self.make_context(data={'signature': 'fake'}):", "1) nodes = AbstractNode.objects.filter(title=title) assert_equal(nodes.count(), 1) node = nodes[0] assert_equal(WikiVersion.objects.get_for_node(node,", "'<EMAIL>' title = 'no full name only email' conference =", "utils.provision_node(self.conference, msg, self.node, self.user) assert_false(self.node.is_public) assert_in(self.conference.admins.first(), self.node.contributors) assert_in('emailed', self.node.system_tags) assert_not_in('spam',", "ctx = self.make_context( method='POST', data={'recipient': address}, ) with ctx: msg", "recipient = '{0}<EMAIL>'.format('' if settings.DEV_MODE else 'stage-') with self.make_context(data={'recipient': recipient}):", "def test_integration(self, mock_upload, mock_send_mail): fullname = '<NAME>' username = '<EMAIL>'", "email in emails: with self.make_context(data={'from': email[0]}): msg = message.ConferenceMessage() assert_equal(msg.sender_email,", "create_fake_conference_nodes( 3, conference1, ) create_fake_conference_nodes( 2, conference2, ) url =", "self.app.app.preprocess_request() msg = message.ConferenceMessage() assert_equal(msg.conference_name, 'chocolate') assert_equal(msg.conference_category, 'data') conf.__class__.delete(conf) def", "}, ) with ctx: msg = message.ConferenceMessage() assert not msg.is_spam", "import BlacklistedEmailError from website import settings from website.conferences import views", "ctx = self.make_context( method='POST', data={'X-Mailgun-Dkim-Check-Result': message.DKIM_PASS_VALUES[0][::-1]}, ) with ctx: msg", "parsed_first.port = None parsed_second = furl.furl(second) parsed_second.port = None assert_equal(parsed_first,", "data if i < bad_n: # Delete only contributor node.contributor_set.filter(user=node.contributors.first()).delete()", "username = '<EMAIL>' title = 'no full name only email'", "@mock.patch('website.conferences.utils.upload_attachments') def test_create_conference_node_with_same_name_as_existing_node(self, mock_upload, mock_send_mail): conference = ConferenceFactory() user =", "node added private_node = ProjectFactory(is_public=False) conf.submissions.add(private_node) assert_equal(conf.submissions.count(), 5) assert_equal(conf.valid_submissions.count(), 3)", "with ctx: msg = message.ConferenceMessage() assert_equal(msg.recipient, address) def test_text(self): text", "settings.MAILGUN_API_KEY @classmethod def tearDownClass(cls): super(ContextTestCase, cls).tearDownClass() settings.MAILGUN_API_KEY = cls._MAILGUN_API_KEY def", "message.SSCORE_MAX_VALUE + 1}, ) with ctx: msg = message.ConferenceMessage() assert", "'dragon on my back' self.content = 'dragon attack' self.attachment =", "settings.MAILGUN_API_KEY = cls._MAILGUN_API_KEY def make_context(self, method='POST', **kwargs): data = {", "class TestProvisionNode(ContextTestCase): def setUp(self): super(TestProvisionNode, self).setUp() self.node = ProjectFactory() self.user", "= 'hammer-to-fall' self.attachment.filename = file_name self.attachment.content_type = 'application/json' utils.upload_attachment(self.user, self.node,", "with self.make_context(data={'recipient': recipient}): self.app.app.preprocess_request() msg = message.ConferenceMessage() with assert_raises(message.ConferenceError): msg.route", "= ConferenceFactory() # Create conference nodes n_conference_nodes = 3 create_fake_conference_nodes(", "assert_equal(res.status_code, 200) assert_equal(len(res.json), n_conference_nodes - n_conference_nodes_bad) def test_conference_data_url_upper(self): conference =", "deleted_node.save() conf.submissions.add(deleted_node) # Private node added private_node = ProjectFactory(is_public=False) conf.submissions.add(private_node)", "'123', 'token': 'secret', 'signature': hmac.new( key=settings.MAILGUN_API_KEY, msg='{}{}'.format('123', 'secret'), digestmod=hashlib.sha256, ).hexdigest(),", "test_conference_data_url_upper(self): conference = ConferenceFactory() # Create conference nodes n_conference_nodes =", "ProjectFactory, UserFactory def assert_absolute(url): parsed_domain = furl.furl(settings.DOMAIN) parsed_url = furl.furl(url)", "'poster') assert_equal(conf.field_names['mail_subject'], 'Presentation title') def test_conference_valid_submissions(self): conf = ConferenceFactory(endpoint='Hamburgers', name='Hamburger", "test_text(self): text = 'welcome to my nuclear family' ctx =", ") create_fake_conference_nodes( 2, conference2, ) url = api_url_for('conference_submissions') res =", "= OSFUser.objects.get(username='<EMAIL>') assert user.email == '<EMAIL>' assert user.fullname == user._id", "assert_raises(message.ConferenceError): msg.verify_signature() def test_is_spam_false_missing_headers(self): ctx = self.make_context( method='POST', data={'X-Mailgun-Sscore': message.SSCORE_MAX_VALUE", "'', self.conference.endpoint, ) def make_context(self, **kwargs): data = { 'attachment-count':", "= message.ConferenceMessage() utils.provision_node(self.conference, msg, self.node, self.user) assert_false(self.node.is_public) assert_in(self.conference.admins.first(), self.node.contributors) assert_in('emailed',", "UserFactory def assert_absolute(url): parsed_domain = furl.furl(settings.DOMAIN) parsed_url = furl.furl(url) assert_equal(parsed_domain.host,", "= { key: value for key, value in data.items() if", "super(ContextTestCase, cls).setUpClass() settings.MAILGUN_API_KEY, cls._MAILGUN_API_KEY = cls.MAILGUN_API_KEY, settings.MAILGUN_API_KEY @classmethod def tearDownClass(cls):", "0, 'from': '{0} <{1}>'.format(user.fullname, user.username), 'recipient': recipient, 'subject': title, 'stripped-text':", "web_url_for from tests.base import OsfTestCase, fake from osf_tests.factories import ConferenceFactory,", "'<NAME>' username = '<EMAIL>' fetched, created = get_or_create_user(fullname, username, is_spam=True)", "<{1}>'.format(user.fullname, user.username), 'recipient': recipient, 'subject': title, 'stripped-text': body, }, upload_files=[", "@mock.patch('website.conferences.views.send_mail') @mock.patch('website.conferences.utils.upload_attachments') def test_integration(self, mock_upload, mock_send_mail): fullname = '<NAME>' username", "cls._MAILGUN_API_KEY = cls.MAILGUN_API_KEY, settings.MAILGUN_API_KEY @classmethod def tearDownClass(cls): super(ContextTestCase, cls).tearDownClass() settings.MAILGUN_API_KEY", "'http://queen.com/' self.attachment.filename = '' self.attachment.content_type = 'application/json' utils.upload_attachment(self.user, self.node, self.attachment)", "api_url_for('meeting_hook'), { 'X-Mailgun-Sscore': 0, 'timestamp': '123', 'token': 'secret', 'signature': hmac.new(", "302) res = res.follow() assert_equal(res.request.path, '/meetings/') def test_conference_submissions(self): AbstractNode.objects.all().delete() conference1", "django.core.exceptions import ValidationError from django.db import IntegrityError import furl from", "200) def test_confererence_results_endpoint_is_case_insensitive(self): ConferenceFactory(endpoint='StudySwap') url = web_url_for('conference_results', meeting='studyswap') res =", "200) class TestConferenceModel(OsfTestCase): def test_endpoint_is_required(self): with assert_raises(IntegrityError): ConferenceFactory(endpoint=None, name=fake.company()).save() def", "msg, self.node, self.user) assert_true(self.node.is_public) assert_in(self.conference.admins.first(), self.node.contributors) assert_in('emailed', self.node.system_tags) assert_in(self.conference.endpoint, self.node.system_tags)", "def test_get_or_create_user_not_exists(self): fullname = '<NAME>' username = '<EMAIL>' fetched, created", "@mock.patch('website.conferences.views.send_mail') @mock.patch('website.conferences.utils.upload_attachments') def test_integration_wo_full_name(self, mock_upload, mock_send_mail): username = '<EMAIL>' title", "TestConferenceModel(OsfTestCase): def test_endpoint_is_required(self): with assert_raises(IntegrityError): ConferenceFactory(endpoint=None, name=fake.company()).save() def test_name_is_required(self): with", "message.ConferenceMessage() assert_equal(msg.sender_name, name[1]) def test_sender_email(self): emails = [ (u'<EMAIL>', u'<EMAIL>'),", "if settings.DEV_MODE else '') with self.make_context(data={'recipient': recipient}): self.app.app.preprocess_request() msg =", "method='POST', data={ 'attachment-count': 1, 'attachment-1': (sio, 'attachment-1'), }, ) with", "hmac.new( key=settings.MAILGUN_API_KEY, msg='{}{}'.format('123', 'secret'), digestmod=hashlib.sha256, ).hexdigest(), } data.update(kwargs.pop('data', {})) data", "in fetched.system_tags) def test_get_or_create_user_is_spam(self): fullname = '<NAME>' username = '<EMAIL>'", "from osf_tests.factories import ConferenceFactory, ProjectFactory, UserFactory def assert_absolute(url): parsed_domain =", "'<NAME>' username = '<EMAIL>' title = 'good songs' conference =", "= self.app.get(url) assert_equal(res.status_code, 200) assert_equal(len(res.json), n_conference_nodes) def test_conference_results(self): conference =", "only contributor node.contributor_set.filter(user=node.contributors.first()).delete() node.save() nodes.append(node) return nodes class TestConferenceUtils(OsfTestCase): def", "'hammer-to-fall' self.attachment.filename = file_name self.attachment.content_type = 'application/json' utils.upload_attachment(self.user, self.node, self.attachment)", "None assert_equal(parsed_first, parsed_second) def create_fake_conference_nodes(n, conference): nodes = [] for", "def test_get_or_create_user_exists(self): user = UserFactory() fetched, created = get_or_create_user(user.fullname, user.username,", "self.app.get(url) assert_equal(res.status_code, 200) assert_equal(len(res.json), n_conference_nodes - n_conference_nodes_bad) def test_conference_data_url_upper(self): conference", "nodes def create_fake_conference_nodes_bad_data(conference, n, bad_n, endpoint): nodes = [] for", "= 'slightly mad' sio = StringIO(content) ctx = self.make_context( method='POST',", "msg.is_spam def test_is_spam_false_all_headers(self): ctx = self.make_context( method='POST', data={ 'X-Mailgun-Sscore': message.SSCORE_MAX_VALUE", "web_url_for('conference_results', meeting='studyswap') res = self.app.get(url) assert_equal(res.status_code, 200) class TestConferenceModel(OsfTestCase): def", "AbstractNode from addons.wiki.models import WikiVersion from osf.exceptions import BlacklistedEmailError from", "conference = ConferenceFactory() with self.make_context(data={'from': '<EMAIL>', 'subject': 'It\\'s PARTY TIME!'}):", "'secret'), digestmod=hashlib.sha256, ).hexdigest(), 'attachment-count': '1', 'X-Mailgun-Sscore': 0, 'from': '{0} <{1}>'.format(fullname,", "else '') with self.make_context(data={'recipient': recipient}): self.app.app.preprocess_request() msg = message.ConferenceMessage() assert_equal(msg.conference_name,", "hmac.new( key=settings.MAILGUN_API_KEY, msg='{}{}'.format('123', 'secret'), digestmod=hashlib.sha256, ).hexdigest(), 'attachment-count': '1', 'X-Mailgun-Sscore': 0,", "self.attachment) mock_get_url.assert_called_with( self.node._id, 'osfstorage', _internal=True, base_url=self.node.osfstorage_region.waterbutler_url, cookie=self.user.get_or_create_cookie(), name=file_name ) mock_put.assert_called_with(", "ConferenceFactory() url = web_url_for('conference_results__plain', meeting=conference.endpoint) res = self.app.get(url) assert_equal(res.status_code, 200)", "mock_send_mail.call_args assert_equal(call_args, (username, views.CONFERENCE_INACTIVE)) assert_equal(call_kwargs['fullname'], fullname) assert_equal_urls( call_kwargs['presentations_url'], web_url_for('conference_view', _absolute=True),", "is not None } return self.app.app.test_request_context(method=method, data=data, **kwargs) class TestProvisionNode(ContextTestCase):", ") with ctx: msg = message.ConferenceMessage() assert_equal(msg.subject, 'Hip Hopera') def", "self.make_context( method='POST', data={'X-Mailgun-Spf': message.SPF_PASS_VALUES[0][::-1]}, ) with ctx: msg = message.ConferenceMessage()", "= OSFUser.objects.filter(username=username) assert_equal(users.count(), 1) nodes = AbstractNode.objects.filter(title=title) assert_equal(nodes.count(), 1) node", "Auth from osf.models import OSFUser, AbstractNode from addons.wiki.models import WikiVersion", "with self.make_context(data={'from': '<EMAIL>', 'subject': 'It\\'s PARTY TIME!'}): msg = message.ConferenceMessage()", "self.node.system_tags) def test_provision_spam(self): with self.make_context(data={'X-Mailgun-Sscore': message.SSCORE_MAX_VALUE + 1}): msg =", "cookie=self.user.get_or_create_cookie(), name=file_name ) mock_put.assert_called_with( mock_get_url.return_value, data=self.content, ) @mock.patch('website.conferences.utils.waterbutler_api_url_for') @mock.patch('website.conferences.utils.requests.put') def", "{})) return super(TestProvisionNode, self).make_context(data=data, **kwargs) def test_provision(self): with self.make_context(): msg", "username = '<EMAIL>' with assert_raises(BlacklistedEmailError) as e: get_or_create_user(fullname, username, is_spam=True)", "ctx: msg = message.ConferenceMessage() assert msg.is_spam def test_is_spam_true_dkim(self): ctx =", "{ 'X-Mailgun-Sscore': 0, 'timestamp': '123', 'token': 'secret', 'signature': hmac.new( key=settings.MAILGUN_API_KEY,", "'secret'), digestmod=hashlib.sha256, ).hexdigest(), 'attachment-count': '1', 'X-Mailgun-Sscore': 0, 'from': username, 'recipient':", "= self.app.post( api_url_for('meeting_hook'), { 'X-Mailgun-Sscore': 0, 'timestamp': '123', 'token': 'secret',", "bad project data does not make whole conference break def", "name=fake.company()).save() def test_name_is_required(self): with assert_raises(IntegrityError): ConferenceFactory(endpoint='spsp2014', name=None).save() def test_default_field_names(self): conf", "message.SSCORE_MAX_VALUE - 1}, ) with ctx: msg = message.ConferenceMessage() assert", "fetched, created = get_or_create_user(fullname, username, is_spam=False) fetched.save() # in order", "(u'<EMAIL>', u'<EMAIL>'), (u'<EMAIL>', u'<EMAIL>') ] for email in emails: with", "assert_equal(parsed_domain.host, parsed_url.host) def assert_equal_urls(first, second): parsed_first = furl.furl(first) parsed_first.port =", "message.ConferenceMessage() assert_equal(msg.conference_name, 'conf') assert_equal(msg.conference_category, 'poster') def test_alternate_route_invalid(self): recipient = '{0}<EMAIL>'.format('test-'", "False def test_verify_signature_valid(self): with self.make_context(): msg = message.ConferenceMessage() msg.verify_signature() def", ") mock_put.assert_called_with( mock_get_url.return_value, data=self.content, ) @mock.patch('website.conferences.utils.upload_attachments') def test_add_poster_by_email(self, mock_upload_attachments): conference", "content), ], ) assert_true(mock_upload.called) users = OSFUser.objects.filter(username=username) assert_equal(users.count(), 1) nodes", "= 'dragon on my back' content = 'dragon attack' recipient", ") assert AbstractNode.objects.filter(title=title, creator=user).count() == 2 assert mock_upload.called assert mock_send_mail.called", "= get_or_create_user(fullname, username, is_spam=True) fetched.save() # in order to access", "**kwargs): data = { 'attachment-count': '1', 'attachment-1': (self.attachment, 'attachment-1'), 'X-Mailgun-Sscore':", "self.app.get(url) assert_equal(res.status_code, 200) def test_confererence_results_endpoint_is_case_insensitive(self): ConferenceFactory(endpoint='StudySwap') url = web_url_for('conference_results', meeting='studyswap')", "Private node added private_node = ProjectFactory(is_public=False) conf.submissions.add(private_node) assert_equal(conf.submissions.count(), 5) assert_equal(conf.valid_submissions.count(),", "= self.app.get(url) assert_equal(res.status_code, 200) def test_confererence_results_endpoint_is_case_insensitive(self): ConferenceFactory(endpoint='StudySwap') url = web_url_for('conference_results',", "= furl.furl(second) parsed_second.port = None assert_equal(parsed_first, parsed_second) def create_fake_conference_nodes(n, conference):", "import * # noqa (PEP8 asserts) import hmac import hashlib" ]
[ "class SendHandler(Handler): filemode = \"w\" class Server(object): def __init__(self, handlers):", "SendHandler(Handler): filemode = \"w\" class Server(object): def __init__(self, handlers): self.handlers", "key in to_destroy: server = self.servers.pop(key) server.stop() def connection_key(self, connection):", "import socketserver import socket import sys import threading import json", "sock.connect((self._kwargs[\"host\"], self._kwargs[\"port\"])) print(\"Connector: Connected: %s\" % self._kwargs) self._kwargs[\"handler\"](self._kwargs[\"server\"], sock) except", "= config connections = {self.connection_key(connection): connection for connection in config[\"connections\"]}", "{\"listen\": Listener, \"connect\": Connector}[connection[\"type\"]] return connhandler(kwargs={\"server\": self, \"host\": host, \"port\":", "\"port\": port, \"handler\": handler}) def run(config, handlers): server = Server(handlers)", "for key in to_destroy: server = self.servers.pop(key) server.stop() def connection_key(self,", "sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: try: sock.connect((self._kwargs[\"host\"], self._kwargs[\"port\"])) print(\"Connector: Connected:", "= self.servers.keys() - connections.keys() for key in to_create: server =", "socketserver import socket import sys import threading import json import", "%s\" % self._kwargs) self._kwargs[\"handler\"](self._kwargs[\"server\"], sock) except Exception as e: print(e)", "wrapper for that socket\"\"\" def __hash__(self): return id(self) class ReceiveHandler(Handler):", "connections = {self.connection_key(connection): connection for connection in config[\"connections\"]} to_create =", "connhandler(kwargs={\"server\": self, \"host\": host, \"port\": port, \"handler\": handler}) def run(config,", "binary = False filemode = \"r\" def __init__(self, server, conn):", "= conn self.makefile() self.handle() def makefile(self): args = {\"mode\": self.filemode", "TCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer): def server_bind(self): self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.socket.bind(self.server_address) class Listener(threading.Thread):", "self.file a file wrapper for that socket\"\"\" def __hash__(self): return", "None self.servers = {} def configure(self, config): self.config = config", "def configure(self, config): self.config = config connections = {self.connection_key(connection): connection", "server = self.servers.pop(key) server.stop() def connection_key(self, connection): return json.dumps(connection, sort_keys=True,", "\"tcp\" host = \"0.0.0.0\" port = 1024 if len(addr) ==", "if len(addr) == 3: host, port = addr[1:] port =", "self.server.server_close() class Connector(threading.Thread): def __init__(self, *arg, **kw): self.is_stopping = False", "server = self.start_connection(connections[key]) server.start() self.servers[key] = server for key in", "self.filemode + [\"\", \"b\"][self.binary]} if not self.binary: args[\"encoding\"] = self.encoding", "id(self) class ReceiveHandler(Handler): filemode = \"r\" class SendHandler(Handler): filemode =", "self.is_stopping = True class Handler(object): encoding = \"utf-8\" binary =", "= self.servers.pop(key) server.stop() def connection_key(self, connection): return json.dumps(connection, sort_keys=True, separators=(',',", "args[\"encoding\"] = self.encoding self.file = self.conn.makefile(**args) def handle(self): \"\"\"self.conn is", "**kw) def run(self): print(\"Connector: Started: %s\" % self._kwargs) while not", "False filemode = \"r\" def __init__(self, server, conn): self.server =", "{\"mode\": self.filemode + [\"\", \"b\"][self.binary]} if not self.binary: args[\"encoding\"] =", "Server(object): def __init__(self, handlers): self.handlers = handlers self.config = None", "self.file = self.conn.makefile(**args) def handle(self): \"\"\"self.conn is a socket object,", "connection in config[\"connections\"]} to_create = connections.keys() - self.servers.keys() to_destroy =", "socketserver.TCPServer): def server_bind(self): self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.socket.bind(self.server_address) class Listener(threading.Thread): def", "self.encoding self.file = self.conn.makefile(**args) def handle(self): \"\"\"self.conn is a socket", "connections.keys() for key in to_create: server = self.start_connection(connections[key]) server.start() self.servers[key]", "handler = self.handlers[connection[\"handler\"]] addr = connection[\"address\"].split(\":\") assert addr[0] == \"tcp\"", "= 1024 if len(addr) == 2: port = addr[1] if", "kwargs[\"port\"]), Server) self.server.serve_forever() def stop(self): self.server.shutdown() self.server.server_close() class Connector(threading.Thread): def", "self.is_stopping: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: try: sock.connect((self._kwargs[\"host\"], self._kwargs[\"port\"])) print(\"Connector:", "self.conn.makefile(**args) def handle(self): \"\"\"self.conn is a socket object, self.file a", "is a socket object, self.file a file wrapper for that", "start_connection(self, connection): handler = self.handlers[connection[\"handler\"]] addr = connection[\"address\"].split(\":\") assert addr[0]", "\"handler\": handler}) def run(config, handlers): server = Server(handlers) server.configure(config) return", "kwargs) Handler(server, self.request) self.server = TCPServer((kwargs[\"host\"], kwargs[\"port\"]), Server) self.server.serve_forever() def", "sys import threading import json import queue import time import", "import socket import sys import threading import json import queue", "\"0.0.0.0\" port = 1024 if len(addr) == 2: port =", "= server self.conn = conn self.makefile() self.handle() def makefile(self): args", "Exception as e: print(e) traceback.print_exc() finally: sock.close() time.sleep(1) def stop(self):", "self.handle() def makefile(self): args = {\"mode\": self.filemode + [\"\", \"b\"][self.binary]}", "% self._kwargs) while not self.is_stopping: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try:", "for connection in config[\"connections\"]} to_create = connections.keys() - self.servers.keys() to_destroy", "self.servers.pop(key) server.stop() def connection_key(self, connection): return json.dumps(connection, sort_keys=True, separators=(',', ':'))", "assert addr[0] == \"tcp\" host = \"0.0.0.0\" port = 1024", "to_create = connections.keys() - self.servers.keys() to_destroy = self.servers.keys() - connections.keys()", "server = self._kwargs[\"server\"] class Server(socketserver.BaseRequestHandler): def handle(self): print(\"Listener: Connection request", "port, \"handler\": handler}) def run(config, handlers): server = Server(handlers) server.configure(config)", "def __hash__(self): return id(self) class ReceiveHandler(Handler): filemode = \"r\" class", "= False threading.Thread.__init__(self, *arg, **kw) def run(self): print(\"Connector: Started: %s\"", "as e: print(e) traceback.print_exc() finally: sock.close() time.sleep(1) def stop(self): self.is_stopping", "socket.SO_REUSEADDR, 1) self.socket.bind(self.server_address) class Listener(threading.Thread): def run(self): kwargs = self._kwargs", "addr[1] if len(addr) == 3: host, port = addr[1:] port", "self.server = TCPServer((kwargs[\"host\"], kwargs[\"port\"]), Server) self.server.serve_forever() def stop(self): self.server.shutdown() self.server.server_close()", "filemode = \"w\" class Server(object): def __init__(self, handlers): self.handlers =", "= \"w\" class Server(object): def __init__(self, handlers): self.handlers = handlers", "= self._kwargs print(\"Listener: Started: %s\" % kwargs) Handler = self._kwargs[\"handler\"]", "connection[\"address\"].split(\":\") assert addr[0] == \"tcp\" host = \"0.0.0.0\" port =", "== 2: port = addr[1] if len(addr) == 3: host,", "Connector(threading.Thread): def __init__(self, *arg, **kw): self.is_stopping = False threading.Thread.__init__(self, *arg,", "def server_bind(self): self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.socket.bind(self.server_address) class Listener(threading.Thread): def run(self):", "= {\"mode\": self.filemode + [\"\", \"b\"][self.binary]} if not self.binary: args[\"encoding\"]", "len(addr) == 3: host, port = addr[1:] port = int(port)", "import time import datetime import traceback class TCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer): def", "except Exception as e: print(e) traceback.print_exc() finally: sock.close() time.sleep(1) def", "= server for key in to_destroy: server = self.servers.pop(key) server.stop()", "addr = connection[\"address\"].split(\":\") assert addr[0] == \"tcp\" host = \"0.0.0.0\"", "in to_destroy: server = self.servers.pop(key) server.stop() def connection_key(self, connection): return", "__hash__(self): return id(self) class ReceiveHandler(Handler): filemode = \"r\" class SendHandler(Handler):", "self.start_connection(connections[key]) server.start() self.servers[key] = server for key in to_destroy: server", "2: port = addr[1] if len(addr) == 3: host, port", "class Connector(threading.Thread): def __init__(self, *arg, **kw): self.is_stopping = False threading.Thread.__init__(self,", "\"r\" class SendHandler(Handler): filemode = \"w\" class Server(object): def __init__(self,", "print(\"Listener: Started: %s\" % kwargs) Handler = self._kwargs[\"handler\"] server =", "= self.encoding self.file = self.conn.makefile(**args) def handle(self): \"\"\"self.conn is a", "handler}) def run(config, handlers): server = Server(handlers) server.configure(config) return server", "\"b\"][self.binary]} if not self.binary: args[\"encoding\"] = self.encoding self.file = self.conn.makefile(**args)", "datetime import traceback class TCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer): def server_bind(self): self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,", "for key in to_create: server = self.start_connection(connections[key]) server.start() self.servers[key] =", "makefile(self): args = {\"mode\": self.filemode + [\"\", \"b\"][self.binary]} if not", "self._kwargs[\"handler\"] server = self._kwargs[\"server\"] class Server(socketserver.BaseRequestHandler): def handle(self): print(\"Listener: Connection", "print(\"Connector: Started: %s\" % self._kwargs) while not self.is_stopping: sock =", "self.config = config connections = {self.connection_key(connection): connection for connection in", "def handle(self): \"\"\"self.conn is a socket object, self.file a file", "= addr[1:] port = int(port) connhandler = {\"listen\": Listener, \"connect\":", "= {\"listen\": Listener, \"connect\": Connector}[connection[\"type\"]] return connhandler(kwargs={\"server\": self, \"host\": host,", "filemode = \"r\" def __init__(self, server, conn): self.server = server", "return json.dumps(connection, sort_keys=True, separators=(',', ':')) def start_connection(self, connection): handler =", "self._kwargs print(\"Listener: Started: %s\" % kwargs) Handler = self._kwargs[\"handler\"] server", "__init__(self, *arg, **kw): self.is_stopping = False threading.Thread.__init__(self, *arg, **kw) def", "handlers self.config = None self.servers = {} def configure(self, config):", "sort_keys=True, separators=(',', ':')) def start_connection(self, connection): handler = self.handlers[connection[\"handler\"]] addr", "[\"\", \"b\"][self.binary]} if not self.binary: args[\"encoding\"] = self.encoding self.file =", "ReceiveHandler(Handler): filemode = \"r\" class SendHandler(Handler): filemode = \"w\" class", "server self.conn = conn self.makefile() self.handle() def makefile(self): args =", "stop(self): self.is_stopping = True class Handler(object): encoding = \"utf-8\" binary", "config[\"connections\"]} to_create = connections.keys() - self.servers.keys() to_destroy = self.servers.keys() -", "= handlers self.config = None self.servers = {} def configure(self,", "stop(self): self.server.shutdown() self.server.server_close() class Connector(threading.Thread): def __init__(self, *arg, **kw): self.is_stopping", "server.stop() def connection_key(self, connection): return json.dumps(connection, sort_keys=True, separators=(',', ':')) def", "def run(self): print(\"Connector: Started: %s\" % self._kwargs) while not self.is_stopping:", "port = int(port) connhandler = {\"listen\": Listener, \"connect\": Connector}[connection[\"type\"]] return", "conn self.makefile() self.handle() def makefile(self): args = {\"mode\": self.filemode +", "Connector}[connection[\"type\"]] return connhandler(kwargs={\"server\": self, \"host\": host, \"port\": port, \"handler\": handler})", "a socket object, self.file a file wrapper for that socket\"\"\"", "Server(socketserver.BaseRequestHandler): def handle(self): print(\"Listener: Connection request received: %s\" % kwargs)", "to_destroy = self.servers.keys() - connections.keys() for key in to_create: server", "in config[\"connections\"]} to_create = connections.keys() - self.servers.keys() to_destroy = self.servers.keys()", "Server) self.server.serve_forever() def stop(self): self.server.shutdown() self.server.server_close() class Connector(threading.Thread): def __init__(self,", "host = \"0.0.0.0\" port = 1024 if len(addr) == 2:", "run(self): print(\"Connector: Started: %s\" % self._kwargs) while not self.is_stopping: sock", "finally: sock.close() time.sleep(1) def stop(self): self.is_stopping = True class Handler(object):", "run(self): kwargs = self._kwargs print(\"Listener: Started: %s\" % kwargs) Handler", "a file wrapper for that socket\"\"\" def __hash__(self): return id(self)", "filemode = \"r\" class SendHandler(Handler): filemode = \"w\" class Server(object):", "\"w\" class Server(object): def __init__(self, handlers): self.handlers = handlers self.config", "import threading import json import queue import time import datetime", "print(\"Connector: Connected: %s\" % self._kwargs) self._kwargs[\"handler\"](self._kwargs[\"server\"], sock) except Exception as", "handle(self): \"\"\"self.conn is a socket object, self.file a file wrapper", "%s\" % kwargs) Handler = self._kwargs[\"handler\"] server = self._kwargs[\"server\"] class", "not self.binary: args[\"encoding\"] = self.encoding self.file = self.conn.makefile(**args) def handle(self):", "import datetime import traceback class TCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer): def server_bind(self): self.socket.setsockopt(socket.SOL_SOCKET,", "self.servers.keys() to_destroy = self.servers.keys() - connections.keys() for key in to_create:", "self._kwargs[\"server\"] class Server(socketserver.BaseRequestHandler): def handle(self): print(\"Listener: Connection request received: %s\"", "json import queue import time import datetime import traceback class", "= addr[1] if len(addr) == 3: host, port = addr[1:]", "self._kwargs) while not self.is_stopping: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: try:", "try: sock.connect((self._kwargs[\"host\"], self._kwargs[\"port\"])) print(\"Connector: Connected: %s\" % self._kwargs) self._kwargs[\"handler\"](self._kwargs[\"server\"], sock)", "def __init__(self, server, conn): self.server = server self.conn = conn", "\"utf-8\" binary = False filemode = \"r\" def __init__(self, server,", "def makefile(self): args = {\"mode\": self.filemode + [\"\", \"b\"][self.binary]} if", "connections.keys() - self.servers.keys() to_destroy = self.servers.keys() - connections.keys() for key", "- self.servers.keys() to_destroy = self.servers.keys() - connections.keys() for key in", "Connection request received: %s\" % kwargs) Handler(server, self.request) self.server =", "%s\" % kwargs) Handler(server, self.request) self.server = TCPServer((kwargs[\"host\"], kwargs[\"port\"]), Server)", "object, self.file a file wrapper for that socket\"\"\" def __hash__(self):", "% kwargs) Handler = self._kwargs[\"handler\"] server = self._kwargs[\"server\"] class Server(socketserver.BaseRequestHandler):", "server.start() self.servers[key] = server for key in to_destroy: server =", "= self.handlers[connection[\"handler\"]] addr = connection[\"address\"].split(\":\") assert addr[0] == \"tcp\" host", "% kwargs) Handler(server, self.request) self.server = TCPServer((kwargs[\"host\"], kwargs[\"port\"]), Server) self.server.serve_forever()", "sock) except Exception as e: print(e) traceback.print_exc() finally: sock.close() time.sleep(1)", "self.servers.keys() - connections.keys() for key in to_create: server = self.start_connection(connections[key])", "= self.conn.makefile(**args) def handle(self): \"\"\"self.conn is a socket object, self.file", "received: %s\" % kwargs) Handler(server, self.request) self.server = TCPServer((kwargs[\"host\"], kwargs[\"port\"]),", "class TCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer): def server_bind(self): self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.socket.bind(self.server_address) class", "\"\"\"self.conn is a socket object, self.file a file wrapper for", "threading import json import queue import time import datetime import", "self.handlers[connection[\"handler\"]] addr = connection[\"address\"].split(\":\") assert addr[0] == \"tcp\" host =", "*arg, **kw) def run(self): print(\"Connector: Started: %s\" % self._kwargs) while", "request received: %s\" % kwargs) Handler(server, self.request) self.server = TCPServer((kwargs[\"host\"],", "connection): handler = self.handlers[connection[\"handler\"]] addr = connection[\"address\"].split(\":\") assert addr[0] ==", "{} def configure(self, config): self.config = config connections = {self.connection_key(connection):", "self.makefile() self.handle() def makefile(self): args = {\"mode\": self.filemode + [\"\",", "to_create: server = self.start_connection(connections[key]) server.start() self.servers[key] = server for key", "self.is_stopping = False threading.Thread.__init__(self, *arg, **kw) def run(self): print(\"Connector: Started:", "queue import time import datetime import traceback class TCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):", "addr[0] == \"tcp\" host = \"0.0.0.0\" port = 1024 if", "def __init__(self, *arg, **kw): self.is_stopping = False threading.Thread.__init__(self, *arg, **kw)", "self.handlers = handlers self.config = None self.servers = {} def", "self.server = server self.conn = conn self.makefile() self.handle() def makefile(self):", "def stop(self): self.server.shutdown() self.server.server_close() class Connector(threading.Thread): def __init__(self, *arg, **kw):", "server, conn): self.server = server self.conn = conn self.makefile() self.handle()", "server_bind(self): self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.socket.bind(self.server_address) class Listener(threading.Thread): def run(self): kwargs", "= connections.keys() - self.servers.keys() to_destroy = self.servers.keys() - connections.keys() for", "False threading.Thread.__init__(self, *arg, **kw) def run(self): print(\"Connector: Started: %s\" %", "encoding = \"utf-8\" binary = False filemode = \"r\" def", "**kw): self.is_stopping = False threading.Thread.__init__(self, *arg, **kw) def run(self): print(\"Connector:", "+ [\"\", \"b\"][self.binary]} if not self.binary: args[\"encoding\"] = self.encoding self.file", "':')) def start_connection(self, connection): handler = self.handlers[connection[\"handler\"]] addr = connection[\"address\"].split(\":\")", "not self.is_stopping: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: try: sock.connect((self._kwargs[\"host\"], self._kwargs[\"port\"]))", "Listener, \"connect\": Connector}[connection[\"type\"]] return connhandler(kwargs={\"server\": self, \"host\": host, \"port\": port,", "import queue import time import datetime import traceback class TCPServer(socketserver.ThreadingMixIn,", "port = 1024 if len(addr) == 2: port = addr[1]", "Handler = self._kwargs[\"handler\"] server = self._kwargs[\"server\"] class Server(socketserver.BaseRequestHandler): def handle(self):", "= socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: try: sock.connect((self._kwargs[\"host\"], self._kwargs[\"port\"])) print(\"Connector: Connected: %s\"", "def __init__(self, handlers): self.handlers = handlers self.config = None self.servers", "handlers): self.handlers = handlers self.config = None self.servers = {}", "__init__(self, server, conn): self.server = server self.conn = conn self.makefile()", "in to_create: server = self.start_connection(connections[key]) server.start() self.servers[key] = server for", "separators=(',', ':')) def start_connection(self, connection): handler = self.handlers[connection[\"handler\"]] addr =", "if not self.binary: args[\"encoding\"] = self.encoding self.file = self.conn.makefile(**args) def", "addr[1:] port = int(port) connhandler = {\"listen\": Listener, \"connect\": Connector}[connection[\"type\"]]", "connection_key(self, connection): return json.dumps(connection, sort_keys=True, separators=(',', ':')) def start_connection(self, connection):", "print(e) traceback.print_exc() finally: sock.close() time.sleep(1) def stop(self): self.is_stopping = True", "class Listener(threading.Thread): def run(self): kwargs = self._kwargs print(\"Listener: Started: %s\"", "Handler(object): encoding = \"utf-8\" binary = False filemode = \"r\"", "self.server.serve_forever() def stop(self): self.server.shutdown() self.server.server_close() class Connector(threading.Thread): def __init__(self, *arg,", "traceback.print_exc() finally: sock.close() time.sleep(1) def stop(self): self.is_stopping = True class", "import json import queue import time import datetime import traceback", "that socket\"\"\" def __hash__(self): return id(self) class ReceiveHandler(Handler): filemode =", "\"host\": host, \"port\": port, \"handler\": handler}) def run(config, handlers): server", "time.sleep(1) def stop(self): self.is_stopping = True class Handler(object): encoding =", "= {} def configure(self, config): self.config = config connections =", "Listener(threading.Thread): def run(self): kwargs = self._kwargs print(\"Listener: Started: %s\" %", "e: print(e) traceback.print_exc() finally: sock.close() time.sleep(1) def stop(self): self.is_stopping =", "class Handler(object): encoding = \"utf-8\" binary = False filemode =", "= connection[\"address\"].split(\":\") assert addr[0] == \"tcp\" host = \"0.0.0.0\" port", "time import datetime import traceback class TCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer): def server_bind(self):", "TCPServer((kwargs[\"host\"], kwargs[\"port\"]), Server) self.server.serve_forever() def stop(self): self.server.shutdown() self.server.server_close() class Connector(threading.Thread):", "host, port = addr[1:] port = int(port) connhandler = {\"listen\":", "= {self.connection_key(connection): connection for connection in config[\"connections\"]} to_create = connections.keys()", "self.request) self.server = TCPServer((kwargs[\"host\"], kwargs[\"port\"]), Server) self.server.serve_forever() def stop(self): self.server.shutdown()", "Started: %s\" % self._kwargs) while not self.is_stopping: sock = socket.socket(socket.AF_INET,", "while not self.is_stopping: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: try: sock.connect((self._kwargs[\"host\"],", "socket.SOCK_STREAM) try: try: sock.connect((self._kwargs[\"host\"], self._kwargs[\"port\"])) print(\"Connector: Connected: %s\" % self._kwargs)", "= False filemode = \"r\" def __init__(self, server, conn): self.server", "__init__(self, handlers): self.handlers = handlers self.config = None self.servers =", "configure(self, config): self.config = config connections = {self.connection_key(connection): connection for", "= \"r\" def __init__(self, server, conn): self.server = server self.conn", "= True class Handler(object): encoding = \"utf-8\" binary = False", "\"connect\": Connector}[connection[\"type\"]] return connhandler(kwargs={\"server\": self, \"host\": host, \"port\": port, \"handler\":", "self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.socket.bind(self.server_address) class Listener(threading.Thread): def run(self): kwargs =", "args = {\"mode\": self.filemode + [\"\", \"b\"][self.binary]} if not self.binary:", "== \"tcp\" host = \"0.0.0.0\" port = 1024 if len(addr)", "socket object, self.file a file wrapper for that socket\"\"\" def", "return connhandler(kwargs={\"server\": self, \"host\": host, \"port\": port, \"handler\": handler}) def", "self, \"host\": host, \"port\": port, \"handler\": handler}) def run(config, handlers):", "class Server(socketserver.BaseRequestHandler): def handle(self): print(\"Listener: Connection request received: %s\" %", "print(\"Listener: Connection request received: %s\" % kwargs) Handler(server, self.request) self.server", "def run(self): kwargs = self._kwargs print(\"Listener: Started: %s\" % kwargs)", "socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: try: sock.connect((self._kwargs[\"host\"], self._kwargs[\"port\"])) print(\"Connector: Connected: %s\" %", "{self.connection_key(connection): connection for connection in config[\"connections\"]} to_create = connections.keys() -", "server for key in to_destroy: server = self.servers.pop(key) server.stop() def", "True class Handler(object): encoding = \"utf-8\" binary = False filemode", "= self._kwargs[\"server\"] class Server(socketserver.BaseRequestHandler): def handle(self): print(\"Listener: Connection request received:", "= TCPServer((kwargs[\"host\"], kwargs[\"port\"]), Server) self.server.serve_forever() def stop(self): self.server.shutdown() self.server.server_close() class", "% self._kwargs) self._kwargs[\"handler\"](self._kwargs[\"server\"], sock) except Exception as e: print(e) traceback.print_exc()", "Started: %s\" % kwargs) Handler = self._kwargs[\"handler\"] server = self._kwargs[\"server\"]", "= \"r\" class SendHandler(Handler): filemode = \"w\" class Server(object): def", "def connection_key(self, connection): return json.dumps(connection, sort_keys=True, separators=(',', ':')) def start_connection(self,", "class Server(object): def __init__(self, handlers): self.handlers = handlers self.config =", "Handler(server, self.request) self.server = TCPServer((kwargs[\"host\"], kwargs[\"port\"]), Server) self.server.serve_forever() def stop(self):", "- connections.keys() for key in to_create: server = self.start_connection(connections[key]) server.start()", "= int(port) connhandler = {\"listen\": Listener, \"connect\": Connector}[connection[\"type\"]] return connhandler(kwargs={\"server\":", "self.conn = conn self.makefile() self.handle() def makefile(self): args = {\"mode\":", "kwargs = self._kwargs print(\"Listener: Started: %s\" % kwargs) Handler =", "self.servers = {} def configure(self, config): self.config = config connections", "to_destroy: server = self.servers.pop(key) server.stop() def connection_key(self, connection): return json.dumps(connection,", "conn): self.server = server self.conn = conn self.makefile() self.handle() def", "for that socket\"\"\" def __hash__(self): return id(self) class ReceiveHandler(Handler): filemode", "config connections = {self.connection_key(connection): connection for connection in config[\"connections\"]} to_create", "self.servers[key] = server for key in to_destroy: server = self.servers.pop(key)", "self.binary: args[\"encoding\"] = self.encoding self.file = self.conn.makefile(**args) def handle(self): \"\"\"self.conn", "self._kwargs[\"handler\"](self._kwargs[\"server\"], sock) except Exception as e: print(e) traceback.print_exc() finally: sock.close()", "int(port) connhandler = {\"listen\": Listener, \"connect\": Connector}[connection[\"type\"]] return connhandler(kwargs={\"server\": self,", "key in to_create: server = self.start_connection(connections[key]) server.start() self.servers[key] = server", "1) self.socket.bind(self.server_address) class Listener(threading.Thread): def run(self): kwargs = self._kwargs print(\"Listener:", "*arg, **kw): self.is_stopping = False threading.Thread.__init__(self, *arg, **kw) def run(self):", "traceback class TCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer): def server_bind(self): self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.socket.bind(self.server_address)", "= self.start_connection(connections[key]) server.start() self.servers[key] = server for key in to_destroy:", "try: try: sock.connect((self._kwargs[\"host\"], self._kwargs[\"port\"])) print(\"Connector: Connected: %s\" % self._kwargs) self._kwargs[\"handler\"](self._kwargs[\"server\"],", "self._kwargs) self._kwargs[\"handler\"](self._kwargs[\"server\"], sock) except Exception as e: print(e) traceback.print_exc() finally:", "\"r\" def __init__(self, server, conn): self.server = server self.conn =", "Connected: %s\" % self._kwargs) self._kwargs[\"handler\"](self._kwargs[\"server\"], sock) except Exception as e:", "def stop(self): self.is_stopping = True class Handler(object): encoding = \"utf-8\"", "config): self.config = config connections = {self.connection_key(connection): connection for connection", "= self._kwargs[\"handler\"] server = self._kwargs[\"server\"] class Server(socketserver.BaseRequestHandler): def handle(self): print(\"Listener:", "import traceback class TCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer): def server_bind(self): self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)", "def handle(self): print(\"Listener: Connection request received: %s\" % kwargs) Handler(server,", "file wrapper for that socket\"\"\" def __hash__(self): return id(self) class", "class ReceiveHandler(Handler): filemode = \"r\" class SendHandler(Handler): filemode = \"w\"", "import sys import threading import json import queue import time", "threading.Thread.__init__(self, *arg, **kw) def run(self): print(\"Connector: Started: %s\" % self._kwargs)", "self.server.shutdown() self.server.server_close() class Connector(threading.Thread): def __init__(self, *arg, **kw): self.is_stopping =", "port = addr[1:] port = int(port) connhandler = {\"listen\": Listener,", "self.socket.bind(self.server_address) class Listener(threading.Thread): def run(self): kwargs = self._kwargs print(\"Listener: Started:", "def start_connection(self, connection): handler = self.handlers[connection[\"handler\"]] addr = connection[\"address\"].split(\":\") assert", "= None self.servers = {} def configure(self, config): self.config =", "1024 if len(addr) == 2: port = addr[1] if len(addr)", "port = addr[1] if len(addr) == 3: host, port =", "connection for connection in config[\"connections\"]} to_create = connections.keys() - self.servers.keys()", "%s\" % self._kwargs) while not self.is_stopping: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)", "if len(addr) == 2: port = addr[1] if len(addr) ==", "== 3: host, port = addr[1:] port = int(port) connhandler", "kwargs) Handler = self._kwargs[\"handler\"] server = self._kwargs[\"server\"] class Server(socketserver.BaseRequestHandler): def", "host, \"port\": port, \"handler\": handler}) def run(config, handlers): server =", "socket import sys import threading import json import queue import", "handle(self): print(\"Listener: Connection request received: %s\" % kwargs) Handler(server, self.request)", "self.config = None self.servers = {} def configure(self, config): self.config", "len(addr) == 2: port = addr[1] if len(addr) == 3:", "sock.close() time.sleep(1) def stop(self): self.is_stopping = True class Handler(object): encoding", "json.dumps(connection, sort_keys=True, separators=(',', ':')) def start_connection(self, connection): handler = self.handlers[connection[\"handler\"]]", "socket\"\"\" def __hash__(self): return id(self) class ReceiveHandler(Handler): filemode = \"r\"", "connhandler = {\"listen\": Listener, \"connect\": Connector}[connection[\"type\"]] return connhandler(kwargs={\"server\": self, \"host\":", "return id(self) class ReceiveHandler(Handler): filemode = \"r\" class SendHandler(Handler): filemode", "3: host, port = addr[1:] port = int(port) connhandler =", "connection): return json.dumps(connection, sort_keys=True, separators=(',', ':')) def start_connection(self, connection): handler", "self._kwargs[\"port\"])) print(\"Connector: Connected: %s\" % self._kwargs) self._kwargs[\"handler\"](self._kwargs[\"server\"], sock) except Exception", "= \"0.0.0.0\" port = 1024 if len(addr) == 2: port", "= \"utf-8\" binary = False filemode = \"r\" def __init__(self," ]
[ "binary char\") if currName == \"\": break name.append(currName) mmax.append( data[OnOffstart", "#print(\"increment params\") numParameters = numParameters + 1 except: pass #print(\"Found", "+ 1 except: pass #print(\"Found {} parameters.\".format(numParameters)) tD['Parameters'] = []", "!= -1: fxName=\"\" OnOffblockSize = 0x30 for j in range(12):", "1 is the name # so actual paramters start from", "[] name = [] mpedal = [] numParameters = 0", "= fxName + chr(data[OnOffstart + j + OnOffblockSize]) tD =", "i in range(numParameters - 2): #print(i) tD['Parameters'].append({'name': name[i+2], 'mmax': mmax[i", "} mmax = [] mdefault = [] name = []", "OnOffblockSize + 1]), hex(data[OnOffstart + (j+1) * OnOffblockSize + 2]),", "+ j * OnOffblockSize + i] == 0x00: break currName", "* OnOffblockSize - 1] == 0x00 and data[OnOffstart + (j+1)", "13] * 256) mdefault.append(data[OnOffstart + j * OnOffblockSize + 16]", ") \"\"\" #print(\"increment params\") numParameters = numParameters + 1 except:", "format has a length and PRME offset. ZDL has none", "(j+1) * OnOffblockSize + 2]), hex(data[OnOffstart + (j+1) * OnOffblockSize", "#print(\"OnOffStart at {}\".format(OnOffstart)) try: # this is WAY too large,", "and data[OnOffstart + (j+1) * OnOffblockSize - 2] == 0x00):", "+ (j+1) * OnOffblockSize - 1] == 0x00 and data[OnOffstart", "#print(mdefault[j]) \"\"\" print(\"[{}] {} {} {} {}\".format( OnOffstart + (j+1)", "if not ( data[OnOffstart + (j+1) * OnOffblockSize - 1]", "len(sys.argv) == 2: f = open(sys.argv[1], \"rb\") data = f.read()", "char\") if currName == \"\": break name.append(currName) mmax.append( data[OnOffstart +", "OnOffblockSize + 12] + data[OnOffstart + j * OnOffblockSize +", "index 2, but clearly there are 2 less for i", "j + OnOffblockSize] == 0x00: break fxName = fxName +", "name = [] mpedal = [] numParameters = 0 #print(\"OnOffStart", "sys import json def check(data): OnOffstart = data.find(b\"OnOff\") if OnOffstart", "\"\"\" print(\"[{}] {} {} {} {}\".format( OnOffstart + (j+1) *", "a zoom firmware if __name__ == \"__main__\": if len(sys.argv) ==", "+ 3])) ) \"\"\" #print(\"increment params\") numParameters = numParameters +", "+ i]) if data[OnOffstart + j * OnOffblockSize + i]", "* OnOffblockSize + i] == 0x00: break currName = currName", "(j+1) * OnOffblockSize - 1] == 0x00 and data[OnOffstart +", "= numParameters + 1 except: pass #print(\"Found {} parameters.\".format(numParameters)) tD['Parameters']", "is the name # so actual paramters start from index", "import sys import json def check(data): OnOffstart = data.find(b\"OnOff\") if", "if data[OnOffstart + j + OnOffblockSize] == 0x00: break fxName", "data[OnOffstart + j * OnOffblockSize + i] & 0x80: raise", "break name.append(currName) mmax.append( data[OnOffstart + j * OnOffblockSize + 12]", "hex(data[OnOffstart + (j+1) * OnOffblockSize + 3])) ) \"\"\" #print(\"increment", "j * OnOffblockSize + 12] + data[OnOffstart + j *", "(j+1) * OnOffblockSize, hex(data[OnOffstart + (j+1) * OnOffblockSize]), hex(data[OnOffstart +", "OnOffblockSize + 0x18 ] == 0x00 and data[OnOffstart + (j)", "j * OnOffblockSize + 16] + data[OnOffstart + j *", "data[OnOffstart + (j+1) * OnOffblockSize - 1] == 0x00 and", "numParameters + 1 except: pass #print(\"Found {} parameters.\".format(numParameters)) tD['Parameters'] =", "return fxName+'.OnOff' # handles a zoom firmware if __name__ ==", "'mdefault': mdefault[i + 2], 'pedal': mpedal[i+2]}) #json.dump(tD, sys.stdout, indent=4) f", "def check(data): OnOffstart = data.find(b\"OnOff\") if OnOffstart != -1: fxName=\"\"", "== 0x00 ): print(\"Empty next slot\") break \"\"\" currName =", "of the parameters\") break; if not ( data[OnOffstart + (j)", "is the OnOff state # 1 is the name #", "] == 0x00 and data[OnOffstart + (j) * OnOffblockSize +", "(j) * OnOffblockSize + 0x18 ] == 0x00 and data[OnOffstart", "* OnOffblockSize, hex(data[OnOffstart + (j+1) * OnOffblockSize]), hex(data[OnOffstart + (j+1)", "length and PRME offset. ZDL has none of this. print(\"End", "+ j + OnOffblockSize] == 0x00: break fxName = fxName", "* OnOffblockSize + 2]), hex(data[OnOffstart + (j+1) * OnOffblockSize +", "+ data[OnOffstart + j * OnOffblockSize + 13] * 256)", "but clearly there are 2 less for i in range(numParameters", "j * OnOffblockSize + 17] * 256); if data[OnOffstart +", "PRME offset. ZDL has none of this. print(\"End of the", "less for i in range(numParameters - 2): #print(i) tD['Parameters'].append({'name': name[i+2],", "fxName = fxName + chr(data[OnOffstart + j + OnOffblockSize]) tD", "= [] mdefault = [] name = [] mpedal =", "+ 2], 'mdefault': mdefault[i + 2], 'pedal': mpedal[i+2]}) #json.dump(tD, sys.stdout,", "data[OnOffstart + j + OnOffblockSize] == 0x00: break fxName =", "the OnOff state # 1 is the name # so", "in range(numParameters - 2): #print(i) tD['Parameters'].append({'name': name[i+2], 'mmax': mmax[i +", "for j in range(12): if data[OnOffstart + j + OnOffblockSize]", "* OnOffblockSize + 0x19] == 0x00 and data[OnOffstart + (j)", "mmax[i + 2], 'mdefault': mdefault[i + 2], 'pedal': mpedal[i+2]}) #json.dump(tD,", "try: # this is WAY too large, let except break", "+ j * OnOffblockSize + i] & 0x80: raise Exception(\"Non", "0x00 and data[OnOffstart + (j+1) * OnOffblockSize - 2] ==", "of this. print(\"End of the parameters\") break; if not (", "offset. ZDL has none of this. print(\"End of the parameters\")", "ZDL has none of this. print(\"End of the parameters\") break;", "mmax.append( data[OnOffstart + j * OnOffblockSize + 12] + data[OnOffstart", "+ (j+1) * OnOffblockSize + 2]), hex(data[OnOffstart + (j+1) *", "\"fxname\" :fxName } mmax = [] mdefault = [] name", "16] + data[OnOffstart + j * OnOffblockSize + 17] *", "{}\".format(OnOffstart)) try: # this is WAY too large, let except", "loop for j in range(0, 2000): \"\"\" if not (", "+ j * OnOffblockSize + 12] + data[OnOffstart + j", "chr(data[OnOffstart + j + OnOffblockSize]) tD = { \"fxname\" :fxName", "= 0x30 for j in range(12): if data[OnOffstart + j", "= [] name = [] mpedal = [] numParameters =", "== 0x00: break fxName = fxName + chr(data[OnOffstart + j", "+ j * OnOffblockSize + 16] + data[OnOffstart + j", "mpedal[i+2]}) #json.dump(tD, sys.stdout, indent=4) f = open(fxName+'.json', \"w\") json.dump(tD, f,", "OnOffstart + (j+1) * OnOffblockSize, hex(data[OnOffstart + (j+1) * OnOffblockSize]),", "start from index 2, but clearly there are 2 less", "# this is WAY too large, let except break the", "= 0 #print(\"OnOffStart at {}\".format(OnOffstart)) try: # this is WAY", "0x00 and data[OnOffstart + (j) * OnOffblockSize + 0x1A] ==", "+ OnOffblockSize]) tD = { \"fxname\" :fxName } mmax =", "in range(12): if data[OnOffstart + j + OnOffblockSize] == 0x00:", "+ 0x18 ] == 0x00 and data[OnOffstart + (j) *", "{ \"fxname\" :fxName } mmax = [] mdefault = []", "ZD2 format has a length and PRME offset. ZDL has", "if __name__ == \"__main__\": if len(sys.argv) == 2: f =", "17] * 256); if data[OnOffstart + j * OnOffblockSize +", "so actual paramters start from index 2, but clearly there", "fxName=\"\" OnOffblockSize = 0x30 for j in range(12): if data[OnOffstart", "2] == 0x00): # ZD2 format has a length and", "{} parameters.\".format(numParameters)) tD['Parameters'] = [] # 0 is the OnOff", "else: mpedal.append(False) #print(mmax[j]) #print(mdefault[j]) \"\"\" print(\"[{}] {} {} {} {}\".format(", "name # so actual paramters start from index 2, but", "tD['Parameters'].append({'name': name[i+2], 'mmax': mmax[i + 2], 'mdefault': mdefault[i + 2],", "& 0x80: raise Exception(\"Non binary char\") if currName == \"\":", "+ j * OnOffblockSize + i]) if data[OnOffstart + j", "+ i] & 0x80: raise Exception(\"Non binary char\") if currName", "3])) ) \"\"\" #print(\"increment params\") numParameters = numParameters + 1", "break the loop for j in range(0, 2000): \"\"\" if", "= [] mpedal = [] numParameters = 0 #print(\"OnOffStart at", "# -*- coding: ascii -*- import sys import json def", "range(0, 2000): \"\"\" if not ( data[OnOffstart + (j+1) *", "* 256); if data[OnOffstart + j * OnOffblockSize + 0x2C]:", "[] mdefault = [] name = [] mpedal = []", "f.close() return fxName+'.OnOff' # handles a zoom firmware if __name__", "the parameters\") break; if not ( data[OnOffstart + (j) *", "[] mpedal = [] numParameters = 0 #print(\"OnOffStart at {}\".format(OnOffstart))", "j in range(12): if data[OnOffstart + j + OnOffblockSize] ==", "256); if data[OnOffstart + j * OnOffblockSize + 0x2C]: mpedal.append(True)", "1 except: pass #print(\"Found {} parameters.\".format(numParameters)) tD['Parameters'] = [] #", "+ 2], 'pedal': mpedal[i+2]}) #json.dump(tD, sys.stdout, indent=4) f = open(fxName+'.json',", "(j+1) * OnOffblockSize + 3])) ) \"\"\" #print(\"increment params\") numParameters", "except: pass #print(\"Found {} parameters.\".format(numParameters)) tD['Parameters'] = [] # 0", "j * OnOffblockSize + 0x2C]: mpedal.append(True) else: mpedal.append(False) #print(mmax[j]) #print(mdefault[j])", "firmware if __name__ == \"__main__\": if len(sys.argv) == 2: f", "except break the loop for j in range(0, 2000): \"\"\"", "range(numParameters - 2): #print(i) tD['Parameters'].append({'name': name[i+2], 'mmax': mmax[i + 2],", "OnOffblockSize + 13] * 256) mdefault.append(data[OnOffstart + j * OnOffblockSize", "i]) if data[OnOffstart + j * OnOffblockSize + i] &", "OnOffblockSize = 0x30 for j in range(12): if data[OnOffstart +", "\"\": break name.append(currName) mmax.append( data[OnOffstart + j * OnOffblockSize +", "- 2): #print(i) tD['Parameters'].append({'name': name[i+2], 'mmax': mmax[i + 2], 'mdefault':", "0x00 and data[OnOffstart + (j) * OnOffblockSize + 0x1B] ==", "has a length and PRME offset. ZDL has none of", "pass #print(\"Found {} parameters.\".format(numParameters)) tD['Parameters'] = [] # 0 is", "{} {} {}\".format( OnOffstart + (j+1) * OnOffblockSize, hex(data[OnOffstart +", "raise Exception(\"Non binary char\") if currName == \"\": break name.append(currName)", "OnOffblockSize + 2]), hex(data[OnOffstart + (j+1) * OnOffblockSize + 3]))", "- 2] == 0x00): # ZD2 format has a length", "( data[OnOffstart + (j) * OnOffblockSize + 0x18 ] ==", "numParameters = numParameters + 1 except: pass #print(\"Found {} parameters.\".format(numParameters))", "j * OnOffblockSize + i]) if data[OnOffstart + j *", "1]), hex(data[OnOffstart + (j+1) * OnOffblockSize + 2]), hex(data[OnOffstart +", "not ( data[OnOffstart + (j) * OnOffblockSize + 0x18 ]", "+ (j+1) * OnOffblockSize, hex(data[OnOffstart + (j+1) * OnOffblockSize]), hex(data[OnOffstart", "sys.stdout, indent=4) f = open(fxName+'.json', \"w\") json.dump(tD, f, indent=4) f.close()", "and data[OnOffstart + (j) * OnOffblockSize + 0x19] == 0x00", "0x80: raise Exception(\"Non binary char\") if currName == \"\": break", "data[OnOffstart + (j) * OnOffblockSize + 0x1A] == 0x00 and", "OnOffblockSize]), hex(data[OnOffstart + (j+1) * OnOffblockSize + 1]), hex(data[OnOffstart +", "'pedal': mpedal[i+2]}) #json.dump(tD, sys.stdout, indent=4) f = open(fxName+'.json', \"w\") json.dump(tD,", "data[OnOffstart + (j) * OnOffblockSize + 0x18 ] == 0x00", "break \"\"\" currName = \"\" for i in range(12): if", "# 0 is the OnOff state # 1 is the", "data[OnOffstart + j * OnOffblockSize + 0x2C]: mpedal.append(True) else: mpedal.append(False)", "currName == \"\": break name.append(currName) mmax.append( data[OnOffstart + j *", "# 1 is the name # so actual paramters start", "OnOffblockSize] == 0x00: break fxName = fxName + chr(data[OnOffstart +", "__name__ == \"__main__\": if len(sys.argv) == 2: f = open(sys.argv[1],", "mdefault[i + 2], 'pedal': mpedal[i+2]}) #json.dump(tD, sys.stdout, indent=4) f =", "if not ( data[OnOffstart + (j) * OnOffblockSize + 0x18", "-*- coding: ascii -*- import sys import json def check(data):", "* OnOffblockSize + i] & 0x80: raise Exception(\"Non binary char\")", "256) mdefault.append(data[OnOffstart + j * OnOffblockSize + 16] + data[OnOffstart", "for i in range(numParameters - 2): #print(i) tD['Parameters'].append({'name': name[i+2], 'mmax':", "* OnOffblockSize + 12] + data[OnOffstart + j * OnOffblockSize", "+ (j+1) * OnOffblockSize + 1]), hex(data[OnOffstart + (j+1) *", "+ j * OnOffblockSize + 0x2C]: mpedal.append(True) else: mpedal.append(False) #print(mmax[j])", "2000): \"\"\" if not ( data[OnOffstart + (j+1) * OnOffblockSize", "tD = { \"fxname\" :fxName } mmax = [] mdefault", "params\") numParameters = numParameters + 1 except: pass #print(\"Found {}", "not ( data[OnOffstart + (j+1) * OnOffblockSize - 1] ==", "none of this. print(\"End of the parameters\") break; if not", "json.dump(tD, f, indent=4) f.close() return fxName+'.OnOff' # handles a zoom", "# so actual paramters start from index 2, but clearly", "j * OnOffblockSize + 13] * 256) mdefault.append(data[OnOffstart + j", "this is WAY too large, let except break the loop", "* OnOffblockSize + 0x2C]: mpedal.append(True) else: mpedal.append(False) #print(mmax[j]) #print(mdefault[j]) \"\"\"", "state # 1 is the name # so actual paramters", "2]), hex(data[OnOffstart + (j+1) * OnOffblockSize + 3])) ) \"\"\"", "2], 'mdefault': mdefault[i + 2], 'pedal': mpedal[i+2]}) #json.dump(tD, sys.stdout, indent=4)", "= [] numParameters = 0 #print(\"OnOffStart at {}\".format(OnOffstart)) try: #", "* OnOffblockSize + 0x1A] == 0x00 and data[OnOffstart + (j)", "( data[OnOffstart + (j+1) * OnOffblockSize - 1] == 0x00", "if OnOffstart != -1: fxName=\"\" OnOffblockSize = 0x30 for j", "0x1B] == 0x00 ): print(\"Empty next slot\") break \"\"\" currName", "+ (j+1) * OnOffblockSize]), hex(data[OnOffstart + (j+1) * OnOffblockSize +", "import json def check(data): OnOffstart = data.find(b\"OnOff\") if OnOffstart !=", "+ (j) * OnOffblockSize + 0x19] == 0x00 and data[OnOffstart", "= open(fxName+'.json', \"w\") json.dump(tD, f, indent=4) f.close() return fxName+'.OnOff' #", "chr(data[OnOffstart + j * OnOffblockSize + i]) if data[OnOffstart +", "+ 13] * 256) mdefault.append(data[OnOffstart + j * OnOffblockSize +", "(j) * OnOffblockSize + 0x1A] == 0x00 and data[OnOffstart +", "0x1A] == 0x00 and data[OnOffstart + (j) * OnOffblockSize +", "(j) * OnOffblockSize + 0x1B] == 0x00 ): print(\"Empty next", "+ (j) * OnOffblockSize + 0x1B] == 0x00 ): print(\"Empty", "+ (j+1) * OnOffblockSize + 3])) ) \"\"\" #print(\"increment params\")", "fxName+'.OnOff' # handles a zoom firmware if __name__ == \"__main__\":", "1] == 0x00 and data[OnOffstart + (j+1) * OnOffblockSize -", "+ OnOffblockSize] == 0x00: break fxName = fxName + chr(data[OnOffstart", "OnOffblockSize + 0x1A] == 0x00 and data[OnOffstart + (j) *", "== 0x00 and data[OnOffstart + (j+1) * OnOffblockSize - 2]", "mmax = [] mdefault = [] name = [] mpedal", "* OnOffblockSize + 17] * 256); if data[OnOffstart + j", "+ j * OnOffblockSize + 17] * 256); if data[OnOffstart", "#print(mmax[j]) #print(mdefault[j]) \"\"\" print(\"[{}] {} {} {} {}\".format( OnOffstart +", "json def check(data): OnOffstart = data.find(b\"OnOff\") if OnOffstart != -1:", "too large, let except break the loop for j in", "0x30 for j in range(12): if data[OnOffstart + j +", "== 0x00): # ZD2 format has a length and PRME", "+ chr(data[OnOffstart + j + OnOffblockSize]) tD = { \"fxname\"", "2, but clearly there are 2 less for i in", "hex(data[OnOffstart + (j+1) * OnOffblockSize + 1]), hex(data[OnOffstart + (j+1)", "+ (j+1) * OnOffblockSize - 2] == 0x00): # ZD2", "there are 2 less for i in range(numParameters - 2):", "2: f = open(sys.argv[1], \"rb\") data = f.read() f.close() check(data)", "name.append(currName) mmax.append( data[OnOffstart + j * OnOffblockSize + 12] +", "handles a zoom firmware if __name__ == \"__main__\": if len(sys.argv)", ":fxName } mmax = [] mdefault = [] name =", "OnOffblockSize + 0x19] == 0x00 and data[OnOffstart + (j) *", "# ZD2 format has a length and PRME offset. ZDL", "12] + data[OnOffstart + j * OnOffblockSize + 13] *", "+ 17] * 256); if data[OnOffstart + j * OnOffblockSize", "j * OnOffblockSize + i] == 0x00: break currName =", "+ data[OnOffstart + j * OnOffblockSize + 17] * 256);", "let except break the loop for j in range(0, 2000):", "mdefault = [] name = [] mpedal = [] numParameters", "range(12): if data[OnOffstart + j * OnOffblockSize + i] ==", "name[i+2], 'mmax': mmax[i + 2], 'mdefault': mdefault[i + 2], 'pedal':", "OnOffblockSize + 0x2C]: mpedal.append(True) else: mpedal.append(False) #print(mmax[j]) #print(mdefault[j]) \"\"\" print(\"[{}]", "is WAY too large, let except break the loop for", "* OnOffblockSize + 13] * 256) mdefault.append(data[OnOffstart + j *", "2): #print(i) tD['Parameters'].append({'name': name[i+2], 'mmax': mmax[i + 2], 'mdefault': mdefault[i", "i] & 0x80: raise Exception(\"Non binary char\") if currName ==", "* 256) mdefault.append(data[OnOffstart + j * OnOffblockSize + 16] +", "0x00: break currName = currName + chr(data[OnOffstart + j *", "f, indent=4) f.close() return fxName+'.OnOff' # handles a zoom firmware", "paramters start from index 2, but clearly there are 2", "0x00: break fxName = fxName + chr(data[OnOffstart + j +", "== 0x00: break currName = currName + chr(data[OnOffstart + j", "and data[OnOffstart + (j) * OnOffblockSize + 0x1B] == 0x00", "+ j * OnOffblockSize + 13] * 256) mdefault.append(data[OnOffstart +", "this. print(\"End of the parameters\") break; if not ( data[OnOffstart", "0x00 and data[OnOffstart + (j) * OnOffblockSize + 0x19] ==", "j in range(0, 2000): \"\"\" if not ( data[OnOffstart +", "mpedal.append(True) else: mpedal.append(False) #print(mmax[j]) #print(mdefault[j]) \"\"\" print(\"[{}] {} {} {}", "OnOffblockSize + i] == 0x00: break currName = currName +", "break; if not ( data[OnOffstart + (j) * OnOffblockSize +", "and data[OnOffstart + (j) * OnOffblockSize + 0x1A] == 0x00", "check(data): OnOffstart = data.find(b\"OnOff\") if OnOffstart != -1: fxName=\"\" OnOffblockSize", "0x00): # ZD2 format has a length and PRME offset.", "OnOffblockSize]) tD = { \"fxname\" :fxName } mmax = []", "+ 0x1B] == 0x00 ): print(\"Empty next slot\") break \"\"\"", "open(fxName+'.json', \"w\") json.dump(tD, f, indent=4) f.close() return fxName+'.OnOff' # handles", "OnOffstart = data.find(b\"OnOff\") if OnOffstart != -1: fxName=\"\" OnOffblockSize =", "OnOffblockSize + i]) if data[OnOffstart + j * OnOffblockSize +", "{} {} {} {}\".format( OnOffstart + (j+1) * OnOffblockSize, hex(data[OnOffstart", "\"\"\" if not ( data[OnOffstart + (j+1) * OnOffblockSize -", "(j+1) * OnOffblockSize + 1]), hex(data[OnOffstart + (j+1) * OnOffblockSize", "currName = \"\" for i in range(12): if data[OnOffstart +", "has none of this. print(\"End of the parameters\") break; if", "0x2C]: mpedal.append(True) else: mpedal.append(False) #print(mmax[j]) #print(mdefault[j]) \"\"\" print(\"[{}] {} {}", "tD['Parameters'] = [] # 0 is the OnOff state #", "print(\"End of the parameters\") break; if not ( data[OnOffstart +", "== 0x00 and data[OnOffstart + (j) * OnOffblockSize + 0x1A]", "[] numParameters = 0 #print(\"OnOffStart at {}\".format(OnOffstart)) try: # this", "# handles a zoom firmware if __name__ == \"__main__\": if", "== 0x00 and data[OnOffstart + (j) * OnOffblockSize + 0x1B]", "data[OnOffstart + (j) * OnOffblockSize + 0x1B] == 0x00 ):", "* OnOffblockSize + 1]), hex(data[OnOffstart + (j+1) * OnOffblockSize +", "for i in range(12): if data[OnOffstart + j * OnOffblockSize", "-1: fxName=\"\" OnOffblockSize = 0x30 for j in range(12): if", "= [] # 0 is the OnOff state # 1", "): print(\"Empty next slot\") break \"\"\" currName = \"\" for", "in range(12): if data[OnOffstart + j * OnOffblockSize + i]", "data[OnOffstart + j * OnOffblockSize + 12] + data[OnOffstart +", "if len(sys.argv) == 2: f = open(sys.argv[1], \"rb\") data =", "+ 0x2C]: mpedal.append(True) else: mpedal.append(False) #print(mmax[j]) #print(mdefault[j]) \"\"\" print(\"[{}] {}", "j * OnOffblockSize + i] & 0x80: raise Exception(\"Non binary", "OnOffblockSize + 16] + data[OnOffstart + j * OnOffblockSize +", "+ 1]), hex(data[OnOffstart + (j+1) * OnOffblockSize + 2]), hex(data[OnOffstart", "indent=4) f = open(fxName+'.json', \"w\") json.dump(tD, f, indent=4) f.close() return", "(j+1) * OnOffblockSize]), hex(data[OnOffstart + (j+1) * OnOffblockSize + 1]),", "+ (j) * OnOffblockSize + 0x1A] == 0x00 and data[OnOffstart", "the loop for j in range(0, 2000): \"\"\" if not", "#json.dump(tD, sys.stdout, indent=4) f = open(fxName+'.json', \"w\") json.dump(tD, f, indent=4)", "coding: ascii -*- import sys import json def check(data): OnOffstart", "in range(0, 2000): \"\"\" if not ( data[OnOffstart + (j+1)", "mpedal = [] numParameters = 0 #print(\"OnOffStart at {}\".format(OnOffstart)) try:", "print(\"[{}] {} {} {} {}\".format( OnOffstart + (j+1) * OnOffblockSize,", "numParameters = 0 #print(\"OnOffStart at {}\".format(OnOffstart)) try: # this is", "zoom firmware if __name__ == \"__main__\": if len(sys.argv) == 2:", "= currName + chr(data[OnOffstart + j * OnOffblockSize + i])", "OnOff state # 1 is the name # so actual", "are 2 less for i in range(numParameters - 2): #print(i)", "0x19] == 0x00 and data[OnOffstart + (j) * OnOffblockSize +", "actual paramters start from index 2, but clearly there are", "-*- import sys import json def check(data): OnOffstart = data.find(b\"OnOff\")", "\"__main__\": if len(sys.argv) == 2: f = open(sys.argv[1], \"rb\") data", "clearly there are 2 less for i in range(numParameters -", "OnOffstart != -1: fxName=\"\" OnOffblockSize = 0x30 for j in", "for j in range(0, 2000): \"\"\" if not ( data[OnOffstart", "* OnOffblockSize]), hex(data[OnOffstart + (j+1) * OnOffblockSize + 1]), hex(data[OnOffstart", "* OnOffblockSize + 0x1B] == 0x00 ): print(\"Empty next slot\")", "+ j + OnOffblockSize]) tD = { \"fxname\" :fxName }", "+ 2]), hex(data[OnOffstart + (j+1) * OnOffblockSize + 3])) )", "WAY too large, let except break the loop for j", "mdefault.append(data[OnOffstart + j * OnOffblockSize + 16] + data[OnOffstart +", "- 1] == 0x00 and data[OnOffstart + (j+1) * OnOffblockSize", "* OnOffblockSize + 16] + data[OnOffstart + j * OnOffblockSize", "data[OnOffstart + j * OnOffblockSize + i] == 0x00: break", "hex(data[OnOffstart + (j+1) * OnOffblockSize + 2]), hex(data[OnOffstart + (j+1)", "currName = currName + chr(data[OnOffstart + j * OnOffblockSize +", "mpedal.append(False) #print(mmax[j]) #print(mdefault[j]) \"\"\" print(\"[{}] {} {} {} {}\".format( OnOffstart", "from index 2, but clearly there are 2 less for", "data.find(b\"OnOff\") if OnOffstart != -1: fxName=\"\" OnOffblockSize = 0x30 for", "== 2: f = open(sys.argv[1], \"rb\") data = f.read() f.close()", "if data[OnOffstart + j * OnOffblockSize + 0x2C]: mpedal.append(True) else:", "2 less for i in range(numParameters - 2): #print(i) tD['Parameters'].append({'name':", "data[OnOffstart + j * OnOffblockSize + 13] * 256) mdefault.append(data[OnOffstart", "OnOffblockSize + 0x1B] == 0x00 ): print(\"Empty next slot\") break", "i in range(12): if data[OnOffstart + j * OnOffblockSize +", "currName + chr(data[OnOffstart + j * OnOffblockSize + i]) if", "OnOffblockSize + 17] * 256); if data[OnOffstart + j *", "(j+1) * OnOffblockSize - 2] == 0x00): # ZD2 format", "ascii -*- import sys import json def check(data): OnOffstart =", "#print(i) tD['Parameters'].append({'name': name[i+2], 'mmax': mmax[i + 2], 'mdefault': mdefault[i +", "at {}\".format(OnOffstart)) try: # this is WAY too large, let", "+ i] == 0x00: break currName = currName + chr(data[OnOffstart", "'mmax': mmax[i + 2], 'mdefault': mdefault[i + 2], 'pedal': mpedal[i+2]})", "range(12): if data[OnOffstart + j + OnOffblockSize] == 0x00: break", "Exception(\"Non binary char\") if currName == \"\": break name.append(currName) mmax.append(", "parameters\") break; if not ( data[OnOffstart + (j) * OnOffblockSize", "#print(\"Found {} parameters.\".format(numParameters)) tD['Parameters'] = [] # 0 is the", "0 is the OnOff state # 1 is the name", "a length and PRME offset. ZDL has none of this.", "if data[OnOffstart + j * OnOffblockSize + i] == 0x00:", "j + OnOffblockSize]) tD = { \"fxname\" :fxName } mmax", "0 #print(\"OnOffStart at {}\".format(OnOffstart)) try: # this is WAY too", "data[OnOffstart + (j) * OnOffblockSize + 0x19] == 0x00 and", "+ chr(data[OnOffstart + j * OnOffblockSize + i]) if data[OnOffstart", "= { \"fxname\" :fxName } mmax = [] mdefault =", "OnOffblockSize, hex(data[OnOffstart + (j+1) * OnOffblockSize]), hex(data[OnOffstart + (j+1) *", "\"\"\" #print(\"increment params\") numParameters = numParameters + 1 except: pass", "\"\" for i in range(12): if data[OnOffstart + j *", "parameters.\".format(numParameters)) tD['Parameters'] = [] # 0 is the OnOff state", "+ 12] + data[OnOffstart + j * OnOffblockSize + 13]", "== \"\": break name.append(currName) mmax.append( data[OnOffstart + j * OnOffblockSize", "OnOffblockSize - 2] == 0x00): # ZD2 format has a", "== \"__main__\": if len(sys.argv) == 2: f = open(sys.argv[1], \"rb\")", "* OnOffblockSize + 0x18 ] == 0x00 and data[OnOffstart +", "break currName = currName + chr(data[OnOffstart + j * OnOffblockSize", "if data[OnOffstart + j * OnOffblockSize + i] & 0x80:", "+ 0x1A] == 0x00 and data[OnOffstart + (j) * OnOffblockSize", "+ 0x19] == 0x00 and data[OnOffstart + (j) * OnOffblockSize", "0x18 ] == 0x00 and data[OnOffstart + (j) * OnOffblockSize", "indent=4) f.close() return fxName+'.OnOff' # handles a zoom firmware if", "print(\"Empty next slot\") break \"\"\" currName = \"\" for i", "break fxName = fxName + chr(data[OnOffstart + j + OnOffblockSize])", "= \"\" for i in range(12): if data[OnOffstart + j", "OnOffblockSize - 1] == 0x00 and data[OnOffstart + (j+1) *", "the name # so actual paramters start from index 2,", "large, let except break the loop for j in range(0,", "data[OnOffstart + j * OnOffblockSize + 17] * 256); if", "if currName == \"\": break name.append(currName) mmax.append( data[OnOffstart + j", "{} {}\".format( OnOffstart + (j+1) * OnOffblockSize, hex(data[OnOffstart + (j+1)", "OnOffblockSize + i] & 0x80: raise Exception(\"Non binary char\") if", "== 0x00 and data[OnOffstart + (j) * OnOffblockSize + 0x19]", "\"w\") json.dump(tD, f, indent=4) f.close() return fxName+'.OnOff' # handles a", "* OnOffblockSize + i]) if data[OnOffstart + j * OnOffblockSize", "* OnOffblockSize + 3])) ) \"\"\" #print(\"increment params\") numParameters =", "and PRME offset. ZDL has none of this. print(\"End of", "= data.find(b\"OnOff\") if OnOffstart != -1: fxName=\"\" OnOffblockSize = 0x30", "[] # 0 is the OnOff state # 1 is", "2], 'pedal': mpedal[i+2]}) #json.dump(tD, sys.stdout, indent=4) f = open(fxName+'.json', \"w\")", "+ 16] + data[OnOffstart + j * OnOffblockSize + 17]", "+ (j) * OnOffblockSize + 0x18 ] == 0x00 and", "OnOffblockSize + 3])) ) \"\"\" #print(\"increment params\") numParameters = numParameters", "(j) * OnOffblockSize + 0x19] == 0x00 and data[OnOffstart +", "slot\") break \"\"\" currName = \"\" for i in range(12):", "f = open(fxName+'.json', \"w\") json.dump(tD, f, indent=4) f.close() return fxName+'.OnOff'", "data[OnOffstart + (j+1) * OnOffblockSize - 2] == 0x00): #", "fxName + chr(data[OnOffstart + j + OnOffblockSize]) tD = {", "{}\".format( OnOffstart + (j+1) * OnOffblockSize, hex(data[OnOffstart + (j+1) *", "* OnOffblockSize - 2] == 0x00): # ZD2 format has", "hex(data[OnOffstart + (j+1) * OnOffblockSize]), hex(data[OnOffstart + (j+1) * OnOffblockSize", "next slot\") break \"\"\" currName = \"\" for i in", "i] == 0x00: break currName = currName + chr(data[OnOffstart +", "\"\"\" currName = \"\" for i in range(12): if data[OnOffstart", "0x00 ): print(\"Empty next slot\") break \"\"\" currName = \"\"" ]
[ "in range(ord('a'), ord('z') + 1)] upper_char = [chr(x) for x", "x in range(ord('A'), ord('Z') + 1)] number_char = [chr(x) for", "source += \"\".join(lower_char) source += \"\".join(upper_char) source += \"\".join(number_char) source", "= [chr(x) for x in range(ord('0'), ord('9') + 1)] source", "random source = '' lower_char = [chr(x) for x in", "\"\".join(number_char) source += \"_\" print(source) # 随机取出20位字符串,包括下划线 while True: s", "+ 1)] source += \"\".join(lower_char) source += \"\".join(upper_char) source +=", "+= \"\".join(upper_char) source += \"\".join(number_char) source += \"_\" print(source) #", "随机6位密码 a-zA-Z0-9下划线 import random source = '' lower_char = [chr(x)", "+ 1)] number_char = [chr(x) for x in range(ord('0'), ord('9')", "= '' lower_char = [chr(x) for x in range(ord('a'), ord('z')", "lower_char = [chr(x) for x in range(ord('a'), ord('z') + 1)]", "for x in range(ord('A'), ord('Z') + 1)] number_char = [chr(x)", "[chr(x) for x in range(ord('a'), ord('z') + 1)] upper_char =", "'' lower_char = [chr(x) for x in range(ord('a'), ord('z') +", "= [chr(x) for x in range(ord('A'), ord('Z') + 1)] number_char", "for x in range(ord('0'), ord('9') + 1)] source += \"\".join(lower_char)", "# 随机取出20位字符串,包括下划线 while True: s = \"\".join(random.sample(source, 20)) if '_'", "[chr(x) for x in range(ord('A'), ord('Z') + 1)] number_char =", "1)] number_char = [chr(x) for x in range(ord('0'), ord('9') +", "while True: s = \"\".join(random.sample(source, 20)) if '_' in s:", "range(ord('a'), ord('z') + 1)] upper_char = [chr(x) for x in", "[chr(x) for x in range(ord('0'), ord('9') + 1)] source +=", "range(ord('0'), ord('9') + 1)] source += \"\".join(lower_char) source += \"\".join(upper_char)", "ord('z') + 1)] upper_char = [chr(x) for x in range(ord('A'),", "ord('9') + 1)] source += \"\".join(lower_char) source += \"\".join(upper_char) source", "1)] source += \"\".join(lower_char) source += \"\".join(upper_char) source += \"\".join(number_char)", "\"\".join(upper_char) source += \"\".join(number_char) source += \"_\" print(source) # 随机取出20位字符串,包括下划线", "source += \"\".join(number_char) source += \"_\" print(source) # 随机取出20位字符串,包括下划线 while", "随机取出20位字符串,包括下划线 while True: s = \"\".join(random.sample(source, 20)) if '_' in", "print(source) # 随机取出20位字符串,包括下划线 while True: s = \"\".join(random.sample(source, 20)) if", "upper_char = [chr(x) for x in range(ord('A'), ord('Z') + 1)]", "in range(ord('0'), ord('9') + 1)] source += \"\".join(lower_char) source +=", "x in range(ord('a'), ord('z') + 1)] upper_char = [chr(x) for", "ord('Z') + 1)] number_char = [chr(x) for x in range(ord('0'),", "s = \"\".join(random.sample(source, 20)) if '_' in s: print(s) break", "x in range(ord('0'), ord('9') + 1)] source += \"\".join(lower_char) source", "a-zA-Z0-9下划线 import random source = '' lower_char = [chr(x) for", "import random source = '' lower_char = [chr(x) for x", "1)] upper_char = [chr(x) for x in range(ord('A'), ord('Z') +", "in range(ord('A'), ord('Z') + 1)] number_char = [chr(x) for x", "source = '' lower_char = [chr(x) for x in range(ord('a'),", "True: s = \"\".join(random.sample(source, 20)) if '_' in s: print(s)", "\"_\" print(source) # 随机取出20位字符串,包括下划线 while True: s = \"\".join(random.sample(source, 20))", "source += \"\".join(upper_char) source += \"\".join(number_char) source += \"_\" print(source)", "= [chr(x) for x in range(ord('a'), ord('z') + 1)] upper_char", "+ 1)] upper_char = [chr(x) for x in range(ord('A'), ord('Z')", "+= \"\".join(number_char) source += \"_\" print(source) # 随机取出20位字符串,包括下划线 while True:", "for x in range(ord('a'), ord('z') + 1)] upper_char = [chr(x)", "source += \"_\" print(source) # 随机取出20位字符串,包括下划线 while True: s =", "+= \"_\" print(source) # 随机取出20位字符串,包括下划线 while True: s = \"\".join(random.sample(source,", "number_char = [chr(x) for x in range(ord('0'), ord('9') + 1)]", "\"\".join(lower_char) source += \"\".join(upper_char) source += \"\".join(number_char) source += \"_\"", "# 随机6位密码 a-zA-Z0-9下划线 import random source = '' lower_char =", "+= \"\".join(lower_char) source += \"\".join(upper_char) source += \"\".join(number_char) source +=", "range(ord('A'), ord('Z') + 1)] number_char = [chr(x) for x in" ]
[ "from django.test import TestCase from rest_framework.test import APIRequestFactory from .models", "TestCase from rest_framework.test import APIRequestFactory from .models import GBIC, GBICType", "gbic_test = GBIC.objects.create( serial='showdomilhao', patrimony_number='777', gbic_type=gbic_type_test ) gbic_test.delete() response =", "from rest_framework.test import APIRequestFactory from .models import GBIC, GBICType from", "GBIC, GBICType from .views import GBICListViewSet # Create your tests", "def test_gbic_view_set(self): request = APIRequestFactory().get(\"\") gbic_detail = GBICListViewSet.as_view(actions={'get': 'retrieve'}) gbic_type_test", "here. class GBICTest(TestCase): def test_gbic_view_set(self): request = APIRequestFactory().get(\"\") gbic_detail =", "gbic_type_test = GBICType.objects.create(description='muitoruim') gbic_test = GBIC.objects.create( serial='showdomilhao', patrimony_number='777', gbic_type=gbic_type_test )", "gbic_detail = GBICListViewSet.as_view(actions={'get': 'retrieve'}) gbic_type_test = GBICType.objects.create(description='muito_bom') gbic_test = GBIC.objects.create(", "GBICType.objects.create(description='muitoruim') gbic_test = GBIC.objects.create( serial='showdomilhao', patrimony_number='777', gbic_type=gbic_type_test ) gbic_test.delete() response", "request = APIRequestFactory().get(\"\") gbic_detail = GBICListViewSet.as_view(actions={'get': 'retrieve'}) gbic_type_test = GBICType.objects.create(description='muito_bom')", "GBICType from .views import GBICListViewSet # Create your tests here.", "'retrieve'}) gbic_type_test = GBICType.objects.create(description='muitoruim') gbic_test = GBIC.objects.create( serial='showdomilhao', patrimony_number='777', gbic_type=gbic_type_test", "# Create your tests here. class GBICTest(TestCase): def test_gbic_view_set(self): request", "import GBICListViewSet # Create your tests here. class GBICTest(TestCase): def", "from .views import GBICListViewSet # Create your tests here. class", "import TestCase from rest_framework.test import APIRequestFactory from .models import GBIC,", "from .models import GBIC, GBICType from .views import GBICListViewSet #", "gbic_test = GBIC.objects.create( serial='showdaxuxa', patrimony_number='666', gbic_type=gbic_type_test ) response = gbic_detail(request,", "pk=gbic_test.pk) self.assertEqual(response.status_code, 200) def test_deleted_gbic_view_set(self): request = APIRequestFactory().get(\"\") gbic_detail =", "self.assertEqual(response.status_code, 200) def test_deleted_gbic_view_set(self): request = APIRequestFactory().get(\"\") gbic_detail = GBICListViewSet.as_view(actions={'get':", "django.test import TestCase from rest_framework.test import APIRequestFactory from .models import", "tests here. class GBICTest(TestCase): def test_gbic_view_set(self): request = APIRequestFactory().get(\"\") gbic_detail", "patrimony_number='777', gbic_type=gbic_type_test ) gbic_test.delete() response = gbic_detail(request, pk=gbic_test.pk) self.assertEqual(response.status_code, 404)", "gbic_detail = GBICListViewSet.as_view(actions={'get': 'retrieve'}) gbic_type_test = GBICType.objects.create(description='muitoruim') gbic_test = GBIC.objects.create(", ") response = gbic_detail(request, pk=gbic_test.pk) self.assertEqual(response.status_code, 200) def test_deleted_gbic_view_set(self): request", "= GBICType.objects.create(description='muitoruim') gbic_test = GBIC.objects.create( serial='showdomilhao', patrimony_number='777', gbic_type=gbic_type_test ) gbic_test.delete()", "GBIC.objects.create( serial='showdomilhao', patrimony_number='777', gbic_type=gbic_type_test ) gbic_test.delete() response = gbic_detail(request, pk=gbic_test.pk)", "response = gbic_detail(request, pk=gbic_test.pk) self.assertEqual(response.status_code, 200) def test_deleted_gbic_view_set(self): request =", "APIRequestFactory().get(\"\") gbic_detail = GBICListViewSet.as_view(actions={'get': 'retrieve'}) gbic_type_test = GBICType.objects.create(description='muito_bom') gbic_test =", "serial='showdaxuxa', patrimony_number='666', gbic_type=gbic_type_test ) response = gbic_detail(request, pk=gbic_test.pk) self.assertEqual(response.status_code, 200)", "= APIRequestFactory().get(\"\") gbic_detail = GBICListViewSet.as_view(actions={'get': 'retrieve'}) gbic_type_test = GBICType.objects.create(description='muitoruim') gbic_test", "import GBIC, GBICType from .views import GBICListViewSet # Create your", "def test_deleted_gbic_view_set(self): request = APIRequestFactory().get(\"\") gbic_detail = GBICListViewSet.as_view(actions={'get': 'retrieve'}) gbic_type_test", "= APIRequestFactory().get(\"\") gbic_detail = GBICListViewSet.as_view(actions={'get': 'retrieve'}) gbic_type_test = GBICType.objects.create(description='muito_bom') gbic_test", "= GBICListViewSet.as_view(actions={'get': 'retrieve'}) gbic_type_test = GBICType.objects.create(description='muito_bom') gbic_test = GBIC.objects.create( serial='showdaxuxa',", ".models import GBIC, GBICType from .views import GBICListViewSet # Create", "GBICListViewSet # Create your tests here. class GBICTest(TestCase): def test_gbic_view_set(self):", "your tests here. class GBICTest(TestCase): def test_gbic_view_set(self): request = APIRequestFactory().get(\"\")", "class GBICTest(TestCase): def test_gbic_view_set(self): request = APIRequestFactory().get(\"\") gbic_detail = GBICListViewSet.as_view(actions={'get':", "= GBIC.objects.create( serial='showdaxuxa', patrimony_number='666', gbic_type=gbic_type_test ) response = gbic_detail(request, pk=gbic_test.pk)", "= gbic_detail(request, pk=gbic_test.pk) self.assertEqual(response.status_code, 200) def test_deleted_gbic_view_set(self): request = APIRequestFactory().get(\"\")", "GBICListViewSet.as_view(actions={'get': 'retrieve'}) gbic_type_test = GBICType.objects.create(description='muitoruim') gbic_test = GBIC.objects.create( serial='showdomilhao', patrimony_number='777',", "'retrieve'}) gbic_type_test = GBICType.objects.create(description='muito_bom') gbic_test = GBIC.objects.create( serial='showdaxuxa', patrimony_number='666', gbic_type=gbic_type_test", "patrimony_number='666', gbic_type=gbic_type_test ) response = gbic_detail(request, pk=gbic_test.pk) self.assertEqual(response.status_code, 200) def", "= GBICListViewSet.as_view(actions={'get': 'retrieve'}) gbic_type_test = GBICType.objects.create(description='muitoruim') gbic_test = GBIC.objects.create( serial='showdomilhao',", "Create your tests here. class GBICTest(TestCase): def test_gbic_view_set(self): request =", "gbic_detail(request, pk=gbic_test.pk) self.assertEqual(response.status_code, 200) def test_deleted_gbic_view_set(self): request = APIRequestFactory().get(\"\") gbic_detail", "GBICListViewSet.as_view(actions={'get': 'retrieve'}) gbic_type_test = GBICType.objects.create(description='muito_bom') gbic_test = GBIC.objects.create( serial='showdaxuxa', patrimony_number='666',", "serial='showdomilhao', patrimony_number='777', gbic_type=gbic_type_test ) gbic_test.delete() response = gbic_detail(request, pk=gbic_test.pk) self.assertEqual(response.status_code,", "test_gbic_view_set(self): request = APIRequestFactory().get(\"\") gbic_detail = GBICListViewSet.as_view(actions={'get': 'retrieve'}) gbic_type_test =", "GBIC.objects.create( serial='showdaxuxa', patrimony_number='666', gbic_type=gbic_type_test ) response = gbic_detail(request, pk=gbic_test.pk) self.assertEqual(response.status_code,", "import APIRequestFactory from .models import GBIC, GBICType from .views import", "gbic_type=gbic_type_test ) response = gbic_detail(request, pk=gbic_test.pk) self.assertEqual(response.status_code, 200) def test_deleted_gbic_view_set(self):", "GBICTest(TestCase): def test_gbic_view_set(self): request = APIRequestFactory().get(\"\") gbic_detail = GBICListViewSet.as_view(actions={'get': 'retrieve'})", "gbic_type_test = GBICType.objects.create(description='muito_bom') gbic_test = GBIC.objects.create( serial='showdaxuxa', patrimony_number='666', gbic_type=gbic_type_test )", "test_deleted_gbic_view_set(self): request = APIRequestFactory().get(\"\") gbic_detail = GBICListViewSet.as_view(actions={'get': 'retrieve'}) gbic_type_test =", "rest_framework.test import APIRequestFactory from .models import GBIC, GBICType from .views", "request = APIRequestFactory().get(\"\") gbic_detail = GBICListViewSet.as_view(actions={'get': 'retrieve'}) gbic_type_test = GBICType.objects.create(description='muitoruim')", "APIRequestFactory().get(\"\") gbic_detail = GBICListViewSet.as_view(actions={'get': 'retrieve'}) gbic_type_test = GBICType.objects.create(description='muitoruim') gbic_test =", "= GBIC.objects.create( serial='showdomilhao', patrimony_number='777', gbic_type=gbic_type_test ) gbic_test.delete() response = gbic_detail(request,", "APIRequestFactory from .models import GBIC, GBICType from .views import GBICListViewSet", ".views import GBICListViewSet # Create your tests here. class GBICTest(TestCase):", "= GBICType.objects.create(description='muito_bom') gbic_test = GBIC.objects.create( serial='showdaxuxa', patrimony_number='666', gbic_type=gbic_type_test ) response", "GBICType.objects.create(description='muito_bom') gbic_test = GBIC.objects.create( serial='showdaxuxa', patrimony_number='666', gbic_type=gbic_type_test ) response =", "200) def test_deleted_gbic_view_set(self): request = APIRequestFactory().get(\"\") gbic_detail = GBICListViewSet.as_view(actions={'get': 'retrieve'})" ]
[ "branch: \"FruitBranch\" = None): \"\"\"Adds a new branch to the", "\"\\n\\t \".join(lines[1:]) return summary def copy(self) -> \"FruitBranch\": \"\"\"Returns a", "# transform the dataset X_train_transformed = fruit.transform(X_train) X_test_tranformed = fruit.transform(X_test)", "self.fork() self._branches[self._cbi].add(*objects) self._fitted = False def nfeatures(self) -> int: \"\"\"Returns", "_compile(self): # checks if the FruitBranch is configured correctly and", "of self.fit\") result = np.zeros((X.shape[0], self.nfeatures())) index = 0 for", "the FruitBranch configuration. :param X: (Multidimensional) time series dataset as", "self._fitted: bool = False self._fit_sample_size: Union[float, int] = 1 #", "transformed results of X from all branches. :param X: (Multidimensional)", "Union[float, int] = 1 # cache that is calculated at", "all preparateurs added to the branch. :rtype: List[DataPreparateur] \"\"\" return", "``self.fit`` wasn't called \"\"\" if not self._fitted: raise RuntimeError(\"Missing call", "import Word from fruits.sieving.abstract import FeatureSieve from fruits.preparation.abstract import DataPreparateur", "or ``1`` for one random time series., defaults to 1", "for fitting self._fitted: bool = False self._fit_sample_size: Union[float, int] =", "(Copy)\") for branch in self._branches: copy_.fork(branch.deepcopy()) return copy_ class FruitBranch:", "series dataset fruit.fit(X_train) # transform the dataset X_train_transformed = fruit.transform(X_train)", "words specified for ISS calculation\") if not self._sieves: raise RuntimeError(\"No", "-> str: \"\"\"Simple identifier for the Fruit object.\"\"\" return self._name", "FruitBranch object. :returns: Copy of the branch with same settings", "# choose sieves fruit.add(fruits.sieving.PPV(0.5)) fruit.add(fruits.sieving.END) # add a new branch", "\"\"\" summary = \"{:-^80}\".format(\"fruits.FruitBranch\") summary += f\"\\nNumber of features: {self.nfeatures()}\"", ") ) else: return ( sum([s.nfeatures() for s in self._sieves])", "values from time series data that are somehow representative of", "in self._branches: copy_.fork(branch.deepcopy()) return copy_ class FruitBranch: \"\"\"One branch of", "as a float which will be multiplied by ``X.shape[0]`` or", "cache needed in this branch self._cache = CoquantileCache() self._cache.process(X, list(self._collect_cache_keys()))", "on one specific output # of an ISS-result self._sieves_extended: list", "this object. The summary contains a summary for each FruitBranch", "numpy as np from fruits.cache import Cache, CoquantileCache from fruits.scope", "X: np.ndarray, callbacks: List[AbstractCallback] = []) -> np.ndarray: \"\"\"Transforms the", "\" + \\ \"\\n\\t+ \".join([str(x) for x in self._preparateurs]) summary", "returns a sample of the data used for fitting if", "were added to this branch.\"\"\" self._sieves = [] self._sieve_prerequisites =", "of the branch with same settings but all calculations done", "import inspect from typing import List, Union, Set, Any import", "= name # list of FruitBranches self._branches: List[FruitBranch] = []", "+= \"-\" elif len(self._words) > 10: summary += \"\\n\\t+ \"", "at :meth:`~fruits.scope.force_input_shape`. :type X: np.ndarray :param callbacks: List of callbacks.", "copy(self) -> \"Fruit\": \"\"\"Creates a shallow copy of this Fruit", "branches combined. :rtype: int \"\"\" return sum([branch.nfeatures() for branch in", "\"\"\" if mode is not None: self._calculator_options[\"mode\"] = mode if", "X: np.ndarray :returns: Two dimensional feature array :rtype: np.ndarray \"\"\"", "callback in callbacks: callback.on_sieving_end(sieved_data) return sieved_data def fit_transform(self, X: np.ndarray)", "words and sieves. :rtype: str \"\"\" summary = \"{:-^80}\".format(\"fruits.FruitBranch\") summary", "import SignatureCalculator, CachePlan from fruits.words.word import Word from fruits.sieving.abstract import", "from all branches. :param X: (Multidimensional) time series dataset :type", "list = [] self._sieves: list = [] # calculator options", "sums. A Fruit consists of a number of :class:`~fruits.core.fruit.FruitBranch` objects.", "size=s, replace=False) return X[indices, :, :] def fit(self, X: np.ndarray):", "-> \"Fruit\": \"\"\"Creates a shallow copy of this Fruit object.", "to this branch.\"\"\" self._words = [] self._sieves_extended = [] self._fitted", "Iterated Sums: The preprocessed data is now used to calculate", "i.e. the features for each time series. \"\"\" def __init__(self):", "self.nfeatures())) index = 0 for branch in self._branches: for callback", ":] def fit(self, X: np.ndarray): \"\"\"Fits the branch to the", "str \"\"\" summary = \"{:-^80}\".format(\"fruits.FruitBranch\") summary += f\"\\nNumber of features:", "s = 1 indices = np.random.choice(X.shape[0], size=s, replace=False) return X[indices,", "prepared_data, words=self._words, **self._calculator_options )[0] for iterated_data in iss_calculations: iterated_data =", "summary += f\"\\nNumber of features: {self.nfeatures()}\" summary += f\"\\n\\nPreparateurs ({len(self._preparateurs)}):", "fit_transform(self, X: np.ndarray) -> np.ndarray: \"\"\"This function does the same", "needed in this branch self._cache = CoquantileCache() self._cache.process(X, list(self._collect_cache_keys())) def", "time series dataset fruit.fit(X_train) # transform the dataset X_train_transformed =", "in self._sieves]) * CachePlan(self._words).n_iterated_sums( list(range(len(self._words))) ) ) else: return (", "x in self._words]) summary += f\"\\nSieves ({len(self._sieves)}): \" if len(self._sieves)", "\"\"\"Clears all settings, configurations and calculated results the branch has.", "X: (Multidimensional) time series dataset as an array of three", "= [] self._sieves_extended = [] self._fitted = False def add_sieve(self,", "a look at :meth:`~fruits.scope.force_input_shape`. :type X: np.ndarray \"\"\" for branch", "in self._preparateurs: prep_keys = prep._get_cache_keys() if 'coquantile' in prep_keys: keys", "multiple object(s) to the currently selected branch. :param objects: One", "the end of the pipeline, each branch returns their own", "str: \"\"\"Simple identifier for the Fruit object.\"\"\" return self._name @name.setter", "branch returns their own features and they will be concatenated", "created and switched to. :type branch: FruitBranch, optional \"\"\" if", "in ``[0, 1, ..., len(self.branches())-1]`` :type index: int \"\"\" if", "def clear_sieves(self): \"\"\"Removes all feature sieves that were added to", "# collects cache keys of all FitTransformers in the branch", "Union[FitTransform, Word, type]): \"\"\"Adds one or multiple object(s) to the", "features from all branches this Fruit object contains. :param X:", "type]): \"\"\"Adds one or multiple object(s) to the branch. :type", "series. \"\"\" def __init__(self, name: str = \"\"): self.name: str", "returns their own features and they will be concatenated by", "f\"\\nBranches: {len(self.branches())}\" summary += f\"\\nFeatures: {self.nfeatures()}\" for branch in self.branches():", "in callbacks: callback.on_sieving_end(sieved_data) return sieved_data def fit_transform(self, X: np.ndarray) ->", "True def transform(self, X: np.ndarray, callbacks: List[AbstractCallback] = []) ->", "Fruit object. This also creates deep copies of all branches", "def _get_cache(self, X: np.ndarray): # returns the already processed cache", "branch is cleared, it has the same settings as a", "have a look at :meth:`fruits.core.fruit.FruitBranch.configure`. :type kwargs: Any \"\"\" for", ":type preparateur: DataPreparateur \"\"\" if not isinstance(preparateur, DataPreparateur): raise TypeError", "objects. At the end of the pipeline, each branch returns", "\"\"\"Returns a list of all words in the branch. :rtype:", "self.clear_words() self.clear_sieves() self._calculator_options = {\"batch_size\": 1, \"mode\": \"single\"} def nfeatures(self)", "return keys def _get_cache(self, X: np.ndarray): # returns the already", "of this object. The summary contains a summary for each", "in self._preparateurs: copy_.add(preparateur) for iterator in self._words: copy_.add(iterator) for sieve", "callback.on_sieve(sieved_data[k:k+new_features]) k += new_features for callback in callbacks: callback.on_sieving_end(sieved_data) return", "can customize any of the following three steps. - Preparing", "get_words(self) -> List[Word]: \"\"\"Returns a list of all words in", "Fruit: \"\"\"Feature Extractor using iterated sums. A Fruit consists of", "What this action explicitly does depends on the FruitBranch configuration.", "fit_transform(self, X: np.ndarray) -> np.ndarray: \"\"\"Fits all branches to the", "str \"\"\" summary = \"{:=^80}\".format(f\"Summary of fruits.Fruit: '{self.name}'\") summary +=", "self._fit_sample_size: Union[float, int] = 1 # cache that is calculated", "a two dimensional array of all features from all branches", "np.ndarray: # returns a sample of the data used for", "\"\"\"This function does the same that calling ``self.fit(X)`` and ``self.transform(X)``", "indices = np.random.choice(X.shape[0], size=s, replace=False) return X[indices, :, :] def", "+= f\"\\n\\nPreparateurs ({len(self._preparateurs)}): \" if len(self._preparateurs) == 0: summary +=", "identifier for the Fruit object.\"\"\" return self._name @name.setter def name(self,", "replace=False) return X[indices, :, :] def fit(self, X: np.ndarray): \"\"\"Fits", "calculated at fitting and also used in the # transformation", "fruit branch if arguments differ from ``None``. :param mode: See", "summary += \"\\n\\t \" summary += \"\\n\\t \".join(lines[1:]) return summary", "# configure the fruit fruit.configure(mode=\"extended\") # fit the fruit on", "of Summary\") return summary def copy(self) -> \"Fruit\": \"\"\"Creates a", "and switched to. :type branch: FruitBranch, optional \"\"\" if branch", "index = 0 for branch in self._branches: for callback in", "int = 0 self._fitted: bool = False @property def name(self)", "List[FruitBranch] = [] # pointer for the current branch index", "np.ndarray :returns: Two dimensional feature array :rtype: np.ndarray \"\"\" self.fit(X)", "a sample of the data used for fitting if (isinstance(self._fit_sample_size,", ":, :] else: s = int(self._fit_sample_size * X.shape[0]) if s", "Each :class:`~fruits.sieving.abstract.FeatureSieve` added to the branch will be fitted on", "sieved_data def fit_transform(self, X: np.ndarray) -> np.ndarray: \"\"\"This function does", "self._sieves: raise RuntimeError(\"No FeatureSieve objects specified\") def _collect_cache_keys(self) -> Set[str]:", "optional :rtype: np.ndarray :raises: RuntimeError if Fruit.fit wasn't called \"\"\"", "\" + \\ \"\\n\\t+ \".join([str(x) for x in self._words[:9]]) summary", "import numpy as np from fruits.cache import Cache, CoquantileCache from", "not self._words: raise RuntimeError(\"No words specified for ISS calculation\") if", "is cleared, it has the same settings as a newly", "\".join(lines[1:]) return summary def copy(self) -> \"FruitBranch\": \"\"\"Returns a shallow", "a shallow copy of this FruitBranch object. :returns: Copy of", "= prep.transform(prepared_data, cache=self._cache) self._sieves_extended = [] iss_calculations = SignatureCalculator().transform( prepared_data,", "At the end of the pipeline, each branch returns their", "not (0 <= index < len(self._branches)): raise IndexError(\"Index has to", "index:index+k] = branch.transform(X, callbacks) index += k result = np.nan_to_num(result,", "FeatureSieve): raise TypeError self._sieves.append(sieve) self._fitted = False def get_sieves(self) ->", "prep.fit(prepared_data) prepared_data = prep.transform(prepared_data, cache=self._cache) self._sieves_extended = [] iss_calculations =", "to the input data. - Calculating Iterated Sums: The preprocessed", "deep copies of all branches in this object. :rtype: Fruit", "sum([branch.nfeatures() for branch in self._branches]) def configure(self, **kwargs: Any): \"\"\"Makes", "branch.configure(**kwargs) def fit(self, X: np.ndarray): \"\"\"Fits all branches to the", "sieve.transform( iterated_data[:, it, :], cache=self._cache, ) for callback in callbacks:", "inspect.isclass(obj): obj = obj() if isinstance(obj, DataPreparateur): self.add_preparateur(obj) elif isinstance(obj,", "they will be concatenated by this class. A simple example", "list of FruitBranches self._branches: List[FruitBranch] = [] # pointer for", "in a classifier ... The ``fruit`` above will result in", "sample that is used for fitting. This is represented as", "result[:, index:index+k] = branch.transform(X, callbacks) index += k result =", "to this branch.\"\"\" self._sieves = [] self._sieve_prerequisites = None self._sieves_extended", "the input data. - Calculating Iterated Sums: The preprocessed data", "np.ndarray \"\"\" self.fit(X) return self.transform(X) def summary(self) -> str: \"\"\"Returns", "given data. :param X: (Multidimensional) time series dataset as an", "Set[str]: # collects cache keys of all FitTransformers in the", "start of the extraction procedure. There are many so called", "= batch_size if fit_sample_size is not None: self._fit_sample_size = fit_sample_size", "clear_preparateurs(self): \"\"\"Removes all preparateurs that were added to this branch.\"\"\"", "branch or the branch with the given index. :rtype: FruitBranch", ":param kwargs: For possible options, have a look at :meth:`fruits.core.fruit.FruitBranch.configure`.", "raise TypeError self._sieves.append(sieve) self._fitted = False def get_sieves(self) -> List[FeatureSieve]:", "callbacks. To write your own callback, override the class :class:`~fruits.core.callback.AbstractCallback`.,", "represented as a float which will be multiplied by ``X.shape[0]``", "ISS-result self._sieves_extended: list = [] # configurations for fitting self._fitted:", "the fruit on a time series dataset fruit.fit(X_train) # transform", "be in [0, len(self.branches()))\") self._cbi = index def add(self, *objects:", "list \"\"\" return self._branches def switch_branch(self, index: int): \"\"\"Switches to", "None): \"\"\"Returns the currently selected branch or the branch with", "= np.random.randint(0, X.shape[0]) return X[ind:ind+1, :, :] else: s =", "be concatenated by this class. A simple example (using two", "= keys.union(sieve_keys['coquantile']) return keys def _get_cache(self, X: np.ndarray): # returns", "this Fruit object. :rtype: str \"\"\" summary = \"{:=^80}\".format(f\"Summary of", "\"FruitBranch\": \"\"\"Returns a deep copy of this FruitBranch object. :returns:", "many so called :class:`~fruits.preparation.abstract.DataPreparateur` objects in fruits available for preprocessing.", "preparateur: DataPreparateur \"\"\" if not isinstance(preparateur, DataPreparateur): raise TypeError self._preparateurs.append(preparateur)", "to calculate the iterated sums signature for different :class:`~fruits.words.word.Word` objects", "if branch is None: branch = FruitBranch() self._branches.append(branch) self._cbi =", "raise TypeError(\"Cannot add variable of type\"+str(type(obj))) def clear(self): \"\"\"Clears all", "self._cache = CoquantileCache() self._cache.process(X, list(self._collect_cache_keys())) def _select_fit_sample(self, X: np.ndarray) ->", "defaults to None :type batch_size: int, optional :param fit_sample_size: Size", "for data processing self._preparateurs: list = [] self._words: list =", "callbacks: callback.on_next_branch() k = branch.nfeatures() result[:, index:index+k] = branch.transform(X, callbacks)", "\" if len(self._words) == 0: summary += \"-\" elif len(self._words)", "branch of a Fruit object. A FruitBranch object extracts values", "\"\"\" def __init__(self): # lists of used classes for data", "# list of FruitBranches self._branches: List[FruitBranch] = [] # pointer", "self._calculator_options[\"batch_size\"] = batch_size if fit_sample_size is not None: self._fit_sample_size =", "bool = False self._fit_sample_size: Union[float, int] = 1 # cache", "dimensions. Have a look at :meth:`~fruits.scope.force_input_shape`. :type X: np.ndarray :param", "features for the different time series. :param X: (Multidimensional) time", "callback, override the class :class:`~fruits.core.callback.AbstractCallback`., defaults to [] :type callbacks:", "lists containing sieves # all sieves in one list are", "= False def add(self, *objects: Union[FitTransform, Word, type]): \"\"\"Adds one", "if not self._words: raise RuntimeError(\"No words specified for ISS calculation\")", "branches if arguments differ from ``None``. :param kwargs: For possible", "transform(self, X: np.ndarray, callbacks: List[AbstractCallback] = []) -> np.ndarray: \"\"\"Transforms", "SignatureCalculator().transform( prepared_data, words=self._words, **self._calculator_options )[0] for i, iterated_data in enumerate(iss_calculations):", "if len(self._sieves) == 0: summary += \"-\" else: for x", "self.name: str = name # list of FruitBranches self._branches: List[FruitBranch]", "pipeline, each branch returns their own features and they will", "( sum([s.nfeatures() for s in self._sieves]) * len(self._words) ) def", "specified for ISS calculation\") if not self._sieves: raise RuntimeError(\"No FeatureSieve", "len(self._branches) - 1 self._fitted = False def branch(self, index: int", "fruit.add(fruits.sieving.PPV(0.5)) fruit.add(fruits.sieving.END) # configure the fruit fruit.configure(mode=\"extended\") # fit the", "for the different time series. :param X: (Multidimensional) time series", "0: summary += \"-\" elif len(self._words) > 10: summary +=", "if isinstance(obj, DataPreparateur): self.add_preparateur(obj) elif isinstance(obj, Word): self.add_word(obj) elif isinstance(obj,", "options, have a look at :meth:`fruits.core.fruit.FruitBranch.configure`. :type kwargs: Any \"\"\"", "if (isinstance(self._fit_sample_size, int) and self._fit_sample_size == 1): ind = np.random.randint(0,", "DataPreparateur \"\"\" if not isinstance(preparateur, DataPreparateur): raise TypeError self._preparateurs.append(preparateur) self._fitted", "iterated_data[:, it, :], cache=self._cache, ) for callback in callbacks: callback.on_sieve(sieved_data[k:k+new_features])", "specified\") def _collect_cache_keys(self) -> Set[str]: # collects cache keys of", "Sums: The preprocessed data is now used to calculate the", "will be fitted on the iterated sums from the previous", "contains a summary for each FruitBranch in this Fruit object.", "feature sieves that were added to this branch.\"\"\" self._sieves =", "prep in self._preparateurs: prep.fit(prepared_data) prepared_data = prep.transform(prepared_data, cache=self._cache) self._sieves_extended =", "used in the ISS calculation self._calculator_options: dict = {\"batch_size\": 1,", "= [] self._words: list = [] self._sieves: list = []", "objects specified\") def _collect_cache_keys(self) -> Set[str]: # collects cache keys", "configured correctly and ready # for fitting if not self._words:", "sum([s.nfeatures() for s in self._sieves]) * len(self._words) ) def _compile(self):", "self._sieves: sieve_keys = sieve._get_cache_keys() if 'coquantile' in sieve_keys: keys =", "branches this Fruit object contains. :param X: (Multidimensional) time series", "and sieves. :rtype: str \"\"\" summary = \"{:-^80}\".format(\"fruits.FruitBranch\") summary +=", "int \"\"\" if self._calculator_options[\"mode\"] == \"extended\": return ( sum([s.nfeatures() for", "prep_keys = prep._get_cache_keys() if 'coquantile' in prep_keys: keys = keys.union(prep_keys['coquantile'])", "branch with the given index. :rtype: FruitBranch \"\"\" if index", "fruits.cache import Cache, CoquantileCache from fruits.scope import force_input_shape, FitTransform from", "dimensional feature array :rtype: np.ndarray \"\"\" self.fit(X) return self.transform(X) def", "or multiple object(s) to the branch. :type objects: One or", "the branch. :type objects: One or more objects of the", "steps. - Preparing data: Apply functions at the start of", ")[0] for i, iterated_data in enumerate(iss_calculations): for callback in callbacks:", "= prep._get_cache_keys() if 'coquantile' in prep_keys: keys = keys.union(prep_keys['coquantile']) for", "({len(self._preparateurs)}): \" if len(self._preparateurs) == 0: summary += \"-\" else:", "results (features) in a classifier ... The ``fruit`` above will", "\"\"\" return self._sieves def clear_sieves(self): \"\"\"Removes all feature sieves that", "{self.nfeatures()}\" for branch in self.branches(): summary += \"\\n\\n\" + branch.summary()", "result in ``2*8*2=32`` features per time series. \"\"\" def __init__(self,", ":rtype: int \"\"\" if self._calculator_options[\"mode\"] == \"extended\": return ( sum([s.nfeatures()", "FruitBranch object. :returns: Deepcopy of the branch with same settings", "= SignatureCalculator().transform( prepared_data, words=self._words, **self._calculator_options )[0] for iterated_data in iss_calculations:", "\"\"\"Returns all branches of this Fruit object. :rtype: list \"\"\"", ":type X: np.ndarray :param callbacks: List of callbacks. To write", "\"\"\"Fits the branch to the given dataset. What this action", "of all preparateurs added to the branch. :rtype: List[DataPreparateur] \"\"\"", "inspect from typing import List, Union, Set, Any import numpy", "override the class :class:`~fruits.core.callback.AbstractCallback`., defaults to [] :type callbacks: List[AbstractCallback],", "configuration. :param X: (Multidimensional) time series dataset as an array", "to the branch with the given index. :param index: Integer", "the current configuration produces. :rtype: int \"\"\" if self._calculator_options[\"mode\"] ==", "self._fitted: raise RuntimeError(\"Missing call of self.fit\") result = np.zeros((X.shape[0], self.nfeatures()))", "array :rtype: np.ndarray \"\"\" self.fit(X) return self.transform(X) def summary(self) ->", "contains. :param X: (Multidimensional) time series dataset as an array", "'coquantile' in prep_keys: keys = keys.union(prep_keys['coquantile']) for sieve in self._sieves:", "choose sieves fruit.add(fruits.sieving.PPV(0.5)) fruit.add(fruits.sieving.END) # add a new branch without", "np.ndarray: \"\"\"Returns a two dimensional array of all features from", "-> \"Fruit\": \"\"\"Creates a deep copy of this Fruit object.", "Fruit(self.name+\" (Copy)\") for branch in self._branches: copy_.fork(branch.deepcopy()) return copy_ class", "copy_.add(iterator) for sieve in self._sieves: copy_.add(sieve) return copy_ def deepcopy(self)", "def get_sieves(self) -> List[FeatureSieve]: \"\"\"Returns a list of all feature", "else: summary += \"\\n\\t+ \" + \\ \"\\n\\t+ \".join([str(x) for", "self._preparateurs: copy_.add(preparateur.copy()) for iterator in self._words: copy_.add(iterator.copy()) for sieve in", "of this FruitBranch object. :returns: Deepcopy of the branch with", ":type callbacks: List[AbstractCallback], optional :rtype: np.ndarray :raises: RuntimeError if ``self.fit``", "in self._preparateurs: prepared_data = prep.transform(prepared_data, cache=self._cache) for callback in callbacks:", "\"\"\" self._compile() self._get_cache(X) prepared_data = self._select_fit_sample(X) for prep in self._preparateurs:", "added to this branch.\"\"\" self._sieves = [] self._sieve_prerequisites = None", "for the current branch index self._cbi: int = 0 self._fitted:", "the branch. :rtype: List[FeatureSieve] \"\"\" return self._sieves def clear_sieves(self): \"\"\"Removes", "np.zeros((prepared_data.shape[0], self.nfeatures())) k = 0 iss_calculations = SignatureCalculator().transform( prepared_data, words=self._words,", "fruit.add(fruits.sieving.END) # configure the fruit fruit.configure(mode=\"extended\") # fit the fruit", "= 0 self._fitted: bool = False @property def name(self) ->", "\"\"\" def __init__(self, name: str = \"\"): self.name: str =", "look at :meth:`~fruits.scope.force_input_shape`. :type X: np.ndarray :param callbacks: List of", "copy_ = Fruit(self.name+\" (Copy)\") for branch in self._branches: copy_.fork(branch.copy()) return", "to the branch will be fitted on the iterated sums", "TypeError self._preparateurs.append(preparateur) self._fitted = False def get_preparateurs(self) -> List[DataPreparateur]: \"\"\"Returns", "will be concatenated by this class. A simple example (using", "pipeline. If none is given, an empty FruitBranch will be", "= branch.transform(X, callbacks) index += k result = np.nan_to_num(result, copy=False,", "the branch is cleared, it has the same settings as", "= False def add_sieve(self, sieve: FeatureSieve): \"\"\"Appends a new feature", "of the following types: - :class:`~fruits.preparation.abstract.DataPreparateur` - :class:`~fruits.words.word.Word` - :class:`~fruits.sieving.abstract.FeatureSieve`", "+= f\"\\nBranches: {len(self.branches())}\" summary += f\"\\nFeatures: {self.nfeatures()}\" for branch in", "sieve: FeatureSieve): \"\"\"Appends a new feature sieve to the FruitBranch.", "specific output # of an ISS-result self._sieves_extended: list = []", "Extractor using iterated sums. A Fruit consists of a number", "the branch. :type preparateur: DataPreparateur \"\"\" if not isinstance(preparateur, DataPreparateur):", "callbacks: callback.on_preparateur(prepared_data) for callback in callbacks: callback.on_preparation_end(prepared_data) sieved_data = np.zeros((prepared_data.shape[0],", "None): \"\"\"Adds a new branch to the pipeline. If none", "self._words: raise RuntimeError(\"No words specified for ISS calculation\") if not", "self._words.append(word) self._fitted = False def get_words(self) -> List[Word]: \"\"\"Returns a", ":]) self._sieves_extended.append(sieves_copy) self._fitted = True def transform(self, X: np.ndarray, callbacks:", "False def add_word(self, word: Word): \"\"\"Adds a word to the", "mode: str, optional :param batch_size: See :meth:`~ruits.signature.iss.SignatureCalculator.transform`, defaults to None", "for s in self._sieves]) * CachePlan(self._words).n_iterated_sums( list(range(len(self._words))) ) ) else:", "(using two branches): .. code-block:: python fruit = fruits.Fruit(\"My Fruit\")", "fruit.add(fruits.sieving.END) # add a new branch without INC fruit.fork() fruit.add(fruits.words.creation.simplewords_by_weight(4))", "creates shallow copies of all branches in this object. :rtype:", "FitTransformers in the branch keys: Set[str] = set() for prep", "if 'coquantile' in prep_keys: keys = keys.union(prep_keys['coquantile']) for sieve in", "all branches combined. :rtype: int \"\"\" return sum([branch.nfeatures() for branch", "index: int = None): \"\"\"Returns the currently selected branch or", "an ISS-result self._sieves_extended: list = [] # configurations for fitting", "for different :class:`~fruits.words.word.Word` objects the user can specify. - Extracting", "branch = FruitBranch() self._branches.append(branch) self._cbi = len(self._branches) - 1 self._fitted", "self._branches: copy_.fork(branch.copy()) return copy_ def deepcopy(self) -> \"Fruit\": \"\"\"Creates a", "used in the # transformation process self._cache: Cache def configure(self,", "..., len(self.branches())-1]`` :type index: int \"\"\" if not (0 <=", "prep in self._preparateurs: prep_keys = prep._get_cache_keys() if 'coquantile' in prep_keys:", "copy_ = FruitBranch() for preparateur in self._preparateurs: copy_.add(preparateur.copy()) for iterator", "None: branch = FruitBranch() self._branches.append(branch) self._cbi = len(self._branches) - 1", ":class:`~fruits.core.callback.AbstractCallback`., defaults to None :type callbacks: List[AbstractCallback], optional :rtype: np.ndarray", "the given dataset and returns the transformed results of X", "self._sieves]) * CachePlan(self._words).n_iterated_sums( list(range(len(self._words))) ) ) else: return ( sum([s.nfeatures()", "fruits.preparation.abstract import DataPreparateur class Fruit: \"\"\"Feature Extractor using iterated sums.", "is now used to calculate the iterated sums signature for", "for fitting if (isinstance(self._fit_sample_size, int) and self._fit_sample_size == 1): ind", "sums from the previous step. The branch then returns an", "objects of the following types: - :class:`~fruits.preparation.abstract.DataPreparateur` - :class:`~fruits.words.word.Word` -", "for preprocessing. The preparateurs will be applied sequentially to the", "self._preparateurs: prepared_data = prep.transform(prepared_data, cache=self._cache) for callback in callbacks: callback.on_preparateur(prepared_data)", "+ lines[0] summary += \"\\n\\t \" summary += \"\\n\\t \".join(lines[1:])", "dataset fruit.fit(X_train) # transform the dataset X_train_transformed = fruit.transform(X_train) X_test_tranformed", "branch. :rtype: List[Word] \"\"\" return self._words def clear_words(self): \"\"\"Removes all", "self._fitted = False def branch(self, index: int = None): \"\"\"Returns", "_get_cache(self, X: np.ndarray): # returns the already processed cache needed", "object contains. :param X: (Multidimensional) time series dataset as an", "sieves. :rtype: str \"\"\" summary = \"{:-^80}\".format(\"fruits.FruitBranch\") summary += f\"\\nNumber", "for iterator in self._words: copy_.add(iterator) for sieve in self._sieves: copy_.add(sieve)", "clear_sieves(self): \"\"\"Removes all feature sieves that were added to this", "FruitBranch object extracts values from time series data that are", "def clear_words(self): \"\"\"Removes all words that were added to this", ":param callbacks: List of callbacks. To write your own callback,", "is not None: self._fit_sample_size = fit_sample_size def add_preparateur(self, preparateur: DataPreparateur):", "configurations and calculated results the branch has. After the branch", "above will result in ``2*8*2=32`` features per time series. \"\"\"", "if arguments differ from ``None``. :param kwargs: For possible options,", "branch.nfeatures() result[:, index:index+k] = branch.transform(X, callbacks) index += k result", "a float which will be multiplied by ``X.shape[0]`` or ``1``", "self.transform(X) def summary(self) -> str: \"\"\"Returns a summary of this", "= []) -> np.ndarray: \"\"\"Transforms the given time series dataset.", "from the previous step. The branch then returns an array", "also creates shallow copies of all branches in this object.", "branch in self.branches(): summary += \"\\n\\n\" + branch.summary() summary +=", "**self._calculator_options )[0] for i, iterated_data in enumerate(iss_calculations): for callback in", "f\"\\nNumber of features: {self.nfeatures()}\" summary += f\"\\n\\nPreparateurs ({len(self._preparateurs)}): \" if", "look at :meth:`fruits.core.fruit.FruitBranch.configure`. :type kwargs: Any \"\"\" for branch in", "\"-\" elif len(self._words) > 10: summary += \"\\n\\t+ \" +", "DataPreparateur): raise TypeError self._preparateurs.append(preparateur) self._fitted = False def get_preparateurs(self) ->", "shallow copies of all branches in this object. :rtype: Fruit", "will be created and switched to. :type branch: FruitBranch, optional", "# for fitting if not self._words: raise RuntimeError(\"No words specified", "checks if the FruitBranch is configured correctly and ready #", "the data used for fitting if (isinstance(self._fit_sample_size, int) and self._fit_sample_size", "for sieve in sieves_copy: sieve.fit(iterated_data[:, :]) self._sieves_extended.append(sieves_copy) self._fitted = True", "cache=self._cache) for callback in callbacks: callback.on_preparateur(prepared_data) for callback in callbacks:", "total number of features of all branches combined. :rtype: int", "np.ndarray): \"\"\"Fits the branch to the given dataset. What this", "int \"\"\" if not (0 <= index < len(self._branches)): raise", "Apply functions at the start of the extraction procedure. There", "a summary of this object. The summary contains all added", "def fit(self, X: np.ndarray): \"\"\"Fits all branches to the given", "is calculated at fitting and also used in the #", "self._preparateurs]) summary += f\"\\nIterators ({len(self._words)}): \" if len(self._words) == 0:", "\"\\n\\t+ \" + \\ \"\\n\\t+ \".join([str(x) for x in self._words[:9]])", "fruits.core.callback import AbstractCallback from fruits.signature.iss import SignatureCalculator, CachePlan from fruits.words.word", "Word] \"\"\" if len(self._branches) == 0: self.fork() self._branches[self._cbi].add(*objects) self._fitted =", "s in self._sieves]) * len(self._words) ) def _compile(self): # checks", "FruitBranch \"\"\" copy_ = FruitBranch() for preparateur in self._preparateurs: copy_.add(preparateur.copy())", "the following three steps. - Preparing data: Apply functions at", "bool = False @property def name(self) -> str: \"\"\"Simple identifier", "index. :rtype: FruitBranch \"\"\" if index is None: return self._branches[self._cbi]", "in iss_calculations: iterated_data = iterated_data.reshape(iterated_data.shape[0] * iterated_data.shape[1], iterated_data.shape[2]) sieves_copy =", "The ``fruit`` above will result in ``2*8*2=32`` features per time", "callback in callbacks: callback.on_iterated_sum(iterated_data) for sieve in self._sieves_extended[i]: nf =", "\"\"\" copy_ = Fruit(self.name+\" (Copy)\") for branch in self._branches: copy_.fork(branch.deepcopy())", "+ \\ \"\\n\\t+ \".join([str(x) for x in self._preparateurs]) summary +=", "self._compile() self._get_cache(X) prepared_data = self._select_fit_sample(X) for prep in self._preparateurs: prep.fit(prepared_data)", "from those sieves), i.e. the features for each time series.", "somehow representative of the input data. The user can customize", "\"\"\" if not isinstance(preparateur, DataPreparateur): raise TypeError self._preparateurs.append(preparateur) self._fitted =", "_select_fit_sample(self, X: np.ndarray) -> np.ndarray: # returns a sample of", "fruit.transform(X_train) X_test_tranformed = fruit.transform(X_test) # use the transformed results (features)", "{\"batch_size\": 1, \"mode\": \"single\"} def nfeatures(self) -> int: \"\"\"Returns the", "str = \"\"): self.name: str = name # list of", "summary += f\"\\nFeatures: {self.nfeatures()}\" for branch in self.branches(): summary +=", "summary += \"\\n\\t...\" else: summary += \"\\n\\t+ \" + \\", "\"\"\"Returns a list of all preparateurs added to the branch.", "branch to the pipeline. If none is given, an empty", "summary += f\"\\n\\nPreparateurs ({len(self._preparateurs)}): \" if len(self._preparateurs) == 0: summary", "own callback, override the class :class:`~fruits.core.callback.AbstractCallback`., defaults to None :type", "for branch in self._branches: copy_.fork(branch.deepcopy()) return copy_ class FruitBranch: \"\"\"One", "callback in callbacks: callback.on_preparation_end(prepared_data) sieved_data = np.zeros((prepared_data.shape[0], self.nfeatures())) k =", "procedure. There are many so called :class:`~fruits.preparation.abstract.DataPreparateur` objects in fruits", "= [] # configurations for fitting self._fitted: bool = False", "X[indices, :, :] def fit(self, X: np.ndarray): \"\"\"Fits the branch", "kwargs: Any \"\"\" for branch in self._branches: branch.configure(**kwargs) def fit(self,", "Set, Any import numpy as np from fruits.cache import Cache,", "number of features of all branches combined. :rtype: int \"\"\"", "\"\"\"Makes changes to the default configuration of a all branches", "the following types: - :class:`~fruits.preparation.abstract.DataPreparateur` - :class:`~fruits.words.word.Word` - :class:`~fruits.sieving.abstract.FeatureSieve` \"\"\"", "= keys.union(prep_keys['coquantile']) for sieve in self._sieves: sieve_keys = sieve._get_cache_keys() if", "\"\"\"Transforms the given time series dataset. The results are the", "is None: branch = FruitBranch() self._branches.append(branch) self._cbi = len(self._branches) -", "10: summary += \"\\n\\t+ \" + \\ \"\\n\\t+ \".join([str(x) for", "in this branch self._cache = CoquantileCache() self._cache.process(X, list(self._collect_cache_keys())) def _select_fit_sample(self,", "\"\\n\\t+ \".join([str(x) for x in self._words[:9]]) summary += \"\\n\\t...\" else:", "series. :param X: (Multidimensional) time series dataset as an array", "index < len(self._branches)): raise IndexError(\"Index has to be in [0,", "[0, len(self.branches()))\") self._cbi = index def add(self, *objects: Union[FitTransform, Word,", "and calculated results the branch has. After the branch is", "* len(self._words) ) def _compile(self): # checks if the FruitBranch", "-> \"FruitBranch\": \"\"\"Returns a deep copy of this FruitBranch object.", "return self.transform(X) def summary(self) -> str: \"\"\"Returns a summary of", "Fruit object. :rtype: str \"\"\" summary = \"{:=^80}\".format(f\"Summary of fruits.Fruit:", "data processing self._preparateurs: list = [] self._words: list = []", "return self._branches[index] def branches(self) -> list: \"\"\"Returns all branches of", "a list of all feature sieves added to the branch.", "copies of all branches in this object. :rtype: Fruit \"\"\"", "self._branches.append(branch) self._cbi = len(self._branches) - 1 self._fitted = False def", "name: str): self._name = name def fork(self, branch: \"FruitBranch\" =", "x.summary().split(\"\\n\") summary += \"\\n\\t+ \" + lines[0] summary += \"\\n\\t", "keys.union(prep_keys['coquantile']) for sieve in self._sieves: sieve_keys = sieve._get_cache_keys() if 'coquantile'", "(Copy)\") for branch in self._branches: copy_.fork(branch.copy()) return copy_ def deepcopy(self)", "from fruits.signature.iss import SignatureCalculator, CachePlan from fruits.words.word import Word from", "== 0: summary += \"-\" elif len(self._words) > 10: summary", "object. A FruitBranch object extracts values from time series data", "Word \"\"\" if not isinstance(word, Word): raise TypeError self._words.append(word) self._fitted", "return copy_ def deepcopy(self) -> \"FruitBranch\": \"\"\"Returns a deep copy", "dataset. The results are the calculated features for the different", "X: np.ndarray) -> np.ndarray: # returns a sample of the", "process self._cache: Cache def configure(self, mode: str = None, batch_size:", "isinstance(obj, FeatureSieve): self.add_sieve(obj) else: raise TypeError(\"Cannot add variable of type\"+str(type(obj)))", "it in range(iterated_data.shape[1]): sieved_data[:, k+it*nf:k+(it+1)*nf] = sieve.transform( iterated_data[:, it, :],", "= nf * iterated_data.shape[1] for it in range(iterated_data.shape[1]): sieved_data[:, k+it*nf:k+(it+1)*nf]", "is represented as a float which will be multiplied by", "\" summary += \"\\n\\t \".join(lines[1:]) return summary def copy(self) ->", "\" if len(self._preparateurs) == 0: summary += \"-\" else: summary", "summary += \"\\n{:=^80}\".format(f\"End of Summary\") return summary def copy(self) ->", "at the start of the extraction procedure. There are many", "Word, type]): \"\"\"Adds one or multiple object(s) to the branch.", "i, iterated_data in enumerate(iss_calculations): for callback in callbacks: callback.on_iterated_sum(iterated_data) for", "used to calculate the iterated sums signature for different :class:`~fruits.words.word.Word`", "optional: add preparateurs for preprocessing fruit.add(fruits.preparation.INC) # add words for", "callbacks) index += k result = np.nan_to_num(result, copy=False, nan=0.0) return", "= mode if batch_size is not None: self._calculator_options[\"batch_size\"] = batch_size", "\".join([str(x) for x in self._preparateurs]) summary += f\"\\nIterators ({len(self._words)}): \"", "is None: return self._branches[self._cbi] return self._branches[index] def branches(self) -> list:", "branch.summary() summary += \"\\n{:=^80}\".format(f\"End of Summary\") return summary def copy(self)", "in self._branches]) def configure(self, **kwargs: Any): \"\"\"Makes changes to the", "keys of all FitTransformers in the branch keys: Set[str] =", "* iterated_data.shape[1], iterated_data.shape[2]) sieves_copy = [sieve.copy() for sieve in self._sieves]", "objects: Union[FitTransform, Word] \"\"\" if len(self._branches) == 0: self.fork() self._branches[self._cbi].add(*objects)", "all calculations done erased. :rtype: FruitBranch \"\"\" copy_ = FruitBranch()", "time series dataset as an array of three dimensions. Have", "iterated_data.shape[1] for it in range(iterated_data.shape[1]): sieved_data[:, k+it*nf:k+(it+1)*nf] = sieve.transform( iterated_data[:,", "\"\"\" return self._words def clear_words(self): \"\"\"Removes all words that were", "with the given index. :rtype: FruitBranch \"\"\" if index is", "from fruits.sieving.abstract import FeatureSieve from fruits.preparation.abstract import DataPreparateur class Fruit:", "sieve: FeatureSieve \"\"\" if not isinstance(sieve, FeatureSieve): raise TypeError self._sieves.append(sieve)", "def switch_branch(self, index: int): \"\"\"Switches to the branch with the", "with the given index. :param index: Integer in ``[0, 1,", "len(self._preparateurs) == 0: summary += \"-\" else: summary += \"\\n\\t+", "objects: One or more objects of the following types: -", "in objects_flattened: if inspect.isclass(obj): obj = obj() if isinstance(obj, DataPreparateur):", "\"\"\" return self._preparateurs def clear_preparateurs(self): \"\"\"Removes all preparateurs that were", "List[Word] \"\"\" return self._words def clear_words(self): \"\"\"Removes all words that", "a list of all preparateurs added to the branch. :rtype:", "list of all words in the branch. :rtype: List[Word] \"\"\"", "user can specify. - Extracting Features: Each :class:`~fruits.sieving.abstract.FeatureSieve` added to", "None): \"\"\"Makes changes to the default configuration of a fruit", "extraction procedure. There are many so called :class:`~fruits.preparation.abstract.DataPreparateur` objects in", "the random time series sample that is used for fitting.", "else: raise TypeError(\"Cannot add variable of type\"+str(type(obj))) def clear(self): \"\"\"Clears", "callbacks: List of callbacks. To write your own callback, override", "self._preparateurs: prep_keys = prep._get_cache_keys() if 'coquantile' in prep_keys: keys =", "* X.shape[0]) if s < 1: s = 1 indices", "be multiplied by ``X.shape[0]`` or ``1`` for one random time", ":class:`~fruits.sieving.abstract.FeatureSieve` :type objects: Union[FitTransform, Word] \"\"\" if len(self._branches) == 0:", "x in self._preparateurs]) summary += f\"\\nIterators ({len(self._words)}): \" if len(self._words)", "if len(self._preparateurs) == 0: summary += \"-\" else: summary +=", "for callback in callbacks: callback.on_preparation_end(prepared_data) sieved_data = np.zeros((prepared_data.shape[0], self.nfeatures())) k", "\"\"\"Returns a shallow copy of this FruitBranch object. :returns: Copy", "prepared_data, words=self._words, **self._calculator_options )[0] for i, iterated_data in enumerate(iss_calculations): for", "per time series. \"\"\" def __init__(self, name: str = \"\"):", "def add_word(self, word: Word): \"\"\"Adds a word to the branch.", "+ branch.summary() summary += \"\\n{:=^80}\".format(f\"End of Summary\") return summary def", "in self._sieves]) * len(self._words) ) def _compile(self): # checks if", ") def _compile(self): # checks if the FruitBranch is configured", "After the branch is cleared, it has the same settings", "erased. :rtype: FruitBranch \"\"\" copy_ = FruitBranch() for preparateur in", "keys: Set[str] = set() for prep in self._preparateurs: prep_keys =", "List[AbstractCallback] = []) -> np.ndarray: \"\"\"Transforms the given time series", "this FruitBranch object. :returns: Deepcopy of the branch with same", "branch in self._branches: branch.fit(X) self._fitted = True def transform(self, X:", "one specific output # of an ISS-result self._sieves_extended: list =", "self.nfeatures())) k = 0 iss_calculations = SignatureCalculator().transform( prepared_data, words=self._words, **self._calculator_options", "X: (Multidimensional) time series dataset :type X: np.ndarray :returns: Two", "-> \"FruitBranch\": \"\"\"Returns a shallow copy of this FruitBranch object.", "self.clear_preparateurs() self.clear_words() self.clear_sieves() self._calculator_options = {\"batch_size\": 1, \"mode\": \"single\"} def", "1, \"mode\": \"single\"} # list with inner lists containing sieves", "= fruit.transform(X_test) # use the transformed results (features) in a", "+= \"-\" else: summary += \"\\n\\t+ \" + \\ \"\\n\\t+", "np.ndarray, callbacks: List[AbstractCallback] = []) -> np.ndarray: \"\"\"Returns a two", "\"\"\" if not (0 <= index < len(self._branches)): raise IndexError(\"Index", "RuntimeError(\"No words specified for ISS calculation\") if not self._sieves: raise", "has the same settings as a newly created FruitBranch object.", "the already processed cache needed in this branch self._cache =", "multiplied by ``X.shape[0]`` or ``1`` for one random time series.,", "[] # configurations for fitting self._fitted: bool = False self._fit_sample_size:", ":type objects: Union[FitTransform, Word] \"\"\" if len(self._branches) == 0: self.fork()", "the input data. The user can customize any of the", "callback, override the class :class:`~fruits.core.callback.AbstractCallback`., defaults to None :type callbacks:", "a shallow copy of this Fruit object. This also creates", "used for fitting. This is represented as a float which", "add_preparateur(self, preparateur: DataPreparateur): \"\"\"Adds a preparateur to the branch. :type", "for x in self._words]) summary += f\"\\nSieves ({len(self._sieves)}): \" if", "new branch to the pipeline. If none is given, an", "self._select_fit_sample(X) for prep in self._preparateurs: prep.fit(prepared_data) prepared_data = prep.transform(prepared_data, cache=self._cache)", "self.fit\") self._get_cache(X) prepared_data = force_input_shape(X) for prep in self._preparateurs: prepared_data", "cache=self._cache, ) for callback in callbacks: callback.on_sieve(sieved_data[k:k+new_features]) k += new_features", "s in self._sieves]) * CachePlan(self._words).n_iterated_sums( list(range(len(self._words))) ) ) else: return", "from all branches this Fruit object contains. :param X: (Multidimensional)", "for prep in self._preparateurs: prepared_data = prep.transform(prepared_data, cache=self._cache) for callback", "branches): .. code-block:: python fruit = fruits.Fruit(\"My Fruit\") # optional:", "is configured correctly and ready # for fitting if not", "were added to this branch.\"\"\" self._words = [] self._sieves_extended =", "({len(self._sieves)}): \" if len(self._sieves) == 0: summary += \"-\" else:", ":type batch_size: int, optional :param fit_sample_size: Size of the random", "[] self._sieve_prerequisites = None self._sieves_extended = [] self._fitted = False", "\"{:-^80}\".format(\"fruits.FruitBranch\") summary += f\"\\nNumber of features: {self.nfeatures()}\" summary += f\"\\n\\nPreparateurs", "X.shape[0]) return X[ind:ind+1, :, :] else: s = int(self._fit_sample_size *", "and also used in the # transformation process self._cache: Cache", "= sieve._get_cache_keys() if 'coquantile' in sieve_keys: keys = keys.union(sieve_keys['coquantile']) return", "result = np.nan_to_num(result, copy=False, nan=0.0) return result def fit_transform(self, X:", "list = [] # calculator options used in the ISS", "to the branch. :rtype: List[DataPreparateur] \"\"\" return self._preparateurs def clear_preparateurs(self):", "of all branches combined. :rtype: int \"\"\" return sum([branch.nfeatures() for", "it, :], cache=self._cache, ) for callback in callbacks: callback.on_sieve(sieved_data[k:k+new_features]) k", "the pipeline. If none is given, an empty FruitBranch will", "summary += \"-\" else: summary += \"\\n\\t+ \" + \\", "if fit_sample_size is not None: self._fit_sample_size = fit_sample_size def add_preparateur(self,", "Integer in ``[0, 1, ..., len(self.branches())-1]`` :type index: int \"\"\"", "+= \"\\n\\t \".join(lines[1:]) return summary def copy(self) -> \"FruitBranch\": \"\"\"Returns", "callbacks: callback.on_sieving_end(sieved_data) return sieved_data def fit_transform(self, X: np.ndarray) -> np.ndarray:", "summary = \"{:=^80}\".format(f\"Summary of fruits.Fruit: '{self.name}'\") summary += f\"\\nBranches: {len(self.branches())}\"", "# pointer for the current branch index self._cbi: int =", "optional :param batch_size: See :meth:`~ruits.signature.iss.SignatureCalculator.transform`, defaults to None :type batch_size:", "step. The branch then returns an array of numbers (the", "FruitBranch. :type sieve: FeatureSieve \"\"\" if not isinstance(sieve, FeatureSieve): raise", "self._sieves]) * len(self._words) ) def _compile(self): # checks if the", "branches of this Fruit object. :rtype: list \"\"\" return self._branches", "calculations done erased. :rtype: FruitBranch \"\"\" copy_ = FruitBranch() for", ":param X: (Multidimensional) time series dataset :type X: np.ndarray :returns:", "callbacks: List[AbstractCallback], optional :rtype: np.ndarray :raises: RuntimeError if ``self.fit`` wasn't", "FruitBranch \"\"\" if index is None: return self._branches[self._cbi] return self._branches[index]", "has. After the branch is cleared, it has the same", "to the branch. :type objects: One or more objects of", "fruit on a time series dataset fruit.fit(X_train) # transform the", "X.shape[0]) if s < 1: s = 1 indices =", "optional :rtype: np.ndarray :raises: RuntimeError if ``self.fit`` wasn't called \"\"\"", "\"\"\" if len(self._branches) == 0: self.fork() self._branches[self._cbi].add(*objects) self._fitted = False", "\"{:=^80}\".format(f\"Summary of fruits.Fruit: '{self.name}'\") summary += f\"\\nBranches: {len(self.branches())}\" summary +=", "array of three dimensions. Have a look at `:meth:`~fruits.scope.force_input_shape`. :type", "self._sieves_extended.append(sieves_copy) self._fitted = True def transform(self, X: np.ndarray, callbacks: List[AbstractCallback]", "int, optional :param fit_sample_size: Size of the random time series", "for prep in self._preparateurs: prep.fit(prepared_data) prepared_data = prep.transform(prepared_data, cache=self._cache) self._sieves_extended", "for callback in callbacks: callback.on_sieving_end(sieved_data) return sieved_data def fit_transform(self, X:", "are somehow representative of the input data. The user can", "nfeatures(self) -> int: \"\"\"Returns the total number of features the", "all settings, configurations and calculated results the branch has. After", "* iterated_data.shape[1] for it in range(iterated_data.shape[1]): sieved_data[:, k+it*nf:k+(it+1)*nf] = sieve.transform(", "\"\"\"Returns the total number of features the current configuration produces.", "\"\"\" summary = \"{:=^80}\".format(f\"Summary of fruits.Fruit: '{self.name}'\") summary += f\"\\nBranches:", "action explicitly does depends on the FruitBranch configuration. :param X:", "object. :rtype: list \"\"\" return self._branches def switch_branch(self, index: int):", "classifier ... The ``fruit`` above will result in ``2*8*2=32`` features", "in self._branches: for callback in callbacks: callback.on_next_branch() k = branch.nfeatures()", "by this class. A simple example (using two branches): ..", "sieved_data[:, k+it*nf:k+(it+1)*nf] = sieve.transform( iterated_data[:, it, :], cache=self._cache, ) for", "-> int: \"\"\"Returns the total number of features the current", "self._preparateurs: prep.fit(prepared_data) prepared_data = prep.transform(prepared_data, cache=self._cache) self._sieves_extended = [] iss_calculations", "= sieve.transform( iterated_data[:, it, :], cache=self._cache, ) for callback in", "branch in self._branches: for callback in callbacks: callback.on_next_branch() k =", "transform(self, X: np.ndarray, callbacks: List[AbstractCallback] = []) -> np.ndarray: \"\"\"Returns", "# add a new branch without INC fruit.fork() fruit.add(fruits.words.creation.simplewords_by_weight(4)) fruit.add(fruits.sieving.PPV(0.5))", "= 1 # cache that is calculated at fitting and", "configuration of a all branches if arguments differ from ``None``.", "+= k result = np.nan_to_num(result, copy=False, nan=0.0) return result def", "return ( sum([s.nfeatures() for s in self._sieves]) * len(self._words) )", "1 self._fitted = False def branch(self, index: int = None):", "obj in objects_flattened: if inspect.isclass(obj): obj = obj() if isinstance(obj,", "= None): \"\"\"Adds a new branch to the pipeline. If", "'coquantile' in sieve_keys: keys = keys.union(sieve_keys['coquantile']) return keys def _get_cache(self,", "List[AbstractCallback], optional :rtype: np.ndarray :raises: RuntimeError if Fruit.fit wasn't called", ":meth:`~fruits.scope.force_input_shape`. :type X: np.ndarray \"\"\" for branch in self._branches: branch.fit(X)", "list with inner lists containing sieves # all sieves in", "Cache def configure(self, mode: str = None, batch_size: int =", "not self._fitted: raise RuntimeError(\"Missing call of self.fit\") result = np.zeros((X.shape[0],", "self._branches: copy_.fork(branch.deepcopy()) return copy_ class FruitBranch: \"\"\"One branch of a", "self._preparateurs = [] self._fitted = False def add_word(self, word: Word):", "different time series. :param X: (Multidimensional) time series dataset as", "this Fruit object contains. :param X: (Multidimensional) time series dataset", "self._cbi = len(self._branches) - 1 self._fitted = False def branch(self,", "= None): \"\"\"Makes changes to the default configuration of a", "= 0 for branch in self._branches: for callback in callbacks:", "\"\"\"Returns a summary of this object. The summary contains all", "the class :class:`~fruits.core.callback.AbstractCallback`., defaults to [] :type callbacks: List[AbstractCallback], optional", "``2*8*2=32`` features per time series. \"\"\" def __init__(self, name: str", "index self._cbi: int = 0 self._fitted: bool = False @property", ":rtype: np.ndarray \"\"\" self.fit(X) return self.transform(X) def summary(self) -> str:", "as an array of three dimensions. Have a look at", "variable of type\"+str(type(obj))) def clear(self): \"\"\"Clears all settings, configurations and", "callback.on_sieving_end(sieved_data) return sieved_data def fit_transform(self, X: np.ndarray) -> np.ndarray: \"\"\"This", "combined. :rtype: int \"\"\" return sum([branch.nfeatures() for branch in self._branches])", "fruits.Fruit: '{self.name}'\") summary += f\"\\nBranches: {len(self.branches())}\" summary += f\"\\nFeatures: {self.nfeatures()}\"", "= np.nan_to_num(result, copy=False, nan=0.0) return result def fit_transform(self, X: np.ndarray)", "np.ndarray): \"\"\"Fits all branches to the given data. :param X:", "time series. \"\"\" def __init__(self, name: str = \"\"): self.name:", "return self._name @name.setter def name(self, name: str): self._name = name", "Union, Set, Any import numpy as np from fruits.cache import", "fitting and also used in the # transformation process self._cache:", "sample of the data used for fitting if (isinstance(self._fit_sample_size, int)", "calculation self._calculator_options: dict = {\"batch_size\": 1, \"mode\": \"single\"} # list", "fitting. This is represented as a float which will be", "summary = \"{:-^80}\".format(\"fruits.FruitBranch\") summary += f\"\\nNumber of features: {self.nfeatures()}\" summary", "if arguments differ from ``None``. :param mode: See :meth:`fruits.signature.iss.SignatureCalculator.transform`, defaults", "len(self._branches) == 0: self.fork() self._branches[self._cbi].add(*objects) self._fitted = False def nfeatures(self)", "Fruit object.\"\"\" return self._name @name.setter def name(self, name: str): self._name", "of features: {self.nfeatures()}\" summary += f\"\\n\\nPreparateurs ({len(self._preparateurs)}): \" if len(self._preparateurs)", "sieves fruit.add(fruits.sieving.PPV(0.5)) fruit.add(fruits.sieving.END) # add a new branch without INC", "* CachePlan(self._words).n_iterated_sums( list(range(len(self._words))) ) ) else: return ( sum([s.nfeatures() for", "def fork(self, branch: \"FruitBranch\" = None): \"\"\"Adds a new branch", "of FruitBranches self._branches: List[FruitBranch] = [] # pointer for the", "to None :type callbacks: List[AbstractCallback], optional :rtype: np.ndarray :raises: RuntimeError", "but all calculations done erased. :rtype: FruitBranch \"\"\" copy_ =", "three dimensions. Have a look at `:meth:`~fruits.scope.force_input_shape`. :type X: np.ndarray", ":raises: RuntimeError if Fruit.fit wasn't called \"\"\" if not self._fitted:", "at `:meth:`~fruits.scope.force_input_shape`. :type X: np.ndarray :returns: Array of features. :rtype:", "word to the branch. :type word: Word \"\"\" if not", "the given dataset. What this action explicitly does depends on", "import Cache, CoquantileCache from fruits.scope import force_input_shape, FitTransform from fruits.core.callback", "returns the already processed cache needed in this branch self._cache", "for iterated_data in iss_calculations: iterated_data = iterated_data.reshape(iterated_data.shape[0] * iterated_data.shape[1], iterated_data.shape[2])", "time series., defaults to 1 :type fit_sample_size: Union[float, int] \"\"\"", ":type mode: str, optional :param batch_size: See :meth:`~ruits.signature.iss.SignatureCalculator.transform`, defaults to", "np.ndarray): # returns the already processed cache needed in this", "new_features = nf * iterated_data.shape[1] for it in range(iterated_data.shape[1]): sieved_data[:,", "\" if len(self._sieves) == 0: summary += \"-\" else: for", "current configuration produces. :rtype: int \"\"\" if self._calculator_options[\"mode\"] == \"extended\":", "FruitBranch \"\"\" copy_ = FruitBranch() for preparateur in self._preparateurs: copy_.add(preparateur)", "(Multidimensional) time series dataset :type X: np.ndarray :returns: Two dimensional", "self._cache.process(X, list(self._collect_cache_keys())) def _select_fit_sample(self, X: np.ndarray) -> np.ndarray: # returns", "of the data used for fitting if (isinstance(self._fit_sample_size, int) and", "Fruit\") # optional: add preparateurs for preprocessing fruit.add(fruits.preparation.INC) # add", "Calculating Iterated Sums: The preprocessed data is now used to", "self._fitted = False def get_preparateurs(self) -> List[DataPreparateur]: \"\"\"Returns a list", "summary += \"\\n\\t+ \" + lines[0] summary += \"\\n\\t \"", "Size of the random time series sample that is used", ":meth:`fruits.signature.iss.SignatureCalculator.transform`, defaults to None :type mode: str, optional :param batch_size:", ":rtype: int \"\"\" return sum([branch.nfeatures() for branch in self._branches]) def", "data. :param X: (Multidimensional) time series dataset as an array", "\"Fruit\": \"\"\"Creates a shallow copy of this Fruit object. This", ":returns: Deepcopy of the branch with same settings but all", "= [sieve.copy() for sieve in self._sieves] for sieve in sieves_copy:", "for callback in callbacks: callback.on_preparateur(prepared_data) for callback in callbacks: callback.on_preparation_end(prepared_data)", "def fit_transform(self, X: np.ndarray) -> np.ndarray: \"\"\"This function does the", "callback.on_next_branch() k = branch.nfeatures() result[:, index:index+k] = branch.transform(X, callbacks) index", "branch then returns an array of numbers (the transformed results", "a classifier ... The ``fruit`` above will result in ``2*8*2=32``", "of the random time series sample that is used for", "FeatureSieve objects specified\") def _collect_cache_keys(self) -> Set[str]: # collects cache", "fruit.add(fruits.words.creation.simplewords_by_weight(4)) fruit.add(fruits.sieving.PPV(0.5)) fruit.add(fruits.sieving.END) # configure the fruit fruit.configure(mode=\"extended\") # fit", "all branches if arguments differ from ``None``. :param kwargs: For", "of callbacks. To write your own callback, override the class", "``1`` for one random time series., defaults to 1 :type", "- :class:`~fruits.preparation.abstract.DataPreparateur` - :class:`~fruits.words.word.Word` - :class:`~fruits.sieving.abstract.FeatureSieve` \"\"\" objects_flattened = np.array(objects,", "write your own callback, override the class :class:`~fruits.core.callback.AbstractCallback`., defaults to", "Union[float, int] \"\"\" if mode is not None: self._calculator_options[\"mode\"] =", "RuntimeError(\"No FeatureSieve objects specified\") def _collect_cache_keys(self) -> Set[str]: # collects", "int(self._fit_sample_size * X.shape[0]) if s < 1: s = 1", "the branch. :type word: Word \"\"\" if not isinstance(word, Word):", "keys.union(sieve_keys['coquantile']) return keys def _get_cache(self, X: np.ndarray): # returns the", "from fruits.cache import Cache, CoquantileCache from fruits.scope import force_input_shape, FitTransform", "this class. A simple example (using two branches): .. code-block::", "else: s = int(self._fit_sample_size * X.shape[0]) if s < 1:", "copy=False, nan=0.0) return result def fit_transform(self, X: np.ndarray) -> np.ndarray:", "\"\\n\\t+ \".join([str(x) for x in self._preparateurs]) summary += f\"\\nIterators ({len(self._words)}):", "x in self._sieves: lines = x.summary().split(\"\\n\") summary += \"\\n\\t+ \"", "def __init__(self): # lists of used classes for data processing", "def add(self, *objects: Union[FitTransform, Word, type]): \"\"\"Adds one or multiple", "sequentially to the input data. - Calculating Iterated Sums: The", "object. :returns: Deepcopy of the branch with same settings but", "the same settings as a newly created FruitBranch object. \"\"\"", "three steps. - Preparing data: Apply functions at the start", "without INC fruit.fork() fruit.add(fruits.words.creation.simplewords_by_weight(4)) fruit.add(fruits.sieving.PPV(0.5)) fruit.add(fruits.sieving.END) # configure the fruit", "object(s) to the currently selected branch. :param objects: One or", "= prep.transform(prepared_data, cache=self._cache) for callback in callbacks: callback.on_preparateur(prepared_data) for callback", "\"\"\"Returns a summary of this object. The summary contains a", "raise RuntimeError(\"Missing call of self.fit\") self._get_cache(X) prepared_data = force_input_shape(X) for", "if not self._fitted: raise RuntimeError(\"Missing call of self.fit\") result =", "prepared_data = prep.transform(prepared_data, cache=self._cache) self._sieves_extended = [] iss_calculations = SignatureCalculator().transform(", "prep_keys: keys = keys.union(prep_keys['coquantile']) for sieve in self._sieves: sieve_keys =", "array of three dimensions. Have a look at :meth:`~fruits.scope.force_input_shape`. :type", "= False def branch(self, index: int = None): \"\"\"Returns the", "this action explicitly does depends on the FruitBranch configuration. :param", "self._words]) summary += f\"\\nSieves ({len(self._sieves)}): \" if len(self._sieves) == 0:", "series sample that is used for fitting. This is represented", "the calculated features for the different time series. :param X:", "functions at the start of the extraction procedure. There are", "so called :class:`~fruits.preparation.abstract.DataPreparateur` objects in fruits available for preprocessing. The", "in self._words: copy_.add(iterator) for sieve in self._sieves: copy_.add(sieve) return copy_", "= obj() if isinstance(obj, DataPreparateur): self.add_preparateur(obj) elif isinstance(obj, Word): self.add_word(obj)", ":type sieve: FeatureSieve \"\"\" if not isinstance(sieve, FeatureSieve): raise TypeError", "= Fruit(self.name+\" (Copy)\") for branch in self._branches: copy_.fork(branch.deepcopy()) return copy_", "ISS calculation\") if not self._sieves: raise RuntimeError(\"No FeatureSieve objects specified\")", "fitted on the iterated sums from the previous step. The", "summary def copy(self) -> \"Fruit\": \"\"\"Creates a shallow copy of", "fitting self._fitted: bool = False self._fit_sample_size: Union[float, int] = 1", "= x.summary().split(\"\\n\") summary += \"\\n\\t+ \" + lines[0] summary +=", "def _compile(self): # checks if the FruitBranch is configured correctly", "this object. :rtype: Fruit \"\"\" copy_ = Fruit(self.name+\" (Copy)\") for", "self.fit\") result = np.zeros((X.shape[0], self.nfeatures())) index = 0 for branch", "-> List[Word]: \"\"\"Returns a list of all words in the", "callbacks: List[AbstractCallback] = []) -> np.ndarray: \"\"\"Returns a two dimensional", "self._sieves] for sieve in sieves_copy: sieve.fit(iterated_data[:, :]) self._sieves_extended.append(sieves_copy) self._fitted =", "from typing import List, Union, Set, Any import numpy as", "self._preparateurs.append(preparateur) self._fitted = False def get_preparateurs(self) -> List[DataPreparateur]: \"\"\"Returns a", "\"-\" else: summary += \"\\n\\t+ \" + \\ \"\\n\\t+ \".join([str(x)", "for each time series. \"\"\" def __init__(self): # lists of", "\"\"\"Makes changes to the default configuration of a fruit branch", "collects cache keys of all FitTransformers in the branch keys:", "wasn't called \"\"\" if not self._fitted: raise RuntimeError(\"Missing call of", "not None: self._calculator_options[\"mode\"] = mode if batch_size is not None:", "concatenated by this class. A simple example (using two branches):", "of this Fruit object. :rtype: list \"\"\" return self._branches def", "a Fruit object. A FruitBranch object extracts values from time", "of a fruit branch if arguments differ from ``None``. :param", ":returns: Two dimensional feature array :rtype: np.ndarray \"\"\" self.fit(X) return", "will be multiplied by ``X.shape[0]`` or ``1`` for one random", "+= f\"\\nFeatures: {self.nfeatures()}\" for branch in self.branches(): summary += \"\\n\\n\"", "code-block:: python fruit = fruits.Fruit(\"My Fruit\") # optional: add preparateurs", "any of the following three steps. - Preparing data: Apply", "dataset X_train_transformed = fruit.transform(X_train) X_test_tranformed = fruit.transform(X_test) # use the", "raise RuntimeError(\"No FeatureSieve objects specified\") def _collect_cache_keys(self) -> Set[str]: #", "len(self._words) == 0: summary += \"-\" elif len(self._words) > 10:", "callbacks: List[AbstractCallback] = []) -> np.ndarray: \"\"\"Transforms the given time", "added preparateurs, words and sieves. :rtype: str \"\"\" summary =", "The summary contains all added preparateurs, words and sieves. :rtype:", "callbacks: callback.on_sieve(sieved_data[k:k+new_features]) k += new_features for callback in callbacks: callback.on_sieving_end(sieved_data)", "int] \"\"\" if mode is not None: self._calculator_options[\"mode\"] = mode", "to the branch. :rtype: List[FeatureSieve] \"\"\" return self._sieves def clear_sieves(self):", "for fitting if not self._words: raise RuntimeError(\"No words specified for", "input data. - Calculating Iterated Sums: The preprocessed data is", "each FruitBranch in this Fruit object. :rtype: str \"\"\" summary", "add_sieve(self, sieve: FeatureSieve): \"\"\"Appends a new feature sieve to the", "X: np.ndarray) -> np.ndarray: \"\"\"Fits all branches to the given", "same that calling ``self.fit(X)`` and ``self.transform(X)`` consecutively does. :param X:", "branch without INC fruit.fork() fruit.add(fruits.words.creation.simplewords_by_weight(4)) fruit.add(fruits.sieving.PPV(0.5)) fruit.add(fruits.sieving.END) # configure the", "transformed results (features) in a classifier ... The ``fruit`` above", "Extracting Features: Each :class:`~fruits.sieving.abstract.FeatureSieve` added to the branch will be", "fit_sample_size def add_preparateur(self, preparateur: DataPreparateur): \"\"\"Adds a preparateur to the", "of features of all branches combined. :rtype: int \"\"\" return", "iterated_data = iterated_data.reshape(iterated_data.shape[0] * iterated_data.shape[1], iterated_data.shape[2]) sieves_copy = [sieve.copy() for", "= False def nfeatures(self) -> int: \"\"\"Returns the total number", "Word): raise TypeError self._words.append(word) self._fitted = False def get_words(self) ->", "\"\\n\\t+ \" + \\ \"\\n\\t+ \".join([str(x) for x in self._words])", "\"\\n\\t \" summary += \"\\n\\t \".join(lines[1:]) return summary def copy(self)", "new_features for callback in callbacks: callback.on_sieving_end(sieved_data) return sieved_data def fit_transform(self,", ":type objects: One or more objects of the following types:", "self._fitted = False def add_word(self, word: Word): \"\"\"Adds a word", "X: np.ndarray :param callbacks: List of callbacks. To write your", "time series dataset :type X: np.ndarray :returns: Two dimensional feature", "copy of this FruitBranch object. :returns: Deepcopy of the branch", "- 1 self._fitted = False def branch(self, index: int =", "Fruit object. This also creates shallow copies of all branches", "does. :param X: (Multidimensional) time series dataset as an array", "self._preparateurs: copy_.add(preparateur) for iterator in self._words: copy_.add(iterator) for sieve in", "a list of all words in the branch. :rtype: List[Word]", "branch if arguments differ from ``None``. :param mode: See :meth:`fruits.signature.iss.SignatureCalculator.transform`,", "are the calculated features for the different time series. :param", "copy_.fork(branch.copy()) return copy_ def deepcopy(self) -> \"Fruit\": \"\"\"Creates a deep", "(features) in a classifier ... The ``fruit`` above will result", "len(self.branches())-1]`` :type index: int \"\"\" if not (0 <= index", "def clear_preparateurs(self): \"\"\"Removes all preparateurs that were added to this", "iterator in self._words: copy_.add(iterator) for sieve in self._sieves: copy_.add(sieve) return", "all branches in this object. :rtype: Fruit \"\"\" copy_ =", "branch in self._branches]) def configure(self, **kwargs: Any): \"\"\"Makes changes to", "the total number of features the current configuration produces. :rtype:", "will result in ``2*8*2=32`` features per time series. \"\"\" def", ":] else: s = int(self._fit_sample_size * X.shape[0]) if s <", "k = 0 iss_calculations = SignatureCalculator().transform( prepared_data, words=self._words, **self._calculator_options )[0]", "k += new_features for callback in callbacks: callback.on_sieving_end(sieved_data) return sieved_data", "the given index. :param index: Integer in ``[0, 1, ...,", "a deep copy of this FruitBranch object. :returns: Deepcopy of", "series dataset as an array of three dimensions. Have a", "FruitBranch() for preparateur in self._preparateurs: copy_.add(preparateur) for iterator in self._words:", "are trained on one specific output # of an ISS-result", "= False self._fit_sample_size: Union[float, int] = 1 # cache that", "a newly created FruitBranch object. \"\"\" self.clear_preparateurs() self.clear_words() self.clear_sieves() self._calculator_options", "= FruitBranch() for preparateur in self._preparateurs: copy_.add(preparateur.copy()) for iterator in", "the branch has. After the branch is cleared, it has", "# returns the already processed cache needed in this branch", "index: int \"\"\" if not (0 <= index < len(self._branches)):", "The preparateurs will be applied sequentially to the input data.", "fruit.add(fruits.sieving.PPV(0.5)) fruit.add(fruits.sieving.END) # add a new branch without INC fruit.fork()", "in range(iterated_data.shape[1]): sieved_data[:, k+it*nf:k+(it+1)*nf] = sieve.transform( iterated_data[:, it, :], cache=self._cache,", "feature sieves added to the branch. :rtype: List[FeatureSieve] \"\"\" return", "branch self._cache = CoquantileCache() self._cache.process(X, list(self._collect_cache_keys())) def _select_fit_sample(self, X: np.ndarray)", "python fruit = fruits.Fruit(\"My Fruit\") # optional: add preparateurs for", "\"\"): self.name: str = name # list of FruitBranches self._branches:", "object.\"\"\" return self._name @name.setter def name(self, name: str): self._name =", "array of all features from all branches this Fruit object", "= np.random.choice(X.shape[0], size=s, replace=False) return X[indices, :, :] def fit(self,", "# lists of used classes for data processing self._preparateurs: list", "fruits.signature.iss import SignatureCalculator, CachePlan from fruits.words.word import Word from fruits.sieving.abstract", "return ( sum([s.nfeatures() for s in self._sieves]) * CachePlan(self._words).n_iterated_sums( list(range(len(self._words)))", "{self.nfeatures()}\" summary += f\"\\n\\nPreparateurs ({len(self._preparateurs)}): \" if len(self._preparateurs) == 0:", ":rtype: FruitBranch \"\"\" copy_ = FruitBranch() for preparateur in self._preparateurs:", "has to be in [0, len(self.branches()))\") self._cbi = index def", "object extracts values from time series data that are somehow", "Copy of the branch with same settings but all calculations", ":rtype: List[DataPreparateur] \"\"\" return self._preparateurs def clear_preparateurs(self): \"\"\"Removes all preparateurs", "branch will be fitted on the iterated sums from the", "kwargs: For possible options, have a look at :meth:`fruits.core.fruit.FruitBranch.configure`. :type", "mode is not None: self._calculator_options[\"mode\"] = mode if batch_size is", "s < 1: s = 1 indices = np.random.choice(X.shape[0], size=s,", "def summary(self) -> str: \"\"\"Returns a summary of this object.", "\"\"\"Simple identifier for the Fruit object.\"\"\" return self._name @name.setter def", "self._words = [] self._sieves_extended = [] self._fitted = False def", "branches to the given dataset and returns the transformed results", "\" + lines[0] summary += \"\\n\\t \" summary += \"\\n\\t", "import AbstractCallback from fruits.signature.iss import SignatureCalculator, CachePlan from fruits.words.word import", "series dataset. The results are the calculated features for the", "FruitBranches self._branches: List[FruitBranch] = [] # pointer for the current", "= force_input_shape(X) for prep in self._preparateurs: prepared_data = prep.transform(prepared_data, cache=self._cache)", "+= \"\\n\\t+ \" + lines[0] summary += \"\\n\\t \" summary", "time series sample that is used for fitting. This is", "return X[ind:ind+1, :, :] else: s = int(self._fit_sample_size * X.shape[0])", "deep copy of this FruitBranch object. :returns: Deepcopy of the", "raise TypeError self._words.append(word) self._fitted = False def get_words(self) -> List[Word]:", "callback.on_preparateur(prepared_data) for callback in callbacks: callback.on_preparation_end(prepared_data) sieved_data = np.zeros((prepared_data.shape[0], self.nfeatures()))", "new feature sieve to the FruitBranch. :type sieve: FeatureSieve \"\"\"", "configuration of a fruit branch if arguments differ from ``None``.", "+= \"\\n\\t+ \" + \\ \"\\n\\t+ \".join([str(x) for x in", "name # list of FruitBranches self._branches: List[FruitBranch] = [] #", "in self._preparateurs]) summary += f\"\\nIterators ({len(self._words)}): \" if len(self._words) ==", "To write your own callback, override the class :class:`~fruits.core.callback.AbstractCallback`., defaults", "the # transformation process self._cache: Cache def configure(self, mode: str", "in callbacks: callback.on_next_branch() k = branch.nfeatures() result[:, index:index+k] = branch.transform(X,", "feature sieve to the FruitBranch. :type sieve: FeatureSieve \"\"\" if", "at :meth:`~fruits.scope.force_input_shape`. :type X: np.ndarray \"\"\" self._compile() self._get_cache(X) prepared_data =", "copy(self) -> \"FruitBranch\": \"\"\"Returns a shallow copy of this FruitBranch", ":rtype: np.ndarray :raises: RuntimeError if Fruit.fit wasn't called \"\"\" if", "False def get_preparateurs(self) -> List[DataPreparateur]: \"\"\"Returns a list of all", "SignatureCalculator, CachePlan from fruits.words.word import Word from fruits.sieving.abstract import FeatureSieve", "{\"batch_size\": 1, \"mode\": \"single\"} # list with inner lists containing", "RuntimeError(\"Missing call of self.fit\") result = np.zeros((X.shape[0], self.nfeatures())) index =", "called \"\"\" if not self._fitted: raise RuntimeError(\"Missing call of self.fit\")", "to [] :type callbacks: List[AbstractCallback], optional :rtype: np.ndarray :raises: RuntimeError", "ready # for fitting if not self._words: raise RuntimeError(\"No words", "transform the dataset X_train_transformed = fruit.transform(X_train) X_test_tranformed = fruit.transform(X_test) #", "configure(self, **kwargs: Any): \"\"\"Makes changes to the default configuration of", "None: self._fit_sample_size = fit_sample_size def add_preparateur(self, preparateur: DataPreparateur): \"\"\"Adds a", "creates deep copies of all branches in this object. :rtype:", "if 'coquantile' in sieve_keys: keys = keys.union(sieve_keys['coquantile']) return keys def", "fitting if not self._words: raise RuntimeError(\"No words specified for ISS", "for iterated sums calculation fruit.add(fruits.words.creation.simplewords_by_weight(4)) # choose sieves fruit.add(fruits.sieving.PPV(0.5)) fruit.add(fruits.sieving.END)", "if not self._fitted: raise RuntimeError(\"Missing call of self.fit\") self._get_cache(X) prepared_data", "this Fruit object. :rtype: list \"\"\" return self._branches def switch_branch(self,", "def _select_fit_sample(self, X: np.ndarray) -> np.ndarray: # returns a sample", "branch has. After the branch is cleared, it has the", "\"\"\"Adds a new branch to the pipeline. If none is", "in the branch. :rtype: List[Word] \"\"\" return self._words def clear_words(self):", "iterated_data in enumerate(iss_calculations): for callback in callbacks: callback.on_iterated_sum(iterated_data) for sieve", "branches. :param X: (Multidimensional) time series dataset :type X: np.ndarray", "data that are somehow representative of the input data. The", "if the FruitBranch is configured correctly and ready # for", "def _collect_cache_keys(self) -> Set[str]: # collects cache keys of all", "cache=self._cache) self._sieves_extended = [] iss_calculations = SignatureCalculator().transform( prepared_data, words=self._words, **self._calculator_options", ":meth:`~fruits.scope.force_input_shape`. :type X: np.ndarray :param callbacks: List of callbacks. To", "add(self, *objects: Union[FitTransform, Word, type]): \"\"\"Adds one or multiple object(s)", "return summary def copy(self) -> \"FruitBranch\": \"\"\"Returns a shallow copy", "for branch in self._branches: branch.fit(X) self._fitted = True def transform(self,", "same settings but all calculations done erased. :rtype: FruitBranch \"\"\"", "[] self._sieves_extended = [] self._fitted = False def add_sieve(self, sieve:", "self._words: list = [] self._sieves: list = [] # calculator", "fork(self, branch: \"FruitBranch\" = None): \"\"\"Adds a new branch to", "created FruitBranch object. \"\"\" self.clear_preparateurs() self.clear_words() self.clear_sieves() self._calculator_options = {\"batch_size\":", "None, batch_size: int = None, fit_sample_size: Union[float, int] = None):", "\"\"\"Adds one or multiple object(s) to the currently selected branch.", "- :class:`~fruits.words.word.Word` - :class:`~fruits.sieving.abstract.FeatureSieve` \"\"\" objects_flattened = np.array(objects, dtype=object).flatten() for", "for iterator in self._words: copy_.add(iterator.copy()) for sieve in self._sieves: copy_.add(sieve.copy())", "nf = sieve.nfeatures() new_features = nf * iterated_data.shape[1] for it", "\"\"\" return self._branches def switch_branch(self, index: int): \"\"\"Switches to the", "can specify. - Extracting Features: Each :class:`~fruits.sieving.abstract.FeatureSieve` added to the", "inner lists containing sieves # all sieves in one list", "end of the pipeline, each branch returns their own features", "branch. :type word: Word \"\"\" if not isinstance(word, Word): raise", "= 1 indices = np.random.choice(X.shape[0], size=s, replace=False) return X[indices, :,", "= fit_sample_size def add_preparateur(self, preparateur: DataPreparateur): \"\"\"Adds a preparateur to", "k result = np.nan_to_num(result, copy=False, nan=0.0) return result def fit_transform(self,", "\"extended\": return ( sum([s.nfeatures() for s in self._sieves]) * CachePlan(self._words).n_iterated_sums(", "str = name # list of FruitBranches self._branches: List[FruitBranch] =", "summary for each FruitBranch in this Fruit object. :rtype: str", "preparateur in self._preparateurs: copy_.add(preparateur.copy()) for iterator in self._words: copy_.add(iterator.copy()) for", "\"\"\"Returns the currently selected branch or the branch with the", "\"\"\"Returns the total number of features of all branches combined.", "look at :meth:`~fruits.scope.force_input_shape`. :type X: np.ndarray \"\"\" for branch in", "this branch.\"\"\" self._sieves = [] self._sieve_prerequisites = None self._sieves_extended =", "random time series., defaults to 1 :type fit_sample_size: Union[float, int]", "it has the same settings as a newly created FruitBranch", "X: np.ndarray) -> np.ndarray: \"\"\"This function does the same that", "data used for fitting if (isinstance(self._fit_sample_size, int) and self._fit_sample_size ==", "ind = np.random.randint(0, X.shape[0]) return X[ind:ind+1, :, :] else: s", "0: self.fork() self._branches[self._cbi].add(*objects) self._fitted = False def nfeatures(self) -> int:", "np.random.randint(0, X.shape[0]) return X[ind:ind+1, :, :] else: s = int(self._fit_sample_size", "self._sieves: lines = x.summary().split(\"\\n\") summary += \"\\n\\t+ \" + lines[0]", "= index def add(self, *objects: Union[FitTransform, Word, type]): \"\"\"Adds one", ":param fit_sample_size: Size of the random time series sample that", "object. The summary contains a summary for each FruitBranch in", "all branches to the given dataset and returns the transformed", ":param mode: See :meth:`fruits.signature.iss.SignatureCalculator.transform`, defaults to None :type mode: str,", "to the FruitBranch. :type sieve: FeatureSieve \"\"\" if not isinstance(sieve,", "Word from fruits.sieving.abstract import FeatureSieve from fruits.preparation.abstract import DataPreparateur class", "in ``2*8*2=32`` features per time series. \"\"\" def __init__(self, name:", "one or multiple object(s) to the currently selected branch. :param", "if mode is not None: self._calculator_options[\"mode\"] = mode if batch_size", "those sieves), i.e. the features for each time series. \"\"\"", "List[DataPreparateur]: \"\"\"Returns a list of all preparateurs added to the", "isinstance(sieve, FeatureSieve): raise TypeError self._sieves.append(sieve) self._fitted = False def get_sieves(self)", "+= \"\\n{:=^80}\".format(f\"End of Summary\") return summary def copy(self) -> \"Fruit\":", "for callback in callbacks: callback.on_sieve(sieved_data[k:k+new_features]) k += new_features for callback", "\"\"\"Appends a new feature sieve to the FruitBranch. :type sieve:", ":type kwargs: Any \"\"\" for branch in self._branches: branch.configure(**kwargs) def", "np.ndarray, callbacks: List[AbstractCallback] = []) -> np.ndarray: \"\"\"Transforms the given", "defaults to None :type mode: str, optional :param batch_size: See", "that were added to this branch.\"\"\" self._preparateurs = [] self._fitted", "a summary of this object. The summary contains a summary", "of three dimensions. Have a look at :meth:`~fruits.scope.force_input_shape`. :type X:", "also used in the # transformation process self._cache: Cache def", "Fruit object. A FruitBranch object extracts values from time series", "def name(self) -> str: \"\"\"Simple identifier for the Fruit object.\"\"\"", "iterated sums from the previous step. The branch then returns", "len(self._words) > 10: summary += \"\\n\\t+ \" + \\ \"\\n\\t+", "in self._words]) summary += f\"\\nSieves ({len(self._sieves)}): \" if len(self._sieves) ==", "X: np.ndarray \"\"\" self._compile() self._get_cache(X) prepared_data = self._select_fit_sample(X) for prep", "self._sieves: list = [] # calculator options used in the", "... The ``fruit`` above will result in ``2*8*2=32`` features per", "self._sieves_extended[i]: nf = sieve.nfeatures() new_features = nf * iterated_data.shape[1] for", "return self._branches[self._cbi] return self._branches[index] def branches(self) -> list: \"\"\"Returns all", "object. This also creates deep copies of all branches in", "Have a look at :meth:`~fruits.scope.force_input_shape`. :type X: np.ndarray \"\"\" self._compile()", ":type callbacks: List[AbstractCallback], optional :rtype: np.ndarray :raises: RuntimeError if Fruit.fit", "branch is None: branch = FruitBranch() self._branches.append(branch) self._cbi = len(self._branches)", "in self._branches: copy_.fork(branch.copy()) return copy_ def deepcopy(self) -> \"Fruit\": \"\"\"Creates", "features: {self.nfeatures()}\" summary += f\"\\n\\nPreparateurs ({len(self._preparateurs)}): \" if len(self._preparateurs) ==", "available for preprocessing. The preparateurs will be applied sequentially to", "changes to the default configuration of a all branches if", "self._words[:9]]) summary += \"\\n\\t...\" else: summary += \"\\n\\t+ \" +", "clear_words(self): \"\"\"Removes all words that were added to this branch.\"\"\"", "words in the branch. :rtype: List[Word] \"\"\" return self._words def", "number of :class:`~fruits.core.fruit.FruitBranch` objects. At the end of the pipeline,", "optional \"\"\" if branch is None: branch = FruitBranch() self._branches.append(branch)", "all words in the branch. :rtype: List[Word] \"\"\" return self._words", "int: \"\"\"Returns the total number of features of all branches", "FruitBranch in this Fruit object. :rtype: str \"\"\" summary =", "[] iss_calculations = SignatureCalculator().transform( prepared_data, words=self._words, **self._calculator_options )[0] for iterated_data", "fruit.transform(X_test) # use the transformed results (features) in a classifier", "none is given, an empty FruitBranch will be created and", "override the class :class:`~fruits.core.callback.AbstractCallback`., defaults to None :type callbacks: List[AbstractCallback],", "SignatureCalculator().transform( prepared_data, words=self._words, **self._calculator_options )[0] for iterated_data in iss_calculations: iterated_data", "self._words: copy_.add(iterator.copy()) for sieve in self._sieves: copy_.add(sieve.copy()) copy_._calculator_options = self._calculator_options.copy()", "if ``self.fit`` wasn't called \"\"\" if not self._fitted: raise RuntimeError(\"Missing", "dataset and returns the transformed results of X from all", "possible options, have a look at :meth:`fruits.core.fruit.FruitBranch.configure`. :type kwargs: Any", "A FruitBranch object extracts values from time series data that", ":param objects: One or more objects of the following types:", "on the FruitBranch configuration. :param X: (Multidimensional) time series dataset", "prepared_data = force_input_shape(X) for prep in self._preparateurs: prepared_data = prep.transform(prepared_data,", "\"\\n\\t+ \" + \\ \"\\n\\t+ \".join([str(x) for x in self._preparateurs])", "self._fitted = False def add(self, *objects: Union[FitTransform, Word, type]): \"\"\"Adds", "\"\"\" return sum([branch.nfeatures() for branch in self._branches]) def configure(self, **kwargs:", "copy_.add(preparateur) for iterator in self._words: copy_.add(iterator) for sieve in self._sieves:", "if not isinstance(sieve, FeatureSieve): raise TypeError self._sieves.append(sieve) self._fitted = False", "branch. :rtype: List[DataPreparateur] \"\"\" return self._preparateurs def clear_preparateurs(self): \"\"\"Removes all", "of the pipeline, each branch returns their own features and", "This is represented as a float which will be multiplied", ":class:`~fruits.preparation.abstract.DataPreparateur` - :class:`~fruits.words.word.Word` - :class:`~fruits.sieving.abstract.FeatureSieve` \"\"\" objects_flattened = np.array(objects, dtype=object).flatten()", "= [] self._fitted = False def add(self, *objects: Union[FitTransform, Word,", "dimensional array of all features from all branches this Fruit", ":rtype: str \"\"\" summary = \"{:=^80}\".format(f\"Summary of fruits.Fruit: '{self.name}'\") summary", "The user can customize any of the following three steps.", "``self.fit(X)`` and ``self.transform(X)`` consecutively does. :param X: (Multidimensional) time series", "in self._sieves: copy_.add(sieve) return copy_ def deepcopy(self) -> \"FruitBranch\": \"\"\"Returns", "two dimensional array of all features from all branches this", "int \"\"\" return sum([branch.nfeatures() for branch in self._branches]) def configure(self,", "to the given dataset and returns the transformed results of", "self._fit_sample_size == 1): ind = np.random.randint(0, X.shape[0]) return X[ind:ind+1, :,", "Fruit \"\"\" copy_ = Fruit(self.name+\" (Copy)\") for branch in self._branches:", "self._branches[index] def branches(self) -> list: \"\"\"Returns all branches of this", "List[Word]: \"\"\"Returns a list of all words in the branch.", "lists of used classes for data processing self._preparateurs: list =", "@property def name(self) -> str: \"\"\"Simple identifier for the Fruit", "np.ndarray \"\"\" for branch in self._branches: branch.fit(X) self._fitted = True", "branch.\"\"\" self._words = [] self._sieves_extended = [] self._fitted = False", "def add_sieve(self, sieve: FeatureSieve): \"\"\"Appends a new feature sieve to", "len(self.branches()))\") self._cbi = index def add(self, *objects: Union[FitTransform, Word, type]):", "calculation\") if not self._sieves: raise RuntimeError(\"No FeatureSieve objects specified\") def", "an array of three dimensions. Have a look at `:meth:`~fruits.scope.force_input_shape`.", "an array of numbers (the transformed results from those sieves),", "index: Integer in ``[0, 1, ..., len(self.branches())-1]`` :type index: int", "int] = 1 # cache that is calculated at fitting", ":type X: np.ndarray \"\"\" self._compile() self._get_cache(X) prepared_data = self._select_fit_sample(X) for", "calculation fruit.add(fruits.words.creation.simplewords_by_weight(4)) # choose sieves fruit.add(fruits.sieving.PPV(0.5)) fruit.add(fruits.sieving.END) # add a", "\"\"\"Fits all branches to the given data. :param X: (Multidimensional)", "that calling ``self.fit(X)`` and ``self.transform(X)`` consecutively does. :param X: (Multidimensional)", "fitting if (isinstance(self._fit_sample_size, int) and self._fit_sample_size == 1): ind =", "a new branch without INC fruit.fork() fruit.add(fruits.words.creation.simplewords_by_weight(4)) fruit.add(fruits.sieving.PPV(0.5)) fruit.add(fruits.sieving.END) #", "\"mode\": \"single\"} # list with inner lists containing sieves #", "fruit fruit.configure(mode=\"extended\") # fit the fruit on a time series", "and self._fit_sample_size == 1): ind = np.random.randint(0, X.shape[0]) return X[ind:ind+1,", "of this object. The summary contains all added preparateurs, words", "# calculator options used in the ISS calculation self._calculator_options: dict", "Fruit consists of a number of :class:`~fruits.core.fruit.FruitBranch` objects. At the", "class FruitBranch: \"\"\"One branch of a Fruit object. A FruitBranch", "one list are trained on one specific output # of", ":, :] def fit(self, X: np.ndarray): \"\"\"Fits the branch to", "preparateur: DataPreparateur): \"\"\"Adds a preparateur to the branch. :type preparateur:", "if not isinstance(preparateur, DataPreparateur): raise TypeError self._preparateurs.append(preparateur) self._fitted = False", "\"\"\"Feature Extractor using iterated sums. A Fruit consists of a", "signature for different :class:`~fruits.words.word.Word` objects the user can specify. -", "CoquantileCache() self._cache.process(X, list(self._collect_cache_keys())) def _select_fit_sample(self, X: np.ndarray) -> np.ndarray: #", "for sieve in self._sieves] for sieve in sieves_copy: sieve.fit(iterated_data[:, :])", ":type word: Word \"\"\" if not isinstance(word, Word): raise TypeError", "X: np.ndarray \"\"\" for branch in self._branches: branch.fit(X) self._fitted =", "batch_size: See :meth:`~ruits.signature.iss.SignatureCalculator.transform`, defaults to None :type batch_size: int, optional", "``[0, 1, ..., len(self.branches())-1]`` :type index: int \"\"\" if not", "prep._get_cache_keys() if 'coquantile' in prep_keys: keys = keys.union(prep_keys['coquantile']) for sieve", "added to the branch will be fitted on the iterated", "iss_calculations = SignatureCalculator().transform( prepared_data, words=self._words, **self._calculator_options )[0] for i, iterated_data", "index def add(self, *objects: Union[FitTransform, Word, type]): \"\"\"Adds one or", "data. - Calculating Iterated Sums: The preprocessed data is now", "[sieve.copy() for sieve in self._sieves] for sieve in sieves_copy: sieve.fit(iterated_data[:,", "features per time series. \"\"\" def __init__(self, name: str =", "object. :rtype: str \"\"\" summary = \"{:=^80}\".format(f\"Summary of fruits.Fruit: '{self.name}'\")", "add variable of type\"+str(type(obj))) def clear(self): \"\"\"Clears all settings, configurations", "from fruits.core.callback import AbstractCallback from fruits.signature.iss import SignatureCalculator, CachePlan from", "elif len(self._words) > 10: summary += \"\\n\\t+ \" + \\", "= branch.nfeatures() result[:, index:index+k] = branch.transform(X, callbacks) index += k", "branch with the given index. :param index: Integer in ``[0,", "preparateurs will be applied sequentially to the input data. -", "\"mode\": \"single\"} def nfeatures(self) -> int: \"\"\"Returns the total number", "List[FeatureSieve]: \"\"\"Returns a list of all feature sieves added to", "__init__(self, name: str = \"\"): self.name: str = name #", "\"\\n\\t+ \" + lines[0] summary += \"\\n\\t \" summary +=", "< len(self._branches)): raise IndexError(\"Index has to be in [0, len(self.branches()))\")", "RuntimeError(\"Missing call of self.fit\") self._get_cache(X) prepared_data = force_input_shape(X) for prep", "= FruitBranch() self._branches.append(branch) self._cbi = len(self._branches) - 1 self._fitted =", "INC fruit.fork() fruit.add(fruits.words.creation.simplewords_by_weight(4)) fruit.add(fruits.sieving.PPV(0.5)) fruit.add(fruits.sieving.END) # configure the fruit fruit.configure(mode=\"extended\")", "+= \"\\n\\t \" summary += \"\\n\\t \".join(lines[1:]) return summary def", "called :class:`~fruits.preparation.abstract.DataPreparateur` objects in fruits available for preprocessing. The preparateurs", "= \"\"): self.name: str = name # list of FruitBranches", "isinstance(obj, Word): self.add_word(obj) elif isinstance(obj, FeatureSieve): self.add_sieve(obj) else: raise TypeError(\"Cannot", "iterator in self._words: copy_.add(iterator.copy()) for sieve in self._sieves: copy_.add(sieve.copy()) copy_._calculator_options", "= iterated_data.reshape(iterated_data.shape[0] * iterated_data.shape[1], iterated_data.shape[2]) sieves_copy = [sieve.copy() for sieve", "results are the calculated features for the different time series.", "the pipeline, each branch returns their own features and they", "the dataset X_train_transformed = fruit.transform(X_train) X_test_tranformed = fruit.transform(X_test) # use", "\"\"\"Returns a deep copy of this FruitBranch object. :returns: Deepcopy", "-> Set[str]: # collects cache keys of all FitTransformers in", "in callbacks: callback.on_sieve(sieved_data[k:k+new_features]) k += new_features for callback in callbacks:", "FeatureSieve \"\"\" if not isinstance(sieve, FeatureSieve): raise TypeError self._sieves.append(sieve) self._fitted", "fruits.words.word import Word from fruits.sieving.abstract import FeatureSieve from fruits.preparation.abstract import", "in self._sieves: lines = x.summary().split(\"\\n\") summary += \"\\n\\t+ \" +", ":class:`~fruits.words.word.Word` - :class:`~fruits.sieving.abstract.FeatureSieve` :type objects: Union[FitTransform, Word] \"\"\" if len(self._branches)", "calculated features for the different time series. :param X: (Multidimensional)", "types: - :class:`~fruits.preparation.abstract.DataPreparateur` - :class:`~fruits.words.word.Word` - :class:`~fruits.sieving.abstract.FeatureSieve` \"\"\" objects_flattened =", "TypeError(\"Cannot add variable of type\"+str(type(obj))) def clear(self): \"\"\"Clears all settings,", "obj() if isinstance(obj, DataPreparateur): self.add_preparateur(obj) elif isinstance(obj, Word): self.add_word(obj) elif", "a word to the branch. :type word: Word \"\"\" if", ":returns: Array of features. :rtype: np.ndarray \"\"\" self.fit(X) return self.transform(X)", "correctly and ready # for fitting if not self._words: raise", "elif isinstance(obj, FeatureSieve): self.add_sieve(obj) else: raise TypeError(\"Cannot add variable of", "X_test_tranformed = fruit.transform(X_test) # use the transformed results (features) in", "int) and self._fit_sample_size == 1): ind = np.random.randint(0, X.shape[0]) return", "in callbacks: callback.on_preparateur(prepared_data) for callback in callbacks: callback.on_preparation_end(prepared_data) sieved_data =", "preprocessing fruit.add(fruits.preparation.INC) # add words for iterated sums calculation fruit.add(fruits.words.creation.simplewords_by_weight(4))", "which will be multiplied by ``X.shape[0]`` or ``1`` for one", "iterated sums calculation fruit.add(fruits.words.creation.simplewords_by_weight(4)) # choose sieves fruit.add(fruits.sieving.PPV(0.5)) fruit.add(fruits.sieving.END) #", "with same settings but all calculations done erased. :rtype: FruitBranch", "= fruits.Fruit(\"My Fruit\") # optional: add preparateurs for preprocessing fruit.add(fruits.preparation.INC)", "self._cbi = index def add(self, *objects: Union[FitTransform, Word, type]): \"\"\"Adds", "-> List[DataPreparateur]: \"\"\"Returns a list of all preparateurs added to", "time series. :param X: (Multidimensional) time series dataset as an", "in self._words[:9]]) summary += \"\\n\\t...\" else: summary += \"\\n\\t+ \"", "self._fitted: raise RuntimeError(\"Missing call of self.fit\") self._get_cache(X) prepared_data = force_input_shape(X)", ":rtype: str \"\"\" summary = \"{:-^80}\".format(\"fruits.FruitBranch\") summary += f\"\\nNumber of", "for the Fruit object.\"\"\" return self._name @name.setter def name(self, name:", "this object. The summary contains all added preparateurs, words and", "prep.transform(prepared_data, cache=self._cache) self._sieves_extended = [] iss_calculations = SignatureCalculator().transform( prepared_data, words=self._words,", ":param X: (Multidimensional) time series dataset as an array of", "their own features and they will be concatenated by this", "following types: - :class:`~fruits.preparation.abstract.DataPreparateur` - :class:`~fruits.words.word.Word` - :class:`~fruits.sieving.abstract.FeatureSieve` \"\"\" objects_flattened", ":meth:`~fruits.scope.force_input_shape`. :type X: np.ndarray \"\"\" self._compile() self._get_cache(X) prepared_data = self._select_fit_sample(X)", "default configuration of a fruit branch if arguments differ from", "for branch in self.branches(): summary += \"\\n\\n\" + branch.summary() summary", "the different time series. :param X: (Multidimensional) time series dataset", "prepared_data = prep.transform(prepared_data, cache=self._cache) for callback in callbacks: callback.on_preparateur(prepared_data) for", "features and they will be concatenated by this class. A", "deepcopy(self) -> \"Fruit\": \"\"\"Creates a deep copy of this Fruit", "= self._select_fit_sample(X) for prep in self._preparateurs: prep.fit(prepared_data) prepared_data = prep.transform(prepared_data,", "fruit.add(fruits.preparation.INC) # add words for iterated sums calculation fruit.add(fruits.words.creation.simplewords_by_weight(4)) #", "for x in self._words[:9]]) summary += \"\\n\\t...\" else: summary +=", "the class :class:`~fruits.core.callback.AbstractCallback`., defaults to None :type callbacks: List[AbstractCallback], optional", "self._preparateurs def clear_preparateurs(self): \"\"\"Removes all preparateurs that were added to", ":class:`~fruits.core.fruit.FruitBranch` objects. At the end of the pipeline, each branch", "def configure(self, **kwargs: Any): \"\"\"Makes changes to the default configuration", "the previous step. The branch then returns an array of", "all features from all branches this Fruit object contains. :param", "branch. :type objects: One or more objects of the following", "in enumerate(iss_calculations): for callback in callbacks: callback.on_iterated_sum(iterated_data) for sieve in", "X: np.ndarray :returns: Array of features. :rtype: np.ndarray \"\"\" self.fit(X)", "to the given dataset. What this action explicitly does depends", "= fruit.transform(X_train) X_test_tranformed = fruit.transform(X_test) # use the transformed results", "fit_sample_size is not None: self._fit_sample_size = fit_sample_size def add_preparateur(self, preparateur:", "shallow copy of this FruitBranch object. :returns: Copy of the", "more objects of the following types: - :class:`~fruits.preparation.abstract.DataPreparateur` - :class:`~fruits.words.word.Word`", "that were added to this branch.\"\"\" self._words = [] self._sieves_extended", "= [] # calculator options used in the ISS calculation", "calculate the iterated sums signature for different :class:`~fruits.words.word.Word` objects the", ":meth:`~ruits.signature.iss.SignatureCalculator.transform`, defaults to None :type batch_size: int, optional :param fit_sample_size:", "the given data. :param X: (Multidimensional) time series dataset as", "a look at :meth:`fruits.core.fruit.FruitBranch.configure`. :type kwargs: Any \"\"\" for branch", "of fruits.Fruit: '{self.name}'\") summary += f\"\\nBranches: {len(self.branches())}\" summary += f\"\\nFeatures:", "**self._calculator_options )[0] for iterated_data in iss_calculations: iterated_data = iterated_data.reshape(iterated_data.shape[0] *", "each branch returns their own features and they will be", "copy_.fork(branch.deepcopy()) return copy_ class FruitBranch: \"\"\"One branch of a Fruit", "explicitly does depends on the FruitBranch configuration. :param X: (Multidimensional)", "simple example (using two branches): .. code-block:: python fruit =", "objects_flattened: if inspect.isclass(obj): obj = obj() if isinstance(obj, DataPreparateur): self.add_preparateur(obj)", "for ISS calculation\") if not self._sieves: raise RuntimeError(\"No FeatureSieve objects", "results from those sieves), i.e. the features for each time", "self._sieves = [] self._sieve_prerequisites = None self._sieves_extended = [] self._fitted", "objects in fruits available for preprocessing. The preparateurs will be", "# returns a sample of the data used for fitting", "1 # cache that is calculated at fitting and also", "to this branch.\"\"\" self._preparateurs = [] self._fitted = False def", "False self._fit_sample_size: Union[float, int] = 1 # cache that is", "a new feature sieve to the FruitBranch. :type sieve: FeatureSieve", "as np from fruits.cache import Cache, CoquantileCache from fruits.scope import", "raise RuntimeError(\"Missing call of self.fit\") result = np.zeros((X.shape[0], self.nfeatures())) index", "self._preparateurs: list = [] self._words: list = [] self._sieves: list", "lines[0] summary += \"\\n\\t \" summary += \"\\n\\t \".join(lines[1:]) return", "return sum([branch.nfeatures() for branch in self._branches]) def configure(self, **kwargs: Any):", "result def fit_transform(self, X: np.ndarray) -> np.ndarray: \"\"\"Fits all branches", "to the branch. :type word: Word \"\"\" if not isinstance(word,", "that is calculated at fitting and also used in the", "if not (0 <= index < len(self._branches)): raise IndexError(\"Index has", "list(range(len(self._words))) ) ) else: return ( sum([s.nfeatures() for s in", "sum([s.nfeatures() for s in self._sieves]) * CachePlan(self._words).n_iterated_sums( list(range(len(self._words))) ) )", "= [] self._sieve_prerequisites = None self._sieves_extended = [] self._fitted =", "int): \"\"\"Switches to the branch with the given index. :param", "in prep_keys: keys = keys.union(prep_keys['coquantile']) for sieve in self._sieves: sieve_keys", "= [] self._sieves: list = [] # calculator options used", "The summary contains a summary for each FruitBranch in this", "None: return self._branches[self._cbi] return self._branches[index] def branches(self) -> list: \"\"\"Returns", "= [] self._fitted = False def add_sieve(self, sieve: FeatureSieve): \"\"\"Appends", "your own callback, override the class :class:`~fruits.core.callback.AbstractCallback`., defaults to None", "configuration produces. :rtype: int \"\"\" if self._calculator_options[\"mode\"] == \"extended\": return", "dataset. What this action explicitly does depends on the FruitBranch", "keys def _get_cache(self, X: np.ndarray): # returns the already processed", "calling ``self.fit(X)`` and ``self.transform(X)`` consecutively does. :param X: (Multidimensional) time", "fit(self, X: np.ndarray): \"\"\"Fits all branches to the given data.", "return result def fit_transform(self, X: np.ndarray) -> np.ndarray: \"\"\"Fits all", "each time series. \"\"\" def __init__(self): # lists of used", "nfeatures(self) -> int: \"\"\"Returns the total number of features of", "``fruit`` above will result in ``2*8*2=32`` features per time series.", "# use the transformed results (features) in a classifier ...", "preprocessing. The preparateurs will be applied sequentially to the input", "sieve.nfeatures() new_features = nf * iterated_data.shape[1] for it in range(iterated_data.shape[1]):", "the fruit fruit.configure(mode=\"extended\") # fit the fruit on a time", "IndexError(\"Index has to be in [0, len(self.branches()))\") self._cbi = index", "If none is given, an empty FruitBranch will be created", "given index. :param index: Integer in ``[0, 1, ..., len(self.branches())-1]``", "See :meth:`~ruits.signature.iss.SignatureCalculator.transform`, defaults to None :type batch_size: int, optional :param", "not None: self._calculator_options[\"batch_size\"] = batch_size if fit_sample_size is not None:", "class :class:`~fruits.core.callback.AbstractCallback`., defaults to None :type callbacks: List[AbstractCallback], optional :rtype:", "get_preparateurs(self) -> List[DataPreparateur]: \"\"\"Returns a list of all preparateurs added", "of self.fit\") self._get_cache(X) prepared_data = force_input_shape(X) for prep in self._preparateurs:", "for sieve in self._sieves: copy_.add(sieve.copy()) copy_._calculator_options = self._calculator_options.copy() return copy_", "a all branches if arguments differ from ``None``. :param kwargs:", "= SignatureCalculator().transform( prepared_data, words=self._words, **self._calculator_options )[0] for i, iterated_data in", "the current branch index self._cbi: int = 0 self._fitted: bool", "branch keys: Set[str] = set() for prep in self._preparateurs: prep_keys", ")[0] for iterated_data in iss_calculations: iterated_data = iterated_data.reshape(iterated_data.shape[0] * iterated_data.shape[1],", "# list with inner lists containing sieves # all sieves", "customize any of the following three steps. - Preparing data:", "not self._fitted: raise RuntimeError(\"Missing call of self.fit\") self._get_cache(X) prepared_data =", "time series data that are somehow representative of the input", "ISS calculation self._calculator_options: dict = {\"batch_size\": 1, \"mode\": \"single\"} #", "arguments differ from ``None``. :param kwargs: For possible options, have", "given time series dataset. The results are the calculated features", "if not self._sieves: raise RuntimeError(\"No FeatureSieve objects specified\") def _collect_cache_keys(self)", "example (using two branches): .. code-block:: python fruit = fruits.Fruit(\"My", "of used classes for data processing self._preparateurs: list = []", "time series dataset. The results are the calculated features for", "at :meth:`fruits.core.fruit.FruitBranch.configure`. :type kwargs: Any \"\"\" for branch in self._branches:", "summary += f\"\\nIterators ({len(self._words)}): \" if len(self._words) == 0: summary", "np.random.choice(X.shape[0], size=s, replace=False) return X[indices, :, :] def fit(self, X:", "of a all branches if arguments differ from ``None``. :param", "branch.transform(X, callbacks) index += k result = np.nan_to_num(result, copy=False, nan=0.0)", "= None self._sieves_extended = [] self._fitted = False def add(self,", "def branches(self) -> list: \"\"\"Returns all branches of this Fruit", "of the following three steps. - Preparing data: Apply functions", "False @property def name(self) -> str: \"\"\"Simple identifier for the", ":param batch_size: See :meth:`~ruits.signature.iss.SignatureCalculator.transform`, defaults to None :type batch_size: int,", "return summary def copy(self) -> \"Fruit\": \"\"\"Creates a shallow copy", "AbstractCallback from fruits.signature.iss import SignatureCalculator, CachePlan from fruits.words.word import Word", "(isinstance(self._fit_sample_size, int) and self._fit_sample_size == 1): ind = np.random.randint(0, X.shape[0])", "class :class:`~fruits.core.callback.AbstractCallback`., defaults to [] :type callbacks: List[AbstractCallback], optional :rtype:", "np.ndarray: \"\"\"This function does the same that calling ``self.fit(X)`` and", "np.ndarray :raises: RuntimeError if Fruit.fit wasn't called \"\"\" if not", "of the input data. The user can customize any of", "``None``. :param mode: See :meth:`fruits.signature.iss.SignatureCalculator.transform`, defaults to None :type mode:", "is used for fitting. This is represented as a float", "= [] iss_calculations = SignatureCalculator().transform( prepared_data, words=self._words, **self._calculator_options )[0] for", "nf * iterated_data.shape[1] for it in range(iterated_data.shape[1]): sieved_data[:, k+it*nf:k+(it+1)*nf] =", "pointer for the current branch index self._cbi: int = 0", "of all features from all branches this Fruit object contains.", "all sieves in one list are trained on one specific", "branch in self._branches: copy_.fork(branch.copy()) return copy_ def deepcopy(self) -> \"Fruit\":", "sieve_keys = sieve._get_cache_keys() if 'coquantile' in sieve_keys: keys = keys.union(sieve_keys['coquantile'])", "following three steps. - Preparing data: Apply functions at the", "sieve in self._sieves: copy_.add(sieve) return copy_ def deepcopy(self) -> \"FruitBranch\":", "sieve in self._sieves: sieve_keys = sieve._get_cache_keys() if 'coquantile' in sieve_keys:", "np.ndarray) -> np.ndarray: \"\"\"This function does the same that calling", "str = None, batch_size: int = None, fit_sample_size: Union[float, int]", "= np.array(objects, dtype=object).flatten() for obj in objects_flattened: if inspect.isclass(obj): obj", "Any import numpy as np from fruits.cache import Cache, CoquantileCache", "the features for each time series. \"\"\" def __init__(self): #", "0: summary += \"-\" else: summary += \"\\n\\t+ \" +", "given dataset. What this action explicitly does depends on the", "changes to the default configuration of a fruit branch if", "({len(self._words)}): \" if len(self._words) == 0: summary += \"-\" elif", "None: self._calculator_options[\"mode\"] = mode if batch_size is not None: self._calculator_options[\"batch_size\"]", "branch with same settings but all calculations done erased. :rtype:", "of all branches in this object. :rtype: Fruit \"\"\" copy_", "preparateurs added to the branch. :rtype: List[DataPreparateur] \"\"\" return self._preparateurs", "summary += \"-\" else: for x in self._sieves: lines =", "List, Union, Set, Any import numpy as np from fruits.cache", "a look at :meth:`~fruits.scope.force_input_shape`. :type X: np.ndarray :param callbacks: List", "arguments differ from ``None``. :param mode: See :meth:`fruits.signature.iss.SignatureCalculator.transform`, defaults to", "List[DataPreparateur] \"\"\" return self._preparateurs def clear_preparateurs(self): \"\"\"Removes all preparateurs that", "force_input_shape, FitTransform from fruits.core.callback import AbstractCallback from fruits.signature.iss import SignatureCalculator,", "callbacks: List[AbstractCallback], optional :rtype: np.ndarray :raises: RuntimeError if Fruit.fit wasn't", "= False @property def name(self) -> str: \"\"\"Simple identifier for", "and ready # for fitting if not self._words: raise RuntimeError(\"No", ":class:`~fruits.words.word.Word` objects the user can specify. - Extracting Features: Each", "int = None): \"\"\"Returns the currently selected branch or the", "X from all branches. :param X: (Multidimensional) time series dataset", "self._branches: List[FruitBranch] = [] # pointer for the current branch", "def clear(self): \"\"\"Clears all settings, configurations and calculated results the", "None, fit_sample_size: Union[float, int] = None): \"\"\"Makes changes to the", ":rtype: List[Word] \"\"\" return self._words def clear_words(self): \"\"\"Removes all words", "= len(self._branches) - 1 self._fitted = False def branch(self, index:", "\"\"\"One branch of a Fruit object. A FruitBranch object extracts", "in self._preparateurs: copy_.add(preparateur.copy()) for iterator in self._words: copy_.add(iterator.copy()) for sieve", "\"\\n{:=^80}\".format(f\"End of Summary\") return summary def copy(self) -> \"Fruit\": \"\"\"Creates", "deep copy of this Fruit object. This also creates deep", "the Fruit object.\"\"\" return self._name @name.setter def name(self, name: str):", "= None, batch_size: int = None, fit_sample_size: Union[float, int] =", ":type index: int \"\"\" if not (0 <= index <", "set() for prep in self._preparateurs: prep_keys = prep._get_cache_keys() if 'coquantile'", "object. \"\"\" self.clear_preparateurs() self.clear_words() self.clear_sieves() self._calculator_options = {\"batch_size\": 1, \"mode\":", "def fit_transform(self, X: np.ndarray) -> np.ndarray: \"\"\"Fits all branches to", "fruits.Fruit(\"My Fruit\") # optional: add preparateurs for preprocessing fruit.add(fruits.preparation.INC) #", "to the default configuration of a fruit branch if arguments", "be fitted on the iterated sums from the previous step.", "for x in self._sieves: lines = x.summary().split(\"\\n\") summary += \"\\n\\t+", "FeatureSieve): self.add_sieve(obj) else: raise TypeError(\"Cannot add variable of type\"+str(type(obj))) def", "# all sieves in one list are trained on one", "a number of :class:`~fruits.core.fruit.FruitBranch` objects. At the end of the", "of :class:`~fruits.core.fruit.FruitBranch` objects. At the end of the pipeline, each", "name def fork(self, branch: \"FruitBranch\" = None): \"\"\"Adds a new", "False def get_words(self) -> List[Word]: \"\"\"Returns a list of all", "int = None, fit_sample_size: Union[float, int] = None): \"\"\"Makes changes", "self._fitted: bool = False @property def name(self) -> str: \"\"\"Simple", "= name def fork(self, branch: \"FruitBranch\" = None): \"\"\"Adds a", "self._fit_sample_size = fit_sample_size def add_preparateur(self, preparateur: DataPreparateur): \"\"\"Adds a preparateur", "np.nan_to_num(result, copy=False, nan=0.0) return result def fit_transform(self, X: np.ndarray) ->", "1): ind = np.random.randint(0, X.shape[0]) return X[ind:ind+1, :, :] else:", "in fruits available for preprocessing. The preparateurs will be applied", "the transformed results of X from all branches. :param X:", "sums signature for different :class:`~fruits.words.word.Word` objects the user can specify.", "of this FruitBranch object. :returns: Copy of the branch with", "self._branches: branch.configure(**kwargs) def fit(self, X: np.ndarray): \"\"\"Fits all branches to", "DataPreparateur): self.add_preparateur(obj) elif isinstance(obj, Word): self.add_word(obj) elif isinstance(obj, FeatureSieve): self.add_sieve(obj)", "all branches. :param X: (Multidimensional) time series dataset :type X:", ":type X: np.ndarray :returns: Two dimensional feature array :rtype: np.ndarray", "[] self._words: list = [] self._sieves: list = [] #", "summary def copy(self) -> \"FruitBranch\": \"\"\"Returns a shallow copy of", "- Preparing data: Apply functions at the start of the", "self.clear_sieves() self._calculator_options = {\"batch_size\": 1, \"mode\": \"single\"} def nfeatures(self) ->", "callback.on_preparation_end(prepared_data) sieved_data = np.zeros((prepared_data.shape[0], self.nfeatures())) k = 0 iss_calculations =", "= False def add_word(self, word: Word): \"\"\"Adds a word to", "a preparateur to the branch. :type preparateur: DataPreparateur \"\"\" if", "for s in self._sieves]) * len(self._words) ) def _compile(self): #", "\"\"\"Returns a list of all feature sieves added to the", "FruitBranch will be created and switched to. :type branch: FruitBranch,", "the default configuration of a fruit branch if arguments differ", ":], cache=self._cache, ) for callback in callbacks: callback.on_sieve(sieved_data[k:k+new_features]) k +=", "self._sieves.append(sieve) self._fitted = False def get_sieves(self) -> List[FeatureSieve]: \"\"\"Returns a", "of this Fruit object. This also creates shallow copies of", "empty FruitBranch will be created and switched to. :type branch:", "RuntimeError if Fruit.fit wasn't called \"\"\" if not self._fitted: raise", ":class:`~fruits.words.word.Word` - :class:`~fruits.sieving.abstract.FeatureSieve` \"\"\" objects_flattened = np.array(objects, dtype=object).flatten() for obj", "Have a look at `:meth:`~fruits.scope.force_input_shape`. :type X: np.ndarray :returns: Array", "branch. :param objects: One or more objects of the following", "of a Fruit object. A FruitBranch object extracts values from", "all preparateurs that were added to this branch.\"\"\" self._preparateurs =", "def transform(self, X: np.ndarray, callbacks: List[AbstractCallback] = []) -> np.ndarray:", "an array of three dimensions. Have a look at :meth:`~fruits.scope.force_input_shape`.", "to 1 :type fit_sample_size: Union[float, int] \"\"\" if mode is", "the same that calling ``self.fit(X)`` and ``self.transform(X)`` consecutively does. :param", "def add_preparateur(self, preparateur: DataPreparateur): \"\"\"Adds a preparateur to the branch.", "calculator options used in the ISS calculation self._calculator_options: dict =", "in self._branches: branch.fit(X) self._fitted = True def transform(self, X: np.ndarray,", "== 0: self.fork() self._branches[self._cbi].add(*objects) self._fitted = False def nfeatures(self) ->", "return self._words def clear_words(self): \"\"\"Removes all words that were added", "that is used for fitting. This is represented as a", "copy_ = Fruit(self.name+\" (Copy)\") for branch in self._branches: copy_.fork(branch.deepcopy()) return", "given, an empty FruitBranch will be created and switched to.", "your own callback, override the class :class:`~fruits.core.callback.AbstractCallback`., defaults to []", "applied sequentially to the input data. - Calculating Iterated Sums:", "force_input_shape(X) for prep in self._preparateurs: prepared_data = prep.transform(prepared_data, cache=self._cache) for", "of type\"+str(type(obj))) def clear(self): \"\"\"Clears all settings, configurations and calculated", "defaults to None :type callbacks: List[AbstractCallback], optional :rtype: np.ndarray :raises:", "the iterated sums from the previous step. The branch then", "Deepcopy of the branch with same settings but all calculations", "\"\"\" if not self._fitted: raise RuntimeError(\"Missing call of self.fit\") self._get_cache(X)", "This also creates shallow copies of all branches in this", "own callback, override the class :class:`~fruits.core.callback.AbstractCallback`., defaults to [] :type", "is not None: self._calculator_options[\"batch_size\"] = batch_size if fit_sample_size is not", "list of all preparateurs added to the branch. :rtype: List[DataPreparateur]", "enumerate(iss_calculations): for callback in callbacks: callback.on_iterated_sum(iterated_data) for sieve in self._sieves_extended[i]:", "elif isinstance(obj, Word): self.add_word(obj) elif isinstance(obj, FeatureSieve): self.add_sieve(obj) else: raise", "use the transformed results (features) in a classifier ... The", "return self._branches def switch_branch(self, index: int): \"\"\"Switches to the branch", "summary(self) -> str: \"\"\"Returns a summary of this object. The", "containing sieves # all sieves in one list are trained", "sieves in one list are trained on one specific output", "calculated results the branch has. After the branch is cleared,", "\\ \"\\n\\t+ \".join([str(x) for x in self._preparateurs]) summary += f\"\\nIterators", "for branch in self._branches: for callback in callbacks: callback.on_next_branch() k", "in self._sieves_extended[i]: nf = sieve.nfeatures() new_features = nf * iterated_data.shape[1]", "self.fit(X) return self.transform(X) def summary(self) -> str: \"\"\"Returns a summary", "-> np.ndarray: # returns a sample of the data used", "+ \\ \"\\n\\t+ \".join([str(x) for x in self._words]) summary +=", "TypeError self._sieves.append(sieve) self._fitted = False def get_sieves(self) -> List[FeatureSieve]: \"\"\"Returns", "for preprocessing fruit.add(fruits.preparation.INC) # add words for iterated sums calculation", "given dataset and returns the transformed results of X from", "= None, fit_sample_size: Union[float, int] = None): \"\"\"Makes changes to", "return copy_ def deepcopy(self) -> \"Fruit\": \"\"\"Creates a deep copy", "sieves_copy = [sieve.copy() for sieve in self._sieves] for sieve in", "processing self._preparateurs: list = [] self._words: list = [] self._sieves:", "preprocessed data is now used to calculate the iterated sums", "else: return ( sum([s.nfeatures() for s in self._sieves]) * len(self._words)", "self._sieves_extended = [] self._fitted = False def add(self, *objects: Union[FitTransform,", "used for fitting if (isinstance(self._fit_sample_size, int) and self._fit_sample_size == 1):", "of all FitTransformers in the branch keys: Set[str] = set()", "consecutively does. :param X: (Multidimensional) time series dataset as an", "X: np.ndarray): # returns the already processed cache needed in", "data is now used to calculate the iterated sums signature", "obj = obj() if isinstance(obj, DataPreparateur): self.add_preparateur(obj) elif isinstance(obj, Word):", "in self._branches: branch.configure(**kwargs) def fit(self, X: np.ndarray): \"\"\"Fits all branches", "branch. :rtype: List[FeatureSieve] \"\"\" return self._sieves def clear_sieves(self): \"\"\"Removes all", "1: s = 1 indices = np.random.choice(X.shape[0], size=s, replace=False) return", "to. :type branch: FruitBranch, optional \"\"\" if branch is None:", "fruit.configure(mode=\"extended\") # fit the fruit on a time series dataset", "of three dimensions. Have a look at `:meth:`~fruits.scope.force_input_shape`. :type X:", "previous step. The branch then returns an array of numbers", "the ISS calculation self._calculator_options: dict = {\"batch_size\": 1, \"mode\": \"single\"}", "all FitTransformers in the branch keys: Set[str] = set() for", "copy_ = FruitBranch() for preparateur in self._preparateurs: copy_.add(preparateur) for iterator", "differ from ``None``. :param kwargs: For possible options, have a", ":class:`~fruits.preparation.abstract.DataPreparateur` objects in fruits available for preprocessing. The preparateurs will", "f\"\\nIterators ({len(self._words)}): \" if len(self._words) == 0: summary += \"-\"", "features the current configuration produces. :rtype: int \"\"\" if self._calculator_options[\"mode\"]", "the currently selected branch. :param objects: One or more objects", "isinstance(word, Word): raise TypeError self._words.append(word) self._fitted = False def get_words(self)", "\"FruitBranch\": \"\"\"Returns a shallow copy of this FruitBranch object. :returns:", "= np.zeros((X.shape[0], self.nfeatures())) index = 0 for branch in self._branches:", "for x in self._preparateurs]) summary += f\"\\nIterators ({len(self._words)}): \" if", "summary += f\"\\nSieves ({len(self._sieves)}): \" if len(self._sieves) == 0: summary", "np.ndarray :returns: Array of features. :rtype: np.ndarray \"\"\" self.fit(X) return", "preparateurs, words and sieves. :rtype: str \"\"\" summary = \"{:-^80}\".format(\"fruits.FruitBranch\")", "the following types: - :class:`~fruits.preparation.abstract.DataPreparateur` - :class:`~fruits.words.word.Word` - :class:`~fruits.sieving.abstract.FeatureSieve` :type", "[] self._sieves: list = [] # calculator options used in", "added to the branch. :rtype: List[DataPreparateur] \"\"\" return self._preparateurs def", "\"\"\"Adds a word to the branch. :type word: Word \"\"\"", "None :type batch_size: int, optional :param fit_sample_size: Size of the", "from fruits.preparation.abstract import DataPreparateur class Fruit: \"\"\"Feature Extractor using iterated", "types: - :class:`~fruits.preparation.abstract.DataPreparateur` - :class:`~fruits.words.word.Word` - :class:`~fruits.sieving.abstract.FeatureSieve` :type objects: Union[FitTransform,", "object. :returns: Copy of the branch with same settings but", "of the extraction procedure. There are many so called :class:`~fruits.preparation.abstract.DataPreparateur`", "\"\"\" self.fit(X) return self.transform(X) def summary(self) -> str: \"\"\"Returns a", "for it in range(iterated_data.shape[1]): sieved_data[:, k+it*nf:k+(it+1)*nf] = sieve.transform( iterated_data[:, it,", "'{self.name}'\") summary += f\"\\nBranches: {len(self.branches())}\" summary += f\"\\nFeatures: {self.nfeatures()}\" for", "> 10: summary += \"\\n\\t+ \" + \\ \"\\n\\t+ \".join([str(x)", "switched to. :type branch: FruitBranch, optional \"\"\" if branch is", "the FruitBranch is configured correctly and ready # for fitting", "summary += \"\\n\\n\" + branch.summary() summary += \"\\n{:=^80}\".format(f\"End of Summary\")", "does depends on the FruitBranch configuration. :param X: (Multidimensional) time", "self._name = name def fork(self, branch: \"FruitBranch\" = None): \"\"\"Adds", "\"\"\" for branch in self._branches: branch.fit(X) self._fitted = True def", "following types: - :class:`~fruits.preparation.abstract.DataPreparateur` - :class:`~fruits.words.word.Word` - :class:`~fruits.sieving.abstract.FeatureSieve` :type objects:", "currently selected branch or the branch with the given index.", "copy_ class FruitBranch: \"\"\"One branch of a Fruit object. A", "( sum([s.nfeatures() for s in self._sieves]) * CachePlan(self._words).n_iterated_sums( list(range(len(self._words))) )", "of a number of :class:`~fruits.core.fruit.FruitBranch` objects. At the end of", "get_sieves(self) -> List[FeatureSieve]: \"\"\"Returns a list of all feature sieves", "all feature sieves that were added to this branch.\"\"\" self._sieves", "self._sieve_prerequisites = None self._sieves_extended = [] self._fitted = False def", "to None :type batch_size: int, optional :param fit_sample_size: Size of", "\\ \"\\n\\t+ \".join([str(x) for x in self._words[:9]]) summary += \"\\n\\t...\"", "# optional: add preparateurs for preprocessing fruit.add(fruits.preparation.INC) # add words", "in self._sieves] for sieve in sieves_copy: sieve.fit(iterated_data[:, :]) self._sieves_extended.append(sieves_copy) self._fitted", "of X from all branches. :param X: (Multidimensional) time series", "callback.on_iterated_sum(iterated_data) for sieve in self._sieves_extended[i]: nf = sieve.nfeatures() new_features =", "\"\"\" if not self._fitted: raise RuntimeError(\"Missing call of self.fit\") result", "configurations for fitting self._fitted: bool = False self._fit_sample_size: Union[float, int]", "words=self._words, **self._calculator_options )[0] for i, iterated_data in enumerate(iss_calculations): for callback", "= \"{:-^80}\".format(\"fruits.FruitBranch\") summary += f\"\\nNumber of features: {self.nfeatures()}\" summary +=", "List[AbstractCallback], optional :rtype: np.ndarray :raises: RuntimeError if ``self.fit`` wasn't called", "added to this branch.\"\"\" self._preparateurs = [] self._fitted = False", "default configuration of a all branches if arguments differ from", "in the branch keys: Set[str] = set() for prep in", "self.add_word(obj) elif isinstance(obj, FeatureSieve): self.add_sieve(obj) else: raise TypeError(\"Cannot add variable", "sieve_keys: keys = keys.union(sieve_keys['coquantile']) return keys def _get_cache(self, X: np.ndarray):", "X: np.ndarray): \"\"\"Fits the branch to the given dataset. What", "a time series dataset fruit.fit(X_train) # transform the dataset X_train_transformed", "-> np.ndarray: \"\"\"This function does the same that calling ``self.fit(X)``", "added to this branch.\"\"\" self._words = [] self._sieves_extended = []", "self._branches: branch.fit(X) self._fitted = True def transform(self, X: np.ndarray, callbacks:", "FeatureSieve): \"\"\"Appends a new feature sieve to the FruitBranch. :type", "For possible options, have a look at :meth:`fruits.core.fruit.FruitBranch.configure`. :type kwargs:", "list: \"\"\"Returns all branches of this Fruit object. :rtype: list", "class. A simple example (using two branches): .. code-block:: python", "List[FeatureSieve] \"\"\" return self._sieves def clear_sieves(self): \"\"\"Removes all feature sieves", "\"FruitBranch\" = None): \"\"\"Adds a new branch to the pipeline.", ":type fit_sample_size: Union[float, int] \"\"\" if mode is not None:", "= \"{:=^80}\".format(f\"Summary of fruits.Fruit: '{self.name}'\") summary += f\"\\nBranches: {len(self.branches())}\" summary", "iterated_data.shape[1], iterated_data.shape[2]) sieves_copy = [sieve.copy() for sieve in self._sieves] for", "does the same that calling ``self.fit(X)`` and ``self.transform(X)`` consecutively does.", "dataset :type X: np.ndarray :returns: Two dimensional feature array :rtype:", "using iterated sums. A Fruit consists of a number of", "\"\\n\\t...\" else: summary += \"\\n\\t+ \" + \\ \"\\n\\t+ \".join([str(x)", "produces. :rtype: int \"\"\" if self._calculator_options[\"mode\"] == \"extended\": return (", "object. The summary contains all added preparateurs, words and sieves.", "- Extracting Features: Each :class:`~fruits.sieving.abstract.FeatureSieve` added to the branch will", "There are many so called :class:`~fruits.preparation.abstract.DataPreparateur` objects in fruits available", "+= new_features for callback in callbacks: callback.on_sieving_end(sieved_data) return sieved_data def", "function does the same that calling ``self.fit(X)`` and ``self.transform(X)`` consecutively", "selected branch or the branch with the given index. :rtype:", "a look at :meth:`~fruits.scope.force_input_shape`. :type X: np.ndarray \"\"\" self._compile() self._get_cache(X)", "[] self._fitted = False def add_word(self, word: Word): \"\"\"Adds a", "index. :param index: Integer in ``[0, 1, ..., len(self.branches())-1]`` :type", "*objects: Union[FitTransform, Word, type]): \"\"\"Adds one or multiple object(s) to", "data: Apply functions at the start of the extraction procedure.", "import FeatureSieve from fruits.preparation.abstract import DataPreparateur class Fruit: \"\"\"Feature Extractor", "copy_.add(sieve) return copy_ def deepcopy(self) -> \"FruitBranch\": \"\"\"Returns a deep", "\"\"\"Switches to the branch with the given index. :param index:", "index is None: return self._branches[self._cbi] return self._branches[index] def branches(self) ->", "dimensions. Have a look at :meth:`~fruits.scope.force_input_shape`. :type X: np.ndarray \"\"\"", "- Calculating Iterated Sums: The preprocessed data is now used", "of features. :rtype: np.ndarray \"\"\" self.fit(X) return self.transform(X) def summary(self)", "isinstance(preparateur, DataPreparateur): raise TypeError self._preparateurs.append(preparateur) self._fitted = False def get_preparateurs(self)", "if s < 1: s = 1 indices = np.random.choice(X.shape[0],", "for callback in callbacks: callback.on_iterated_sum(iterated_data) for sieve in self._sieves_extended[i]: nf", "given index. :rtype: FruitBranch \"\"\" if index is None: return", "extracts values from time series data that are somehow representative", "= []) -> np.ndarray: \"\"\"Returns a two dimensional array of", "return self._sieves def clear_sieves(self): \"\"\"Removes all feature sieves that were", "then returns an array of numbers (the transformed results from", "return sieved_data def fit_transform(self, X: np.ndarray) -> np.ndarray: \"\"\"This function", "1 indices = np.random.choice(X.shape[0], size=s, replace=False) return X[indices, :, :]", "sieve in sieves_copy: sieve.fit(iterated_data[:, :]) self._sieves_extended.append(sieves_copy) self._fitted = True def", "user can customize any of the following three steps. -", "- :class:`~fruits.words.word.Word` - :class:`~fruits.sieving.abstract.FeatureSieve` :type objects: Union[FitTransform, Word] \"\"\" if", "added to the branch. :rtype: List[FeatureSieve] \"\"\" return self._sieves def", "= [] # pointer for the current branch index self._cbi:", "- :class:`~fruits.sieving.abstract.FeatureSieve` :type objects: Union[FitTransform, Word] \"\"\" if len(self._branches) ==", "if index is None: return self._branches[self._cbi] return self._branches[index] def branches(self)", ":class:`~fruits.sieving.abstract.FeatureSieve` added to the branch will be fitted on the", "branch index self._cbi: int = 0 self._fitted: bool = False", "FitTransform from fruits.core.callback import AbstractCallback from fruits.signature.iss import SignatureCalculator, CachePlan", "+= \"\\n\\t...\" else: summary += \"\\n\\t+ \" + \\ \"\\n\\t+", "= True def transform(self, X: np.ndarray, callbacks: List[AbstractCallback] = [])", "self._name @name.setter def name(self, name: str): self._name = name def", "from fruits.words.word import Word from fruits.sieving.abstract import FeatureSieve from fruits.preparation.abstract", "settings, configurations and calculated results the branch has. After the", "for i, iterated_data in enumerate(iss_calculations): for callback in callbacks: callback.on_iterated_sum(iterated_data)", "``X.shape[0]`` or ``1`` for one random time series., defaults to", "time series. \"\"\" def __init__(self): # lists of used classes", "-> np.ndarray: \"\"\"Fits all branches to the given dataset and", "the branch with same settings but all calculations done erased.", "k+it*nf:k+(it+1)*nf] = sieve.transform( iterated_data[:, it, :], cache=self._cache, ) for callback", "== 0: summary += \"-\" else: summary += \"\\n\\t+ \"", "str, optional :param batch_size: See :meth:`~ruits.signature.iss.SignatureCalculator.transform`, defaults to None :type", "currently selected branch. :param objects: One or more objects of", "data. The user can customize any of the following three", "-> int: \"\"\"Returns the total number of features of all", "= False def get_preparateurs(self) -> List[DataPreparateur]: \"\"\"Returns a list of", "classes for data processing self._preparateurs: list = [] self._words: list", "X_train_transformed = fruit.transform(X_train) X_test_tranformed = fruit.transform(X_test) # use the transformed", "def copy(self) -> \"FruitBranch\": \"\"\"Returns a shallow copy of this", "\"\"\"Adds one or multiple object(s) to the branch. :type objects:", "self._sieves_extended: list = [] # configurations for fitting self._fitted: bool", "index: int): \"\"\"Switches to the branch with the given index.", "[] self._fitted = False def add_sieve(self, sieve: FeatureSieve): \"\"\"Appends a", "in one list are trained on one specific output #", "look at `:meth:`~fruits.scope.force_input_shape`. :type X: np.ndarray :returns: Array of features.", "def copy(self) -> \"Fruit\": \"\"\"Creates a shallow copy of this", "\".join([str(x) for x in self._words]) summary += f\"\\nSieves ({len(self._sieves)}): \"", "processed cache needed in this branch self._cache = CoquantileCache() self._cache.process(X,", "object. This also creates shallow copies of all branches in", "x in self._words[:9]]) summary += \"\\n\\t...\" else: summary += \"\\n\\t+", "DataPreparateur): \"\"\"Adds a preparateur to the branch. :type preparateur: DataPreparateur", "X: np.ndarray): \"\"\"Fits all branches to the given data. :param", "transformation process self._cache: Cache def configure(self, mode: str = None,", "output # of an ISS-result self._sieves_extended: list = [] #", ":type branch: FruitBranch, optional \"\"\" if branch is None: branch", "settings as a newly created FruitBranch object. \"\"\" self.clear_preparateurs() self.clear_words()", "< 1: s = 1 indices = np.random.choice(X.shape[0], size=s, replace=False)", "Any \"\"\" for branch in self._branches: branch.configure(**kwargs) def fit(self, X:", "nan=0.0) return result def fit_transform(self, X: np.ndarray) -> np.ndarray: \"\"\"Fits", "sieves added to the branch. :rtype: List[FeatureSieve] \"\"\" return self._sieves", "Have a look at :meth:`~fruits.scope.force_input_shape`. :type X: np.ndarray \"\"\" for", "name: str = \"\"): self.name: str = name # list", "len(self._branches)): raise IndexError(\"Index has to be in [0, len(self.branches()))\") self._cbi", "not isinstance(word, Word): raise TypeError self._words.append(word) self._fitted = False def", "objects the user can specify. - Extracting Features: Each :class:`~fruits.sieving.abstract.FeatureSieve`", "\"\"\" for branch in self._branches: branch.configure(**kwargs) def fit(self, X: np.ndarray):", "= False def get_words(self) -> List[Word]: \"\"\"Returns a list of", "\"\"\" copy_ = Fruit(self.name+\" (Copy)\") for branch in self._branches: copy_.fork(branch.copy())", "``None``. :param kwargs: For possible options, have a look at", "X: np.ndarray, callbacks: List[AbstractCallback] = []) -> np.ndarray: \"\"\"Returns a", "self._cache: Cache def configure(self, mode: str = None, batch_size: int", "in self.branches(): summary += \"\\n\\n\" + branch.summary() summary += \"\\n{:=^80}\".format(f\"End", "def get_preparateurs(self) -> List[DataPreparateur]: \"\"\"Returns a list of all preparateurs", "if len(self._branches) == 0: self.fork() self._branches[self._cbi].add(*objects) self._fitted = False def", "See :meth:`fruits.signature.iss.SignatureCalculator.transform`, defaults to None :type mode: str, optional :param", ":rtype: list \"\"\" return self._branches def switch_branch(self, index: int): \"\"\"Switches", "words that were added to this branch.\"\"\" self._words = []", "= FruitBranch() for preparateur in self._preparateurs: copy_.add(preparateur) for iterator in", "transformed results from those sieves), i.e. the features for each", "not self._sieves: raise RuntimeError(\"No FeatureSieve objects specified\") def _collect_cache_keys(self) ->", "a deep copy of this Fruit object. This also creates", "\"\"\" self.clear_preparateurs() self.clear_words() self.clear_sieves() self._calculator_options = {\"batch_size\": 1, \"mode\": \"single\"}", "copy_ def deepcopy(self) -> \"Fruit\": \"\"\"Creates a deep copy of", "A simple example (using two branches): .. code-block:: python fruit", "not isinstance(sieve, FeatureSieve): raise TypeError self._sieves.append(sieve) self._fitted = False def", "(Multidimensional) time series dataset as an array of three dimensions.", "all words that were added to this branch.\"\"\" self._words =", "self._sieves def clear_sieves(self): \"\"\"Removes all feature sieves that were added", "branch. :type preparateur: DataPreparateur \"\"\" if not isinstance(preparateur, DataPreparateur): raise", "dataset as an array of three dimensions. Have a look", "np.ndarray: \"\"\"Fits all branches to the given dataset and returns", "self._calculator_options[\"mode\"] == \"extended\": return ( sum([s.nfeatures() for s in self._sieves])", "not None: self._fit_sample_size = fit_sample_size def add_preparateur(self, preparateur: DataPreparateur): \"\"\"Adds", "add words for iterated sums calculation fruit.add(fruits.words.creation.simplewords_by_weight(4)) # choose sieves", "in self._preparateurs: prep.fit(prepared_data) prepared_data = prep.transform(prepared_data, cache=self._cache) self._sieves_extended = []", "fruit.fork() fruit.add(fruits.words.creation.simplewords_by_weight(4)) fruit.add(fruits.sieving.PPV(0.5)) fruit.add(fruits.sieving.END) # configure the fruit fruit.configure(mode=\"extended\") #", "of numbers (the transformed results from those sieves), i.e. the", "def get_words(self) -> List[Word]: \"\"\"Returns a list of all words", "two branches): .. code-block:: python fruit = fruits.Fruit(\"My Fruit\") #", "<= index < len(self._branches)): raise IndexError(\"Index has to be in", ".. code-block:: python fruit = fruits.Fruit(\"My Fruit\") # optional: add", "= {\"batch_size\": 1, \"mode\": \"single\"} def nfeatures(self) -> int: \"\"\"Returns", "len(self._sieves) == 0: summary += \"-\" else: for x in", "The branch then returns an array of numbers (the transformed", "iterated_data.reshape(iterated_data.shape[0] * iterated_data.shape[1], iterated_data.shape[2]) sieves_copy = [sieve.copy() for sieve in", "DataPreparateur class Fruit: \"\"\"Feature Extractor using iterated sums. A Fruit", "three dimensions. Have a look at :meth:`~fruits.scope.force_input_shape`. :type X: np.ndarray", "self._fitted = True def transform(self, X: np.ndarray, callbacks: List[AbstractCallback] =", "cleared, it has the same settings as a newly created", "branch to the given dataset. What this action explicitly does", "for prep in self._preparateurs: prep_keys = prep._get_cache_keys() if 'coquantile' in", "def fit(self, X: np.ndarray): \"\"\"Fits the branch to the given", "or multiple object(s) to the currently selected branch. :param objects:", "done erased. :rtype: FruitBranch \"\"\" copy_ = FruitBranch() for preparateur", "Union[FitTransform, Word] \"\"\" if len(self._branches) == 0: self.fork() self._branches[self._cbi].add(*objects) self._fitted", "from ``None``. :param kwargs: For possible options, have a look", "if not isinstance(word, Word): raise TypeError self._words.append(word) self._fitted = False", "self.branches(): summary += \"\\n\\n\" + branch.summary() summary += \"\\n{:=^80}\".format(f\"End of", "a new branch to the pipeline. If none is given,", ":class:`~fruits.core.callback.AbstractCallback`., defaults to [] :type callbacks: List[AbstractCallback], optional :rtype: np.ndarray", "self._sieves_extended = [] self._fitted = False def add_sieve(self, sieve: FeatureSieve):", "def branch(self, index: int = None): \"\"\"Returns the currently selected", "1 :type fit_sample_size: Union[float, int] \"\"\" if mode is not", ":rtype: List[FeatureSieve] \"\"\" return self._sieves def clear_sieves(self): \"\"\"Removes all feature", "FruitBranch object. \"\"\" self.clear_preparateurs() self.clear_words() self.clear_sieves() self._calculator_options = {\"batch_size\": 1,", "= int(self._fit_sample_size * X.shape[0]) if s < 1: s =", "+= f\"\\nIterators ({len(self._words)}): \" if len(self._words) == 0: summary +=", "and they will be concatenated by this class. A simple", "add preparateurs for preprocessing fruit.add(fruits.preparation.INC) # add words for iterated", "or the branch with the given index. :rtype: FruitBranch \"\"\"", "[] self._fitted = False def add(self, *objects: Union[FitTransform, Word, type]):", "= Fruit(self.name+\" (Copy)\") for branch in self._branches: copy_.fork(branch.copy()) return copy_", "for sieve in self._sieves_extended[i]: nf = sieve.nfeatures() new_features = nf", "np.zeros((X.shape[0], self.nfeatures())) index = 0 for branch in self._branches: for", "branch: FruitBranch, optional \"\"\" if branch is None: branch =", "f\"\\nFeatures: {self.nfeatures()}\" for branch in self.branches(): summary += \"\\n\\n\" +", "self._branches def switch_branch(self, index: int): \"\"\"Switches to the branch with", "shallow copy of this Fruit object. This also creates shallow", "self._branches: for callback in callbacks: callback.on_next_branch() k = branch.nfeatures() result[:,", "batch_size is not None: self._calculator_options[\"batch_size\"] = batch_size if fit_sample_size is", "list are trained on one specific output # of an", "branch(self, index: int = None): \"\"\"Returns the currently selected branch", "summary of this object. The summary contains a summary for", "**kwargs: Any): \"\"\"Makes changes to the default configuration of a", "deepcopy(self) -> \"FruitBranch\": \"\"\"Returns a deep copy of this FruitBranch", "branches to the given data. :param X: (Multidimensional) time series", "branch.fit(X) self._fitted = True def transform(self, X: np.ndarray, callbacks: List[AbstractCallback]", "\"\"\" if branch is None: branch = FruitBranch() self._branches.append(branch) self._cbi", "this FruitBranch object. :returns: Copy of the branch with same", "(0 <= index < len(self._branches)): raise IndexError(\"Index has to be", "a fruit branch if arguments differ from ``None``. :param mode:", "self._fitted = False def get_sieves(self) -> List[FeatureSieve]: \"\"\"Returns a list", "Have a look at :meth:`~fruits.scope.force_input_shape`. :type X: np.ndarray :param callbacks:", "in the # transformation process self._cache: Cache def configure(self, mode:", "batch_size if fit_sample_size is not None: self._fit_sample_size = fit_sample_size def", "# transformation process self._cache: Cache def configure(self, mode: str =", "FruitBranch: \"\"\"One branch of a Fruit object. A FruitBranch object", "different :class:`~fruits.words.word.Word` objects the user can specify. - Extracting Features:", "CoquantileCache from fruits.scope import force_input_shape, FitTransform from fruits.core.callback import AbstractCallback", "on a time series dataset fruit.fit(X_train) # transform the dataset", "to the currently selected branch. :param objects: One or more", "\"Fruit\": \"\"\"Creates a deep copy of this Fruit object. This", "\"\"\"Removes all preparateurs that were added to this branch.\"\"\" self._preparateurs", "copy of this Fruit object. This also creates shallow copies", "the given index. :rtype: FruitBranch \"\"\" if index is None:", "sieves that were added to this branch.\"\"\" self._sieves = []", "contains all added preparateurs, words and sieves. :rtype: str \"\"\"", "-> str: \"\"\"Returns a summary of this object. The summary", "lines = x.summary().split(\"\\n\") summary += \"\\n\\t+ \" + lines[0] summary", "for sieve in self._sieves: sieve_keys = sieve._get_cache_keys() if 'coquantile' in", "summary contains all added preparateurs, words and sieves. :rtype: str", "results the branch has. After the branch is cleared, it", "trained on one specific output # of an ISS-result self._sieves_extended:", "keys = keys.union(sieve_keys['coquantile']) return keys def _get_cache(self, X: np.ndarray): #", "options used in the ISS calculation self._calculator_options: dict = {\"batch_size\":", "Two dimensional feature array :rtype: np.ndarray \"\"\" self.fit(X) return self.transform(X)", "Fruit object. :rtype: list \"\"\" return self._branches def switch_branch(self, index:", "range(iterated_data.shape[1]): sieved_data[:, k+it*nf:k+(it+1)*nf] = sieve.transform( iterated_data[:, it, :], cache=self._cache, )", "This also creates deep copies of all branches in this", "for sieve in self._sieves: copy_.add(sieve) return copy_ def deepcopy(self) ->", "\"\"\"Creates a shallow copy of this Fruit object. This also", "= False def get_sieves(self) -> List[FeatureSieve]: \"\"\"Returns a list of", "from time series data that are somehow representative of the", "copy of this FruitBranch object. :returns: Copy of the branch", "fruits available for preprocessing. The preparateurs will be applied sequentially", ":type X: np.ndarray \"\"\" for branch in self._branches: branch.fit(X) self._fitted", "prepared_data = self._select_fit_sample(X) for prep in self._preparateurs: prep.fit(prepared_data) prepared_data =", "for one random time series., defaults to 1 :type fit_sample_size:", "\"\\n\\t+ \".join([str(x) for x in self._words]) summary += f\"\\nSieves ({len(self._sieves)}):", "sieve in self._sieves_extended[i]: nf = sieve.nfeatures() new_features = nf *", "FruitBranch configuration. :param X: (Multidimensional) time series dataset as an", "copy_.add(preparateur.copy()) for iterator in self._words: copy_.add(iterator.copy()) for sieve in self._sieves:", "= sieve.nfeatures() new_features = nf * iterated_data.shape[1] for it in", "batch_size: int, optional :param fit_sample_size: Size of the random time", "\"\"\"Removes all words that were added to this branch.\"\"\" self._words", "total number of features the current configuration produces. :rtype: int", "the user can specify. - Extracting Features: Each :class:`~fruits.sieving.abstract.FeatureSieve` added", "self.add_preparateur(obj) elif isinstance(obj, Word): self.add_word(obj) elif isinstance(obj, FeatureSieve): self.add_sieve(obj) else:", "-> np.ndarray: \"\"\"Returns a two dimensional array of all features", "be created and switched to. :type branch: FruitBranch, optional \"\"\"", "- :class:`~fruits.preparation.abstract.DataPreparateur` - :class:`~fruits.words.word.Word` - :class:`~fruits.sieving.abstract.FeatureSieve` :type objects: Union[FitTransform, Word]", "is not None: self._calculator_options[\"mode\"] = mode if batch_size is not", "Fruit object contains. :param X: (Multidimensional) time series dataset as", "same settings as a newly created FruitBranch object. \"\"\" self.clear_preparateurs()", "self._get_cache(X) prepared_data = force_input_shape(X) for prep in self._preparateurs: prepared_data =", "= CoquantileCache() self._cache.process(X, list(self._collect_cache_keys())) def _select_fit_sample(self, X: np.ndarray) -> np.ndarray:", "sieve.fit(iterated_data[:, :]) self._sieves_extended.append(sieves_copy) self._fitted = True def transform(self, X: np.ndarray,", "sieve in self._sieves] for sieve in sieves_copy: sieve.fit(iterated_data[:, :]) self._sieves_extended.append(sieves_copy)", "now used to calculate the iterated sums signature for different", "def configure(self, mode: str = None, batch_size: int = None,", "== 0: summary += \"-\" else: for x in self._sieves:", "# configurations for fitting self._fitted: bool = False self._fit_sample_size: Union[float,", "the branch to the given dataset. What this action explicitly", "mode if batch_size is not None: self._calculator_options[\"batch_size\"] = batch_size if", "features of all branches combined. :rtype: int \"\"\" return sum([branch.nfeatures()", "or more objects of the following types: - :class:`~fruits.preparation.abstract.DataPreparateur` -", "type\"+str(type(obj))) def clear(self): \"\"\"Clears all settings, configurations and calculated results", "\"-\" else: for x in self._sieves: lines = x.summary().split(\"\\n\") summary", "result = np.zeros((X.shape[0], self.nfeatures())) index = 0 for branch in", "import DataPreparateur class Fruit: \"\"\"Feature Extractor using iterated sums. A", "to be in [0, len(self.branches()))\") self._cbi = index def add(self,", ":meth:`fruits.core.fruit.FruitBranch.configure`. :type kwargs: Any \"\"\" for branch in self._branches: branch.configure(**kwargs)", "on the iterated sums from the previous step. The branch", "callbacks: callback.on_preparation_end(prepared_data) sieved_data = np.zeros((prepared_data.shape[0], self.nfeatures())) k = 0 iss_calculations", "= None): \"\"\"Returns the currently selected branch or the branch", "iterated_data.shape[2]) sieves_copy = [sieve.copy() for sieve in self._sieves] for sieve", ":raises: RuntimeError if ``self.fit`` wasn't called \"\"\" if not self._fitted:", "len(self._words) ) def _compile(self): # checks if the FruitBranch is", "= [] self._fitted = False def add_word(self, word: Word): \"\"\"Adds", "the FruitBranch. :type sieve: FeatureSieve \"\"\" if not isinstance(sieve, FeatureSieve):", "were added to this branch.\"\"\" self._preparateurs = [] self._fitted =", "in [0, len(self.branches()))\") self._cbi = index def add(self, *objects: Union[FitTransform,", "None: self._calculator_options[\"batch_size\"] = batch_size if fit_sample_size is not None: self._fit_sample_size", "= np.zeros((prepared_data.shape[0], self.nfeatures())) k = 0 iss_calculations = SignatureCalculator().transform( prepared_data,", "new branch without INC fruit.fork() fruit.add(fruits.words.creation.simplewords_by_weight(4)) fruit.add(fruits.sieving.PPV(0.5)) fruit.add(fruits.sieving.END) # configure", "callbacks: callback.on_iterated_sum(iterated_data) for sieve in self._sieves_extended[i]: nf = sieve.nfeatures() new_features", "sieve._get_cache_keys() if 'coquantile' in sieve_keys: keys = keys.union(sieve_keys['coquantile']) return keys", "differ from ``None``. :param mode: See :meth:`fruits.signature.iss.SignatureCalculator.transform`, defaults to None", ") else: return ( sum([s.nfeatures() for s in self._sieves]) *", "False def nfeatures(self) -> int: \"\"\"Returns the total number of", "__init__(self): # lists of used classes for data processing self._preparateurs:", "from ``None``. :param mode: See :meth:`fruits.signature.iss.SignatureCalculator.transform`, defaults to None :type", "np.ndarray :param callbacks: List of callbacks. To write your own", "preparateurs for preprocessing fruit.add(fruits.preparation.INC) # add words for iterated sums", "random time series sample that is used for fitting. This", "self._calculator_options = {\"batch_size\": 1, \"mode\": \"single\"} def nfeatures(self) -> int:", "\"\"\" if not isinstance(word, Word): raise TypeError self._words.append(word) self._fitted =", "all added preparateurs, words and sieves. :rtype: str \"\"\" summary", "configure the fruit fruit.configure(mode=\"extended\") # fit the fruit on a", "summary += f\"\\nBranches: {len(self.branches())}\" summary += f\"\\nFeatures: {self.nfeatures()}\" for branch", "str): self._name = name def fork(self, branch: \"FruitBranch\" = None):", "== 1): ind = np.random.randint(0, X.shape[0]) return X[ind:ind+1, :, :]", "if batch_size is not None: self._calculator_options[\"batch_size\"] = batch_size if fit_sample_size", "if inspect.isclass(obj): obj = obj() if isinstance(obj, DataPreparateur): self.add_preparateur(obj) elif", "`:meth:`~fruits.scope.force_input_shape`. :type X: np.ndarray :returns: Array of features. :rtype: np.ndarray", "current branch index self._cbi: int = 0 self._fitted: bool =", "[] # pointer for the current branch index self._cbi: int", "in the ISS calculation self._calculator_options: dict = {\"batch_size\": 1, \"mode\":", "the start of the extraction procedure. There are many so", "np.ndarray) -> np.ndarray: \"\"\"Fits all branches to the given dataset", "if Fruit.fit wasn't called \"\"\" if not self._fitted: raise RuntimeError(\"Missing", "1, \"mode\": \"single\"} def nfeatures(self) -> int: \"\"\"Returns the total", "fruit.fit(X_train) # transform the dataset X_train_transformed = fruit.transform(X_train) X_test_tranformed =", "iss_calculations = SignatureCalculator().transform( prepared_data, words=self._words, **self._calculator_options )[0] for iterated_data in", "index += k result = np.nan_to_num(result, copy=False, nan=0.0) return result", "False def branch(self, index: int = None): \"\"\"Returns the currently", "switch_branch(self, index: int): \"\"\"Switches to the branch with the given", "List of callbacks. To write your own callback, override the", ":rtype: Fruit \"\"\" copy_ = Fruit(self.name+\" (Copy)\") for branch in", "RuntimeError if ``self.fit`` wasn't called \"\"\" if not self._fitted: raise", "list(self._collect_cache_keys())) def _select_fit_sample(self, X: np.ndarray) -> np.ndarray: # returns a", "of this Fruit object. This also creates deep copies of", "typing import List, Union, Set, Any import numpy as np", "copy_ def deepcopy(self) -> \"FruitBranch\": \"\"\"Returns a deep copy of", "list = [] self._words: list = [] self._sieves: list =", "self.add_sieve(obj) else: raise TypeError(\"Cannot add variable of type\"+str(type(obj))) def clear(self):", "class Fruit: \"\"\"Feature Extractor using iterated sums. A Fruit consists", "raise RuntimeError(\"No words specified for ISS calculation\") if not self._sieves:", "is given, an empty FruitBranch will be created and switched", "for fitting. This is represented as a float which will", "self._fitted = False def add_sieve(self, sieve: FeatureSieve): \"\"\"Appends a new", "\"single\"} def nfeatures(self) -> int: \"\"\"Returns the total number of", ":param index: Integer in ``[0, 1, ..., len(self.branches())-1]`` :type index:", "used classes for data processing self._preparateurs: list = [] self._words:", "a summary for each FruitBranch in this Fruit object. :rtype:", "the branch. :rtype: List[DataPreparateur] \"\"\" return self._preparateurs def clear_preparateurs(self): \"\"\"Removes", "None :type callbacks: List[AbstractCallback], optional :rtype: np.ndarray :raises: RuntimeError if", "of all feature sieves added to the branch. :rtype: List[FeatureSieve]", "defaults to 1 :type fit_sample_size: Union[float, int] \"\"\" if mode", "array of numbers (the transformed results from those sieves), i.e.", "add_word(self, word: Word): \"\"\"Adds a word to the branch. :type", "0 for branch in self._branches: for callback in callbacks: callback.on_next_branch()", "iterated sums. A Fruit consists of a number of :class:`~fruits.core.fruit.FruitBranch`", "type]): \"\"\"Adds one or multiple object(s) to the currently selected", "fit(self, X: np.ndarray): \"\"\"Fits the branch to the given dataset.", "self._calculator_options[\"mode\"] = mode if batch_size is not None: self._calculator_options[\"batch_size\"] =", "[]) -> np.ndarray: \"\"\"Returns a two dimensional array of all", "False def get_sieves(self) -> List[FeatureSieve]: \"\"\"Returns a list of all", "[] :type callbacks: List[AbstractCallback], optional :rtype: np.ndarray :raises: RuntimeError if", "a look at `:meth:`~fruits.scope.force_input_shape`. :type X: np.ndarray :returns: Array of", "\"\"\" if self._calculator_options[\"mode\"] == \"extended\": return ( sum([s.nfeatures() for s", "return X[indices, :, :] def fit(self, X: np.ndarray): \"\"\"Fits the", "Any): \"\"\"Makes changes to the default configuration of a all", "Word): self.add_word(obj) elif isinstance(obj, FeatureSieve): self.add_sieve(obj) else: raise TypeError(\"Cannot add", "k = branch.nfeatures() result[:, index:index+k] = branch.transform(X, callbacks) index +=", "of an ISS-result self._sieves_extended: list = [] # configurations for", "import force_input_shape, FitTransform from fruits.core.callback import AbstractCallback from fruits.signature.iss import", "+ \\ \"\\n\\t+ \".join([str(x) for x in self._words[:9]]) summary +=", "def nfeatures(self) -> int: \"\"\"Returns the total number of features", "summary += \"\\n\\t \".join(lines[1:]) return summary def copy(self) -> \"FruitBranch\":", "Array of features. :rtype: np.ndarray \"\"\" self.fit(X) return self.transform(X) def", "at :meth:`~fruits.scope.force_input_shape`. :type X: np.ndarray \"\"\" for branch in self._branches:", "dtype=object).flatten() for obj in objects_flattened: if inspect.isclass(obj): obj = obj()", "0 iss_calculations = SignatureCalculator().transform( prepared_data, words=self._words, **self._calculator_options )[0] for i,", "\"\"\"Removes all feature sieves that were added to this branch.\"\"\"", "configure(self, mode: str = None, batch_size: int = None, fit_sample_size:", "also creates deep copies of all branches in this object.", "copy of this Fruit object. This also creates deep copies", "returns an array of numbers (the transformed results from those", "of features the current configuration produces. :rtype: int \"\"\" if", "CachePlan from fruits.words.word import Word from fruits.sieving.abstract import FeatureSieve from", "-> List[FeatureSieve]: \"\"\"Returns a list of all feature sieves added", "# fit the fruit on a time series dataset fruit.fit(X_train)", "in callbacks: callback.on_preparation_end(prepared_data) sieved_data = np.zeros((prepared_data.shape[0], self.nfeatures())) k = 0", "self._branches[self._cbi] return self._branches[index] def branches(self) -> list: \"\"\"Returns all branches", "to the default configuration of a all branches if arguments", "raise TypeError self._preparateurs.append(preparateur) self._fitted = False def get_preparateurs(self) -> List[DataPreparateur]:", "one or multiple object(s) to the branch. :type objects: One", "multiple object(s) to the branch. :type objects: One or more", "look at :meth:`~fruits.scope.force_input_shape`. :type X: np.ndarray \"\"\" self._compile() self._get_cache(X) prepared_data", "the branch. :rtype: List[Word] \"\"\" return self._words def clear_words(self): \"\"\"Removes", "call of self.fit\") self._get_cache(X) prepared_data = force_input_shape(X) for prep in", "are many so called :class:`~fruits.preparation.abstract.DataPreparateur` objects in fruits available for", "\"\"\" copy_ = FruitBranch() for preparateur in self._preparateurs: copy_.add(preparateur.copy()) for", "np.ndarray :raises: RuntimeError if ``self.fit`` wasn't called \"\"\" if not", "list = [] # configurations for fitting self._fitted: bool =", "summary of this object. The summary contains all added preparateurs,", "features for each time series. \"\"\" def __init__(self): # lists", "FruitBranch() for preparateur in self._preparateurs: copy_.add(preparateur.copy()) for iterator in self._words:", "branches(self) -> list: \"\"\"Returns all branches of this Fruit object.", "summary += \"-\" elif len(self._words) > 10: summary += \"\\n\\t+", "as a newly created FruitBranch object. \"\"\" self.clear_preparateurs() self.clear_words() self.clear_sieves()", ":returns: Copy of the branch with same settings but all", "for each FruitBranch in this Fruit object. :rtype: str \"\"\"", "branch in self._branches: copy_.fork(branch.deepcopy()) return copy_ class FruitBranch: \"\"\"One branch", "CachePlan(self._words).n_iterated_sums( list(range(len(self._words))) ) ) else: return ( sum([s.nfeatures() for s", "branch.\"\"\" self._sieves = [] self._sieve_prerequisites = None self._sieves_extended = []", "raise IndexError(\"Index has to be in [0, len(self.branches()))\") self._cbi =", "this Fruit object. This also creates deep copies of all", "numbers (the transformed results from those sieves), i.e. the features", "import List, Union, Set, Any import numpy as np from", "fit_sample_size: Union[float, int] \"\"\" if mode is not None: self._calculator_options[\"mode\"]", "already processed cache needed in this branch self._cache = CoquantileCache()", "in self._words: copy_.add(iterator.copy()) for sieve in self._sieves: copy_.add(sieve.copy()) copy_._calculator_options =", "cache keys of all FitTransformers in the branch keys: Set[str]", "prep in self._preparateurs: prepared_data = prep.transform(prepared_data, cache=self._cache) for callback in", "results of X from all branches. :param X: (Multidimensional) time", "object. :rtype: Fruit \"\"\" copy_ = Fruit(self.name+\" (Copy)\") for branch", "int: \"\"\"Returns the total number of features the current configuration", "be applied sequentially to the input data. - Calculating Iterated", "the total number of features of all branches combined. :rtype:", "the branch with the given index. :rtype: FruitBranch \"\"\" if", "words for iterated sums calculation fruit.add(fruits.words.creation.simplewords_by_weight(4)) # choose sieves fruit.add(fruits.sieving.PPV(0.5))", "call of self.fit\") result = np.zeros((X.shape[0], self.nfeatures())) index = 0", "self._branches]) def configure(self, **kwargs: Any): \"\"\"Makes changes to the default", "``self.transform(X)`` consecutively does. :param X: (Multidimensional) time series dataset as", "name(self, name: str): self._name = name def fork(self, branch: \"FruitBranch\"", "mode: str = None, batch_size: int = None, fit_sample_size: Union[float,", "for callback in callbacks: callback.on_next_branch() k = branch.nfeatures() result[:, index:index+k]", "at fitting and also used in the # transformation process", "specify. - Extracting Features: Each :class:`~fruits.sieving.abstract.FeatureSieve` added to the branch", "f\"\\nSieves ({len(self._sieves)}): \" if len(self._sieves) == 0: summary += \"-\"", ":rtype: FruitBranch \"\"\" if index is None: return self._branches[self._cbi] return", "one random time series., defaults to 1 :type fit_sample_size: Union[float,", "fruits.scope import force_input_shape, FitTransform from fruits.core.callback import AbstractCallback from fruits.signature.iss", "+= \"\\n\\n\" + branch.summary() summary += \"\\n{:=^80}\".format(f\"End of Summary\") return", "Set[str] = set() for prep in self._preparateurs: prep_keys = prep._get_cache_keys()", "str: \"\"\"Returns a summary of this object. The summary contains", "add a new branch without INC fruit.fork() fruit.add(fruits.words.creation.simplewords_by_weight(4)) fruit.add(fruits.sieving.PPV(0.5)) fruit.add(fruits.sieving.END)", "and returns the transformed results of X from all branches.", "float which will be multiplied by ``X.shape[0]`` or ``1`` for", "for branch in self._branches: branch.configure(**kwargs) def fit(self, X: np.ndarray): \"\"\"Fits", "self._get_cache(X) prepared_data = self._select_fit_sample(X) for prep in self._preparateurs: prep.fit(prepared_data) prepared_data", ":rtype: np.ndarray :raises: RuntimeError if ``self.fit`` wasn't called \"\"\" if", "sieve to the FruitBranch. :type sieve: FeatureSieve \"\"\" if not", "word: Word \"\"\" if not isinstance(word, Word): raise TypeError self._words.append(word)", "the given time series dataset. The results are the calculated", "self._words def clear_words(self): \"\"\"Removes all words that were added to", "== \"extended\": return ( sum([s.nfeatures() for s in self._sieves]) *", "\"\"\"Fits all branches to the given dataset and returns the", "selected branch. :param objects: One or more objects of the", "FruitBranch() self._branches.append(branch) self._cbi = len(self._branches) - 1 self._fitted = False", "the branch keys: Set[str] = set() for prep in self._preparateurs:", "summary contains a summary for each FruitBranch in this Fruit", "sieved_data = np.zeros((prepared_data.shape[0], self.nfeatures())) k = 0 iss_calculations = SignatureCalculator().transform(", ") for callback in callbacks: callback.on_sieve(sieved_data[k:k+new_features]) k += new_features for", "self._fitted = False def get_words(self) -> List[Word]: \"\"\"Returns a list", "self._sieves_extended = [] iss_calculations = SignatureCalculator().transform( prepared_data, words=self._words, **self._calculator_options )[0]", "to None :type mode: str, optional :param batch_size: See :meth:`~ruits.signature.iss.SignatureCalculator.transform`,", "branches in this object. :rtype: Fruit \"\"\" copy_ = Fruit(self.name+\"", "summary += \"\\n\\t+ \" + \\ \"\\n\\t+ \".join([str(x) for x", "to the pipeline. If none is given, an empty FruitBranch", "batch_size: int = None, fit_sample_size: Union[float, int] = None): \"\"\"Makes", "\".join([str(x) for x in self._words[:9]]) summary += \"\\n\\t...\" else: summary", "= 0 iss_calculations = SignatureCalculator().transform( prepared_data, words=self._words, **self._calculator_options )[0] for", "objects_flattened = np.array(objects, dtype=object).flatten() for obj in objects_flattened: if inspect.isclass(obj):", "self._fitted = False def nfeatures(self) -> int: \"\"\"Returns the total", "return self._preparateurs def clear_preparateurs(self): \"\"\"Removes all preparateurs that were added", "self._calculator_options: dict = {\"batch_size\": 1, \"mode\": \"single\"} # list with", "fruit = fruits.Fruit(\"My Fruit\") # optional: add preparateurs for preprocessing", "mode: See :meth:`fruits.signature.iss.SignatureCalculator.transform`, defaults to None :type mode: str, optional", "isinstance(obj, DataPreparateur): self.add_preparateur(obj) elif isinstance(obj, Word): self.add_word(obj) elif isinstance(obj, FeatureSieve):", "\"\"\" objects_flattened = np.array(objects, dtype=object).flatten() for obj in objects_flattened: if", "in this Fruit object. :rtype: str \"\"\" summary = \"{:=^80}\".format(f\"Summary", "f\"\\n\\nPreparateurs ({len(self._preparateurs)}): \" if len(self._preparateurs) == 0: summary += \"-\"", "Fruit(self.name+\" (Copy)\") for branch in self._branches: copy_.fork(branch.copy()) return copy_ def", "settings but all calculations done erased. :rtype: FruitBranch \"\"\" copy_", "int] = None): \"\"\"Makes changes to the default configuration of", "in self._sieves: sieve_keys = sieve._get_cache_keys() if 'coquantile' in sieve_keys: keys", "# cache that is calculated at fitting and also used", "callback in callbacks: callback.on_next_branch() k = branch.nfeatures() result[:, index:index+k] =", "\" + \\ \"\\n\\t+ \".join([str(x) for x in self._words]) summary", "by ``X.shape[0]`` or ``1`` for one random time series., defaults", "np.ndarray) -> np.ndarray: # returns a sample of the data", "Word): \"\"\"Adds a word to the branch. :type word: Word", "the transformed results (features) in a classifier ... The ``fruit``", "for obj in objects_flattened: if inspect.isclass(obj): obj = obj() if", "in sieve_keys: keys = keys.union(sieve_keys['coquantile']) return keys def _get_cache(self, X:", "branch in self._branches: branch.configure(**kwargs) def fit(self, X: np.ndarray): \"\"\"Fits all", "\"\"\" copy_ = FruitBranch() for preparateur in self._preparateurs: copy_.add(preparateur) for", "and ``self.transform(X)`` consecutively does. :param X: (Multidimensional) time series dataset", "sieves), i.e. the features for each time series. \"\"\" def", "the currently selected branch or the branch with the given", "Summary\") return summary def copy(self) -> \"Fruit\": \"\"\"Creates a shallow", "keys = keys.union(prep_keys['coquantile']) for sieve in self._sieves: sieve_keys = sieve._get_cache_keys()", "# add words for iterated sums calculation fruit.add(fruits.words.creation.simplewords_by_weight(4)) # choose", "self._words: copy_.add(iterator) for sieve in self._sieves: copy_.add(sieve) return copy_ def", "series. \"\"\" def __init__(self): # lists of used classes for", "(the transformed results from those sieves), i.e. the features for", "List[AbstractCallback] = []) -> np.ndarray: \"\"\"Returns a two dimensional array", "for branch in self._branches: copy_.fork(branch.copy()) return copy_ def deepcopy(self) ->", "{len(self.branches())}\" summary += f\"\\nFeatures: {self.nfeatures()}\" for branch in self.branches(): summary", "np from fruits.cache import Cache, CoquantileCache from fruits.scope import force_input_shape,", "this branch.\"\"\" self._words = [] self._sieves_extended = [] self._fitted =", "series., defaults to 1 :type fit_sample_size: Union[float, int] \"\"\" if", "all branches to the given data. :param X: (Multidimensional) time", "this branch self._cache = CoquantileCache() self._cache.process(X, list(self._collect_cache_keys())) def _select_fit_sample(self, X:", "def deepcopy(self) -> \"Fruit\": \"\"\"Creates a deep copy of this", "None :type mode: str, optional :param batch_size: See :meth:`~ruits.signature.iss.SignatureCalculator.transform`, defaults", "series dataset :type X: np.ndarray :returns: Two dimensional feature array", "\"\\n\\n\" + branch.summary() summary += \"\\n{:=^80}\".format(f\"End of Summary\") return summary", "all feature sieves added to the branch. :rtype: List[FeatureSieve] \"\"\"", "with inner lists containing sieves # all sieves in one", "preparateurs that were added to this branch.\"\"\" self._preparateurs = []", "The results are the calculated features for the different time", "_collect_cache_keys(self) -> Set[str]: # collects cache keys of all FitTransformers", "features. :rtype: np.ndarray \"\"\" self.fit(X) return self.transform(X) def summary(self) ->", "this Fruit object. This also creates shallow copies of all", "input data. The user can customize any of the following", "None self._sieves_extended = [] self._fitted = False def add(self, *objects:", "sums calculation fruit.add(fruits.words.creation.simplewords_by_weight(4)) # choose sieves fruit.add(fruits.sieving.PPV(0.5)) fruit.add(fruits.sieving.END) # add", "of all words in the branch. :rtype: List[Word] \"\"\" return", "callback in callbacks: callback.on_sieve(sieved_data[k:k+new_features]) k += new_features for callback in", "self._cbi: int = 0 self._fitted: bool = False @property def", "Fruit.fit wasn't called \"\"\" if not self._fitted: raise RuntimeError(\"Missing call", "own features and they will be concatenated by this class.", "return copy_ class FruitBranch: \"\"\"One branch of a Fruit object.", "- :class:`~fruits.sieving.abstract.FeatureSieve` \"\"\" objects_flattened = np.array(objects, dtype=object).flatten() for obj in", "in callbacks: callback.on_iterated_sum(iterated_data) for sieve in self._sieves_extended[i]: nf = sieve.nfeatures()", "returns the transformed results of X from all branches. :param", "to the given data. :param X: (Multidimensional) time series dataset", "False def add(self, *objects: Union[FitTransform, Word, type]): \"\"\"Adds one or", "Union[float, int] = None): \"\"\"Makes changes to the default configuration", "fit the fruit on a time series dataset fruit.fit(X_train) #", "fruits.sieving.abstract import FeatureSieve from fruits.preparation.abstract import DataPreparateur class Fruit: \"\"\"Feature", "iterated_data in iss_calculations: iterated_data = iterated_data.reshape(iterated_data.shape[0] * iterated_data.shape[1], iterated_data.shape[2]) sieves_copy", "prep.transform(prepared_data, cache=self._cache) for callback in callbacks: callback.on_preparateur(prepared_data) for callback in", "series data that are somehow representative of the input data.", "-> list: \"\"\"Returns all branches of this Fruit object. :rtype:", "the default configuration of a all branches if arguments differ", "callback in callbacks: callback.on_preparateur(prepared_data) for callback in callbacks: callback.on_preparation_end(prepared_data) sieved_data", "\"\"\" if not isinstance(sieve, FeatureSieve): raise TypeError self._sieves.append(sieve) self._fitted =", "X[ind:ind+1, :, :] else: s = int(self._fit_sample_size * X.shape[0]) if", "self._sieves: copy_.add(sieve) return copy_ def deepcopy(self) -> \"FruitBranch\": \"\"\"Returns a", "words=self._words, **self._calculator_options )[0] for iterated_data in iss_calculations: iterated_data = iterated_data.reshape(iterated_data.shape[0]", "sieves_copy: sieve.fit(iterated_data[:, :]) self._sieves_extended.append(sieves_copy) self._fitted = True def transform(self, X:", "if len(self._words) == 0: summary += \"-\" elif len(self._words) >", "iss_calculations: iterated_data = iterated_data.reshape(iterated_data.shape[0] * iterated_data.shape[1], iterated_data.shape[2]) sieves_copy = [sieve.copy()", "0: summary += \"-\" else: for x in self._sieves: lines", "fit_sample_size: Union[float, int] = None): \"\"\"Makes changes to the default", "all branches of this Fruit object. :rtype: list \"\"\" return", "fit_sample_size: Size of the random time series sample that is", "list of all feature sieves added to the branch. :rtype:", "dict = {\"batch_size\": 1, \"mode\": \"single\"} # list with inner", "the branch will be fitted on the iterated sums from", "newly created FruitBranch object. \"\"\" self.clear_preparateurs() self.clear_words() self.clear_sieves() self._calculator_options =", "for branch in self._branches]) def configure(self, **kwargs: Any): \"\"\"Makes changes", "FruitBranch, optional \"\"\" if branch is None: branch = FruitBranch()", "if self._calculator_options[\"mode\"] == \"extended\": return ( sum([s.nfeatures() for s in", "0 self._fitted: bool = False @property def name(self) -> str:", "False def add_sieve(self, sieve: FeatureSieve): \"\"\"Appends a new feature sieve", ":type X: np.ndarray :returns: Array of features. :rtype: np.ndarray \"\"\"", "np.array(objects, dtype=object).flatten() for obj in objects_flattened: if inspect.isclass(obj): obj =", "word: Word): \"\"\"Adds a word to the branch. :type word:", "that are somehow representative of the input data. The user", "branch.\"\"\" self._preparateurs = [] self._fitted = False def add_word(self, word:", "= set() for prep in self._preparateurs: prep_keys = prep._get_cache_keys() if", "representative of the input data. The user can customize any", "preparateur to the branch. :type preparateur: DataPreparateur \"\"\" if not", "consists of a number of :class:`~fruits.core.fruit.FruitBranch` objects. At the end", "FeatureSieve from fruits.preparation.abstract import DataPreparateur class Fruit: \"\"\"Feature Extractor using", "object(s) to the branch. :type objects: One or more objects", "Preparing data: Apply functions at the start of the extraction", "+= f\"\\nNumber of features: {self.nfeatures()}\" summary += f\"\\n\\nPreparateurs ({len(self._preparateurs)}): \"", "from fruits.scope import force_input_shape, FitTransform from fruits.core.callback import AbstractCallback from", "@name.setter def name(self, name: str): self._name = name def fork(self,", "= {\"batch_size\": 1, \"mode\": \"single\"} # list with inner lists", "cache that is calculated at fitting and also used in", "A Fruit consists of a number of :class:`~fruits.core.fruit.FruitBranch` objects. At", "The preprocessed data is now used to calculate the iterated", "an empty FruitBranch will be created and switched to. :type", "in this object. :rtype: Fruit \"\"\" copy_ = Fruit(self.name+\" (Copy)\")", "\"\"\" if index is None: return self._branches[self._cbi] return self._branches[index] def", "for preparateur in self._preparateurs: copy_.add(preparateur.copy()) for iterator in self._words: copy_.add(iterator.copy())", "defaults to [] :type callbacks: List[AbstractCallback], optional :rtype: np.ndarray :raises:", "else: for x in self._sieves: lines = x.summary().split(\"\\n\") summary +=", "depends on the FruitBranch configuration. :param X: (Multidimensional) time series", "feature array :rtype: np.ndarray \"\"\" self.fit(X) return self.transform(X) def summary(self)", "fruit.add(fruits.words.creation.simplewords_by_weight(4)) # choose sieves fruit.add(fruits.sieving.PPV(0.5)) fruit.add(fruits.sieving.END) # add a new", "def name(self, name: str): self._name = name def fork(self, branch:", "\\ \"\\n\\t+ \".join([str(x) for x in self._words]) summary += f\"\\nSieves", "\"\"\"Creates a deep copy of this Fruit object. This also", "the branch with the given index. :param index: Integer in", "One or more objects of the following types: - :class:`~fruits.preparation.abstract.DataPreparateur`", "for preparateur in self._preparateurs: copy_.add(preparateur) for iterator in self._words: copy_.add(iterator)", "preparateur in self._preparateurs: copy_.add(preparateur) for iterator in self._words: copy_.add(iterator) for", "+= f\"\\nSieves ({len(self._sieves)}): \" if len(self._sieves) == 0: summary +=", "[] # calculator options used in the ISS calculation self._calculator_options:", "s = int(self._fit_sample_size * X.shape[0]) if s < 1: s", "this branch.\"\"\" self._preparateurs = [] self._fitted = False def add_word(self,", "TypeError self._words.append(word) self._fitted = False def get_words(self) -> List[Word]: \"\"\"Returns", "def __init__(self, name: str = \"\"): self.name: str = name", "Cache, CoquantileCache from fruits.scope import force_input_shape, FitTransform from fruits.core.callback import", "name(self) -> str: \"\"\"Simple identifier for the Fruit object.\"\"\" return", "sieves # all sieves in one list are trained on", "# checks if the FruitBranch is configured correctly and ready", "copy_.add(iterator.copy()) for sieve in self._sieves: copy_.add(sieve.copy()) copy_._calculator_options = self._calculator_options.copy() return", "FruitBranch is configured correctly and ready # for fitting if", "number of features the current configuration produces. :rtype: int \"\"\"", "all branches this Fruit object contains. :param X: (Multidimensional) time", "the extraction procedure. There are many so called :class:`~fruits.preparation.abstract.DataPreparateur` objects", "iterated sums signature for different :class:`~fruits.words.word.Word` objects the user can", ":class:`~fruits.sieving.abstract.FeatureSieve` \"\"\" objects_flattened = np.array(objects, dtype=object).flatten() for obj in objects_flattened:", "will be applied sequentially to the input data. - Calculating", "# of an ISS-result self._sieves_extended: list = [] # configurations", "the iterated sums signature for different :class:`~fruits.words.word.Word` objects the user", "np.ndarray: \"\"\"Transforms the given time series dataset. The results are", "dimensions. Have a look at `:meth:`~fruits.scope.force_input_shape`. :type X: np.ndarray :returns:", "clear(self): \"\"\"Clears all settings, configurations and calculated results the branch", "\"single\"} # list with inner lists containing sieves # all", "in sieves_copy: sieve.fit(iterated_data[:, :]) self._sieves_extended.append(sieves_copy) self._fitted = True def transform(self,", "Word, type]): \"\"\"Adds one or multiple object(s) to the currently", "[]) -> np.ndarray: \"\"\"Transforms the given time series dataset. The", "-> np.ndarray: \"\"\"Transforms the given time series dataset. The results", "+= \"-\" else: for x in self._sieves: lines = x.summary().split(\"\\n\")", "np.ndarray \"\"\" self._compile() self._get_cache(X) prepared_data = self._select_fit_sample(X) for prep in", "optional :param fit_sample_size: Size of the random time series sample", ":class:`~fruits.preparation.abstract.DataPreparateur` - :class:`~fruits.words.word.Word` - :class:`~fruits.sieving.abstract.FeatureSieve` :type objects: Union[FitTransform, Word] \"\"\"", "\"\"\"Returns a two dimensional array of all features from all", "Features: Each :class:`~fruits.sieving.abstract.FeatureSieve` added to the branch will be fitted", "1, ..., len(self.branches())-1]`` :type index: int \"\"\" if not (0", "self._branches[self._cbi].add(*objects) self._fitted = False def nfeatures(self) -> int: \"\"\"Returns the", "to the branch. :type preparateur: DataPreparateur \"\"\" if not isinstance(preparateur,", "not isinstance(preparateur, DataPreparateur): raise TypeError self._preparateurs.append(preparateur) self._fitted = False def", "that were added to this branch.\"\"\" self._sieves = [] self._sieve_prerequisites", "def deepcopy(self) -> \"FruitBranch\": \"\"\"Returns a deep copy of this", "\"\"\"Adds a preparateur to the branch. :type preparateur: DataPreparateur \"\"\"" ]
[ "not os.path.isdir(path): os.mkdir(path) class ParseDict(argparse.Action): def __call__(self, parser, namespace, values,", "= output[output.find('LATEST'):].split('\\\\n')[0].split(' ')[-1] return latest_version else: return False def _setup_rpi(vendor_id:", "and systemd service file\\n\" f\"to your system to enable automated", "of workoutizer commands. Usage, e.g.: \" \"wkz manage 'runserver 0.0.0.0:8000", "option_string=None): d = {} if values: for item in values:", "workoutizer.settings import WORKOUTIZER_DIR, WORKOUTIZER_DB_PATH, TRACKS_DIR from workoutizer import __version__ BASE_DIR", "check=False, start_at_task=None ) inventory = InventoryManager(loader=loader, sources=()) variable_manager = VariableManager(loader=loader,", "None): if not ip_port: ip_port = f\"{_get_local_ip_address()}:8000\" result = _run_ansible(", "ansible...\") _setup_rpi( vendor_id=vendor_id, product_id=product_id, ip_port=f\"{ip}:8000\" ) _run_ansible(playbook='install_packages.yml') click.echo(f\"Successfully configured to", "_upgrade(): latest_version = _get_latest_version_of(\"workoutizer\") from workoutizer import __version__ as current_version", "= s.getsockname()[0] s.close() return ip_address def _build_home(): if os.path.isdir(WORKOUTIZER_DIR): if", "manage 'runserver 0.0.0.0:8000 --noreload'.\") def manage(cmd): execute_from_command_line([\"manage.py\"] + cmd.split(' '))", "' 'and applies the required migrations.') def init(): _build_home() execute_from_command_line([\"manage.py\",", "above errors.\") quit() return result def _wkz_as_service(url: str): click.echo(f\"configuring workoutizer", "{WORKOUTIZER_DIR}\") @click.option('--ip', default=\"\", help=url_help) @click.option('--product_id', help=\"product ip of your device\",", "at {WORKOUTIZER_DB_PATH}\") return else: click.echo(f\"removed database at {WORKOUTIZER_DB_PATH}\") os.remove(WORKOUTIZER_DB_PATH) _make_tracks_dir(TRACKS_DIR)", "\"migrate\"]) execute_from_command_line([\"manage.py\", \"check\"]) click.echo(f\"Successfully upgraded from {current_version} to {latest_version}\") else:", "workoutizer to run as system service\") if not url: url", "changes \" f\"require a system restart to take effect.\") else:", "\"-m\", \"pip\", \"search\", package])) latest_version = output[output.find('LATEST'):].split('\\\\n')[0].split(' ')[-1] return latest_version", "pbex = PlaybookExecutor(playbooks=[os.path.join(SETUP_DIR, 'ansible', playbook)], inventory=inventory, variable_manager=variable_manager, loader=loader, passwords={}) return", "'setup') os.environ[\"DJANGO_SETTINGS_MODULE\"] = \"workoutizer.settings\" example_rpi_cmd = \"wkz --setup_rpi vendor_id=091e product_id=4b48\"", "being passed, it will be determined automatically.') def wkz_as_service(url): _pip_install('ansible==2.9.10')", "systemd service file\\n\" f\"to your system to enable automated mounting", "run(url): if not url: url = f\"{_get_local_ip_address()}:8000\" execute_from_command_line([\"manage.py\", \"runserver\", url])", "click.echo(f\"starting setup using ansible...\") _setup_rpi( vendor_id=vendor_id, product_id=product_id, ip_port=f\"{ip}:8000\" ) _run_ansible(playbook='install_packages.yml')", "\"pip\", \"install\", package]) def _run_ansible(playbook: str, variables: dict = None):", "upgrade: bool = False): if upgrade: subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\",", "files are stored in: {WORKOUTIZER_DIR}\") @click.option('--ip', default=\"\", help=url_help) @click.option('--product_id', help=\"product", "current_version if latest_version: click.echo(f\"found newer version: {latest_version}, you have {current_version}", "variables: dict = None): if variables is None: variables =", "logical value = split_items[1] d[key] = value setattr(namespace, self.dest, d)", "execute_from_command_line([\"manage.py\", \"runserver\", url]) @click.argument('url', default=\"\") @click.command(help='Configure workoutizer to run as", "product id is required. Passing ' f'the local ip address", "ip: ip = _get_local_ip_address() answer = input(f\"Are you sure you", "Raspberry Pi to auto mount devices. Passing vendor and product", "is optionally. E.g.: {example_rpi_cmd}') def setup_rpi(ip, vendor_id, product_id): if not", "device when plugged in. Note: These changes \" f\"require a", "required migrations.') def init(): _build_home() execute_from_command_line([\"manage.py\", \"collectstatic\", \"--noinput\"]) execute_from_command_line([\"manage.py\", \"migrate\"])", "click.echo(f\"installing ansible...\") _pip_install('ansible==2.9.10') click.echo(f\"starting setup using ansible...\") _setup_rpi( vendor_id=vendor_id, product_id=product_id,", "\" \"not yet covered with the given set of workoutizer", "of currently installed workoutizer.') def version(): click.echo(__version__) @click.command(help='Check for a", "package]) def _run_ansible(playbook: str, variables: dict = None): if variables", "else: os.mkdir(WORKOUTIZER_DIR) _make_tracks_dir(TRACKS_DIR) def _make_tracks_dir(path): if not os.path.isdir(path): os.mkdir(path) class", "cli.add_command(init) cli.add_command(setup_rpi) cli.add_command(run) cli.add_command(manage) cli.add_command(wkz_as_service) def _upgrade(): latest_version = _get_latest_version_of(\"workoutizer\")", "None): if variables is None: variables = {} from ansible", "import click from django.core.management import execute_from_command_line from workoutizer.settings import WORKOUTIZER_DIR,", "f\"Start setup? [Y/n] \") if answer.lower() == 'y': click.echo(f\"installing ansible...\")", "command to initialize workoutizer. This fetches the static files, creates", "effect.\") else: click.echo(f\"Aborted.\") @click.argument('url', default=\"\") @click.command(help=\"Run workoutizer. Passing the local", "devices. Passing vendor and product id is required. Passing '", "_run_ansible(playbook: str, variables: dict = None): if variables is None:", "if there is any.') def upgrade(): _upgrade() cli.add_command(upgrade) cli.add_command(version) cli.add_command(init)", "latest_version = _get_latest_version_of(\"workoutizer\") from workoutizer import __version__ as current_version if", "_make_tracks_dir(path): if not os.path.isdir(path): os.mkdir(path) class ParseDict(argparse.Action): def __call__(self, parser,", "\"wkz --setup_rpi vendor_id=091e product_id=4b48\" url_help = 'specify ip address and", "applied\\n\" f\"migrations on this database.\\n\\n\" f\"Do you want to use", "= os.path.dirname(os.path.dirname(__file__)) SETUP_DIR = os.path.join(BASE_DIR, 'setup') os.environ[\"DJANGO_SETTINGS_MODULE\"] = \"workoutizer.settings\" example_rpi_cmd", "str, product_id: str, ip_port: str = None): if not ip_port:", "upgrade: subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", package, '--upgrade']) else: subprocess.check_call([sys.executable, \"-m\",", "_get_latest_version_of(package: str): outdated = str( subprocess.check_output([sys.executable, \"-m\", \"pip\", \"list\", '--outdated',", "and install if there is any.') def upgrade(): _upgrade() cli.add_command(upgrade)", "if result == 0: click.echo(f\"Successfully configured workoutizer as systemd service.", "it with: systemctl start wkz.service\") else: click.echo(f\"ERROR: Could not configure", "{WORKOUTIZER_DB_PATH}\") os.remove(WORKOUTIZER_DB_PATH) _make_tracks_dir(TRACKS_DIR) else: os.mkdir(WORKOUTIZER_DIR) _make_tracks_dir(TRACKS_DIR) def _make_tracks_dir(path): if not", "be determined automatically. Usage, e.g.: 'wkz run 0.0.0.0:8000'.\") def run(url):", "instead of creating a new one? [Y/n] \") if answer.lower()", "like: address:port' @click.group() def cli(): pass @click.command(help='Mandatory command to initialize", "= {} from ansible import context from ansible.cli import CLI", "_get_local_ip_address(): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect((\"8.8.8.8\", 80)) ip_address = s.getsockname()[0]", "{WORKOUTIZER_DB_PATH}\") return else: click.echo(f\"removed database at {WORKOUTIZER_DB_PATH}\") os.remove(WORKOUTIZER_DB_PATH) _make_tracks_dir(TRACKS_DIR) else:", "_wkz_as_service(url: str): click.echo(f\"configuring workoutizer to run as system service\") if", "if package in outdated: output = str(subprocess.check_output([sys.executable, \"-m\", \"pip\", \"search\",", "forks=100, remote_user='xxx', private_key_file=None, ssh_common_args=None, ssh_extra_args=None, sftp_extra_args=None, scp_extra_args=None, become=True, become_method='sudo', become_user='root',", "result == 0: pass else: click.echo(f\"ERROR: Could not configure Raspberry", "commands. Usage, e.g.: \" \"wkz manage 'runserver 0.0.0.0:8000 --noreload'.\") def", "dict = None): if variables is None: variables = {}", "from workoutizer.settings import WORKOUTIZER_DIR, WORKOUTIZER_DB_PATH, TRACKS_DIR from workoutizer import __version__", "systemctl start wkz.service\") else: click.echo(f\"ERROR: Could not configure workoutizer as", "PlaybookExecutor from ansible.parsing.dataloader import DataLoader from ansible.inventory.manager import InventoryManager from", "str = None): if not ip_port: ip_port = f\"{_get_local_ip_address()}:8000\" result", "url, 'wkz_executable': wkz_executable, } ) if result == 0: click.echo(f\"Successfully", "port is ' 'optionally. In case of no ip address", "= item.split(\"=\", 1) key = split_items[0].strip() # we remove blanks", "\"install\", package, '--upgrade']) else: subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", package]) def", "url_help = 'specify ip address and port pair, like: address:port'", "automatically.') def wkz_as_service(url): _pip_install('ansible==2.9.10') _wkz_as_service(url=url) @click.argument('cmd', nargs=1) @click.command(help=\"Pass commands to", "device\", required=True) @click.option('--vendor_id', help=\"vendor ip of your device\", required=True) @click.command(help='Configure", "ip_address = s.getsockname()[0] s.close() return ip_address def _build_home(): if os.path.isdir(WORKOUTIZER_DIR):", "Run it with: systemctl start wkz.service\") else: click.echo(f\"ERROR: Could not", "DataLoader() context.CLIARGS = ImmutableDict( tags={}, listtags=False, listtasks=False, listhosts=False, syntax=False, connection='ssh',", "from workoutizer import __version__ as current_version if latest_version: click.echo(f\"found newer", "system to enable automated mounting of your device.\\n\" f\"This might", "because of mismatching applied\\n\" f\"migrations on this database.\\n\\n\" f\"Do you", "and port is optionally. In case of no ip address", "s.getsockname()[0] s.close() return ip_address def _build_home(): if os.path.isdir(WORKOUTIZER_DIR): if os.path.isfile(WORKOUTIZER_DB_PATH):", "workoutizer database at: {WORKOUTIZER_DB_PATH}\\n\") answer = input(f\"Workoutizer could try to", "latest_version: click.echo(f\"found newer version: {latest_version}, you have {current_version} installed\") _pip_install('workoutizer',", "def version(): click.echo(__version__) @click.command(help='Check for a newer version and install", "\"--noinput\"]) execute_from_command_line([\"manage.py\", \"migrate\"]) execute_from_command_line([\"manage.py\", \"check\"]) click.echo(f\"Successfully upgraded from {current_version} to", "if not url: url = f\"{_get_local_ip_address()}:8000\" execute_from_command_line([\"manage.py\", \"runserver\", url]) @click.argument('url',", "d = {} if values: for item in values: split_items", "{current_version} to {latest_version}\") else: click.echo(f\"No update available. You are running", "from workoutizer import __version__ BASE_DIR = os.path.dirname(os.path.dirname(__file__)) SETUP_DIR = os.path.join(BASE_DIR,", "ip address \" \"being passed, it will be determined automatically.", "if not os.path.isdir(path): os.mkdir(path) class ParseDict(argparse.Action): def __call__(self, parser, namespace,", "workoutizer to run as systemd service. Passing the local ip", "function to access all django commands which are \" \"not", "to access all django commands which are \" \"not yet", "address and port is ' 'optionally. In case of no", "click.echo(f\"keeping existing database at {WORKOUTIZER_DB_PATH}\") return else: click.echo(f\"removed database at", "'y': click.echo(f\"keeping existing database at {WORKOUTIZER_DB_PATH}\") return else: click.echo(f\"removed database", "address being passed, it will be determined automatically.') def wkz_as_service(url):", "outdated: output = str(subprocess.check_output([sys.executable, \"-m\", \"pip\", \"search\", package])) latest_version =", "_run_ansible(playbook='install_packages.yml') click.echo(f\"Successfully configured to automatically mount your device when plugged", "def setup_rpi(ip, vendor_id, product_id): if not ip: ip = _get_local_ip_address()", "from django.core.management import execute_from_command_line from workoutizer.settings import WORKOUTIZER_DIR, WORKOUTIZER_DB_PATH, TRACKS_DIR", "if answer.lower() == 'y': click.echo(f\"installing ansible...\") _pip_install('ansible==2.9.10') click.echo(f\"starting setup using", "E.g.: {example_rpi_cmd}') def setup_rpi(ip, vendor_id, product_id): if not ip: ip", "f\"This will copy the required udev rule and systemd service", "@click.argument('url', default=\"\") @click.command(help=\"Run workoutizer. Passing the local ip address and", "@click.command(help='Configure Raspberry Pi to auto mount devices. Passing vendor and", "system restart to take effect.\") else: click.echo(f\"Aborted.\") @click.argument('url', default=\"\") @click.command(help=\"Run", "could try to use the existing database instead of creating", "of mismatching applied\\n\" f\"migrations on this database.\\n\\n\" f\"Do you want", "might take a while...\\n\\n\" f\"Start setup? [Y/n] \") if answer.lower()", ") _run_ansible(playbook='install_packages.yml') click.echo(f\"Successfully configured to automatically mount your device when", "self.dest, d) def _pip_install(package, upgrade: bool = False): if upgrade:", "= DataLoader() context.CLIARGS = ImmutableDict( tags={}, listtags=False, listtasks=False, listhosts=False, syntax=False,", "execute_from_command_line([\"manage.py\", \"collectstatic\", \"--noinput\"]) execute_from_command_line([\"manage.py\", \"migrate\"]) execute_from_command_line([\"manage.py\", \"check\"]) click.echo(f\"Successfully upgraded from", "private_key_file=None, ssh_common_args=None, ssh_extra_args=None, sftp_extra_args=None, scp_extra_args=None, become=True, become_method='sudo', become_user='root', verbosity=True, check=False,", "at {WORKOUTIZER_DB_PATH}\") os.remove(WORKOUTIZER_DB_PATH) _make_tracks_dir(TRACKS_DIR) else: os.mkdir(WORKOUTIZER_DIR) _make_tracks_dir(TRACKS_DIR) def _make_tracks_dir(path): if", "os.path.isdir(WORKOUTIZER_DIR): if os.path.isfile(WORKOUTIZER_DB_PATH): click.echo(f\"Found existing workoutizer database at: {WORKOUTIZER_DB_PATH}\\n\") answer", "= {} if values: for item in values: split_items =", "import PlaybookExecutor from ansible.parsing.dataloader import DataLoader from ansible.inventory.manager import InventoryManager", "Note: These changes \" f\"require a system restart to take", "remote_user='xxx', private_key_file=None, ssh_common_args=None, ssh_extra_args=None, sftp_extra_args=None, scp_extra_args=None, become=True, become_method='sudo', become_user='root', verbosity=True,", "from ansible.vars.manager import VariableManager loader = DataLoader() context.CLIARGS = ImmutableDict(", "workoutizer import __version__ BASE_DIR = os.path.dirname(os.path.dirname(__file__)) SETUP_DIR = os.path.join(BASE_DIR, 'setup')", "= input(f\"Are you sure you want to setup your Raspberry", "database instead of creating a new one.\\n\" f\"Note that this", "= InventoryManager(loader=loader, sources=()) variable_manager = VariableManager(loader=loader, inventory=inventory, version_info=CLI.version_info(gitinfo=False)) variable_manager._extra_vars =", "local ip address and port is ' 'optionally. In case", "vendor_id=091e product_id=4b48\" url_help = 'specify ip address and port pair,", "= variables pbex = PlaybookExecutor(playbooks=[os.path.join(SETUP_DIR, 'ansible', playbook)], inventory=inventory, variable_manager=variable_manager, loader=loader,", "from ansible import context from ansible.cli import CLI from ansible.module_utils.common.collections", "' f'the local ip address and port is optionally. E.g.:", "You are running the latest version: {current_version}\") def _get_latest_version_of(package: str):", "@click.command(help='Check for a newer version and install if there is", "start_at_task=None ) inventory = InventoryManager(loader=loader, sources=()) variable_manager = VariableManager(loader=loader, inventory=inventory,", "configured workoutizer as systemd service. Run it with: systemctl start", "from ansible.cli import CLI from ansible.module_utils.common.collections import ImmutableDict from ansible.executor.playbook_executor", "'runserver 0.0.0.0:8000 --noreload'.\") def manage(cmd): execute_from_command_line([\"manage.py\"] + cmd.split(' ')) @click.command(help='Show", "workoutizer. This fetches the static files, creates the database '", "')) @click.command(help='Show the version of currently installed workoutizer.') def version():", "and product id is required. Passing ' f'the local ip", "which are \" \"not yet covered with the given set", "def _build_home(): if os.path.isdir(WORKOUTIZER_DIR): if os.path.isfile(WORKOUTIZER_DB_PATH): click.echo(f\"Found existing workoutizer database", "_get_latest_version_of(\"workoutizer\") from workoutizer import __version__ as current_version if latest_version: click.echo(f\"found", "mount your device when plugged in. Note: These changes \"", "if not ip_port: ip_port = f\"{_get_local_ip_address()}:8000\" result = _run_ansible( playbook='setup_on_rpi.yml',", "from {current_version} to {latest_version}\") else: click.echo(f\"No update available. You are", "'wkz_executable': wkz_executable, } ) if result == 0: click.echo(f\"Successfully configured", "if answer.lower() == 'y': click.echo(f\"keeping existing database at {WORKOUTIZER_DB_PATH}\") return", "connection='ssh', module_path=None, forks=100, remote_user='xxx', private_key_file=None, ssh_common_args=None, ssh_extra_args=None, sftp_extra_args=None, scp_extra_args=None, become=True,", "return result def _wkz_as_service(url: str): click.echo(f\"configuring workoutizer to run as", "env_binaries[:env_binaries.find('python')] + \"wkz\" result = _run_ansible( playbook='wkz_as_service.yml', variables={ 'address_plus_port': url,", "device\", required=True) @click.command(help='Configure Raspberry Pi to auto mount devices. Passing", "a system restart to take effect.\") else: click.echo(f\"Aborted.\") @click.argument('url', default=\"\")", ") inventory = InventoryManager(loader=loader, sources=()) variable_manager = VariableManager(loader=loader, inventory=inventory, version_info=CLI.version_info(gitinfo=False))", "address:port' @click.group() def cli(): pass @click.command(help='Mandatory command to initialize workoutizer.", "will copy the required udev rule and systemd service file\\n\"", "execute_from_command_line([\"manage.py\", \"check\"]) click.echo(f\"Successfully upgraded from {current_version} to {latest_version}\") else: click.echo(f\"No", "and port pair, like: address:port' @click.group() def cli(): pass @click.command(help='Mandatory", "InventoryManager(loader=loader, sources=()) variable_manager = VariableManager(loader=loader, inventory=inventory, version_info=CLI.version_info(gitinfo=False)) variable_manager._extra_vars = variables", "click from django.core.management import execute_from_command_line from workoutizer.settings import WORKOUTIZER_DIR, WORKOUTIZER_DB_PATH,", "of your device.\\n\" f\"This might take a while...\\n\\n\" f\"Start setup?", "not configure Raspberry Pi, see above errors.\") quit() return result", "lead to faulty behaviour because of mismatching applied\\n\" f\"migrations on", "systemd service. Passing the local ip address and port is", "click.echo(f\"No update available. You are running the latest version: {current_version}\")", "passed, it will be determined automatically. Usage, e.g.: 'wkz run", "product_id): if not ip: ip = _get_local_ip_address() answer = input(f\"Are", "0: pass else: click.echo(f\"ERROR: Could not configure Raspberry Pi, see", "s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect((\"8.8.8.8\", 80)) ip_address = s.getsockname()[0] s.close()", "cli.add_command(manage) cli.add_command(wkz_as_service) def _upgrade(): latest_version = _get_latest_version_of(\"workoutizer\") from workoutizer import", "else: click.echo(f\"No update available. You are running the latest version:", "not ip: ip = _get_local_ip_address() answer = input(f\"Are you sure", "see above errors.\") return result def _get_local_ip_address(): s = socket.socket(socket.AF_INET,", "f\"Note that this could lead to faulty behaviour because of", "setattr(namespace, self.dest, d) def _pip_install(package, upgrade: bool = False): if", "= f\"{_get_local_ip_address()}:8000\" execute_from_command_line([\"manage.py\", \"runserver\", url]) @click.argument('url', default=\"\") @click.command(help='Configure workoutizer to", "_pip_install('workoutizer', upgrade=True) execute_from_command_line([\"manage.py\", \"collectstatic\", \"--noinput\"]) execute_from_command_line([\"manage.py\", \"migrate\"]) execute_from_command_line([\"manage.py\", \"check\"]) click.echo(f\"Successfully", "are stored in: {WORKOUTIZER_DIR}\") @click.option('--ip', default=\"\", help=url_help) @click.option('--product_id', help=\"product ip", "= f\"{_get_local_ip_address()}:8000\" result = _run_ansible( playbook='setup_on_rpi.yml', variables={ 'vendor_id': vendor_id, 'product_id':", "result == 0: click.echo(f\"Successfully configured workoutizer as systemd service. Run", "{current_version}\") def _get_latest_version_of(package: str): outdated = str( subprocess.check_output([sys.executable, \"-m\", \"pip\",", "{example_rpi_cmd}') def setup_rpi(ip, vendor_id, product_id): if not ip: ip =", "def wkz_as_service(url): _pip_install('ansible==2.9.10') _wkz_as_service(url=url) @click.argument('cmd', nargs=1) @click.command(help=\"Pass commands to django's", "vendor and product id is required. Passing ' f'the local", "WORKOUTIZER_DB_PATH, TRACKS_DIR from workoutizer import __version__ BASE_DIR = os.path.dirname(os.path.dirname(__file__)) SETUP_DIR", "database instead of creating a new one? [Y/n] \") if", "click.echo(f\"Successfully configured to automatically mount your device when plugged in.", "BASE_DIR = os.path.dirname(os.path.dirname(__file__)) SETUP_DIR = os.path.join(BASE_DIR, 'setup') os.environ[\"DJANGO_SETTINGS_MODULE\"] = \"workoutizer.settings\"", "@click.option('--product_id', help=\"product ip of your device\", required=True) @click.option('--vendor_id', help=\"vendor ip", "not url: url = f\"{_get_local_ip_address()}:8000\" execute_from_command_line([\"manage.py\", \"runserver\", url]) @click.argument('url', default=\"\")", "_wkz_as_service(url=url) @click.argument('cmd', nargs=1) @click.command(help=\"Pass commands to django's manage.py. Convenience function", "syntax=False, connection='ssh', module_path=None, forks=100, remote_user='xxx', private_key_file=None, ssh_common_args=None, ssh_extra_args=None, sftp_extra_args=None, scp_extra_args=None,", "\") if answer.lower() == 'y': click.echo(f\"keeping existing database at {WORKOUTIZER_DB_PATH}\")", "configured to automatically mount your device when plugged in. Note:", "values: split_items = item.split(\"=\", 1) key = split_items[0].strip() # we", "variables={ 'vendor_id': vendor_id, 'product_id': product_id, 'address_plus_port': ip_port, } ) if", "existing database instead of creating a new one.\\n\" f\"Note that", "values: for item in values: split_items = item.split(\"=\", 1) key", "if result == 0: pass else: click.echo(f\"ERROR: Could not configure", "of creating a new one.\\n\" f\"Note that this could lead", "ansible import context from ansible.cli import CLI from ansible.module_utils.common.collections import", "latest_version = output[output.find('LATEST'):].split('\\\\n')[0].split(' ')[-1] return latest_version else: return False def", "no ip address \" \"being passed, it will be determined", "service, see above errors.\") return result def _get_local_ip_address(): s =", "auto mount devices. Passing vendor and product id is required.", "see above errors.\") quit() return result def _wkz_as_service(url: str): click.echo(f\"configuring", "ip of your device\", required=True) @click.command(help='Configure Raspberry Pi to auto", "example_rpi_cmd = \"wkz --setup_rpi vendor_id=091e product_id=4b48\" url_help = 'specify ip", "you have {current_version} installed\") _pip_install('workoutizer', upgrade=True) execute_from_command_line([\"manage.py\", \"collectstatic\", \"--noinput\"]) execute_from_command_line([\"manage.py\",", "version_info=CLI.version_info(gitinfo=False)) variable_manager._extra_vars = variables pbex = PlaybookExecutor(playbooks=[os.path.join(SETUP_DIR, 'ansible', playbook)], inventory=inventory,", "manage.py. Convenience function to access all django commands which are", "wkz.service\") else: click.echo(f\"ERROR: Could not configure workoutizer as systemd service,", "TRACKS_DIR from workoutizer import __version__ BASE_DIR = os.path.dirname(os.path.dirname(__file__)) SETUP_DIR =", "when plugged in. Note: These changes \" f\"require a system", "ImmutableDict( tags={}, listtags=False, listtasks=False, listhosts=False, syntax=False, connection='ssh', module_path=None, forks=100, remote_user='xxx',", "str( subprocess.check_output([sys.executable, \"-m\", \"pip\", \"list\", '--outdated', '--disable-pip-version-check'])) if package in", "from ansible.module_utils.common.collections import ImmutableDict from ansible.executor.playbook_executor import PlaybookExecutor from ansible.parsing.dataloader", "def run(url): if not url: url = f\"{_get_local_ip_address()}:8000\" execute_from_command_line([\"manage.py\", \"runserver\",", "import sys import click from django.core.management import execute_from_command_line from workoutizer.settings", "using ansible...\") _setup_rpi( vendor_id=vendor_id, product_id=product_id, ip_port=f\"{ip}:8000\" ) _run_ansible(playbook='install_packages.yml') click.echo(f\"Successfully configured", "click.echo(f\"database and track files are stored in: {WORKOUTIZER_DIR}\") @click.option('--ip', default=\"\",", "your system to enable automated mounting of your device.\\n\" f\"This", "restart to take effect.\") else: click.echo(f\"Aborted.\") @click.argument('url', default=\"\") @click.command(help=\"Run workoutizer.", "__version__ BASE_DIR = os.path.dirname(os.path.dirname(__file__)) SETUP_DIR = os.path.join(BASE_DIR, 'setup') os.environ[\"DJANGO_SETTINGS_MODULE\"] =", "address and port pair, like: address:port' @click.group() def cli(): pass", "variables={ 'address_plus_port': url, 'wkz_executable': wkz_executable, } ) if result ==", "creating a new one? [Y/n] \") if answer.lower() == 'y':", "newer version: {latest_version}, you have {current_version} installed\") _pip_install('workoutizer', upgrade=True) execute_from_command_line([\"manage.py\",", "{latest_version}\") else: click.echo(f\"No update available. You are running the latest", "0: click.echo(f\"Successfully configured workoutizer as systemd service. Run it with:", "socket import sys import click from django.core.management import execute_from_command_line from", "applies the required migrations.') def init(): _build_home() execute_from_command_line([\"manage.py\", \"collectstatic\", \"--noinput\"])", "key = split_items[0].strip() # we remove blanks around keys, as", "0.0.0.0:8000'.\") def run(url): if not url: url = f\"{_get_local_ip_address()}:8000\" execute_from_command_line([\"manage.py\",", "value setattr(namespace, self.dest, d) def _pip_install(package, upgrade: bool = False):", "else: click.echo(f\"Aborted.\") @click.argument('url', default=\"\") @click.command(help=\"Run workoutizer. Passing the local ip", "ansible.parsing.dataloader import DataLoader from ansible.inventory.manager import InventoryManager from ansible.vars.manager import", "playbook)], inventory=inventory, variable_manager=variable_manager, loader=loader, passwords={}) return pbex.run() if __name__ ==", "all django commands which are \" \"not yet covered with", "answer.lower() == 'y': click.echo(f\"installing ansible...\") _pip_install('ansible==2.9.10') click.echo(f\"starting setup using ansible...\")", "+ cmd.split(' ')) @click.command(help='Show the version of currently installed workoutizer.')", "import WORKOUTIZER_DIR, WORKOUTIZER_DB_PATH, TRACKS_DIR from workoutizer import __version__ BASE_DIR =", "manage(cmd): execute_from_command_line([\"manage.py\"] + cmd.split(' ')) @click.command(help='Show the version of currently", "{latest_version}, you have {current_version} installed\") _pip_install('workoutizer', upgrade=True) execute_from_command_line([\"manage.py\", \"collectstatic\", \"--noinput\"])", "= str(subprocess.check_output([sys.executable, \"-m\", \"pip\", \"search\", package])) latest_version = output[output.find('LATEST'):].split('\\\\n')[0].split(' ')[-1]", "str, ip_port: str = None): if not ip_port: ip_port =", "d) def _pip_install(package, upgrade: bool = False): if upgrade: subprocess.check_call([sys.executable,", "os.mkdir(WORKOUTIZER_DIR) _make_tracks_dir(TRACKS_DIR) def _make_tracks_dir(path): if not os.path.isdir(path): os.mkdir(path) class ParseDict(argparse.Action):", "your device.\\n\" f\"This might take a while...\\n\\n\" f\"Start setup? [Y/n]", "the existing database instead of creating a new one.\\n\" f\"Note", "ip_port, } ) if result == 0: pass else: click.echo(f\"ERROR:", "subprocess.check_output([sys.executable, \"-m\", \"pip\", \"list\", '--outdated', '--disable-pip-version-check'])) if package in outdated:", "is ' 'optionally. In case of no ip address being", "is any.') def upgrade(): _upgrade() cli.add_command(upgrade) cli.add_command(version) cli.add_command(init) cli.add_command(setup_rpi) cli.add_command(run)", "ImmutableDict from ansible.executor.playbook_executor import PlaybookExecutor from ansible.parsing.dataloader import DataLoader from", "module_path=None, forks=100, remote_user='xxx', private_key_file=None, ssh_common_args=None, ssh_extra_args=None, sftp_extra_args=None, scp_extra_args=None, become=True, become_method='sudo',", "result def _get_local_ip_address(): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect((\"8.8.8.8\", 80)) ip_address", "else: return False def _setup_rpi(vendor_id: str, product_id: str, ip_port: str", "if os.path.isdir(WORKOUTIZER_DIR): if os.path.isfile(WORKOUTIZER_DB_PATH): click.echo(f\"Found existing workoutizer database at: {WORKOUTIZER_DB_PATH}\\n\")", "def upgrade(): _upgrade() cli.add_command(upgrade) cli.add_command(version) cli.add_command(init) cli.add_command(setup_rpi) cli.add_command(run) cli.add_command(manage) cli.add_command(wkz_as_service)", "existing workoutizer database at: {WORKOUTIZER_DB_PATH}\\n\") answer = input(f\"Workoutizer could try", "_pip_install('ansible==2.9.10') _wkz_as_service(url=url) @click.argument('cmd', nargs=1) @click.command(help=\"Pass commands to django's manage.py. Convenience", "PlaybookExecutor(playbooks=[os.path.join(SETUP_DIR, 'ansible', playbook)], inventory=inventory, variable_manager=variable_manager, loader=loader, passwords={}) return pbex.run() if", "determined automatically.') def wkz_as_service(url): _pip_install('ansible==2.9.10') _wkz_as_service(url=url) @click.argument('cmd', nargs=1) @click.command(help=\"Pass commands", "import execute_from_command_line from workoutizer.settings import WORKOUTIZER_DIR, WORKOUTIZER_DB_PATH, TRACKS_DIR from workoutizer", "package])) latest_version = output[output.find('LATEST'):].split('\\\\n')[0].split(' ')[-1] return latest_version else: return False", "sftp_extra_args=None, scp_extra_args=None, become=True, become_method='sudo', become_user='root', verbosity=True, check=False, start_at_task=None ) inventory", "\"not yet covered with the given set of workoutizer commands.", "nargs=1) @click.command(help=\"Pass commands to django's manage.py. Convenience function to access", "return False def _setup_rpi(vendor_id: str, product_id: str, ip_port: str =", "on this database.\\n\\n\" f\"Do you want to use the existing", "= _run_ansible( playbook='setup_on_rpi.yml', variables={ 'vendor_id': vendor_id, 'product_id': product_id, 'address_plus_port': ip_port,", "use the existing database instead of creating a new one?", "port is optionally. In case of no ip address \"", "to take effect.\") else: click.echo(f\"Aborted.\") @click.argument('url', default=\"\") @click.command(help=\"Run workoutizer. Passing", "values, option_string=None): d = {} if values: for item in", "the local ip address and port is ' 'optionally. In", "= 'specify ip address and port pair, like: address:port' @click.group()", "port is optionally. E.g.: {example_rpi_cmd}') def setup_rpi(ip, vendor_id, product_id): if", "str): click.echo(f\"configuring workoutizer to run as system service\") if not", "version and install if there is any.') def upgrade(): _upgrade()", "the version of currently installed workoutizer.') def version(): click.echo(__version__) @click.command(help='Check", "s.connect((\"8.8.8.8\", 80)) ip_address = s.getsockname()[0] s.close() return ip_address def _build_home():", "workoutizer commands. Usage, e.g.: \" \"wkz manage 'runserver 0.0.0.0:8000 --noreload'.\")", "url: url = f\"{_get_local_ip_address()}:8000\" env_binaries = sys.executable wkz_executable = env_binaries[:env_binaries.find('python')]", "to automatically mount your device when plugged in. Note: These", "workoutizer as systemd service. Run it with: systemctl start wkz.service\")", "return latest_version else: return False def _setup_rpi(vendor_id: str, product_id: str,", "remove blanks around keys, as is logical value = split_items[1]", "django commands which are \" \"not yet covered with the", "os.mkdir(path) class ParseDict(argparse.Action): def __call__(self, parser, namespace, values, option_string=None): d", "database.\\n\\n\" f\"Do you want to use the existing database instead", "service. Passing the local ip address and port is '", "import ImmutableDict from ansible.executor.playbook_executor import PlaybookExecutor from ansible.parsing.dataloader import DataLoader", "variables pbex = PlaybookExecutor(playbooks=[os.path.join(SETUP_DIR, 'ansible', playbook)], inventory=inventory, variable_manager=variable_manager, loader=loader, passwords={})", "you sure you want to setup your Raspberry Pi?\\n\\n\" f\"This", "execute_from_command_line([\"manage.py\", \"collectstatic\", \"--noinput\"]) execute_from_command_line([\"manage.py\", \"migrate\"]) execute_from_command_line([\"manage.py\", \"check\"]) click.echo(f\"database and track", "take a while...\\n\\n\" f\"Start setup? [Y/n] \") if answer.lower() ==", "\") if answer.lower() == 'y': click.echo(f\"installing ansible...\") _pip_install('ansible==2.9.10') click.echo(f\"starting setup", "given set of workoutizer commands. Usage, e.g.: \" \"wkz manage", "pass else: click.echo(f\"ERROR: Could not configure Raspberry Pi, see above", "faulty behaviour because of mismatching applied\\n\" f\"migrations on this database.\\n\\n\"", "ip_port: str = None): if not ip_port: ip_port = f\"{_get_local_ip_address()}:8000\"", "answer = input(f\"Are you sure you want to setup your", "1) key = split_items[0].strip() # we remove blanks around keys,", "ansible.cli import CLI from ansible.module_utils.common.collections import ImmutableDict from ansible.executor.playbook_executor import", "Pi?\\n\\n\" f\"This will copy the required udev rule and systemd", "False): if upgrade: subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", package, '--upgrade']) else:", "to use the existing database instead of creating a new", "id is required. Passing ' f'the local ip address and", "else: click.echo(f\"removed database at {WORKOUTIZER_DB_PATH}\") os.remove(WORKOUTIZER_DB_PATH) _make_tracks_dir(TRACKS_DIR) else: os.mkdir(WORKOUTIZER_DIR) _make_tracks_dir(TRACKS_DIR)", "bool = False): if upgrade: subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", package,", "_upgrade() cli.add_command(upgrade) cli.add_command(version) cli.add_command(init) cli.add_command(setup_rpi) cli.add_command(run) cli.add_command(manage) cli.add_command(wkz_as_service) def _upgrade():", "sys.executable wkz_executable = env_binaries[:env_binaries.find('python')] + \"wkz\" result = _run_ansible( playbook='wkz_as_service.yml',", "optionally. E.g.: {example_rpi_cmd}') def setup_rpi(ip, vendor_id, product_id): if not ip:", "split_items[1] d[key] = value setattr(namespace, self.dest, d) def _pip_install(package, upgrade:", "plugged in. Note: These changes \" f\"require a system restart", "url: url = f\"{_get_local_ip_address()}:8000\" execute_from_command_line([\"manage.py\", \"runserver\", url]) @click.argument('url', default=\"\") @click.command(help='Configure", "is logical value = split_items[1] d[key] = value setattr(namespace, self.dest,", "\"install\", package]) def _run_ansible(playbook: str, variables: dict = None): if", "in outdated: output = str(subprocess.check_output([sys.executable, \"-m\", \"pip\", \"search\", package])) latest_version", "+ \"wkz\" result = _run_ansible( playbook='wkz_as_service.yml', variables={ 'address_plus_port': url, 'wkz_executable':", "is None: variables = {} from ansible import context from", "ip address being passed, it will be determined automatically.') def", "in: {WORKOUTIZER_DIR}\") @click.option('--ip', default=\"\", help=url_help) @click.option('--product_id', help=\"product ip of your", "latest version: {current_version}\") def _get_latest_version_of(package: str): outdated = str( subprocess.check_output([sys.executable,", "latest_version else: return False def _setup_rpi(vendor_id: str, product_id: str, ip_port:", "@click.command(help='Show the version of currently installed workoutizer.') def version(): click.echo(__version__)", "ip of your device\", required=True) @click.option('--vendor_id', help=\"vendor ip of your", "{WORKOUTIZER_DB_PATH}\\n\") answer = input(f\"Workoutizer could try to use the existing", "one.\\n\" f\"Note that this could lead to faulty behaviour because", "local ip address and port is optionally. In case of", "= str( subprocess.check_output([sys.executable, \"-m\", \"pip\", \"list\", '--outdated', '--disable-pip-version-check'])) if package", "package, '--upgrade']) else: subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", package]) def _run_ansible(playbook:", "_run_ansible( playbook='wkz_as_service.yml', variables={ 'address_plus_port': url, 'wkz_executable': wkz_executable, } ) if", "'ansible', playbook)], inventory=inventory, variable_manager=variable_manager, loader=loader, passwords={}) return pbex.run() if __name__", "required=True) @click.command(help='Configure Raspberry Pi to auto mount devices. Passing vendor", "the local ip address and port is optionally. In case", "False def _setup_rpi(vendor_id: str, product_id: str, ip_port: str = None):", "copy the required udev rule and systemd service file\\n\" f\"to", "above errors.\") return result def _get_local_ip_address(): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)", "__version__ as current_version if latest_version: click.echo(f\"found newer version: {latest_version}, you", "answer.lower() == 'y': click.echo(f\"keeping existing database at {WORKOUTIZER_DB_PATH}\") return else:", "with the given set of workoutizer commands. Usage, e.g.: \"", "item.split(\"=\", 1) key = split_items[0].strip() # we remove blanks around", "currently installed workoutizer.') def version(): click.echo(__version__) @click.command(help='Check for a newer", "DataLoader from ansible.inventory.manager import InventoryManager from ansible.vars.manager import VariableManager loader", "of no ip address being passed, it will be determined", "run 0.0.0.0:8000'.\") def run(url): if not url: url = f\"{_get_local_ip_address()}:8000\"", "run as systemd service. Passing the local ip address and", "listhosts=False, syntax=False, connection='ssh', module_path=None, forks=100, remote_user='xxx', private_key_file=None, ssh_common_args=None, ssh_extra_args=None, sftp_extra_args=None,", "your device\", required=True) @click.command(help='Configure Raspberry Pi to auto mount devices.", "result def _wkz_as_service(url: str): click.echo(f\"configuring workoutizer to run as system", "a while...\\n\\n\" f\"Start setup? [Y/n] \") if answer.lower() == 'y':", "\"-m\", \"pip\", \"list\", '--outdated', '--disable-pip-version-check'])) if package in outdated: output", "env_binaries = sys.executable wkz_executable = env_binaries[:env_binaries.find('python')] + \"wkz\" result =", "return result def _get_local_ip_address(): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect((\"8.8.8.8\", 80))", "subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", package]) def _run_ansible(playbook: str, variables: dict", "version: {latest_version}, you have {current_version} installed\") _pip_install('workoutizer', upgrade=True) execute_from_command_line([\"manage.py\", \"collectstatic\",", "from ansible.inventory.manager import InventoryManager from ansible.vars.manager import VariableManager loader =", "class ParseDict(argparse.Action): def __call__(self, parser, namespace, values, option_string=None): d =", "ip address and port is optionally. E.g.: {example_rpi_cmd}') def setup_rpi(ip,", "to enable automated mounting of your device.\\n\" f\"This might take", "= value setattr(namespace, self.dest, d) def _pip_install(package, upgrade: bool =", "== 'y': click.echo(f\"installing ansible...\") _pip_install('ansible==2.9.10') click.echo(f\"starting setup using ansible...\") _setup_rpi(", "} ) if result == 0: pass else: click.echo(f\"ERROR: Could", "not url: url = f\"{_get_local_ip_address()}:8000\" env_binaries = sys.executable wkz_executable =", "Passing the local ip address and port is optionally. In", "cli(): pass @click.command(help='Mandatory command to initialize workoutizer. This fetches the", "inventory=inventory, variable_manager=variable_manager, loader=loader, passwords={}) return pbex.run() if __name__ == '__main__':", "\"workoutizer.settings\" example_rpi_cmd = \"wkz --setup_rpi vendor_id=091e product_id=4b48\" url_help = 'specify", "cli.add_command(wkz_as_service) def _upgrade(): latest_version = _get_latest_version_of(\"workoutizer\") from workoutizer import __version__", "upgraded from {current_version} to {latest_version}\") else: click.echo(f\"No update available. You", "database at {WORKOUTIZER_DB_PATH}\") return else: click.echo(f\"removed database at {WORKOUTIZER_DB_PATH}\") os.remove(WORKOUTIZER_DB_PATH)", "systemd service. Run it with: systemctl start wkz.service\") else: click.echo(f\"ERROR:", "we remove blanks around keys, as is logical value =", "setup? [Y/n] \") if answer.lower() == 'y': click.echo(f\"installing ansible...\") _pip_install('ansible==2.9.10')", "will be determined automatically.') def wkz_as_service(url): _pip_install('ansible==2.9.10') _wkz_as_service(url=url) @click.argument('cmd', nargs=1)", "from ansible.parsing.dataloader import DataLoader from ansible.inventory.manager import InventoryManager from ansible.vars.manager", "to initialize workoutizer. This fetches the static files, creates the", "'--outdated', '--disable-pip-version-check'])) if package in outdated: output = str(subprocess.check_output([sys.executable, \"-m\",", "Could not configure workoutizer as systemd service, see above errors.\")", "scp_extra_args=None, become=True, become_method='sudo', become_user='root', verbosity=True, check=False, start_at_task=None ) inventory =", "os.path.isfile(WORKOUTIZER_DB_PATH): click.echo(f\"Found existing workoutizer database at: {WORKOUTIZER_DB_PATH}\\n\") answer = input(f\"Workoutizer", "Raspberry Pi?\\n\\n\" f\"This will copy the required udev rule and", "workoutizer. Passing the local ip address and port is optionally.", "f\"{_get_local_ip_address()}:8000\" env_binaries = sys.executable wkz_executable = env_binaries[:env_binaries.find('python')] + \"wkz\" result", "is optionally. In case of no ip address \" \"being", "is required. Passing ' f'the local ip address and port", "commands to django's manage.py. Convenience function to access all django", "execute_from_command_line from workoutizer.settings import WORKOUTIZER_DIR, WORKOUTIZER_DB_PATH, TRACKS_DIR from workoutizer import", "installed workoutizer.') def version(): click.echo(__version__) @click.command(help='Check for a newer version", "\"collectstatic\", \"--noinput\"]) execute_from_command_line([\"manage.py\", \"migrate\"]) execute_from_command_line([\"manage.py\", \"check\"]) click.echo(f\"Successfully upgraded from {current_version}", "\"wkz manage 'runserver 0.0.0.0:8000 --noreload'.\") def manage(cmd): execute_from_command_line([\"manage.py\"] + cmd.split('", "it will be determined automatically.') def wkz_as_service(url): _pip_install('ansible==2.9.10') _wkz_as_service(url=url) @click.argument('cmd',", "In case of no ip address being passed, it will", "to {latest_version}\") else: click.echo(f\"No update available. You are running the", "s.close() return ip_address def _build_home(): if os.path.isdir(WORKOUTIZER_DIR): if os.path.isfile(WORKOUTIZER_DB_PATH): click.echo(f\"Found", "the latest version: {current_version}\") def _get_latest_version_of(package: str): outdated = str(", "for a newer version and install if there is any.')", "enable automated mounting of your device.\\n\" f\"This might take a", "service file\\n\" f\"to your system to enable automated mounting of", "These changes \" f\"require a system restart to take effect.\")", "= VariableManager(loader=loader, inventory=inventory, version_info=CLI.version_info(gitinfo=False)) variable_manager._extra_vars = variables pbex = PlaybookExecutor(playbooks=[os.path.join(SETUP_DIR,", "upgrade(): _upgrade() cli.add_command(upgrade) cli.add_command(version) cli.add_command(init) cli.add_command(setup_rpi) cli.add_command(run) cli.add_command(manage) cli.add_command(wkz_as_service) def", "@click.argument('cmd', nargs=1) @click.command(help=\"Pass commands to django's manage.py. Convenience function to", "one? [Y/n] \") if answer.lower() == 'y': click.echo(f\"keeping existing database", "\"being passed, it will be determined automatically. Usage, e.g.: 'wkz", "case of no ip address \" \"being passed, it will", "item in values: split_items = item.split(\"=\", 1) key = split_items[0].strip()", "def _pip_install(package, upgrade: bool = False): if upgrade: subprocess.check_call([sys.executable, \"-m\",", "product_id=product_id, ip_port=f\"{ip}:8000\" ) _run_ansible(playbook='install_packages.yml') click.echo(f\"Successfully configured to automatically mount your", "cmd.split(' ')) @click.command(help='Show the version of currently installed workoutizer.') def", "commands which are \" \"not yet covered with the given", "click.echo(f\"ERROR: Could not configure Raspberry Pi, see above errors.\") quit()", "variable_manager=variable_manager, loader=loader, passwords={}) return pbex.run() if __name__ == '__main__': cli()", "version(): click.echo(__version__) @click.command(help='Check for a newer version and install if", "local ip address and port is optionally. E.g.: {example_rpi_cmd}') def", "\"search\", package])) latest_version = output[output.find('LATEST'):].split('\\\\n')[0].split(' ')[-1] return latest_version else: return", "def _make_tracks_dir(path): if not os.path.isdir(path): os.mkdir(path) class ParseDict(argparse.Action): def __call__(self,", "database at {WORKOUTIZER_DB_PATH}\") os.remove(WORKOUTIZER_DB_PATH) _make_tracks_dir(TRACKS_DIR) else: os.mkdir(WORKOUTIZER_DIR) _make_tracks_dir(TRACKS_DIR) def _make_tracks_dir(path):", "d[key] = value setattr(namespace, self.dest, d) def _pip_install(package, upgrade: bool", "optionally. In case of no ip address \" \"being passed,", "newer version and install if there is any.') def upgrade():", "default=\"\") @click.command(help=\"Run workoutizer. Passing the local ip address and port", "fetches the static files, creates the database ' 'and applies", "= _run_ansible( playbook='wkz_as_service.yml', variables={ 'address_plus_port': url, 'wkz_executable': wkz_executable, } )", "instead of creating a new one.\\n\" f\"Note that this could", "try to use the existing database instead of creating a", "ssh_extra_args=None, sftp_extra_args=None, scp_extra_args=None, become=True, become_method='sudo', become_user='root', verbosity=True, check=False, start_at_task=None )", ") if result == 0: click.echo(f\"Successfully configured workoutizer as systemd", "import CLI from ansible.module_utils.common.collections import ImmutableDict from ansible.executor.playbook_executor import PlaybookExecutor", "def _setup_rpi(vendor_id: str, product_id: str, ip_port: str = None): if", "could lead to faulty behaviour because of mismatching applied\\n\" f\"migrations", "\"--noinput\"]) execute_from_command_line([\"manage.py\", \"migrate\"]) execute_from_command_line([\"manage.py\", \"check\"]) click.echo(f\"database and track files are", "the static files, creates the database ' 'and applies the", "'specify ip address and port pair, like: address:port' @click.group() def", "existing database at {WORKOUTIZER_DB_PATH}\") return else: click.echo(f\"removed database at {WORKOUTIZER_DB_PATH}\")", "new one? [Y/n] \") if answer.lower() == 'y': click.echo(f\"keeping existing", "default=\"\", help=url_help) @click.option('--product_id', help=\"product ip of your device\", required=True) @click.option('--vendor_id',", "SETUP_DIR = os.path.join(BASE_DIR, 'setup') os.environ[\"DJANGO_SETTINGS_MODULE\"] = \"workoutizer.settings\" example_rpi_cmd = \"wkz", "not configure workoutizer as systemd service, see above errors.\") return", "click.echo(f\"removed database at {WORKOUTIZER_DB_PATH}\") os.remove(WORKOUTIZER_DB_PATH) _make_tracks_dir(TRACKS_DIR) else: os.mkdir(WORKOUTIZER_DIR) _make_tracks_dir(TRACKS_DIR) def", "'y': click.echo(f\"installing ansible...\") _pip_install('ansible==2.9.10') click.echo(f\"starting setup using ansible...\") _setup_rpi( vendor_id=vendor_id,", "def _run_ansible(playbook: str, variables: dict = None): if variables is", "to run as systemd service. Passing the local ip address", "to faulty behaviour because of mismatching applied\\n\" f\"migrations on this", "variable_manager._extra_vars = variables pbex = PlaybookExecutor(playbooks=[os.path.join(SETUP_DIR, 'ansible', playbook)], inventory=inventory, variable_manager=variable_manager,", "click.echo(f\"configuring workoutizer to run as system service\") if not url:", "return ip_address def _build_home(): if os.path.isdir(WORKOUTIZER_DIR): if os.path.isfile(WORKOUTIZER_DB_PATH): click.echo(f\"Found existing", "pair, like: address:port' @click.group() def cli(): pass @click.command(help='Mandatory command to", "f\"{_get_local_ip_address()}:8000\" execute_from_command_line([\"manage.py\", \"runserver\", url]) @click.argument('url', default=\"\") @click.command(help='Configure workoutizer to run", "== 0: pass else: click.echo(f\"ERROR: Could not configure Raspberry Pi,", "else: click.echo(f\"ERROR: Could not configure Raspberry Pi, see above errors.\")", "f\"Do you want to use the existing database instead of", "ip address and port pair, like: address:port' @click.group() def cli():", "= ImmutableDict( tags={}, listtags=False, listtasks=False, listhosts=False, syntax=False, connection='ssh', module_path=None, forks=100,", "required=True) @click.option('--vendor_id', help=\"vendor ip of your device\", required=True) @click.command(help='Configure Raspberry", "_build_home() execute_from_command_line([\"manage.py\", \"collectstatic\", \"--noinput\"]) execute_from_command_line([\"manage.py\", \"migrate\"]) execute_from_command_line([\"manage.py\", \"check\"]) click.echo(f\"database and", "udev rule and systemd service file\\n\" f\"to your system to", "no ip address being passed, it will be determined automatically.')", "of no ip address \" \"being passed, it will be", "_get_local_ip_address() answer = input(f\"Are you sure you want to setup", "'--disable-pip-version-check'])) if package in outdated: output = str(subprocess.check_output([sys.executable, \"-m\", \"pip\",", "workoutizer import __version__ as current_version if latest_version: click.echo(f\"found newer version:", "@click.command(help='Configure workoutizer to run as systemd service. Passing the local", "any.') def upgrade(): _upgrade() cli.add_command(upgrade) cli.add_command(version) cli.add_command(init) cli.add_command(setup_rpi) cli.add_command(run) cli.add_command(manage)", "systemd service, see above errors.\") return result def _get_local_ip_address(): s", "Pi to auto mount devices. Passing vendor and product id", "ip_port=f\"{ip}:8000\" ) _run_ansible(playbook='install_packages.yml') click.echo(f\"Successfully configured to automatically mount your device", "help=\"product ip of your device\", required=True) @click.option('--vendor_id', help=\"vendor ip of", "cli.add_command(setup_rpi) cli.add_command(run) cli.add_command(manage) cli.add_command(wkz_as_service) def _upgrade(): latest_version = _get_latest_version_of(\"workoutizer\") from", "os.path.isdir(path): os.mkdir(path) class ParseDict(argparse.Action): def __call__(self, parser, namespace, values, option_string=None):", "ip_port = f\"{_get_local_ip_address()}:8000\" result = _run_ansible( playbook='setup_on_rpi.yml', variables={ 'vendor_id': vendor_id,", "inventory=inventory, version_info=CLI.version_info(gitinfo=False)) variable_manager._extra_vars = variables pbex = PlaybookExecutor(playbooks=[os.path.join(SETUP_DIR, 'ansible', playbook)],", "socket.SOCK_DGRAM) s.connect((\"8.8.8.8\", 80)) ip_address = s.getsockname()[0] s.close() return ip_address def", "required udev rule and systemd service file\\n\" f\"to your system", "workoutizer as systemd service, see above errors.\") return result def", "mount devices. Passing vendor and product id is required. Passing", "')[-1] return latest_version else: return False def _setup_rpi(vendor_id: str, product_id:", "@click.argument('url', default=\"\") @click.command(help='Configure workoutizer to run as systemd service. Passing", "[Y/n] \") if answer.lower() == 'y': click.echo(f\"keeping existing database at", "to run as system service\") if not url: url =", "listtasks=False, listhosts=False, syntax=False, connection='ssh', module_path=None, forks=100, remote_user='xxx', private_key_file=None, ssh_common_args=None, ssh_extra_args=None,", "outdated = str( subprocess.check_output([sys.executable, \"-m\", \"pip\", \"list\", '--outdated', '--disable-pip-version-check'])) if", "address and port is optionally. In case of no ip", "import context from ansible.cli import CLI from ansible.module_utils.common.collections import ImmutableDict", "execute_from_command_line([\"manage.py\", \"check\"]) click.echo(f\"database and track files are stored in: {WORKOUTIZER_DIR}\")", "url]) @click.argument('url', default=\"\") @click.command(help='Configure workoutizer to run as systemd service.", "f\"{_get_local_ip_address()}:8000\" result = _run_ansible( playbook='setup_on_rpi.yml', variables={ 'vendor_id': vendor_id, 'product_id': product_id,", "'address_plus_port': url, 'wkz_executable': wkz_executable, } ) if result == 0:", "of your device\", required=True) @click.option('--vendor_id', help=\"vendor ip of your device\",", "update available. You are running the latest version: {current_version}\") def", "as system service\") if not url: url = f\"{_get_local_ip_address()}:8000\" env_binaries", "if values: for item in values: split_items = item.split(\"=\", 1)", "click.echo(f\"ERROR: Could not configure workoutizer as systemd service, see above", "become_method='sudo', become_user='root', verbosity=True, check=False, start_at_task=None ) inventory = InventoryManager(loader=loader, sources=())", "parser, namespace, values, option_string=None): d = {} if values: for", "= False): if upgrade: subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", package, '--upgrade'])", "_run_ansible( playbook='setup_on_rpi.yml', variables={ 'vendor_id': vendor_id, 'product_id': product_id, 'address_plus_port': ip_port, }", "\"-m\", \"pip\", \"install\", package, '--upgrade']) else: subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\",", "context from ansible.cli import CLI from ansible.module_utils.common.collections import ImmutableDict from", "passed, it will be determined automatically.') def wkz_as_service(url): _pip_install('ansible==2.9.10') _wkz_as_service(url=url)", "errors.\") return result def _get_local_ip_address(): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect((\"8.8.8.8\",", "import socket import sys import click from django.core.management import execute_from_command_line", "if upgrade: subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", package, '--upgrade']) else: subprocess.check_call([sys.executable,", "required. Passing ' f'the local ip address and port is", "url = f\"{_get_local_ip_address()}:8000\" env_binaries = sys.executable wkz_executable = env_binaries[:env_binaries.find('python')] +", "= sys.executable wkz_executable = env_binaries[:env_binaries.find('python')] + \"wkz\" result = _run_ansible(", "ansible.vars.manager import VariableManager loader = DataLoader() context.CLIARGS = ImmutableDict( tags={},", "set of workoutizer commands. Usage, e.g.: \" \"wkz manage 'runserver", "wkz_executable, } ) if result == 0: click.echo(f\"Successfully configured workoutizer", "input(f\"Are you sure you want to setup your Raspberry Pi?\\n\\n\"", "CLI from ansible.module_utils.common.collections import ImmutableDict from ansible.executor.playbook_executor import PlaybookExecutor from", "track files are stored in: {WORKOUTIZER_DIR}\") @click.option('--ip', default=\"\", help=url_help) @click.option('--product_id',", "subprocess import socket import sys import click from django.core.management import", "have {current_version} installed\") _pip_install('workoutizer', upgrade=True) execute_from_command_line([\"manage.py\", \"collectstatic\", \"--noinput\"]) execute_from_command_line([\"manage.py\", \"migrate\"])", "playbook='setup_on_rpi.yml', variables={ 'vendor_id': vendor_id, 'product_id': product_id, 'address_plus_port': ip_port, } )", "import os import argparse import subprocess import socket import sys", "product_id, 'address_plus_port': ip_port, } ) if result == 0: pass", "this could lead to faulty behaviour because of mismatching applied\\n\"", "value = split_items[1] d[key] = value setattr(namespace, self.dest, d) def", "{} from ansible import context from ansible.cli import CLI from", "listtags=False, listtasks=False, listhosts=False, syntax=False, connection='ssh', module_path=None, forks=100, remote_user='xxx', private_key_file=None, ssh_common_args=None,", "case of no ip address being passed, it will be", "ansible.inventory.manager import InventoryManager from ansible.vars.manager import VariableManager loader = DataLoader()", "variable_manager = VariableManager(loader=loader, inventory=inventory, version_info=CLI.version_info(gitinfo=False)) variable_manager._extra_vars = variables pbex =", "quit() return result def _wkz_as_service(url: str): click.echo(f\"configuring workoutizer to run", "and port is optionally. E.g.: {example_rpi_cmd}') def setup_rpi(ip, vendor_id, product_id):", "def _get_local_ip_address(): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect((\"8.8.8.8\", 80)) ip_address =", "_make_tracks_dir(TRACKS_DIR) else: os.mkdir(WORKOUTIZER_DIR) _make_tracks_dir(TRACKS_DIR) def _make_tracks_dir(path): if not os.path.isdir(path): os.mkdir(path)", "def __call__(self, parser, namespace, values, option_string=None): d = {} if", "setup your Raspberry Pi?\\n\\n\" f\"This will copy the required udev", "\"runserver\", url]) @click.argument('url', default=\"\") @click.command(help='Configure workoutizer to run as systemd", "{current_version} installed\") _pip_install('workoutizer', upgrade=True) execute_from_command_line([\"manage.py\", \"collectstatic\", \"--noinput\"]) execute_from_command_line([\"manage.py\", \"migrate\"]) execute_from_command_line([\"manage.py\",", "_pip_install(package, upgrade: bool = False): if upgrade: subprocess.check_call([sys.executable, \"-m\", \"pip\",", "covered with the given set of workoutizer commands. Usage, e.g.:", "'product_id': product_id, 'address_plus_port': ip_port, } ) if result == 0:", "of your device\", required=True) @click.command(help='Configure Raspberry Pi to auto mount", "if variables is None: variables = {} from ansible import", "install if there is any.') def upgrade(): _upgrade() cli.add_command(upgrade) cli.add_command(version)", "migrations.') def init(): _build_home() execute_from_command_line([\"manage.py\", \"collectstatic\", \"--noinput\"]) execute_from_command_line([\"manage.py\", \"migrate\"]) execute_from_command_line([\"manage.py\",", "ip_address def _build_home(): if os.path.isdir(WORKOUTIZER_DIR): if os.path.isfile(WORKOUTIZER_DB_PATH): click.echo(f\"Found existing workoutizer", "the given set of workoutizer commands. Usage, e.g.: \" \"wkz", "running the latest version: {current_version}\") def _get_latest_version_of(package: str): outdated =", "\" f\"require a system restart to take effect.\") else: click.echo(f\"Aborted.\")", "version: {current_version}\") def _get_latest_version_of(package: str): outdated = str( subprocess.check_output([sys.executable, \"-m\",", "configure Raspberry Pi, see above errors.\") quit() return result def", "result = _run_ansible( playbook='setup_on_rpi.yml', variables={ 'vendor_id': vendor_id, 'product_id': product_id, 'address_plus_port':", "for item in values: split_items = item.split(\"=\", 1) key =", "execute_from_command_line([\"manage.py\"] + cmd.split(' ')) @click.command(help='Show the version of currently installed", "pass @click.command(help='Mandatory command to initialize workoutizer. This fetches the static", "keys, as is logical value = split_items[1] d[key] = value", "click.echo(f\"Aborted.\") @click.argument('url', default=\"\") @click.command(help=\"Run workoutizer. Passing the local ip address", "playbook='wkz_as_service.yml', variables={ 'address_plus_port': url, 'wkz_executable': wkz_executable, } ) if result", "wkz_as_service(url): _pip_install('ansible==2.9.10') _wkz_as_service(url=url) @click.argument('cmd', nargs=1) @click.command(help=\"Pass commands to django's manage.py.", "else: click.echo(f\"ERROR: Could not configure workoutizer as systemd service, see", "click.echo(__version__) @click.command(help='Check for a newer version and install if there", "if latest_version: click.echo(f\"found newer version: {latest_version}, you have {current_version} installed\")", "yet covered with the given set of workoutizer commands. Usage,", "this database.\\n\\n\" f\"Do you want to use the existing database", "namespace, values, option_string=None): d = {} if values: for item", "device.\\n\" f\"This might take a while...\\n\\n\" f\"Start setup? [Y/n] \")", "start wkz.service\") else: click.echo(f\"ERROR: Could not configure workoutizer as systemd", "'--upgrade']) else: subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", package]) def _run_ansible(playbook: str,", "<filename>workoutizer/__main__.py<gh_stars>0 import os import argparse import subprocess import socket import", "\"pip\", \"search\", package])) latest_version = output[output.find('LATEST'):].split('\\\\n')[0].split(' ')[-1] return latest_version else:", "files, creates the database ' 'and applies the required migrations.')", "@click.option('--vendor_id', help=\"vendor ip of your device\", required=True) @click.command(help='Configure Raspberry Pi", "available. You are running the latest version: {current_version}\") def _get_latest_version_of(package:", "stored in: {WORKOUTIZER_DIR}\") @click.option('--ip', default=\"\", help=url_help) @click.option('--product_id', help=\"product ip of", "= None): if variables is None: variables = {} from", "Passing ' f'the local ip address and port is optionally.", "_make_tracks_dir(TRACKS_DIR) def _make_tracks_dir(path): if not os.path.isdir(path): os.mkdir(path) class ParseDict(argparse.Action): def", "product_id: str, ip_port: str = None): if not ip_port: ip_port", "sys import click from django.core.management import execute_from_command_line from workoutizer.settings import", "_pip_install('ansible==2.9.10') click.echo(f\"starting setup using ansible...\") _setup_rpi( vendor_id=vendor_id, product_id=product_id, ip_port=f\"{ip}:8000\" )", "your device when plugged in. Note: These changes \" f\"require", "result = _run_ansible( playbook='wkz_as_service.yml', variables={ 'address_plus_port': url, 'wkz_executable': wkz_executable, }", "mounting of your device.\\n\" f\"This might take a while...\\n\\n\" f\"Start", "the database ' 'and applies the required migrations.') def init():", "product_id=4b48\" url_help = 'specify ip address and port pair, like:", "Raspberry Pi, see above errors.\") quit() return result def _wkz_as_service(url:", "= split_items[1] d[key] = value setattr(namespace, self.dest, d) def _pip_install(package,", "if not url: url = f\"{_get_local_ip_address()}:8000\" env_binaries = sys.executable wkz_executable", "become_user='root', verbosity=True, check=False, start_at_task=None ) inventory = InventoryManager(loader=loader, sources=()) variable_manager", "f\"to your system to enable automated mounting of your device.\\n\"", "execute_from_command_line([\"manage.py\", \"migrate\"]) execute_from_command_line([\"manage.py\", \"check\"]) click.echo(f\"Successfully upgraded from {current_version} to {latest_version}\")", "default=\"\") @click.command(help='Configure workoutizer to run as systemd service. Passing the", "your device\", required=True) @click.option('--vendor_id', help=\"vendor ip of your device\", required=True)", "file\\n\" f\"to your system to enable automated mounting of your", "address \" \"being passed, it will be determined automatically. Usage,", "= input(f\"Workoutizer could try to use the existing database instead", "workoutizer.') def version(): click.echo(__version__) @click.command(help='Check for a newer version and", "\"check\"]) click.echo(f\"Successfully upgraded from {current_version} to {latest_version}\") else: click.echo(f\"No update", "the required migrations.') def init(): _build_home() execute_from_command_line([\"manage.py\", \"collectstatic\", \"--noinput\"]) execute_from_command_line([\"manage.py\",", "import __version__ BASE_DIR = os.path.dirname(os.path.dirname(__file__)) SETUP_DIR = os.path.join(BASE_DIR, 'setup') os.environ[\"DJANGO_SETTINGS_MODULE\"]", "Usage, e.g.: 'wkz run 0.0.0.0:8000'.\") def run(url): if not url:", "to auto mount devices. Passing vendor and product id is", "ip address and port is ' 'optionally. In case of", "automatically. Usage, e.g.: 'wkz run 0.0.0.0:8000'.\") def run(url): if not", "cli.add_command(upgrade) cli.add_command(version) cli.add_command(init) cli.add_command(setup_rpi) cli.add_command(run) cli.add_command(manage) cli.add_command(wkz_as_service) def _upgrade(): latest_version", "f\"migrations on this database.\\n\\n\" f\"Do you want to use the", "= _get_local_ip_address() answer = input(f\"Are you sure you want to", "a newer version and install if there is any.') def", "ip address and port is optionally. In case of no", "\"pip\", \"list\", '--outdated', '--disable-pip-version-check'])) if package in outdated: output =", "VariableManager loader = DataLoader() context.CLIARGS = ImmutableDict( tags={}, listtags=False, listtasks=False,", "rule and systemd service file\\n\" f\"to your system to enable", "e.g.: 'wkz run 0.0.0.0:8000'.\") def run(url): if not url: url", "variables = {} from ansible import context from ansible.cli import", "if not ip: ip = _get_local_ip_address() answer = input(f\"Are you", "ansible...\") _pip_install('ansible==2.9.10') click.echo(f\"starting setup using ansible...\") _setup_rpi( vendor_id=vendor_id, product_id=product_id, ip_port=f\"{ip}:8000\"", "\"check\"]) click.echo(f\"database and track files are stored in: {WORKOUTIZER_DIR}\") @click.option('--ip',", "initialize workoutizer. This fetches the static files, creates the database", "_setup_rpi(vendor_id: str, product_id: str, ip_port: str = None): if not", "tags={}, listtags=False, listtasks=False, listhosts=False, syntax=False, connection='ssh', module_path=None, forks=100, remote_user='xxx', private_key_file=None,", "\"list\", '--outdated', '--disable-pip-version-check'])) if package in outdated: output = str(subprocess.check_output([sys.executable,", "def init(): _build_home() execute_from_command_line([\"manage.py\", \"collectstatic\", \"--noinput\"]) execute_from_command_line([\"manage.py\", \"migrate\"]) execute_from_command_line([\"manage.py\", \"check\"])", "upgrade=True) execute_from_command_line([\"manage.py\", \"collectstatic\", \"--noinput\"]) execute_from_command_line([\"manage.py\", \"migrate\"]) execute_from_command_line([\"manage.py\", \"check\"]) click.echo(f\"Successfully upgraded", "@click.command(help='Mandatory command to initialize workoutizer. This fetches the static files,", "it will be determined automatically. Usage, e.g.: 'wkz run 0.0.0.0:8000'.\")", ") if result == 0: pass else: click.echo(f\"ERROR: Could not", "subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", package, '--upgrade']) else: subprocess.check_call([sys.executable, \"-m\", \"pip\",", "while...\\n\\n\" f\"Start setup? [Y/n] \") if answer.lower() == 'y': click.echo(f\"installing", "{} if values: for item in values: split_items = item.split(\"=\",", "f\"require a system restart to take effect.\") else: click.echo(f\"Aborted.\") @click.argument('url',", "input(f\"Workoutizer could try to use the existing database instead of", "This fetches the static files, creates the database ' 'and", "'wkz run 0.0.0.0:8000'.\") def run(url): if not url: url =", "[Y/n] \") if answer.lower() == 'y': click.echo(f\"installing ansible...\") _pip_install('ansible==2.9.10') click.echo(f\"starting", "_setup_rpi( vendor_id=vendor_id, product_id=product_id, ip_port=f\"{ip}:8000\" ) _run_ansible(playbook='install_packages.yml') click.echo(f\"Successfully configured to automatically", "click.echo(f\"Successfully upgraded from {current_version} to {latest_version}\") else: click.echo(f\"No update available.", "\"migrate\"]) execute_from_command_line([\"manage.py\", \"check\"]) click.echo(f\"database and track files are stored in:", "= f\"{_get_local_ip_address()}:8000\" env_binaries = sys.executable wkz_executable = env_binaries[:env_binaries.find('python')] + \"wkz\"", "import VariableManager loader = DataLoader() context.CLIARGS = ImmutableDict( tags={}, listtags=False,", "your Raspberry Pi?\\n\\n\" f\"This will copy the required udev rule", "verbosity=True, check=False, start_at_task=None ) inventory = InventoryManager(loader=loader, sources=()) variable_manager =", "address and port is optionally. E.g.: {example_rpi_cmd}') def setup_rpi(ip, vendor_id,", "ip_port: ip_port = f\"{_get_local_ip_address()}:8000\" result = _run_ansible( playbook='setup_on_rpi.yml', variables={ 'vendor_id':", "blanks around keys, as is logical value = split_items[1] d[key]", "os.path.join(BASE_DIR, 'setup') os.environ[\"DJANGO_SETTINGS_MODULE\"] = \"workoutizer.settings\" example_rpi_cmd = \"wkz --setup_rpi vendor_id=091e", "automated mounting of your device.\\n\" f\"This might take a while...\\n\\n\"", "ssh_common_args=None, ssh_extra_args=None, sftp_extra_args=None, scp_extra_args=None, become=True, become_method='sudo', become_user='root', verbosity=True, check=False, start_at_task=None", "new one.\\n\" f\"Note that this could lead to faulty behaviour", "to django's manage.py. Convenience function to access all django commands", "a new one? [Y/n] \") if answer.lower() == 'y': click.echo(f\"keeping", "service. Run it with: systemctl start wkz.service\") else: click.echo(f\"ERROR: Could", "as systemd service, see above errors.\") return result def _get_local_ip_address():", "help=\"vendor ip of your device\", required=True) @click.command(help='Configure Raspberry Pi to", "database ' 'and applies the required migrations.') def init(): _build_home()", "} ) if result == 0: click.echo(f\"Successfully configured workoutizer as", "ParseDict(argparse.Action): def __call__(self, parser, namespace, values, option_string=None): d = {}", "import subprocess import socket import sys import click from django.core.management", "inventory = InventoryManager(loader=loader, sources=()) variable_manager = VariableManager(loader=loader, inventory=inventory, version_info=CLI.version_info(gitinfo=False)) variable_manager._extra_vars", "wkz_executable = env_binaries[:env_binaries.find('python')] + \"wkz\" result = _run_ansible( playbook='wkz_as_service.yml', variables={", "automatically mount your device when plugged in. Note: These changes", "import __version__ as current_version if latest_version: click.echo(f\"found newer version: {latest_version},", "= \"workoutizer.settings\" example_rpi_cmd = \"wkz --setup_rpi vendor_id=091e product_id=4b48\" url_help =", "are \" \"not yet covered with the given set of", "def manage(cmd): execute_from_command_line([\"manage.py\"] + cmd.split(' ')) @click.command(help='Show the version of", "\"wkz\" result = _run_ansible( playbook='wkz_as_service.yml', variables={ 'address_plus_port': url, 'wkz_executable': wkz_executable,", "to setup your Raspberry Pi?\\n\\n\" f\"This will copy the required", "' 'optionally. In case of no ip address being passed,", "be determined automatically.') def wkz_as_service(url): _pip_install('ansible==2.9.10') _wkz_as_service(url=url) @click.argument('cmd', nargs=1) @click.command(help=\"Pass", "use the existing database instead of creating a new one.\\n\"", "mismatching applied\\n\" f\"migrations on this database.\\n\\n\" f\"Do you want to", "split_items[0].strip() # we remove blanks around keys, as is logical", "def cli(): pass @click.command(help='Mandatory command to initialize workoutizer. This fetches", "def _upgrade(): latest_version = _get_latest_version_of(\"workoutizer\") from workoutizer import __version__ as", "of creating a new one? [Y/n] \") if answer.lower() ==", "vendor_id, 'product_id': product_id, 'address_plus_port': ip_port, } ) if result ==", "in values: split_items = item.split(\"=\", 1) key = split_items[0].strip() #", "setup using ansible...\") _setup_rpi( vendor_id=vendor_id, product_id=product_id, ip_port=f\"{ip}:8000\" ) _run_ansible(playbook='install_packages.yml') click.echo(f\"Successfully", "url = f\"{_get_local_ip_address()}:8000\" execute_from_command_line([\"manage.py\", \"runserver\", url]) @click.argument('url', default=\"\") @click.command(help='Configure workoutizer", "answer = input(f\"Workoutizer could try to use the existing database", "become=True, become_method='sudo', become_user='root', verbosity=True, check=False, start_at_task=None ) inventory = InventoryManager(loader=loader,", "ip = _get_local_ip_address() answer = input(f\"Are you sure you want", "django's manage.py. Convenience function to access all django commands which", "import DataLoader from ansible.inventory.manager import InventoryManager from ansible.vars.manager import VariableManager", "ansible.executor.playbook_executor import PlaybookExecutor from ansible.parsing.dataloader import DataLoader from ansible.inventory.manager import", "str(subprocess.check_output([sys.executable, \"-m\", \"pip\", \"search\", package])) latest_version = output[output.find('LATEST'):].split('\\\\n')[0].split(' ')[-1] return", "argparse import subprocess import socket import sys import click from", "execute_from_command_line([\"manage.py\", \"migrate\"]) execute_from_command_line([\"manage.py\", \"check\"]) click.echo(f\"database and track files are stored", "Could not configure Raspberry Pi, see above errors.\") quit() return", "creates the database ' 'and applies the required migrations.') def", "Passing vendor and product id is required. Passing ' f'the", "'optionally. In case of no ip address being passed, it", "f'the local ip address and port is optionally. E.g.: {example_rpi_cmd}')", "from ansible.executor.playbook_executor import PlaybookExecutor from ansible.parsing.dataloader import DataLoader from ansible.inventory.manager", "sources=()) variable_manager = VariableManager(loader=loader, inventory=inventory, version_info=CLI.version_info(gitinfo=False)) variable_manager._extra_vars = variables pbex", "want to use the existing database instead of creating a", "click.echo(f\"Successfully configured workoutizer as systemd service. Run it with: systemctl", "VariableManager(loader=loader, inventory=inventory, version_info=CLI.version_info(gitinfo=False)) variable_manager._extra_vars = variables pbex = PlaybookExecutor(playbooks=[os.path.join(SETUP_DIR, 'ansible',", "the existing database instead of creating a new one? [Y/n]", "str): outdated = str( subprocess.check_output([sys.executable, \"-m\", \"pip\", \"list\", '--outdated', '--disable-pip-version-check']))", "and track files are stored in: {WORKOUTIZER_DIR}\") @click.option('--ip', default=\"\", help=url_help)", "variables is None: variables = {} from ansible import context", "behaviour because of mismatching applied\\n\" f\"migrations on this database.\\n\\n\" f\"Do", "WORKOUTIZER_DIR, WORKOUTIZER_DB_PATH, TRACKS_DIR from workoutizer import __version__ BASE_DIR = os.path.dirname(os.path.dirname(__file__))", "click.echo(f\"found newer version: {latest_version}, you have {current_version} installed\") _pip_install('workoutizer', upgrade=True)", "in. Note: These changes \" f\"require a system restart to", "def _get_latest_version_of(package: str): outdated = str( subprocess.check_output([sys.executable, \"-m\", \"pip\", \"list\",", "@click.command(help=\"Run workoutizer. Passing the local ip address and port is", "\"pip\", \"install\", package, '--upgrade']) else: subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", package])", "click.echo(f\"Found existing workoutizer database at: {WORKOUTIZER_DB_PATH}\\n\") answer = input(f\"Workoutizer could", "init(): _build_home() execute_from_command_line([\"manage.py\", \"collectstatic\", \"--noinput\"]) execute_from_command_line([\"manage.py\", \"migrate\"]) execute_from_command_line([\"manage.py\", \"check\"]) click.echo(f\"database", "cli.add_command(run) cli.add_command(manage) cli.add_command(wkz_as_service) def _upgrade(): latest_version = _get_latest_version_of(\"workoutizer\") from workoutizer", "take effect.\") else: click.echo(f\"Aborted.\") @click.argument('url', default=\"\") @click.command(help=\"Run workoutizer. Passing the", "version of currently installed workoutizer.') def version(): click.echo(__version__) @click.command(help='Check for", "django.core.management import execute_from_command_line from workoutizer.settings import WORKOUTIZER_DIR, WORKOUTIZER_DB_PATH, TRACKS_DIR from", "else: subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", package]) def _run_ansible(playbook: str, variables:", "\"-m\", \"pip\", \"install\", package]) def _run_ansible(playbook: str, variables: dict =", "with: systemctl start wkz.service\") else: click.echo(f\"ERROR: Could not configure workoutizer", "\" \"being passed, it will be determined automatically. Usage, e.g.:", "sure you want to setup your Raspberry Pi?\\n\\n\" f\"This will", "== 'y': click.echo(f\"keeping existing database at {WORKOUTIZER_DB_PATH}\") return else: click.echo(f\"removed", "help=url_help) @click.option('--product_id', help=\"product ip of your device\", required=True) @click.option('--vendor_id', help=\"vendor", "import argparse import subprocess import socket import sys import click", "loader = DataLoader() context.CLIARGS = ImmutableDict( tags={}, listtags=False, listtasks=False, listhosts=False,", "want to setup your Raspberry Pi?\\n\\n\" f\"This will copy the", "= split_items[0].strip() # we remove blanks around keys, as is", "--setup_rpi vendor_id=091e product_id=4b48\" url_help = 'specify ip address and port", "existing database instead of creating a new one? [Y/n] \")", "there is any.') def upgrade(): _upgrade() cli.add_command(upgrade) cli.add_command(version) cli.add_command(init) cli.add_command(setup_rpi)", "f\"This might take a while...\\n\\n\" f\"Start setup? [Y/n] \") if", "@click.command(help=\"Pass commands to django's manage.py. Convenience function to access all", "as systemd service. Run it with: systemctl start wkz.service\") else:", "--noreload'.\") def manage(cmd): execute_from_command_line([\"manage.py\"] + cmd.split(' ')) @click.command(help='Show the version", "os.path.dirname(os.path.dirname(__file__)) SETUP_DIR = os.path.join(BASE_DIR, 'setup') os.environ[\"DJANGO_SETTINGS_MODULE\"] = \"workoutizer.settings\" example_rpi_cmd =", "ansible.module_utils.common.collections import ImmutableDict from ansible.executor.playbook_executor import PlaybookExecutor from ansible.parsing.dataloader import", "the required udev rule and systemd service file\\n\" f\"to your", "service\") if not url: url = f\"{_get_local_ip_address()}:8000\" env_binaries = sys.executable", "\"collectstatic\", \"--noinput\"]) execute_from_command_line([\"manage.py\", \"migrate\"]) execute_from_command_line([\"manage.py\", \"check\"]) click.echo(f\"database and track files", "Passing the local ip address and port is ' 'optionally.", "None: variables = {} from ansible import context from ansible.cli", "Convenience function to access all django commands which are \"", "as systemd service. Passing the local ip address and port", "Pi, see above errors.\") quit() return result def _wkz_as_service(url: str):", "system service\") if not url: url = f\"{_get_local_ip_address()}:8000\" env_binaries =", "'address_plus_port': ip_port, } ) if result == 0: pass else:", "InventoryManager from ansible.vars.manager import VariableManager loader = DataLoader() context.CLIARGS =", "cli.add_command(version) cli.add_command(init) cli.add_command(setup_rpi) cli.add_command(run) cli.add_command(manage) cli.add_command(wkz_as_service) def _upgrade(): latest_version =", "errors.\") quit() return result def _wkz_as_service(url: str): click.echo(f\"configuring workoutizer to", "= PlaybookExecutor(playbooks=[os.path.join(SETUP_DIR, 'ansible', playbook)], inventory=inventory, variable_manager=variable_manager, loader=loader, passwords={}) return pbex.run()", "vendor_id=vendor_id, product_id=product_id, ip_port=f\"{ip}:8000\" ) _run_ansible(playbook='install_packages.yml') click.echo(f\"Successfully configured to automatically mount", "= socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect((\"8.8.8.8\", 80)) ip_address = s.getsockname()[0] s.close() return", "80)) ip_address = s.getsockname()[0] s.close() return ip_address def _build_home(): if", "configure workoutizer as systemd service, see above errors.\") return result", "if os.path.isfile(WORKOUTIZER_DB_PATH): click.echo(f\"Found existing workoutizer database at: {WORKOUTIZER_DB_PATH}\\n\") answer =", "@click.group() def cli(): pass @click.command(help='Mandatory command to initialize workoutizer. This", "package in outdated: output = str(subprocess.check_output([sys.executable, \"-m\", \"pip\", \"search\", package]))", "e.g.: \" \"wkz manage 'runserver 0.0.0.0:8000 --noreload'.\") def manage(cmd): execute_from_command_line([\"manage.py\"]", "'and applies the required migrations.') def init(): _build_home() execute_from_command_line([\"manage.py\", \"collectstatic\",", "return else: click.echo(f\"removed database at {WORKOUTIZER_DB_PATH}\") os.remove(WORKOUTIZER_DB_PATH) _make_tracks_dir(TRACKS_DIR) else: os.mkdir(WORKOUTIZER_DIR)", "not ip_port: ip_port = f\"{_get_local_ip_address()}:8000\" result = _run_ansible( playbook='setup_on_rpi.yml', variables={", "In case of no ip address \" \"being passed, it", "static files, creates the database ' 'and applies the required", "port pair, like: address:port' @click.group() def cli(): pass @click.command(help='Mandatory command", "creating a new one.\\n\" f\"Note that this could lead to", "str, variables: dict = None): if variables is None: variables", "= None): if not ip_port: ip_port = f\"{_get_local_ip_address()}:8000\" result =", "\" \"wkz manage 'runserver 0.0.0.0:8000 --noreload'.\") def manage(cmd): execute_from_command_line([\"manage.py\"] +", "= _get_latest_version_of(\"workoutizer\") from workoutizer import __version__ as current_version if latest_version:", "== 0: click.echo(f\"Successfully configured workoutizer as systemd service. Run it", "0.0.0.0:8000 --noreload'.\") def manage(cmd): execute_from_command_line([\"manage.py\"] + cmd.split(' ')) @click.command(help='Show the", "socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect((\"8.8.8.8\", 80)) ip_address = s.getsockname()[0] s.close() return ip_address", "os.environ[\"DJANGO_SETTINGS_MODULE\"] = \"workoutizer.settings\" example_rpi_cmd = \"wkz --setup_rpi vendor_id=091e product_id=4b48\" url_help", "that this could lead to faulty behaviour because of mismatching", "os.remove(WORKOUTIZER_DB_PATH) _make_tracks_dir(TRACKS_DIR) else: os.mkdir(WORKOUTIZER_DIR) _make_tracks_dir(TRACKS_DIR) def _make_tracks_dir(path): if not os.path.isdir(path):", "output = str(subprocess.check_output([sys.executable, \"-m\", \"pip\", \"search\", package])) latest_version = output[output.find('LATEST'):].split('\\\\n')[0].split('", "= env_binaries[:env_binaries.find('python')] + \"wkz\" result = _run_ansible( playbook='wkz_as_service.yml', variables={ 'address_plus_port':", "Usage, e.g.: \" \"wkz manage 'runserver 0.0.0.0:8000 --noreload'.\") def manage(cmd):", "installed\") _pip_install('workoutizer', upgrade=True) execute_from_command_line([\"manage.py\", \"collectstatic\", \"--noinput\"]) execute_from_command_line([\"manage.py\", \"migrate\"]) execute_from_command_line([\"manage.py\", \"check\"])", "database at: {WORKOUTIZER_DB_PATH}\\n\") answer = input(f\"Workoutizer could try to use", "are running the latest version: {current_version}\") def _get_latest_version_of(package: str): outdated", "setup_rpi(ip, vendor_id, product_id): if not ip: ip = _get_local_ip_address() answer", "as is logical value = split_items[1] d[key] = value setattr(namespace,", "= os.path.join(BASE_DIR, 'setup') os.environ[\"DJANGO_SETTINGS_MODULE\"] = \"workoutizer.settings\" example_rpi_cmd = \"wkz --setup_rpi", "and port is ' 'optionally. In case of no ip", "def _wkz_as_service(url: str): click.echo(f\"configuring workoutizer to run as system service\")", "access all django commands which are \" \"not yet covered", "output[output.find('LATEST'):].split('\\\\n')[0].split(' ')[-1] return latest_version else: return False def _setup_rpi(vendor_id: str,", "'vendor_id': vendor_id, 'product_id': product_id, 'address_plus_port': ip_port, } ) if result", "_build_home(): if os.path.isdir(WORKOUTIZER_DIR): if os.path.isfile(WORKOUTIZER_DB_PATH): click.echo(f\"Found existing workoutizer database at:", "__call__(self, parser, namespace, values, option_string=None): d = {} if values:", "run as system service\") if not url: url = f\"{_get_local_ip_address()}:8000\"", "you want to use the existing database instead of creating", "context.CLIARGS = ImmutableDict( tags={}, listtags=False, listtasks=False, listhosts=False, syntax=False, connection='ssh', module_path=None,", "will be determined automatically. Usage, e.g.: 'wkz run 0.0.0.0:8000'.\") def", "# we remove blanks around keys, as is logical value", "vendor_id, product_id): if not ip: ip = _get_local_ip_address() answer =", "os import argparse import subprocess import socket import sys import", "@click.option('--ip', default=\"\", help=url_help) @click.option('--product_id', help=\"product ip of your device\", required=True)", "determined automatically. Usage, e.g.: 'wkz run 0.0.0.0:8000'.\") def run(url): if", "a new one.\\n\" f\"Note that this could lead to faulty", "= \"wkz --setup_rpi vendor_id=091e product_id=4b48\" url_help = 'specify ip address", "at: {WORKOUTIZER_DB_PATH}\\n\") answer = input(f\"Workoutizer could try to use the", "split_items = item.split(\"=\", 1) key = split_items[0].strip() # we remove", "around keys, as is logical value = split_items[1] d[key] =", "you want to setup your Raspberry Pi?\\n\\n\" f\"This will copy", "as current_version if latest_version: click.echo(f\"found newer version: {latest_version}, you have", "import InventoryManager from ansible.vars.manager import VariableManager loader = DataLoader() context.CLIARGS" ]
[ "['\"T\"', '\"5\"']} def trim_adapters(fastq_files, dirs, config): QUALITY_CUTOFF = 5 to_trim", "trim_sequences += [str(Seq(sequence).reverse_complement()) for sequence in v] return trim_sequences def", "reverse complement of the adapters for _, v in builtin_adapters.items():", "\"standard\").lower() if quality_format not in SUPPORTED_FORMATS: logger.error(\"quality_format is set to", "quality_flag = '-q ' + quality_flag if len(fastq_files) == 1:", "builtin_adapters.items(): trim_sequences += [str(Seq(sequence)) for sequence in v] trim_sequences +=", "if quality_format not in SUPPORTED_FORMATS: logger.error(\"quality_format is set to an", "import Seq from itertools import izip, repeat from bcbio.distributed.transaction import", "[cutadapt, \"--times=\" + \"2\", \"--quality-base=\" + quality_base, \"--quality-cutoff=5\", \"--format=fastq\", \"--minimum-length=0\"]", "in v] return trim_sequences def _cutadapt_trim(fastq_files, quality_format, adapters, out_files, cores):", "\".join(SUPPORTED_FORMATS))) exit(1) return quality_format def _get_builtin_adapters(lane_config): chemistries = lane_config[\"algorithm\"].get(\"adapters\", [])", "tempfile from bcbio.utils import (file_exists, safe_makedir, replace_suffix, append_stem, is_pair, replace_directory,", "_run_cutadapt_on_single_file(base_cmd, fastq_file, out_file): stat_file = replace_suffix(out_file, \".trim_stats.txt\") with open(stat_file, \"w\")", "return [fastq1_out] base_cmd += (\"-i {fastq1} -o {tx_fastq1_out} -c {temp_file}", "sequenced. this takes adapter sequences and trims the only the", "min_length = int(lane_config[\"algorithm\"].get(\"min_read_length\", 20)) supplied_quality_format = _get_quality_format(lane_config) if supplied_quality_format ==", "fastq2_out]) as tx_out_files: tx_fastq1_out = tx_out_files[0] tx_fastq2_out = tx_out_files[1] do.run(base_cmd.format(**locals()),", "quality_format def _get_builtin_adapters(lane_config): chemistries = lane_config[\"algorithm\"].get(\"adapters\", []) adapters = {chemistry:", "insert resulting in the reverse complement of the 3' adapter", "\"illumina\": quality_flag = QUALITY_FLAGS[QUALITY_CUTOFF][0] else: quality_flag = QUALITY_FLAGS[QUALITY_CUTOFF][1] quality_flag =", "{fastq1} -ir {fastq2} -of {tx_fastq1_out} \" \"-or {tx_fastq2_out} -c {temp_file}", "dirs, config) jarfile = config_utils.get_jar(\"AlienTrimmer\", jarpath) jvm_opts = \" \".join(resources.get(\"jvm_opts\",", "for adapter in to_trim: temp.write(adapter + \"\\n\") temp.close() if len(fastq_files)", "custom_trim # for unstranded RNA-seq, libraries, both polyA and polyT", "else: out_files = [fastq.filter_single_reads_by_length(fastq_files[0], quality_format, min_length)] map(os.remove, fastq_files) return out_files", "in builtin_adapters.items(): trim_sequences += [str(Seq(sequence)) for sequence in v] trim_sequences", "is_pair, replace_directory, map_wrap) from bcbio.log import logger from bcbio.bam import", "twice remove adapters which will allow things like: # realsequenceAAAAAAadapter", "dirs) fastq1_out = out_files[0] if supplied_quality_format == \"illumina\": quality_flag =", "also trim the reverse complement of the adapters for _,", "config) try: jarpath = config_utils.get_program(\"AlienTrimmer\", config, \"dir\") # fall back", "logger.info(\"Trimming %s from the 3' end of reads in %s", "QUALITY_FLAGS[QUALITY_CUTOFF][1] quality_flag = '-q ' + quality_flag if len(fastq_files) ==", "= \"fastq-sanger\" if is_pair(fastq_files): fastq1, fastq2 = fastq_files out_files =", "what we want; we could also do two or #", "import file_transaction from bcbio.pipeline import config_utils SUPPORTED_ADAPTERS = { \"illumina\":", "[]) builtin_adapters = {k: v for k, v in builtin_adapters.items()", "supplied_quality_format = _get_quality_format(lane_config) if supplied_quality_format == \"illumina\": quality_format = \"fastq-illumina\"", "= temp.name for adapter in to_trim: temp.write(adapter + \"\\n\") temp.close()", "logger from bcbio.bam import fastq from bcbio.provenance import do from", "out_file, fastq_file]) do.run(cmd, \"Running cutadapt on %s.\" % (fastq_file), None)", "fixed_files)): return fixed_files logger.info(\"Trimming %s from the 3' end of", "from %s and %s with AlienTrimmer.\" % (to_trim, fastq1, fastq2))", "\"_trimmed\"), out_dir) return out_files def _get_sequences_to_trim(lane_config): builtin_adapters = _get_builtin_adapters(lane_config) polya", "the adapters for _, v in builtin_adapters.items(): trim_sequences += [str(Seq(sequence))", "we could also do two or # more passes of", "= {5: ['\"E\"', '\"&\"'], 20: ['\"T\"', '\"5\"']} def trim_adapters(fastq_files, dirs,", "if len(fastq_files) == 1: with file_transaction(fastq1_out) as tx_fastq1_out: do.run(base_cmd.format(**locals()), message)", "\"illumina\": [\"AACACTCTTTCCCT\", \"AGATCGGAAGAGCG\"], \"truseq\": [\"AGATCGGAAGAG\"], \"polya\": [\"AAAAAAAAAAAAA\"], \"nextera\": [\"AATGATACGGCGA\", \"CAAGCAGAAGACG\"]}", "Anaconda Python. TODO: Could we use cutadapt as a library", "= [cutadapt, \"--times=\" + \"2\", \"--quality-base=\" + quality_base, \"--quality-cutoff=5\", \"--format=fastq\",", "adapters) base_cmd.extend(adapter_cmd) if all(map(file_exists, out_files)): return out_files with file_transaction(out_files) as", "\"fastq-illumina\" else: quality_format = \"fastq-sanger\" if is_pair(fastq_files): fastq1, fastq2 =", "@map_wrap def _run_cutadapt_on_single_file(base_cmd, fastq_file, out_file): stat_file = replace_suffix(out_file, \".trim_stats.txt\") with", "return trim_sequences def _cutadapt_trim(fastq_files, quality_format, adapters, out_files, cores): \"\"\"Trimming with", "version next to our Anaconda Python. TODO: Could we use", "= custom_trim # for unstranded RNA-seq, libraries, both polyA and", "a library to avoid this? \"\"\" if quality_format == \"illumina\":", "[\"-Xms750m\", \"-Xmx2g\"])) base_cmd = (\"java -jar {jvm_opts} {jarfile} -k 10", "in SUPPORTED_FORMATS: logger.error(\"quality_format is set to an unsupported format. \"", "AlienTrimmer.\" % (to_trim, fastq1) else: fastq2 = fastq_files[1] fastq2_out =", "fastq_files out_files = fastq.filter_reads_by_length(fastq1, fastq2, quality_format, min_length) else: out_files =", "we want; we could also do two or # more", "lane_config[\"algorithm\"].get(\"num_cores\", 1) out_files = _cutadapt_trim(fastq_files, quality_format, to_trim, out_files, cores) fixed_files", "\"--times=\" + \"2\", \"--quality-base=\" + quality_base, \"--quality-cutoff=5\", \"--format=fastq\", \"--minimum-length=0\"] adapter_cmd", "length can be longer than the insert resulting in the", "# --times=2 tries twice remove adapters which will allow things", "20)) supplied_quality_format = _get_quality_format(lane_config) if supplied_quality_format == \"illumina\": quality_format =", "= fastq_files out_files = fastq.filter_reads_by_length(fastq1, fastq2, quality_format, min_length) else: out_files", "{tx_fastq1_out} \" \"-or {tx_fastq2_out} -c {temp_file} {quality_flag}\") message = (\"Trimming", "== \"illumina\": quality_flag = QUALITY_FLAGS[QUALITY_CUTOFF][0] else: quality_flag = QUALITY_FLAGS[QUALITY_CUTOFF][1] quality_flag", "fastq2_out] def trim_read_through(fastq_files, dirs, lane_config): \"\"\" for small insert sizes,", "remove_short_reads(out_files, dirs, lane_config) return fixed_files def remove_short_reads(fastq_files, dirs, lane_config): \"\"\"", "{jarfile} -k 10 \") fastq1 = fastq_files[0] supplied_quality_format = _get_quality_format(config)", "3' end as well if polya: trim_sequences += [polya, str(Seq(polya).reverse_complement())]", "+ out_file, fastq_file]) do.run(cmd, \"Running cutadapt on %s.\" % (fastq_file),", "insert sizes, the read length can be longer than the", "\"--quality-base=\" + quality_base, \"--quality-cutoff=5\", \"--format=fastq\", \"--minimum-length=0\"] adapter_cmd = map(lambda x:", "tmp_out_files: if isinstance(tmp_out_files, basestring): tmp_out_files = [tmp_out_files] map(_run_cutadapt_on_single_file, izip(repeat(base_cmd), fastq_files,", "= fastq.filter_reads_by_length(fastq1, fastq2, quality_format, min_length) else: out_files = [fastq.filter_single_reads_by_length(fastq_files[0], quality_format,", "and polyT can appear # at the 3' end as", "in v] trim_sequences += [str(Seq(sequence).reverse_complement()) for sequence in v] return", "as tmp_out_files: if isinstance(tmp_out_files, basestring): tmp_out_files = [tmp_out_files] map(_run_cutadapt_on_single_file, izip(repeat(base_cmd),", "use cutadapt as a library to avoid this? \"\"\" if", "import logger from bcbio.bam import fastq from bcbio.provenance import do", "of cutadapt cutadapt = os.path.join(os.path.dirname(sys.executable), \"cutadapt\") base_cmd = [cutadapt, \"--times=\"", "with open(stat_file, \"w\") as stat_handle: cmd = list(base_cmd) cmd.extend([\"--output=\" +", "repeat from bcbio.distributed.transaction import file_transaction from bcbio.pipeline import config_utils SUPPORTED_ADAPTERS", "[fastq1_out] else: with file_transaction([fastq1_out, fastq2_out]) as tx_out_files: tx_fastq1_out = tx_out_files[0]", "sequence in v] return trim_sequences def _cutadapt_trim(fastq_files, quality_format, adapters, out_files,", "from bcbio.bam import fastq from bcbio.provenance import do from Bio.Seq", "= (\"java -jar {jvm_opts} {jarfile} -k 10 \") fastq1 =", "= config_utils.get_resources(\"AlienTrimmer\", config) try: jarpath = config_utils.get_program(\"AlienTrimmer\", config, \"dir\") #", "\"dir\") # fall back on Cutadapt if AlienTrimmer is not", "fastq from bcbio.provenance import do from Bio.Seq import Seq from", "out_files def _get_read_through_trimmed_outfiles(fastq_files, dirs): out_dir = os.path.join(dirs[\"work\"], \"trim\") safe_makedir(out_dir) out_files", "return out_files def _get_sequences_to_trim(lane_config): builtin_adapters = _get_builtin_adapters(lane_config) polya = builtin_adapters.get(\"polya\",", "[str(Seq(sequence)) for sequence in v] trim_sequences += [str(Seq(sequence).reverse_complement()) for sequence", "to our Anaconda Python. TODO: Could we use cutadapt as", "and %s with AlienTrimmer.\" % (to_trim, fastq1, fastq2)) with tempfile.NamedTemporaryFile(delete=False)", "fixed_files def remove_short_reads(fastq_files, dirs, lane_config): \"\"\" remove reads from a", "def _run_cutadapt_on_single_file(base_cmd, fastq_file, out_file): stat_file = replace_suffix(out_file, \".trim_stats.txt\") with open(stat_file,", "= out_files[1] if all(map(file_exists, [fastq1_out, fastq2_out])): return [fastq1_out, fastq2_out] base_cmd", "length threshold (30 bases) \"\"\" min_length = int(lane_config[\"algorithm\"].get(\"min_read_length\", 20)) supplied_quality_format", "= lane_config[\"algorithm\"].get(\"adapters\", []) adapters = {chemistry: SUPPORTED_ADAPTERS[chemistry] for chemistry in", "%s from the 3' end of reads in %s using", "dirs, lane_config): \"\"\" remove reads from a single or pair", "sys import tempfile from bcbio.utils import (file_exists, safe_makedir, replace_suffix, append_stem,", "k, v in builtin_adapters.items() if k != \"polya\"} trim_sequences =", "config_utils.get_jar(\"AlienTrimmer\", jarpath) jvm_opts = \" \".join(resources.get(\"jvm_opts\", [\"-Xms750m\", \"-Xmx2g\"])) base_cmd =", "with file_transaction([fastq1_out, fastq2_out]) as tx_out_files: tx_fastq1_out = tx_out_files[0] tx_fastq2_out =", "import fastq from bcbio.provenance import do from Bio.Seq import Seq", "fastq_file, out_file): stat_file = replace_suffix(out_file, \".trim_stats.txt\") with open(stat_file, \"w\") as", "from a single or pair of fastq files which fall", "fastq_files, tmp_out_files)) return out_files @map_wrap def _run_cutadapt_on_single_file(base_cmd, fastq_file, out_file): stat_file", "Could we use cutadapt as a library to avoid this?", "trim_read_through(fastq_files, dirs, lane_config): \"\"\" for small insert sizes, the read", "small insert sizes, the read length can be longer than", "for k, v in builtin_adapters.items() if k != \"polya\"} trim_sequences", "= replace_suffix(out_file, \".trim_stats.txt\") with open(stat_file, \"w\") as stat_handle: cmd =", "out_files, cores): \"\"\"Trimming with cutadapt, using version installed with bcbio-nextgen.", "could also do two or # more passes of cutadapt", "builtin_adapters = _get_builtin_adapters(lane_config) polya = builtin_adapters.get(\"polya\", [None])[0] # allow for", "return fixed_files def remove_short_reads(fastq_files, dirs, lane_config): \"\"\" remove reads from", "longer than the insert resulting in the reverse complement of", "_get_quality_format(lane_config): SUPPORTED_FORMATS = [\"illumina\", \"standard\"] quality_format = lane_config[\"algorithm\"].get(\"quality_format\", \"standard\").lower() if", "config[\"algorithm\"].get(\"num_cores\", 0) out_files = _get_read_through_trimmed_outfiles(fastq_files, dirs) fastq1_out = out_files[0] if", "[\"AATGATACGGCGA\", \"CAAGCAGAAGACG\"]} QUALITY_FLAGS = {5: ['\"E\"', '\"&\"'], 20: ['\"T\"', '\"5\"']}", "else: fastq2 = fastq_files[1] fastq2_out = out_files[1] if all(map(file_exists, [fastq1_out,", "if k != \"polya\"} trim_sequences = custom_trim # for unstranded", "trim_sequences = custom_trim # for unstranded RNA-seq, libraries, both polyA", "from bcbio.provenance import do from Bio.Seq import Seq from itertools", "'\"&\"'], 20: ['\"T\"', '\"5\"']} def trim_adapters(fastq_files, dirs, config): QUALITY_CUTOFF =", "_get_quality_format(lane_config) if supplied_quality_format == \"illumina\": quality_format = \"fastq-illumina\" else: quality_format", "def _get_read_through_trimmed_outfiles(fastq_files, dirs): out_dir = os.path.join(dirs[\"work\"], \"trim\") safe_makedir(out_dir) out_files =", "safe_makedir(out_dir) out_files = replace_directory(append_stem(fastq_files, \"_trimmed\"), out_dir) return out_files def _get_sequences_to_trim(lane_config):", "# XXX: remove after it has been live for a", "sequences and trims the only the reverse complement of the", "can appear # at the 3' end as well if", "'-q ' + quality_flag if len(fastq_files) == 1: if file_exists(fastq1_out):", "# allow for trimming of custom sequences for advanced users", "MYSEQUENCEAAAA (no polyA trim) \"\"\" quality_format = _get_quality_format(lane_config) to_trim =", "return trim_read_through(fastq_files, dirs, config) jarfile = config_utils.get_jar(\"AlienTrimmer\", jarpath) jvm_opts =", "fastq2, quality_format, min_length) else: out_files = [fastq.filter_single_reads_by_length(fastq_files[0], quality_format, min_length)] map(os.remove,", "os import sys import tempfile from bcbio.utils import (file_exists, safe_makedir,", "= int(lane_config[\"algorithm\"].get(\"min_read_length\", 20)) supplied_quality_format = _get_quality_format(lane_config) if supplied_quality_format == \"illumina\":", "= map(lambda x: \"--adapter=\" + x, adapters) base_cmd.extend(adapter_cmd) if all(map(file_exists,", "import os import sys import tempfile from bcbio.utils import (file_exists,", "cores) fixed_files = remove_short_reads(out_files, dirs, lane_config) return fixed_files def remove_short_reads(fastq_files,", "return out_files def _get_read_through_trimmed_outfiles(fastq_files, dirs): out_dir = os.path.join(dirs[\"work\"], \"trim\") safe_makedir(out_dir)", "custom sequences for advanced users custom_trim = lane_config[\"algorithm\"].get(\"custom_trim\", []) builtin_adapters", "out_files = _get_read_through_trimmed_outfiles(fastq_files, dirs) fastq1_out = out_files[0] if supplied_quality_format ==", "avoid this? \"\"\" if quality_format == \"illumina\": quality_base = \"64\"", "(\", \".join(SUPPORTED_FORMATS))) exit(1) return quality_format def _get_builtin_adapters(lane_config): chemistries = lane_config[\"algorithm\"].get(\"adapters\",", "\".fixed\") if all(map(file_exists, fixed_files)): return fixed_files logger.info(\"Trimming %s from the", "system executable to find the version next to our Anaconda", "fastq_file]) do.run(cmd, \"Running cutadapt on %s.\" % (fastq_file), None) def", "from Fastq or BAM files. \"\"\" import os import sys", "tempfile.NamedTemporaryFile(delete=False) as temp: temp_file = temp.name for adapter in to_trim:", "XXX: remove after it has been live for a while", "the reverse complement of the adapters for _, v in", "trim_sequences += [polya, str(Seq(polya).reverse_complement())] # also trim the reverse complement", "\".join(to_trim), \", \".join(fastq_files))) cores = lane_config[\"algorithm\"].get(\"num_cores\", 1) out_files = _cutadapt_trim(fastq_files,", "{chemistry: SUPPORTED_ADAPTERS[chemistry] for chemistry in chemistries if chemistry in SUPPORTED_ADAPTERS}", "[\"AACACTCTTTCCCT\", \"AGATCGGAAGAGCG\"], \"truseq\": [\"AGATCGGAAGAG\"], \"polya\": [\"AAAAAAAAAAAAA\"], \"nextera\": [\"AATGATACGGCGA\", \"CAAGCAGAAGACG\"]} QUALITY_FLAGS", "fastq1, fastq2)) with tempfile.NamedTemporaryFile(delete=False) as temp: temp_file = temp.name for", "= config_utils.get_jar(\"AlienTrimmer\", jarpath) jvm_opts = \" \".join(resources.get(\"jvm_opts\", [\"-Xms750m\", \"-Xmx2g\"])) base_cmd", "# more passes of cutadapt cutadapt = os.path.join(os.path.dirname(sys.executable), \"cutadapt\") base_cmd", "to_trim: temp.write(adapter + \"\\n\") temp.close() if len(fastq_files) == 1: with", "remove both the poly-A and the adapter # this behavior", "a while except: return trim_read_through(fastq_files, dirs, config) jarfile = config_utils.get_jar(\"AlienTrimmer\",", "== 1: if file_exists(fastq1_out): return [fastq1_out] base_cmd += (\"-i {fastq1}", "open(stat_file, \"w\") as stat_handle: cmd = list(base_cmd) cmd.extend([\"--output=\" + out_file,", "[fastq1_out, fastq2_out] def trim_read_through(fastq_files, dirs, lane_config): \"\"\" for small insert", "lane_config): \"\"\" for small insert sizes, the read length can", "v for k, v in builtin_adapters.items() if k != \"polya\"}", "1: if file_exists(fastq1_out): return [fastq1_out] base_cmd += (\"-i {fastq1} -o", "(\"-i {fastq1} -o {tx_fastq1_out} -c {temp_file} \" \"{quality_flag}\") message =", "if len(fastq_files) == 1: if file_exists(fastq1_out): return [fastq1_out] base_cmd +=", "= { \"illumina\": [\"AACACTCTTTCCCT\", \"AGATCGGAAGAGCG\"], \"truseq\": [\"AGATCGGAAGAG\"], \"polya\": [\"AAAAAAAAAAAAA\"], \"nextera\":", "quality_flag = QUALITY_FLAGS[QUALITY_CUTOFF][0] else: quality_flag = QUALITY_FLAGS[QUALITY_CUTOFF][1] quality_flag = '-q", "['\"E\"', '\"&\"'], 20: ['\"T\"', '\"5\"']} def trim_adapters(fastq_files, dirs, config): QUALITY_CUTOFF", "config) jarfile = config_utils.get_jar(\"AlienTrimmer\", jarpath) jvm_opts = \" \".join(resources.get(\"jvm_opts\", [\"-Xms750m\",", "_get_read_through_trimmed_outfiles(fastq_files, dirs) fastq1_out = out_files[0] if supplied_quality_format == \"illumina\": quality_flag", "{quality_flag}\") message = (\"Trimming %s from %s and %s with", "5 to_trim = _get_sequences_to_trim(config) resources = config_utils.get_resources(\"AlienTrimmer\", config) try: jarpath", "trim the reverse complement of the adapters for _, v", "% (\", \".join(to_trim), \", \".join(fastq_files))) cores = lane_config[\"algorithm\"].get(\"num_cores\", 1) out_files", "live for a while except: return trim_read_through(fastq_files, dirs, config) jarfile", "\"\"\" if quality_format == \"illumina\": quality_base = \"64\" else: quality_base", "file_transaction([fastq1_out, fastq2_out]) as tx_out_files: tx_fastq1_out = tx_out_files[0] tx_fastq2_out = tx_out_files[1]", "dirs, lane_config): \"\"\" for small insert sizes, the read length", "= \"64\" else: quality_base = \"33\" # --times=2 tries twice", "% (to_trim, fastq1) else: fastq2 = fastq_files[1] fastq2_out = out_files[1]", "quality_base, \"--quality-cutoff=5\", \"--format=fastq\", \"--minimum-length=0\"] adapter_cmd = map(lambda x: \"--adapter=\" +", "v] trim_sequences += [str(Seq(sequence).reverse_complement()) for sequence in v] return trim_sequences", "-k 10 \") fastq1 = fastq_files[0] supplied_quality_format = _get_quality_format(config) cores", "out_file): stat_file = replace_suffix(out_file, \".trim_stats.txt\") with open(stat_file, \"w\") as stat_handle:", "of fastq files which fall below a length threshold (30", "allow for trimming of custom sequences for advanced users custom_trim", "installed # XXX: remove after it has been live for", "= [\"illumina\", \"standard\"] quality_format = lane_config[\"algorithm\"].get(\"quality_format\", \"standard\").lower() if quality_format not", "libraries, both polyA and polyT can appear # at the", "# fall back on Cutadapt if AlienTrimmer is not installed", "' + quality_flag if len(fastq_files) == 1: if file_exists(fastq1_out): return", "bases) \"\"\" min_length = int(lane_config[\"algorithm\"].get(\"min_read_length\", 20)) supplied_quality_format = _get_quality_format(lane_config) if", "SUPPORTED_FORMATS = [\"illumina\", \"standard\"] quality_format = lane_config[\"algorithm\"].get(\"quality_format\", \"standard\").lower() if quality_format", "fastq1 = fastq_files[0] supplied_quality_format = _get_quality_format(config) cores = config[\"algorithm\"].get(\"num_cores\", 0)", "builtin_adapters.get(\"polya\", [None])[0] # allow for trimming of custom sequences for", "\"2\", \"--quality-base=\" + quality_base, \"--quality-cutoff=5\", \"--format=fastq\", \"--minimum-length=0\"] adapter_cmd = map(lambda", "trimming of input reads from Fastq or BAM files. \"\"\"", "polyT can appear # at the 3' end as well", "polya: trim_sequences += [polya, str(Seq(polya).reverse_complement())] # also trim the reverse", "else: quality_format = \"fastq-sanger\" if is_pair(fastq_files): fastq1, fastq2 = fastq_files", "= _get_sequences_to_trim(lane_config) out_files = _get_read_through_trimmed_outfiles(fastq_files, dirs) fixed_files = append_stem(out_files, \".fixed\")", "find the version next to our Anaconda Python. TODO: Could", "+ \"\\n\") temp.close() if len(fastq_files) == 1: with file_transaction(fastq1_out) as", "\"33\" # --times=2 tries twice remove adapters which will allow", "+ \"2\", \"--quality-base=\" + quality_base, \"--quality-cutoff=5\", \"--format=fastq\", \"--minimum-length=0\"] adapter_cmd =", "[]) adapters = {chemistry: SUPPORTED_ADAPTERS[chemistry] for chemistry in chemistries if", "next to our Anaconda Python. TODO: Could we use cutadapt", "file_exists(fastq1_out): return [fastq1_out] base_cmd += (\"-i {fastq1} -o {tx_fastq1_out} -c", "if polya: trim_sequences += [polya, str(Seq(polya).reverse_complement())] # also trim the", "cores): \"\"\"Trimming with cutadapt, using version installed with bcbio-nextgen. Uses", "if all(map(file_exists, [fastq1_out, fastq2_out])): return [fastq1_out, fastq2_out] base_cmd += (\"-if", "adapter sequences and trims the only the reverse complement of", "resulting in the reverse complement of the 3' adapter being", "fixed_files = append_stem(out_files, \".fixed\") if all(map(file_exists, fixed_files)): return fixed_files logger.info(\"Trimming", "os.path.join(dirs[\"work\"], \"trim\") safe_makedir(out_dir) out_files = replace_directory(append_stem(fastq_files, \"_trimmed\"), out_dir) return out_files", "if file_exists(fastq1_out): return [fastq1_out] base_cmd += (\"-i {fastq1} -o {tx_fastq1_out}", "be longer than the insert resulting in the reverse complement", "jarpath) jvm_opts = \" \".join(resources.get(\"jvm_opts\", [\"-Xms750m\", \"-Xmx2g\"])) base_cmd = (\"java", "the adapter MYSEQUENCEAAAARETPADA -> MYSEQUENCEAAAA (no polyA trim) \"\"\" quality_format", "except: return trim_read_through(fastq_files, dirs, config) jarfile = config_utils.get_jar(\"AlienTrimmer\", jarpath) jvm_opts", "polya = builtin_adapters.get(\"polya\", [None])[0] # allow for trimming of custom", "as well if polya: trim_sequences += [polya, str(Seq(polya).reverse_complement())] # also", "TODO: Could we use cutadapt as a library to avoid", "% (\", \".join(SUPPORTED_FORMATS))) exit(1) return quality_format def _get_builtin_adapters(lane_config): chemistries =", "{ \"illumina\": [\"AACACTCTTTCCCT\", \"AGATCGGAAGAGCG\"], \"truseq\": [\"AGATCGGAAGAG\"], \"polya\": [\"AAAAAAAAAAAAA\"], \"nextera\": [\"AATGATACGGCGA\",", "all(map(file_exists, [fastq1_out, fastq2_out])): return [fastq1_out, fastq2_out] base_cmd += (\"-if {fastq1}", "out_files = _cutadapt_trim(fastq_files, quality_format, to_trim, out_files, cores) fixed_files = remove_short_reads(out_files,", "\"\\n\") temp.close() if len(fastq_files) == 1: with file_transaction(fastq1_out) as tx_fastq1_out:", "well if polya: trim_sequences += [polya, str(Seq(polya).reverse_complement())] # also trim", "{temp_file} \" \"{quality_flag}\") message = \"Trimming %s from %s with", "tmp_out_files)) return out_files @map_wrap def _run_cutadapt_on_single_file(base_cmd, fastq_file, out_file): stat_file =", "quality_format, min_length) else: out_files = [fastq.filter_single_reads_by_length(fastq_files[0], quality_format, min_length)] map(os.remove, fastq_files)", "builtin_adapters.items() if k != \"polya\"} trim_sequences = custom_trim # for", "def _get_quality_format(lane_config): SUPPORTED_FORMATS = [\"illumina\", \"standard\"] quality_format = lane_config[\"algorithm\"].get(\"quality_format\", \"standard\").lower()", "chemistries = lane_config[\"algorithm\"].get(\"adapters\", []) adapters = {chemistry: SUPPORTED_ADAPTERS[chemistry] for chemistry", "\" \"-or {tx_fastq2_out} -c {temp_file} {quality_flag}\") message = (\"Trimming %s", "def trim_read_through(fastq_files, dirs, lane_config): \"\"\" for small insert sizes, the", "threshold (30 bases) \"\"\" min_length = int(lane_config[\"algorithm\"].get(\"min_read_length\", 20)) supplied_quality_format =", "min_length) else: out_files = [fastq.filter_single_reads_by_length(fastq_files[0], quality_format, min_length)] map(os.remove, fastq_files) return", "adapters for _, v in builtin_adapters.items(): trim_sequences += [str(Seq(sequence)) for", "\"--format=fastq\", \"--minimum-length=0\"] adapter_cmd = map(lambda x: \"--adapter=\" + x, adapters)", "else: with file_transaction([fastq1_out, fastq2_out]) as tx_out_files: tx_fastq1_out = tx_out_files[0] tx_fastq2_out", "cores = lane_config[\"algorithm\"].get(\"num_cores\", 1) out_files = _cutadapt_trim(fastq_files, quality_format, to_trim, out_files,", "= _get_builtin_adapters(lane_config) polya = builtin_adapters.get(\"polya\", [None])[0] # allow for trimming", "else: quality_flag = QUALITY_FLAGS[QUALITY_CUTOFF][1] quality_flag = '-q ' + quality_flag", "= QUALITY_FLAGS[QUALITY_CUTOFF][1] quality_flag = '-q ' + quality_flag if len(fastq_files)", "adapter in to_trim: temp.write(adapter + \"\\n\") temp.close() if len(fastq_files) ==", "= tx_out_files[1] do.run(base_cmd.format(**locals()), message) return [fastq1_out, fastq2_out] def trim_read_through(fastq_files, dirs,", "QUALITY_CUTOFF = 5 to_trim = _get_sequences_to_trim(config) resources = config_utils.get_resources(\"AlienTrimmer\", config)", "\"nextera\": [\"AATGATACGGCGA\", \"CAAGCAGAAGACG\"]} QUALITY_FLAGS = {5: ['\"E\"', '\"&\"'], 20: ['\"T\"',", "temp.write(adapter + \"\\n\") temp.close() if len(fastq_files) == 1: with file_transaction(fastq1_out)", "= 5 to_trim = _get_sequences_to_trim(config) resources = config_utils.get_resources(\"AlienTrimmer\", config) try:", "the system executable to find the version next to our", "more passes of cutadapt cutadapt = os.path.join(os.path.dirname(sys.executable), \"cutadapt\") base_cmd =", "from bcbio.utils import (file_exists, safe_makedir, replace_suffix, append_stem, is_pair, replace_directory, map_wrap)", "quality_format, min_length)] map(os.remove, fastq_files) return out_files def _get_read_through_trimmed_outfiles(fastq_files, dirs): out_dir", "as a library to avoid this? \"\"\" if quality_format ==", "import do from Bio.Seq import Seq from itertools import izip,", "of input reads from Fastq or BAM files. \"\"\" import", "{fastq2} -of {tx_fastq1_out} \" \"-or {tx_fastq2_out} -c {temp_file} {quality_flag}\") message", "cutadapt on %s.\" % (fastq_file), None) def _get_quality_format(lane_config): SUPPORTED_FORMATS =", "_cutadapt_trim(fastq_files, quality_format, to_trim, out_files, cores) fixed_files = remove_short_reads(out_files, dirs, lane_config)", "\"CAAGCAGAAGACG\"]} QUALITY_FLAGS = {5: ['\"E\"', '\"&\"'], 20: ['\"T\"', '\"5\"']} def", "SUPPORTED_ADAPTERS = { \"illumina\": [\"AACACTCTTTCCCT\", \"AGATCGGAAGAGCG\"], \"truseq\": [\"AGATCGGAAGAG\"], \"polya\": [\"AAAAAAAAAAAAA\"],", "reverse complement of the 3' adapter being sequenced. this takes", "+ quality_base, \"--quality-cutoff=5\", \"--format=fastq\", \"--minimum-length=0\"] adapter_cmd = map(lambda x: \"--adapter=\"", "safe_makedir, replace_suffix, append_stem, is_pair, replace_directory, map_wrap) from bcbio.log import logger", "{fastq1} -o {tx_fastq1_out} -c {temp_file} \" \"{quality_flag}\") message = \"Trimming", "QUALITY_FLAGS[QUALITY_CUTOFF][0] else: quality_flag = QUALITY_FLAGS[QUALITY_CUTOFF][1] quality_flag = '-q ' +", "\"\"\" quality_format = _get_quality_format(lane_config) to_trim = _get_sequences_to_trim(lane_config) out_files = _get_read_through_trimmed_outfiles(fastq_files,", "want; we could also do two or # more passes", "v] return trim_sequences def _cutadapt_trim(fastq_files, quality_format, adapters, out_files, cores): \"\"\"Trimming", "import tempfile from bcbio.utils import (file_exists, safe_makedir, replace_suffix, append_stem, is_pair,", "base_cmd = [cutadapt, \"--times=\" + \"2\", \"--quality-base=\" + quality_base, \"--quality-cutoff=5\",", "(\"Trimming %s from %s and %s with AlienTrimmer.\" % (to_trim,", "\".join(fastq_files))) cores = lane_config[\"algorithm\"].get(\"num_cores\", 1) out_files = _cutadapt_trim(fastq_files, quality_format, to_trim,", "else: quality_base = \"33\" # --times=2 tries twice remove adapters", "bcbio.distributed.transaction import file_transaction from bcbio.pipeline import config_utils SUPPORTED_ADAPTERS = {", "fastq2 = fastq_files[1] fastq2_out = out_files[1] if all(map(file_exists, [fastq1_out, fastq2_out])):", "out_files def _get_sequences_to_trim(lane_config): builtin_adapters = _get_builtin_adapters(lane_config) polya = builtin_adapters.get(\"polya\", [None])[0]", "in builtin_adapters.items() if k != \"polya\"} trim_sequences = custom_trim #", "== \"illumina\": quality_base = \"64\" else: quality_base = \"33\" #", "an unsupported format. \" \"Supported formats are %s.\" % (\",", "jarfile = config_utils.get_jar(\"AlienTrimmer\", jarpath) jvm_opts = \" \".join(resources.get(\"jvm_opts\", [\"-Xms750m\", \"-Xmx2g\"]))", "in the reverse complement of the 3' adapter being sequenced.", "in %s using \" \"cutadapt.\" % (\", \".join(to_trim), \", \".join(fastq_files)))", "lane_config[\"algorithm\"].get(\"quality_format\", \"standard\").lower() if quality_format not in SUPPORTED_FORMATS: logger.error(\"quality_format is set", "fastq.filter_reads_by_length(fastq1, fastq2, quality_format, min_length) else: out_files = [fastq.filter_single_reads_by_length(fastq_files[0], quality_format, min_length)]", "quality_format, to_trim, out_files, cores) fixed_files = remove_short_reads(out_files, dirs, lane_config) return", "jarpath = config_utils.get_program(\"AlienTrimmer\", config, \"dir\") # fall back on Cutadapt", "[fastq1_out, fastq2_out] base_cmd += (\"-if {fastq1} -ir {fastq2} -of {tx_fastq1_out}", "fastq1) else: fastq2 = fastq_files[1] fastq2_out = out_files[1] if all(map(file_exists,", "[\"AAAAAAAAAAAAA\"], \"nextera\": [\"AATGATACGGCGA\", \"CAAGCAGAAGACG\"]} QUALITY_FLAGS = {5: ['\"E\"', '\"&\"'], 20:", "quality_flag if len(fastq_files) == 1: if file_exists(fastq1_out): return [fastq1_out] base_cmd", "from bcbio.distributed.transaction import file_transaction from bcbio.pipeline import config_utils SUPPORTED_ADAPTERS =", "supplied_quality_format = _get_quality_format(config) cores = config[\"algorithm\"].get(\"num_cores\", 0) out_files = _get_read_through_trimmed_outfiles(fastq_files,", "out_dir = os.path.join(dirs[\"work\"], \"trim\") safe_makedir(out_dir) out_files = replace_directory(append_stem(fastq_files, \"_trimmed\"), out_dir)", "= [tmp_out_files] map(_run_cutadapt_on_single_file, izip(repeat(base_cmd), fastq_files, tmp_out_files)) return out_files @map_wrap def", "and the adapter # this behavior might not be what", "trim) \"\"\" quality_format = _get_quality_format(lane_config) to_trim = _get_sequences_to_trim(lane_config) out_files =", "map(_run_cutadapt_on_single_file, izip(repeat(base_cmd), fastq_files, tmp_out_files)) return out_files @map_wrap def _run_cutadapt_on_single_file(base_cmd, fastq_file,", "return fixed_files logger.info(\"Trimming %s from the 3' end of reads", "message) return [fastq1_out, fastq2_out] def trim_read_through(fastq_files, dirs, lane_config): \"\"\" for", "after it has been live for a while except: return", "\"-Xmx2g\"])) base_cmd = (\"java -jar {jvm_opts} {jarfile} -k 10 \")", "+ quality_flag if len(fastq_files) == 1: if file_exists(fastq1_out): return [fastq1_out]", "of reads in %s using \" \"cutadapt.\" % (\", \".join(to_trim),", "RNA-seq, libraries, both polyA and polyT can appear # at", "tx_fastq2_out = tx_out_files[1] do.run(base_cmd.format(**locals()), message) return [fastq1_out, fastq2_out] def trim_read_through(fastq_files,", "quality_format == \"illumina\": quality_base = \"64\" else: quality_base = \"33\"", "both the poly-A and the adapter # this behavior might", "out_files = replace_directory(append_stem(fastq_files, \"_trimmed\"), out_dir) return out_files def _get_sequences_to_trim(lane_config): builtin_adapters", "base_cmd = (\"java -jar {jvm_opts} {jarfile} -k 10 \") fastq1", "\"\"\" import os import sys import tempfile from bcbio.utils import", "= lane_config[\"algorithm\"].get(\"num_cores\", 1) out_files = _cutadapt_trim(fastq_files, quality_format, to_trim, out_files, cores)", "os.path.join(os.path.dirname(sys.executable), \"cutadapt\") base_cmd = [cutadapt, \"--times=\" + \"2\", \"--quality-base=\" +", "fastq2 = fastq_files out_files = fastq.filter_reads_by_length(fastq1, fastq2, quality_format, min_length) else:", "[fastq1_out] base_cmd += (\"-i {fastq1} -o {tx_fastq1_out} -c {temp_file} \"", "while except: return trim_read_through(fastq_files, dirs, config) jarfile = config_utils.get_jar(\"AlienTrimmer\", jarpath)", "\") fastq1 = fastq_files[0] supplied_quality_format = _get_quality_format(config) cores = config[\"algorithm\"].get(\"num_cores\",", "quality_format, adapters, out_files, cores): \"\"\"Trimming with cutadapt, using version installed", "= '-q ' + quality_flag if len(fastq_files) == 1: if", "do two or # more passes of cutadapt cutadapt =", "stat_handle: cmd = list(base_cmd) cmd.extend([\"--output=\" + out_file, fastq_file]) do.run(cmd, \"Running", "fastq2)) with tempfile.NamedTemporaryFile(delete=False) as temp: temp_file = temp.name for adapter", "-of {tx_fastq1_out} \" \"-or {tx_fastq2_out} -c {temp_file} {quality_flag}\") message =", "appear # at the 3' end as well if polya:", "tmp_out_files = [tmp_out_files] map(_run_cutadapt_on_single_file, izip(repeat(base_cmd), fastq_files, tmp_out_files)) return out_files @map_wrap", "Cutadapt if AlienTrimmer is not installed # XXX: remove after", "file_transaction(out_files) as tmp_out_files: if isinstance(tmp_out_files, basestring): tmp_out_files = [tmp_out_files] map(_run_cutadapt_on_single_file,", "sizes, the read length can be longer than the insert", "tx_out_files: tx_fastq1_out = tx_out_files[0] tx_fastq2_out = tx_out_files[1] do.run(base_cmd.format(**locals()), message) return", "isinstance(tmp_out_files, basestring): tmp_out_files = [tmp_out_files] map(_run_cutadapt_on_single_file, izip(repeat(base_cmd), fastq_files, tmp_out_files)) return", "executable to find the version next to our Anaconda Python.", "if AlienTrimmer is not installed # XXX: remove after it", "AlienTrimmer is not installed # XXX: remove after it has", "for chemistry in chemistries if chemistry in SUPPORTED_ADAPTERS} return adapters", "\"Trimming %s from %s with AlienTrimmer.\" % (to_trim, fastq1) else:", "which fall below a length threshold (30 bases) \"\"\" min_length", "MYSEQUENCEAAAARETPADA -> MYSEQUENCEAAAA (no polyA trim) \"\"\" quality_format = _get_quality_format(lane_config)", "QUALITY_FLAGS = {5: ['\"E\"', '\"&\"'], 20: ['\"T\"', '\"5\"']} def trim_adapters(fastq_files,", "\"\"\" for small insert sizes, the read length can be", "\"cutadapt\") base_cmd = [cutadapt, \"--times=\" + \"2\", \"--quality-base=\" + quality_base,", "lane_config[\"algorithm\"].get(\"custom_trim\", []) builtin_adapters = {k: v for k, v in", "tries twice remove adapters which will allow things like: #", "single or pair of fastq files which fall below a", "1: with file_transaction(fastq1_out) as tx_fastq1_out: do.run(base_cmd.format(**locals()), message) return [fastq1_out] else:", "this? \"\"\" if quality_format == \"illumina\": quality_base = \"64\" else:", "\"w\") as stat_handle: cmd = list(base_cmd) cmd.extend([\"--output=\" + out_file, fastq_file])", "-c {temp_file} \" \"{quality_flag}\") message = \"Trimming %s from %s", "version installed with bcbio-nextgen. Uses the system executable to find", "(file_exists, safe_makedir, replace_suffix, append_stem, is_pair, replace_directory, map_wrap) from bcbio.log import", "fall back on Cutadapt if AlienTrimmer is not installed #", "fixed_files logger.info(\"Trimming %s from the 3' end of reads in", "from the 3' end of reads in %s using \"", "= fastq_files[0] supplied_quality_format = _get_quality_format(config) cores = config[\"algorithm\"].get(\"num_cores\", 0) out_files", "quality_base = \"33\" # --times=2 tries twice remove adapters which", "[\"illumina\", \"standard\"] quality_format = lane_config[\"algorithm\"].get(\"quality_format\", \"standard\").lower() if quality_format not in", "pair of fastq files which fall below a length threshold", "!= \"polya\"} trim_sequences = custom_trim # for unstranded RNA-seq, libraries,", "we use cutadapt as a library to avoid this? \"\"\"", "return quality_format def _get_builtin_adapters(lane_config): chemistries = lane_config[\"algorithm\"].get(\"adapters\", []) adapters =", "\"{quality_flag}\") message = \"Trimming %s from %s with AlienTrimmer.\" %", "as temp: temp_file = temp.name for adapter in to_trim: temp.write(adapter", "only the reverse complement of the adapter MYSEQUENCEAAAARETPADA -> MYSEQUENCEAAAA", "from bcbio.pipeline import config_utils SUPPORTED_ADAPTERS = { \"illumina\": [\"AACACTCTTTCCCT\", \"AGATCGGAAGAGCG\"],", "\"-or {tx_fastq2_out} -c {temp_file} {quality_flag}\") message = (\"Trimming %s from", "file_transaction from bcbio.pipeline import config_utils SUPPORTED_ADAPTERS = { \"illumina\": [\"AACACTCTTTCCCT\",", "# at the 3' end as well if polya: trim_sequences", "len(fastq_files) == 1: if file_exists(fastq1_out): return [fastq1_out] base_cmd += (\"-i", "with tempfile.NamedTemporaryFile(delete=False) as temp: temp_file = temp.name for adapter in", "def remove_short_reads(fastq_files, dirs, lane_config): \"\"\" remove reads from a single", "[fastq1_out, fastq2_out])): return [fastq1_out, fastq2_out] base_cmd += (\"-if {fastq1} -ir", "= _get_quality_format(lane_config) if supplied_quality_format == \"illumina\": quality_format = \"fastq-illumina\" else:", "cutadapt as a library to avoid this? \"\"\" if quality_format", "(\"-if {fastq1} -ir {fastq2} -of {tx_fastq1_out} \" \"-or {tx_fastq2_out} -c", "reads in %s using \" \"cutadapt.\" % (\", \".join(to_trim), \",", "on %s.\" % (fastq_file), None) def _get_quality_format(lane_config): SUPPORTED_FORMATS = [\"illumina\",", "= [fastq.filter_single_reads_by_length(fastq_files[0], quality_format, min_length)] map(os.remove, fastq_files) return out_files def _get_read_through_trimmed_outfiles(fastq_files,", "fastq_files[1] fastq2_out = out_files[1] if all(map(file_exists, [fastq1_out, fastq2_out])): return [fastq1_out,", "\"cutadapt.\" % (\", \".join(to_trim), \", \".join(fastq_files))) cores = lane_config[\"algorithm\"].get(\"num_cores\", 1)", "= append_stem(out_files, \".fixed\") if all(map(file_exists, fixed_files)): return fixed_files logger.info(\"Trimming %s", "temp_file = temp.name for adapter in to_trim: temp.write(adapter + \"\\n\")", "%s from %s and %s with AlienTrimmer.\" % (to_trim, fastq1,", "(to_trim, fastq1, fastq2)) with tempfile.NamedTemporaryFile(delete=False) as temp: temp_file = temp.name", "using version installed with bcbio-nextgen. Uses the system executable to", "users custom_trim = lane_config[\"algorithm\"].get(\"custom_trim\", []) builtin_adapters = {k: v for", "return out_files with file_transaction(out_files) as tmp_out_files: if isinstance(tmp_out_files, basestring): tmp_out_files", "\"standard\"] quality_format = lane_config[\"algorithm\"].get(\"quality_format\", \"standard\").lower() if quality_format not in SUPPORTED_FORMATS:", "custom_trim = lane_config[\"algorithm\"].get(\"custom_trim\", []) builtin_adapters = {k: v for k,", "the version next to our Anaconda Python. TODO: Could we", "= {chemistry: SUPPORTED_ADAPTERS[chemistry] for chemistry in chemistries if chemistry in", "input reads from Fastq or BAM files. \"\"\" import os", "\".join(resources.get(\"jvm_opts\", [\"-Xms750m\", \"-Xmx2g\"])) base_cmd = (\"java -jar {jvm_opts} {jarfile} -k", "read length can be longer than the insert resulting in", "{temp_file} {quality_flag}\") message = (\"Trimming %s from %s and %s", "cutadapt = os.path.join(os.path.dirname(sys.executable), \"cutadapt\") base_cmd = [cutadapt, \"--times=\" + \"2\",", "from %s with AlienTrimmer.\" % (to_trim, fastq1) else: fastq2 =", "library to avoid this? \"\"\" if quality_format == \"illumina\": quality_base", "quality_flag = QUALITY_FLAGS[QUALITY_CUTOFF][1] quality_flag = '-q ' + quality_flag if", "config, \"dir\") # fall back on Cutadapt if AlienTrimmer is", "the 3' adapter being sequenced. this takes adapter sequences and", "which will allow things like: # realsequenceAAAAAAadapter to remove both", "base_cmd += (\"-i {fastq1} -o {tx_fastq1_out} -c {temp_file} \" \"{quality_flag}\")", "import (file_exists, safe_makedir, replace_suffix, append_stem, is_pair, replace_directory, map_wrap) from bcbio.log", "all(map(file_exists, out_files)): return out_files with file_transaction(out_files) as tmp_out_files: if isinstance(tmp_out_files,", "realsequenceAAAAAAadapter to remove both the poly-A and the adapter #", "\"--minimum-length=0\"] adapter_cmd = map(lambda x: \"--adapter=\" + x, adapters) base_cmd.extend(adapter_cmd)", "(\", \".join(to_trim), \", \".join(fastq_files))) cores = lane_config[\"algorithm\"].get(\"num_cores\", 1) out_files =", "supplied_quality_format == \"illumina\": quality_flag = QUALITY_FLAGS[QUALITY_CUTOFF][0] else: quality_flag = QUALITY_FLAGS[QUALITY_CUTOFF][1]", "with AlienTrimmer.\" % (to_trim, fastq1, fastq2)) with tempfile.NamedTemporaryFile(delete=False) as temp:", "temp.close() if len(fastq_files) == 1: with file_transaction(fastq1_out) as tx_fastq1_out: do.run(base_cmd.format(**locals()),", "sequence in v] trim_sequences += [str(Seq(sequence).reverse_complement()) for sequence in v]", "is set to an unsupported format. \" \"Supported formats are", "not installed # XXX: remove after it has been live", "_get_builtin_adapters(lane_config): chemistries = lane_config[\"algorithm\"].get(\"adapters\", []) adapters = {chemistry: SUPPORTED_ADAPTERS[chemistry] for", "_get_sequences_to_trim(config) resources = config_utils.get_resources(\"AlienTrimmer\", config) try: jarpath = config_utils.get_program(\"AlienTrimmer\", config,", "Fastq or BAM files. \"\"\" import os import sys import", "remove reads from a single or pair of fastq files", "of custom sequences for advanced users custom_trim = lane_config[\"algorithm\"].get(\"custom_trim\", [])", "-o {tx_fastq1_out} -c {temp_file} \" \"{quality_flag}\") message = \"Trimming %s", "quality_format = \"fastq-sanger\" if is_pair(fastq_files): fastq1, fastq2 = fastq_files out_files", "\"illumina\": quality_base = \"64\" else: quality_base = \"33\" # --times=2", "of the adapters for _, v in builtin_adapters.items(): trim_sequences +=", "to avoid this? \"\"\" if quality_format == \"illumina\": quality_base =", "= config_utils.get_program(\"AlienTrimmer\", config, \"dir\") # fall back on Cutadapt if", "being sequenced. this takes adapter sequences and trims the only", "jvm_opts = \" \".join(resources.get(\"jvm_opts\", [\"-Xms750m\", \"-Xmx2g\"])) base_cmd = (\"java -jar", "-> MYSEQUENCEAAAA (no polyA trim) \"\"\" quality_format = _get_quality_format(lane_config) to_trim", "dirs, lane_config) return fixed_files def remove_short_reads(fastq_files, dirs, lane_config): \"\"\" remove", "be what we want; we could also do two or", "from itertools import izip, repeat from bcbio.distributed.transaction import file_transaction from", "\"trim\") safe_makedir(out_dir) out_files = replace_directory(append_stem(fastq_files, \"_trimmed\"), out_dir) return out_files def", "this takes adapter sequences and trims the only the reverse", "as tx_out_files: tx_fastq1_out = tx_out_files[0] tx_fastq2_out = tx_out_files[1] do.run(base_cmd.format(**locals()), message)", "10 \") fastq1 = fastq_files[0] supplied_quality_format = _get_quality_format(config) cores =", "also do two or # more passes of cutadapt cutadapt", "fixed_files = remove_short_reads(out_files, dirs, lane_config) return fixed_files def remove_short_reads(fastq_files, dirs,", "files which fall below a length threshold (30 bases) \"\"\"", "out_files)): return out_files with file_transaction(out_files) as tmp_out_files: if isinstance(tmp_out_files, basestring):", "at the 3' end as well if polya: trim_sequences +=", "append_stem(out_files, \".fixed\") if all(map(file_exists, fixed_files)): return fixed_files logger.info(\"Trimming %s from", "# realsequenceAAAAAAadapter to remove both the poly-A and the adapter", "if all(map(file_exists, fixed_files)): return fixed_files logger.info(\"Trimming %s from the 3'", "# this behavior might not be what we want; we", "if supplied_quality_format == \"illumina\": quality_format = \"fastq-illumina\" else: quality_format =", "quality_format = _get_quality_format(lane_config) to_trim = _get_sequences_to_trim(lane_config) out_files = _get_read_through_trimmed_outfiles(fastq_files, dirs)", "def _get_sequences_to_trim(lane_config): builtin_adapters = _get_builtin_adapters(lane_config) polya = builtin_adapters.get(\"polya\", [None])[0] #", "for a while except: return trim_read_through(fastq_files, dirs, config) jarfile =", "\"Running cutadapt on %s.\" % (fastq_file), None) def _get_quality_format(lane_config): SUPPORTED_FORMATS", "_get_quality_format(config) cores = config[\"algorithm\"].get(\"num_cores\", 0) out_files = _get_read_through_trimmed_outfiles(fastq_files, dirs) fastq1_out", "quality_format = \"fastq-illumina\" else: quality_format = \"fastq-sanger\" if is_pair(fastq_files): fastq1,", "map(os.remove, fastq_files) return out_files def _get_read_through_trimmed_outfiles(fastq_files, dirs): out_dir = os.path.join(dirs[\"work\"],", "{tx_fastq2_out} -c {temp_file} {quality_flag}\") message = (\"Trimming %s from %s", "SUPPORTED_ADAPTERS[chemistry] for chemistry in chemistries if chemistry in SUPPORTED_ADAPTERS} return", "return [fastq1_out, fastq2_out] def trim_read_through(fastq_files, dirs, lane_config): \"\"\" for small", "if isinstance(tmp_out_files, basestring): tmp_out_files = [tmp_out_files] map(_run_cutadapt_on_single_file, izip(repeat(base_cmd), fastq_files, tmp_out_files))", "= lane_config[\"algorithm\"].get(\"quality_format\", \"standard\").lower() if quality_format not in SUPPORTED_FORMATS: logger.error(\"quality_format is", "remove adapters which will allow things like: # realsequenceAAAAAAadapter to", "dirs, config): QUALITY_CUTOFF = 5 to_trim = _get_sequences_to_trim(config) resources =", "%s from %s with AlienTrimmer.\" % (to_trim, fastq1) else: fastq2", "if quality_format == \"illumina\": quality_base = \"64\" else: quality_base =", "trimming of custom sequences for advanced users custom_trim = lane_config[\"algorithm\"].get(\"custom_trim\",", "message = \"Trimming %s from %s with AlienTrimmer.\" % (to_trim,", "temp: temp_file = temp.name for adapter in to_trim: temp.write(adapter +", "= os.path.join(dirs[\"work\"], \"trim\") safe_makedir(out_dir) out_files = replace_directory(append_stem(fastq_files, \"_trimmed\"), out_dir) return", "= config[\"algorithm\"].get(\"num_cores\", 0) out_files = _get_read_through_trimmed_outfiles(fastq_files, dirs) fastq1_out = out_files[0]", "replace_suffix, append_stem, is_pair, replace_directory, map_wrap) from bcbio.log import logger from", "map(lambda x: \"--adapter=\" + x, adapters) base_cmd.extend(adapter_cmd) if all(map(file_exists, out_files)):", "cmd.extend([\"--output=\" + out_file, fastq_file]) do.run(cmd, \"Running cutadapt on %s.\" %", "len(fastq_files) == 1: with file_transaction(fastq1_out) as tx_fastq1_out: do.run(base_cmd.format(**locals()), message) return", "BAM files. \"\"\" import os import sys import tempfile from", "out_files[1] if all(map(file_exists, [fastq1_out, fastq2_out])): return [fastq1_out, fastq2_out] base_cmd +=", "== \"illumina\": quality_format = \"fastq-illumina\" else: quality_format = \"fastq-sanger\" if", "Bio.Seq import Seq from itertools import izip, repeat from bcbio.distributed.transaction", "has been live for a while except: return trim_read_through(fastq_files, dirs,", "takes adapter sequences and trims the only the reverse complement", "adapter # this behavior might not be what we want;", "_get_read_through_trimmed_outfiles(fastq_files, dirs) fixed_files = append_stem(out_files, \".fixed\") if all(map(file_exists, fixed_files)): return", "[\"AGATCGGAAGAG\"], \"polya\": [\"AAAAAAAAAAAAA\"], \"nextera\": [\"AATGATACGGCGA\", \"CAAGCAGAAGACG\"]} QUALITY_FLAGS = {5: ['\"E\"',", "the reverse complement of the 3' adapter being sequenced. this", "[fastq.filter_single_reads_by_length(fastq_files[0], quality_format, min_length)] map(os.remove, fastq_files) return out_files def _get_read_through_trimmed_outfiles(fastq_files, dirs):", "poly-A and the adapter # this behavior might not be", "or # more passes of cutadapt cutadapt = os.path.join(os.path.dirname(sys.executable), \"cutadapt\")", "of the 3' adapter being sequenced. this takes adapter sequences", "_get_sequences_to_trim(lane_config): builtin_adapters = _get_builtin_adapters(lane_config) polya = builtin_adapters.get(\"polya\", [None])[0] # allow", "of the adapter MYSEQUENCEAAAARETPADA -> MYSEQUENCEAAAA (no polyA trim) \"\"\"", "config): QUALITY_CUTOFF = 5 to_trim = _get_sequences_to_trim(config) resources = config_utils.get_resources(\"AlienTrimmer\",", "\" \"{quality_flag}\") message = \"Trimming %s from %s with AlienTrimmer.\"", "dirs): out_dir = os.path.join(dirs[\"work\"], \"trim\") safe_makedir(out_dir) out_files = replace_directory(append_stem(fastq_files, \"_trimmed\"),", "out_dir) return out_files def _get_sequences_to_trim(lane_config): builtin_adapters = _get_builtin_adapters(lane_config) polya =", "passes of cutadapt cutadapt = os.path.join(os.path.dirname(sys.executable), \"cutadapt\") base_cmd = [cutadapt,", "all(map(file_exists, fixed_files)): return fixed_files logger.info(\"Trimming %s from the 3' end", "out_files, cores) fixed_files = remove_short_reads(out_files, dirs, lane_config) return fixed_files def", "\"--quality-cutoff=5\", \"--format=fastq\", \"--minimum-length=0\"] adapter_cmd = map(lambda x: \"--adapter=\" + x,", "% (to_trim, fastq1, fastq2)) with tempfile.NamedTemporaryFile(delete=False) as temp: temp_file =", "sequences for advanced users custom_trim = lane_config[\"algorithm\"].get(\"custom_trim\", []) builtin_adapters =", "_get_sequences_to_trim(lane_config) out_files = _get_read_through_trimmed_outfiles(fastq_files, dirs) fixed_files = append_stem(out_files, \".fixed\") if", "= _get_read_through_trimmed_outfiles(fastq_files, dirs) fastq1_out = out_files[0] if supplied_quality_format == \"illumina\":", "out_files @map_wrap def _run_cutadapt_on_single_file(base_cmd, fastq_file, out_file): stat_file = replace_suffix(out_file, \".trim_stats.txt\")", "both polyA and polyT can appear # at the 3'", "\"64\" else: quality_base = \"33\" # --times=2 tries twice remove", "'\"5\"']} def trim_adapters(fastq_files, dirs, config): QUALITY_CUTOFF = 5 to_trim =", "adapters = {chemistry: SUPPORTED_ADAPTERS[chemistry] for chemistry in chemistries if chemistry", "and trims the only the reverse complement of the adapter", "fall below a length threshold (30 bases) \"\"\" min_length =", "\"truseq\": [\"AGATCGGAAGAG\"], \"polya\": [\"AAAAAAAAAAAAA\"], \"nextera\": [\"AATGATACGGCGA\", \"CAAGCAGAAGACG\"]} QUALITY_FLAGS = {5:", "with AlienTrimmer.\" % (to_trim, fastq1) else: fastq2 = fastq_files[1] fastq2_out", "file_transaction(fastq1_out) as tx_fastq1_out: do.run(base_cmd.format(**locals()), message) return [fastq1_out] else: with file_transaction([fastq1_out,", "+= [str(Seq(sequence)) for sequence in v] trim_sequences += [str(Seq(sequence).reverse_complement()) for", "out_files[0] if supplied_quality_format == \"illumina\": quality_flag = QUALITY_FLAGS[QUALITY_CUTOFF][0] else: quality_flag", "= \"Trimming %s from %s with AlienTrimmer.\" % (to_trim, fastq1)", "int(lane_config[\"algorithm\"].get(\"min_read_length\", 20)) supplied_quality_format = _get_quality_format(lane_config) if supplied_quality_format == \"illumina\": quality_format", "3' adapter being sequenced. this takes adapter sequences and trims", "% (fastq_file), None) def _get_quality_format(lane_config): SUPPORTED_FORMATS = [\"illumina\", \"standard\"] quality_format", "if supplied_quality_format == \"illumina\": quality_flag = QUALITY_FLAGS[QUALITY_CUTOFF][0] else: quality_flag =", "the 3' end of reads in %s using \" \"cutadapt.\"", "a length threshold (30 bases) \"\"\" min_length = int(lane_config[\"algorithm\"].get(\"min_read_length\", 20))", "as tx_fastq1_out: do.run(base_cmd.format(**locals()), message) return [fastq1_out] else: with file_transaction([fastq1_out, fastq2_out])", "-ir {fastq2} -of {tx_fastq1_out} \" \"-or {tx_fastq2_out} -c {temp_file} {quality_flag}\")", "izip, repeat from bcbio.distributed.transaction import file_transaction from bcbio.pipeline import config_utils", "if is_pair(fastq_files): fastq1, fastq2 = fastq_files out_files = fastq.filter_reads_by_length(fastq1, fastq2,", "return [fastq1_out, fastq2_out] base_cmd += (\"-if {fastq1} -ir {fastq2} -of", "adapter being sequenced. this takes adapter sequences and trims the", "bcbio.log import logger from bcbio.bam import fastq from bcbio.provenance import", "tx_out_files[1] do.run(base_cmd.format(**locals()), message) return [fastq1_out, fastq2_out] def trim_read_through(fastq_files, dirs, lane_config):", "= _get_quality_format(config) cores = config[\"algorithm\"].get(\"num_cores\", 0) out_files = _get_read_through_trimmed_outfiles(fastq_files, dirs)", "= (\"Trimming %s from %s and %s with AlienTrimmer.\" %", "out_files = _get_read_through_trimmed_outfiles(fastq_files, dirs) fixed_files = append_stem(out_files, \".fixed\") if all(map(file_exists,", "reads from a single or pair of fastq files which", "(to_trim, fastq1) else: fastq2 = fastq_files[1] fastq2_out = out_files[1] if", "# for unstranded RNA-seq, libraries, both polyA and polyT can", "\" \".join(resources.get(\"jvm_opts\", [\"-Xms750m\", \"-Xmx2g\"])) base_cmd = (\"java -jar {jvm_opts} {jarfile}", "replace_suffix(out_file, \".trim_stats.txt\") with open(stat_file, \"w\") as stat_handle: cmd = list(base_cmd)", "fastq_files) return out_files def _get_read_through_trimmed_outfiles(fastq_files, dirs): out_dir = os.path.join(dirs[\"work\"], \"trim\")", "\".trim_stats.txt\") with open(stat_file, \"w\") as stat_handle: cmd = list(base_cmd) cmd.extend([\"--output=\"", "to an unsupported format. \" \"Supported formats are %s.\" %", "\"\"\" remove reads from a single or pair of fastq", "with cutadapt, using version installed with bcbio-nextgen. Uses the system", "config_utils.get_program(\"AlienTrimmer\", config, \"dir\") # fall back on Cutadapt if AlienTrimmer", "cores = config[\"algorithm\"].get(\"num_cores\", 0) out_files = _get_read_through_trimmed_outfiles(fastq_files, dirs) fastq1_out =", "1) out_files = _cutadapt_trim(fastq_files, quality_format, to_trim, out_files, cores) fixed_files =", "[tmp_out_files] map(_run_cutadapt_on_single_file, izip(repeat(base_cmd), fastq_files, tmp_out_files)) return out_files @map_wrap def _run_cutadapt_on_single_file(base_cmd,", "= \" \".join(resources.get(\"jvm_opts\", [\"-Xms750m\", \"-Xmx2g\"])) base_cmd = (\"java -jar {jvm_opts}", "= tx_out_files[0] tx_fastq2_out = tx_out_files[1] do.run(base_cmd.format(**locals()), message) return [fastq1_out, fastq2_out]", "the 3' end as well if polya: trim_sequences += [polya,", "things like: # realsequenceAAAAAAadapter to remove both the poly-A and", "+ x, adapters) base_cmd.extend(adapter_cmd) if all(map(file_exists, out_files)): return out_files with", "itertools import izip, repeat from bcbio.distributed.transaction import file_transaction from bcbio.pipeline", "(30 bases) \"\"\" min_length = int(lane_config[\"algorithm\"].get(\"min_read_length\", 20)) supplied_quality_format = _get_quality_format(lane_config)", "base_cmd += (\"-if {fastq1} -ir {fastq2} -of {tx_fastq1_out} \" \"-or", "-jar {jvm_opts} {jarfile} -k 10 \") fastq1 = fastq_files[0] supplied_quality_format", "izip(repeat(base_cmd), fastq_files, tmp_out_files)) return out_files @map_wrap def _run_cutadapt_on_single_file(base_cmd, fastq_file, out_file):", "bcbio.utils import (file_exists, safe_makedir, replace_suffix, append_stem, is_pair, replace_directory, map_wrap) from", "{tx_fastq1_out} -c {temp_file} \" \"{quality_flag}\") message = \"Trimming %s from", "SUPPORTED_FORMATS: logger.error(\"quality_format is set to an unsupported format. \" \"Supported", "do from Bio.Seq import Seq from itertools import izip, repeat", "(\"java -jar {jvm_opts} {jarfile} -k 10 \") fastq1 = fastq_files[0]", "to_trim = _get_sequences_to_trim(config) resources = config_utils.get_resources(\"AlienTrimmer\", config) try: jarpath =", "been live for a while except: return trim_read_through(fastq_files, dirs, config)", "bcbio.pipeline import config_utils SUPPORTED_ADAPTERS = { \"illumina\": [\"AACACTCTTTCCCT\", \"AGATCGGAAGAGCG\"], \"truseq\":", "+= [polya, str(Seq(polya).reverse_complement())] # also trim the reverse complement of", "= _get_read_through_trimmed_outfiles(fastq_files, dirs) fixed_files = append_stem(out_files, \".fixed\") if all(map(file_exists, fixed_files)):", "the reverse complement of the adapter MYSEQUENCEAAAARETPADA -> MYSEQUENCEAAAA (no", "_, v in builtin_adapters.items(): trim_sequences += [str(Seq(sequence)) for sequence in", "are %s.\" % (\", \".join(SUPPORTED_FORMATS))) exit(1) return quality_format def _get_builtin_adapters(lane_config):", "lane_config) return fixed_files def remove_short_reads(fastq_files, dirs, lane_config): \"\"\" remove reads", "for small insert sizes, the read length can be longer", "behavior might not be what we want; we could also", "\"polya\": [\"AAAAAAAAAAAAA\"], \"nextera\": [\"AATGATACGGCGA\", \"CAAGCAGAAGACG\"]} QUALITY_FLAGS = {5: ['\"E\"', '\"&\"'],", "complement of the adapters for _, v in builtin_adapters.items(): trim_sequences", "config_utils SUPPORTED_ADAPTERS = { \"illumina\": [\"AACACTCTTTCCCT\", \"AGATCGGAAGAGCG\"], \"truseq\": [\"AGATCGGAAGAG\"], \"polya\":", "fastq1_out = out_files[0] if supplied_quality_format == \"illumina\": quality_flag = QUALITY_FLAGS[QUALITY_CUTOFF][0]", "the only the reverse complement of the adapter MYSEQUENCEAAAARETPADA ->", "or BAM files. \"\"\" import os import sys import tempfile", "config_utils.get_resources(\"AlienTrimmer\", config) try: jarpath = config_utils.get_program(\"AlienTrimmer\", config, \"dir\") # fall", "remove_short_reads(fastq_files, dirs, lane_config): \"\"\" remove reads from a single or", "fastq files which fall below a length threshold (30 bases)", "quality_format = lane_config[\"algorithm\"].get(\"quality_format\", \"standard\").lower() if quality_format not in SUPPORTED_FORMATS: logger.error(\"quality_format", "AlienTrimmer.\" % (to_trim, fastq1, fastq2)) with tempfile.NamedTemporaryFile(delete=False) as temp: temp_file", "like: # realsequenceAAAAAAadapter to remove both the poly-A and the", "[polya, str(Seq(polya).reverse_complement())] # also trim the reverse complement of the", "_cutadapt_trim(fastq_files, quality_format, adapters, out_files, cores): \"\"\"Trimming with cutadapt, using version", "the insert resulting in the reverse complement of the 3'", "is_pair(fastq_files): fastq1, fastq2 = fastq_files out_files = fastq.filter_reads_by_length(fastq1, fastq2, quality_format,", "message = (\"Trimming %s from %s and %s with AlienTrimmer.\"", "polyA and polyT can appear # at the 3' end", "polyA trim) \"\"\" quality_format = _get_quality_format(lane_config) to_trim = _get_sequences_to_trim(lane_config) out_files", "with file_transaction(out_files) as tmp_out_files: if isinstance(tmp_out_files, basestring): tmp_out_files = [tmp_out_files]", "format. \" \"Supported formats are %s.\" % (\", \".join(SUPPORTED_FORMATS))) exit(1)", "import config_utils SUPPORTED_ADAPTERS = { \"illumina\": [\"AACACTCTTTCCCT\", \"AGATCGGAAGAGCG\"], \"truseq\": [\"AGATCGGAAGAG\"],", "the adapter # this behavior might not be what we", "the poly-A and the adapter # this behavior might not", "-c {temp_file} {quality_flag}\") message = (\"Trimming %s from %s and", "not be what we want; we could also do two", "map_wrap) from bcbio.log import logger from bcbio.bam import fastq from", "fastq2_out = out_files[1] if all(map(file_exists, [fastq1_out, fastq2_out])): return [fastq1_out, fastq2_out]", "%s with AlienTrimmer.\" % (to_trim, fastq1) else: fastq2 = fastq_files[1]", "base_cmd.extend(adapter_cmd) if all(map(file_exists, out_files)): return out_files with file_transaction(out_files) as tmp_out_files:", "def _get_builtin_adapters(lane_config): chemistries = lane_config[\"algorithm\"].get(\"adapters\", []) adapters = {chemistry: SUPPORTED_ADAPTERS[chemistry]", "Seq from itertools import izip, repeat from bcbio.distributed.transaction import file_transaction", "append_stem, is_pair, replace_directory, map_wrap) from bcbio.log import logger from bcbio.bam", "fastq2_out])): return [fastq1_out, fastq2_out] base_cmd += (\"-if {fastq1} -ir {fastq2}", "on Cutadapt if AlienTrimmer is not installed # XXX: remove", "for unstranded RNA-seq, libraries, both polyA and polyT can appear", "using \" \"cutadapt.\" % (\", \".join(to_trim), \", \".join(fastq_files))) cores =", "out_files = [fastq.filter_single_reads_by_length(fastq_files[0], quality_format, min_length)] map(os.remove, fastq_files) return out_files def", "import sys import tempfile from bcbio.utils import (file_exists, safe_makedir, replace_suffix,", "= QUALITY_FLAGS[QUALITY_CUTOFF][0] else: quality_flag = QUALITY_FLAGS[QUALITY_CUTOFF][1] quality_flag = '-q '", "from Bio.Seq import Seq from itertools import izip, repeat from", "basestring): tmp_out_files = [tmp_out_files] map(_run_cutadapt_on_single_file, izip(repeat(base_cmd), fastq_files, tmp_out_files)) return out_files", "trims the only the reverse complement of the adapter MYSEQUENCEAAAARETPADA", "with file_transaction(fastq1_out) as tx_fastq1_out: do.run(base_cmd.format(**locals()), message) return [fastq1_out] else: with", "bcbio.bam import fastq from bcbio.provenance import do from Bio.Seq import", "= fastq_files[1] fastq2_out = out_files[1] if all(map(file_exists, [fastq1_out, fastq2_out])): return", "v in builtin_adapters.items() if k != \"polya\"} trim_sequences = custom_trim", "trim_sequences def _cutadapt_trim(fastq_files, quality_format, adapters, out_files, cores): \"\"\"Trimming with cutadapt,", "back on Cutadapt if AlienTrimmer is not installed # XXX:", "%s.\" % (\", \".join(SUPPORTED_FORMATS))) exit(1) return quality_format def _get_builtin_adapters(lane_config): chemistries", "str(Seq(polya).reverse_complement())] # also trim the reverse complement of the adapters", "(fastq_file), None) def _get_quality_format(lane_config): SUPPORTED_FORMATS = [\"illumina\", \"standard\"] quality_format =", "out_files with file_transaction(out_files) as tmp_out_files: if isinstance(tmp_out_files, basestring): tmp_out_files =", "\"Supported formats are %s.\" % (\", \".join(SUPPORTED_FORMATS))) exit(1) return quality_format", "adapter MYSEQUENCEAAAARETPADA -> MYSEQUENCEAAAA (no polyA trim) \"\"\" quality_format =", "def trim_adapters(fastq_files, dirs, config): QUALITY_CUTOFF = 5 to_trim = _get_sequences_to_trim(config)", "\"--adapter=\" + x, adapters) base_cmd.extend(adapter_cmd) if all(map(file_exists, out_files)): return out_files", "\" \"cutadapt.\" % (\", \".join(to_trim), \", \".join(fastq_files))) cores = lane_config[\"algorithm\"].get(\"num_cores\",", "3' end of reads in %s using \" \"cutadapt.\" %", "resources = config_utils.get_resources(\"AlienTrimmer\", config) try: jarpath = config_utils.get_program(\"AlienTrimmer\", config, \"dir\")", "trim_read_through(fastq_files, dirs, config) jarfile = config_utils.get_jar(\"AlienTrimmer\", jarpath) jvm_opts = \"", "0) out_files = _get_read_through_trimmed_outfiles(fastq_files, dirs) fastq1_out = out_files[0] if supplied_quality_format", "= _get_quality_format(lane_config) to_trim = _get_sequences_to_trim(lane_config) out_files = _get_read_through_trimmed_outfiles(fastq_files, dirs) fixed_files", "quality_base = \"64\" else: quality_base = \"33\" # --times=2 tries", "%s.\" % (fastq_file), None) def _get_quality_format(lane_config): SUPPORTED_FORMATS = [\"illumina\", \"standard\"]", "for _, v in builtin_adapters.items(): trim_sequences += [str(Seq(sequence)) for sequence", "= replace_directory(append_stem(fastq_files, \"_trimmed\"), out_dir) return out_files def _get_sequences_to_trim(lane_config): builtin_adapters =", "trim_sequences += [str(Seq(sequence)) for sequence in v] trim_sequences += [str(Seq(sequence).reverse_complement())", "reads from Fastq or BAM files. \"\"\" import os import", "from bcbio.log import logger from bcbio.bam import fastq from bcbio.provenance", "do.run(base_cmd.format(**locals()), message) return [fastq1_out, fastq2_out] def trim_read_through(fastq_files, dirs, lane_config): \"\"\"", "with bcbio-nextgen. Uses the system executable to find the version", "x: \"--adapter=\" + x, adapters) base_cmd.extend(adapter_cmd) if all(map(file_exists, out_files)): return", "--times=2 tries twice remove adapters which will allow things like:", "def _cutadapt_trim(fastq_files, quality_format, adapters, out_files, cores): \"\"\"Trimming with cutadapt, using", "below a length threshold (30 bases) \"\"\" min_length = int(lane_config[\"algorithm\"].get(\"min_read_length\",", "\"\"\"Provide trimming of input reads from Fastq or BAM files.", "if all(map(file_exists, out_files)): return out_files with file_transaction(out_files) as tmp_out_files: if", "\"illumina\": quality_format = \"fastq-illumina\" else: quality_format = \"fastq-sanger\" if is_pair(fastq_files):", "is not installed # XXX: remove after it has been", "%s and %s with AlienTrimmer.\" % (to_trim, fastq1, fastq2)) with", "unstranded RNA-seq, libraries, both polyA and polyT can appear #", "two or # more passes of cutadapt cutadapt = os.path.join(os.path.dirname(sys.executable),", "do.run(cmd, \"Running cutadapt on %s.\" % (fastq_file), None) def _get_quality_format(lane_config):", "quality_format not in SUPPORTED_FORMATS: logger.error(\"quality_format is set to an unsupported", "= builtin_adapters.get(\"polya\", [None])[0] # allow for trimming of custom sequences", "this behavior might not be what we want; we could", "exit(1) return quality_format def _get_builtin_adapters(lane_config): chemistries = lane_config[\"algorithm\"].get(\"adapters\", []) adapters", "k != \"polya\"} trim_sequences = custom_trim # for unstranded RNA-seq,", "return [fastq1_out] else: with file_transaction([fastq1_out, fastq2_out]) as tx_out_files: tx_fastq1_out =", "adapter_cmd = map(lambda x: \"--adapter=\" + x, adapters) base_cmd.extend(adapter_cmd) if", "message) return [fastq1_out] else: with file_transaction([fastq1_out, fastq2_out]) as tx_out_files: tx_fastq1_out", "20: ['\"T\"', '\"5\"']} def trim_adapters(fastq_files, dirs, config): QUALITY_CUTOFF = 5", "= _get_sequences_to_trim(config) resources = config_utils.get_resources(\"AlienTrimmer\", config) try: jarpath = config_utils.get_program(\"AlienTrimmer\",", "the read length can be longer than the insert resulting", "replace_directory(append_stem(fastq_files, \"_trimmed\"), out_dir) return out_files def _get_sequences_to_trim(lane_config): builtin_adapters = _get_builtin_adapters(lane_config)", "for trimming of custom sequences for advanced users custom_trim =", "list(base_cmd) cmd.extend([\"--output=\" + out_file, fastq_file]) do.run(cmd, \"Running cutadapt on %s.\"", "{k: v for k, v in builtin_adapters.items() if k !=", "= \"33\" # --times=2 tries twice remove adapters which will", "fastq2_out] base_cmd += (\"-if {fastq1} -ir {fastq2} -of {tx_fastq1_out} \"", "builtin_adapters = {k: v for k, v in builtin_adapters.items() if", "allow things like: # realsequenceAAAAAAadapter to remove both the poly-A", "+= (\"-if {fastq1} -ir {fastq2} -of {tx_fastq1_out} \" \"-or {tx_fastq2_out}", "our Anaconda Python. TODO: Could we use cutadapt as a", "end of reads in %s using \" \"cutadapt.\" % (\",", "tx_out_files[0] tx_fastq2_out = tx_out_files[1] do.run(base_cmd.format(**locals()), message) return [fastq1_out, fastq2_out] def", "remove after it has been live for a while except:", "cutadapt cutadapt = os.path.join(os.path.dirname(sys.executable), \"cutadapt\") base_cmd = [cutadapt, \"--times=\" +", "not in SUPPORTED_FORMATS: logger.error(\"quality_format is set to an unsupported format.", "return out_files @map_wrap def _run_cutadapt_on_single_file(base_cmd, fastq_file, out_file): stat_file = replace_suffix(out_file,", "reverse complement of the adapter MYSEQUENCEAAAARETPADA -> MYSEQUENCEAAAA (no polyA", "formats are %s.\" % (\", \".join(SUPPORTED_FORMATS))) exit(1) return quality_format def", "\"\"\" min_length = int(lane_config[\"algorithm\"].get(\"min_read_length\", 20)) supplied_quality_format = _get_quality_format(lane_config) if supplied_quality_format", "\"polya\"} trim_sequences = custom_trim # for unstranded RNA-seq, libraries, both", "replace_directory, map_wrap) from bcbio.log import logger from bcbio.bam import fastq", "= out_files[0] if supplied_quality_format == \"illumina\": quality_flag = QUALITY_FLAGS[QUALITY_CUTOFF][0] else:", "= \"fastq-illumina\" else: quality_format = \"fastq-sanger\" if is_pair(fastq_files): fastq1, fastq2", "installed with bcbio-nextgen. Uses the system executable to find the", "Uses the system executable to find the version next to", "= lane_config[\"algorithm\"].get(\"custom_trim\", []) builtin_adapters = {k: v for k, v", "x, adapters) base_cmd.extend(adapter_cmd) if all(map(file_exists, out_files)): return out_files with file_transaction(out_files)", "cutadapt, using version installed with bcbio-nextgen. Uses the system executable", "will allow things like: # realsequenceAAAAAAadapter to remove both the", "= list(base_cmd) cmd.extend([\"--output=\" + out_file, fastq_file]) do.run(cmd, \"Running cutadapt on", "import izip, repeat from bcbio.distributed.transaction import file_transaction from bcbio.pipeline import", "to find the version next to our Anaconda Python. TODO:", "as stat_handle: cmd = list(base_cmd) cmd.extend([\"--output=\" + out_file, fastq_file]) do.run(cmd,", "v in builtin_adapters.items(): trim_sequences += [str(Seq(sequence)) for sequence in v]", "\"fastq-sanger\" if is_pair(fastq_files): fastq1, fastq2 = fastq_files out_files = fastq.filter_reads_by_length(fastq1,", "a single or pair of fastq files which fall below", "== 1: with file_transaction(fastq1_out) as tx_fastq1_out: do.run(base_cmd.format(**locals()), message) return [fastq1_out]", "lane_config[\"algorithm\"].get(\"adapters\", []) adapters = {chemistry: SUPPORTED_ADAPTERS[chemistry] for chemistry in chemistries", "Python. TODO: Could we use cutadapt as a library to", "(no polyA trim) \"\"\" quality_format = _get_quality_format(lane_config) to_trim = _get_sequences_to_trim(lane_config)", "try: jarpath = config_utils.get_program(\"AlienTrimmer\", config, \"dir\") # fall back on", "dirs) fixed_files = append_stem(out_files, \".fixed\") if all(map(file_exists, fixed_files)): return fixed_files", "set to an unsupported format. \" \"Supported formats are %s.\"", "bcbio.provenance import do from Bio.Seq import Seq from itertools import", "cmd = list(base_cmd) cmd.extend([\"--output=\" + out_file, fastq_file]) do.run(cmd, \"Running cutadapt", "or pair of fastq files which fall below a length", "= os.path.join(os.path.dirname(sys.executable), \"cutadapt\") base_cmd = [cutadapt, \"--times=\" + \"2\", \"--quality-base=\"", "min_length)] map(os.remove, fastq_files) return out_files def _get_read_through_trimmed_outfiles(fastq_files, dirs): out_dir =", "complement of the 3' adapter being sequenced. this takes adapter", "for advanced users custom_trim = lane_config[\"algorithm\"].get(\"custom_trim\", []) builtin_adapters = {k:", "None) def _get_quality_format(lane_config): SUPPORTED_FORMATS = [\"illumina\", \"standard\"] quality_format = lane_config[\"algorithm\"].get(\"quality_format\",", "temp.name for adapter in to_trim: temp.write(adapter + \"\\n\") temp.close() if", "fastq_files[0] supplied_quality_format = _get_quality_format(config) cores = config[\"algorithm\"].get(\"num_cores\", 0) out_files =", "it has been live for a while except: return trim_read_through(fastq_files,", "trim_adapters(fastq_files, dirs, config): QUALITY_CUTOFF = 5 to_trim = _get_sequences_to_trim(config) resources", "complement of the adapter MYSEQUENCEAAAARETPADA -> MYSEQUENCEAAAA (no polyA trim)", "to remove both the poly-A and the adapter # this", "logger.error(\"quality_format is set to an unsupported format. \" \"Supported formats", "to_trim = _get_sequences_to_trim(lane_config) out_files = _get_read_through_trimmed_outfiles(fastq_files, dirs) fixed_files = append_stem(out_files,", "lane_config): \"\"\" remove reads from a single or pair of", "= _cutadapt_trim(fastq_files, quality_format, to_trim, out_files, cores) fixed_files = remove_short_reads(out_files, dirs,", "out_files = fastq.filter_reads_by_length(fastq1, fastq2, quality_format, min_length) else: out_files = [fastq.filter_single_reads_by_length(fastq_files[0],", "[None])[0] # allow for trimming of custom sequences for advanced", "{jvm_opts} {jarfile} -k 10 \") fastq1 = fastq_files[0] supplied_quality_format =", "tx_fastq1_out = tx_out_files[0] tx_fastq2_out = tx_out_files[1] do.run(base_cmd.format(**locals()), message) return [fastq1_out,", "_get_read_through_trimmed_outfiles(fastq_files, dirs): out_dir = os.path.join(dirs[\"work\"], \"trim\") safe_makedir(out_dir) out_files = replace_directory(append_stem(fastq_files,", "\" \"Supported formats are %s.\" % (\", \".join(SUPPORTED_FORMATS))) exit(1) return", "adapters, out_files, cores): \"\"\"Trimming with cutadapt, using version installed with", "{5: ['\"E\"', '\"&\"'], 20: ['\"T\"', '\"5\"']} def trim_adapters(fastq_files, dirs, config):", "+= [str(Seq(sequence).reverse_complement()) for sequence in v] return trim_sequences def _cutadapt_trim(fastq_files,", "for sequence in v] trim_sequences += [str(Seq(sequence).reverse_complement()) for sequence in", "fastq1, fastq2 = fastq_files out_files = fastq.filter_reads_by_length(fastq1, fastq2, quality_format, min_length)", "_get_quality_format(lane_config) to_trim = _get_sequences_to_trim(lane_config) out_files = _get_read_through_trimmed_outfiles(fastq_files, dirs) fixed_files =", "for sequence in v] return trim_sequences def _cutadapt_trim(fastq_files, quality_format, adapters,", "\"AGATCGGAAGAGCG\"], \"truseq\": [\"AGATCGGAAGAG\"], \"polya\": [\"AAAAAAAAAAAAA\"], \"nextera\": [\"AATGATACGGCGA\", \"CAAGCAGAAGACG\"]} QUALITY_FLAGS =", "%s with AlienTrimmer.\" % (to_trim, fastq1, fastq2)) with tempfile.NamedTemporaryFile(delete=False) as", "bcbio-nextgen. Uses the system executable to find the version next", "\"\"\"Trimming with cutadapt, using version installed with bcbio-nextgen. Uses the", "than the insert resulting in the reverse complement of the", "\", \".join(fastq_files))) cores = lane_config[\"algorithm\"].get(\"num_cores\", 1) out_files = _cutadapt_trim(fastq_files, quality_format,", "# also trim the reverse complement of the adapters for", "end as well if polya: trim_sequences += [polya, str(Seq(polya).reverse_complement())] #", "do.run(base_cmd.format(**locals()), message) return [fastq1_out] else: with file_transaction([fastq1_out, fastq2_out]) as tx_out_files:", "can be longer than the insert resulting in the reverse", "+= (\"-i {fastq1} -o {tx_fastq1_out} -c {temp_file} \" \"{quality_flag}\") message", "%s using \" \"cutadapt.\" % (\", \".join(to_trim), \", \".join(fastq_files))) cores", "_get_builtin_adapters(lane_config) polya = builtin_adapters.get(\"polya\", [None])[0] # allow for trimming of", "= remove_short_reads(out_files, dirs, lane_config) return fixed_files def remove_short_reads(fastq_files, dirs, lane_config):", "= {k: v for k, v in builtin_adapters.items() if k", "in to_trim: temp.write(adapter + \"\\n\") temp.close() if len(fastq_files) == 1:", "advanced users custom_trim = lane_config[\"algorithm\"].get(\"custom_trim\", []) builtin_adapters = {k: v", "[str(Seq(sequence).reverse_complement()) for sequence in v] return trim_sequences def _cutadapt_trim(fastq_files, quality_format,", "tx_fastq1_out: do.run(base_cmd.format(**locals()), message) return [fastq1_out] else: with file_transaction([fastq1_out, fastq2_out]) as", "files. \"\"\" import os import sys import tempfile from bcbio.utils", "might not be what we want; we could also do", "stat_file = replace_suffix(out_file, \".trim_stats.txt\") with open(stat_file, \"w\") as stat_handle: cmd", "unsupported format. \" \"Supported formats are %s.\" % (\", \".join(SUPPORTED_FORMATS)))", "supplied_quality_format == \"illumina\": quality_format = \"fastq-illumina\" else: quality_format = \"fastq-sanger\"", "to_trim, out_files, cores) fixed_files = remove_short_reads(out_files, dirs, lane_config) return fixed_files", "adapters which will allow things like: # realsequenceAAAAAAadapter to remove" ]
[ "= request.query_params.get('category') list_id = int(request.query_params.get('id')) parentConfig = AnalysisConfig.objects.get(project=project) jsonHelper =", "get_object_or_404(projects, id=kwargs['project_id']) if (SolverProgress.objects.filter(project=project).exists()): progress = json.loads(get_object_or_404(SolverProgress, project=project).progress) logs =", "to media folder. a query will be created to make", "request.query_params.get('solver') client = docker.from_env() solverPath = os.path.abspath('./solvers') if DockerLogs.objects.filter(project=project).exists(): DockerLogs.objects.filter(project=project).delete()", "\"\"\" kills the running docker container \"\"\" client = docker.from_env()", "< len(jsonHelper[category]): # check if an entry with the same", "entry with the same name exists\", status=400) else: return Response(data=\"No", "response else: return Response(data=\"not found\", status=404) class solverProgress(APIView): parser_classes =", "check if the docker is running, and if a container", "name exists if not list(filter(lambda name: name[\"Name\"] == data[\"Name\"], jsonHelper[category]))", "= SolverResults.objects.filter(project=project).values()[0] folderPath = resutls['path'] # create a ZipFile object", "SolverProgress.objects.get_or_create( project=project, defaults={'progress' :json.dumps({\"status\": \"\", \"message\": \"\"})}) progress = SolverProgress.objects.get(", "project = get_object_or_404(projects, id=kwargs['project_id']) data = request.data.dict() # if request", "data[\"Name\"]: jsonHelper[category][list_id] = data parentConfig.config = json.dumps(jsonHelper) parentConfig.save() return Response(data=jsonHelper[category],", "filename in filenames: if not filename == 'results.zip': filePath =", "get_object_or_404(projects, id=kwargs['project_id']) if (SolverResults.objects.filter(project=project).exists()): resutls = SolverResults.objects.filter(project=project).values()[0] folderPath = resutls['path']", "is no category similar to the user request if category", "query will be created to make it available for download", "setting for the main folder directory is on. If you", "parentConfig.config = json.dumps(jsonHelper) parentConfig.save() return Response(data=jsonHelper[category], status=status.HTTP_201_CREATED) def put(self, request,", "exists if not list(filter(lambda name: name[\"Name\"] == data[\"Name\"], jsonHelper[category])) or", "MultiPartParser] def get(self, request, *args, **kwargs): \"\"\" return a list", "datetime import datetime class solverConfig(APIView): parser_classes = [FormParser, MultiPartParser] def", "import FormParser, JSONParser, MultiPartParser, FileUploadParser from rest_framework import status import", "the entry\", status=400) # if there is no category similar", "int(request.query_params.get('id')) parentConfig = AnalysisConfig.objects.get(project=project) jsonHelper = json.loads(parentConfig.config) if category in", "if jsonHelper[category]: if list_id >= 0 and list_id < len(jsonHelper[category]):", "config \"\"\" project = get_object_or_404(projects, id=kwargs['project_id']) category = request.query_params.get('category') parentConfig", "name: name[\"Name\"] == data[\"Name\"], jsonHelper[category])): jsonHelper[category].append(data) else: return Response(data=\"an entry", "'bind': '/home/fenics/shared', 'mode': 'rw'}}, working_dir=\"/home/fenics/shared\", # runs solver.py with two", "= '''please check if the docker is running, and if", "folderPath = os.path.abspath( \"../FEniCSUI/media/{}/results/\".format(kwargs['project_id'])) os.makedirs(folderPath, exist_ok=True) filePath = '{}/{}.{}'.format(folderPath, filename,", "container.stop() return Response(data=\"container stopped successfully\", status=200) except: return Response(data=\"No container", "threading import Thread from time import sleep from datetime import", "\"RECEIVED\", \"message\": {\"progress\": \"0.0\"}}, \"logs\":\"\"}) progress.save() # initiate related solver", "jsonHelper: del jsonHelper[category] parentConfig.config = json.dumps(jsonHelper) parentConfig.save() return Response(data=jsonHelper, status=status.HTTP_410_GONE)", "if not filename == 'results.zip': filePath = os.path.join(folderName, filename) #", "= current_time + str(line.strip(), 'utf-8') + \"\\n\" + logs.log logs.save()", "category \"\"\" project = get_object_or_404(projects, id=kwargs['project_id']) category = request.query_params.get('category') list_id", "= get_object_or_404(SolverProgress, project=project) progress.progress = json.dumps(data) progress.save() else: SolverProgress.objects.create(project=project, progress=data)", "with WSL, make sure it has access to the windows", "initiate related solver solver = request.query_params.get('solver') client = docker.from_env() solverPath", "exist\".format(category), status=status.HTTP_204_NO_CONTENT) def delete(self, request, *args, **kwargs): \"\"\" Delete an", "check if an entry with the same name exists if", "return Response(data=config[\"config\"], status=status.HTTP_200_OK) def streamDockerLog(container, project): for line in container.logs(stream=True):", "category = request.query_params.get('category') parentConfig = AnalysisConfig.objects.get(project=project) jsonHelper = json.loads(parentConfig.config) #", "in url parameters \"\"\" project = get_object_or_404(projects, id=kwargs['project_id']) # set", "def delete(self, request, *args, **kwargs): \"\"\" kills the running docker", "saved in the database \"\"\" project = get_object_or_404(projects, id=kwargs['project_id']) if", "status=status.HTTP_204_NO_CONTENT) def post(self, request, *args, **kwargs): \"\"\" create a new", "id=kwargs['project_id']) config = json.loads(AnalysisConfig.objects.get( project=project).config).keys() return Response(data=config, status=status.HTTP_200_OK) def delete(self,", "return Response(data=jsonHelper[category], status=status.HTTP_200_OK) else: return Response(data=\"an entry with the same", "return Response(data=jsonHelper, status=status.HTTP_410_GONE) else: return Response(data=\"The category {} does not", "with the same name exists if not list(filter(lambda name: name[\"Name\"]", "= 'attachment; filename=results.zip' return response else: return Response(data=\"not found\", status=404)", "= request.query_params.get('category') parentConfig = AnalysisConfig.objects.get(project=project) jsonHelper = json.loads(parentConfig.config) if category", "not exist\".format(category), status=status.HTTP_204_NO_CONTENT) class Categories(APIView): parser_classes = [FormParser, MultiPartParser] def", "projects from .models import AnalysisConfig, SolverResults, SolverProgress, DockerLogs from rest_framework.parsers", "AnalysisConfig.objects.get(project=project) jsonHelper = json.loads(parentConfig.config) # if request does not contain", "the entry\", status=400) category = request.query_params.get('category') list_id = int(request.query_params.get('id')) parentConfig", "if category in jsonHelper: del jsonHelper[category] parentConfig.config = json.dumps(jsonHelper) parentConfig.save()", "to zip zipObj.write(filePath, os.path.basename(filePath)) zipFile = open('{}/results.zip'.format(folderPath), 'rb') response= HttpResponse(zipFile,content_type='application/zip')", "category entry's data \"\"\" project = get_object_or_404(projects, id=kwargs['project_id']) data =", "request, *args, **kwargs): \"\"\" Update the progress from solver \"\"\"", "parentConfig.save() return Response(data=jsonHelper[category], status=status.HTTP_200_OK) else: return Response(data=\"an entry with the", "FileUploadParser from rest_framework import status import docker import os import", "str(line.strip(), 'utf-8') + \"\\n\" + logs.log logs.save() class solvers(APIView): parser_classes", "solver)], name=\"FEniCSDocker\", auto_remove=False, detach=True) thread = Thread(target=streamDockerLog, args=(container, project)) thread.start()", "found\", status=404) class solverProgress(APIView): parser_classes = [JSONParser] def get(self, request,", "put(self, request, *args, **kwargs): \"\"\" Edit an existing category entry's", "= os.path.abspath('./solvers') if DockerLogs.objects.filter(project=project).exists(): DockerLogs.objects.filter(project=project).delete() DockerLogs.objects.create(project=project,log=\"\") try: container = client.containers.run(", "id=kwargs['project_id']) data = request.data if SolverProgress.objects.filter(project=project).exists(): progress = get_object_or_404(SolverProgress, project=project)", "list_id = int(request.query_params.get('id')) parentConfig = AnalysisConfig.objects.get(project=project) jsonHelper = json.loads(parentConfig.config) if", "list_id >= 0 and list_id < len(jsonHelper[category]): # check if", "AnalysisConfig.objects.get(project=project) jsonHelper = json.loads(parentConfig.config) if category in jsonHelper: del jsonHelper[category]", "list(filter(lambda name: name[\"Name\"] == data[\"Name\"], jsonHelper[category])) or jsonHelper[category][list_id][\"Name\"] == data[\"Name\"]:", "solvers(APIView): parser_classes = [FormParser, MultiPartParser] def get(self, request, *args, **kwargs):", "= json.dumps({\"state\":{\"status\": \"RECEIVED\", \"message\": {\"progress\": \"0.0\"}}, \"logs\":\"\"}) progress.save() # initiate", "= get_object_or_404(projects, id=kwargs['project_id']) config = json.loads(AnalysisConfig.objects.get( project=project).config).keys() return Response(data=config, status=status.HTTP_200_OK)", "delete(self, request, *args, **kwargs): \"\"\" kills the running docker container", "**kwargs): \"\"\" return a list of entries within a given", "from solver \"\"\" project = get_object_or_404(projects, id=kwargs['project_id']) data = request.data", "\"\", \"message\": \"\"})}) progress = SolverProgress.objects.get( project=project ) progress.progress =", "get(self, request, *args, **kwargs): \"\"\" Get the solver config to", "\"\"\" project = get_object_or_404(projects, id=kwargs['project_id']) if (SolverProgress.objects.filter(project=project).exists()): progress = json.loads(get_object_or_404(SolverProgress,", "solverHub.py {} {}`\".format( project.id, solver)], name=\"FEniCSDocker\", auto_remove=False, detach=True) thread =", "request, *args, **kwargs): \"\"\" create a new category for solver", "logs = get_object_or_404(DockerLogs, project=project) now = datetime.now() current_time = now.strftime(\"[%H:%M:%S]:", "similar to the user request if category not in jsonHelper:", "request, *args, **kwargs): \"\"\" Get the results saved in the", "an entry from the category \"\"\" project = get_object_or_404(projects, id=kwargs['project_id'])", "progress.progress = json.dumps(data) progress.save() else: SolverProgress.objects.create(project=project, progress=data) return Response(data=get_object_or_404(SolverProgress, project=project).progress,", "category not in jsonHelper: jsonHelper[category] = [] jsonHelper[category].append(data) # check", "within a given category \"\"\" project = get_object_or_404(projects, id=kwargs['project_id']) category", "\"\"\" project = get_object_or_404(projects, id=kwargs['project_id']) category = request.query_params.get('category') parentConfig =", "solver = request.query_params.get('solver') client = docker.from_env() solverPath = os.path.abspath('./solvers') if", "ZipFile('{}/results.zip'.format(folderPath), 'w') as zipObj: # Iterate over all the files", "status=status.HTTP_204_NO_CONTENT) else: return Response(data=\"The category {} does not exist\".format(category), status=status.HTTP_204_NO_CONTENT)", "\"Name\" in data: return Response(data=\"Please provide a 'Name' for the", "same name exists\", status=400) parentConfig.config = json.dumps(jsonHelper) parentConfig.save() return Response(data=jsonHelper[category],", "= get_object_or_404(projects, id=kwargs['project_id']) config = AnalysisConfig.objects.filter(project=project).values()[0] return Response(data=config[\"config\"], status=status.HTTP_200_OK) def", "Response(data=\"submitted to analysis\", status=status.HTTP_200_OK) def delete(self, request, *args, **kwargs): \"\"\"", "no category similar to the user request if category not", "status=400) category = request.query_params.get('category') list_id = int(request.query_params.get('id')) parentConfig = AnalysisConfig.objects.get(project=project)", "a new category for solver configuration \"\"\" project = get_object_or_404(projects,", "filenames: if not filename == 'results.zip': filePath = os.path.join(folderName, filename)", "django.shortcuts import get_object_or_404 from dashboard.models import projects from .models import", "= json.loads(parentConfig.config) if category in jsonHelper: return Response(data=jsonHelper[category], status=status.HTTP_200_OK) else:", "request does not contain a name if not \"Name\" in", "Response(data=jsonHelper[category], status=status.HTTP_201_CREATED) def put(self, request, *args, **kwargs): \"\"\" Edit an", "return Response(data=\"The category {} does not exist\".format(category), status=status.HTTP_204_NO_CONTENT) def post(self,", "MultiPartParser] def get(self, request, *args, **kwargs): \"\"\" Get the solver", "status=status.HTTP_200_OK) def delete(self, request, *args, **kwargs): \"\"\" kills the running", "project)) thread.start() except: message = '''please check if the docker", "jsonHelper[category])) or jsonHelper[category][list_id][\"Name\"] == data[\"Name\"]: jsonHelper[category][list_id] = data parentConfig.config =", "from datetime import datetime class solverConfig(APIView): parser_classes = [FormParser, MultiPartParser]", "parser_classes = [FormParser, MultiPartParser] def get(self, request, *args, **kwargs): \"\"\"", "Response(data=\"results updated at {}\".format(filePath), status=status.HTTP_201_CREATED) class downloadResults(APIView): def get(self, request,", "MultiPartParser, FileUploadParser from rest_framework import status import docker import os", "for the main folder directory is on. If you are", "return Response(data=\"not found\", status=404) class solverProgress(APIView): parser_classes = [JSONParser] def", "the related solver defined in url parameters \"\"\" project =", "class downloadResults(APIView): def get(self, request, *args, **kwargs): \"\"\" Get the", "as zipObj: # Iterate over all the files in directory", "= AnalysisConfig.objects.get(project=project) jsonHelper = json.loads(parentConfig.config) # if request does not", "Response(data=\"container stopped successfully\", status=200) except: return Response(data=\"No container running\", status=404)", "status=404) class saveResults(APIView): parser_classes = [FileUploadParser] def put(self, request, filename,", ">= 0 and list_id < len(jsonHelper[category]): jsonHelper[category].pop(int(list_id)) parentConfig.config = json.dumps(jsonHelper)", "= client.containers.get(\"FEniCSDocker\") container.stop() return Response(data=\"container stopped successfully\", status=200) except: return", "provide a 'Name' for the entry\", status=400) # if there", "filePath = '{}/{}.{}'.format(folderPath, filename, fileType) with open(filePath, 'wb+') as destination:", "not exist\".format(category), status=status.HTTP_204_NO_CONTENT) def post(self, request, *args, **kwargs): \"\"\" create", "[FormParser, MultiPartParser] def get(self, request, *args, **kwargs): \"\"\" Get the", "\"\"\" project = get_object_or_404(projects, id=kwargs['project_id']) data = request.data if SolverProgress.objects.filter(project=project).exists():", "Response(data=message, status=500) return Response(data=\"submitted to analysis\", status=status.HTTP_200_OK) def delete(self, request,", "docker windows, make sure the file sharing setting for the", ") progress.progress = json.dumps({\"state\":{\"status\": \"RECEIVED\", \"message\": {\"progress\": \"0.0\"}}, \"logs\":\"\"}) progress.save()", "is on. If you are woking with WSL, make sure", "SolverProgress, DockerLogs from rest_framework.parsers import FormParser, JSONParser, MultiPartParser, FileUploadParser from", "request, *args, **kwargs): \"\"\" Get the progress \"\"\" project =", "except: message = '''please check if the docker is running,", "data \"\"\" project = get_object_or_404(projects, id=kwargs['project_id']) data = request.data.dict() #", "MultiPartParser] def get(self, request, *args, **kwargs): \"\"\" Return the existing", "now.strftime(\"[%H:%M:%S]: \") logs.log = current_time + str(line.strip(), 'utf-8') + \"\\n\"", "return Response(data=\"The category {} does not exist\".format(category), status=status.HTTP_204_NO_CONTENT) class Categories(APIView):", "else: return Response(data=\"The category {} does not exist\".format(category), status=status.HTTP_204_NO_CONTENT) def", "the main folder directory is on. If you are woking", "HttpResponse(zipFile,content_type='application/zip') response['Content-Disposition'] = 'attachment; filename=results.zip' return response else: return Response(data=\"not", "solver solver = request.query_params.get('solver') client = docker.from_env() solverPath = os.path.abspath('./solvers')", "os import json from zipfile import ZipFile from django.http import", "id={}\".format(list_id), status=status.HTTP_204_NO_CONTENT) else: return Response(data=\"The category {} does not exist\".format(category),", "Response(data=config, status=status.HTTP_200_OK) def delete(self, request, *args, **kwargs): \"\"\" DELETE the", "**kwargs): \"\"\" save results to media folder. a query will", "streamDockerLog(container, project): for line in container.logs(stream=True): logs = get_object_or_404(DockerLogs, project=project)", "**kwargs): \"\"\" Update the progress from solver \"\"\" project =", "if (SolverResults.objects.filter(project=project).exists()): resutls = SolverResults.objects.filter(project=project).values()[0] folderPath = resutls['path'] # create", "if list_id >= 0 and list_id < len(jsonHelper[category]): # check", "exist\".format(category), status=status.HTTP_204_NO_CONTENT) def post(self, request, *args, **kwargs): \"\"\" create a", "SolverResults.objects.filter(project=project).values()[0] folderPath = resutls['path'] # create a ZipFile object with", "for the entry\", status=400) # if there is no category", "*args, **kwargs): \"\"\" save results to media folder. a query", "to python file command=[\"`sudo pip3 install requests \\n python3 solverHub.py", "the same name exists if not list(filter(lambda name: name[\"Name\"] ==", "put(self, request, filename, format=None, *args, **kwargs): \"\"\" save results to", "logs.save() class solvers(APIView): parser_classes = [FormParser, MultiPartParser] def get(self, request,", "jsonHelper = json.loads(parentConfig.config) if category in jsonHelper: if list_id >=", "\"quay.io/fenicsproject/stable:current\", volumes={solverPath: { 'bind': '/home/fenics/shared', 'mode': 'rw'}}, working_dir=\"/home/fenics/shared\", # runs", "id=kwargs['project_id']) category = request.query_params.get('category') list_id = int(request.query_params.get('id')) parentConfig = AnalysisConfig.objects.get(project=project)", "DockerLogs from rest_framework.parsers import FormParser, JSONParser, MultiPartParser, FileUploadParser from rest_framework", "make sure it has access to the windows docker. Instructions", "Return the existing categories in the solver config \"\"\" project", "parentConfig.save() return Response(data=jsonHelper, status=status.HTTP_410_GONE) else: return Response(data=\"The category {} does", "name[\"Name\"] == data[\"Name\"], jsonHelper[category])): jsonHelper[category].append(data) else: return Response(data=\"an entry with", "id=kwargs['project_id']) config = AnalysisConfig.objects.filter(project=project).values()[0] return Response(data=config[\"config\"], status=status.HTTP_200_OK) def streamDockerLog(container, project):", "docker.from_env() try: container = client.containers.get(\"FEniCSDocker\") container.stop() return Response(data=\"container stopped successfully\",", "**kwargs): \"\"\" Runs the related solver defined in url parameters", "'w') as zipObj: # Iterate over all the files in", "print(message) return Response(data=message, status=500) return Response(data=\"submitted to analysis\", status=status.HTTP_200_OK) def", "Response(data=jsonHelper[category], status=status.HTTP_200_OK) else: return Response(data=\"No entry with the id={}\".format(list_id), status=status.HTTP_204_NO_CONTENT)", "= request.data.dict() # if request does not contain a name", "solver defined in url parameters \"\"\" project = get_object_or_404(projects, id=kwargs['project_id'])", "two arguments to be passed in to python file command=[\"`sudo", "AnalysisConfig, SolverResults, SolverProgress, DockerLogs from rest_framework.parsers import FormParser, JSONParser, MultiPartParser,", "exists elif not list(filter(lambda name: name[\"Name\"] == data[\"Name\"], jsonHelper[category])): jsonHelper[category].append(data)", "stopped successfully\", status=200) except: return Response(data=\"No container running\", status=404) class", "Get the results saved in the database \"\"\" project =", "the files in directory for folderName, subfolders, filenames in os.walk(folderPath):", "= os.path.abspath( \"../FEniCSUI/media/{}/results/\".format(kwargs['project_id'])) os.makedirs(folderPath, exist_ok=True) filePath = '{}/{}.{}'.format(folderPath, filename, fileType)", "status=status.HTTP_201_CREATED) def put(self, request, *args, **kwargs): \"\"\" Edit an existing", "entry with the same name exists\", status=400) parentConfig.config = json.dumps(jsonHelper)", "parentConfig = AnalysisConfig.objects.get(project=project) jsonHelper = json.loads(parentConfig.config) if jsonHelper[category]: if list_id", "{} does not exist\".format(category), status=status.HTTP_204_NO_CONTENT) class Categories(APIView): parser_classes = [FormParser,", "current_time + str(line.strip(), 'utf-8') + \"\\n\" + logs.log logs.save() class", "with the same name exists elif not list(filter(lambda name: name[\"Name\"]", "entry\", status=400) # if there is no category similar to", "return Response(data=json.dumps({\"state\":progress,\"logs\":logs}), status=status.HTTP_200_OK) def post(self, request, *args, **kwargs): \"\"\" Update", "the same name exists\", status=400) parentConfig.config = json.dumps(jsonHelper) parentConfig.save() return", "= request.data.dict() category = request.query_params.get('category') parentConfig = AnalysisConfig.objects.get(project=project) jsonHelper =", "status=status.HTTP_204_NO_CONTENT) class Categories(APIView): parser_classes = [FormParser, MultiPartParser] def get(self, request,", "the same name exists elif not list(filter(lambda name: name[\"Name\"] ==", "progress = \"null\" logs=\"\" return Response(data=json.dumps({\"state\":progress,\"logs\":logs}), status=status.HTTP_200_OK) def post(self, request,", "= json.dumps(data) progress.save() else: SolverProgress.objects.create(project=project, progress=data) return Response(data=get_object_or_404(SolverProgress, project=project).progress, status=status.HTTP_201_CREATED)", "= get_object_or_404(projects, id=kwargs['project_id']) category = request.query_params.get('category') list_id = int(request.query_params.get('id')) parentConfig", "from rest_framework.parsers import FormParser, JSONParser, MultiPartParser, FileUploadParser from rest_framework import", "\"\"\" Return the existing categories in the solver config \"\"\"", "the solver config \"\"\" project = get_object_or_404(projects, id=kwargs['project_id']) config =", "submitted to the analysis \"\"\" project = get_object_or_404(projects, id=kwargs['project_id']) config", "SolverResults.objects.create(project=project, path=folderPath) return Response(data=\"results updated at {}\".format(filePath), status=status.HTTP_201_CREATED) class downloadResults(APIView):", "*args, **kwargs): \"\"\" Runs the related solver defined in url", "id=kwargs['project_id']) if (SolverResults.objects.filter(project=project).exists()): resutls = SolverResults.objects.filter(project=project).values()[0] folderPath = resutls['path'] #", "= AnalysisConfig.objects.get(project=project) jsonHelper = json.loads(parentConfig.config) if jsonHelper[category]: if list_id >=", "and list_id < len(jsonHelper[category]): # check if an entry with", "defaults={'progress' :json.dumps({\"status\": \"\", \"message\": \"\"})}) progress = SolverProgress.objects.get( project=project )", "category = request.query_params.get('category') parentConfig = AnalysisConfig.objects.get(project=project) jsonHelper = json.loads(parentConfig.config) if", "progress = get_object_or_404(SolverProgress, project=project) progress.progress = json.dumps(data) progress.save() else: SolverProgress.objects.create(project=project,", "container = client.containers.get(\"FEniCSDocker\") container.stop() return Response(data=\"container stopped successfully\", status=200) except:", "\"\"\" project = get_object_or_404(projects, id=kwargs['project_id']) if (SolverResults.objects.filter(project=project).exists()): resutls = SolverResults.objects.filter(project=project).values()[0]", "= Thread(target=streamDockerLog, args=(container, project)) thread.start() except: message = '''please check", "Edit an existing category entry's data \"\"\" project = get_object_or_404(projects,", "*args, **kwargs): \"\"\" Return the existing categories in the solver", "if a container with the name FEniCSDocker does not exist.", "contain a name if not \"Name\" in data: return Response(data=\"Please", "in directory for folderName, subfolders, filenames in os.walk(folderPath): for filename", "line in container.logs(stream=True): logs = get_object_or_404(DockerLogs, project=project) now = datetime.now()", "return Response(data=\"The category {} does not exist!\".format(category), status=status.HTTP_404_NOT_FOUND) class getConfiguration(APIView):", "\"\"\" project = get_object_or_404(projects, id=kwargs['project_id']) config = AnalysisConfig.objects.filter(project=project).values()[0] return Response(data=config[\"config\"],", "request, *args, **kwargs): \"\"\" Runs the related solver defined in", "= [FileUploadParser] def put(self, request, filename, format=None, *args, **kwargs): \"\"\"", "else: return Response(data=\"No entry with the id={}\".format(list_id), status=status.HTTP_204_NO_CONTENT) else: return", "command=[\"`sudo pip3 install requests \\n python3 solverHub.py {} {}`\".format( project.id,", "project = get_object_or_404(projects, id=kwargs['project_id']) config = json.loads(AnalysisConfig.objects.get( project=project).config).keys() return Response(data=config,", ">= 0 and list_id < len(jsonHelper[category]): # check if an", "'Name' for the entry\", status=400) category = request.query_params.get('category') list_id =", "request.query_params.get('category') list_id = int(request.query_params.get('id')) parentConfig = AnalysisConfig.objects.get(project=project) jsonHelper = json.loads(parentConfig.config)", "parentConfig.save() return Response(data=jsonHelper[category], status=status.HTTP_200_OK) else: return Response(data=\"No entry with the", "return Response(data=\"an entry with the same name exists\", status=400) else:", "category in jsonHelper: return Response(data=jsonHelper[category], status=status.HTTP_200_OK) else: return Response(data=\"The category", "list(filter(lambda name: name[\"Name\"] == data[\"Name\"], jsonHelper[category])): jsonHelper[category].append(data) else: return Response(data=\"an", "project=project) now = datetime.now() current_time = now.strftime(\"[%H:%M:%S]: \") logs.log =", "passed in to python file command=[\"`sudo pip3 install requests \\n", "parentConfig.config = json.dumps(jsonHelper) parentConfig.save() return Response(data=jsonHelper[category], status=status.HTTP_200_OK) else: return Response(data=\"No", "create a ZipFile object with ZipFile('{}/results.zip'.format(folderPath), 'w') as zipObj: #", "return Response(data=\"No container running\", status=404) class saveResults(APIView): parser_classes = [FileUploadParser]", "delete(self, request, *args, **kwargs): \"\"\" DELETE the existing categories in", "jsonHelper: return Response(data=jsonHelper[category], status=status.HTTP_200_OK) else: return Response(data=\"The category {} does", "thread.start() except: message = '''please check if the docker is", "create a new category for solver configuration \"\"\" project =", "int(request.query_params.get('id')) parentConfig = AnalysisConfig.objects.get(project=project) jsonHelper = json.loads(parentConfig.config) if jsonHelper[category]: if", "get_object_or_404(projects, id=kwargs['project_id']) category = request.query_params.get('category') parentConfig = AnalysisConfig.objects.get(project=project) jsonHelper =", "a name if not \"Name\" in data: return Response(data=\"Please provide", "del jsonHelper[category] parentConfig.config = json.dumps(jsonHelper) parentConfig.save() return Response(data=jsonHelper, status=status.HTTP_410_GONE) else:", "project = get_object_or_404(projects, id=kwargs['project_id']) if (SolverProgress.objects.filter(project=project).exists()): progress = json.loads(get_object_or_404(SolverProgress, project=project).progress)", "from threading import Thread from time import sleep from datetime", "the name FEniCSDocker does not exist. if you are using", "# set progress to initial SolverProgress.objects.get_or_create( project=project, defaults={'progress' :json.dumps({\"status\": \"\",", "json.dumps(jsonHelper) parentConfig.save() return Response(data=jsonHelper[category], status=status.HTTP_200_OK) else: return Response(data=\"an entry with", "Response(data=jsonHelper, status=status.HTTP_410_GONE) else: return Response(data=\"The category {} does not exist!\".format(category),", "project = get_object_or_404(projects, id=kwargs['project_id']) data = request.data.dict() category = request.query_params.get('category')", "jsonHelper = json.loads(parentConfig.config) if category in jsonHelper: return Response(data=jsonHelper[category], status=status.HTTP_200_OK)", "category = request.query_params.get('category') list_id = int(request.query_params.get('id')) parentConfig = AnalysisConfig.objects.get(project=project) jsonHelper", "return Response(data=message, status=500) return Response(data=\"submitted to analysis\", status=status.HTTP_200_OK) def delete(self,", "not \"Name\" in data: return Response(data=\"Please provide a 'Name' for", "= int(request.query_params.get('id')) parentConfig = AnalysisConfig.objects.get(project=project) jsonHelper = json.loads(parentConfig.config) if category", "**kwargs): \"\"\" Return the existing categories in the solver config", "filename, fileType) with open(filePath, 'wb+') as destination: for chunk in", "+ \"\\n\" + logs.log logs.save() class solvers(APIView): parser_classes = [FormParser,", "{ 'bind': '/home/fenics/shared', 'mode': 'rw'}}, working_dir=\"/home/fenics/shared\", # runs solver.py with", "'mode': 'rw'}}, working_dir=\"/home/fenics/shared\", # runs solver.py with two arguments to", "python3 solverHub.py {} {}`\".format( project.id, solver)], name=\"FEniCSDocker\", auto_remove=False, detach=True) thread", "from rest_framework.response import Response from rest_framework.views import APIView from django.shortcuts", "running\", status=404) class saveResults(APIView): parser_classes = [FileUploadParser] def put(self, request,", "status=status.HTTP_404_NOT_FOUND) class getConfiguration(APIView): parser_classes = [FormParser, MultiPartParser] def get(self, request,", "getConfiguration(APIView): parser_classes = [FormParser, MultiPartParser] def get(self, request, *args, **kwargs):", "HttpResponse from threading import Thread from time import sleep from", "rest_framework import status import docker import os import json from", "data.chunks(): destination.write(chunk) if not SolverResults.objects.filter(project=project).exists(): SolverResults.objects.create(project=project, path=folderPath) return Response(data=\"results updated", "\"../FEniCSUI/media/{}/results/\".format(kwargs['project_id'])) os.makedirs(folderPath, exist_ok=True) filePath = '{}/{}.{}'.format(folderPath, filename, fileType) with open(filePath,", "request.data['file'] folderPath = os.path.abspath( \"../FEniCSUI/media/{}/results/\".format(kwargs['project_id'])) os.makedirs(folderPath, exist_ok=True) filePath = '{}/{}.{}'.format(folderPath,", "request if category not in jsonHelper: jsonHelper[category] = [] jsonHelper[category].append(data)", "existing categories in the solver config \"\"\" project = get_object_or_404(projects,", "return Response(data=\"No entry with the id={}\".format(list_id), status=status.HTTP_204_NO_CONTENT) else: return Response(data=\"The", "get(self, request, *args, **kwargs): \"\"\" Get the results saved in", "else: return Response(data=\"The category {} does not exist\".format(category), status=status.HTTP_204_NO_CONTENT) class", "category {} does not exist\".format(category), status=status.HTTP_204_NO_CONTENT) class Categories(APIView): parser_classes =", "in data: return Response(data=\"Please provide a 'Name' for the entry\",", "jsonHelper: jsonHelper[category] = [] jsonHelper[category].append(data) # check if the entry", "id=kwargs['project_id']) data = request.data.dict() category = request.query_params.get('category') parentConfig = AnalysisConfig.objects.get(project=project)", "running docker container \"\"\" client = docker.from_env() try: container =", "parentConfig.config = json.dumps(jsonHelper) parentConfig.save() return Response(data=jsonHelper, status=status.HTTP_410_GONE) else: return Response(data=\"The", "container = client.containers.run( \"quay.io/fenicsproject/stable:current\", volumes={solverPath: { 'bind': '/home/fenics/shared', 'mode': 'rw'}},", "request, *args, **kwargs): \"\"\" return a list of entries within", "main folder directory is on. If you are woking with", "**kwargs): \"\"\" kills the running docker container \"\"\" client =", "to be passed in to python file command=[\"`sudo pip3 install", "with ZipFile('{}/results.zip'.format(folderPath), 'w') as zipObj: # Iterate over all the", "from rest_framework.views import APIView from django.shortcuts import get_object_or_404 from dashboard.models", "rest_framework.parsers import FormParser, JSONParser, MultiPartParser, FileUploadParser from rest_framework import status", "\"\"\" project = get_object_or_404(projects, id=kwargs['project_id']) category = request.query_params.get('category') list_id =", "jsonHelper[category]: if list_id >= 0 and list_id < len(jsonHelper[category]): jsonHelper[category].pop(int(list_id))", "AnalysisConfig.objects.get(project=project) jsonHelper = json.loads(parentConfig.config) if category in jsonHelper: return Response(data=jsonHelper[category],", "destination: for chunk in data.chunks(): destination.write(chunk) if not SolverResults.objects.filter(project=project).exists(): SolverResults.objects.create(project=project,", "**kwargs): \"\"\" Delete an entry from the category \"\"\" project", "\"\"\" project = get_object_or_404(projects, id=kwargs['project_id']) data = request.data.dict() category =", "the progress from solver \"\"\" project = get_object_or_404(projects, id=kwargs['project_id']) data", "category {} does not exist\".format(category), status=status.HTTP_204_NO_CONTENT) def delete(self, request, *args,", "project = get_object_or_404(projects, id=kwargs['project_id']) fileType = request.query_params.get('fileType') data = request.data['file']", "if category in jsonHelper: if list_id >= 0 and list_id", "name exists\", status=400) else: return Response(data=\"No entry with the id={}\".format(list_id),", "= SolverProgress.objects.get( project=project ) progress.progress = json.dumps({\"state\":{\"status\": \"RECEIVED\", \"message\": {\"progress\":", "Response(data=\"The category {} does not exist!\".format(category), status=status.HTTP_404_NOT_FOUND) class getConfiguration(APIView): parser_classes", "# if request does not contain a name if not", "the windows docker. Instructions can be found at: https://nickjanetakis.com/blog/setting-up-docker-for-windows-and-wsl-to-work-flawlessly''' print(message)", "and if a container with the name FEniCSDocker does not", "saveResults(APIView): parser_classes = [FileUploadParser] def put(self, request, filename, format=None, *args,", "{} does not exist\".format(category), status=status.HTTP_204_NO_CONTENT) def delete(self, request, *args, **kwargs):", "return Response(data=\"Please provide a 'Name' for the entry\", status=400) category", "\"\"})}) progress = SolverProgress.objects.get( project=project ) progress.progress = json.dumps({\"state\":{\"status\": \"RECEIVED\",", "= request.data['file'] folderPath = os.path.abspath( \"../FEniCSUI/media/{}/results/\".format(kwargs['project_id'])) os.makedirs(folderPath, exist_ok=True) filePath =", "get_object_or_404(projects, id=kwargs['project_id']) # set progress to initial SolverProgress.objects.get_or_create( project=project, defaults={'progress'", "SolverResults, SolverProgress, DockerLogs from rest_framework.parsers import FormParser, JSONParser, MultiPartParser, FileUploadParser", "sure the file sharing setting for the main folder directory", "request, *args, **kwargs): \"\"\" kills the running docker container \"\"\"", "in to python file command=[\"`sudo pip3 install requests \\n python3", "[] jsonHelper[category].append(data) # check if the entry with the same", "*args, **kwargs): \"\"\" Get the progress \"\"\" project = get_object_or_404(projects,", "WSL, make sure it has access to the windows docker.", "= [JSONParser] def get(self, request, *args, **kwargs): \"\"\" Get the", "project = get_object_or_404(projects, id=kwargs['project_id']) category = request.query_params.get('category') parentConfig = AnalysisConfig.objects.get(project=project)", "progress = SolverProgress.objects.get( project=project ) progress.progress = json.dumps({\"state\":{\"status\": \"RECEIVED\", \"message\":", "data = request.data.dict() category = request.query_params.get('category') parentConfig = AnalysisConfig.objects.get(project=project) jsonHelper", "jsonHelper = json.loads(parentConfig.config) if category in jsonHelper: del jsonHelper[category] parentConfig.config", "parser_classes = [JSONParser] def get(self, request, *args, **kwargs): \"\"\" Get", "request, filename, format=None, *args, **kwargs): \"\"\" save results to media", "SolverResults.objects.filter(project=project).exists(): SolverResults.objects.create(project=project, path=folderPath) return Response(data=\"results updated at {}\".format(filePath), status=status.HTTP_201_CREATED) class", "the running docker container \"\"\" client = docker.from_env() try: container", "= get_object_or_404(projects, id=kwargs['project_id']) if (SolverResults.objects.filter(project=project).exists()): resutls = SolverResults.objects.filter(project=project).values()[0] folderPath =", "jsonHelper[category][list_id] = data parentConfig.config = json.dumps(jsonHelper) parentConfig.save() return Response(data=jsonHelper[category], status=status.HTTP_200_OK)", "'wb+') as destination: for chunk in data.chunks(): destination.write(chunk) if not", "Response(data=\"The category {} does not exist\".format(category), status=status.HTTP_204_NO_CONTENT) def delete(self, request,", "not exist. if you are using docker windows, make sure", "FEniCSDocker does not exist. if you are using docker windows,", "docker is running, and if a container with the name", "current_time = now.strftime(\"[%H:%M:%S]: \") logs.log = current_time + str(line.strip(), 'utf-8')", "not filename == 'results.zip': filePath = os.path.join(folderName, filename) # Add", "== data[\"Name\"], jsonHelper[category])): jsonHelper[category].append(data) else: return Response(data=\"an entry with the", "(SolverResults.objects.filter(project=project).exists()): resutls = SolverResults.objects.filter(project=project).values()[0] folderPath = resutls['path'] # create a", "in the database \"\"\" project = get_object_or_404(projects, id=kwargs['project_id']) if (SolverResults.objects.filter(project=project).exists()):", "import sleep from datetime import datetime class solverConfig(APIView): parser_classes =", "file command=[\"`sudo pip3 install requests \\n python3 solverHub.py {} {}`\".format(", "detach=True) thread = Thread(target=streamDockerLog, args=(container, project)) thread.start() except: message =", "file sharing setting for the main folder directory is on.", "= json.loads(AnalysisConfig.objects.get( project=project).config).keys() return Response(data=config, status=status.HTTP_200_OK) def delete(self, request, *args,", "= json.dumps(jsonHelper) parentConfig.save() return Response(data=jsonHelper[category], status=status.HTTP_200_OK) else: return Response(data=\"an entry", "with the same name exists\", status=400) parentConfig.config = json.dumps(jsonHelper) parentConfig.save()", "an existing category entry's data \"\"\" project = get_object_or_404(projects, id=kwargs['project_id'])", "def get(self, request, *args, **kwargs): \"\"\" Get the solver config", "return Response(data=\"The category {} does not exist\".format(category), status=status.HTTP_204_NO_CONTENT) def delete(self,", "same name exists\", status=400) else: return Response(data=\"No entry with the", "= json.loads(parentConfig.config) if jsonHelper[category]: if list_id >= 0 and list_id", "[FormParser, MultiPartParser] def get(self, request, *args, **kwargs): \"\"\" Runs the", "= AnalysisConfig.objects.get(project=project) jsonHelper = json.loads(parentConfig.config) if category in jsonHelper: return", "list_id >= 0 and list_id < len(jsonHelper[category]): jsonHelper[category].pop(int(list_id)) parentConfig.config =", "project=project ) progress.progress = json.dumps({\"state\":{\"status\": \"RECEIVED\", \"message\": {\"progress\": \"0.0\"}}, \"logs\":\"\"})", "Instructions can be found at: https://nickjanetakis.com/blog/setting-up-docker-for-windows-and-wsl-to-work-flawlessly''' print(message) return Response(data=message, status=500)", "id=kwargs['project_id']) data = request.data.dict() # if request does not contain", "format=None, *args, **kwargs): \"\"\" save results to media folder. a", "there is no category similar to the user request if", "DockerLogs.objects.filter(project=project).exists(): DockerLogs.objects.filter(project=project).delete() DockerLogs.objects.create(project=project,log=\"\") try: container = client.containers.run( \"quay.io/fenicsproject/stable:current\", volumes={solverPath: {", "try: container = client.containers.get(\"FEniCSDocker\") container.stop() return Response(data=\"container stopped successfully\", status=200)", "entry from the category \"\"\" project = get_object_or_404(projects, id=kwargs['project_id']) category", "get_object_or_404(DockerLogs, project=project) now = datetime.now() current_time = now.strftime(\"[%H:%M:%S]: \") logs.log", "project = get_object_or_404(projects, id=kwargs['project_id']) # set progress to initial SolverProgress.objects.get_or_create(", "at {}\".format(filePath), status=status.HTTP_201_CREATED) class downloadResults(APIView): def get(self, request, *args, **kwargs):", "directory for folderName, subfolders, filenames in os.walk(folderPath): for filename in", "Response(data=\"not found\", status=404) class solverProgress(APIView): parser_classes = [JSONParser] def get(self,", "open('{}/results.zip'.format(folderPath), 'rb') response= HttpResponse(zipFile,content_type='application/zip') response['Content-Disposition'] = 'attachment; filename=results.zip' return response", "get_object_or_404(SolverProgress, project=project) progress.progress = json.dumps(data) progress.save() else: SolverProgress.objects.create(project=project, progress=data) return", "try: container = client.containers.run( \"quay.io/fenicsproject/stable:current\", volumes={solverPath: { 'bind': '/home/fenics/shared', 'mode':", "all the files in directory for folderName, subfolders, filenames in", "**kwargs): \"\"\" create a new category for solver configuration \"\"\"", "= get_object_or_404(projects, id=kwargs['project_id']) if (SolverProgress.objects.filter(project=project).exists()): progress = json.loads(get_object_or_404(SolverProgress, project=project).progress) logs", "if (SolverProgress.objects.filter(project=project).exists()): progress = json.loads(get_object_or_404(SolverProgress, project=project).progress) logs = get_object_or_404(DockerLogs, project=project).log", "get_object_or_404(DockerLogs, project=project).log else: progress = \"null\" logs=\"\" return Response(data=json.dumps({\"state\":progress,\"logs\":logs}), status=status.HTTP_200_OK)", "\"\"\" DELETE the existing categories in the solver config \"\"\"", "working_dir=\"/home/fenics/shared\", # runs solver.py with two arguments to be passed", "class solvers(APIView): parser_classes = [FormParser, MultiPartParser] def get(self, request, *args,", "exists\", status=400) else: return Response(data=\"No entry with the id={}\".format(list_id), status=status.HTTP_204_NO_CONTENT)", "django.http import HttpResponse from threading import Thread from time import", "in the solver config \"\"\" project = get_object_or_404(projects, id=kwargs['project_id']) config", "at: https://nickjanetakis.com/blog/setting-up-docker-for-windows-and-wsl-to-work-flawlessly''' print(message) return Response(data=message, status=500) return Response(data=\"submitted to analysis\",", "in the solver config \"\"\" project = get_object_or_404(projects, id=kwargs['project_id']) category", "id=kwargs['project_id']) fileType = request.query_params.get('fileType') data = request.data['file'] folderPath = os.path.abspath(", "Response(data=jsonHelper[category], status=status.HTTP_200_OK) else: return Response(data=\"The category {} does not exist\".format(category),", "folder. a query will be created to make it available", "and list_id < len(jsonHelper[category]): jsonHelper[category].pop(int(list_id)) parentConfig.config = json.dumps(jsonHelper) parentConfig.save() return", "return Response(data=config, status=status.HTTP_200_OK) def delete(self, request, *args, **kwargs): \"\"\" DELETE", "a 'Name' for the entry\", status=400) category = request.query_params.get('category') list_id", "project = get_object_or_404(projects, id=kwargs['project_id']) data = request.data if SolverProgress.objects.filter(project=project).exists(): progress", "exists\", status=400) parentConfig.config = json.dumps(jsonHelper) parentConfig.save() return Response(data=jsonHelper[category], status=status.HTTP_201_CREATED) def", "are woking with WSL, make sure it has access to", "def delete(self, request, *args, **kwargs): \"\"\" Delete an entry from", "category in jsonHelper: if list_id >= 0 and list_id <", "check if the entry with the same name exists elif", "Categories(APIView): parser_classes = [FormParser, MultiPartParser] def get(self, request, *args, **kwargs):", "request, *args, **kwargs): \"\"\" DELETE the existing categories in the", "the solver config to be submitted to the analysis \"\"\"", "json.dumps({\"state\":{\"status\": \"RECEIVED\", \"message\": {\"progress\": \"0.0\"}}, \"logs\":\"\"}) progress.save() # initiate related", "= get_object_or_404(projects, id=kwargs['project_id']) data = request.data.dict() category = request.query_params.get('category') parentConfig", "status=404) class solverProgress(APIView): parser_classes = [JSONParser] def get(self, request, *args,", "json.loads(get_object_or_404(SolverProgress, project=project).progress) logs = get_object_or_404(DockerLogs, project=project).log else: progress = \"null\"", "return a list of entries within a given category \"\"\"", "*args, **kwargs): \"\"\" Edit an existing category entry's data \"\"\"", "jsonHelper[category].append(data) # check if the entry with the same name", "category in jsonHelper: del jsonHelper[category] parentConfig.config = json.dumps(jsonHelper) parentConfig.save() return", "= int(request.query_params.get('id')) parentConfig = AnalysisConfig.objects.get(project=project) jsonHelper = json.loads(parentConfig.config) if jsonHelper[category]:", "= get_object_or_404(projects, id=kwargs['project_id']) data = request.data if SolverProgress.objects.filter(project=project).exists(): progress =", "\"null\" logs=\"\" return Response(data=json.dumps({\"state\":progress,\"logs\":logs}), status=status.HTTP_200_OK) def post(self, request, *args, **kwargs):", "filename, format=None, *args, **kwargs): \"\"\" save results to media folder.", "id=kwargs['project_id']) # set progress to initial SolverProgress.objects.get_or_create( project=project, defaults={'progress' :json.dumps({\"status\":", "def post(self, request, *args, **kwargs): \"\"\" create a new category", "in jsonHelper: del jsonHelper[category] parentConfig.config = json.dumps(jsonHelper) parentConfig.save() return Response(data=jsonHelper,", "class solverProgress(APIView): parser_classes = [JSONParser] def get(self, request, *args, **kwargs):", "AnalysisConfig.objects.get(project=project) jsonHelper = json.loads(parentConfig.config) if category in jsonHelper: if list_id", "project = get_object_or_404(projects, id=kwargs['project_id']) config = AnalysisConfig.objects.filter(project=project).values()[0] return Response(data=config[\"config\"], status=status.HTTP_200_OK)", "*args, **kwargs): \"\"\" create a new category for solver configuration", "or jsonHelper[category][list_id][\"Name\"] == data[\"Name\"]: jsonHelper[category][list_id] = data parentConfig.config = json.dumps(jsonHelper)", "\\n python3 solverHub.py {} {}`\".format( project.id, solver)], name=\"FEniCSDocker\", auto_remove=False, detach=True)", "json from zipfile import ZipFile from django.http import HttpResponse from", "\"\"\" create a new category for solver configuration \"\"\" project", "not contain a name if not \"Name\" in data: return", "\"\"\" project = get_object_or_404(projects, id=kwargs['project_id']) config = json.loads(AnalysisConfig.objects.get( project=project).config).keys() return", "rest_framework.views import APIView from django.shortcuts import get_object_or_404 from dashboard.models import", "Runs the related solver defined in url parameters \"\"\" project", "json.loads(AnalysisConfig.objects.get( project=project).config).keys() return Response(data=config, status=status.HTTP_200_OK) def delete(self, request, *args, **kwargs):", "destination.write(chunk) if not SolverResults.objects.filter(project=project).exists(): SolverResults.objects.create(project=project, path=folderPath) return Response(data=\"results updated at", "same name exists if not list(filter(lambda name: name[\"Name\"] == data[\"Name\"],", "get(self, request, *args, **kwargs): \"\"\" Return the existing categories in", "json.loads(parentConfig.config) if category in jsonHelper: if list_id >= 0 and", "solverProgress(APIView): parser_classes = [JSONParser] def get(self, request, *args, **kwargs): \"\"\"", "docker container \"\"\" client = docker.from_env() try: container = client.containers.get(\"FEniCSDocker\")", "created to make it available for download \"\"\" project =", "= get_object_or_404(projects, id=kwargs['project_id']) category = request.query_params.get('category') parentConfig = AnalysisConfig.objects.get(project=project) jsonHelper", "\"\"\" Runs the related solver defined in url parameters \"\"\"", "# Add file to zip zipObj.write(filePath, os.path.basename(filePath)) zipFile = open('{}/results.zip'.format(folderPath),", "install requests \\n python3 solverHub.py {} {}`\".format( project.id, solver)], name=\"FEniCSDocker\",", "auto_remove=False, detach=True) thread = Thread(target=streamDockerLog, args=(container, project)) thread.start() except: message", "'rw'}}, working_dir=\"/home/fenics/shared\", # runs solver.py with two arguments to be", "to initial SolverProgress.objects.get_or_create( project=project, defaults={'progress' :json.dumps({\"status\": \"\", \"message\": \"\"})}) progress", "os.makedirs(folderPath, exist_ok=True) filePath = '{}/{}.{}'.format(folderPath, filename, fileType) with open(filePath, 'wb+')", "data[\"Name\"], jsonHelper[category])) or jsonHelper[category][list_id][\"Name\"] == data[\"Name\"]: jsonHelper[category][list_id] = data parentConfig.config", "be passed in to python file command=[\"`sudo pip3 install requests", "can be found at: https://nickjanetakis.com/blog/setting-up-docker-for-windows-and-wsl-to-work-flawlessly''' print(message) return Response(data=message, status=500) return", "entry's data \"\"\" project = get_object_or_404(projects, id=kwargs['project_id']) data = request.data.dict()", "directory is on. If you are woking with WSL, make", "return Response(data=\"results updated at {}\".format(filePath), status=status.HTTP_201_CREATED) class downloadResults(APIView): def get(self,", "DockerLogs.objects.create(project=project,log=\"\") try: container = client.containers.run( \"quay.io/fenicsproject/stable:current\", volumes={solverPath: { 'bind': '/home/fenics/shared',", "you are woking with WSL, make sure it has access", "Update the progress from solver \"\"\" project = get_object_or_404(projects, id=kwargs['project_id'])", "name if not \"Name\" in data: return Response(data=\"Please provide a", "*args, **kwargs): \"\"\" Update the progress from solver \"\"\" project", "Response(data=\"an entry with the same name exists\", status=400) parentConfig.config =", "\"0.0\"}}, \"logs\":\"\"}) progress.save() # initiate related solver solver = request.query_params.get('solver')", "existing category entry's data \"\"\" project = get_object_or_404(projects, id=kwargs['project_id']) data", "Response(data=config[\"config\"], status=status.HTTP_200_OK) def streamDockerLog(container, project): for line in container.logs(stream=True): logs", "response= HttpResponse(zipFile,content_type='application/zip') response['Content-Disposition'] = 'attachment; filename=results.zip' return response else: return", "config = AnalysisConfig.objects.filter(project=project).values()[0] return Response(data=config[\"config\"], status=status.HTTP_200_OK) def streamDockerLog(container, project): for", "= [] jsonHelper[category].append(data) # check if the entry with the", "def get(self, request, *args, **kwargs): \"\"\" Return the existing categories", "if the docker is running, and if a container with", "import datetime class solverConfig(APIView): parser_classes = [FormParser, MultiPartParser] def get(self,", "SolverProgress.objects.get( project=project ) progress.progress = json.dumps({\"state\":{\"status\": \"RECEIVED\", \"message\": {\"progress\": \"0.0\"}},", "has access to the windows docker. Instructions can be found", "os.walk(folderPath): for filename in filenames: if not filename == 'results.zip':", "\"\"\" save results to media folder. a query will be", "given category \"\"\" project = get_object_or_404(projects, id=kwargs['project_id']) category = request.query_params.get('category')", "elif not list(filter(lambda name: name[\"Name\"] == data[\"Name\"], jsonHelper[category])): jsonHelper[category].append(data) else:", "\"\"\" Update the progress from solver \"\"\" project = get_object_or_404(projects,", "= [FormParser, MultiPartParser] def get(self, request, *args, **kwargs): \"\"\" Get", "with two arguments to be passed in to python file", "post(self, request, *args, **kwargs): \"\"\" create a new category for", "'Name' for the entry\", status=400) # if there is no", "entry with the same name exists elif not list(filter(lambda name:", "*args, **kwargs): \"\"\" Delete an entry from the category \"\"\"", "# check if an entry with the same name exists", "list_id < len(jsonHelper[category]): jsonHelper[category].pop(int(list_id)) parentConfig.config = json.dumps(jsonHelper) parentConfig.save() return Response(data=jsonHelper[category],", "def delete(self, request, *args, **kwargs): \"\"\" DELETE the existing categories", "data = request.data['file'] folderPath = os.path.abspath( \"../FEniCSUI/media/{}/results/\".format(kwargs['project_id'])) os.makedirs(folderPath, exist_ok=True) filePath", "path=folderPath) return Response(data=\"results updated at {}\".format(filePath), status=status.HTTP_201_CREATED) class downloadResults(APIView): def", "in os.walk(folderPath): for filename in filenames: if not filename ==", "request, *args, **kwargs): \"\"\" Delete an entry from the category", "the results saved in the database \"\"\" project = get_object_or_404(projects,", "config \"\"\" project = get_object_or_404(projects, id=kwargs['project_id']) config = json.loads(AnalysisConfig.objects.get( project=project).config).keys()", "parser_classes = [FileUploadParser] def put(self, request, filename, format=None, *args, **kwargs):", "zipObj.write(filePath, os.path.basename(filePath)) zipFile = open('{}/results.zip'.format(folderPath), 'rb') response= HttpResponse(zipFile,content_type='application/zip') response['Content-Disposition'] =", "json.dumps(jsonHelper) parentConfig.save() return Response(data=jsonHelper, status=status.HTTP_410_GONE) else: return Response(data=\"The category {}", "arguments to be passed in to python file command=[\"`sudo pip3", "docker. Instructions can be found at: https://nickjanetakis.com/blog/setting-up-docker-for-windows-and-wsl-to-work-flawlessly''' print(message) return Response(data=message,", "*args, **kwargs): \"\"\" Get the results saved in the database", "json.loads(parentConfig.config) if category in jsonHelper: del jsonHelper[category] parentConfig.config = json.dumps(jsonHelper)", ".models import AnalysisConfig, SolverResults, SolverProgress, DockerLogs from rest_framework.parsers import FormParser,", "configuration \"\"\" project = get_object_or_404(projects, id=kwargs['project_id']) data = request.data.dict() category", "\"\"\" project = get_object_or_404(projects, id=kwargs['project_id']) data = request.data.dict() # if", "from django.http import HttpResponse from threading import Thread from time", "solver configuration \"\"\" project = get_object_or_404(projects, id=kwargs['project_id']) data = request.data.dict()", "# Iterate over all the files in directory for folderName,", "DockerLogs.objects.filter(project=project).delete() DockerLogs.objects.create(project=project,log=\"\") try: container = client.containers.run( \"quay.io/fenicsproject/stable:current\", volumes={solverPath: { 'bind':", "'results.zip': filePath = os.path.join(folderName, filename) # Add file to zip", "= now.strftime(\"[%H:%M:%S]: \") logs.log = current_time + str(line.strip(), 'utf-8') +", "jsonHelper[category][list_id][\"Name\"] == data[\"Name\"]: jsonHelper[category][list_id] = data parentConfig.config = json.dumps(jsonHelper) parentConfig.save()", "requests \\n python3 solverHub.py {} {}`\".format( project.id, solver)], name=\"FEniCSDocker\", auto_remove=False,", "not list(filter(lambda name: name[\"Name\"] == data[\"Name\"], jsonHelper[category])): jsonHelper[category].append(data) else: return", "request.query_params.get('category') parentConfig = AnalysisConfig.objects.get(project=project) jsonHelper = json.loads(parentConfig.config) if category in", "with open(filePath, 'wb+') as destination: for chunk in data.chunks(): destination.write(chunk)", "Response(data=\"The category {} does not exist\".format(category), status=status.HTTP_204_NO_CONTENT) class Categories(APIView): parser_classes", "else: return Response(data=\"an entry with the same name exists\", status=400)", "= data parentConfig.config = json.dumps(jsonHelper) parentConfig.save() return Response(data=jsonHelper[category], status=status.HTTP_200_OK) else:", "import docker import os import json from zipfile import ZipFile", "it available for download \"\"\" project = get_object_or_404(projects, id=kwargs['project_id']) fileType", "\"\"\" Get the results saved in the database \"\"\" project", "data[\"Name\"], jsonHelper[category])): jsonHelper[category].append(data) else: return Response(data=\"an entry with the same", "id=kwargs['project_id']) category = request.query_params.get('category') parentConfig = AnalysisConfig.objects.get(project=project) jsonHelper = json.loads(parentConfig.config)", "= docker.from_env() solverPath = os.path.abspath('./solvers') if DockerLogs.objects.filter(project=project).exists(): DockerLogs.objects.filter(project=project).delete() DockerLogs.objects.create(project=project,log=\"\") try:", "name FEniCSDocker does not exist. if you are using docker", "status=400) # if there is no category similar to the", "{} does not exist\".format(category), status=status.HTTP_204_NO_CONTENT) def post(self, request, *args, **kwargs):", "make sure the file sharing setting for the main folder", "defined in url parameters \"\"\" project = get_object_or_404(projects, id=kwargs['project_id']) #", "a query will be created to make it available for", "zipfile import ZipFile from django.http import HttpResponse from threading import", "if not list(filter(lambda name: name[\"Name\"] == data[\"Name\"], jsonHelper[category])) or jsonHelper[category][list_id][\"Name\"]", "'rb') response= HttpResponse(zipFile,content_type='application/zip') response['Content-Disposition'] = 'attachment; filename=results.zip' return response else:", "in filenames: if not filename == 'results.zip': filePath = os.path.join(folderName,", "class solverConfig(APIView): parser_classes = [FormParser, MultiPartParser] def get(self, request, *args,", "datetime class solverConfig(APIView): parser_classes = [FormParser, MultiPartParser] def get(self, request,", "# initiate related solver solver = request.query_params.get('solver') client = docker.from_env()", "from rest_framework import status import docker import os import json", "related solver solver = request.query_params.get('solver') client = docker.from_env() solverPath =", "status=500) return Response(data=\"submitted to analysis\", status=status.HTTP_200_OK) def delete(self, request, *args,", "status=400) else: return Response(data=\"No entry with the id={}\".format(list_id), status=status.HTTP_204_NO_CONTENT) else:", "a list of entries within a given category \"\"\" project", "return Response(data=jsonHelper[category], status=status.HTTP_200_OK) else: return Response(data=\"The category {} does not", "not in jsonHelper: jsonHelper[category] = [] jsonHelper[category].append(data) # check if", "return Response(data=jsonHelper[category], status=status.HTTP_201_CREATED) def put(self, request, *args, **kwargs): \"\"\" Edit", "to the windows docker. Instructions can be found at: https://nickjanetakis.com/blog/setting-up-docker-for-windows-and-wsl-to-work-flawlessly'''", "the user request if category not in jsonHelper: jsonHelper[category] =", "import ZipFile from django.http import HttpResponse from threading import Thread", "config = json.loads(AnalysisConfig.objects.get( project=project).config).keys() return Response(data=config, status=status.HTTP_200_OK) def delete(self, request,", "{\"progress\": \"0.0\"}}, \"logs\":\"\"}) progress.save() # initiate related solver solver =", "you are using docker windows, make sure the file sharing", "def post(self, request, *args, **kwargs): \"\"\" Update the progress from", "if SolverProgress.objects.filter(project=project).exists(): progress = get_object_or_404(SolverProgress, project=project) progress.progress = json.dumps(data) progress.save()", "MultiPartParser] def get(self, request, *args, **kwargs): \"\"\" Runs the related", "does not exist. if you are using docker windows, make", "the file sharing setting for the main folder directory is", "results saved in the database \"\"\" project = get_object_or_404(projects, id=kwargs['project_id'])", "not exist!\".format(category), status=status.HTTP_404_NOT_FOUND) class getConfiguration(APIView): parser_classes = [FormParser, MultiPartParser] def", "to the analysis \"\"\" project = get_object_or_404(projects, id=kwargs['project_id']) config =", "# runs solver.py with two arguments to be passed in", "progress to initial SolverProgress.objects.get_or_create( project=project, defaults={'progress' :json.dumps({\"status\": \"\", \"message\": \"\"})})", "the existing categories in the solver config \"\"\" project =", "import json from zipfile import ZipFile from django.http import HttpResponse", "are using docker windows, make sure the file sharing setting", "folder directory is on. If you are woking with WSL,", "for download \"\"\" project = get_object_or_404(projects, id=kwargs['project_id']) fileType = request.query_params.get('fileType')", "import get_object_or_404 from dashboard.models import projects from .models import AnalysisConfig,", "does not contain a name if not \"Name\" in data:", "\") logs.log = current_time + str(line.strip(), 'utf-8') + \"\\n\" +", "same name exists elif not list(filter(lambda name: name[\"Name\"] == data[\"Name\"],", "fileType = request.query_params.get('fileType') data = request.data['file'] folderPath = os.path.abspath( \"../FEniCSUI/media/{}/results/\".format(kwargs['project_id']))", "as destination: for chunk in data.chunks(): destination.write(chunk) if not SolverResults.objects.filter(project=project).exists():", "= json.dumps(jsonHelper) parentConfig.save() return Response(data=jsonHelper, status=status.HTTP_410_GONE) else: return Response(data=\"The category", "if an entry with the same name exists if not", "project=project).config).keys() return Response(data=config, status=status.HTTP_200_OK) def delete(self, request, *args, **kwargs): \"\"\"", "windows docker. Instructions can be found at: https://nickjanetakis.com/blog/setting-up-docker-for-windows-and-wsl-to-work-flawlessly''' print(message) return", "kills the running docker container \"\"\" client = docker.from_env() try:", "(SolverProgress.objects.filter(project=project).exists()): progress = json.loads(get_object_or_404(SolverProgress, project=project).progress) logs = get_object_or_404(DockerLogs, project=project).log else:", "client = docker.from_env() solverPath = os.path.abspath('./solvers') if DockerLogs.objects.filter(project=project).exists(): DockerLogs.objects.filter(project=project).delete() DockerLogs.objects.create(project=project,log=\"\")", "https://nickjanetakis.com/blog/setting-up-docker-for-windows-and-wsl-to-work-flawlessly''' print(message) return Response(data=message, status=500) return Response(data=\"submitted to analysis\", status=status.HTTP_200_OK)", "to be submitted to the analysis \"\"\" project = get_object_or_404(projects,", "chunk in data.chunks(): destination.write(chunk) if not SolverResults.objects.filter(project=project).exists(): SolverResults.objects.create(project=project, path=folderPath) return", "data = request.data if SolverProgress.objects.filter(project=project).exists(): progress = get_object_or_404(SolverProgress, project=project) progress.progress", "def put(self, request, *args, **kwargs): \"\"\" Edit an existing category", "= request.data if SolverProgress.objects.filter(project=project).exists(): progress = get_object_or_404(SolverProgress, project=project) progress.progress =", "category {} does not exist\".format(category), status=status.HTTP_204_NO_CONTENT) def post(self, request, *args,", "be created to make it available for download \"\"\" project", "related solver defined in url parameters \"\"\" project = get_object_or_404(projects,", "make it available for download \"\"\" project = get_object_or_404(projects, id=kwargs['project_id'])", "a ZipFile object with ZipFile('{}/results.zip'.format(folderPath), 'w') as zipObj: # Iterate", "time import sleep from datetime import datetime class solverConfig(APIView): parser_classes", "== 'results.zip': filePath = os.path.join(folderName, filename) # Add file to", "**kwargs): \"\"\" Get the results saved in the database \"\"\"", "status=status.HTTP_200_OK) else: return Response(data=\"No entry with the id={}\".format(list_id), status=status.HTTP_204_NO_CONTENT) else:", "\"\"\" project = get_object_or_404(projects, id=kwargs['project_id']) # set progress to initial", "json.loads(parentConfig.config) if jsonHelper[category]: if list_id >= 0 and list_id <", "if category in jsonHelper: return Response(data=jsonHelper[category], status=status.HTTP_200_OK) else: return Response(data=\"The", "progress from solver \"\"\" project = get_object_or_404(projects, id=kwargs['project_id']) data =", "project = get_object_or_404(projects, id=kwargs['project_id']) category = request.query_params.get('category') list_id = int(request.query_params.get('id'))", "windows, make sure the file sharing setting for the main", "solverConfig(APIView): parser_classes = [FormParser, MultiPartParser] def get(self, request, *args, **kwargs):", "if there is no category similar to the user request", "logs.log = current_time + str(line.strip(), 'utf-8') + \"\\n\" + logs.log", "found at: https://nickjanetakis.com/blog/setting-up-docker-for-windows-and-wsl-to-work-flawlessly''' print(message) return Response(data=message, status=500) return Response(data=\"submitted to", "status=status.HTTP_200_OK) else: return Response(data=\"an entry with the same name exists\",", "for filename in filenames: if not filename == 'results.zip': filePath", "request.data if SolverProgress.objects.filter(project=project).exists(): progress = get_object_or_404(SolverProgress, project=project) progress.progress = json.dumps(data)", "Get the solver config to be submitted to the analysis", "post(self, request, *args, **kwargs): \"\"\" Update the progress from solver", "categories in the solver config \"\"\" project = get_object_or_404(projects, id=kwargs['project_id'])", "[FormParser, MultiPartParser] def get(self, request, *args, **kwargs): \"\"\" Return the", "provide a 'Name' for the entry\", status=400) category = request.query_params.get('category')", "get_object_or_404(projects, id=kwargs['project_id']) data = request.data if SolverProgress.objects.filter(project=project).exists(): progress = get_object_or_404(SolverProgress,", "jsonHelper[category].pop(int(list_id)) parentConfig.config = json.dumps(jsonHelper) parentConfig.save() return Response(data=jsonHelper[category], status=status.HTTP_200_OK) else: return", "Add file to zip zipObj.write(filePath, os.path.basename(filePath)) zipFile = open('{}/results.zip'.format(folderPath), 'rb')", "does not exist\".format(category), status=status.HTTP_204_NO_CONTENT) def delete(self, request, *args, **kwargs): \"\"\"", "= json.loads(parentConfig.config) if category in jsonHelper: del jsonHelper[category] parentConfig.config =", "filename == 'results.zip': filePath = os.path.join(folderName, filename) # Add file", "sure it has access to the windows docker. Instructions can", "with the name FEniCSDocker does not exist. if you are", "parameters \"\"\" project = get_object_or_404(projects, id=kwargs['project_id']) # set progress to", "parentConfig = AnalysisConfig.objects.get(project=project) jsonHelper = json.loads(parentConfig.config) # if request does", "= get_object_or_404(projects, id=kwargs['project_id']) data = request.data.dict() # if request does", "import HttpResponse from threading import Thread from time import sleep", "if you are using docker windows, make sure the file", "python file command=[\"`sudo pip3 install requests \\n python3 solverHub.py {}", "does not exist\".format(category), status=status.HTTP_204_NO_CONTENT) def post(self, request, *args, **kwargs): \"\"\"", "progress = json.loads(get_object_or_404(SolverProgress, project=project).progress) logs = get_object_or_404(DockerLogs, project=project).log else: progress", "project=project, defaults={'progress' :json.dumps({\"status\": \"\", \"message\": \"\"})}) progress = SolverProgress.objects.get( project=project", "= json.dumps(jsonHelper) parentConfig.save() return Response(data=jsonHelper[category], status=status.HTTP_200_OK) else: return Response(data=\"No entry", "return Response(data=\"container stopped successfully\", status=200) except: return Response(data=\"No container running\",", "response['Content-Disposition'] = 'attachment; filename=results.zip' return response else: return Response(data=\"not found\",", "woking with WSL, make sure it has access to the", "{}\".format(filePath), status=status.HTTP_201_CREATED) class downloadResults(APIView): def get(self, request, *args, **kwargs): \"\"\"", "**kwargs): \"\"\" Get the solver config to be submitted to", "from the category \"\"\" project = get_object_or_404(projects, id=kwargs['project_id']) category =", "sleep from datetime import datetime class solverConfig(APIView): parser_classes = [FormParser,", "request.data.dict() category = request.query_params.get('category') parentConfig = AnalysisConfig.objects.get(project=project) jsonHelper = json.loads(parentConfig.config)", "request, *args, **kwargs): \"\"\" Get the solver config to be", "volumes={solverPath: { 'bind': '/home/fenics/shared', 'mode': 'rw'}}, working_dir=\"/home/fenics/shared\", # runs solver.py", "'attachment; filename=results.zip' return response else: return Response(data=\"not found\", status=404) class", "name exists\", status=400) parentConfig.config = json.dumps(jsonHelper) parentConfig.save() return Response(data=jsonHelper[category], status=status.HTTP_201_CREATED)", "name: name[\"Name\"] == data[\"Name\"], jsonHelper[category])) or jsonHelper[category][list_id][\"Name\"] == data[\"Name\"]: jsonHelper[category][list_id]", "from .models import AnalysisConfig, SolverResults, SolverProgress, DockerLogs from rest_framework.parsers import", "json.dumps(jsonHelper) parentConfig.save() return Response(data=jsonHelper[category], status=status.HTTP_201_CREATED) def put(self, request, *args, **kwargs):", "Response(data=\"No entry with the id={}\".format(list_id), status=status.HTTP_204_NO_CONTENT) else: return Response(data=\"The category", "\"message\": {\"progress\": \"0.0\"}}, \"logs\":\"\"}) progress.save() # initiate related solver solver", "running, and if a container with the name FEniCSDocker does", "Iterate over all the files in directory for folderName, subfolders,", "AnalysisConfig.objects.filter(project=project).values()[0] return Response(data=config[\"config\"], status=status.HTTP_200_OK) def streamDockerLog(container, project): for line in", "status=status.HTTP_200_OK) def delete(self, request, *args, **kwargs): \"\"\" DELETE the existing", "status import docker import os import json from zipfile import", "rest_framework.response import Response from rest_framework.views import APIView from django.shortcuts import", "from django.shortcuts import get_object_or_404 from dashboard.models import projects from .models", "class getConfiguration(APIView): parser_classes = [FormParser, MultiPartParser] def get(self, request, *args,", "list_id < len(jsonHelper[category]): # check if an entry with the", "== data[\"Name\"], jsonHelper[category])) or jsonHelper[category][list_id][\"Name\"] == data[\"Name\"]: jsonHelper[category][list_id] = data", "progress \"\"\" project = get_object_or_404(projects, id=kwargs['project_id']) if (SolverProgress.objects.filter(project=project).exists()): progress =", "does not exist!\".format(category), status=status.HTTP_404_NOT_FOUND) class getConfiguration(APIView): parser_classes = [FormParser, MultiPartParser]", "analysis\", status=status.HTTP_200_OK) def delete(self, request, *args, **kwargs): \"\"\" kills the", "= json.dumps(jsonHelper) parentConfig.save() return Response(data=jsonHelper[category], status=status.HTTP_201_CREATED) def put(self, request, *args,", "= json.loads(parentConfig.config) if category in jsonHelper: if list_id >= 0", "list of entries within a given category \"\"\" project =", "not SolverResults.objects.filter(project=project).exists(): SolverResults.objects.create(project=project, path=folderPath) return Response(data=\"results updated at {}\".format(filePath), status=status.HTTP_201_CREATED)", "os.path.basename(filePath)) zipFile = open('{}/results.zip'.format(folderPath), 'rb') response= HttpResponse(zipFile,content_type='application/zip') response['Content-Disposition'] = 'attachment;", "name exists elif not list(filter(lambda name: name[\"Name\"] == data[\"Name\"], jsonHelper[category])):", "DELETE the existing categories in the solver config \"\"\" project", "request.query_params.get('fileType') data = request.data['file'] folderPath = os.path.abspath( \"../FEniCSUI/media/{}/results/\".format(kwargs['project_id'])) os.makedirs(folderPath, exist_ok=True)", "0 and list_id < len(jsonHelper[category]): # check if an entry", "def get(self, request, *args, **kwargs): \"\"\" return a list of", "be found at: https://nickjanetakis.com/blog/setting-up-docker-for-windows-and-wsl-to-work-flawlessly''' print(message) return Response(data=message, status=500) return Response(data=\"submitted", "'utf-8') + \"\\n\" + logs.log logs.save() class solvers(APIView): parser_classes =", "pip3 install requests \\n python3 solverHub.py {} {}`\".format( project.id, solver)],", "logs=\"\" return Response(data=json.dumps({\"state\":progress,\"logs\":logs}), status=status.HTTP_200_OK) def post(self, request, *args, **kwargs): \"\"\"", "runs solver.py with two arguments to be passed in to", "= get_object_or_404(projects, id=kwargs['project_id']) fileType = request.query_params.get('fileType') data = request.data['file'] folderPath", "{} does not exist!\".format(category), status=status.HTTP_404_NOT_FOUND) class getConfiguration(APIView): parser_classes = [FormParser,", "using docker windows, make sure the file sharing setting for", "+ logs.log logs.save() class solvers(APIView): parser_classes = [FormParser, MultiPartParser] def", "delete(self, request, *args, **kwargs): \"\"\" Delete an entry from the", "[JSONParser] def get(self, request, *args, **kwargs): \"\"\" Get the progress", "solver.py with two arguments to be passed in to python", "if request does not contain a name if not \"Name\"", "# check if the entry with the same name exists", "solver config \"\"\" project = get_object_or_404(projects, id=kwargs['project_id']) config = json.loads(AnalysisConfig.objects.get(", "container running\", status=404) class saveResults(APIView): parser_classes = [FileUploadParser] def put(self,", "from zipfile import ZipFile from django.http import HttpResponse from threading", "analysis \"\"\" project = get_object_or_404(projects, id=kwargs['project_id']) config = AnalysisConfig.objects.filter(project=project).values()[0] return", "= [FormParser, MultiPartParser] def get(self, request, *args, **kwargs): \"\"\" Return", "return Response(data=jsonHelper[category], status=status.HTTP_200_OK) else: return Response(data=\"No entry with the id={}\".format(list_id),", "\"\"\" Edit an existing category entry's data \"\"\" project =", "the same name exists\", status=400) else: return Response(data=\"No entry with", "*args, **kwargs): \"\"\" return a list of entries within a", "not list(filter(lambda name: name[\"Name\"] == data[\"Name\"], jsonHelper[category])) or jsonHelper[category][list_id][\"Name\"] ==", "status=status.HTTP_200_OK) else: return Response(data=\"The category {} does not exist\".format(category), status=status.HTTP_204_NO_CONTENT)", "on. If you are woking with WSL, make sure it", "save results to media folder. a query will be created", "initial SolverProgress.objects.get_or_create( project=project, defaults={'progress' :json.dumps({\"status\": \"\", \"message\": \"\"})}) progress =", "in jsonHelper: jsonHelper[category] = [] jsonHelper[category].append(data) # check if the", "Thread(target=streamDockerLog, args=(container, project)) thread.start() except: message = '''please check if", "data: return Response(data=\"Please provide a 'Name' for the entry\", status=400)", "[FileUploadParser] def put(self, request, filename, format=None, *args, **kwargs): \"\"\" save", "be submitted to the analysis \"\"\" project = get_object_or_404(projects, id=kwargs['project_id'])", "in jsonHelper: if list_id >= 0 and list_id < len(jsonHelper[category]):", "Response(data=\"an entry with the same name exists\", status=400) else: return", "for line in container.logs(stream=True): logs = get_object_or_404(DockerLogs, project=project) now =", "user request if category not in jsonHelper: jsonHelper[category] = []", "return Response(data=\"an entry with the same name exists\", status=400) parentConfig.config", "= AnalysisConfig.objects.filter(project=project).values()[0] return Response(data=config[\"config\"], status=status.HTTP_200_OK) def streamDockerLog(container, project): for line", "exist. if you are using docker windows, make sure the", "\"\"\" client = docker.from_env() try: container = client.containers.get(\"FEniCSDocker\") container.stop() return", "solver config \"\"\" project = get_object_or_404(projects, id=kwargs['project_id']) category = request.query_params.get('category')", "class saveResults(APIView): parser_classes = [FileUploadParser] def put(self, request, filename, format=None,", "jsonHelper = json.loads(parentConfig.config) if jsonHelper[category]: if list_id >= 0 and", "request.query_params.get('category') parentConfig = AnalysisConfig.objects.get(project=project) jsonHelper = json.loads(parentConfig.config) # if request", "zipFile = open('{}/results.zip'.format(folderPath), 'rb') response= HttpResponse(zipFile,content_type='application/zip') response['Content-Disposition'] = 'attachment; filename=results.zip'", "if not SolverResults.objects.filter(project=project).exists(): SolverResults.objects.create(project=project, path=folderPath) return Response(data=\"results updated at {}\".format(filePath),", "updated at {}\".format(filePath), status=status.HTTP_201_CREATED) class downloadResults(APIView): def get(self, request, *args,", "def get(self, request, *args, **kwargs): \"\"\" Get the progress \"\"\"", "for solver configuration \"\"\" project = get_object_or_404(projects, id=kwargs['project_id']) data =", "jsonHelper = json.loads(parentConfig.config) # if request does not contain a", "parentConfig.save() return Response(data=jsonHelper[category], status=status.HTTP_201_CREATED) def put(self, request, *args, **kwargs): \"\"\"", "If you are woking with WSL, make sure it has", "it has access to the windows docker. Instructions can be", "Response(data=\"The category {} does not exist\".format(category), status=status.HTTP_204_NO_CONTENT) def post(self, request,", "the analysis \"\"\" project = get_object_or_404(projects, id=kwargs['project_id']) config = AnalysisConfig.objects.filter(project=project).values()[0]", "'{}/{}.{}'.format(folderPath, filename, fileType) with open(filePath, 'wb+') as destination: for chunk", "status=status.HTTP_201_CREATED) class downloadResults(APIView): def get(self, request, *args, **kwargs): \"\"\" Get", "\"logs\":\"\"}) progress.save() # initiate related solver solver = request.query_params.get('solver') client", "progress.save() # initiate related solver solver = request.query_params.get('solver') client =", "get_object_or_404(projects, id=kwargs['project_id']) config = json.loads(AnalysisConfig.objects.get( project=project).config).keys() return Response(data=config, status=status.HTTP_200_OK) def", "url parameters \"\"\" project = get_object_or_404(projects, id=kwargs['project_id']) # set progress", "\"message\": \"\"})}) progress = SolverProgress.objects.get( project=project ) progress.progress = json.dumps({\"state\":{\"status\":", "filename=results.zip' return response else: return Response(data=\"not found\", status=404) class solverProgress(APIView):", "for chunk in data.chunks(): destination.write(chunk) if not SolverResults.objects.filter(project=project).exists(): SolverResults.objects.create(project=project, path=folderPath)", "docker.from_env() solverPath = os.path.abspath('./solvers') if DockerLogs.objects.filter(project=project).exists(): DockerLogs.objects.filter(project=project).delete() DockerLogs.objects.create(project=project,log=\"\") try: container", "category \"\"\" project = get_object_or_404(projects, id=kwargs['project_id']) category = request.query_params.get('category') parentConfig", "+ str(line.strip(), 'utf-8') + \"\\n\" + logs.log logs.save() class solvers(APIView):", "docker import os import json from zipfile import ZipFile from", "name=\"FEniCSDocker\", auto_remove=False, detach=True) thread = Thread(target=streamDockerLog, args=(container, project)) thread.start() except:", "\"\"\" Delete an entry from the category \"\"\" project =", "subfolders, filenames in os.walk(folderPath): for filename in filenames: if not", "the progress \"\"\" project = get_object_or_404(projects, id=kwargs['project_id']) if (SolverProgress.objects.filter(project=project).exists()): progress", "Response(data=\"No container running\", status=404) class saveResults(APIView): parser_classes = [FileUploadParser] def", "len(jsonHelper[category]): # check if an entry with the same name", "= datetime.now() current_time = now.strftime(\"[%H:%M:%S]: \") logs.log = current_time +", "with the same name exists\", status=400) else: return Response(data=\"No entry", "filenames in os.walk(folderPath): for filename in filenames: if not filename", "= get_object_or_404(projects, id=kwargs['project_id']) # set progress to initial SolverProgress.objects.get_or_create( project=project,", "from time import sleep from datetime import datetime class solverConfig(APIView):", "**kwargs): \"\"\" Edit an existing category entry's data \"\"\" project", "except: return Response(data=\"No container running\", status=404) class saveResults(APIView): parser_classes =", "<filename>FEniCSUI/AnalysesHub/views.py from rest_framework.response import Response from rest_framework.views import APIView from", "return Response(data=\"Please provide a 'Name' for the entry\", status=400) #", "os.path.join(folderName, filename) # Add file to zip zipObj.write(filePath, os.path.basename(filePath)) zipFile", "the docker is running, and if a container with the", "Response(data=\"Please provide a 'Name' for the entry\", status=400) category =", "0 and list_id < len(jsonHelper[category]): jsonHelper[category].pop(int(list_id)) parentConfig.config = json.dumps(jsonHelper) parentConfig.save()", "thread = Thread(target=streamDockerLog, args=(container, project)) thread.start() except: message = '''please", "client = docker.from_env() try: container = client.containers.get(\"FEniCSDocker\") container.stop() return Response(data=\"container", "jsonHelper[category] = [] jsonHelper[category].append(data) # check if the entry with", "resutls['path'] # create a ZipFile object with ZipFile('{}/results.zip'.format(folderPath), 'w') as", "else: return Response(data=\"The category {} does not exist!\".format(category), status=status.HTTP_404_NOT_FOUND) class", "progress.progress = json.dumps({\"state\":{\"status\": \"RECEIVED\", \"message\": {\"progress\": \"0.0\"}}, \"logs\":\"\"}) progress.save() #", "jsonHelper[category] parentConfig.config = json.dumps(jsonHelper) parentConfig.save() return Response(data=jsonHelper, status=status.HTTP_410_GONE) else: return", "SolverProgress.objects.filter(project=project).exists(): progress = get_object_or_404(SolverProgress, project=project) progress.progress = json.dumps(data) progress.save() else:", "project=project) progress.progress = json.dumps(data) progress.save() else: SolverProgress.objects.create(project=project, progress=data) return Response(data=get_object_or_404(SolverProgress,", "class Categories(APIView): parser_classes = [FormParser, MultiPartParser] def get(self, request, *args,", "successfully\", status=200) except: return Response(data=\"No container running\", status=404) class saveResults(APIView):", "a 'Name' for the entry\", status=400) # if there is", "Get the progress \"\"\" project = get_object_or_404(projects, id=kwargs['project_id']) if (SolverProgress.objects.filter(project=project).exists()):", "= [FormParser, MultiPartParser] def get(self, request, *args, **kwargs): \"\"\" return", "in jsonHelper: return Response(data=jsonHelper[category], status=status.HTTP_200_OK) else: return Response(data=\"The category {}", "the database \"\"\" project = get_object_or_404(projects, id=kwargs['project_id']) if (SolverResults.objects.filter(project=project).exists()): resutls", "project.id, solver)], name=\"FEniCSDocker\", auto_remove=False, detach=True) thread = Thread(target=streamDockerLog, args=(container, project))", "container \"\"\" client = docker.from_env() try: container = client.containers.get(\"FEniCSDocker\") container.stop()", "= open('{}/results.zip'.format(folderPath), 'rb') response= HttpResponse(zipFile,content_type='application/zip') response['Content-Disposition'] = 'attachment; filename=results.zip' return", "'''please check if the docker is running, and if a", "id=kwargs['project_id']) if (SolverProgress.objects.filter(project=project).exists()): progress = json.loads(get_object_or_404(SolverProgress, project=project).progress) logs = get_object_or_404(DockerLogs,", "from dashboard.models import projects from .models import AnalysisConfig, SolverResults, SolverProgress,", "= AnalysisConfig.objects.get(project=project) jsonHelper = json.loads(parentConfig.config) if category in jsonHelper: if", "AnalysisConfig.objects.get(project=project) jsonHelper = json.loads(parentConfig.config) if jsonHelper[category]: if list_id >= 0", "= docker.from_env() try: container = client.containers.get(\"FEniCSDocker\") container.stop() return Response(data=\"container stopped", "get(self, request, *args, **kwargs): \"\"\" Get the progress \"\"\" project", "the solver config \"\"\" project = get_object_or_404(projects, id=kwargs['project_id']) category =", "= resutls['path'] # create a ZipFile object with ZipFile('{}/results.zip'.format(folderPath), 'w')", "def put(self, request, filename, format=None, *args, **kwargs): \"\"\" save results", "APIView from django.shortcuts import get_object_or_404 from dashboard.models import projects from", "category for solver configuration \"\"\" project = get_object_or_404(projects, id=kwargs['project_id']) data", "return Response(data=\"submitted to analysis\", status=status.HTTP_200_OK) def delete(self, request, *args, **kwargs):", "category {} does not exist!\".format(category), status=status.HTTP_404_NOT_FOUND) class getConfiguration(APIView): parser_classes =", "a given category \"\"\" project = get_object_or_404(projects, id=kwargs['project_id']) category =", "entry with the same name exists if not list(filter(lambda name:", "available for download \"\"\" project = get_object_or_404(projects, id=kwargs['project_id']) fileType =", "{}`\".format( project.id, solver)], name=\"FEniCSDocker\", auto_remove=False, detach=True) thread = Thread(target=streamDockerLog, args=(container,", "import Thread from time import sleep from datetime import datetime", "**kwargs): \"\"\" DELETE the existing categories in the solver config", "json.loads(parentConfig.config) # if request does not contain a name if", "to make it available for download \"\"\" project = get_object_or_404(projects,", "import projects from .models import AnalysisConfig, SolverResults, SolverProgress, DockerLogs from", "json.loads(parentConfig.config) if category in jsonHelper: return Response(data=jsonHelper[category], status=status.HTTP_200_OK) else: return", "category similar to the user request if category not in", "an entry with the same name exists if not list(filter(lambda", "client.containers.run( \"quay.io/fenicsproject/stable:current\", volumes={solverPath: { 'bind': '/home/fenics/shared', 'mode': 'rw'}}, working_dir=\"/home/fenics/shared\", #", "the category \"\"\" project = get_object_or_404(projects, id=kwargs['project_id']) category = request.query_params.get('category')", "JSONParser, MultiPartParser, FileUploadParser from rest_framework import status import docker import", "get(self, request, *args, **kwargs): \"\"\" return a list of entries", "the entry with the same name exists elif not list(filter(lambda", "container.logs(stream=True): logs = get_object_or_404(DockerLogs, project=project) now = datetime.now() current_time =", "def get(self, request, *args, **kwargs): \"\"\" Runs the related solver", "ZipFile from django.http import HttpResponse from threading import Thread from", "data = request.data.dict() # if request does not contain a", "request, *args, **kwargs): \"\"\" Return the existing categories in the", "import Response from rest_framework.views import APIView from django.shortcuts import get_object_or_404", "*args, **kwargs): \"\"\" DELETE the existing categories in the solver", "= [FormParser, MultiPartParser] def get(self, request, *args, **kwargs): \"\"\" Runs", "else: progress = \"null\" logs=\"\" return Response(data=json.dumps({\"state\":progress,\"logs\":logs}), status=status.HTTP_200_OK) def post(self,", "= request.query_params.get('solver') client = docker.from_env() solverPath = os.path.abspath('./solvers') if DockerLogs.objects.filter(project=project).exists():", "not exist\".format(category), status=status.HTTP_204_NO_CONTENT) def delete(self, request, *args, **kwargs): \"\"\" Delete", "get(self, request, *args, **kwargs): \"\"\" Runs the related solver defined", "= \"null\" logs=\"\" return Response(data=json.dumps({\"state\":progress,\"logs\":logs}), status=status.HTTP_200_OK) def post(self, request, *args,", "import APIView from django.shortcuts import get_object_or_404 from dashboard.models import projects", "the id={}\".format(list_id), status=status.HTTP_204_NO_CONTENT) else: return Response(data=\"The category {} does not", "resutls = SolverResults.objects.filter(project=project).values()[0] folderPath = resutls['path'] # create a ZipFile", "project=project).progress) logs = get_object_or_404(DockerLogs, project=project).log else: progress = \"null\" logs=\"\"", "\"\"\" Get the solver config to be submitted to the", "files in directory for folderName, subfolders, filenames in os.walk(folderPath): for", "if category not in jsonHelper: jsonHelper[category] = [] jsonHelper[category].append(data) #", "= AnalysisConfig.objects.get(project=project) jsonHelper = json.loads(parentConfig.config) if category in jsonHelper: del", "in container.logs(stream=True): logs = get_object_or_404(DockerLogs, project=project) now = datetime.now() current_time", "name[\"Name\"] == data[\"Name\"], jsonHelper[category])) or jsonHelper[category][list_id][\"Name\"] == data[\"Name\"]: jsonHelper[category][list_id] =", "download \"\"\" project = get_object_or_404(projects, id=kwargs['project_id']) fileType = request.query_params.get('fileType') data", "logs.log logs.save() class solvers(APIView): parser_classes = [FormParser, MultiPartParser] def get(self,", "if list_id >= 0 and list_id < len(jsonHelper[category]): jsonHelper[category].pop(int(list_id)) parentConfig.config", "project): for line in container.logs(stream=True): logs = get_object_or_404(DockerLogs, project=project) now", "now = datetime.now() current_time = now.strftime(\"[%H:%M:%S]: \") logs.log = current_time", "get_object_or_404(projects, id=kwargs['project_id']) fileType = request.query_params.get('fileType') data = request.data['file'] folderPath =", "\"\"\" return a list of entries within a given category", "project=project).log else: progress = \"null\" logs=\"\" return Response(data=json.dumps({\"state\":progress,\"logs\":logs}), status=status.HTTP_200_OK) def", "get_object_or_404(projects, id=kwargs['project_id']) category = request.query_params.get('category') list_id = int(request.query_params.get('id')) parentConfig =", "= request.query_params.get('fileType') data = request.data['file'] folderPath = os.path.abspath( \"../FEniCSUI/media/{}/results/\".format(kwargs['project_id'])) os.makedirs(folderPath,", "file to zip zipObj.write(filePath, os.path.basename(filePath)) zipFile = open('{}/results.zip'.format(folderPath), 'rb') response=", "access to the windows docker. Instructions can be found at:", "status=status.HTTP_200_OK) def post(self, request, *args, **kwargs): \"\"\" Update the progress", "set progress to initial SolverProgress.objects.get_or_create( project=project, defaults={'progress' :json.dumps({\"status\": \"\", \"message\":", "jsonHelper[category].append(data) else: return Response(data=\"an entry with the same name exists\",", "= get_object_or_404(DockerLogs, project=project) now = datetime.now() current_time = now.strftime(\"[%H:%M:%S]: \")", "\"\\n\" + logs.log logs.save() class solvers(APIView): parser_classes = [FormParser, MultiPartParser]", "if DockerLogs.objects.filter(project=project).exists(): DockerLogs.objects.filter(project=project).delete() DockerLogs.objects.create(project=project,log=\"\") try: container = client.containers.run( \"quay.io/fenicsproject/stable:current\", volumes={solverPath:", "to the user request if category not in jsonHelper: jsonHelper[category]", "database \"\"\" project = get_object_or_404(projects, id=kwargs['project_id']) if (SolverResults.objects.filter(project=project).exists()): resutls =", "filePath = os.path.join(folderName, filename) # Add file to zip zipObj.write(filePath,", "= os.path.join(folderName, filename) # Add file to zip zipObj.write(filePath, os.path.basename(filePath))", "\"\"\" Get the progress \"\"\" project = get_object_or_404(projects, id=kwargs['project_id']) if", "downloadResults(APIView): def get(self, request, *args, **kwargs): \"\"\" Get the results", "import status import docker import os import json from zipfile", "jsonHelper: if list_id >= 0 and list_id < len(jsonHelper[category]): #", "entries within a given category \"\"\" project = get_object_or_404(projects, id=kwargs['project_id'])", "data parentConfig.config = json.dumps(jsonHelper) parentConfig.save() return Response(data=jsonHelper[category], status=status.HTTP_200_OK) else: return", "config to be submitted to the analysis \"\"\" project =", "Response(data=json.dumps({\"state\":progress,\"logs\":logs}), status=status.HTTP_200_OK) def post(self, request, *args, **kwargs): \"\"\" Update the", "status=status.HTTP_410_GONE) else: return Response(data=\"The category {} does not exist!\".format(category), status=status.HTTP_404_NOT_FOUND)", "container with the name FEniCSDocker does not exist. if you", "if not \"Name\" in data: return Response(data=\"Please provide a 'Name'", "will be created to make it available for download \"\"\"", "len(jsonHelper[category]): jsonHelper[category].pop(int(list_id)) parentConfig.config = json.dumps(jsonHelper) parentConfig.save() return Response(data=jsonHelper[category], status=status.HTTP_200_OK) else:", "object with ZipFile('{}/results.zip'.format(folderPath), 'w') as zipObj: # Iterate over all", "filename) # Add file to zip zipObj.write(filePath, os.path.basename(filePath)) zipFile =", "if the entry with the same name exists elif not", "\"\"\" project = get_object_or_404(projects, id=kwargs['project_id']) fileType = request.query_params.get('fileType') data =", "request.data.dict() # if request does not contain a name if", "= client.containers.run( \"quay.io/fenicsproject/stable:current\", volumes={solverPath: { 'bind': '/home/fenics/shared', 'mode': 'rw'}}, working_dir=\"/home/fenics/shared\",", "solver config to be submitted to the analysis \"\"\" project", "get_object_or_404 from dashboard.models import projects from .models import AnalysisConfig, SolverResults,", "get_object_or_404(projects, id=kwargs['project_id']) data = request.data.dict() category = request.query_params.get('category') parentConfig =", "solverPath = os.path.abspath('./solvers') if DockerLogs.objects.filter(project=project).exists(): DockerLogs.objects.filter(project=project).delete() DockerLogs.objects.create(project=project,log=\"\") try: container =", "return response else: return Response(data=\"not found\", status=404) class solverProgress(APIView): parser_classes", "import AnalysisConfig, SolverResults, SolverProgress, DockerLogs from rest_framework.parsers import FormParser, JSONParser,", "status=200) except: return Response(data=\"No container running\", status=404) class saveResults(APIView): parser_classes", "os.path.abspath( \"../FEniCSUI/media/{}/results/\".format(kwargs['project_id'])) os.makedirs(folderPath, exist_ok=True) filePath = '{}/{}.{}'.format(folderPath, filename, fileType) with", "new category for solver configuration \"\"\" project = get_object_or_404(projects, id=kwargs['project_id'])", ":json.dumps({\"status\": \"\", \"message\": \"\"})}) progress = SolverProgress.objects.get( project=project ) progress.progress", "= '{}/{}.{}'.format(folderPath, filename, fileType) with open(filePath, 'wb+') as destination: for", "= get_object_or_404(DockerLogs, project=project).log else: progress = \"null\" logs=\"\" return Response(data=json.dumps({\"state\":progress,\"logs\":logs}),", "= request.query_params.get('category') parentConfig = AnalysisConfig.objects.get(project=project) jsonHelper = json.loads(parentConfig.config) # if", "over all the files in directory for folderName, subfolders, filenames", "solver \"\"\" project = get_object_or_404(projects, id=kwargs['project_id']) data = request.data if", "of entries within a given category \"\"\" project = get_object_or_404(projects,", "{} {}`\".format( project.id, solver)], name=\"FEniCSDocker\", auto_remove=False, detach=True) thread = Thread(target=streamDockerLog,", "Thread from time import sleep from datetime import datetime class", "[FormParser, MultiPartParser] def get(self, request, *args, **kwargs): \"\"\" return a", "for the entry\", status=400) category = request.query_params.get('category') list_id = int(request.query_params.get('id'))", "is running, and if a container with the name FEniCSDocker", "fileType) with open(filePath, 'wb+') as destination: for chunk in data.chunks():", "a container with the name FEniCSDocker does not exist. if", "zipObj: # Iterate over all the files in directory for", "Response(data=\"Please provide a 'Name' for the entry\", status=400) # if", "request, *args, **kwargs): \"\"\" Edit an existing category entry's data", "results to media folder. a query will be created to", "zip zipObj.write(filePath, os.path.basename(filePath)) zipFile = open('{}/results.zip'.format(folderPath), 'rb') response= HttpResponse(zipFile,content_type='application/zip') response['Content-Disposition']", "== data[\"Name\"]: jsonHelper[category][list_id] = data parentConfig.config = json.dumps(jsonHelper) parentConfig.save() return", "jsonHelper[category])): jsonHelper[category].append(data) else: return Response(data=\"an entry with the same name", "FormParser, JSONParser, MultiPartParser, FileUploadParser from rest_framework import status import docker", "'/home/fenics/shared', 'mode': 'rw'}}, working_dir=\"/home/fenics/shared\", # runs solver.py with two arguments", "= json.loads(get_object_or_404(SolverProgress, project=project).progress) logs = get_object_or_404(DockerLogs, project=project).log else: progress =", "ZipFile object with ZipFile('{}/results.zip'.format(folderPath), 'w') as zipObj: # Iterate over", "logs = get_object_or_404(DockerLogs, project=project).log else: progress = \"null\" logs=\"\" return", "Delete an entry from the category \"\"\" project = get_object_or_404(projects,", "parentConfig.config = json.dumps(jsonHelper) parentConfig.save() return Response(data=jsonHelper[category], status=status.HTTP_200_OK) else: return Response(data=\"an", "os.path.abspath('./solvers') if DockerLogs.objects.filter(project=project).exists(): DockerLogs.objects.filter(project=project).delete() DockerLogs.objects.create(project=project,log=\"\") try: container = client.containers.run( \"quay.io/fenicsproject/stable:current\",", "Response from rest_framework.views import APIView from django.shortcuts import get_object_or_404 from", "exist\".format(category), status=status.HTTP_204_NO_CONTENT) class Categories(APIView): parser_classes = [FormParser, MultiPartParser] def get(self,", "entry\", status=400) category = request.query_params.get('category') list_id = int(request.query_params.get('id')) parentConfig =", "Response(data=jsonHelper[category], status=status.HTTP_200_OK) else: return Response(data=\"an entry with the same name", "def get(self, request, *args, **kwargs): \"\"\" Get the results saved", "project = get_object_or_404(projects, id=kwargs['project_id']) if (SolverResults.objects.filter(project=project).exists()): resutls = SolverResults.objects.filter(project=project).values()[0] folderPath", "# if there is no category similar to the user", "exist_ok=True) filePath = '{}/{}.{}'.format(folderPath, filename, fileType) with open(filePath, 'wb+') as", "with the id={}\".format(list_id), status=status.HTTP_204_NO_CONTENT) else: return Response(data=\"The category {} does", "datetime.now() current_time = now.strftime(\"[%H:%M:%S]: \") logs.log = current_time + str(line.strip(),", "exist!\".format(category), status=status.HTTP_404_NOT_FOUND) class getConfiguration(APIView): parser_classes = [FormParser, MultiPartParser] def get(self,", "status=status.HTTP_204_NO_CONTENT) def delete(self, request, *args, **kwargs): \"\"\" Delete an entry", "**kwargs): \"\"\" Get the progress \"\"\" project = get_object_or_404(projects, id=kwargs['project_id'])", "= json.loads(parentConfig.config) # if request does not contain a name", "for folderName, subfolders, filenames in os.walk(folderPath): for filename in filenames:", "parentConfig = AnalysisConfig.objects.get(project=project) jsonHelper = json.loads(parentConfig.config) if category in jsonHelper:", "< len(jsonHelper[category]): jsonHelper[category].pop(int(list_id)) parentConfig.config = json.dumps(jsonHelper) parentConfig.save() return Response(data=jsonHelper[category], status=status.HTTP_200_OK)", "media folder. a query will be created to make it", "folderPath = resutls['path'] # create a ZipFile object with ZipFile('{}/results.zip'.format(folderPath),", "client.containers.get(\"FEniCSDocker\") container.stop() return Response(data=\"container stopped successfully\", status=200) except: return Response(data=\"No", "def streamDockerLog(container, project): for line in container.logs(stream=True): logs = get_object_or_404(DockerLogs,", "status=400) parentConfig.config = json.dumps(jsonHelper) parentConfig.save() return Response(data=jsonHelper[category], status=status.HTTP_201_CREATED) def put(self,", "status=status.HTTP_200_OK) def streamDockerLog(container, project): for line in container.logs(stream=True): logs =", "get_object_or_404(projects, id=kwargs['project_id']) data = request.data.dict() # if request does not", "entry with the id={}\".format(list_id), status=status.HTTP_204_NO_CONTENT) else: return Response(data=\"The category {}", "*args, **kwargs): \"\"\" Get the solver config to be submitted", "message = '''please check if the docker is running, and", "sharing setting for the main folder directory is on. If", "*args, **kwargs): \"\"\" kills the running docker container \"\"\" client", "dashboard.models import projects from .models import AnalysisConfig, SolverResults, SolverProgress, DockerLogs", "# create a ZipFile object with ZipFile('{}/results.zip'.format(folderPath), 'w') as zipObj:", "in data.chunks(): destination.write(chunk) if not SolverResults.objects.filter(project=project).exists(): SolverResults.objects.create(project=project, path=folderPath) return Response(data=\"results", "folderName, subfolders, filenames in os.walk(folderPath): for filename in filenames: if", "does not exist\".format(category), status=status.HTTP_204_NO_CONTENT) class Categories(APIView): parser_classes = [FormParser, MultiPartParser]", "args=(container, project)) thread.start() except: message = '''please check if the", "to analysis\", status=status.HTTP_200_OK) def delete(self, request, *args, **kwargs): \"\"\" kills", "get_object_or_404(projects, id=kwargs['project_id']) config = AnalysisConfig.objects.filter(project=project).values()[0] return Response(data=config[\"config\"], status=status.HTTP_200_OK) def streamDockerLog(container,", "json.dumps(jsonHelper) parentConfig.save() return Response(data=jsonHelper[category], status=status.HTTP_200_OK) else: return Response(data=\"No entry with", "import os import json from zipfile import ZipFile from django.http", "open(filePath, 'wb+') as destination: for chunk in data.chunks(): destination.write(chunk) if", "else: return Response(data=\"not found\", status=404) class solverProgress(APIView): parser_classes = [JSONParser]" ]
[ "unicode_literals from .base import Opener from .errors import OpenerError from", "'sitedata': appfs.SiteDataFS, 'siteconf': appfs.SiteConfigFS, 'usercache': appfs.UserCacheFS, 'userlog': appfs.UserLogFS } def", "len(tokens) == 2: appname, author = tokens version = None", "<appname>:<author> ' 'or <appname>:<author>:<version>' ) app_fs = fs_class( appname, author=author,", "<appname>:<author>:<version>' ) app_fs = fs_class( appname, author=author, version=version, create=create )", "__future__ import print_function from __future__ import unicode_literals from .base import", "appfs.UserConfigFS, 'sitedata': appfs.SiteDataFS, 'siteconf': appfs.SiteConfigFS, 'usercache': appfs.UserCacheFS, 'userlog': appfs.UserLogFS }", "<reponame>EnjoyLifeFund/macHighSierra-py36-pkgs<gh_stars>0 # coding: utf-8 \"\"\"``AppFS`` opener definition. \"\"\" from __future__", "'userdata': appfs.UserDataFS, 'userconf': appfs.UserConfigFS, 'sitedata': appfs.SiteDataFS, 'siteconf': appfs.SiteConfigFS, 'usercache': appfs.UserCacheFS,", "= None elif len(tokens) == 3: appname, author, version =", "= [ 'userdata', 'userconf', 'sitedata', 'siteconf', 'usercache', 'userlog' ] _protocol_mapping", "from __future__ import print_function from __future__ import unicode_literals from .base", "= tokens version = None elif len(tokens) == 3: appname,", "from __future__ import unicode_literals from .base import Opener from .errors", "app_fs = fs_class( appname, author=author, version=version, create=create ) app_fs =", "( app_fs.opendir(path, factory=ClosingSubFS) if delim else app_fs ) return app_fs", "appfs.UserCacheFS, 'userlog': appfs.UserLogFS } def open_fs(self, fs_url, parse_result, writeable, create,", "'siteconf': appfs.SiteConfigFS, 'usercache': appfs.UserCacheFS, 'userlog': appfs.UserLogFS } def open_fs(self, fs_url,", "def open_fs(self, fs_url, parse_result, writeable, create, cwd): fs_class = self._protocol_mapping[parse_result.protocol]", "utf-8 \"\"\"``AppFS`` opener definition. \"\"\" from __future__ import absolute_import from", "protocols = [ 'userdata', 'userconf', 'sitedata', 'siteconf', 'usercache', 'userlog' ]", "\"\"\" protocols = [ 'userdata', 'userconf', 'sitedata', 'siteconf', 'usercache', 'userlog'", "resource, delim, path = parse_result.resource.partition('/') tokens = resource.split(':', 3) if", "' 'or <appname>:<author>:<version>' ) app_fs = fs_class( appname, author=author, version=version,", "from .base import Opener from .errors import OpenerError from ..subfs", "len(tokens) == 3: appname, author, version = tokens else: raise", "== 3: appname, author, version = tokens else: raise OpenerError(", "fs_url, parse_result, writeable, create, cwd): fs_class = self._protocol_mapping[parse_result.protocol] resource, delim,", "app_fs = ( app_fs.opendir(path, factory=ClosingSubFS) if delim else app_fs )", "fs_class = self._protocol_mapping[parse_result.protocol] resource, delim, path = parse_result.resource.partition('/') tokens =", "cwd): fs_class = self._protocol_mapping[parse_result.protocol] resource, delim, path = parse_result.resource.partition('/') tokens", "import absolute_import from __future__ import print_function from __future__ import unicode_literals", "appfs.SiteDataFS, 'siteconf': appfs.SiteConfigFS, 'usercache': appfs.UserCacheFS, 'userlog': appfs.UserLogFS } def open_fs(self,", "version = None elif len(tokens) == 3: appname, author, version", "appname, author=author, version=version, create=create ) app_fs = ( app_fs.opendir(path, factory=ClosingSubFS)", "from __future__ import absolute_import from __future__ import print_function from __future__", "import OpenerError from ..subfs import ClosingSubFS from .. import appfs", "if len(tokens) == 2: appname, author = tokens version =", "'siteconf', 'usercache', 'userlog' ] _protocol_mapping = { 'userdata': appfs.UserDataFS, 'userconf':", "\"\"\" from __future__ import absolute_import from __future__ import print_function from", "from ..subfs import ClosingSubFS from .. import appfs class AppFSOpener(Opener):", "..subfs import ClosingSubFS from .. import appfs class AppFSOpener(Opener): \"\"\"``AppFS``", "author=author, version=version, create=create ) app_fs = ( app_fs.opendir(path, factory=ClosingSubFS) if", "version = tokens else: raise OpenerError( 'resource should be <appname>:<author>", "path = parse_result.resource.partition('/') tokens = resource.split(':', 3) if len(tokens) ==", "OpenerError( 'resource should be <appname>:<author> ' 'or <appname>:<author>:<version>' ) app_fs", "= tokens else: raise OpenerError( 'resource should be <appname>:<author> '", "= parse_result.resource.partition('/') tokens = resource.split(':', 3) if len(tokens) == 2:", "'userlog': appfs.UserLogFS } def open_fs(self, fs_url, parse_result, writeable, create, cwd):", "raise OpenerError( 'resource should be <appname>:<author> ' 'or <appname>:<author>:<version>' )", "absolute_import from __future__ import print_function from __future__ import unicode_literals from", "= { 'userdata': appfs.UserDataFS, 'userconf': appfs.UserConfigFS, 'sitedata': appfs.SiteDataFS, 'siteconf': appfs.SiteConfigFS,", "should be <appname>:<author> ' 'or <appname>:<author>:<version>' ) app_fs = fs_class(", ".. import appfs class AppFSOpener(Opener): \"\"\"``AppFS`` opener. \"\"\" protocols =", "tokens version = None elif len(tokens) == 3: appname, author,", "open_fs(self, fs_url, parse_result, writeable, create, cwd): fs_class = self._protocol_mapping[parse_result.protocol] resource,", "create, cwd): fs_class = self._protocol_mapping[parse_result.protocol] resource, delim, path = parse_result.resource.partition('/')", "from .errors import OpenerError from ..subfs import ClosingSubFS from ..", "else: raise OpenerError( 'resource should be <appname>:<author> ' 'or <appname>:<author>:<version>'", "coding: utf-8 \"\"\"``AppFS`` opener definition. \"\"\" from __future__ import absolute_import", "tokens else: raise OpenerError( 'resource should be <appname>:<author> ' 'or", "= resource.split(':', 3) if len(tokens) == 2: appname, author =", "= ( app_fs.opendir(path, factory=ClosingSubFS) if delim else app_fs ) return", "class AppFSOpener(Opener): \"\"\"``AppFS`` opener. \"\"\" protocols = [ 'userdata', 'userconf',", "appfs class AppFSOpener(Opener): \"\"\"``AppFS`` opener. \"\"\" protocols = [ 'userdata',", "parse_result.resource.partition('/') tokens = resource.split(':', 3) if len(tokens) == 2: appname,", "'userlog' ] _protocol_mapping = { 'userdata': appfs.UserDataFS, 'userconf': appfs.UserConfigFS, 'sitedata':", "author = tokens version = None elif len(tokens) == 3:", "3: appname, author, version = tokens else: raise OpenerError( 'resource", "tokens = resource.split(':', 3) if len(tokens) == 2: appname, author", "appfs.UserDataFS, 'userconf': appfs.UserConfigFS, 'sitedata': appfs.SiteDataFS, 'siteconf': appfs.SiteConfigFS, 'usercache': appfs.UserCacheFS, 'userlog':", "'userdata', 'userconf', 'sitedata', 'siteconf', 'usercache', 'userlog' ] _protocol_mapping = {", "appfs.SiteConfigFS, 'usercache': appfs.UserCacheFS, 'userlog': appfs.UserLogFS } def open_fs(self, fs_url, parse_result,", "import print_function from __future__ import unicode_literals from .base import Opener", "} def open_fs(self, fs_url, parse_result, writeable, create, cwd): fs_class =", "ClosingSubFS from .. import appfs class AppFSOpener(Opener): \"\"\"``AppFS`` opener. \"\"\"", "== 2: appname, author = tokens version = None elif", "import unicode_literals from .base import Opener from .errors import OpenerError", "author, version = tokens else: raise OpenerError( 'resource should be", "delim, path = parse_result.resource.partition('/') tokens = resource.split(':', 3) if len(tokens)", "\"\"\"``AppFS`` opener. \"\"\" protocols = [ 'userdata', 'userconf', 'sitedata', 'siteconf',", "opener. \"\"\" protocols = [ 'userdata', 'userconf', 'sitedata', 'siteconf', 'usercache',", "_protocol_mapping = { 'userdata': appfs.UserDataFS, 'userconf': appfs.UserConfigFS, 'sitedata': appfs.SiteDataFS, 'siteconf':", "Opener from .errors import OpenerError from ..subfs import ClosingSubFS from", "'userconf', 'sitedata', 'siteconf', 'usercache', 'userlog' ] _protocol_mapping = { 'userdata':", "import Opener from .errors import OpenerError from ..subfs import ClosingSubFS", "__future__ import unicode_literals from .base import Opener from .errors import", "None elif len(tokens) == 3: appname, author, version = tokens", "import ClosingSubFS from .. import appfs class AppFSOpener(Opener): \"\"\"``AppFS`` opener.", "= fs_class( appname, author=author, version=version, create=create ) app_fs = (", ") app_fs = ( app_fs.opendir(path, factory=ClosingSubFS) if delim else app_fs", "AppFSOpener(Opener): \"\"\"``AppFS`` opener. \"\"\" protocols = [ 'userdata', 'userconf', 'sitedata',", "parse_result, writeable, create, cwd): fs_class = self._protocol_mapping[parse_result.protocol] resource, delim, path", "[ 'userdata', 'userconf', 'sitedata', 'siteconf', 'usercache', 'userlog' ] _protocol_mapping =", "writeable, create, cwd): fs_class = self._protocol_mapping[parse_result.protocol] resource, delim, path =", "create=create ) app_fs = ( app_fs.opendir(path, factory=ClosingSubFS) if delim else", "# coding: utf-8 \"\"\"``AppFS`` opener definition. \"\"\" from __future__ import", "opener definition. \"\"\" from __future__ import absolute_import from __future__ import", "OpenerError from ..subfs import ClosingSubFS from .. import appfs class", "resource.split(':', 3) if len(tokens) == 2: appname, author = tokens", "from .. import appfs class AppFSOpener(Opener): \"\"\"``AppFS`` opener. \"\"\" protocols", "appname, author = tokens version = None elif len(tokens) ==", "'userconf': appfs.UserConfigFS, 'sitedata': appfs.SiteDataFS, 'siteconf': appfs.SiteConfigFS, 'usercache': appfs.UserCacheFS, 'userlog': appfs.UserLogFS", ") app_fs = fs_class( appname, author=author, version=version, create=create ) app_fs", "__future__ import absolute_import from __future__ import print_function from __future__ import", "appname, author, version = tokens else: raise OpenerError( 'resource should", "elif len(tokens) == 3: appname, author, version = tokens else:", "self._protocol_mapping[parse_result.protocol] resource, delim, path = parse_result.resource.partition('/') tokens = resource.split(':', 3)", "import appfs class AppFSOpener(Opener): \"\"\"``AppFS`` opener. \"\"\" protocols = [", "version=version, create=create ) app_fs = ( app_fs.opendir(path, factory=ClosingSubFS) if delim", "{ 'userdata': appfs.UserDataFS, 'userconf': appfs.UserConfigFS, 'sitedata': appfs.SiteDataFS, 'siteconf': appfs.SiteConfigFS, 'usercache':", "definition. \"\"\" from __future__ import absolute_import from __future__ import print_function", "'sitedata', 'siteconf', 'usercache', 'userlog' ] _protocol_mapping = { 'userdata': appfs.UserDataFS,", ".base import Opener from .errors import OpenerError from ..subfs import", "appfs.UserLogFS } def open_fs(self, fs_url, parse_result, writeable, create, cwd): fs_class", "= self._protocol_mapping[parse_result.protocol] resource, delim, path = parse_result.resource.partition('/') tokens = resource.split(':',", "'usercache': appfs.UserCacheFS, 'userlog': appfs.UserLogFS } def open_fs(self, fs_url, parse_result, writeable,", "2: appname, author = tokens version = None elif len(tokens)", "'usercache', 'userlog' ] _protocol_mapping = { 'userdata': appfs.UserDataFS, 'userconf': appfs.UserConfigFS,", "be <appname>:<author> ' 'or <appname>:<author>:<version>' ) app_fs = fs_class( appname,", "3) if len(tokens) == 2: appname, author = tokens version", "print_function from __future__ import unicode_literals from .base import Opener from", ".errors import OpenerError from ..subfs import ClosingSubFS from .. import", "] _protocol_mapping = { 'userdata': appfs.UserDataFS, 'userconf': appfs.UserConfigFS, 'sitedata': appfs.SiteDataFS,", "'or <appname>:<author>:<version>' ) app_fs = fs_class( appname, author=author, version=version, create=create", "'resource should be <appname>:<author> ' 'or <appname>:<author>:<version>' ) app_fs =", "\"\"\"``AppFS`` opener definition. \"\"\" from __future__ import absolute_import from __future__", "fs_class( appname, author=author, version=version, create=create ) app_fs = ( app_fs.opendir(path," ]
[ "'svm', 'auc': area, 'f_beta': fb, 'projection': 'PCA'}, ignore_index=True) # Fit", "{}'.format(autoencoder.evaluate(x_test, x_test, batch_size=8, verbose=False))) print('Mean loss on attacks: {}'.format(autoencoder.evaluate(x_attacks, x_attacks,", "tpr = supervised_evaluation(classifier, x_test, y_test) xg_boost_results = xg_boost_results.append({ 'n_components': x_test.shape[1],", "y_pred = classifier.predict(x_test) confusion_matrix(y_test, y_pred) fpr, tpr, _ = roc_curve(y_test,", "'Validation']) plt.show() def plot_history_with_acc(network_history, title='Loss and Accuracy'): plt.figure(figsize=(15, 10)) plt.subplot(211)", "x > 0, dimensions)) for n in dimensions: x_reduced_pca, test_reduced_pca,", "= PCA(n_components=n_components) elif method == 'RP': matrix = random_projection.SparseRandomProjection(n_components=n_components, random_state=7)", "= %0.2f)' % roc_auc) plt.plot([0, 1], [0, 1], color='navy', lw=lw,", "x_test.shape[1], 'TPR': tpr, 'TNR': tnr, 'model': 'random_forest', 'auc': area, 'f_beta':", "= classifier.predict(attack_set) n_accurate_train = y_pred_train[y_pred_train == 1].size n_accurate_test = y_pred_test[y_pred_test", "area, tnr, tpr_train, tpr_test = unsupervised_evaluation(classifier, x_train_red, x_test_red, x_attacks_red) ae_svm_results", "x_test, y_test) random_forest_results = random_forest_results.append({'estimators': estimator, 'n_components': x_test.shape[1], 'TPR': tpr,", "tpr, _ = roc_curve(np.concatenate([np.ones(y_pred_test.shape[0]), -1*np.ones(y_pred_outliers.shape[0])]), np.concatenate([y_pred_test, y_pred_outliers]), pos_label=1) fb =", "'model': 'xgboost', 'auc': area, 'f_beta': fb, 'projection': 'RP'}, ignore_index=True) classifier", "auc(fpr, tpr) plt.figure() lw = 2 plt.plot(fpr, tpr, color='darkorange', lw=lw,", "y_test, svm_results): # SVC Hyper-parameters dimensions = [int(i*x_test.shape[1]) for i", "auc, confusion_matrix from sklearn.decomposition import PCA from sklearn import random_projection", "fb}, ignore_index=True) return ae_svm_results def unsupervised_evaluation(classifier, train_set, test_set, attack_set, beta=20):", "unsupervised_evaluation(classifier, x_reduced_pca, test_reduced_pca, attack_reduced_pca) isolation_results = isolation_results.append({'estimators': estimator, 'contamination': contamination,", "= Model(input_vector, encoded) autoencoder.compile(optimizer=Adam(lr=0.001), loss='mse') network_history = autoencoder.fit(x_train, x_train, shuffle=True,", "area, tnr, tpr = supervised_evaluation(classifier, test_reduced_rp, y_test) random_forest_results = random_forest_results.append({'estimators':", "'n_components': latent_dim, 'TPR_train': tpr_train, 'TPR_test': tpr_test, 'TNR': tnr, 'model': 'ae-svm',", "area, 'f_beta': fb}, ignore_index=True) return ae_svm_results def unsupervised_evaluation(classifier, train_set, test_set,", "x_attacks, ae_svm_results): latent_dim = 3 input_vector = Input(shape=(x_train.shape[1],)) encoded =", "= [0.01] gammas = [x_train_red.shape[1], 2*x_train_red.shape[1], x_train_red.shape[1]/2, 'auto'] for nu", "y_pred_test = classifier.predict(test_set) y_pred_outliers = classifier.predict(attack_set) n_accurate_train = y_pred_train[y_pred_train ==", "ignore_index=True) return svm_results def isolation_forest(x_train, x_test, x_attacks, isolation_results): # Isolation", "y_train, x_test, y_test, xg_boost_results): # XGBoost Hyper-parameters dimensions = [int(i*x_test.shape[1])", "== 'PCA': matrix = PCA(n_components=n_components) elif method == 'RP': matrix", "attacks: {}'.format(autoencoder.evaluate(x_attacks, x_attacks, batch_size=8, verbose=False))) x_train_red = encoder.predict(x_train, batch_size=8) x_test_red", "on train: {}'.format(autoencoder.evaluate(x_train, x_train, batch_size=8, verbose=False))) print('Mean loss on test:", "nu, 'gamma': gamma, 'n_components': n, 'TPR_train': tpr_train, 'TPR_test': tpr_test, 'TNR':", "'projection': 'PCA'}, ignore_index=True) # Fit classifier with RP reduced data", "fb, area, tnr, tpr = supervised_evaluation(classifier, test_reduced_rp, y_test) svm_results =", "title='Loss and Accuracy'): plt.figure(figsize=(15, 10)) plt.subplot(211) plt.title(title) plt.xlabel('Epochs') plt.ylabel('Loss') plt.semilogy(network_history.history['loss'])", "'n_components': n, 'TPR': tpr, 'TNR': tnr, 'model': 'random_forest', 'auc': area,", "area, tnr, tpr_train, tpr_test = unsupervised_evaluation(classifier, x_reduced_pca, test_reduced_pca, attack_reduced_pca) svm_results", "n in dimensions: x_reduced_pca, test_reduced_pca, attack_reduced_pca = reduce_dimensionality(n, x_train, x_test,", "= supervised_evaluation(classifier, test_reduced_pca, y_test) xg_boost_results = xg_boost_results.append({ 'n_components': n, 'TPR':", "= xgb.XGBClassifier() grid = {'max_depth': 10} classifier.set_params(**grid) classifier.fit(x_reduced_pca, y_train) fb,", "beta=20, nn=False): if not nn: y_pred = classifier.predict(x_test) confusion_matrix(y_test, y_pred)", "{}'.format(title)) plt.legend(loc='lower right') plt.show() def plot_roc_supervised(classifier, x_test, y_test, title, nn=False):", "def ada_boost(x_train, y_train, x_test, y_test, ada_boost_results): # AdaBoost Hyper-parameters learning_rates", "= RandomForestClassifier(n_estimators=estimator, n_jobs=7) classifier.fit(x_reduced_rp, y_train) fb, area, tnr, tpr =", "= supervised_evaluation(classifier, test_reduced_rp, y_test) xg_boost_results = xg_boost_results.append({ 'n_components': n, 'TPR':", "y_pred, beta=beta, pos_label=1) area = auc(fpr, tpr) tpr = tpr[1]", "return None train = matrix.fit_transform(train) test = matrix.transform(test) if attack", "2 plt.plot(fpr, tpr, color='darkorange', lw=lw, label='ROC curve (area = %0.2f)'", "ignore_index=True) return xg_boost_results def supervised_evaluation(classifier, x_test, y_test, beta=20, nn=False): if", "'RP') for lr in learning_rates: classifier = AdaBoostClassifier(learning_rate=lr) classifier.fit(x_reduced_pca, y_train)", "keras.models import Sequential from keras.optimizers import Adam from keras.regularizers import", "# SVM Hyper-parameters nus = [0.01] gammas = ['auto'] dimensions", "tpr_train, tpr_test = unsupervised_evaluation(classifier, x_reduced_pca, test_reduced_pca, attack_reduced_pca) isolation_results = isolation_results.append({'estimators':", "return random_forest_results def ada_boost(x_train, y_train, x_test, y_test, ada_boost_results): # AdaBoost", "'n_components': x_test.shape[1], 'TPR': tpr, 'TNR': tnr, 'model': 'xgboost', 'auc': area,", "plot_history_with_acc(network_history) return model def random_forest(x_train, y_train, x_test, y_test, random_forest_results): #", "reduce_dimensionality(n, x_train, x_test, 'RP') classifier = xgb.XGBClassifier() grid = {'max_depth':", "y_train) fb, area, tnr, tpr = supervised_evaluation(classifier, test_reduced_pca, y_test) ada_boost_results", "'None'}, ignore_index=True) return xg_boost_results def supervised_evaluation(classifier, x_test, y_test, beta=20, nn=False):", "[0.25, 0.35, 0.5, 0.75, 0.9, 1]] dimensions = list(filter(lambda x:", "= unsupervised_evaluation(classifier, x_reduced_rp, test_reduced_rp, attack_reduced_rp) isolation_results = isolation_results.append({'estimators': estimator, 'contamination':", "color='navy', lw=lw, linestyle='--') plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.05]) plt.xlabel('False Positive Rate')", "'svm', 'auc': area, 'f_beta': fb, 'projection': 'None'}, ignore_index=True) return svm_results", "IsolationForest(n_estimators=estimator, contamination=contamination, max_features=max_feature, n_jobs=7) classifier.fit(x_reduced_pca) fb, area, tnr, tpr_train, tpr_test", "1.0]) plt.ylim([0.0, 1.05]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('Receiver", "'PCA', attack=x_attacks) for nu in nus: for gamma in gammas:", "y_pred) if nn: y_pred = [round(x[0]) for x in y_pred]", "right') plt.show() def reduce_dimensionality(n_components, train, test, method, attack=None): if method", "IsolationForest(n_estimators=estimator, contamination=contamination, max_features=max_feature, n_jobs=7) classifier.fit(x_reduced_rp) fb, area, tnr, tpr_train, tpr_test", "y_pred)) roc_auc = auc(fpr, tpr) plt.figure() lw = 2 plt.plot(fpr,", "from keras.optimizers import Adam from keras.regularizers import l2 from sklearn.ensemble", "i in [0.25, 0.35, 0.5, 0.75, 0.9, 1]] dimensions =", "import Sequential from keras.optimizers import Adam from keras.regularizers import l2", "model.add(Dropout(0.1)) model.add(Dense(64, activation='relu', kernel_regularizer=l2(0.01))) model.add(Dropout(0.2)) model.add(Dense(128, kernel_initializer='glorot_uniform', activation='sigmoid')) model.add(Dropout(0.4)) model.add(Dense(64,", "model.add(Dense(128, kernel_initializer='glorot_uniform', activation='sigmoid')) model.add(Dropout(0.4)) model.add(Dense(64, kernel_initializer='glorot_uniform', activation='tanh')) model.add(Dropout(0.5)) model.add(Dense(32, kernel_initializer='glorot_uniform',", "attack_reduced_rp = reduce_dimensionality(n, x_train, x_test, 'RP', attack=x_attacks) max_features = list(range(1,", "1, 4)) for estimator in estimators: for contamination in contaminations:", "tpr_test, 'TNR': tnr, 'model': 'svm', 'auc': area, 'f_beta': fb, 'projection':", "classifier.predict(test_set) y_pred_outliers = classifier.predict(attack_set) n_accurate_train = y_pred_train[y_pred_train == 1].size n_accurate_test", "if nn: y_pred = [round(x[0]) for x in y_pred] print(confusion_matrix(y_test,", "classifier = IsolationForest(n_estimators=estimator, contamination=contamination, max_features=max_feature, n_jobs=7) classifier.fit(x_reduced_pca) fb, area, tnr,", "tnr, tpr_train, tpr_test = unsupervised_evaluation(classifier, x_reduced_pca, test_reduced_pca, attack_reduced_pca) svm_results =", "np.concatenate([y_pred_test, y_pred_outliers]), pos_label=1) fb = fbeta_score(np.concatenate([np.ones(y_pred_test.shape[0]), -1*np.ones(y_pred_outliers.shape[0])]), np.concatenate([y_pred_test, y_pred_outliers]), beta=beta,", "y_test) random_forest_results = random_forest_results.append({'estimators': estimator, 'n_components': x_test.shape[1], 'TPR': tpr, 'TNR':", "dimensions = [int(i*x_test.shape[1]) for i in [0.25, 0.35, 0.5, 0.75,", "attack_set, beta=20): y_pred_train = classifier.predict(train_set) y_pred_test = classifier.predict(test_set) y_pred_outliers =", "tnr, tpr = supervised_evaluation(classifier, test_reduced_pca, y_test) random_forest_results = random_forest_results.append({'estimators': estimator,", "tnr, tpr = supervised_evaluation(classifier, test_reduced_pca, y_test) svm_results = svm_results.append({ 'n_components':", "x_train, x_test, 'PCA', attack=x_attacks) x_reduced_rp, test_reduced_rp, attack_reduced_rp = reduce_dimensionality(n, x_train,", "def autoencoder(x_train, x_test, x_attacks, ae_svm_results): latent_dim = 3 input_vector =", "5)) plt.title(title) plt.xlabel('Epochs') plt.ylabel('Loss') plt.semilogy(network_history.history['loss']) plt.semilogy(network_history.history['val_loss']) plt.legend(['Training', 'Validation']) plt.show() def", "gamma=gamma, nu=nu, cache_size=7000) classifier.fit(x_train_red) fb, area, tnr, tpr_train, tpr_test =", "'f_beta': fb, 'projection': 'None'}, ignore_index=True) return svm_results def isolation_forest(x_train, x_test,", "plt.title('Receiver operating characteristic: {}'.format(title)) plt.legend(loc='lower right') plt.show() def plot_roc_supervised(classifier, x_test,", "'auc': area, 'f_beta': fb}, ignore_index=True) return ae_svm_results def unsupervised_evaluation(classifier, train_set,", "activation='relu', kernel_regularizer=l2(0.01))) model.add(Dropout(0.1)) model.add(Dense(64, activation='relu', kernel_regularizer=l2(0.01))) model.add(Dropout(0.2)) model.add(Dense(128, kernel_initializer='glorot_uniform', activation='sigmoid'))", "tnr, tpr def plot_roc(classifier, test, attacks, title): y_pred_test = classifier.predict(test)", "fb, 'projection': 'PCA'}, ignore_index=True) # Fit classifier with RP reduced", "test_set, attack_set, beta=20): y_pred_train = classifier.predict(train_set) y_pred_test = classifier.predict(test_set) y_pred_outliers", "= {'max_depth': 10} classifier.set_params(**grid) classifier.fit(x_reduced_rp, y_train) fb, area, tnr, tpr", "batch_size=8, verbose=False))) print('Mean loss on attacks: {}'.format(autoencoder.evaluate(x_attacks, x_attacks, batch_size=8, verbose=False)))", "= roc_curve(y_test, y_pred) if nn: y_pred = [round(x[0]) for x", "in [0.25, 0.5, 0.9, 1]] dimensions = list(filter(lambda x: x", "'PCA'}, ignore_index=True) # Fit classifier with RP reduced data classifier", "svm_results = svm_results.append({ 'n_components': n, 'TPR': tpr, 'TNR': tnr, 'model':", "estimators = [200, 100] contaminations = [0.01] dimensions = [int(i*x_test.shape[1])", "classifier.set_params(**grid) classifier.fit(x_train, y_train) fb, area, tnr, tpr = supervised_evaluation(classifier, x_test,", "cache_size=7000) classifier.fit(x_reduced_pca, y_train) fb, area, tnr, tpr = supervised_evaluation(classifier, test_reduced_pca,", "confusion_matrix(y_test, y_pred) fpr, tpr, _ = roc_curve(y_test, y_pred) fb =", "'PCA'}, ignore_index=True) classifier = AdaBoostClassifier(learning_rate=lr) classifier.fit(x_reduced_rp, y_train) fb, area, tnr,", "kernel_initializer='glorot_uniform', activation='tanh')) model.add(Dropout(0.5)) model.add(Dense(32, kernel_initializer='glorot_uniform', activation='tanh')) model.add(Dropout(0.4)) model.add(Dense(128, kernel_initializer='glorot_uniform', activation='tanh'))", "roc_curve(y_test, y_pred) if nn: y_pred = [round(x[0]) for x in", "matrix = PCA(n_components=n_components) elif method == 'RP': matrix = random_projection.SparseRandomProjection(n_components=n_components,", "classifier.fit(x_reduced_pca) fb, area, tnr, tpr_train, tpr_test = unsupervised_evaluation(classifier, x_reduced_pca, test_reduced_pca,", "= svm_results.append({'nu': nu, 'gamma': gamma, 'n_components': x_test.shape[1], 'TPR_train': tpr_train, 'TPR_test':", "area, tnr, tpr = supervised_evaluation(classifier, test_reduced_rp, y_test) ada_boost_results = ada_boost_results.append({'LR':", "test_reduced_rp, attack_reduced_rp) isolation_results = isolation_results.append({'estimators': estimator, 'contamination': contamination, 'n_components': n,", "RP reduced data classifier = svm.OneClassSVM(kernel='rbf', gamma=gamma, nu=nu, cache_size=7000) classifier.fit(x_train)", "random_state=7) else: print('unknown projection method, choose either RP or PCA')", "plot_history(network_history, 'AE history') print('Mean loss on train: {}'.format(autoencoder.evaluate(x_train, x_train, batch_size=8,", "fb, 'projection': 'None'}, ignore_index=True) return svm_results def isolation_forest(x_train, x_test, x_attacks,", "y_test) xg_boost_results = xg_boost_results.append({ 'n_components': x_test.shape[1], 'TPR': tpr, 'TNR': tnr,", "'PCA') x_reduced_rp, test_reduced_rp = reduce_dimensionality(n, x_train, x_test, 'RP') for lr", "classifier = svm.SVC(gamma='auto', cache_size=7000) classifier.fit(x_reduced_pca, y_train) fb, area, tnr, tpr", "'f_beta': fb, 'projection': 'PCA'}, ignore_index=True) classifier = svm.SVC(gamma='auto', cache_size=7000) classifier.fit(x_reduced_rp,", "= matrix.fit_transform(train) test = matrix.transform(test) if attack is None: return", "Dense, Input, Dropout from keras.models import Model from keras import", "tnr, 'model': 'random_forest', 'auc': area, 'f_beta': fb, 'projection': 'PCA'}, ignore_index=True)", "'None'}, ignore_index=True) return svm_results def isolation_forest(x_train, x_test, x_attacks, isolation_results): #", "'gamma': gamma, 'n_components': x_test.shape[1], 'TPR_train': tpr_train, 'TPR_test': tpr_test, 'TNR': tnr,", "nus = [0.01] gammas = [x_train_red.shape[1], 2*x_train_red.shape[1], x_train_red.shape[1]/2, 'auto'] for", "model.add(Dropout(0.2)) model.add(Dense(128, kernel_initializer='glorot_uniform', activation='sigmoid')) model.add(Dropout(0.4)) model.add(Dense(64, kernel_initializer='glorot_uniform', activation='tanh')) model.add(Dropout(0.5)) model.add(Dense(32,", "AdaBoostClassifier import xgboost as xgb def one_class_svm(x_train, x_test, x_attacks, svm_results):", "random_forest_results.append({'estimators': estimator, 'n_components': n, 'TPR': tpr, 'TNR': tnr, 'model': 'random_forest',", "fb, 'projection': 'RP'}, ignore_index=True) classifier = xgb.XGBClassifier() grid = {'max_depth':", "for i in [1]] for n in dimensions: x_reduced_pca, test_reduced_pca", "y_test, xg_boost_results): # XGBoost Hyper-parameters dimensions = [int(i*x_test.shape[1]) for i", "= IsolationForest(n_estimators=estimator, contamination=contamination, max_features=max_feature, n_jobs=7) classifier.fit(x_reduced_pca) fb, area, tnr, tpr_train,", "'TPR_train': tpr_train, 'TPR_test': tpr_test, 'TNR': tnr, 'model': 'ae-svm', 'auc': area,", "fb, 'projection': 'PCA'}, ignore_index=True) classifier = AdaBoostClassifier(learning_rate=lr) classifier.fit(x_reduced_rp, y_train) fb,", "linestyle='--') plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.05]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive", "Positive Rate') plt.ylabel('True Positive Rate') plt.title('Receiver operating characteristic: {}'.format(title)) plt.legend(loc='lower", "tnr, tpr_train, tpr_test = unsupervised_evaluation(classifier, x_reduced_rp, test_reduced_rp, attack_reduced_rp) isolation_results =", "verbose=False))) print('Mean loss on attacks: {}'.format(autoencoder.evaluate(x_attacks, x_attacks, batch_size=8, verbose=False))) x_train_red", "= supervised_evaluation(classifier, test_reduced_rp, y_test) random_forest_results = random_forest_results.append({'estimators': estimator, 'n_components': n,", "AdaBoost Hyper-parameters learning_rates = [0.55] dimensions = [int(i*x_test.shape[1]) for i", "svm_results): # SVC Hyper-parameters dimensions = [int(i*x_test.shape[1]) for i in", "tpr, 'TNR': tnr, 'model': 'xgboost', 'auc': area, 'f_beta': fb, 'projection':", "in gammas: classifier = svm.OneClassSVM(kernel='rbf', gamma=gamma, nu=nu, cache_size=7000) classifier.fit(x_train_red) fb,", "tpr def plot_roc(classifier, test, attacks, title): y_pred_test = classifier.predict(test) y_pred_outliers", "'model': 'ada_boost', 'auc': area, 'f_beta': fb, 'projection': 'RP'}, ignore_index=True) return", "encoder.predict(x_train, batch_size=8) x_test_red = encoder.predict(x_test, batch_size=8) x_attacks_red = encoder.predict(x_attacks, batch_size=8)", "= xgb.XGBClassifier() grid = {'max_depth': 10} classifier.set_params(**grid) classifier.fit(x_train, y_train) fb,", "n_jobs=7) classifier.fit(x_train, y_train) fb, area, tnr, tpr = supervised_evaluation(classifier, x_test,", "roc_curve, auc, confusion_matrix from sklearn.decomposition import PCA from sklearn import", "plt.plot(fpr, tpr, color='darkorange', lw=lw, label='ROC curve (area = %0.2f)' %", "label='ROC curve (area = %0.2f)' % roc_auc) plt.plot([0, 1], [0,", "from keras.models import Model from keras import regularizers from keras.models", "x_attacks_red = encoder.predict(x_attacks, batch_size=8) nus = [0.01] gammas = [x_train_red.shape[1],", "== -1].size fpr, tpr, _ = roc_curve(np.concatenate([np.ones(y_pred_test.shape[0]), -1*np.ones(y_pred_outliers.shape[0])]), np.concatenate([y_pred_test, y_pred_outliers]),", "Model(input_vector, encoded) autoencoder.compile(optimizer=Adam(lr=0.001), loss='mse') network_history = autoencoder.fit(x_train, x_train, shuffle=True, batch_size=16,", "area, tnr, tpr = supervised_evaluation(classifier, test_reduced_pca, y_test) ada_boost_results = ada_boost_results.append({'LR':", "tpr, color='darkorange', lw=lw, label='ROC curve (area = %0.2f)' % roc_auc)", "classifier with RP reduced data classifier = svm.OneClassSVM(kernel='rbf', gamma=gamma, nu=nu,", "'TNR': tnr, 'model': 'xgboost', 'auc': area, 'f_beta': fb, 'projection': 'PCA'},", "activation='tanh')) model.add(Dropout(0.3)) model.add(Dense(1, kernel_initializer='normal', activation='sigmoid')) model.compile(loss='binary_crossentropy', optimizer='sgd', metrics=['accuracy']) network_history =", "i in [0.25, 0.5, 0.9, 1]] dimensions = list(filter(lambda x:", "area, tnr, tpr_train, tpr_test def neural_network(x_train, y_train, x_test, y_test): model", "ignore_index=True) classifier = xgb.XGBClassifier() grid = {'max_depth': 10} classifier.set_params(**grid) classifier.fit(x_train,", "Positive Rate') plt.title('Receiver operating characteristic {}'.format(title)) plt.legend(loc='lower right') plt.show() def", "in max_features: classifier = IsolationForest(n_estimators=estimator, contamination=contamination, max_features=max_feature, n_jobs=7) classifier.fit(x_reduced_pca) fb,", "= [0.01] gammas = ['auto'] dimensions = [int(i*x_test.shape[1]) for i", "'f_beta': fb}, ignore_index=True) return ae_svm_results def unsupervised_evaluation(classifier, train_set, test_set, attack_set,", "return svm_results def xg_boost(x_train, y_train, x_test, y_test, xg_boost_results): # XGBoost", "y_train) fb, area, tnr, tpr = supervised_evaluation(classifier, test_reduced_rp, y_test) xg_boost_results", "Rate') plt.title('Receiver operating characteristic: {}'.format(title)) plt.legend(loc='lower right') plt.show() def plot_roc_supervised(classifier,", "svm.OneClassSVM(kernel='rbf', gamma=gamma, nu=nu, cache_size=7000) classifier.fit(x_train) fb, area, tnr, tpr_train, tpr_test", "color='darkorange', lw=lw, label='ROC curve (area = %0.2f)' % roc_auc) plt.plot([0,", "area, 'f_beta': fb, 'projection': 'RP'}, ignore_index=True) return svm_results def xg_boost(x_train,", "plt.show() def plot_history_with_acc(network_history, title='Loss and Accuracy'): plt.figure(figsize=(15, 10)) plt.subplot(211) plt.title(title)", "model.add(Dropout(0.4)) model.add(Dense(128, kernel_initializer='glorot_uniform', activation='tanh')) model.add(Dropout(0.3)) model.add(Dense(1, kernel_initializer='normal', activation='sigmoid')) model.compile(loss='binary_crossentropy', optimizer='sgd',", "tnr, tpr = supervised_evaluation(classifier, test_reduced_rp, y_test) xg_boost_results = xg_boost_results.append({ 'n_components':", "x_train, batch_size=8, verbose=False))) print('Mean loss on test: {}'.format(autoencoder.evaluate(x_test, x_test, batch_size=8,", "= supervised_evaluation(classifier, test_reduced_pca, y_test) ada_boost_results = ada_boost_results.append({'LR': lr, 'n_components': n,", "y_pred] print(confusion_matrix(y_test, y_pred)) roc_auc = auc(fpr, tpr) plt.figure() lw =", "1.05]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('Receiver operating characteristic", "classifier = svm.OneClassSVM(kernel='rbf', gamma=gamma, nu=nu, cache_size=7000) classifier.fit(x_reduced_pca) fb, area, tnr,", "lr, 'n_components': n, 'TPR': tpr, 'TNR': tnr, 'model': 'ada_boost', 'auc':", "= random_projection.SparseRandomProjection(n_components=n_components, random_state=7) else: print('unknown projection method, choose either RP", "if attack is None: return train, test attack = matrix.transform(attack)", "'n_components': n, 'TPR': tpr, 'TNR': tnr, 'model': 'ada_boost', 'auc': area,", "1]] dimensions = list(filter(lambda x: x > 0, dimensions)) for", "= Model(input_vector, decoded) encoder = Model(input_vector, encoded) autoencoder.compile(optimizer=Adam(lr=0.001), loss='mse') network_history", "n_accurate_test = y_pred_test[y_pred_test == 1].size n_accurate_outliers = y_pred_outliers[y_pred_outliers == -1].size", "classifier.fit(x_train_red) fb, area, tnr, tpr_train, tpr_test = unsupervised_evaluation(classifier, x_train_red, x_test_red,", "fbeta_score(y_test, y_pred, beta=beta, pos_label=1) area = auc(fpr, tpr) tpr =", "as np from sklearn.metrics import fbeta_score, roc_curve, auc, confusion_matrix from", "= {'max_depth': 10} classifier.set_params(**grid) classifier.fit(x_train, y_train) fb, area, tnr, tpr", "'TNR': tnr, 'model': 'isolation_forest', 'auc': area, 'f_beta': fb, 'projection': 'RP'},", "classifier = AdaBoostClassifier(learning_rate=lr) classifier.fit(x_reduced_rp, y_train) fb, area, tnr, tpr =", "isolation_results): # Isolation Forest Hyper-parameters estimators = [200, 100] contaminations", "svm_results def isolation_forest(x_train, x_test, x_attacks, isolation_results): # Isolation Forest Hyper-parameters", "for nu in nus: for gamma in gammas: # Fit", "tpr_test = n_accurate_test/test_set.shape[0] tpr_train = n_accurate_train/train_set.shape[0] area = auc(fpr, tpr)", "return model def random_forest(x_train, y_train, x_test, y_test, random_forest_results): # Random", "# XGBoost Hyper-parameters dimensions = [int(i*x_test.shape[1]) for i in [1]]", "y_pred_outliers = classifier.predict(attacks) fpr, tpr, _ = roc_curve(np.concatenate([np.ones(y_pred_test.shape[0]), -1*np.ones(y_pred_outliers.shape[0])]), np.concatenate([y_pred_test,", "= [round(x[0]) for x in y_pred] print(confusion_matrix(y_test, y_pred)) roc_auc =", "plt.legend(loc='lower right') plt.show() def plot_history(network_history, title): plt.figure(figsize=(10, 5)) plt.title(title) plt.xlabel('Epochs')", "y_test, random_forest_results): # Random forest Hyper-parameters estimators = [150, 200]", "= [int(i*x_test.shape[1]) for i in [0.25, 0.5, 0.9, 1]] dimensions", "Hyper-parameters nus = [0.01] gammas = ['auto'] dimensions = [int(i*x_test.shape[1])", "encoder.predict(x_test, batch_size=8) x_attacks_red = encoder.predict(x_attacks, batch_size=8) nus = [0.01] gammas", "= classifier.predict(test_set) y_pred_outliers = classifier.predict(attack_set) n_accurate_train = y_pred_train[y_pred_train == 1].size", "Model from keras import regularizers from keras.models import Sequential from", "supervised_evaluation(classifier, test_reduced_rp, y_test) random_forest_results = random_forest_results.append({'estimators': estimator, 'n_components': n, 'TPR':", "= ada_boost_results.append({'LR': lr, 'n_components': n, 'TPR': tpr, 'TNR': tnr, 'model':", "test_reduced_rp = reduce_dimensionality(n, x_train, x_test, 'RP') classifier = xgb.XGBClassifier() grid", "from keras.regularizers import l2 from sklearn.ensemble import RandomForestClassifier from sklearn.ensemble", "'ae-svm', 'auc': area, 'f_beta': fb}, ignore_index=True) return ae_svm_results def unsupervised_evaluation(classifier,", "autoencoder = Model(input_vector, decoded) encoder = Model(input_vector, encoded) autoencoder.compile(optimizer=Adam(lr=0.001), loss='mse')", "activation='tanh')) model.add(Dropout(0.5)) model.add(Dense(32, kernel_initializer='glorot_uniform', activation='tanh')) model.add(Dropout(0.4)) model.add(Dense(128, kernel_initializer='glorot_uniform', activation='tanh')) model.add(Dropout(0.3))", "Forest Hyper-parameters estimators = [200, 100] contaminations = [0.01] dimensions", "metrics=['accuracy']) network_history = model.fit(x_train, y_train, batch_size=128, epochs=10, verbose=0, validation_data=(x_test, y_test))", "fpr, tpr, _ = roc_curve(y_test, y_pred) if nn: y_pred =", "tnr, 'model': 'ada_boost', 'auc': area, 'f_beta': fb, 'projection': 'PCA'}, ignore_index=True)", "sklearn.decomposition import PCA from sklearn import random_projection from sklearn import", "= reduce_dimensionality(n, x_train, x_test, 'RP') classifier = xgb.XGBClassifier() grid =", "tpr = supervised_evaluation(classifier, x_test, y_test) random_forest_results = random_forest_results.append({'estimators': estimator, 'n_components':", "for i in [0.25, 0.5, 0.9, 1]] dimensions = list(filter(lambda", "import random_projection from sklearn import svm from sklearn.ensemble import IsolationForest", "x_reduced_pca, test_reduced_pca, attack_reduced_pca = reduce_dimensionality(n, x_train, x_test, 'PCA', attack=x_attacks) for", "matrix.fit_transform(train) test = matrix.transform(test) if attack is None: return train,", "0.5, 0.75, 0.9, 1]] dimensions = list(filter(lambda x: x >", "= svm.OneClassSVM(kernel='rbf', gamma=gamma, nu=nu, cache_size=7000) classifier.fit(x_train) fb, area, tnr, tpr_train,", "x_test, 'RP') for lr in learning_rates: classifier = AdaBoostClassifier(learning_rate=lr) classifier.fit(x_reduced_pca,", "grid = {'max_depth': 10} classifier.set_params(**grid) classifier.fit(x_reduced_rp, y_train) fb, area, tnr,", "x_test.shape[1], 'TPR': tpr, 'TNR': tnr, 'model': 'xgboost', 'auc': area, 'f_beta':", "not nn: y_pred = classifier.predict(x_test) confusion_matrix(y_test, y_pred) fpr, tpr, _", "in dimensions: x_reduced_pca, test_reduced_pca = reduce_dimensionality(n, x_train, x_test, 'PCA') x_reduced_rp,", "y_test, ada_boost_results): # AdaBoost Hyper-parameters learning_rates = [0.55] dimensions =", "tpr_train, tpr_test = unsupervised_evaluation(classifier, x_reduced_pca, test_reduced_pca, attack_reduced_pca) svm_results = svm_results.append({'nu':", "train: {}'.format(autoencoder.evaluate(x_train, x_train, batch_size=8, verbose=False))) print('Mean loss on test: {}'.format(autoencoder.evaluate(x_test,", "y_test) ada_boost_results = ada_boost_results.append({'LR': lr, 'n_components': n, 'TPR': tpr, 'TNR':", "tpr = supervised_evaluation(classifier, test_reduced_rp, y_test) ada_boost_results = ada_boost_results.append({'LR': lr, 'n_components':", "'auc': area, 'f_beta': fb, 'projection': 'RP'}, ignore_index=True) return ada_boost_results def", "xg_boost(x_train, y_train, x_test, y_test, xg_boost_results): # XGBoost Hyper-parameters dimensions =", "nus: for gamma in gammas: classifier = svm.OneClassSVM(kernel='rbf', gamma=gamma, nu=nu,", "xg_boost_results = xg_boost_results.append({ 'n_components': x_test.shape[1], 'TPR': tpr, 'TNR': tnr, 'model':", "in [0.25, 0.35, 0.5, 0.75, 0.9, 1]] dimensions = list(filter(lambda", "n_accurate_test/test_set.shape[0] tpr_train = n_accurate_train/train_set.shape[0] area = auc(fpr, tpr) return fb,", "random_forest(x_train, y_train, x_test, y_test, random_forest_results): # Random forest Hyper-parameters estimators", "= svm.SVC(gamma='auto', cache_size=7000) classifier.fit(x_reduced_rp, y_train) fb, area, tnr, tpr =", "fpr, tpr, _ = roc_curve(y_test, y_pred) fb = fbeta_score(y_test, y_pred,", "ada_boost_results.append({'LR': lr, 'n_components': n, 'TPR': tpr, 'TNR': tnr, 'model': 'ada_boost',", "y_pred = [round(x[0]) for x in y_pred] print(confusion_matrix(y_test, y_pred)) roc_auc", "kernel_initializer='glorot_uniform', activation='sigmoid')) model.add(Dropout(0.4)) model.add(Dense(64, kernel_initializer='glorot_uniform', activation='tanh')) model.add(Dropout(0.5)) model.add(Dense(32, kernel_initializer='glorot_uniform', activation='tanh'))", "'PCA'}, ignore_index=True) classifier = xgb.XGBClassifier() grid = {'max_depth': 10} classifier.set_params(**grid)", "test_reduced_rp, y_test) xg_boost_results = xg_boost_results.append({ 'n_components': n, 'TPR': tpr, 'TNR':", "0, dimensions)) for n in dimensions: x_reduced_pca, test_reduced_pca, attack_reduced_pca =", "x_train, x_test, 'RP') for lr in learning_rates: classifier = AdaBoostClassifier(learning_rate=lr)", "area, 'f_beta': fb, 'projection': 'None'}, ignore_index=True) return svm_results def isolation_forest(x_train,", "batch_size=8, verbose=False))) x_train_red = encoder.predict(x_train, batch_size=8) x_test_red = encoder.predict(x_test, batch_size=8)", "y_pred_outliers]), pos_label=1) fb = fbeta_score(np.concatenate([np.ones(y_pred_test.shape[0]), -1*np.ones(y_pred_outliers.shape[0])]), np.concatenate([y_pred_test, y_pred_outliers]), beta=beta, pos_label=1)", "= [int(i*x_test.shape[1]) for i in [0.25, 0.35, 0.5, 0.75, 0.9,", "regularizers from keras.models import Sequential from keras.optimizers import Adam from", "test_reduced_rp = reduce_dimensionality(n, x_train, x_test, 'RP') for lr in learning_rates:", "supervised_evaluation(classifier, test_reduced_rp, y_test) xg_boost_results = xg_boost_results.append({ 'n_components': n, 'TPR': tpr,", "Positive Rate') plt.title('Receiver operating characteristic: {}'.format(title)) plt.legend(loc='lower right') plt.show() def", "fb, area, tnr, tpr_train, tpr_test = unsupervised_evaluation(classifier, x_train, x_test, x_attacks)", "y_pred_outliers = classifier.predict(attack_set) n_accurate_train = y_pred_train[y_pred_train == 1].size n_accurate_test =", "plt.legend(loc='lower right') plt.show() def plot_roc_supervised(classifier, x_test, y_test, title, nn=False): y_pred", "ignore_index=True) return svm_results def xg_boost(x_train, y_train, x_test, y_test, xg_boost_results): #", "[x_train_red.shape[1], 2*x_train_red.shape[1], x_train_red.shape[1]/2, 'auto'] for nu in nus: for gamma", "plt.show() def plot_roc_supervised(classifier, x_test, y_test, title, nn=False): y_pred = classifier.predict(x_test)", "tpr_test = unsupervised_evaluation(classifier, x_reduced_rp, test_reduced_rp, attack_reduced_rp) isolation_results = isolation_results.append({'estimators': estimator,", "[150, 200] dimensions = [int(i*x_test.shape[1]) for i in [1]] for", "activity_regularizer=regularizers.l1(10e-5))(encoded) autoencoder = Model(input_vector, decoded) encoder = Model(input_vector, encoded) autoencoder.compile(optimizer=Adam(lr=0.001),", "activation='sigmoid')) model.add(Dropout(0.4)) model.add(Dense(64, kernel_initializer='glorot_uniform', activation='tanh')) model.add(Dropout(0.5)) model.add(Dense(32, kernel_initializer='glorot_uniform', activation='tanh')) model.add(Dropout(0.4))", "kernel_initializer='glorot_uniform', activation='tanh')) model.add(Dropout(0.4)) model.add(Dense(128, kernel_initializer='glorot_uniform', activation='tanh')) model.add(Dropout(0.3)) model.add(Dense(1, kernel_initializer='normal', activation='sigmoid'))", "tpr = supervised_evaluation(classifier, test_reduced_pca, y_test) random_forest_results = random_forest_results.append({'estimators': estimator, 'n_components':", "'PCA': matrix = PCA(n_components=n_components) elif method == 'RP': matrix =", "verbose=True) plot_history(network_history, 'AE history') print('Mean loss on train: {}'.format(autoencoder.evaluate(x_train, x_train,", "tpr) return fb, area, tnr, tpr_train, tpr_test def neural_network(x_train, y_train,", "import numpy as np from sklearn.metrics import fbeta_score, roc_curve, auc,", "'auc': area, 'f_beta': fb, 'projection': 'RP'}, ignore_index=True) return svm_results def", "matrix = random_projection.SparseRandomProjection(n_components=n_components, random_state=7) else: print('unknown projection method, choose either", "tpr_train, tpr_test = unsupervised_evaluation(classifier, x_reduced_rp, test_reduced_rp, attack_reduced_rp) isolation_results = isolation_results.append({'estimators':", "'projection': 'PCA'}, ignore_index=True) classifier = RandomForestClassifier(n_estimators=estimator, n_jobs=7) classifier.fit(x_reduced_rp, y_train) fb,", "xg_boost_results.append({ 'n_components': x_test.shape[1], 'TPR': tpr, 'TNR': tnr, 'model': 'xgboost', 'auc':", "plt.ylabel('Loss') plt.semilogy(network_history.history['loss']) plt.semilogy(network_history.history['val_loss']) plt.legend(['Training', 'Validation']) plt.subplot(212) plt.xlabel('Epochs') plt.ylabel('Accuracy') plt.plot(network_history.history['acc']) plt.plot(network_history.history['val_acc'])", "plt.plot(network_history.history['acc']) plt.plot(network_history.history['val_acc']) plt.legend(['Training', 'Validation'], loc='lower right') plt.show() def reduce_dimensionality(n_components, train,", "x in y_pred] print(confusion_matrix(y_test, y_pred)) roc_auc = auc(fpr, tpr) plt.figure()", "fpr, tpr, _ = roc_curve(np.concatenate([np.ones(y_pred_test.shape[0]), -1*np.ones(y_pred_outliers.shape[0])]), np.concatenate([y_pred_test, y_pred_outliers]), pos_label=1) roc_auc", "SVM Hyper-parameters nus = [0.01] gammas = ['auto'] dimensions =", "model.add(Dropout(0.5)) model.add(Dense(32, kernel_initializer='glorot_uniform', activation='tanh')) model.add(Dropout(0.4)) model.add(Dense(128, kernel_initializer='glorot_uniform', activation='tanh')) model.add(Dropout(0.3)) model.add(Dense(1,", "x: x > 0, dimensions)) for n in dimensions: x_reduced_pca,", "area, 'f_beta': fb, 'projection': 'PCA'}, ignore_index=True) classifier = svm.SVC(gamma='auto', cache_size=7000)", "x_test, 'PCA', attack=x_attacks) for nu in nus: for gamma in", "_ = roc_curve(np.concatenate([np.ones(y_pred_test.shape[0]), -1*np.ones(y_pred_outliers.shape[0])]), np.concatenate([y_pred_test, y_pred_outliers]), pos_label=1) fb = fbeta_score(np.concatenate([np.ones(y_pred_test.shape[0]),", "y_test): model = Sequential() model.add(Dense(128, input_shape=(x_train.shape[1],), activation='relu', kernel_regularizer=l2(0.01))) model.add(Dropout(0.1)) model.add(Dense(64,", "contaminations: for max_feature in max_features: classifier = IsolationForest(n_estimators=estimator, contamination=contamination, max_features=max_feature,", "= ae_svm_results.append({'nu': nu, 'gamma': gamma, 'n_components': latent_dim, 'TPR_train': tpr_train, 'TPR_test':", "[0, 1], color='navy', lw=lw, linestyle='--') plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.05]) plt.xlabel('False", "'auc': area, 'f_beta': fb, 'projection': 'None'}, ignore_index=True) return xg_boost_results def", "def plot_roc_supervised(classifier, x_test, y_test, title, nn=False): y_pred = classifier.predict(x_test) fpr,", "'auc': area, 'f_beta': fb, 'projection': 'PCA'}, ignore_index=True) # Fit classifier", "Rate') plt.ylabel('True Positive Rate') plt.title('Receiver operating characteristic: {}'.format(title)) plt.legend(loc='lower right')", "x_reduced_pca, test_reduced_pca, attack_reduced_pca) svm_results = svm_results.append({'nu': nu, 'gamma': gamma, 'n_components':", "# SVC Hyper-parameters dimensions = [int(i*x_test.shape[1]) for i in [1]]", "in y_pred] print(confusion_matrix(y_test, y_pred)) roc_auc = auc(fpr, tpr) plt.figure() lw", "0.75, 0.9, 1]] dimensions = list(filter(lambda x: x > 0,", "test, attacks, title): y_pred_test = classifier.predict(test) y_pred_outliers = classifier.predict(attacks) fpr,", "import AdaBoostClassifier import xgboost as xgb def one_class_svm(x_train, x_test, x_attacks,", "fpr[1] return fb, area, tnr, tpr def plot_roc(classifier, test, attacks,", "y_pred_test = classifier.predict(test) y_pred_outliers = classifier.predict(attacks) fpr, tpr, _ =", "= fbeta_score(np.concatenate([np.ones(y_pred_test.shape[0]), -1*np.ones(y_pred_outliers.shape[0])]), np.concatenate([y_pred_test, y_pred_outliers]), beta=beta, pos_label=1) tnr = n_accurate_outliers/attack_set.shape[0]", "activation='sigmoid')) model.compile(loss='binary_crossentropy', optimizer='sgd', metrics=['accuracy']) network_history = model.fit(x_train, y_train, batch_size=128, epochs=10,", "latent_dim, 'TPR_train': tpr_train, 'TPR_test': tpr_test, 'TNR': tnr, 'model': 'ae-svm', 'auc':", "tpr = supervised_evaluation(classifier, test_reduced_rp, y_test) svm_results = svm_results.append({ 'n_components': n,", "fb, area, tnr, tpr = supervised_evaluation(classifier, test_reduced_rp, y_test) random_forest_results =", "classifier = svm.SVC(gamma='auto', cache_size=7000) classifier.fit(x_reduced_rp, y_train) fb, area, tnr, tpr", "fb, area, tnr, tpr = supervised_evaluation(classifier, test_reduced_pca, y_test) svm_results =", "plt.figure(figsize=(15, 10)) plt.subplot(211) plt.title(title) plt.xlabel('Epochs') plt.ylabel('Loss') plt.semilogy(network_history.history['loss']) plt.semilogy(network_history.history['val_loss']) plt.legend(['Training', 'Validation'])", "plt.show() def plot_history(network_history, title): plt.figure(figsize=(10, 5)) plt.title(title) plt.xlabel('Epochs') plt.ylabel('Loss') plt.semilogy(network_history.history['loss'])", "attack_reduced_pca) svm_results = svm_results.append({'nu': nu, 'gamma': gamma, 'n_components': n, 'TPR_train':", "from sklearn.metrics import fbeta_score, roc_curve, auc, confusion_matrix from sklearn.decomposition import", "supervised_evaluation(classifier, x_test, y_test, beta=20, nn=False): if not nn: y_pred =", "from sklearn.ensemble import AdaBoostClassifier import xgboost as xgb def one_class_svm(x_train,", "area, tnr, tpr = supervised_evaluation(classifier, test_reduced_pca, y_test) random_forest_results = random_forest_results.append({'estimators':", "area, 'f_beta': fb, 'projection': 'RP'}, ignore_index=True) classifier = RandomForestClassifier(n_estimators=estimator, n_jobs=7)", "train, test, method, attack=None): if method == 'PCA': matrix =", "[0.01] gammas = [x_train_red.shape[1], 2*x_train_red.shape[1], x_train_red.shape[1]/2, 'auto'] for nu in", "kernel_regularizer=l2(0.01))) model.add(Dropout(0.2)) model.add(Dense(128, kernel_initializer='glorot_uniform', activation='sigmoid')) model.add(Dropout(0.4)) model.add(Dense(64, kernel_initializer='glorot_uniform', activation='tanh')) model.add(Dropout(0.5))", "batch_size=8) x_test_red = encoder.predict(x_test, batch_size=8) x_attacks_red = encoder.predict(x_attacks, batch_size=8) nus", "fb, area, tnr, tpr_train, tpr_test = unsupervised_evaluation(classifier, x_reduced_rp, test_reduced_rp, attack_reduced_rp)", "encoded) autoencoder.compile(optimizer=Adam(lr=0.001), loss='mse') network_history = autoencoder.fit(x_train, x_train, shuffle=True, batch_size=16, epochs=10,", "x_test, 'RP', attack=x_attacks) max_features = list(range(1, n + 1, 4))", "x_test, 'RP') classifier = RandomForestClassifier(n_estimators=estimator, n_jobs=7) classifier.fit(x_reduced_pca, y_train) fb, area,", "learning_rates: classifier = AdaBoostClassifier(learning_rate=lr) classifier.fit(x_reduced_pca, y_train) fb, area, tnr, tpr", "'projection': 'RP'}, ignore_index=True) return isolation_results def autoencoder(x_train, x_test, x_attacks, ae_svm_results):", "'model': 'random_forest', 'auc': area, 'f_beta': fb, 'projection': 'RP'}, ignore_index=True) classifier", "random_forest_results = random_forest_results.append({'estimators': estimator, 'n_components': x_test.shape[1], 'TPR': tpr, 'TNR': tnr,", "y_train) fb, area, tnr, tpr = supervised_evaluation(classifier, test_reduced_rp, y_test) svm_results", "forest Hyper-parameters estimators = [150, 200] dimensions = [int(i*x_test.shape[1]) for", "as xgb def one_class_svm(x_train, x_test, x_attacks, svm_results): # SVM Hyper-parameters", "'PCA'}, ignore_index=True) classifier = IsolationForest(n_estimators=estimator, contamination=contamination, max_features=max_feature, n_jobs=7) classifier.fit(x_reduced_rp) fb,", "list(range(1, n + 1, 4)) for estimator in estimators: for", "tpr, 'TNR': tnr, 'model': 'svm', 'auc': area, 'f_beta': fb, 'projection':", "fb, area, tnr, tpr_train, tpr_test = unsupervised_evaluation(classifier, x_train_red, x_test_red, x_attacks_red)", "x_attacks, batch_size=8, verbose=False))) x_train_red = encoder.predict(x_train, batch_size=8) x_test_red = encoder.predict(x_test,", "= reduce_dimensionality(n, x_train, x_test, 'PCA') x_reduced_rp, test_reduced_rp = reduce_dimensionality(n, x_train,", "fb, area, tnr, tpr def plot_roc(classifier, test, attacks, title): y_pred_test", "'PCA', attack=x_attacks) x_reduced_rp, test_reduced_rp, attack_reduced_rp = reduce_dimensionality(n, x_train, x_test, 'RP',", "xgboost as xgb def one_class_svm(x_train, x_test, x_attacks, svm_results): # SVM", "x_attacks, isolation_results): # Isolation Forest Hyper-parameters estimators = [200, 100]", "'TPR_test': tpr_test, 'TNR': tnr, 'model': 'ae-svm', 'auc': area, 'f_beta': fb},", "test: {}'.format(autoencoder.evaluate(x_test, x_test, batch_size=8, verbose=False))) print('Mean loss on attacks: {}'.format(autoencoder.evaluate(x_attacks,", "area, tnr, tpr = supervised_evaluation(classifier, test_reduced_rp, y_test) xg_boost_results = xg_boost_results.append({", "Model(input_vector, decoded) encoder = Model(input_vector, encoded) autoencoder.compile(optimizer=Adam(lr=0.001), loss='mse') network_history =", "on test: {}'.format(autoencoder.evaluate(x_test, x_test, batch_size=8, verbose=False))) print('Mean loss on attacks:", "y_train) fb, area, tnr, tpr = supervised_evaluation(classifier, x_test, y_test) random_forest_results", "title): y_pred_test = classifier.predict(test) y_pred_outliers = classifier.predict(attacks) fpr, tpr, _", "roc_curve(np.concatenate([np.ones(y_pred_test.shape[0]), -1*np.ones(y_pred_outliers.shape[0])]), np.concatenate([y_pred_test, y_pred_outliers]), pos_label=1) roc_auc = auc(fpr, tpr) plt.figure()", "'model': 'ae-svm', 'auc': area, 'f_beta': fb}, ignore_index=True) return ae_svm_results def", "tnr, tpr_train, tpr_test def neural_network(x_train, y_train, x_test, y_test): model =", "Dropout from keras.models import Model from keras import regularizers from", "= ['auto'] dimensions = [int(i*x_test.shape[1]) for i in [0.25, 0.35,", "tnr, tpr_train, tpr_test = unsupervised_evaluation(classifier, x_reduced_pca, test_reduced_pca, attack_reduced_pca) isolation_results =", "y_test)) plot_history_with_acc(network_history) return model def random_forest(x_train, y_train, x_test, y_test, random_forest_results):", "return fb, area, tnr, tpr def plot_roc(classifier, test, attacks, title):", "import IsolationForest import matplotlib.pyplot as plt from keras.layers import Dense,", "'f_beta': fb, 'projection': 'PCA'}, ignore_index=True) # Fit classifier with RP", "fb, area, tnr, tpr = supervised_evaluation(classifier, test_reduced_pca, y_test) xg_boost_results =", "10)) plt.subplot(211) plt.title(title) plt.xlabel('Epochs') plt.ylabel('Loss') plt.semilogy(network_history.history['loss']) plt.semilogy(network_history.history['val_loss']) plt.legend(['Training', 'Validation']) plt.subplot(212)", "= supervised_evaluation(classifier, x_test, y_test) random_forest_results = random_forest_results.append({'estimators': estimator, 'n_components': x_test.shape[1],", "= supervised_evaluation(classifier, test_reduced_pca, y_test) svm_results = svm_results.append({ 'n_components': n, 'TPR':", "10} classifier.set_params(**grid) classifier.fit(x_train, y_train) fb, area, tnr, tpr = supervised_evaluation(classifier,", "from keras.models import Sequential from keras.optimizers import Adam from keras.regularizers", "batch_size=8) x_attacks_red = encoder.predict(x_attacks, batch_size=8) nus = [0.01] gammas =", "i in [1]] for n in dimensions: x_reduced_pca, test_reduced_pca =", "= classifier.predict(attacks) fpr, tpr, _ = roc_curve(np.concatenate([np.ones(y_pred_test.shape[0]), -1*np.ones(y_pred_outliers.shape[0])]), np.concatenate([y_pred_test, y_pred_outliers]),", "max_feature in max_features: classifier = IsolationForest(n_estimators=estimator, contamination=contamination, max_features=max_feature, n_jobs=7) classifier.fit(x_reduced_pca)", "fb, 'projection': 'PCA'}, ignore_index=True) classifier = svm.SVC(gamma='auto', cache_size=7000) classifier.fit(x_reduced_rp, y_train)", "xgb.XGBClassifier() grid = {'max_depth': 10} classifier.set_params(**grid) classifier.fit(x_reduced_pca, y_train) fb, area,", "tpr) plt.figure() lw = 2 plt.plot(fpr, tpr, color='darkorange', lw=lw, label='ROC", "pos_label=1) roc_auc = auc(fpr, tpr) plt.figure() lw = 2 plt.plot(fpr,", "beta=beta, pos_label=1) area = auc(fpr, tpr) tpr = tpr[1] tnr", "plt.ylabel('Loss') plt.semilogy(network_history.history['loss']) plt.semilogy(network_history.history['val_loss']) plt.legend(['Training', 'Validation']) plt.show() def plot_history_with_acc(network_history, title='Loss and", "'TPR': tpr, 'TNR': tnr, 'model': 'xgboost', 'auc': area, 'f_beta': fb,", "classifier with PCA reduced data classifier = svm.OneClassSVM(kernel='rbf', gamma=gamma, nu=nu,", "classifier = IsolationForest(n_estimators=estimator, contamination=contamination, max_features=max_feature, n_jobs=7) classifier.fit(x_reduced_rp) fb, area, tnr,", "{}'.format(autoencoder.evaluate(x_attacks, x_attacks, batch_size=8, verbose=False))) x_train_red = encoder.predict(x_train, batch_size=8) x_test_red =", "model.add(Dropout(0.3)) model.add(Dense(1, kernel_initializer='normal', activation='sigmoid')) model.compile(loss='binary_crossentropy', optimizer='sgd', metrics=['accuracy']) network_history = model.fit(x_train,", "tnr, 'model': 'isolation_forest', 'auc': area, 'f_beta': fb, 'projection': 'RP'}, ignore_index=True)", "elif method == 'RP': matrix = random_projection.SparseRandomProjection(n_components=n_components, random_state=7) else: print('unknown", "= n_accurate_test/test_set.shape[0] tpr_train = n_accurate_train/train_set.shape[0] area = auc(fpr, tpr) return", "in [1]] for n in dimensions: x_reduced_pca, test_reduced_pca = reduce_dimensionality(n,", "= auc(fpr, tpr) plt.figure() lw = 2 plt.plot(fpr, tpr, color='darkorange',", "characteristic {}'.format(title)) plt.legend(loc='lower right') plt.show() def plot_history(network_history, title): plt.figure(figsize=(10, 5))", "x_test_red, x_attacks_red) ae_svm_results = ae_svm_results.append({'nu': nu, 'gamma': gamma, 'n_components': latent_dim,", "= AdaBoostClassifier(learning_rate=lr) classifier.fit(x_reduced_pca, y_train) fb, area, tnr, tpr = supervised_evaluation(classifier,", "xg_boost_results def supervised_evaluation(classifier, x_test, y_test, beta=20, nn=False): if not nn:", "'n_components': n, 'TPR': tpr, 'TNR': tnr, 'model': 'xgboost', 'auc': area,", "method, attack=None): if method == 'PCA': matrix = PCA(n_components=n_components) elif", "unsupervised_evaluation(classifier, x_train_red, x_test_red, x_attacks_red) ae_svm_results = ae_svm_results.append({'nu': nu, 'gamma': gamma,", "= y_pred_outliers[y_pred_outliers == -1].size fpr, tpr, _ = roc_curve(np.concatenate([np.ones(y_pred_test.shape[0]), -1*np.ones(y_pred_outliers.shape[0])]),", "Input, Dropout from keras.models import Model from keras import regularizers", "'TNR': tnr, 'model': 'svm', 'auc': area, 'f_beta': fb, 'projection': 'None'},", "'TNR': tnr, 'model': 'svm', 'auc': area, 'f_beta': fb, 'projection': 'RP'},", "1 - fpr[1] return fb, area, tnr, tpr def plot_roc(classifier,", "nu in nus: for gamma in gammas: # Fit classifier", "tnr, tpr = supervised_evaluation(classifier, test_reduced_rp, y_test) svm_results = svm_results.append({ 'n_components':", "'xgboost', 'auc': area, 'f_beta': fb, 'projection': 'PCA'}, ignore_index=True) classifier =", "classifier.predict(x_test) fpr, tpr, _ = roc_curve(y_test, y_pred) if nn: y_pred", "[int(i*x_test.shape[1]) for i in [0.25, 0.5, 0.9, 1]] dimensions =", "Rate') plt.ylabel('True Positive Rate') plt.title('Receiver operating characteristic {}'.format(title)) plt.legend(loc='lower right')", "tnr, tpr = supervised_evaluation(classifier, test_reduced_rp, y_test) ada_boost_results = ada_boost_results.append({'LR': lr,", "plt.title('Receiver operating characteristic {}'.format(title)) plt.legend(loc='lower right') plt.show() def plot_history(network_history, title):", "= unsupervised_evaluation(classifier, x_reduced_pca, test_reduced_pca, attack_reduced_pca) isolation_results = isolation_results.append({'estimators': estimator, 'contamination':", "confusion_matrix from sklearn.decomposition import PCA from sklearn import random_projection from", "for lr in learning_rates: classifier = AdaBoostClassifier(learning_rate=lr) classifier.fit(x_reduced_pca, y_train) fb,", "'projection': 'PCA'}, ignore_index=True) classifier = xgb.XGBClassifier() grid = {'max_depth': 10}", "classifier = xgb.XGBClassifier() grid = {'max_depth': 10} classifier.set_params(**grid) classifier.fit(x_reduced_pca, y_train)", "test_reduced_pca, y_test) svm_results = svm_results.append({ 'n_components': n, 'TPR': tpr, 'TNR':", "Sequential from keras.optimizers import Adam from keras.regularizers import l2 from", "-1*np.ones(y_pred_outliers.shape[0])]), np.concatenate([y_pred_test, y_pred_outliers]), beta=beta, pos_label=1) tnr = n_accurate_outliers/attack_set.shape[0] tpr_test =", "estimator in estimators: for n in dimensions: x_reduced_pca, test_reduced_pca =", "sklearn.ensemble import AdaBoostClassifier import xgboost as xgb def one_class_svm(x_train, x_test,", "def random_forest(x_train, y_train, x_test, y_test, random_forest_results): # Random forest Hyper-parameters", "ada_boost_results): # AdaBoost Hyper-parameters learning_rates = [0.55] dimensions = [int(i*x_test.shape[1])", "area, 'f_beta': fb, 'projection': 'PCA'}, ignore_index=True) classifier = RandomForestClassifier(n_estimators=estimator, n_jobs=7)", "area, 'f_beta': fb, 'projection': 'PCA'}, ignore_index=True) classifier = xgb.XGBClassifier() grid", "x_reduced_rp, test_reduced_rp = reduce_dimensionality(n, x_train, x_test, 'RP') classifier = svm.SVC(gamma='auto',", "else: print('unknown projection method, choose either RP or PCA') return", "model.add(Dense(64, kernel_initializer='glorot_uniform', activation='tanh')) model.add(Dropout(0.5)) model.add(Dense(32, kernel_initializer='glorot_uniform', activation='tanh')) model.add(Dropout(0.4)) model.add(Dense(128, kernel_initializer='glorot_uniform',", "dimensions)) for n in dimensions: x_reduced_pca, test_reduced_pca, attack_reduced_pca = reduce_dimensionality(n,", "'TPR_test': tpr_test, 'TNR': tnr, 'model': 'svm', 'auc': area, 'f_beta': fb,", "plot_history_with_acc(network_history, title='Loss and Accuracy'): plt.figure(figsize=(15, 10)) plt.subplot(211) plt.title(title) plt.xlabel('Epochs') plt.ylabel('Loss')", "contamination, 'n_components': n, 'max_features': max_feature, 'TPR_train': tpr_train, 'TPR_test': tpr_test, 'TNR':", "tnr, 'model': 'svm', 'auc': area, 'f_beta': fb, 'projection': 'RP'}, ignore_index=True)", "ae_svm_results.append({'nu': nu, 'gamma': gamma, 'n_components': latent_dim, 'TPR_train': tpr_train, 'TPR_test': tpr_test,", "'auc': area, 'f_beta': fb, 'projection': 'None'}, ignore_index=True) return random_forest_results def", "100] contaminations = [0.01] dimensions = [int(i*x_test.shape[1]) for i in", "{'max_depth': 10} classifier.set_params(**grid) classifier.fit(x_train, y_train) fb, area, tnr, tpr =", "import Adam from keras.regularizers import l2 from sklearn.ensemble import RandomForestClassifier", "encoder = Model(input_vector, encoded) autoencoder.compile(optimizer=Adam(lr=0.001), loss='mse') network_history = autoencoder.fit(x_train, x_train,", "area, 'f_beta': fb, 'projection': 'PCA'}, ignore_index=True) # Fit classifier with", "epochs=10, verbose=0, validation_data=(x_test, y_test)) plot_history_with_acc(network_history) return model def random_forest(x_train, y_train,", "attack=x_attacks) for nu in nus: for gamma in gammas: #", "estimators = [150, 200] dimensions = [int(i*x_test.shape[1]) for i in", "max_features=max_feature, n_jobs=7) classifier.fit(x_reduced_pca) fb, area, tnr, tpr_train, tpr_test = unsupervised_evaluation(classifier,", "RandomForestClassifier(n_estimators=estimator, n_jobs=7) classifier.fit(x_reduced_rp, y_train) fb, area, tnr, tpr = supervised_evaluation(classifier,", "y_train) fb, area, tnr, tpr = supervised_evaluation(classifier, x_test, y_test) xg_boost_results", "max_features=max_feature, n_jobs=7) classifier.fit(x_reduced_rp) fb, area, tnr, tpr_train, tpr_test = unsupervised_evaluation(classifier,", "model.compile(loss='binary_crossentropy', optimizer='sgd', metrics=['accuracy']) network_history = model.fit(x_train, y_train, batch_size=128, epochs=10, verbose=0,", "print('Mean loss on test: {}'.format(autoencoder.evaluate(x_test, x_test, batch_size=8, verbose=False))) print('Mean loss", "roc_auc) plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--') plt.xlim([0.0, 1.0])", "keras import regularizers from keras.models import Sequential from keras.optimizers import", "x_test, 'PCA', attack=x_attacks) x_reduced_rp, test_reduced_rp, attack_reduced_rp = reduce_dimensionality(n, x_train, x_test,", "= svm_results.append({'nu': nu, 'gamma': gamma, 'n_components': n, 'TPR_train': tpr_train, 'TPR_test':", "= [200, 100] contaminations = [0.01] dimensions = [int(i*x_test.shape[1]) for", "area = auc(fpr, tpr) return fb, area, tnr, tpr_train, tpr_test", "data classifier = svm.OneClassSVM(kernel='rbf', gamma=gamma, nu=nu, cache_size=7000) classifier.fit(x_reduced_pca) fb, area,", "= [x_train_red.shape[1], 2*x_train_red.shape[1], x_train_red.shape[1]/2, 'auto'] for nu in nus: for", "= auc(fpr, tpr) return fb, area, tnr, tpr_train, tpr_test def", "= reduce_dimensionality(n, x_train, x_test, 'RP') for lr in learning_rates: classifier", "None train = matrix.fit_transform(train) test = matrix.transform(test) if attack is", "learning_rates = [0.55] dimensions = [int(i*x_test.shape[1]) for i in [1]]", "[int(i*x_test.shape[1]) for i in [1]] for n in dimensions: x_reduced_pca,", "Input(shape=(x_train.shape[1],)) encoded = Dense(latent_dim, activation='relu')(input_vector) decoded = Dense(x_train.shape[1], activity_regularizer=regularizers.l1(10e-5))(encoded) autoencoder", "test_reduced_rp, attack_reduced_rp = reduce_dimensionality(n, x_train, x_test, 'RP', attack=x_attacks) max_features =", "= Dense(latent_dim, activation='relu')(input_vector) decoded = Dense(x_train.shape[1], activity_regularizer=regularizers.l1(10e-5))(encoded) autoencoder = Model(input_vector,", "x_test, y_test, title, nn=False): y_pred = classifier.predict(x_test) fpr, tpr, _", "'RP'}, ignore_index=True) return svm_results def xg_boost(x_train, y_train, x_test, y_test, xg_boost_results):", "= supervised_evaluation(classifier, test_reduced_rp, y_test) ada_boost_results = ada_boost_results.append({'LR': lr, 'n_components': n,", "model.add(Dense(128, kernel_initializer='glorot_uniform', activation='tanh')) model.add(Dropout(0.3)) model.add(Dense(1, kernel_initializer='normal', activation='sigmoid')) model.compile(loss='binary_crossentropy', optimizer='sgd', metrics=['accuracy'])", "svm_results.append({ 'n_components': n, 'TPR': tpr, 'TNR': tnr, 'model': 'svm', 'auc':", "tpr, _ = roc_curve(y_test, y_pred) if nn: y_pred = [round(x[0])", "area, tnr, tpr = supervised_evaluation(classifier, x_test, y_test) random_forest_results = random_forest_results.append({'estimators':", "cache_size=7000) classifier.fit(x_reduced_pca) fb, area, tnr, tpr_train, tpr_test = unsupervised_evaluation(classifier, x_reduced_pca,", "= Dense(x_train.shape[1], activity_regularizer=regularizers.l1(10e-5))(encoded) autoencoder = Model(input_vector, decoded) encoder = Model(input_vector,", "curve (area = %0.2f)' % roc_auc) plt.plot([0, 1], [0, 1],", "plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.05]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate')", "plt from keras.layers import Dense, Input, Dropout from keras.models import", "beta=beta, pos_label=1) tnr = n_accurate_outliers/attack_set.shape[0] tpr_test = n_accurate_test/test_set.shape[0] tpr_train =", "dimensions = list(filter(lambda x: x > 0, dimensions)) for n", "= tpr[1] tnr = 1 - fpr[1] return fb, area,", "area, 'f_beta': fb, 'projection': 'PCA'}, ignore_index=True) classifier = AdaBoostClassifier(learning_rate=lr) classifier.fit(x_reduced_rp,", "attack_reduced_rp) isolation_results = isolation_results.append({'estimators': estimator, 'contamination': contamination, 'n_components': n, 'max_features':", "area = auc(fpr, tpr) tpr = tpr[1] tnr = 1", "= classifier.predict(test) y_pred_outliers = classifier.predict(attacks) fpr, tpr, _ = roc_curve(np.concatenate([np.ones(y_pred_test.shape[0]),", "contamination=contamination, max_features=max_feature, n_jobs=7) classifier.fit(x_reduced_pca) fb, area, tnr, tpr_train, tpr_test =", "y_test, beta=20, nn=False): if not nn: y_pred = classifier.predict(x_test) confusion_matrix(y_test,", "RandomForestClassifier(n_estimators=estimator, n_jobs=7) classifier.fit(x_train, y_train) fb, area, tnr, tpr = supervised_evaluation(classifier,", "from sklearn.ensemble import IsolationForest import matplotlib.pyplot as plt from keras.layers", "y_train) fb, area, tnr, tpr = supervised_evaluation(classifier, test_reduced_rp, y_test) ada_boost_results", "== 1].size n_accurate_outliers = y_pred_outliers[y_pred_outliers == -1].size fpr, tpr, _", "plt.ylim([0.0, 1.05]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('Receiver operating", "'ada_boost', 'auc': area, 'f_beta': fb, 'projection': 'PCA'}, ignore_index=True) classifier =", "'gamma': gamma, 'n_components': n, 'TPR_train': tpr_train, 'TPR_test': tpr_test, 'TNR': tnr,", "tpr_train, 'TPR_test': tpr_test, 'TNR': tnr, 'model': 'isolation_forest', 'auc': area, 'f_beta':", "'TPR_train': tpr_train, 'TPR_test': tpr_test, 'TNR': tnr, 'model': 'isolation_forest', 'auc': area,", "fbeta_score(np.concatenate([np.ones(y_pred_test.shape[0]), -1*np.ones(y_pred_outliers.shape[0])]), np.concatenate([y_pred_test, y_pred_outliers]), beta=beta, pos_label=1) tnr = n_accurate_outliers/attack_set.shape[0] tpr_test", "'f_beta': fb, 'projection': 'RP'}, ignore_index=True) return ada_boost_results def svm_classifier(x_train, y_train,", "= xgb.XGBClassifier() grid = {'max_depth': 10} classifier.set_params(**grid) classifier.fit(x_reduced_rp, y_train) fb,", "Dense(latent_dim, activation='relu')(input_vector) decoded = Dense(x_train.shape[1], activity_regularizer=regularizers.l1(10e-5))(encoded) autoencoder = Model(input_vector, decoded)", "tnr, tpr = supervised_evaluation(classifier, x_test, y_test) random_forest_results = random_forest_results.append({'estimators': estimator,", "classifier.predict(attacks) fpr, tpr, _ = roc_curve(np.concatenate([np.ones(y_pred_test.shape[0]), -1*np.ones(y_pred_outliers.shape[0])]), np.concatenate([y_pred_test, y_pred_outliers]), pos_label=1)", "gammas: # Fit classifier with PCA reduced data classifier =", "fb, area, tnr, tpr = supervised_evaluation(classifier, test_reduced_rp, y_test) ada_boost_results =", "method == 'PCA': matrix = PCA(n_components=n_components) elif method == 'RP':", "_ = roc_curve(y_test, y_pred) fb = fbeta_score(y_test, y_pred, beta=beta, pos_label=1)", "import fbeta_score, roc_curve, auc, confusion_matrix from sklearn.decomposition import PCA from", "y_pred_outliers[y_pred_outliers == -1].size fpr, tpr, _ = roc_curve(np.concatenate([np.ones(y_pred_test.shape[0]), -1*np.ones(y_pred_outliers.shape[0])]), np.concatenate([y_pred_test,", "reduce_dimensionality(n, x_train, x_test, 'PCA', attack=x_attacks) x_reduced_rp, test_reduced_rp, attack_reduced_rp = reduce_dimensionality(n,", "xgb.XGBClassifier() grid = {'max_depth': 10} classifier.set_params(**grid) classifier.fit(x_reduced_rp, y_train) fb, area,", "area, 'f_beta': fb, 'projection': 'None'}, ignore_index=True) return random_forest_results def ada_boost(x_train,", "area, 'f_beta': fb, 'projection': 'RP'}, ignore_index=True) classifier = xgb.XGBClassifier() grid", "_ = roc_curve(y_test, y_pred) if nn: y_pred = [round(x[0]) for", "test_reduced_pca = reduce_dimensionality(n, x_train, x_test, 'PCA') x_reduced_rp, test_reduced_rp = reduce_dimensionality(n,", "= isolation_results.append({'estimators': estimator, 'contamination': contamination, 'n_components': n, 'max_features': max_feature, 'TPR_train':", "tpr_train, 'TPR_test': tpr_test, 'TNR': tnr, 'model': 'svm', 'auc': area, 'f_beta':", "nu=nu, cache_size=7000) classifier.fit(x_reduced_pca) fb, area, tnr, tpr_train, tpr_test = unsupervised_evaluation(classifier,", "'model': 'random_forest', 'auc': area, 'f_beta': fb, 'projection': 'None'}, ignore_index=True) return", "on attacks: {}'.format(autoencoder.evaluate(x_attacks, x_attacks, batch_size=8, verbose=False))) x_train_red = encoder.predict(x_train, batch_size=8)", "'projection': 'RP'}, ignore_index=True) return svm_results def xg_boost(x_train, y_train, x_test, y_test,", "xg_boost_results.append({ 'n_components': n, 'TPR': tpr, 'TNR': tnr, 'model': 'xgboost', 'auc':", "RP or PCA') return None train = matrix.fit_transform(train) test =", "Rate') plt.title('Receiver operating characteristic {}'.format(title)) plt.legend(loc='lower right') plt.show() def plot_history(network_history,", "n_accurate_outliers/attack_set.shape[0] tpr_test = n_accurate_test/test_set.shape[0] tpr_train = n_accurate_train/train_set.shape[0] area = auc(fpr,", "print('unknown projection method, choose either RP or PCA') return None", "n_accurate_train = y_pred_train[y_pred_train == 1].size n_accurate_test = y_pred_test[y_pred_test == 1].size", "fb, area, tnr, tpr = supervised_evaluation(classifier, test_reduced_rp, y_test) xg_boost_results =", "gamma=gamma, nu=nu, cache_size=7000) classifier.fit(x_train) fb, area, tnr, tpr_train, tpr_test =", "test_reduced_rp = reduce_dimensionality(n, x_train, x_test, 'RP') classifier = svm.SVC(gamma='auto', cache_size=7000)", "ignore_index=True) return ada_boost_results def svm_classifier(x_train, y_train, x_test, y_test, svm_results): #", "'random_forest', 'auc': area, 'f_beta': fb, 'projection': 'PCA'}, ignore_index=True) classifier =", "input_vector = Input(shape=(x_train.shape[1],)) encoded = Dense(latent_dim, activation='relu')(input_vector) decoded = Dense(x_train.shape[1],", "ignore_index=True) classifier = IsolationForest(n_estimators=estimator, contamination=contamination, max_features=max_feature, n_jobs=7) classifier.fit(x_reduced_rp) fb, area,", "model def random_forest(x_train, y_train, x_test, y_test, random_forest_results): # Random forest", "= encoder.predict(x_test, batch_size=8) x_attacks_red = encoder.predict(x_attacks, batch_size=8) nus = [0.01]", "'RP') classifier = svm.SVC(gamma='auto', cache_size=7000) classifier.fit(x_reduced_pca, y_train) fb, area, tnr,", "tnr, 'model': 'ae-svm', 'auc': area, 'f_beta': fb}, ignore_index=True) return ae_svm_results", "plt.legend(['Training', 'Validation'], loc='lower right') plt.show() def reduce_dimensionality(n_components, train, test, method,", "in gammas: # Fit classifier with PCA reduced data classifier", "model.add(Dropout(0.4)) model.add(Dense(64, kernel_initializer='glorot_uniform', activation='tanh')) model.add(Dropout(0.5)) model.add(Dense(32, kernel_initializer='glorot_uniform', activation='tanh')) model.add(Dropout(0.4)) model.add(Dense(128,", "'PCA'}, ignore_index=True) classifier = svm.SVC(gamma='auto', cache_size=7000) classifier.fit(x_reduced_rp, y_train) fb, area,", "-1*np.ones(y_pred_outliers.shape[0])]), np.concatenate([y_pred_test, y_pred_outliers]), pos_label=1) roc_auc = auc(fpr, tpr) plt.figure() lw", "'Validation'], loc='lower right') plt.show() def reduce_dimensionality(n_components, train, test, method, attack=None):", "random_projection.SparseRandomProjection(n_components=n_components, random_state=7) else: print('unknown projection method, choose either RP or", "print('Mean loss on attacks: {}'.format(autoencoder.evaluate(x_attacks, x_attacks, batch_size=8, verbose=False))) x_train_red =", "sklearn import svm from sklearn.ensemble import IsolationForest import matplotlib.pyplot as", "return fb, area, tnr, tpr_train, tpr_test def neural_network(x_train, y_train, x_test,", "= supervised_evaluation(classifier, test_reduced_pca, y_test) random_forest_results = random_forest_results.append({'estimators': estimator, 'n_components': n,", "= 1 - fpr[1] return fb, area, tnr, tpr def", "in contaminations: for max_feature in max_features: classifier = IsolationForest(n_estimators=estimator, contamination=contamination,", "'auc': area, 'f_beta': fb, 'projection': 'RP'}, ignore_index=True) classifier = RandomForestClassifier(n_estimators=estimator,", "nn=False): if not nn: y_pred = classifier.predict(x_test) confusion_matrix(y_test, y_pred) fpr,", "x_test, 'RP') classifier = svm.SVC(gamma='auto', cache_size=7000) classifier.fit(x_reduced_pca, y_train) fb, area,", "'auc': area, 'f_beta': fb, 'projection': 'RP'}, ignore_index=True) return isolation_results def", "plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('Receiver operating characteristic: {}'.format(title))", "attack_reduced_pca = reduce_dimensionality(n, x_train, x_test, 'PCA', attack=x_attacks) for nu in", "'PCA'}, ignore_index=True) classifier = RandomForestClassifier(n_estimators=estimator, n_jobs=7) classifier.fit(x_reduced_rp, y_train) fb, area,", "from sklearn.decomposition import PCA from sklearn import random_projection from sklearn", "Dense(x_train.shape[1], activity_regularizer=regularizers.l1(10e-5))(encoded) autoencoder = Model(input_vector, decoded) encoder = Model(input_vector, encoded)", "latent_dim = 3 input_vector = Input(shape=(x_train.shape[1],)) encoded = Dense(latent_dim, activation='relu')(input_vector)", "x_train_red = encoder.predict(x_train, batch_size=8) x_test_red = encoder.predict(x_test, batch_size=8) x_attacks_red =", "nn=False): y_pred = classifier.predict(x_test) fpr, tpr, _ = roc_curve(y_test, y_pred)", "y_train, x_test, y_test): model = Sequential() model.add(Dense(128, input_shape=(x_train.shape[1],), activation='relu', kernel_regularizer=l2(0.01)))", "'f_beta': fb, 'projection': 'RP'}, ignore_index=True) classifier = RandomForestClassifier(n_estimators=estimator, n_jobs=7) classifier.fit(x_train,", "model = Sequential() model.add(Dense(128, input_shape=(x_train.shape[1],), activation='relu', kernel_regularizer=l2(0.01))) model.add(Dropout(0.1)) model.add(Dense(64, activation='relu',", "['auto'] dimensions = [int(i*x_test.shape[1]) for i in [0.25, 0.35, 0.5,", "supervised_evaluation(classifier, x_test, y_test) xg_boost_results = xg_boost_results.append({ 'n_components': x_test.shape[1], 'TPR': tpr,", "plt.xlabel('Epochs') plt.ylabel('Loss') plt.semilogy(network_history.history['loss']) plt.semilogy(network_history.history['val_loss']) plt.legend(['Training', 'Validation']) plt.show() def plot_history_with_acc(network_history, title='Loss", "isolation_results def autoencoder(x_train, x_test, x_attacks, ae_svm_results): latent_dim = 3 input_vector", "x_test, x_attacks, ae_svm_results): latent_dim = 3 input_vector = Input(shape=(x_train.shape[1],)) encoded", "1].size n_accurate_outliers = y_pred_outliers[y_pred_outliers == -1].size fpr, tpr, _ =", "x_test, y_test, beta=20, nn=False): if not nn: y_pred = classifier.predict(x_test)", "tpr_test = unsupervised_evaluation(classifier, x_train, x_test, x_attacks) svm_results = svm_results.append({'nu': nu,", "gamma, 'n_components': n, 'TPR_train': tpr_train, 'TPR_test': tpr_test, 'TNR': tnr, 'model':", "plt.semilogy(network_history.history['loss']) plt.semilogy(network_history.history['val_loss']) plt.legend(['Training', 'Validation']) plt.show() def plot_history_with_acc(network_history, title='Loss and Accuracy'):", "ae_svm_results def unsupervised_evaluation(classifier, train_set, test_set, attack_set, beta=20): y_pred_train = classifier.predict(train_set)", "auc(fpr, tpr) tpr = tpr[1] tnr = 1 - fpr[1]", "sklearn.ensemble import IsolationForest import matplotlib.pyplot as plt from keras.layers import", "Fit classifier with PCA reduced data classifier = svm.OneClassSVM(kernel='rbf', gamma=gamma,", "= n_accurate_outliers/attack_set.shape[0] tpr_test = n_accurate_test/test_set.shape[0] tpr_train = n_accurate_train/train_set.shape[0] area =", "tnr, 'model': 'isolation_forest', 'auc': area, 'f_beta': fb, 'projection': 'PCA'}, ignore_index=True)", "= 3 input_vector = Input(shape=(x_train.shape[1],)) encoded = Dense(latent_dim, activation='relu')(input_vector) decoded", "supervised_evaluation(classifier, test_reduced_rp, y_test) ada_boost_results = ada_boost_results.append({'LR': lr, 'n_components': n, 'TPR':", "encoded = Dense(latent_dim, activation='relu')(input_vector) decoded = Dense(x_train.shape[1], activity_regularizer=regularizers.l1(10e-5))(encoded) autoencoder =", "= supervised_evaluation(classifier, x_test, y_test) xg_boost_results = xg_boost_results.append({ 'n_components': x_test.shape[1], 'TPR':", "sklearn import random_projection from sklearn import svm from sklearn.ensemble import", "import l2 from sklearn.ensemble import RandomForestClassifier from sklearn.ensemble import AdaBoostClassifier", "unsupervised_evaluation(classifier, train_set, test_set, attack_set, beta=20): y_pred_train = classifier.predict(train_set) y_pred_test =", "'f_beta': fb, 'projection': 'RP'}, ignore_index=True) return svm_results def xg_boost(x_train, y_train,", "= autoencoder.fit(x_train, x_train, shuffle=True, batch_size=16, epochs=10, validation_data=(x_test, x_test), verbose=True) plot_history(network_history,", "tpr, _ = roc_curve(np.concatenate([np.ones(y_pred_test.shape[0]), -1*np.ones(y_pred_outliers.shape[0])]), np.concatenate([y_pred_test, y_pred_outliers]), pos_label=1) roc_auc =", "PCA(n_components=n_components) elif method == 'RP': matrix = random_projection.SparseRandomProjection(n_components=n_components, random_state=7) else:", "one_class_svm(x_train, x_test, x_attacks, svm_results): # SVM Hyper-parameters nus = [0.01]", "def plot_history_with_acc(network_history, title='Loss and Accuracy'): plt.figure(figsize=(15, 10)) plt.subplot(211) plt.title(title) plt.xlabel('Epochs')", "test, method, attack=None): if method == 'PCA': matrix = PCA(n_components=n_components)", "'auc': area, 'f_beta': fb, 'projection': 'PCA'}, ignore_index=True) classifier = xgb.XGBClassifier()", "supervised_evaluation(classifier, test_reduced_pca, y_test) random_forest_results = random_forest_results.append({'estimators': estimator, 'n_components': n, 'TPR':", "tnr, tpr_train, tpr_test = unsupervised_evaluation(classifier, x_train, x_test, x_attacks) svm_results =", "tpr_test, 'TNR': tnr, 'model': 'ae-svm', 'auc': area, 'f_beta': fb}, ignore_index=True)", "PCA') return None train = matrix.fit_transform(train) test = matrix.transform(test) if", "np from sklearn.metrics import fbeta_score, roc_curve, auc, confusion_matrix from sklearn.decomposition", "y_test) xg_boost_results = xg_boost_results.append({ 'n_components': n, 'TPR': tpr, 'TNR': tnr,", "attack is None: return train, test attack = matrix.transform(attack) return", "as plt from keras.layers import Dense, Input, Dropout from keras.models", "'TPR_test': tpr_test, 'TNR': tnr, 'model': 'isolation_forest', 'auc': area, 'f_beta': fb,", "test_reduced_pca, attack_reduced_pca = reduce_dimensionality(n, x_train, x_test, 'PCA', attack=x_attacks) x_reduced_rp, test_reduced_rp,", "activation='relu', kernel_regularizer=l2(0.01))) model.add(Dropout(0.2)) model.add(Dense(128, kernel_initializer='glorot_uniform', activation='sigmoid')) model.add(Dropout(0.4)) model.add(Dense(64, kernel_initializer='glorot_uniform', activation='tanh'))", "fb, 'projection': 'RP'}, ignore_index=True) classifier = RandomForestClassifier(n_estimators=estimator, n_jobs=7) classifier.fit(x_train, y_train)", "n_accurate_outliers = y_pred_outliers[y_pred_outliers == -1].size fpr, tpr, _ = roc_curve(np.concatenate([np.ones(y_pred_test.shape[0]),", "classifier.fit(x_train, y_train) fb, area, tnr, tpr = supervised_evaluation(classifier, x_test, y_test)", "random_forest_results.append({'estimators': estimator, 'n_components': x_test.shape[1], 'TPR': tpr, 'TNR': tnr, 'model': 'random_forest',", "random_forest_results def ada_boost(x_train, y_train, x_test, y_test, ada_boost_results): # AdaBoost Hyper-parameters", "supervised_evaluation(classifier, test_reduced_rp, y_test) svm_results = svm_results.append({ 'n_components': n, 'TPR': tpr,", "-1*np.ones(y_pred_outliers.shape[0])]), np.concatenate([y_pred_test, y_pred_outliers]), pos_label=1) fb = fbeta_score(np.concatenate([np.ones(y_pred_test.shape[0]), -1*np.ones(y_pred_outliers.shape[0])]), np.concatenate([y_pred_test, y_pred_outliers]),", "x_test, y_test, svm_results): # SVC Hyper-parameters dimensions = [int(i*x_test.shape[1]) for", "= {'max_depth': 10} classifier.set_params(**grid) classifier.fit(x_reduced_pca, y_train) fb, area, tnr, tpr", "= IsolationForest(n_estimators=estimator, contamination=contamination, max_features=max_feature, n_jobs=7) classifier.fit(x_reduced_rp) fb, area, tnr, tpr_train,", "'svm', 'auc': area, 'f_beta': fb, 'projection': 'RP'}, ignore_index=True) return svm_results", "1.05]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('Receiver operating characteristic:", "print(confusion_matrix(y_test, y_pred)) roc_auc = auc(fpr, tpr) plt.figure() lw = 2", "'TNR': tnr, 'model': 'ae-svm', 'auc': area, 'f_beta': fb}, ignore_index=True) return", "tnr, 'model': 'ada_boost', 'auc': area, 'f_beta': fb, 'projection': 'RP'}, ignore_index=True)", "= unsupervised_evaluation(classifier, x_reduced_pca, test_reduced_pca, attack_reduced_pca) svm_results = svm_results.append({'nu': nu, 'gamma':", "tnr, tpr = supervised_evaluation(classifier, test_reduced_pca, y_test) xg_boost_results = xg_boost_results.append({ 'n_components':", "n_jobs=7) classifier.fit(x_reduced_rp) fb, area, tnr, tpr_train, tpr_test = unsupervised_evaluation(classifier, x_reduced_rp,", "plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('Receiver operating characteristic {}'.format(title))", "Sequential() model.add(Dense(128, input_shape=(x_train.shape[1],), activation='relu', kernel_regularizer=l2(0.01))) model.add(Dropout(0.1)) model.add(Dense(64, activation='relu', kernel_regularizer=l2(0.01))) model.add(Dropout(0.2))", "y_train) fb, area, tnr, tpr = supervised_evaluation(classifier, test_reduced_rp, y_test) random_forest_results", "'RP'}, ignore_index=True) classifier = xgb.XGBClassifier() grid = {'max_depth': 10} classifier.set_params(**grid)", "plt.xlabel('Epochs') plt.ylabel('Accuracy') plt.plot(network_history.history['acc']) plt.plot(network_history.history['val_acc']) plt.legend(['Training', 'Validation'], loc='lower right') plt.show() def", "import svm from sklearn.ensemble import IsolationForest import matplotlib.pyplot as plt", "'model': 'svm', 'auc': area, 'f_beta': fb, 'projection': 'None'}, ignore_index=True) return", "autoencoder(x_train, x_test, x_attacks, ae_svm_results): latent_dim = 3 input_vector = Input(shape=(x_train.shape[1],))", "for n in dimensions: x_reduced_pca, test_reduced_pca, attack_reduced_pca = reduce_dimensionality(n, x_train,", "= xg_boost_results.append({ 'n_components': x_test.shape[1], 'TPR': tpr, 'TNR': tnr, 'model': 'xgboost',", "svm from sklearn.ensemble import IsolationForest import matplotlib.pyplot as plt from", "in estimators: for n in dimensions: x_reduced_pca, test_reduced_pca = reduce_dimensionality(n,", "1], [0, 1], color='navy', lw=lw, linestyle='--') plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.05])", "3 input_vector = Input(shape=(x_train.shape[1],)) encoded = Dense(latent_dim, activation='relu')(input_vector) decoded =", "x_train, x_test, 'RP', attack=x_attacks) max_features = list(range(1, n + 1,", "= reduce_dimensionality(n, x_train, x_test, 'PCA', attack=x_attacks) x_reduced_rp, test_reduced_rp, attack_reduced_rp =", "== 'RP': matrix = random_projection.SparseRandomProjection(n_components=n_components, random_state=7) else: print('unknown projection method,", "gammas = [x_train_red.shape[1], 2*x_train_red.shape[1], x_train_red.shape[1]/2, 'auto'] for nu in nus:", "plt.ylabel('True Positive Rate') plt.title('Receiver operating characteristic: {}'.format(title)) plt.legend(loc='lower right') plt.show()", "neural_network(x_train, y_train, x_test, y_test): model = Sequential() model.add(Dense(128, input_shape=(x_train.shape[1],), activation='relu',", "n, 'TPR': tpr, 'TNR': tnr, 'model': 'svm', 'auc': area, 'f_beta':", "x_train, x_test, 'RP') classifier = RandomForestClassifier(n_estimators=estimator, n_jobs=7) classifier.fit(x_reduced_pca, y_train) fb,", "= roc_curve(y_test, y_pred) fb = fbeta_score(y_test, y_pred, beta=beta, pos_label=1) area", "[0.01] gammas = ['auto'] dimensions = [int(i*x_test.shape[1]) for i in", "ignore_index=True) classifier = AdaBoostClassifier(learning_rate=lr) classifier.fit(x_reduced_rp, y_train) fb, area, tnr, tpr", "gammas = ['auto'] dimensions = [int(i*x_test.shape[1]) for i in [0.25,", "y_pred_outliers]), pos_label=1) roc_auc = auc(fpr, tpr) plt.figure() lw = 2", "tpr = supervised_evaluation(classifier, test_reduced_pca, y_test) ada_boost_results = ada_boost_results.append({'LR': lr, 'n_components':", "'auto'] for nu in nus: for gamma in gammas: classifier", "plt.plot(network_history.history['val_acc']) plt.legend(['Training', 'Validation'], loc='lower right') plt.show() def reduce_dimensionality(n_components, train, test,", "sklearn.ensemble import RandomForestClassifier from sklearn.ensemble import AdaBoostClassifier import xgboost as", "reduced data classifier = svm.OneClassSVM(kernel='rbf', gamma=gamma, nu=nu, cache_size=7000) classifier.fit(x_reduced_pca) fb,", "'projection': 'RP'}, ignore_index=True) classifier = xgb.XGBClassifier() grid = {'max_depth': 10}", "cache_size=7000) classifier.fit(x_train_red) fb, area, tnr, tpr_train, tpr_test = unsupervised_evaluation(classifier, x_train_red,", "random_forest_results): # Random forest Hyper-parameters estimators = [150, 200] dimensions", "'model': 'isolation_forest', 'auc': area, 'f_beta': fb, 'projection': 'PCA'}, ignore_index=True) classifier", "dimensions = [int(i*x_test.shape[1]) for i in [0.25, 0.5, 0.9, 1]]", "fpr, tpr, _ = roc_curve(np.concatenate([np.ones(y_pred_test.shape[0]), -1*np.ones(y_pred_outliers.shape[0])]), np.concatenate([y_pred_test, y_pred_outliers]), pos_label=1) fb", "x_attacks, svm_results): # SVM Hyper-parameters nus = [0.01] gammas =", "[1]] for estimator in estimators: for n in dimensions: x_reduced_pca,", "n, 'max_features': max_feature, 'TPR_train': tpr_train, 'TPR_test': tpr_test, 'TNR': tnr, 'model':", "test_reduced_pca, y_test) random_forest_results = random_forest_results.append({'estimators': estimator, 'n_components': n, 'TPR': tpr,", "y_pred) fb = fbeta_score(y_test, y_pred, beta=beta, pos_label=1) area = auc(fpr,", "'f_beta': fb, 'projection': 'RP'}, ignore_index=True) return isolation_results def autoencoder(x_train, x_test,", "x_reduced_pca, test_reduced_pca = reduce_dimensionality(n, x_train, x_test, 'PCA') x_reduced_rp, test_reduced_rp =", "fb, area, tnr, tpr = supervised_evaluation(classifier, test_reduced_pca, y_test) random_forest_results =", "contamination=contamination, max_features=max_feature, n_jobs=7) classifier.fit(x_reduced_rp) fb, area, tnr, tpr_train, tpr_test =", "= fbeta_score(y_test, y_pred, beta=beta, pos_label=1) area = auc(fpr, tpr) tpr", "classifier.predict(train_set) y_pred_test = classifier.predict(test_set) y_pred_outliers = classifier.predict(attack_set) n_accurate_train = y_pred_train[y_pred_train", "train_set, test_set, attack_set, beta=20): y_pred_train = classifier.predict(train_set) y_pred_test = classifier.predict(test_set)", "operating characteristic {}'.format(title)) plt.legend(loc='lower right') plt.show() def plot_history(network_history, title): plt.figure(figsize=(10,", "test_reduced_pca, attack_reduced_pca = reduce_dimensionality(n, x_train, x_test, 'PCA', attack=x_attacks) for nu", "tnr, tpr = supervised_evaluation(classifier, test_reduced_rp, y_test) random_forest_results = random_forest_results.append({'estimators': estimator,", "= reduce_dimensionality(n, x_train, x_test, 'PCA', attack=x_attacks) for nu in nus:", "= classifier.predict(train_set) y_pred_test = classifier.predict(test_set) y_pred_outliers = classifier.predict(attack_set) n_accurate_train =", "AdaBoostClassifier(learning_rate=lr) classifier.fit(x_reduced_rp, y_train) fb, area, tnr, tpr = supervised_evaluation(classifier, test_reduced_rp,", "classifier = RandomForestClassifier(n_estimators=estimator, n_jobs=7) classifier.fit(x_reduced_pca, y_train) fb, area, tnr, tpr", "'projection': 'None'}, ignore_index=True) return svm_results def isolation_forest(x_train, x_test, x_attacks, isolation_results):", "'projection': 'PCA'}, ignore_index=True) classifier = svm.SVC(gamma='auto', cache_size=7000) classifier.fit(x_reduced_rp, y_train) fb,", "svm_results.append({'nu': nu, 'gamma': gamma, 'n_components': n, 'TPR_train': tpr_train, 'TPR_test': tpr_test,", "model.add(Dense(64, activation='relu', kernel_regularizer=l2(0.01))) model.add(Dropout(0.2)) model.add(Dense(128, kernel_initializer='glorot_uniform', activation='sigmoid')) model.add(Dropout(0.4)) model.add(Dense(64, kernel_initializer='glorot_uniform',", "x_test, y_test, xg_boost_results): # XGBoost Hyper-parameters dimensions = [int(i*x_test.shape[1]) for", "_ = roc_curve(np.concatenate([np.ones(y_pred_test.shape[0]), -1*np.ones(y_pred_outliers.shape[0])]), np.concatenate([y_pred_test, y_pred_outliers]), pos_label=1) roc_auc = auc(fpr,", "= [int(i*x_test.shape[1]) for i in [1]] for n in dimensions:", "tpr_train, tpr_test = unsupervised_evaluation(classifier, x_train, x_test, x_attacks) svm_results = svm_results.append({'nu':", "reduce_dimensionality(n, x_train, x_test, 'PCA') x_reduced_rp, test_reduced_rp = reduce_dimensionality(n, x_train, x_test,", "= svm.SVC(gamma='auto', cache_size=7000) classifier.fit(x_reduced_pca, y_train) fb, area, tnr, tpr =", "'auc': area, 'f_beta': fb, 'projection': 'PCA'}, ignore_index=True) classifier = svm.SVC(gamma='auto',", "y_pred_train[y_pred_train == 1].size n_accurate_test = y_pred_test[y_pred_test == 1].size n_accurate_outliers =", "import matplotlib.pyplot as plt from keras.layers import Dense, Input, Dropout", "[0.55] dimensions = [int(i*x_test.shape[1]) for i in [1]] for n", "= xg_boost_results.append({ 'n_components': n, 'TPR': tpr, 'TNR': tnr, 'model': 'xgboost',", "grid = {'max_depth': 10} classifier.set_params(**grid) classifier.fit(x_reduced_pca, y_train) fb, area, tnr,", "beta=20): y_pred_train = classifier.predict(train_set) y_pred_test = classifier.predict(test_set) y_pred_outliers = classifier.predict(attack_set)", "10} classifier.set_params(**grid) classifier.fit(x_reduced_rp, y_train) fb, area, tnr, tpr = supervised_evaluation(classifier,", "nu, 'gamma': gamma, 'n_components': x_test.shape[1], 'TPR_train': tpr_train, 'TPR_test': tpr_test, 'TNR':", "'f_beta': fb, 'projection': 'PCA'}, ignore_index=True) classifier = xgb.XGBClassifier() grid =", "RandomForestClassifier from sklearn.ensemble import AdaBoostClassifier import xgboost as xgb def", "'projection': 'RP'}, ignore_index=True) classifier = RandomForestClassifier(n_estimators=estimator, n_jobs=7) classifier.fit(x_train, y_train) fb,", "dimensions = [int(i*x_test.shape[1]) for i in [1]] for n in", "svm.SVC(gamma='auto', cache_size=7000) classifier.fit(x_reduced_rp, y_train) fb, area, tnr, tpr = supervised_evaluation(classifier,", "area, tnr, tpr = supervised_evaluation(classifier, test_reduced_rp, y_test) svm_results = svm_results.append({", "attack=x_attacks) x_reduced_rp, test_reduced_rp, attack_reduced_rp = reduce_dimensionality(n, x_train, x_test, 'RP', attack=x_attacks)", "x_attacks) svm_results = svm_results.append({'nu': nu, 'gamma': gamma, 'n_components': x_test.shape[1], 'TPR_train':", "+ 1, 4)) for estimator in estimators: for contamination in", "for gamma in gammas: classifier = svm.OneClassSVM(kernel='rbf', gamma=gamma, nu=nu, cache_size=7000)", "supervised_evaluation(classifier, x_test, y_test) random_forest_results = random_forest_results.append({'estimators': estimator, 'n_components': x_test.shape[1], 'TPR':", "reduce_dimensionality(n, x_train, x_test, 'RP', attack=x_attacks) max_features = list(range(1, n +", "x_train, x_test, 'RP') classifier = svm.SVC(gamma='auto', cache_size=7000) classifier.fit(x_reduced_pca, y_train) fb,", "dimensions = [int(i*x_test.shape[1]) for i in [1]] for estimator in", "PCA reduced data classifier = svm.OneClassSVM(kernel='rbf', gamma=gamma, nu=nu, cache_size=7000) classifier.fit(x_reduced_pca)", "with RP reduced data classifier = svm.OneClassSVM(kernel='rbf', gamma=gamma, nu=nu, cache_size=7000)", "numpy as np from sklearn.metrics import fbeta_score, roc_curve, auc, confusion_matrix", "isolation_results = isolation_results.append({'estimators': estimator, 'contamination': contamination, 'n_components': n, 'max_features': max_feature,", "x_attacks_red) ae_svm_results = ae_svm_results.append({'nu': nu, 'gamma': gamma, 'n_components': latent_dim, 'TPR_train':", "nn: y_pred = [round(x[0]) for x in y_pred] print(confusion_matrix(y_test, y_pred))", "= model.fit(x_train, y_train, batch_size=128, epochs=10, verbose=0, validation_data=(x_test, y_test)) plot_history_with_acc(network_history) return", "'svm', 'auc': area, 'f_beta': fb, 'projection': 'PCA'}, ignore_index=True) classifier =", "= matrix.transform(test) if attack is None: return train, test attack", "Isolation Forest Hyper-parameters estimators = [200, 100] contaminations = [0.01]", "y_train, x_test, y_test, ada_boost_results): # AdaBoost Hyper-parameters learning_rates = [0.55]", "verbose=False))) x_train_red = encoder.predict(x_train, batch_size=8) x_test_red = encoder.predict(x_test, batch_size=8) x_attacks_red", "test_reduced_pca, y_test) ada_boost_results = ada_boost_results.append({'LR': lr, 'n_components': n, 'TPR': tpr,", "i in [1]] for estimator in estimators: for n in", "y_train, x_test, y_test, svm_results): # SVC Hyper-parameters dimensions = [int(i*x_test.shape[1])", "roc_curve(y_test, y_pred) fb = fbeta_score(y_test, y_pred, beta=beta, pos_label=1) area =", "classifier = svm.OneClassSVM(kernel='rbf', gamma=gamma, nu=nu, cache_size=7000) classifier.fit(x_train) fb, area, tnr,", "keras.regularizers import l2 from sklearn.ensemble import RandomForestClassifier from sklearn.ensemble import", "PCA from sklearn import random_projection from sklearn import svm from", "ignore_index=True) classifier = RandomForestClassifier(n_estimators=estimator, n_jobs=7) classifier.fit(x_reduced_rp, y_train) fb, area, tnr,", "plt.ylabel('Accuracy') plt.plot(network_history.history['acc']) plt.plot(network_history.history['val_acc']) plt.legend(['Training', 'Validation'], loc='lower right') plt.show() def reduce_dimensionality(n_components,", "'RP'}, ignore_index=True) return isolation_results def autoencoder(x_train, x_test, x_attacks, ae_svm_results): latent_dim", "'RP', attack=x_attacks) max_features = list(range(1, n + 1, 4)) for", "Hyper-parameters estimators = [200, 100] contaminations = [0.01] dimensions =", "activation='tanh')) model.add(Dropout(0.4)) model.add(Dense(128, kernel_initializer='glorot_uniform', activation='tanh')) model.add(Dropout(0.3)) model.add(Dense(1, kernel_initializer='normal', activation='sigmoid')) model.compile(loss='binary_crossentropy',", "tpr_train = n_accurate_train/train_set.shape[0] area = auc(fpr, tpr) return fb, area,", "method == 'RP': matrix = random_projection.SparseRandomProjection(n_components=n_components, random_state=7) else: print('unknown projection", "4)) for estimator in estimators: for contamination in contaminations: for", "area, tnr, tpr_train, tpr_test = unsupervised_evaluation(classifier, x_reduced_rp, test_reduced_rp, attack_reduced_rp) isolation_results", "'xgboost', 'auc': area, 'f_beta': fb, 'projection': 'RP'}, ignore_index=True) classifier =", "method, choose either RP or PCA') return None train =", "return xg_boost_results def supervised_evaluation(classifier, x_test, y_test, beta=20, nn=False): if not", "ada_boost(x_train, y_train, x_test, y_test, ada_boost_results): # AdaBoost Hyper-parameters learning_rates =", "'f_beta': fb, 'projection': 'RP'}, ignore_index=True) classifier = xgb.XGBClassifier() grid =", "cache_size=7000) classifier.fit(x_reduced_rp, y_train) fb, area, tnr, tpr = supervised_evaluation(classifier, test_reduced_rp,", "tpr_train, 'TPR_test': tpr_test, 'TNR': tnr, 'model': 'ae-svm', 'auc': area, 'f_beta':", "or PCA') return None train = matrix.fit_transform(train) test = matrix.transform(test)", "(area = %0.2f)' % roc_auc) plt.plot([0, 1], [0, 1], color='navy',", "gamma in gammas: classifier = svm.OneClassSVM(kernel='rbf', gamma=gamma, nu=nu, cache_size=7000) classifier.fit(x_train_red)", "y_test, title, nn=False): y_pred = classifier.predict(x_test) fpr, tpr, _ =", "classifier = AdaBoostClassifier(learning_rate=lr) classifier.fit(x_reduced_pca, y_train) fb, area, tnr, tpr =", "loss on attacks: {}'.format(autoencoder.evaluate(x_attacks, x_attacks, batch_size=8, verbose=False))) x_train_red = encoder.predict(x_train,", "'TPR': tpr, 'TNR': tnr, 'model': 'random_forest', 'auc': area, 'f_beta': fb,", "validation_data=(x_test, y_test)) plot_history_with_acc(network_history) return model def random_forest(x_train, y_train, x_test, y_test,", "def plot_roc(classifier, test, attacks, title): y_pred_test = classifier.predict(test) y_pred_outliers =", "test_reduced_pca, attack_reduced_pca) svm_results = svm_results.append({'nu': nu, 'gamma': gamma, 'n_components': n,", "'auc': area, 'f_beta': fb, 'projection': 'None'}, ignore_index=True) return svm_results def", "== 1].size n_accurate_test = y_pred_test[y_pred_test == 1].size n_accurate_outliers = y_pred_outliers[y_pred_outliers", "AdaBoostClassifier(learning_rate=lr) classifier.fit(x_reduced_pca, y_train) fb, area, tnr, tpr = supervised_evaluation(classifier, test_reduced_pca,", "area, tnr, tpr def plot_roc(classifier, test, attacks, title): y_pred_test =", "right') plt.show() def plot_roc_supervised(classifier, x_test, y_test, title, nn=False): y_pred =", "plt.semilogy(network_history.history['val_loss']) plt.legend(['Training', 'Validation']) plt.subplot(212) plt.xlabel('Epochs') plt.ylabel('Accuracy') plt.plot(network_history.history['acc']) plt.plot(network_history.history['val_acc']) plt.legend(['Training', 'Validation'],", "def isolation_forest(x_train, x_test, x_attacks, isolation_results): # Isolation Forest Hyper-parameters estimators", "= roc_curve(np.concatenate([np.ones(y_pred_test.shape[0]), -1*np.ones(y_pred_outliers.shape[0])]), np.concatenate([y_pred_test, y_pred_outliers]), pos_label=1) roc_auc = auc(fpr, tpr)", "'projection': 'None'}, ignore_index=True) return xg_boost_results def supervised_evaluation(classifier, x_test, y_test, beta=20,", "'TNR': tnr, 'model': 'random_forest', 'auc': area, 'f_beta': fb, 'projection': 'None'},", "= list(filter(lambda x: x > 0, dimensions)) for n in", "0.35, 0.5, 0.75, 0.9, 1]] dimensions = list(filter(lambda x: x", "tpr_train, tpr_test = unsupervised_evaluation(classifier, x_train_red, x_test_red, x_attacks_red) ae_svm_results = ae_svm_results.append({'nu':", "x_test, x_attacks) svm_results = svm_results.append({'nu': nu, 'gamma': gamma, 'n_components': x_test.shape[1],", "batch_size=8) nus = [0.01] gammas = [x_train_red.shape[1], 2*x_train_red.shape[1], x_train_red.shape[1]/2, 'auto']", "y_pred = classifier.predict(x_test) fpr, tpr, _ = roc_curve(y_test, y_pred) if", "list(filter(lambda x: x > 0, dimensions)) for n in dimensions:", "n_jobs=7) classifier.fit(x_reduced_pca) fb, area, tnr, tpr_train, tpr_test = unsupervised_evaluation(classifier, x_reduced_pca,", "classifier.fit(x_train) fb, area, tnr, tpr_train, tpr_test = unsupervised_evaluation(classifier, x_train, x_test,", "area, 'f_beta': fb, 'projection': 'PCA'}, ignore_index=True) classifier = IsolationForest(n_estimators=estimator, contamination=contamination,", "max_features = list(range(1, n + 1, 4)) for estimator in", "x_train, shuffle=True, batch_size=16, epochs=10, validation_data=(x_test, x_test), verbose=True) plot_history(network_history, 'AE history')", "'n_components': n, 'TPR': tpr, 'TNR': tnr, 'model': 'svm', 'auc': area,", "fb = fbeta_score(np.concatenate([np.ones(y_pred_test.shape[0]), -1*np.ones(y_pred_outliers.shape[0])]), np.concatenate([y_pred_test, y_pred_outliers]), beta=beta, pos_label=1) tnr =", "= auc(fpr, tpr) tpr = tpr[1] tnr = 1 -", "'n_components': n, 'max_features': max_feature, 'TPR_train': tpr_train, 'TPR_test': tpr_test, 'TNR': tnr,", "n_jobs=7) classifier.fit(x_reduced_rp, y_train) fb, area, tnr, tpr = supervised_evaluation(classifier, test_reduced_rp,", "loc='lower right') plt.show() def reduce_dimensionality(n_components, train, test, method, attack=None): if", "'PCA') x_reduced_rp, test_reduced_rp = reduce_dimensionality(n, x_train, x_test, 'RP') classifier =", "= RandomForestClassifier(n_estimators=estimator, n_jobs=7) classifier.fit(x_train, y_train) fb, area, tnr, tpr =", "unsupervised_evaluation(classifier, x_reduced_rp, test_reduced_rp, attack_reduced_rp) isolation_results = isolation_results.append({'estimators': estimator, 'contamination': contamination,", "tnr, tpr = supervised_evaluation(classifier, test_reduced_pca, y_test) ada_boost_results = ada_boost_results.append({'LR': lr,", "'TPR': tpr, 'TNR': tnr, 'model': 'ada_boost', 'auc': area, 'f_beta': fb,", "fb, 'projection': 'None'}, ignore_index=True) return random_forest_results def ada_boost(x_train, y_train, x_test,", "test_reduced_rp, y_test) svm_results = svm_results.append({ 'n_components': n, 'TPR': tpr, 'TNR':", "svm_results): # SVM Hyper-parameters nus = [0.01] gammas = ['auto']", "'xgboost', 'auc': area, 'f_beta': fb, 'projection': 'None'}, ignore_index=True) return xg_boost_results", "for i in [1]] for estimator in estimators: for n", "x_test.shape[1], 'TPR_train': tpr_train, 'TPR_test': tpr_test, 'TNR': tnr, 'model': 'svm', 'auc':", "l2 from sklearn.ensemble import RandomForestClassifier from sklearn.ensemble import AdaBoostClassifier import", "shuffle=True, batch_size=16, epochs=10, validation_data=(x_test, x_test), verbose=True) plot_history(network_history, 'AE history') print('Mean", "history') print('Mean loss on train: {}'.format(autoencoder.evaluate(x_train, x_train, batch_size=8, verbose=False))) print('Mean", "'f_beta': fb, 'projection': 'PCA'}, ignore_index=True) classifier = RandomForestClassifier(n_estimators=estimator, n_jobs=7) classifier.fit(x_reduced_rp,", "'contamination': contamination, 'n_components': n, 'max_features': max_feature, 'TPR_train': tpr_train, 'TPR_test': tpr_test,", "[1]] for n in dimensions: x_reduced_pca, test_reduced_pca = reduce_dimensionality(n, x_train,", "reduce_dimensionality(n, x_train, x_test, 'RP') classifier = svm.SVC(gamma='auto', cache_size=7000) classifier.fit(x_reduced_pca, y_train)", "def reduce_dimensionality(n_components, train, test, method, attack=None): if method == 'PCA':", "'model': 'ada_boost', 'auc': area, 'f_beta': fb, 'projection': 'PCA'}, ignore_index=True) classifier", "supervised_evaluation(classifier, test_reduced_pca, y_test) xg_boost_results = xg_boost_results.append({ 'n_components': n, 'TPR': tpr,", "= y_pred_test[y_pred_test == 1].size n_accurate_outliers = y_pred_outliers[y_pred_outliers == -1].size fpr,", "plt.figure(figsize=(10, 5)) plt.title(title) plt.xlabel('Epochs') plt.ylabel('Loss') plt.semilogy(network_history.history['loss']) plt.semilogy(network_history.history['val_loss']) plt.legend(['Training', 'Validation']) plt.show()", "fb, area, tnr, tpr_train, tpr_test def neural_network(x_train, y_train, x_test, y_test):", "ada_boost_results = ada_boost_results.append({'LR': lr, 'n_components': n, 'TPR': tpr, 'TNR': tnr,", "in dimensions: x_reduced_pca, test_reduced_pca, attack_reduced_pca = reduce_dimensionality(n, x_train, x_test, 'PCA',", "classifier = RandomForestClassifier(n_estimators=estimator, n_jobs=7) classifier.fit(x_reduced_rp, y_train) fb, area, tnr, tpr", "[0.25, 0.5, 0.9, 1]] dimensions = list(filter(lambda x: x >", "tnr = n_accurate_outliers/attack_set.shape[0] tpr_test = n_accurate_test/test_set.shape[0] tpr_train = n_accurate_train/train_set.shape[0] area", "'model': 'svm', 'auc': area, 'f_beta': fb, 'projection': 'PCA'}, ignore_index=True) #", "%0.2f)' % roc_auc) plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--')", "tnr, 'model': 'xgboost', 'auc': area, 'f_beta': fb, 'projection': 'PCA'}, ignore_index=True)", "'random_forest', 'auc': area, 'f_beta': fb, 'projection': 'RP'}, ignore_index=True) classifier =", "tpr[1] tnr = 1 - fpr[1] return fb, area, tnr,", "= svm_results.append({ 'n_components': n, 'TPR': tpr, 'TNR': tnr, 'model': 'svm',", "y_pred_test[y_pred_test == 1].size n_accurate_outliers = y_pred_outliers[y_pred_outliers == -1].size fpr, tpr,", "tpr = supervised_evaluation(classifier, test_reduced_pca, y_test) svm_results = svm_results.append({ 'n_components': n,", "reduce_dimensionality(n, x_train, x_test, 'PCA', attack=x_attacks) for nu in nus: for", "classifier.fit(x_reduced_rp) fb, area, tnr, tpr_train, tpr_test = unsupervised_evaluation(classifier, x_reduced_rp, test_reduced_rp,", "in nus: for gamma in gammas: # Fit classifier with", "x_train, x_test, x_attacks) svm_results = svm_results.append({'nu': nu, 'gamma': gamma, 'n_components':", "y_train) fb, area, tnr, tpr = supervised_evaluation(classifier, test_reduced_pca, y_test) random_forest_results", "'n_components': n, 'TPR_train': tpr_train, 'TPR_test': tpr_test, 'TNR': tnr, 'model': 'svm',", "area, tnr, tpr = supervised_evaluation(classifier, x_test, y_test) xg_boost_results = xg_boost_results.append({", "- fpr[1] return fb, area, tnr, tpr def plot_roc(classifier, test,", "operating characteristic: {}'.format(title)) plt.legend(loc='lower right') plt.show() def plot_roc_supervised(classifier, x_test, y_test,", "fb, 'projection': 'RP'}, ignore_index=True) return svm_results def xg_boost(x_train, y_train, x_test,", "reduced data classifier = svm.OneClassSVM(kernel='rbf', gamma=gamma, nu=nu, cache_size=7000) classifier.fit(x_train) fb,", "'isolation_forest', 'auc': area, 'f_beta': fb, 'projection': 'PCA'}, ignore_index=True) classifier =", "if method == 'PCA': matrix = PCA(n_components=n_components) elif method ==", "return svm_results def isolation_forest(x_train, x_test, x_attacks, isolation_results): # Isolation Forest", "reduce_dimensionality(n, x_train, x_test, 'RP') for lr in learning_rates: classifier =", "return isolation_results def autoencoder(x_train, x_test, x_attacks, ae_svm_results): latent_dim = 3", "estimators: for n in dimensions: x_reduced_pca, test_reduced_pca = reduce_dimensionality(n, x_train,", "test_reduced_pca, attack_reduced_pca) isolation_results = isolation_results.append({'estimators': estimator, 'contamination': contamination, 'n_components': n,", "estimator in estimators: for contamination in contaminations: for max_feature in", "pos_label=1) fb = fbeta_score(np.concatenate([np.ones(y_pred_test.shape[0]), -1*np.ones(y_pred_outliers.shape[0])]), np.concatenate([y_pred_test, y_pred_outliers]), beta=beta, pos_label=1) tnr", "'RP'}, ignore_index=True) return ada_boost_results def svm_classifier(x_train, y_train, x_test, y_test, svm_results):", "area, tnr, tpr = supervised_evaluation(classifier, test_reduced_pca, y_test) svm_results = svm_results.append({", "tpr = supervised_evaluation(classifier, test_reduced_pca, y_test) xg_boost_results = xg_boost_results.append({ 'n_components': n,", "ignore_index=True) classifier = xgb.XGBClassifier() grid = {'max_depth': 10} classifier.set_params(**grid) classifier.fit(x_reduced_rp,", "tpr = supervised_evaluation(classifier, test_reduced_rp, y_test) xg_boost_results = xg_boost_results.append({ 'n_components': n,", "np.concatenate([y_pred_test, y_pred_outliers]), beta=beta, pos_label=1) tnr = n_accurate_outliers/attack_set.shape[0] tpr_test = n_accurate_test/test_set.shape[0]", "optimizer='sgd', metrics=['accuracy']) network_history = model.fit(x_train, y_train, batch_size=128, epochs=10, verbose=0, validation_data=(x_test,", "[200, 100] contaminations = [0.01] dimensions = [int(i*x_test.shape[1]) for i", "= reduce_dimensionality(n, x_train, x_test, 'RP', attack=x_attacks) max_features = list(range(1, n", "tnr, 'model': 'random_forest', 'auc': area, 'f_beta': fb, 'projection': 'RP'}, ignore_index=True)", "return ada_boost_results def svm_classifier(x_train, y_train, x_test, y_test, svm_results): # SVC", "= reduce_dimensionality(n, x_train, x_test, 'RP') classifier = RandomForestClassifier(n_estimators=estimator, n_jobs=7) classifier.fit(x_reduced_pca,", "Hyper-parameters learning_rates = [0.55] dimensions = [int(i*x_test.shape[1]) for i in", "network_history = model.fit(x_train, y_train, batch_size=128, epochs=10, verbose=0, validation_data=(x_test, y_test)) plot_history_with_acc(network_history)", "= supervised_evaluation(classifier, test_reduced_rp, y_test) svm_results = svm_results.append({ 'n_components': n, 'TPR':", "projection method, choose either RP or PCA') return None train", "from keras import regularizers from keras.models import Sequential from keras.optimizers", "plt.legend(['Training', 'Validation']) plt.show() def plot_history_with_acc(network_history, title='Loss and Accuracy'): plt.figure(figsize=(15, 10))", "fb, area, tnr, tpr = supervised_evaluation(classifier, test_reduced_pca, y_test) ada_boost_results =", "'f_beta': fb, 'projection': 'None'}, ignore_index=True) return xg_boost_results def supervised_evaluation(classifier, x_test,", "SVC Hyper-parameters dimensions = [int(i*x_test.shape[1]) for i in [1]] for", "verbose=0, validation_data=(x_test, y_test)) plot_history_with_acc(network_history) return model def random_forest(x_train, y_train, x_test,", "lw=lw, linestyle='--') plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.05]) plt.xlabel('False Positive Rate') plt.ylabel('True", "'TNR': tnr, 'model': 'ada_boost', 'auc': area, 'f_beta': fb, 'projection': 'PCA'},", "nu in nus: for gamma in gammas: classifier = svm.OneClassSVM(kernel='rbf',", "'TNR': tnr, 'model': 'random_forest', 'auc': area, 'f_beta': fb, 'projection': 'PCA'},", "ignore_index=True) # Fit classifier with RP reduced data classifier =", "reduce_dimensionality(n_components, train, test, method, attack=None): if method == 'PCA': matrix", "decoded) encoder = Model(input_vector, encoded) autoencoder.compile(optimizer=Adam(lr=0.001), loss='mse') network_history = autoencoder.fit(x_train,", "{'max_depth': 10} classifier.set_params(**grid) classifier.fit(x_reduced_rp, y_train) fb, area, tnr, tpr =", "lw=lw, label='ROC curve (area = %0.2f)' % roc_auc) plt.plot([0, 1],", "= classifier.predict(x_test) confusion_matrix(y_test, y_pred) fpr, tpr, _ = roc_curve(y_test, y_pred)", "y_train) fb, area, tnr, tpr = supervised_evaluation(classifier, test_reduced_pca, y_test) xg_boost_results", "kernel_regularizer=l2(0.01))) model.add(Dropout(0.1)) model.add(Dense(64, activation='relu', kernel_regularizer=l2(0.01))) model.add(Dropout(0.2)) model.add(Dense(128, kernel_initializer='glorot_uniform', activation='sigmoid')) model.add(Dropout(0.4))", "x_test, y_test, random_forest_results): # Random forest Hyper-parameters estimators = [150,", "= unsupervised_evaluation(classifier, x_train_red, x_test_red, x_attacks_red) ae_svm_results = ae_svm_results.append({'nu': nu, 'gamma':", "0.9, 1]] dimensions = list(filter(lambda x: x > 0, dimensions))", "svm_results.append({'nu': nu, 'gamma': gamma, 'n_components': x_test.shape[1], 'TPR_train': tpr_train, 'TPR_test': tpr_test,", "fb, 'projection': 'PCA'}, ignore_index=True) classifier = IsolationForest(n_estimators=estimator, contamination=contamination, max_features=max_feature, n_jobs=7)", "model.fit(x_train, y_train, batch_size=128, epochs=10, verbose=0, validation_data=(x_test, y_test)) plot_history_with_acc(network_history) return model", "nu=nu, cache_size=7000) classifier.fit(x_train) fb, area, tnr, tpr_train, tpr_test = unsupervised_evaluation(classifier,", "Adam from keras.regularizers import l2 from sklearn.ensemble import RandomForestClassifier from", "kernel_initializer='glorot_uniform', activation='tanh')) model.add(Dropout(0.3)) model.add(Dense(1, kernel_initializer='normal', activation='sigmoid')) model.compile(loss='binary_crossentropy', optimizer='sgd', metrics=['accuracy']) network_history", "area, 'f_beta': fb, 'projection': 'RP'}, ignore_index=True) return ada_boost_results def svm_classifier(x_train,", "x_train, x_test, 'PCA') x_reduced_rp, test_reduced_rp = reduce_dimensionality(n, x_train, x_test, 'RP')", "fbeta_score, roc_curve, auc, confusion_matrix from sklearn.decomposition import PCA from sklearn", "batch_size=16, epochs=10, validation_data=(x_test, x_test), verbose=True) plot_history(network_history, 'AE history') print('Mean loss", "plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--') plt.xlim([0.0, 1.0]) plt.ylim([0.0,", "xgb def one_class_svm(x_train, x_test, x_attacks, svm_results): # SVM Hyper-parameters nus", "def unsupervised_evaluation(classifier, train_set, test_set, attack_set, beta=20): y_pred_train = classifier.predict(train_set) y_pred_test", "ae_svm_results = ae_svm_results.append({'nu': nu, 'gamma': gamma, 'n_components': latent_dim, 'TPR_train': tpr_train,", "Random forest Hyper-parameters estimators = [150, 200] dimensions = [int(i*x_test.shape[1])", "'f_beta': fb, 'projection': 'None'}, ignore_index=True) return random_forest_results def ada_boost(x_train, y_train,", "svm_results def xg_boost(x_train, y_train, x_test, y_test, xg_boost_results): # XGBoost Hyper-parameters", "'TNR': tnr, 'model': 'ada_boost', 'auc': area, 'f_beta': fb, 'projection': 'RP'},", "classifier.set_params(**grid) classifier.fit(x_reduced_pca, y_train) fb, area, tnr, tpr = supervised_evaluation(classifier, test_reduced_pca,", "fb, 'projection': 'None'}, ignore_index=True) return xg_boost_results def supervised_evaluation(classifier, x_test, y_test,", "test_reduced_rp, y_test) random_forest_results = random_forest_results.append({'estimators': estimator, 'n_components': n, 'TPR': tpr,", "keras.models import Model from keras import regularizers from keras.models import", "tnr = 1 - fpr[1] return fb, area, tnr, tpr", "plot_roc_supervised(classifier, x_test, y_test, title, nn=False): y_pred = classifier.predict(x_test) fpr, tpr,", "{}'.format(title)) plt.legend(loc='lower right') plt.show() def plot_history(network_history, title): plt.figure(figsize=(10, 5)) plt.title(title)", "n, 'TPR': tpr, 'TNR': tnr, 'model': 'random_forest', 'auc': area, 'f_beta':", "plt.figure() lw = 2 plt.plot(fpr, tpr, color='darkorange', lw=lw, label='ROC curve", "plot_roc(classifier, test, attacks, title): y_pred_test = classifier.predict(test) y_pred_outliers = classifier.predict(attacks)", "dimensions: x_reduced_pca, test_reduced_pca, attack_reduced_pca = reduce_dimensionality(n, x_train, x_test, 'PCA', attack=x_attacks)", "def neural_network(x_train, y_train, x_test, y_test): model = Sequential() model.add(Dense(128, input_shape=(x_train.shape[1],),", "isolation_results.append({'estimators': estimator, 'contamination': contamination, 'n_components': n, 'max_features': max_feature, 'TPR_train': tpr_train,", "tnr, tpr = supervised_evaluation(classifier, x_test, y_test) xg_boost_results = xg_boost_results.append({ 'n_components':", "= y_pred_train[y_pred_train == 1].size n_accurate_test = y_pred_test[y_pred_test == 1].size n_accurate_outliers", "= [int(i*x_test.shape[1]) for i in [1]] for estimator in estimators:", "2*x_train_red.shape[1], x_train_red.shape[1]/2, 'auto'] for nu in nus: for gamma in", "'RP'}, ignore_index=True) classifier = RandomForestClassifier(n_estimators=estimator, n_jobs=7) classifier.fit(x_train, y_train) fb, area,", "if not nn: y_pred = classifier.predict(x_test) confusion_matrix(y_test, y_pred) fpr, tpr,", "x_reduced_rp, test_reduced_rp, attack_reduced_rp = reduce_dimensionality(n, x_train, x_test, 'RP', attack=x_attacks) max_features", "svm.SVC(gamma='auto', cache_size=7000) classifier.fit(x_reduced_pca, y_train) fb, area, tnr, tpr = supervised_evaluation(classifier,", "1].size n_accurate_test = y_pred_test[y_pred_test == 1].size n_accurate_outliers = y_pred_outliers[y_pred_outliers ==", "classifier = xgb.XGBClassifier() grid = {'max_depth': 10} classifier.set_params(**grid) classifier.fit(x_train, y_train)", "attack_reduced_pca) isolation_results = isolation_results.append({'estimators': estimator, 'contamination': contamination, 'n_components': n, 'max_features':", "fb = fbeta_score(y_test, y_pred, beta=beta, pos_label=1) area = auc(fpr, tpr)", "x_reduced_rp, test_reduced_rp = reduce_dimensionality(n, x_train, x_test, 'RP') for lr in", "ignore_index=True) classifier = svm.SVC(gamma='auto', cache_size=7000) classifier.fit(x_reduced_rp, y_train) fb, area, tnr,", "Positive Rate') plt.ylabel('True Positive Rate') plt.title('Receiver operating characteristic {}'.format(title)) plt.legend(loc='lower", "gammas: classifier = svm.OneClassSVM(kernel='rbf', gamma=gamma, nu=nu, cache_size=7000) classifier.fit(x_train_red) fb, area,", "'model': 'xgboost', 'auc': area, 'f_beta': fb, 'projection': 'None'}, ignore_index=True) return", "isolation_forest(x_train, x_test, x_attacks, isolation_results): # Isolation Forest Hyper-parameters estimators =", "is None: return train, test attack = matrix.transform(attack) return train,", "# Fit classifier with RP reduced data classifier = svm.OneClassSVM(kernel='rbf',", "random_forest_results = random_forest_results.append({'estimators': estimator, 'n_components': n, 'TPR': tpr, 'TNR': tnr,", "[0.01] dimensions = [int(i*x_test.shape[1]) for i in [0.25, 0.5, 0.9,", "network_history = autoencoder.fit(x_train, x_train, shuffle=True, batch_size=16, epochs=10, validation_data=(x_test, x_test), verbose=True)", "gamma in gammas: # Fit classifier with PCA reduced data", "for gamma in gammas: # Fit classifier with PCA reduced", "estimator, 'n_components': x_test.shape[1], 'TPR': tpr, 'TNR': tnr, 'model': 'random_forest', 'auc':", "for nu in nus: for gamma in gammas: classifier =", "'isolation_forest', 'auc': area, 'f_beta': fb, 'projection': 'RP'}, ignore_index=True) return isolation_results", "fb, 'projection': 'RP'}, ignore_index=True) return isolation_results def autoencoder(x_train, x_test, x_attacks,", "Hyper-parameters estimators = [150, 200] dimensions = [int(i*x_test.shape[1]) for i", "ada_boost_results def svm_classifier(x_train, y_train, x_test, y_test, svm_results): # SVC Hyper-parameters", "x_reduced_rp, test_reduced_rp = reduce_dimensionality(n, x_train, x_test, 'RP') classifier = xgb.XGBClassifier()", "kernel_initializer='normal', activation='sigmoid')) model.compile(loss='binary_crossentropy', optimizer='sgd', metrics=['accuracy']) network_history = model.fit(x_train, y_train, batch_size=128,", "x_test, batch_size=8, verbose=False))) print('Mean loss on attacks: {}'.format(autoencoder.evaluate(x_attacks, x_attacks, batch_size=8,", "for estimator in estimators: for n in dimensions: x_reduced_pca, test_reduced_pca", "0.5, 0.9, 1]] dimensions = list(filter(lambda x: x > 0,", "'TNR': tnr, 'model': 'random_forest', 'auc': area, 'f_beta': fb, 'projection': 'RP'},", "= unsupervised_evaluation(classifier, x_train, x_test, x_attacks) svm_results = svm_results.append({'nu': nu, 'gamma':", "for contamination in contaminations: for max_feature in max_features: classifier =", "for x in y_pred] print(confusion_matrix(y_test, y_pred)) roc_auc = auc(fpr, tpr)", "ae_svm_results): latent_dim = 3 input_vector = Input(shape=(x_train.shape[1],)) encoded = Dense(latent_dim,", "tpr_test = unsupervised_evaluation(classifier, x_train_red, x_test_red, x_attacks_red) ae_svm_results = ae_svm_results.append({'nu': nu,", "supervised_evaluation(classifier, test_reduced_pca, y_test) ada_boost_results = ada_boost_results.append({'LR': lr, 'n_components': n, 'TPR':", "n + 1, 4)) for estimator in estimators: for contamination", "keras.optimizers import Adam from keras.regularizers import l2 from sklearn.ensemble import", "n, 'TPR_train': tpr_train, 'TPR_test': tpr_test, 'TNR': tnr, 'model': 'svm', 'auc':", "in estimators: for contamination in contaminations: for max_feature in max_features:", "reduce_dimensionality(n, x_train, x_test, 'RP') classifier = RandomForestClassifier(n_estimators=estimator, n_jobs=7) classifier.fit(x_reduced_pca, y_train)", "classifier.fit(x_reduced_pca, y_train) fb, area, tnr, tpr = supervised_evaluation(classifier, test_reduced_pca, y_test)", "Hyper-parameters dimensions = [int(i*x_test.shape[1]) for i in [1]] for n", "plt.legend(['Training', 'Validation']) plt.subplot(212) plt.xlabel('Epochs') plt.ylabel('Accuracy') plt.plot(network_history.history['acc']) plt.plot(network_history.history['val_acc']) plt.legend(['Training', 'Validation'], loc='lower", "'Validation']) plt.subplot(212) plt.xlabel('Epochs') plt.ylabel('Accuracy') plt.plot(network_history.history['acc']) plt.plot(network_history.history['val_acc']) plt.legend(['Training', 'Validation'], loc='lower right')", "train = matrix.fit_transform(train) test = matrix.transform(test) if attack is None:", "roc_curve(np.concatenate([np.ones(y_pred_test.shape[0]), -1*np.ones(y_pred_outliers.shape[0])]), np.concatenate([y_pred_test, y_pred_outliers]), pos_label=1) fb = fbeta_score(np.concatenate([np.ones(y_pred_test.shape[0]), -1*np.ones(y_pred_outliers.shape[0])]), np.concatenate([y_pred_test,", "'projection': 'None'}, ignore_index=True) return random_forest_results def ada_boost(x_train, y_train, x_test, y_test,", "tpr_test, 'TNR': tnr, 'model': 'isolation_forest', 'auc': area, 'f_beta': fb, 'projection':", "None: return train, test attack = matrix.transform(attack) return train, test,", "tnr, 'model': 'random_forest', 'auc': area, 'f_beta': fb, 'projection': 'None'}, ignore_index=True)", "# Isolation Forest Hyper-parameters estimators = [200, 100] contaminations =", "'TPR_train': tpr_train, 'TPR_test': tpr_test, 'TNR': tnr, 'model': 'svm', 'auc': area,", "n, 'TPR': tpr, 'TNR': tnr, 'model': 'ada_boost', 'auc': area, 'f_beta':", "'auc': area, 'f_beta': fb, 'projection': 'PCA'}, ignore_index=True) classifier = AdaBoostClassifier(learning_rate=lr)", "xg_boost_results): # XGBoost Hyper-parameters dimensions = [int(i*x_test.shape[1]) for i in", "lw = 2 plt.plot(fpr, tpr, color='darkorange', lw=lw, label='ROC curve (area", "input_shape=(x_train.shape[1],), activation='relu', kernel_regularizer=l2(0.01))) model.add(Dropout(0.1)) model.add(Dense(64, activation='relu', kernel_regularizer=l2(0.01))) model.add(Dropout(0.2)) model.add(Dense(128, kernel_initializer='glorot_uniform',", "for n in dimensions: x_reduced_pca, test_reduced_pca = reduce_dimensionality(n, x_train, x_test,", "nn: y_pred = classifier.predict(x_test) confusion_matrix(y_test, y_pred) fpr, tpr, _ =", "= random_forest_results.append({'estimators': estimator, 'n_components': x_test.shape[1], 'TPR': tpr, 'TNR': tnr, 'model':", "plt.show() def reduce_dimensionality(n_components, train, test, method, attack=None): if method ==", "x_test, y_test, ada_boost_results): # AdaBoost Hyper-parameters learning_rates = [0.55] dimensions", "auc(fpr, tpr) return fb, area, tnr, tpr_train, tpr_test def neural_network(x_train,", "xgb.XGBClassifier() grid = {'max_depth': 10} classifier.set_params(**grid) classifier.fit(x_train, y_train) fb, area,", "x_test), verbose=True) plot_history(network_history, 'AE history') print('Mean loss on train: {}'.format(autoencoder.evaluate(x_train,", "x_test, x_attacks, isolation_results): # Isolation Forest Hyper-parameters estimators = [200,", "plt.ylabel('True Positive Rate') plt.title('Receiver operating characteristic {}'.format(title)) plt.legend(loc='lower right') plt.show()", "model.add(Dense(128, input_shape=(x_train.shape[1],), activation='relu', kernel_regularizer=l2(0.01))) model.add(Dropout(0.1)) model.add(Dense(64, activation='relu', kernel_regularizer=l2(0.01))) model.add(Dropout(0.2)) model.add(Dense(128,", "y_test) svm_results = svm_results.append({ 'n_components': n, 'TPR': tpr, 'TNR': tnr,", "'auc': area, 'f_beta': fb, 'projection': 'RP'}, ignore_index=True) classifier = xgb.XGBClassifier()", "gamma, 'n_components': latent_dim, 'TPR_train': tpr_train, 'TPR_test': tpr_test, 'TNR': tnr, 'model':", "np.concatenate([y_pred_test, y_pred_outliers]), pos_label=1) roc_auc = auc(fpr, tpr) plt.figure() lw =", "plt.xlabel('Epochs') plt.ylabel('Loss') plt.semilogy(network_history.history['loss']) plt.semilogy(network_history.history['val_loss']) plt.legend(['Training', 'Validation']) plt.subplot(212) plt.xlabel('Epochs') plt.ylabel('Accuracy') plt.plot(network_history.history['acc'])", "import xgboost as xgb def one_class_svm(x_train, x_test, x_attacks, svm_results): #", "'model': 'svm', 'auc': area, 'f_beta': fb, 'projection': 'RP'}, ignore_index=True) return", "attacks, title): y_pred_test = classifier.predict(test) y_pred_outliers = classifier.predict(attacks) fpr, tpr,", "cache_size=7000) classifier.fit(x_train) fb, area, tnr, tpr_train, tpr_test = unsupervised_evaluation(classifier, x_train,", "tpr = tpr[1] tnr = 1 - fpr[1] return fb,", "tpr, 'TNR': tnr, 'model': 'random_forest', 'auc': area, 'f_beta': fb, 'projection':", "supervised_evaluation(classifier, test_reduced_pca, y_test) svm_results = svm_results.append({ 'n_components': n, 'TPR': tpr,", "and Accuracy'): plt.figure(figsize=(15, 10)) plt.subplot(211) plt.title(title) plt.xlabel('Epochs') plt.ylabel('Loss') plt.semilogy(network_history.history['loss']) plt.semilogy(network_history.history['val_loss'])", "tpr_test = unsupervised_evaluation(classifier, x_reduced_pca, test_reduced_pca, attack_reduced_pca) svm_results = svm_results.append({'nu': nu,", "'f_beta': fb, 'projection': 'PCA'}, ignore_index=True) classifier = AdaBoostClassifier(learning_rate=lr) classifier.fit(x_reduced_rp, y_train)", "svm_results = svm_results.append({'nu': nu, 'gamma': gamma, 'n_components': x_test.shape[1], 'TPR_train': tpr_train,", "= [0.01] dimensions = [int(i*x_test.shape[1]) for i in [0.25, 0.5,", "activation='relu')(input_vector) decoded = Dense(x_train.shape[1], activity_regularizer=regularizers.l1(10e-5))(encoded) autoencoder = Model(input_vector, decoded) encoder", "estimators: for contamination in contaminations: for max_feature in max_features: classifier", "max_feature, 'TPR_train': tpr_train, 'TPR_test': tpr_test, 'TNR': tnr, 'model': 'isolation_forest', 'auc':", "n_accurate_train/train_set.shape[0] area = auc(fpr, tpr) return fb, area, tnr, tpr_train,", "tnr, tpr_train, tpr_test = unsupervised_evaluation(classifier, x_train_red, x_test_red, x_attacks_red) ae_svm_results =", "import PCA from sklearn import random_projection from sklearn import svm", "attack=x_attacks) max_features = list(range(1, n + 1, 4)) for estimator", "= random_forest_results.append({'estimators': estimator, 'n_components': n, 'TPR': tpr, 'TNR': tnr, 'model':", "ignore_index=True) return isolation_results def autoencoder(x_train, x_test, x_attacks, ae_svm_results): latent_dim =", "'random_forest', 'auc': area, 'f_beta': fb, 'projection': 'None'}, ignore_index=True) return random_forest_results", "svm.OneClassSVM(kernel='rbf', gamma=gamma, nu=nu, cache_size=7000) classifier.fit(x_reduced_pca) fb, area, tnr, tpr_train, tpr_test", "svm_results = svm_results.append({'nu': nu, 'gamma': gamma, 'n_components': n, 'TPR_train': tpr_train,", "ignore_index=True) return random_forest_results def ada_boost(x_train, y_train, x_test, y_test, ada_boost_results): #", "= AdaBoostClassifier(learning_rate=lr) classifier.fit(x_reduced_rp, y_train) fb, area, tnr, tpr = supervised_evaluation(classifier,", "'TNR': tnr, 'model': 'isolation_forest', 'auc': area, 'f_beta': fb, 'projection': 'PCA'},", "unsupervised_evaluation(classifier, x_reduced_pca, test_reduced_pca, attack_reduced_pca) svm_results = svm_results.append({'nu': nu, 'gamma': gamma,", "tpr, 'TNR': tnr, 'model': 'ada_boost', 'auc': area, 'f_beta': fb, 'projection':", "choose either RP or PCA') return None train = matrix.fit_transform(train)", "'auc': area, 'f_beta': fb, 'projection': 'PCA'}, ignore_index=True) classifier = IsolationForest(n_estimators=estimator,", "area, tnr, tpr_train, tpr_test = unsupervised_evaluation(classifier, x_reduced_pca, test_reduced_pca, attack_reduced_pca) isolation_results", "import regularizers from keras.models import Sequential from keras.optimizers import Adam", "attack_reduced_pca = reduce_dimensionality(n, x_train, x_test, 'PCA', attack=x_attacks) x_reduced_rp, test_reduced_rp, attack_reduced_rp", "= encoder.predict(x_attacks, batch_size=8) nus = [0.01] gammas = [x_train_red.shape[1], 2*x_train_red.shape[1],", "'gamma': gamma, 'n_components': latent_dim, 'TPR_train': tpr_train, 'TPR_test': tpr_test, 'TNR': tnr,", "tpr_test def neural_network(x_train, y_train, x_test, y_test): model = Sequential() model.add(Dense(128,", "test_reduced_rp = reduce_dimensionality(n, x_train, x_test, 'RP') classifier = RandomForestClassifier(n_estimators=estimator, n_jobs=7)", "fb, area, tnr, tpr = supervised_evaluation(classifier, x_test, y_test) random_forest_results =", "def xg_boost(x_train, y_train, x_test, y_test, xg_boost_results): # XGBoost Hyper-parameters dimensions", "right') plt.show() def plot_history(network_history, title): plt.figure(figsize=(10, 5)) plt.title(title) plt.xlabel('Epochs') plt.ylabel('Loss')", "nus = [0.01] gammas = ['auto'] dimensions = [int(i*x_test.shape[1]) for", "# Fit classifier with PCA reduced data classifier = svm.OneClassSVM(kernel='rbf',", "ignore_index=True) classifier = RandomForestClassifier(n_estimators=estimator, n_jobs=7) classifier.fit(x_train, y_train) fb, area, tnr,", "y_train) fb, area, tnr, tpr = supervised_evaluation(classifier, test_reduced_pca, y_test) svm_results", "= svm.OneClassSVM(kernel='rbf', gamma=gamma, nu=nu, cache_size=7000) classifier.fit(x_reduced_pca) fb, area, tnr, tpr_train,", "RandomForestClassifier(n_estimators=estimator, n_jobs=7) classifier.fit(x_reduced_pca, y_train) fb, area, tnr, tpr = supervised_evaluation(classifier,", "def svm_classifier(x_train, y_train, x_test, y_test, svm_results): # SVC Hyper-parameters dimensions", "tnr, 'model': 'svm', 'auc': area, 'f_beta': fb, 'projection': 'None'}, ignore_index=True)", "tnr, 'model': 'xgboost', 'auc': area, 'f_beta': fb, 'projection': 'None'}, ignore_index=True)", "loss on test: {}'.format(autoencoder.evaluate(x_test, x_test, batch_size=8, verbose=False))) print('Mean loss on", "xg_boost_results = xg_boost_results.append({ 'n_components': n, 'TPR': tpr, 'TNR': tnr, 'model':", "plt.subplot(211) plt.title(title) plt.xlabel('Epochs') plt.ylabel('Loss') plt.semilogy(network_history.history['loss']) plt.semilogy(network_history.history['val_loss']) plt.legend(['Training', 'Validation']) plt.subplot(212) plt.xlabel('Epochs')", "= reduce_dimensionality(n, x_train, x_test, 'RP') classifier = svm.SVC(gamma='auto', cache_size=7000) classifier.fit(x_reduced_pca,", "either RP or PCA') return None train = matrix.fit_transform(train) test", "tpr_train, tpr_test def neural_network(x_train, y_train, x_test, y_test): model = Sequential()", "'n_components': x_test.shape[1], 'TPR_train': tpr_train, 'TPR_test': tpr_test, 'TNR': tnr, 'model': 'svm',", "nu, 'gamma': gamma, 'n_components': latent_dim, 'TPR_train': tpr_train, 'TPR_test': tpr_test, 'TNR':", "for i in [0.25, 0.35, 0.5, 0.75, 0.9, 1]] dimensions", "'f_beta': fb, 'projection': 'PCA'}, ignore_index=True) classifier = IsolationForest(n_estimators=estimator, contamination=contamination, max_features=max_feature,", "decoded = Dense(x_train.shape[1], activity_regularizer=regularizers.l1(10e-5))(encoded) autoencoder = Model(input_vector, decoded) encoder =", "# AdaBoost Hyper-parameters learning_rates = [0.55] dimensions = [int(i*x_test.shape[1]) for", "estimator, 'contamination': contamination, 'n_components': n, 'max_features': max_feature, 'TPR_train': tpr_train, 'TPR_test':", "autoencoder.fit(x_train, x_train, shuffle=True, batch_size=16, epochs=10, validation_data=(x_test, x_test), verbose=True) plot_history(network_history, 'AE", "n_jobs=7) classifier.fit(x_reduced_pca, y_train) fb, area, tnr, tpr = supervised_evaluation(classifier, test_reduced_pca,", "return train, test attack = matrix.transform(attack) return train, test, attack", "encoder.predict(x_attacks, batch_size=8) nus = [0.01] gammas = [x_train_red.shape[1], 2*x_train_red.shape[1], x_train_red.shape[1]/2,", "y_pred_outliers]), beta=beta, pos_label=1) tnr = n_accurate_outliers/attack_set.shape[0] tpr_test = n_accurate_test/test_set.shape[0] tpr_train", "x_test, y_test) xg_boost_results = xg_boost_results.append({ 'n_components': x_test.shape[1], 'TPR': tpr, 'TNR':", "for estimator in estimators: for contamination in contaminations: for max_feature", "'AE history') print('Mean loss on train: {}'.format(autoencoder.evaluate(x_train, x_train, batch_size=8, verbose=False)))", "verbose=False))) print('Mean loss on test: {}'.format(autoencoder.evaluate(x_test, x_test, batch_size=8, verbose=False))) print('Mean", "fb, 'projection': 'PCA'}, ignore_index=True) classifier = RandomForestClassifier(n_estimators=estimator, n_jobs=7) classifier.fit(x_reduced_rp, y_train)", "nus: for gamma in gammas: # Fit classifier with PCA", "tpr, _ = roc_curve(y_test, y_pred) fb = fbeta_score(y_test, y_pred, beta=beta,", "'RP') classifier = RandomForestClassifier(n_estimators=estimator, n_jobs=7) classifier.fit(x_reduced_pca, y_train) fb, area, tnr,", "gamma=gamma, nu=nu, cache_size=7000) classifier.fit(x_reduced_pca) fb, area, tnr, tpr_train, tpr_test =", "x_test, y_test): model = Sequential() model.add(Dense(128, input_shape=(x_train.shape[1],), activation='relu', kernel_regularizer=l2(0.01))) model.add(Dropout(0.1))", "plt.subplot(212) plt.xlabel('Epochs') plt.ylabel('Accuracy') plt.plot(network_history.history['acc']) plt.plot(network_history.history['val_acc']) plt.legend(['Training', 'Validation'], loc='lower right') plt.show()", "from sklearn import svm from sklearn.ensemble import IsolationForest import matplotlib.pyplot", "'RP': matrix = random_projection.SparseRandomProjection(n_components=n_components, random_state=7) else: print('unknown projection method, choose", "y_train, batch_size=128, epochs=10, verbose=0, validation_data=(x_test, y_test)) plot_history_with_acc(network_history) return model def", "epochs=10, validation_data=(x_test, x_test), verbose=True) plot_history(network_history, 'AE history') print('Mean loss on", "Accuracy'): plt.figure(figsize=(15, 10)) plt.subplot(211) plt.title(title) plt.xlabel('Epochs') plt.ylabel('Loss') plt.semilogy(network_history.history['loss']) plt.semilogy(network_history.history['val_loss']) plt.legend(['Training',", "unsupervised_evaluation(classifier, x_train, x_test, x_attacks) svm_results = svm_results.append({'nu': nu, 'gamma': gamma,", "tnr, 'model': 'xgboost', 'auc': area, 'f_beta': fb, 'projection': 'RP'}, ignore_index=True)", "gamma, 'n_components': x_test.shape[1], 'TPR_train': tpr_train, 'TPR_test': tpr_test, 'TNR': tnr, 'model':", "x_train, x_test, 'RP') classifier = xgb.XGBClassifier() grid = {'max_depth': 10}", "plt.semilogy(network_history.history['val_loss']) plt.legend(['Training', 'Validation']) plt.show() def plot_history_with_acc(network_history, title='Loss and Accuracy'): plt.figure(figsize=(15,", "from keras.layers import Dense, Input, Dropout from keras.models import Model", "x_reduced_pca, test_reduced_pca, attack_reduced_pca) isolation_results = isolation_results.append({'estimators': estimator, 'contamination': contamination, 'n_components':", "area, 'f_beta': fb, 'projection': 'None'}, ignore_index=True) return xg_boost_results def supervised_evaluation(classifier,", "'None'}, ignore_index=True) return random_forest_results def ada_boost(x_train, y_train, x_test, y_test, ada_boost_results):", "fb, area, tnr, tpr = supervised_evaluation(classifier, x_test, y_test) xg_boost_results =", "y_pred) fpr, tpr, _ = roc_curve(y_test, y_pred) fb = fbeta_score(y_test,", "[round(x[0]) for x in y_pred] print(confusion_matrix(y_test, y_pred)) roc_auc = auc(fpr,", "x_train_red.shape[1]/2, 'auto'] for nu in nus: for gamma in gammas:", "x_test_red = encoder.predict(x_test, batch_size=8) x_attacks_red = encoder.predict(x_attacks, batch_size=8) nus =", "y_test) random_forest_results = random_forest_results.append({'estimators': estimator, 'n_components': n, 'TPR': tpr, 'TNR':", "import Dense, Input, Dropout from keras.models import Model from keras", "= list(range(1, n + 1, 4)) for estimator in estimators:", "model.add(Dense(32, kernel_initializer='glorot_uniform', activation='tanh')) model.add(Dropout(0.4)) model.add(Dense(128, kernel_initializer='glorot_uniform', activation='tanh')) model.add(Dropout(0.3)) model.add(Dense(1, kernel_initializer='normal',", "classifier = RandomForestClassifier(n_estimators=estimator, n_jobs=7) classifier.fit(x_train, y_train) fb, area, tnr, tpr", "test_reduced_pca, y_test) xg_boost_results = xg_boost_results.append({ 'n_components': n, 'TPR': tpr, 'TNR':", "for max_feature in max_features: classifier = IsolationForest(n_estimators=estimator, contamination=contamination, max_features=max_feature, n_jobs=7)", "pos_label=1) tnr = n_accurate_outliers/attack_set.shape[0] tpr_test = n_accurate_test/test_set.shape[0] tpr_train = n_accurate_train/train_set.shape[0]", "loss on train: {}'.format(autoencoder.evaluate(x_train, x_train, batch_size=8, verbose=False))) print('Mean loss on", "fb, area, tnr, tpr_train, tpr_test = unsupervised_evaluation(classifier, x_reduced_pca, test_reduced_pca, attack_reduced_pca)", "x_test, x_attacks, svm_results): # SVM Hyper-parameters nus = [0.01] gammas", "'projection': 'PCA'}, ignore_index=True) classifier = AdaBoostClassifier(learning_rate=lr) classifier.fit(x_reduced_rp, y_train) fb, area,", "x_test, 'RP') classifier = xgb.XGBClassifier() grid = {'max_depth': 10} classifier.set_params(**grid)", "= RandomForestClassifier(n_estimators=estimator, n_jobs=7) classifier.fit(x_reduced_pca, y_train) fb, area, tnr, tpr =", "keras.layers import Dense, Input, Dropout from keras.models import Model from", "import RandomForestClassifier from sklearn.ensemble import AdaBoostClassifier import xgboost as xgb", "XGBoost Hyper-parameters dimensions = [int(i*x_test.shape[1]) for i in [1]] for", "'TNR': tnr, 'model': 'xgboost', 'auc': area, 'f_beta': fb, 'projection': 'RP'},", "ignore_index=True) return ae_svm_results def unsupervised_evaluation(classifier, train_set, test_set, attack_set, beta=20): y_pred_train", "x_test, 'PCA') x_reduced_rp, test_reduced_rp = reduce_dimensionality(n, x_train, x_test, 'RP') for", "test_reduced_rp, y_test) ada_boost_results = ada_boost_results.append({'LR': lr, 'n_components': n, 'TPR': tpr,", "= 2 plt.plot(fpr, tpr, color='darkorange', lw=lw, label='ROC curve (area =", "max_features: classifier = IsolationForest(n_estimators=estimator, contamination=contamination, max_features=max_feature, n_jobs=7) classifier.fit(x_reduced_pca) fb, area,", "= Input(shape=(x_train.shape[1],)) encoded = Dense(latent_dim, activation='relu')(input_vector) decoded = Dense(x_train.shape[1], activity_regularizer=regularizers.l1(10e-5))(encoded)", "loss='mse') network_history = autoencoder.fit(x_train, x_train, shuffle=True, batch_size=16, epochs=10, validation_data=(x_test, x_test),", "sklearn.metrics import fbeta_score, roc_curve, auc, confusion_matrix from sklearn.decomposition import PCA", "autoencoder.compile(optimizer=Adam(lr=0.001), loss='mse') network_history = autoencoder.fit(x_train, x_train, shuffle=True, batch_size=16, epochs=10, validation_data=(x_test,", "validation_data=(x_test, x_test), verbose=True) plot_history(network_history, 'AE history') print('Mean loss on train:", "print('Mean loss on train: {}'.format(autoencoder.evaluate(x_train, x_train, batch_size=8, verbose=False))) print('Mean loss", "classifier = svm.OneClassSVM(kernel='rbf', gamma=gamma, nu=nu, cache_size=7000) classifier.fit(x_train_red) fb, area, tnr,", "= [0.55] dimensions = [int(i*x_test.shape[1]) for i in [1]] for", "tnr, 'model': 'svm', 'auc': area, 'f_beta': fb, 'projection': 'PCA'}, ignore_index=True)", "in [1]] for estimator in estimators: for n in dimensions:", "1], color='navy', lw=lw, linestyle='--') plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.05]) plt.xlabel('False Positive", "classifier = xgb.XGBClassifier() grid = {'max_depth': 10} classifier.set_params(**grid) classifier.fit(x_reduced_rp, y_train)", "tpr_test = unsupervised_evaluation(classifier, x_reduced_pca, test_reduced_pca, attack_reduced_pca) isolation_results = isolation_results.append({'estimators': estimator,", "model.add(Dense(1, kernel_initializer='normal', activation='sigmoid')) model.compile(loss='binary_crossentropy', optimizer='sgd', metrics=['accuracy']) network_history = model.fit(x_train, y_train,", "fb, 'projection': 'PCA'}, ignore_index=True) classifier = xgb.XGBClassifier() grid = {'max_depth':", "title, nn=False): y_pred = classifier.predict(x_test) fpr, tpr, _ = roc_curve(y_test,", "IsolationForest import matplotlib.pyplot as plt from keras.layers import Dense, Input,", "{'max_depth': 10} classifier.set_params(**grid) classifier.fit(x_reduced_pca, y_train) fb, area, tnr, tpr =", "from sklearn import random_projection from sklearn import svm from sklearn.ensemble", "contamination in contaminations: for max_feature in max_features: classifier = IsolationForest(n_estimators=estimator,", "random_projection from sklearn import svm from sklearn.ensemble import IsolationForest import", "x_reduced_pca, test_reduced_pca, attack_reduced_pca = reduce_dimensionality(n, x_train, x_test, 'PCA', attack=x_attacks) x_reduced_rp,", "in nus: for gamma in gammas: classifier = svm.OneClassSVM(kernel='rbf', gamma=gamma,", "'n_components': x_test.shape[1], 'TPR': tpr, 'TNR': tnr, 'model': 'random_forest', 'auc': area,", "'model': 'svm', 'auc': area, 'f_beta': fb, 'projection': 'PCA'}, ignore_index=True) classifier", "'TNR': tnr, 'model': 'xgboost', 'auc': area, 'f_beta': fb, 'projection': 'None'},", "y_train, x_test, y_test, random_forest_results): # Random forest Hyper-parameters estimators =", "'max_features': max_feature, 'TPR_train': tpr_train, 'TPR_test': tpr_test, 'TNR': tnr, 'model': 'isolation_forest',", "batch_size=8, verbose=False))) print('Mean loss on test: {}'.format(autoencoder.evaluate(x_test, x_test, batch_size=8, verbose=False)))", "[int(i*x_test.shape[1]) for i in [1]] for estimator in estimators: for", "x_reduced_rp, test_reduced_rp = reduce_dimensionality(n, x_train, x_test, 'RP') classifier = RandomForestClassifier(n_estimators=estimator,", "classifier.predict(test) y_pred_outliers = classifier.predict(attacks) fpr, tpr, _ = roc_curve(np.concatenate([np.ones(y_pred_test.shape[0]), -1*np.ones(y_pred_outliers.shape[0])]),", "dimensions: x_reduced_pca, test_reduced_pca = reduce_dimensionality(n, x_train, x_test, 'PCA') x_reduced_rp, test_reduced_rp", "nu=nu, cache_size=7000) classifier.fit(x_train_red) fb, area, tnr, tpr_train, tpr_test = unsupervised_evaluation(classifier,", "-1].size fpr, tpr, _ = roc_curve(np.concatenate([np.ones(y_pred_test.shape[0]), -1*np.ones(y_pred_outliers.shape[0])]), np.concatenate([y_pred_test, y_pred_outliers]), pos_label=1)", "area, tnr, tpr = supervised_evaluation(classifier, test_reduced_pca, y_test) xg_boost_results = xg_boost_results.append({", "matplotlib.pyplot as plt from keras.layers import Dense, Input, Dropout from", "tpr = supervised_evaluation(classifier, test_reduced_rp, y_test) random_forest_results = random_forest_results.append({'estimators': estimator, 'n_components':", "test = matrix.transform(test) if attack is None: return train, test", "svm.OneClassSVM(kernel='rbf', gamma=gamma, nu=nu, cache_size=7000) classifier.fit(x_train_red) fb, area, tnr, tpr_train, tpr_test", "estimator, 'n_components': n, 'TPR': tpr, 'TNR': tnr, 'model': 'random_forest', 'auc':", "'model': 'random_forest', 'auc': area, 'f_beta': fb, 'projection': 'PCA'}, ignore_index=True) classifier", "grid = {'max_depth': 10} classifier.set_params(**grid) classifier.fit(x_train, y_train) fb, area, tnr,", "plt.title(title) plt.xlabel('Epochs') plt.ylabel('Loss') plt.semilogy(network_history.history['loss']) plt.semilogy(network_history.history['val_loss']) plt.legend(['Training', 'Validation']) plt.subplot(212) plt.xlabel('Epochs') plt.ylabel('Accuracy')", "data classifier = svm.OneClassSVM(kernel='rbf', gamma=gamma, nu=nu, cache_size=7000) classifier.fit(x_train) fb, area,", "[int(i*x_test.shape[1]) for i in [0.25, 0.35, 0.5, 0.75, 0.9, 1]]", "def plot_history(network_history, title): plt.figure(figsize=(10, 5)) plt.title(title) plt.xlabel('Epochs') plt.ylabel('Loss') plt.semilogy(network_history.history['loss']) plt.semilogy(network_history.history['val_loss'])", "= encoder.predict(x_train, batch_size=8) x_test_red = encoder.predict(x_test, batch_size=8) x_attacks_red = encoder.predict(x_attacks,", "fb, 'projection': 'RP'}, ignore_index=True) return ada_boost_results def svm_classifier(x_train, y_train, x_test,", "title): plt.figure(figsize=(10, 5)) plt.title(title) plt.xlabel('Epochs') plt.ylabel('Loss') plt.semilogy(network_history.history['loss']) plt.semilogy(network_history.history['val_loss']) plt.legend(['Training', 'Validation'])", "= roc_curve(np.concatenate([np.ones(y_pred_test.shape[0]), -1*np.ones(y_pred_outliers.shape[0])]), np.concatenate([y_pred_test, y_pred_outliers]), pos_label=1) fb = fbeta_score(np.concatenate([np.ones(y_pred_test.shape[0]), -1*np.ones(y_pred_outliers.shape[0])]),", "classifier.predict(attack_set) n_accurate_train = y_pred_train[y_pred_train == 1].size n_accurate_test = y_pred_test[y_pred_test ==", "'auc': area, 'f_beta': fb, 'projection': 'PCA'}, ignore_index=True) classifier = RandomForestClassifier(n_estimators=estimator,", "contaminations = [0.01] dimensions = [int(i*x_test.shape[1]) for i in [0.25,", "in learning_rates: classifier = AdaBoostClassifier(learning_rate=lr) classifier.fit(x_reduced_pca, y_train) fb, area, tnr,", "'TPR': tpr, 'TNR': tnr, 'model': 'svm', 'auc': area, 'f_beta': fb,", "plot_history(network_history, title): plt.figure(figsize=(10, 5)) plt.title(title) plt.xlabel('Epochs') plt.ylabel('Loss') plt.semilogy(network_history.history['loss']) plt.semilogy(network_history.history['val_loss']) plt.legend(['Training',", "matrix.transform(test) if attack is None: return train, test attack =", "characteristic: {}'.format(title)) plt.legend(loc='lower right') plt.show() def plot_roc_supervised(classifier, x_test, y_test, title,", "% roc_auc) plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--') plt.xlim([0.0,", "'projection': 'PCA'}, ignore_index=True) classifier = IsolationForest(n_estimators=estimator, contamination=contamination, max_features=max_feature, n_jobs=7) classifier.fit(x_reduced_rp)", "classifier.fit(x_reduced_rp, y_train) fb, area, tnr, tpr = supervised_evaluation(classifier, test_reduced_rp, y_test)", "y_pred_train = classifier.predict(train_set) y_pred_test = classifier.predict(test_set) y_pred_outliers = classifier.predict(attack_set) n_accurate_train", "= n_accurate_train/train_set.shape[0] area = auc(fpr, tpr) return fb, area, tnr,", "from sklearn.ensemble import RandomForestClassifier from sklearn.ensemble import AdaBoostClassifier import xgboost", "area, 'f_beta': fb, 'projection': 'RP'}, ignore_index=True) return isolation_results def autoencoder(x_train,", "'model': 'xgboost', 'auc': area, 'f_beta': fb, 'projection': 'PCA'}, ignore_index=True) classifier", "roc_auc = auc(fpr, tpr) plt.figure() lw = 2 plt.plot(fpr, tpr,", "# Random forest Hyper-parameters estimators = [150, 200] dimensions =", "svm_classifier(x_train, y_train, x_test, y_test, svm_results): # SVC Hyper-parameters dimensions =", "def supervised_evaluation(classifier, x_test, y_test, beta=20, nn=False): if not nn: y_pred", "classifier.predict(x_test) confusion_matrix(y_test, y_pred) fpr, tpr, _ = roc_curve(y_test, y_pred) fb", "= svm.OneClassSVM(kernel='rbf', gamma=gamma, nu=nu, cache_size=7000) classifier.fit(x_train_red) fb, area, tnr, tpr_train,", "'TNR': tnr, 'model': 'svm', 'auc': area, 'f_beta': fb, 'projection': 'PCA'},", "= classifier.predict(x_test) fpr, tpr, _ = roc_curve(y_test, y_pred) if nn:", "{}'.format(autoencoder.evaluate(x_train, x_train, batch_size=8, verbose=False))) print('Mean loss on test: {}'.format(autoencoder.evaluate(x_test, x_test,", "= [150, 200] dimensions = [int(i*x_test.shape[1]) for i in [1]]", "n, 'TPR': tpr, 'TNR': tnr, 'model': 'xgboost', 'auc': area, 'f_beta':", "Fit classifier with RP reduced data classifier = svm.OneClassSVM(kernel='rbf', gamma=gamma,", "x_test, 'PCA') x_reduced_rp, test_reduced_rp = reduce_dimensionality(n, x_train, x_test, 'RP') classifier", "= Sequential() model.add(Dense(128, input_shape=(x_train.shape[1],), activation='relu', kernel_regularizer=l2(0.01))) model.add(Dropout(0.1)) model.add(Dense(64, activation='relu', kernel_regularizer=l2(0.01)))", "classifier.set_params(**grid) classifier.fit(x_reduced_rp, y_train) fb, area, tnr, tpr = supervised_evaluation(classifier, test_reduced_rp,", "plt.semilogy(network_history.history['loss']) plt.semilogy(network_history.history['val_loss']) plt.legend(['Training', 'Validation']) plt.subplot(212) plt.xlabel('Epochs') plt.ylabel('Accuracy') plt.plot(network_history.history['acc']) plt.plot(network_history.history['val_acc']) plt.legend(['Training',", "x_train_red, x_test_red, x_attacks_red) ae_svm_results = ae_svm_results.append({'nu': nu, 'gamma': gamma, 'n_components':", "'projection': 'RP'}, ignore_index=True) return ada_boost_results def svm_classifier(x_train, y_train, x_test, y_test,", "lr in learning_rates: classifier = AdaBoostClassifier(learning_rate=lr) classifier.fit(x_reduced_pca, y_train) fb, area,", "x_reduced_rp, test_reduced_rp, attack_reduced_rp) isolation_results = isolation_results.append({'estimators': estimator, 'contamination': contamination, 'n_components':", "> 0, dimensions)) for n in dimensions: x_reduced_pca, test_reduced_pca, attack_reduced_pca", "'ada_boost', 'auc': area, 'f_beta': fb, 'projection': 'RP'}, ignore_index=True) return ada_boost_results", "tpr) tpr = tpr[1] tnr = 1 - fpr[1] return", "batch_size=128, epochs=10, verbose=0, validation_data=(x_test, y_test)) plot_history_with_acc(network_history) return model def random_forest(x_train,", "pos_label=1) area = auc(fpr, tpr) tpr = tpr[1] tnr =", "with PCA reduced data classifier = svm.OneClassSVM(kernel='rbf', gamma=gamma, nu=nu, cache_size=7000)", "n in dimensions: x_reduced_pca, test_reduced_pca = reduce_dimensionality(n, x_train, x_test, 'PCA')", "x_train, x_test, 'PCA', attack=x_attacks) for nu in nus: for gamma", "'model': 'isolation_forest', 'auc': area, 'f_beta': fb, 'projection': 'RP'}, ignore_index=True) return", "200] dimensions = [int(i*x_test.shape[1]) for i in [1]] for estimator", "def one_class_svm(x_train, x_test, x_attacks, svm_results): # SVM Hyper-parameters nus =", "area, tnr, tpr_train, tpr_test = unsupervised_evaluation(classifier, x_train, x_test, x_attacks) svm_results", "10} classifier.set_params(**grid) classifier.fit(x_reduced_pca, y_train) fb, area, tnr, tpr = supervised_evaluation(classifier,", "import Model from keras import regularizers from keras.models import Sequential", "'RP') classifier = xgb.XGBClassifier() grid = {'max_depth': 10} classifier.set_params(**grid) classifier.fit(x_reduced_pca,", "attack=None): if method == 'PCA': matrix = PCA(n_components=n_components) elif method", "plt.title(title) plt.xlabel('Epochs') plt.ylabel('Loss') plt.semilogy(network_history.history['loss']) plt.semilogy(network_history.history['val_loss']) plt.legend(['Training', 'Validation']) plt.show() def plot_history_with_acc(network_history,", "return ae_svm_results def unsupervised_evaluation(classifier, train_set, test_set, attack_set, beta=20): y_pred_train =" ]
[ "msg=\"foo test\") self.assertEqual(2201, res[\"response_code\"]) def test_message_banned(self): res = send_message(self.banned, self.banned_token,", "test\") self.assertEqual(403, res[\"response_code\"]) def test_message_provider(self): res = send_message(self.provider, self.provider_token, to=self.user,", "class TestNotifyUser(unittest.TestCase): def setUp(self): self.provider = \"test_provider\" self.provider_banned = \"test_provider_msg_banned\"", "\"<KEY>\" self.provider_banned_token = \"<KEY>\" self.user_token = \"<KEY>\" def test_message(self): res", "res = send_message(self.sender, self.sender_token, to=self.user, msg=\"foo test\") self.assertEqual(2201, res[\"response_code\"]) def", "import os import sys sys.path.append(os.getcwd()) from notifo import Notifo, send_message", "sys.path.append(os.getcwd()) from notifo import Notifo, send_message class TestNotifyUser(unittest.TestCase): def setUp(self):", "test\") self.assertEqual(2201, res[\"response_code\"]) def test_message_banned(self): res = send_message(self.banned, self.banned_token, to=self.user,", "\"test_user2\" self.banned = \"test_user_banned\" self.banned_token = \"<KEY>\" self.sender_token = \"x633a05b18f7f65bf461ffb3900c6eb70eaafb0ed\"", "= \"<KEY>\" self.sender_token = \"x633a05b18f7f65bf461ffb3900c6eb70eaafb0ed\" self.provider_token = \"<KEY>\" self.provider_banned_token =", "test_message_banned(self): res = send_message(self.banned, self.banned_token, to=self.user, msg=\"foo test\") self.assertEqual(403, res[\"response_code\"])", "send_message(self.provider_banned, self.provider_banned_token, to=self.user, msg=\"foo test\") self.assertEqual(403, res[\"response_code\"]) if __name__ ==", "self.provider_token = \"<KEY>\" self.provider_banned_token = \"<KEY>\" self.user_token = \"<KEY>\" def", "= send_message(self.provider, self.provider_token, to=self.user, msg=\"foo test\") self.assertEqual(2201, res[\"response_code\"]) def test_message_provider_banned(self):", "res[\"response_code\"]) def test_message_banned(self): res = send_message(self.banned, self.banned_token, to=self.user, msg=\"foo test\")", "self.assertEqual(403, res[\"response_code\"]) def test_message_provider(self): res = send_message(self.provider, self.provider_token, to=self.user, msg=\"foo", "Notifo, send_message class TestNotifyUser(unittest.TestCase): def setUp(self): self.provider = \"test_provider\" self.provider_banned", "self.sender = \"test_user2\" self.banned = \"test_user_banned\" self.banned_token = \"<KEY>\" self.sender_token", "self.assertEqual(2201, res[\"response_code\"]) def test_message_with_object(self): res = Notifo(self.sender, self.sender_token).send_message( to=self.user, msg=\"foo", "\"<KEY>\" def test_message(self): res = send_message(self.sender, self.sender_token, to=self.user, msg=\"foo test\")", "utf-8 import unittest import os import sys sys.path.append(os.getcwd()) from notifo", "test\") self.assertEqual(2201, res[\"response_code\"]) def test_message_with_object(self): res = Notifo(self.sender, self.sender_token).send_message( to=self.user,", "res[\"response_code\"]) def test_message_provider(self): res = send_message(self.provider, self.provider_token, to=self.user, msg=\"foo test\")", "# encoding: utf-8 import unittest import os import sys sys.path.append(os.getcwd())", "self.sender_token, to=self.user, msg=\"foo test\") self.assertEqual(2201, res[\"response_code\"]) def test_message_with_object(self): res =", "os import sys sys.path.append(os.getcwd()) from notifo import Notifo, send_message class", "res = send_message(self.provider_banned, self.provider_banned_token, to=self.user, msg=\"foo test\") self.assertEqual(403, res[\"response_code\"]) if", "= \"<KEY>\" def test_message(self): res = send_message(self.sender, self.sender_token, to=self.user, msg=\"foo", "send_message(self.provider, self.provider_token, to=self.user, msg=\"foo test\") self.assertEqual(2201, res[\"response_code\"]) def test_message_provider_banned(self): res", "= \"test_user2\" self.banned = \"test_user_banned\" self.banned_token = \"<KEY>\" self.sender_token =", "self.provider = \"test_provider\" self.provider_banned = \"test_provider_msg_banned\" self.user = \"test_user\" self.sender", "def test_message(self): res = send_message(self.sender, self.sender_token, to=self.user, msg=\"foo test\") self.assertEqual(2201,", "import sys sys.path.append(os.getcwd()) from notifo import Notifo, send_message class TestNotifyUser(unittest.TestCase):", "test_message_provider(self): res = send_message(self.provider, self.provider_token, to=self.user, msg=\"foo test\") self.assertEqual(2201, res[\"response_code\"])", "= send_message(self.provider_banned, self.provider_banned_token, to=self.user, msg=\"foo test\") self.assertEqual(403, res[\"response_code\"]) if __name__", "res = Notifo(self.sender, self.sender_token).send_message( to=self.user, msg=\"foo test\") self.assertEqual(2201, res[\"response_code\"]) def", "self.assertEqual(2201, res[\"response_code\"]) def test_message_provider_banned(self): res = send_message(self.provider_banned, self.provider_banned_token, to=self.user, msg=\"foo", "test_message(self): res = send_message(self.sender, self.sender_token, to=self.user, msg=\"foo test\") self.assertEqual(2201, res[\"response_code\"])", "self.sender_token).send_message( to=self.user, msg=\"foo test\") self.assertEqual(2201, res[\"response_code\"]) def test_message_banned(self): res =", "test_message_with_object(self): res = Notifo(self.sender, self.sender_token).send_message( to=self.user, msg=\"foo test\") self.assertEqual(2201, res[\"response_code\"])", "self.banned = \"test_user_banned\" self.banned_token = \"<KEY>\" self.sender_token = \"x633a05b18f7f65bf461ffb3900c6eb70eaafb0ed\" self.provider_token", "to=self.user, msg=\"foo test\") self.assertEqual(403, res[\"response_code\"]) if __name__ == '__main__': unittest.main()", "test_message_provider_banned(self): res = send_message(self.provider_banned, self.provider_banned_token, to=self.user, msg=\"foo test\") self.assertEqual(403, res[\"response_code\"])", "send_message(self.banned, self.banned_token, to=self.user, msg=\"foo test\") self.assertEqual(403, res[\"response_code\"]) def test_message_provider(self): res", "self.banned_token = \"<KEY>\" self.sender_token = \"x633a05b18f7f65bf461ffb3900c6eb70eaafb0ed\" self.provider_token = \"<KEY>\" self.provider_banned_token", "msg=\"foo test\") self.assertEqual(2201, res[\"response_code\"]) def test_message_with_object(self): res = Notifo(self.sender, self.sender_token).send_message(", "unittest import os import sys sys.path.append(os.getcwd()) from notifo import Notifo,", "= \"<KEY>\" self.provider_banned_token = \"<KEY>\" self.user_token = \"<KEY>\" def test_message(self):", "msg=\"foo test\") self.assertEqual(2201, res[\"response_code\"]) def test_message_provider_banned(self): res = send_message(self.provider_banned, self.provider_banned_token,", "import Notifo, send_message class TestNotifyUser(unittest.TestCase): def setUp(self): self.provider = \"test_provider\"", "to=self.user, msg=\"foo test\") self.assertEqual(2201, res[\"response_code\"]) def test_message_provider_banned(self): res = send_message(self.provider_banned,", "notifo import Notifo, send_message class TestNotifyUser(unittest.TestCase): def setUp(self): self.provider =", "= \"<KEY>\" self.user_token = \"<KEY>\" def test_message(self): res = send_message(self.sender,", "\"<KEY>\" self.sender_token = \"x633a05b18f7f65bf461ffb3900c6eb70eaafb0ed\" self.provider_token = \"<KEY>\" self.provider_banned_token = \"<KEY>\"", "sys sys.path.append(os.getcwd()) from notifo import Notifo, send_message class TestNotifyUser(unittest.TestCase): def", "\"test_provider_msg_banned\" self.user = \"test_user\" self.sender = \"test_user2\" self.banned = \"test_user_banned\"", "= \"test_user_banned\" self.banned_token = \"<KEY>\" self.sender_token = \"x633a05b18f7f65bf461ffb3900c6eb70eaafb0ed\" self.provider_token =", "setUp(self): self.provider = \"test_provider\" self.provider_banned = \"test_provider_msg_banned\" self.user = \"test_user\"", "import unittest import os import sys sys.path.append(os.getcwd()) from notifo import", "self.assertEqual(2201, res[\"response_code\"]) def test_message_banned(self): res = send_message(self.banned, self.banned_token, to=self.user, msg=\"foo", "self.provider_banned_token = \"<KEY>\" self.user_token = \"<KEY>\" def test_message(self): res =", "encoding: utf-8 import unittest import os import sys sys.path.append(os.getcwd()) from", "self.provider_banned = \"test_provider_msg_banned\" self.user = \"test_user\" self.sender = \"test_user2\" self.banned", "to=self.user, msg=\"foo test\") self.assertEqual(2201, res[\"response_code\"]) def test_message_banned(self): res = send_message(self.banned,", "self.banned_token, to=self.user, msg=\"foo test\") self.assertEqual(403, res[\"response_code\"]) def test_message_provider(self): res =", "= send_message(self.sender, self.sender_token, to=self.user, msg=\"foo test\") self.assertEqual(2201, res[\"response_code\"]) def test_message_with_object(self):", "= \"test_provider_msg_banned\" self.user = \"test_user\" self.sender = \"test_user2\" self.banned =", "res[\"response_code\"]) def test_message_provider_banned(self): res = send_message(self.provider_banned, self.provider_banned_token, to=self.user, msg=\"foo test\")", "def setUp(self): self.provider = \"test_provider\" self.provider_banned = \"test_provider_msg_banned\" self.user =", "self.provider_token, to=self.user, msg=\"foo test\") self.assertEqual(2201, res[\"response_code\"]) def test_message_provider_banned(self): res =", "res = send_message(self.banned, self.banned_token, to=self.user, msg=\"foo test\") self.assertEqual(403, res[\"response_code\"]) def", "= \"test_user\" self.sender = \"test_user2\" self.banned = \"test_user_banned\" self.banned_token =", "self.sender_token = \"x633a05b18f7f65bf461ffb3900c6eb70eaafb0ed\" self.provider_token = \"<KEY>\" self.provider_banned_token = \"<KEY>\" self.user_token", "msg=\"foo test\") self.assertEqual(403, res[\"response_code\"]) def test_message_provider(self): res = send_message(self.provider, self.provider_token,", "\"test_provider\" self.provider_banned = \"test_provider_msg_banned\" self.user = \"test_user\" self.sender = \"test_user2\"", "res = send_message(self.provider, self.provider_token, to=self.user, msg=\"foo test\") self.assertEqual(2201, res[\"response_code\"]) def", "self.provider_banned_token, to=self.user, msg=\"foo test\") self.assertEqual(403, res[\"response_code\"]) if __name__ == '__main__':", "TestNotifyUser(unittest.TestCase): def setUp(self): self.provider = \"test_provider\" self.provider_banned = \"test_provider_msg_banned\" self.user", "Notifo(self.sender, self.sender_token).send_message( to=self.user, msg=\"foo test\") self.assertEqual(2201, res[\"response_code\"]) def test_message_banned(self): res", "\"test_user\" self.sender = \"test_user2\" self.banned = \"test_user_banned\" self.banned_token = \"<KEY>\"", "self.user_token = \"<KEY>\" def test_message(self): res = send_message(self.sender, self.sender_token, to=self.user,", "test\") self.assertEqual(2201, res[\"response_code\"]) def test_message_provider_banned(self): res = send_message(self.provider_banned, self.provider_banned_token, to=self.user,", "from notifo import Notifo, send_message class TestNotifyUser(unittest.TestCase): def setUp(self): self.provider", "\"<KEY>\" self.user_token = \"<KEY>\" def test_message(self): res = send_message(self.sender, self.sender_token,", "def test_message_provider_banned(self): res = send_message(self.provider_banned, self.provider_banned_token, to=self.user, msg=\"foo test\") self.assertEqual(403,", "def test_message_banned(self): res = send_message(self.banned, self.banned_token, to=self.user, msg=\"foo test\") self.assertEqual(403,", "send_message(self.sender, self.sender_token, to=self.user, msg=\"foo test\") self.assertEqual(2201, res[\"response_code\"]) def test_message_with_object(self): res", "def test_message_provider(self): res = send_message(self.provider, self.provider_token, to=self.user, msg=\"foo test\") self.assertEqual(2201,", "self.user = \"test_user\" self.sender = \"test_user2\" self.banned = \"test_user_banned\" self.banned_token", "def test_message_with_object(self): res = Notifo(self.sender, self.sender_token).send_message( to=self.user, msg=\"foo test\") self.assertEqual(2201,", "= send_message(self.banned, self.banned_token, to=self.user, msg=\"foo test\") self.assertEqual(403, res[\"response_code\"]) def test_message_provider(self):", "= \"test_provider\" self.provider_banned = \"test_provider_msg_banned\" self.user = \"test_user\" self.sender =", "to=self.user, msg=\"foo test\") self.assertEqual(2201, res[\"response_code\"]) def test_message_with_object(self): res = Notifo(self.sender,", "send_message class TestNotifyUser(unittest.TestCase): def setUp(self): self.provider = \"test_provider\" self.provider_banned =", "res[\"response_code\"]) def test_message_with_object(self): res = Notifo(self.sender, self.sender_token).send_message( to=self.user, msg=\"foo test\")", "\"test_user_banned\" self.banned_token = \"<KEY>\" self.sender_token = \"x633a05b18f7f65bf461ffb3900c6eb70eaafb0ed\" self.provider_token = \"<KEY>\"", "= Notifo(self.sender, self.sender_token).send_message( to=self.user, msg=\"foo test\") self.assertEqual(2201, res[\"response_code\"]) def test_message_banned(self):", "\"x633a05b18f7f65bf461ffb3900c6eb70eaafb0ed\" self.provider_token = \"<KEY>\" self.provider_banned_token = \"<KEY>\" self.user_token = \"<KEY>\"", "= \"x633a05b18f7f65bf461ffb3900c6eb70eaafb0ed\" self.provider_token = \"<KEY>\" self.provider_banned_token = \"<KEY>\" self.user_token =", "to=self.user, msg=\"foo test\") self.assertEqual(403, res[\"response_code\"]) def test_message_provider(self): res = send_message(self.provider," ]
[ "for xyP in XY: Win.append(0) for xyE in zip(x,y): Dis", "= CU.Polygon() P.Load(Wkt) # Unwrapping coordinates if Unwrap: x =", "Unwrap=Unwrap) else: XY = P.CartGrid(Dx=Delta, Dy=Delta, Bounds=Box) Win = []", "Dis = CU.WgsDistance(xyP[1], xyP[0], xyE[1], xyE[0]) Win[-1] += Window(Dis, Par)", ".Exploration as Exp import .CatUtils as CU #----------------------------------------------------------------------------------------- def GaussWin", "[i if i > 0. else i+360. for i in", "if x < 180. else x-360. for x in X]", "XY: Win.append(0) for xyE in zip(x,y): Dis = CU.WgsDistance(xyP[1], xyP[0],", "for I,W in enumerate(Win): aT = -np.inf if Norm >", "Y.append(XY[I][1]) if Unwrap: # Wrap back longitudes X = [x", "coordinates if Unwrap: x = [i if i > 0.", "+= Window(Dis, Par) # Scaling and normalising the rates Norm", "x < 180. else x-360. for x in X] return", "= Exp.GetHypocenter(DbS) # Creating the mesh grid P = CU.Polygon()", "if aT > -np.inf: A.append(aT) X.append(XY[I][0]) Y.append(XY[I][1]) if Unwrap: #", "as np import .Selection as Sel import .Exploration as Exp", "else: XY = P.CartGrid(Dx=Delta, Dy=Delta, Bounds=Box) Win = [] for", "Par <= 0: Par = np.inf # Catalogue selection DbS", "# Unwrapping coordinates if Unwrap: x = [i if i", "Wkt, Window=GaussWin, Par=50., Delta=0.1, SphereGrid=False, Box=[], Buffer=[], Grid=[], Threshold=-100, Unwrap=False,", "P.SphereGrid(Delta=Delta, Unwrap=Unwrap) else: XY = P.CartGrid(Dx=Delta, Dy=Delta, Bounds=Box) Win =", "<= 0: Par = np.inf # Catalogue selection DbS =", "if P.IsInside(G[0], G[1])] else: if SphereGrid: XY = P.SphereGrid(Delta=Delta, Unwrap=Unwrap)", "> 0. and W > 0.: aT = a +", "(Dis, Sig): return np.exp(-(Dis**2)/(Sig**2.)) #----------------------------------------------------------------------------------------- def SmoothMFD (Db, a, Wkt,", "DbS = Sel.AreaSelect(Db, Wkt, Owrite=0, Buffer=Buffer, Unwrap=Unwrap) x,y,z = Exp.GetHypocenter(DbS)", "= Sel.AreaSelect(Db, Wkt, Owrite=0, Buffer=Buffer, Unwrap=Unwrap) x,y,z = Exp.GetHypocenter(DbS) #", "import numpy as np import .Selection as Sel import .Exploration", "W > 0.: aT = a + np.log10(W/Norm) if aT", "aT = -np.inf if ZeroRates: A.append(aT) X.append(XY[I][0]) Y.append(XY[I][1]) else: if", "grid P = CU.Polygon() P.Load(Wkt) # Unwrapping coordinates if Unwrap:", "SphereGrid=False, Box=[], Buffer=[], Grid=[], Threshold=-100, Unwrap=False, ZeroRates=False): if Par <=", "Unwrap=False, ZeroRates=False): if Par <= 0: Par = np.inf #", "python # -*- coding: utf-8 -*- # import numpy as", "#!/usr/bin/env python # -*- coding: utf-8 -*- # import numpy", "if Par <= 0: Par = np.inf # Catalogue selection", "else: if aT > -np.inf: A.append(aT) X.append(XY[I][0]) Y.append(XY[I][1]) if Unwrap:", "for i in x] P.Unwrap() if Grid: XY = [G", "# import numpy as np import .Selection as Sel import", "X = []; Y = [] for I,W in enumerate(Win):", "Catalogue selection DbS = Sel.AreaSelect(Db, Wkt, Owrite=0, Buffer=Buffer, Unwrap=Unwrap) x,y,z", "# -*- coding: utf-8 -*- # import numpy as np", "XY = P.CartGrid(Dx=Delta, Dy=Delta, Bounds=Box) Win = [] for xyP", "if Unwrap: x = [i if i > 0. else", "Filter below threshold aT = -np.inf if ZeroRates: A.append(aT) X.append(XY[I][0])", "= [x if x < 180. else x-360. for x", "as Exp import .CatUtils as CU #----------------------------------------------------------------------------------------- def GaussWin (Dis,", "P.CartGrid(Dx=Delta, Dy=Delta, Bounds=Box) Win = [] for xyP in XY:", "as Sel import .Exploration as Exp import .CatUtils as CU", "in zip(x,y): Dis = CU.WgsDistance(xyP[1], xyP[0], xyE[1], xyE[0]) Win[-1] +=", "for xyE in zip(x,y): Dis = CU.WgsDistance(xyP[1], xyP[0], xyE[1], xyE[0])", "= CU.WgsDistance(xyP[1], xyP[0], xyE[1], xyE[0]) Win[-1] += Window(Dis, Par) #", "xyE[1], xyE[0]) Win[-1] += Window(Dis, Par) # Scaling and normalising", "= [] for I,W in enumerate(Win): aT = -np.inf if", "return np.exp(-(Dis**2)/(Sig**2.)) #----------------------------------------------------------------------------------------- def SmoothMFD (Db, a, Wkt, Window=GaussWin, Par=50.,", "Unwrap=Unwrap) x,y,z = Exp.GetHypocenter(DbS) # Creating the mesh grid P", "aT < Threshold: # Filter below threshold aT = -np.inf", "#----------------------------------------------------------------------------------------- def SmoothMFD (Db, a, Wkt, Window=GaussWin, Par=50., Delta=0.1, SphereGrid=False,", "[x if x < 180. else x-360. for x in", "Sig): return np.exp(-(Dis**2)/(Sig**2.)) #----------------------------------------------------------------------------------------- def SmoothMFD (Db, a, Wkt, Window=GaussWin,", "# Filter below threshold aT = -np.inf if ZeroRates: A.append(aT)", "Threshold=-100, Unwrap=False, ZeroRates=False): if Par <= 0: Par = np.inf", "#----------------------------------------------------------------------------------------- def GaussWin (Dis, Sig): return np.exp(-(Dis**2)/(Sig**2.)) #----------------------------------------------------------------------------------------- def SmoothMFD", "= []; X = []; Y = [] for I,W", "CU.WgsDistance(xyP[1], xyP[0], xyE[1], xyE[0]) Win[-1] += Window(Dis, Par) # Scaling", "= [] for xyP in XY: Win.append(0) for xyE in", "Unwrap: x = [i if i > 0. else i+360.", "def SmoothMFD (Db, a, Wkt, Window=GaussWin, Par=50., Delta=0.1, SphereGrid=False, Box=[],", "a, Wkt, Window=GaussWin, Par=50., Delta=0.1, SphereGrid=False, Box=[], Buffer=[], Grid=[], Threshold=-100,", "G[1])] else: if SphereGrid: XY = P.SphereGrid(Delta=Delta, Unwrap=Unwrap) else: XY", "aT > -np.inf: A.append(aT) X.append(XY[I][0]) Y.append(XY[I][1]) if Unwrap: # Wrap", "normalising the rates Norm = np.sum(Win) A = []; X", "xyE[0]) Win[-1] += Window(Dis, Par) # Scaling and normalising the", "A = []; X = []; Y = [] for", "if i > 0. else i+360. for i in x]", "import .CatUtils as CU #----------------------------------------------------------------------------------------- def GaussWin (Dis, Sig): return", "Par=50., Delta=0.1, SphereGrid=False, Box=[], Buffer=[], Grid=[], Threshold=-100, Unwrap=False, ZeroRates=False): if", "selection DbS = Sel.AreaSelect(Db, Wkt, Owrite=0, Buffer=Buffer, Unwrap=Unwrap) x,y,z =", "Buffer=Buffer, Unwrap=Unwrap) x,y,z = Exp.GetHypocenter(DbS) # Creating the mesh grid", "def GaussWin (Dis, Sig): return np.exp(-(Dis**2)/(Sig**2.)) #----------------------------------------------------------------------------------------- def SmoothMFD (Db,", "i > 0. else i+360. for i in x] P.Unwrap()", "0. else i+360. for i in x] P.Unwrap() if Grid:", "Owrite=0, Buffer=Buffer, Unwrap=Unwrap) x,y,z = Exp.GetHypocenter(DbS) # Creating the mesh", "-*- # import numpy as np import .Selection as Sel", "if SphereGrid: XY = P.SphereGrid(Delta=Delta, Unwrap=Unwrap) else: XY = P.CartGrid(Dx=Delta,", "# Scaling and normalising the rates Norm = np.sum(Win) A", "x] P.Unwrap() if Grid: XY = [G for G in", "Delta=0.1, SphereGrid=False, Box=[], Buffer=[], Grid=[], Threshold=-100, Unwrap=False, ZeroRates=False): if Par", "else x-360. for x in X] return X, Y, A", "Box=[], Buffer=[], Grid=[], Threshold=-100, Unwrap=False, ZeroRates=False): if Par <= 0:", "Norm = np.sum(Win) A = []; X = []; Y", "Exp import .CatUtils as CU #----------------------------------------------------------------------------------------- def GaussWin (Dis, Sig):", "threshold aT = -np.inf if ZeroRates: A.append(aT) X.append(XY[I][0]) Y.append(XY[I][1]) else:", "np.inf # Catalogue selection DbS = Sel.AreaSelect(Db, Wkt, Owrite=0, Buffer=Buffer,", "Unwrap: # Wrap back longitudes X = [x if x", "Grid if P.IsInside(G[0], G[1])] else: if SphereGrid: XY = P.SphereGrid(Delta=Delta,", "< Threshold: # Filter below threshold aT = -np.inf if", "Y = [] for I,W in enumerate(Win): aT = -np.inf", "> -np.inf: A.append(aT) X.append(XY[I][0]) Y.append(XY[I][1]) if Unwrap: # Wrap back", "= P.CartGrid(Dx=Delta, Dy=Delta, Bounds=Box) Win = [] for xyP in", "x,y,z = Exp.GetHypocenter(DbS) # Creating the mesh grid P =", "Bounds=Box) Win = [] for xyP in XY: Win.append(0) for", "Y.append(XY[I][1]) else: if aT > -np.inf: A.append(aT) X.append(XY[I][0]) Y.append(XY[I][1]) if", "P.Load(Wkt) # Unwrapping coordinates if Unwrap: x = [i if", "# Wrap back longitudes X = [x if x <", "and W > 0.: aT = a + np.log10(W/Norm) if", ".Selection as Sel import .Exploration as Exp import .CatUtils as", "= np.sum(Win) A = []; X = []; Y =", "Dy=Delta, Bounds=Box) Win = [] for xyP in XY: Win.append(0)", "aT = a + np.log10(W/Norm) if aT < Threshold: #", "import .Selection as Sel import .Exploration as Exp import .CatUtils", "= a + np.log10(W/Norm) if aT < Threshold: # Filter", "if Grid: XY = [G for G in Grid if", "A.append(aT) X.append(XY[I][0]) Y.append(XY[I][1]) if Unwrap: # Wrap back longitudes X", "SphereGrid: XY = P.SphereGrid(Delta=Delta, Unwrap=Unwrap) else: XY = P.CartGrid(Dx=Delta, Dy=Delta,", "[G for G in Grid if P.IsInside(G[0], G[1])] else: if", "in Grid if P.IsInside(G[0], G[1])] else: if SphereGrid: XY =", "below threshold aT = -np.inf if ZeroRates: A.append(aT) X.append(XY[I][0]) Y.append(XY[I][1])", "xyP in XY: Win.append(0) for xyE in zip(x,y): Dis =", "Sel import .Exploration as Exp import .CatUtils as CU #-----------------------------------------------------------------------------------------", "= -np.inf if Norm > 0. and W > 0.:", "Wrap back longitudes X = [x if x < 180.", "Window=GaussWin, Par=50., Delta=0.1, SphereGrid=False, Box=[], Buffer=[], Grid=[], Threshold=-100, Unwrap=False, ZeroRates=False):", "-np.inf if ZeroRates: A.append(aT) X.append(XY[I][0]) Y.append(XY[I][1]) else: if aT >", "P.IsInside(G[0], G[1])] else: if SphereGrid: XY = P.SphereGrid(Delta=Delta, Unwrap=Unwrap) else:", "ZeroRates: A.append(aT) X.append(XY[I][0]) Y.append(XY[I][1]) else: if aT > -np.inf: A.append(aT)", "import .Exploration as Exp import .CatUtils as CU #----------------------------------------------------------------------------------------- def", "for G in Grid if P.IsInside(G[0], G[1])] else: if SphereGrid:", "CU #----------------------------------------------------------------------------------------- def GaussWin (Dis, Sig): return np.exp(-(Dis**2)/(Sig**2.)) #----------------------------------------------------------------------------------------- def", "-np.inf: A.append(aT) X.append(XY[I][0]) Y.append(XY[I][1]) if Unwrap: # Wrap back longitudes", "Par) # Scaling and normalising the rates Norm = np.sum(Win)", "if Unwrap: # Wrap back longitudes X = [x if", "XY = P.SphereGrid(Delta=Delta, Unwrap=Unwrap) else: XY = P.CartGrid(Dx=Delta, Dy=Delta, Bounds=Box)", "ZeroRates=False): if Par <= 0: Par = np.inf # Catalogue", "back longitudes X = [x if x < 180. else", "Win = [] for xyP in XY: Win.append(0) for xyE", "xyP[0], xyE[1], xyE[0]) Win[-1] += Window(Dis, Par) # Scaling and", "longitudes X = [x if x < 180. else x-360.", "mesh grid P = CU.Polygon() P.Load(Wkt) # Unwrapping coordinates if", "xyE in zip(x,y): Dis = CU.WgsDistance(xyP[1], xyP[0], xyE[1], xyE[0]) Win[-1]", "P.Unwrap() if Grid: XY = [G for G in Grid", "zip(x,y): Dis = CU.WgsDistance(xyP[1], xyP[0], xyE[1], xyE[0]) Win[-1] += Window(Dis,", "A.append(aT) X.append(XY[I][0]) Y.append(XY[I][1]) else: if aT > -np.inf: A.append(aT) X.append(XY[I][0])", "< 180. else x-360. for x in X] return X,", "(Db, a, Wkt, Window=GaussWin, Par=50., Delta=0.1, SphereGrid=False, Box=[], Buffer=[], Grid=[],", "Win.append(0) for xyE in zip(x,y): Dis = CU.WgsDistance(xyP[1], xyP[0], xyE[1],", "a + np.log10(W/Norm) if aT < Threshold: # Filter below", "[] for I,W in enumerate(Win): aT = -np.inf if Norm", "as CU #----------------------------------------------------------------------------------------- def GaussWin (Dis, Sig): return np.exp(-(Dis**2)/(Sig**2.)) #-----------------------------------------------------------------------------------------", "> 0. else i+360. for i in x] P.Unwrap() if", "0. and W > 0.: aT = a + np.log10(W/Norm)", ".CatUtils as CU #----------------------------------------------------------------------------------------- def GaussWin (Dis, Sig): return np.exp(-(Dis**2)/(Sig**2.))", "rates Norm = np.sum(Win) A = []; X = [];", "= [G for G in Grid if P.IsInside(G[0], G[1])] else:", "-np.inf if Norm > 0. and W > 0.: aT", "if aT < Threshold: # Filter below threshold aT =", "coding: utf-8 -*- # import numpy as np import .Selection", "= np.inf # Catalogue selection DbS = Sel.AreaSelect(Db, Wkt, Owrite=0,", "Grid: XY = [G for G in Grid if P.IsInside(G[0],", "0.: aT = a + np.log10(W/Norm) if aT < Threshold:", "aT = -np.inf if Norm > 0. and W >", "<filename>geoist/cattools/Smoothing.py #!/usr/bin/env python # -*- coding: utf-8 -*- # import", "in enumerate(Win): aT = -np.inf if Norm > 0. and", "if Norm > 0. and W > 0.: aT =", "Creating the mesh grid P = CU.Polygon() P.Load(Wkt) # Unwrapping", "Buffer=[], Grid=[], Threshold=-100, Unwrap=False, ZeroRates=False): if Par <= 0: Par", "GaussWin (Dis, Sig): return np.exp(-(Dis**2)/(Sig**2.)) #----------------------------------------------------------------------------------------- def SmoothMFD (Db, a,", "np.sum(Win) A = []; X = []; Y = []", "i in x] P.Unwrap() if Grid: XY = [G for", "if ZeroRates: A.append(aT) X.append(XY[I][0]) Y.append(XY[I][1]) else: if aT > -np.inf:", "the rates Norm = np.sum(Win) A = []; X =", "Window(Dis, Par) # Scaling and normalising the rates Norm =", "utf-8 -*- # import numpy as np import .Selection as", "else i+360. for i in x] P.Unwrap() if Grid: XY", "numpy as np import .Selection as Sel import .Exploration as", "np import .Selection as Sel import .Exploration as Exp import", "G in Grid if P.IsInside(G[0], G[1])] else: if SphereGrid: XY", "the mesh grid P = CU.Polygon() P.Load(Wkt) # Unwrapping coordinates", "and normalising the rates Norm = np.sum(Win) A = [];", "X.append(XY[I][0]) Y.append(XY[I][1]) if Unwrap: # Wrap back longitudes X =", "[]; Y = [] for I,W in enumerate(Win): aT =", "np.exp(-(Dis**2)/(Sig**2.)) #----------------------------------------------------------------------------------------- def SmoothMFD (Db, a, Wkt, Window=GaussWin, Par=50., Delta=0.1,", "Win[-1] += Window(Dis, Par) # Scaling and normalising the rates", "I,W in enumerate(Win): aT = -np.inf if Norm > 0.", "= P.SphereGrid(Delta=Delta, Unwrap=Unwrap) else: XY = P.CartGrid(Dx=Delta, Dy=Delta, Bounds=Box) Win", "CU.Polygon() P.Load(Wkt) # Unwrapping coordinates if Unwrap: x = [i", "+ np.log10(W/Norm) if aT < Threshold: # Filter below threshold", "# Catalogue selection DbS = Sel.AreaSelect(Db, Wkt, Owrite=0, Buffer=Buffer, Unwrap=Unwrap)", "Par = np.inf # Catalogue selection DbS = Sel.AreaSelect(Db, Wkt,", "> 0.: aT = a + np.log10(W/Norm) if aT <", "X.append(XY[I][0]) Y.append(XY[I][1]) else: if aT > -np.inf: A.append(aT) X.append(XY[I][0]) Y.append(XY[I][1])", "180. else x-360. for x in X] return X, Y,", "[]; X = []; Y = [] for I,W in", "P = CU.Polygon() P.Load(Wkt) # Unwrapping coordinates if Unwrap: x", "i+360. for i in x] P.Unwrap() if Grid: XY =", "[] for xyP in XY: Win.append(0) for xyE in zip(x,y):", "0: Par = np.inf # Catalogue selection DbS = Sel.AreaSelect(Db,", "Scaling and normalising the rates Norm = np.sum(Win) A =", "Wkt, Owrite=0, Buffer=Buffer, Unwrap=Unwrap) x,y,z = Exp.GetHypocenter(DbS) # Creating the", "else: if SphereGrid: XY = P.SphereGrid(Delta=Delta, Unwrap=Unwrap) else: XY =", "Grid=[], Threshold=-100, Unwrap=False, ZeroRates=False): if Par <= 0: Par =", "= []; Y = [] for I,W in enumerate(Win): aT", "-*- coding: utf-8 -*- # import numpy as np import", "= [i if i > 0. else i+360. for i", "in x] P.Unwrap() if Grid: XY = [G for G", "XY = [G for G in Grid if P.IsInside(G[0], G[1])]", "enumerate(Win): aT = -np.inf if Norm > 0. and W", "in XY: Win.append(0) for xyE in zip(x,y): Dis = CU.WgsDistance(xyP[1],", "Exp.GetHypocenter(DbS) # Creating the mesh grid P = CU.Polygon() P.Load(Wkt)", "np.log10(W/Norm) if aT < Threshold: # Filter below threshold aT", "Norm > 0. and W > 0.: aT = a", "= -np.inf if ZeroRates: A.append(aT) X.append(XY[I][0]) Y.append(XY[I][1]) else: if aT", "x = [i if i > 0. else i+360. for", "Threshold: # Filter below threshold aT = -np.inf if ZeroRates:", "X = [x if x < 180. else x-360. for", "# Creating the mesh grid P = CU.Polygon() P.Load(Wkt) #", "SmoothMFD (Db, a, Wkt, Window=GaussWin, Par=50., Delta=0.1, SphereGrid=False, Box=[], Buffer=[],", "Unwrapping coordinates if Unwrap: x = [i if i >", "Sel.AreaSelect(Db, Wkt, Owrite=0, Buffer=Buffer, Unwrap=Unwrap) x,y,z = Exp.GetHypocenter(DbS) # Creating" ]
[ "each of them for start_offset, length in terms_offsets: result =", "the Automaton offsets and create Recognizer result for each of", "lexicon :param text: text for recognition :param entities: supported entities", "means prepositions are not allowed) is the default \"\"\" super().__init__(name=name,", "start=start_offset, end=start_offset + length, score=self.DEFAULT_CONFIDENCE_LEVEL, analysis_explanation=AnalysisExplanation(self.name, self.DEFAULT_CONFIDENCE_LEVEL), recognition_metadata={RecognizerResult.RECOGNIZER_NAME_KEY: self.name} )", "def __init__(self, name: str, supported_entity: str, phrase_list: List[str], supported_language: str", "offsets and create Recognizer result for each of them for", "entity (in addition to the lexicon phrase itself). Empty list", "on a lexicon \"\"\" DEFAULT_CONFIDENCE_LEVEL = 0.7 # expected confidence", "entity type to be associated with the entities recognized by", "recognizer def __init__(self, name: str, supported_entity: str, phrase_list: List[str], supported_language:", "+ length, score=self.DEFAULT_CONFIDENCE_LEVEL, analysis_explanation=AnalysisExplanation(self.name, self.DEFAULT_CONFIDENCE_LEVEL), recognition_metadata={RecognizerResult.RECOGNIZER_NAME_KEY: self.name} ) results.append(result) return", "be associated with the entities recognized by the lexicon based", "text for recognition :param entities: supported entities :param nlp_artifacts: artifacts", "nlp_artifacts: artifacts of the nlp engine :return list of entities", "which extends the EntityRecognizer (@Presidio) and recognize entities based on", "EntityRecognizer (@Presidio) and recognize entities based on a lexicon \"\"\"", "entities :param nlp_artifacts: artifacts of the nlp engine :return list", "typing import List from presidio_analyzer import EntityRecognizer, RecognizerResult, AnalysisExplanation from", "= self.terms_recognizer(text, prefixes=self.allowed_prepositions) # Iterate over the Automaton offsets and", "presidio_analyzer import EntityRecognizer, RecognizerResult, AnalysisExplanation from presidio_analyzer.nlp_engine import NlpArtifacts from", "from presidio_analyzer.nlp_engine import NlpArtifacts from hebsafeharbor.common.terms_recognizer import TermsRecognizer class LexiconBasedRecognizer(EntityRecognizer):", "is required.\"\"\" pass def analyze( self, text: str, entities: List[str],", "List[str], nlp_artifacts: NlpArtifacts ) -> List[RecognizerResult]: \"\"\" Recognize entities based", "supported_language=supported_language) self.terms_recognizer = TermsRecognizer(phrase_list) self.allowed_prepositions = allowed_prepositions if allowed_prepositions else", "Iterate over the Automaton offsets and create Recognizer result for", "= 0.7 # expected confidence level for this recognizer def", "hebsafeharbor.common.terms_recognizer import TermsRecognizer class LexiconBasedRecognizer(EntityRecognizer): \"\"\" A class which extends", "text: str, entities: List[str], nlp_artifacts: NlpArtifacts ) -> List[RecognizerResult]: \"\"\"", "name: str, supported_entity: str, phrase_list: List[str], supported_language: str = \"he\",", "extends the EntityRecognizer (@Presidio) and recognize entities based on a", "for recognition :param entities: supported entities :param nlp_artifacts: artifacts of", "nlp_artifacts: NlpArtifacts ) -> List[RecognizerResult]: \"\"\" Recognize entities based on", "LexiconBasedRecognizer :param name: recognizer's name :param supported_entity: entity type to", "lexicon \"\"\" DEFAULT_CONFIDENCE_LEVEL = 0.7 # expected confidence level for", "allowed to be recognized as part of the entity (in", "def load(self) -> None: \"\"\"No loading is required.\"\"\" pass def", "= None): \"\"\" Initializes Hebrew LexiconBasedRecognizer :param name: recognizer's name", "in terms_offsets: result = RecognizerResult( entity_type=self.supported_entities[0], start=start_offset, end=start_offset + length,", "(@Presidio) and recognize entities based on a lexicon \"\"\" DEFAULT_CONFIDENCE_LEVEL", "self.terms_recognizer(text, prefixes=self.allowed_prepositions) # Iterate over the Automaton offsets and create", "[] def load(self) -> None: \"\"\"No loading is required.\"\"\" pass", "-> List[RecognizerResult]: \"\"\" Recognize entities based on lexicon :param text:", "RecognizerResult( entity_type=self.supported_entities[0], start=start_offset, end=start_offset + length, score=self.DEFAULT_CONFIDENCE_LEVEL, analysis_explanation=AnalysisExplanation(self.name, self.DEFAULT_CONFIDENCE_LEVEL), recognition_metadata={RecognizerResult.RECOGNIZER_NAME_KEY:", "based on a lexicon \"\"\" DEFAULT_CONFIDENCE_LEVEL = 0.7 # expected", "prepositions are not allowed) is the default \"\"\" super().__init__(name=name, supported_entities=[supported_entity],", "for each of them for start_offset, length in terms_offsets: result", "allowed_prepositions else [] def load(self) -> None: \"\"\"No loading is", "entities recognized by the lexicon based recognizer :param phrase_list: lexicon's", "associated with the entities recognized by the lexicon based recognizer", "List[str] = None): \"\"\" Initializes Hebrew LexiconBasedRecognizer :param name: recognizer's", "Hebrew is the default :param allowed_prepositions: prepositions that allowed to", "addition to the lexicon phrase itself). Empty list (which means", "LexiconBasedRecognizer(EntityRecognizer): \"\"\" A class which extends the EntityRecognizer (@Presidio) and", "load(self) -> None: \"\"\"No loading is required.\"\"\" pass def analyze(", "required.\"\"\" pass def analyze( self, text: str, entities: List[str], nlp_artifacts:", "TermsRecognizer(phrase_list) self.allowed_prepositions = allowed_prepositions if allowed_prepositions else [] def load(self)", "result for each of them for start_offset, length in terms_offsets:", "this recognizer def __init__(self, name: str, supported_entity: str, phrase_list: List[str],", "lexicon's phrases :param supported_language: the language that the recognizer supports.", "loading is required.\"\"\" pass def analyze( self, text: str, entities:", "Hebrew LexiconBasedRecognizer :param name: recognizer's name :param supported_entity: entity type", "None: \"\"\"No loading is required.\"\"\" pass def analyze( self, text:", "a lexicon \"\"\" DEFAULT_CONFIDENCE_LEVEL = 0.7 # expected confidence level", "supported_language: str = \"he\", allowed_prepositions: List[str] = None): \"\"\" Initializes", "for start_offset, length in terms_offsets: result = RecognizerResult( entity_type=self.supported_entities[0], start=start_offset,", "entities: supported entities :param nlp_artifacts: artifacts of the nlp engine", "supported_entities=[supported_entity], supported_language=supported_language) self.terms_recognizer = TermsRecognizer(phrase_list) self.allowed_prepositions = allowed_prepositions if allowed_prepositions", "\"\"\" Initializes Hebrew LexiconBasedRecognizer :param name: recognizer's name :param supported_entity:", "List[str], supported_language: str = \"he\", allowed_prepositions: List[str] = None): \"\"\"", "supported_language: the language that the recognizer supports. Hebrew is the", "type to be associated with the entities recognized by the", "import List from presidio_analyzer import EntityRecognizer, RecognizerResult, AnalysisExplanation from presidio_analyzer.nlp_engine", "class LexiconBasedRecognizer(EntityRecognizer): \"\"\" A class which extends the EntityRecognizer (@Presidio)", "as part of the entity (in addition to the lexicon", ":param nlp_artifacts: artifacts of the nlp engine :return list of", "Empty list (which means prepositions are not allowed) is the", "default :param allowed_prepositions: prepositions that allowed to be recognized as", "terms_offsets = self.terms_recognizer(text, prefixes=self.allowed_prepositions) # Iterate over the Automaton offsets", ":param supported_language: the language that the recognizer supports. Hebrew is", "\"\"\"No loading is required.\"\"\" pass def analyze( self, text: str,", "List from presidio_analyzer import EntityRecognizer, RecognizerResult, AnalysisExplanation from presidio_analyzer.nlp_engine import", "recognizer's name :param supported_entity: entity type to be associated with", "supported entities :param nlp_artifacts: artifacts of the nlp engine :return", "on lexicon :param text: text for recognition :param entities: supported", "of the nlp engine :return list of entities recognized based", "be recognized as part of the entity (in addition to", "based on the lexicon \"\"\" results = [] terms_offsets =", "Recognize entities based on lexicon :param text: text for recognition", ":param entities: supported entities :param nlp_artifacts: artifacts of the nlp", "lexicon \"\"\" results = [] terms_offsets = self.terms_recognizer(text, prefixes=self.allowed_prepositions) #", "level for this recognizer def __init__(self, name: str, supported_entity: str,", "supported_entity: str, phrase_list: List[str], supported_language: str = \"he\", allowed_prepositions: List[str]", "(which means prepositions are not allowed) is the default \"\"\"", "not allowed) is the default \"\"\" super().__init__(name=name, supported_entities=[supported_entity], supported_language=supported_language) self.terms_recognizer", "them for start_offset, length in terms_offsets: result = RecognizerResult( entity_type=self.supported_entities[0],", "None): \"\"\" Initializes Hebrew LexiconBasedRecognizer :param name: recognizer's name :param", "language that the recognizer supports. Hebrew is the default :param", "else [] def load(self) -> None: \"\"\"No loading is required.\"\"\"", "from typing import List from presidio_analyzer import EntityRecognizer, RecognizerResult, AnalysisExplanation", "DEFAULT_CONFIDENCE_LEVEL = 0.7 # expected confidence level for this recognizer", "import EntityRecognizer, RecognizerResult, AnalysisExplanation from presidio_analyzer.nlp_engine import NlpArtifacts from hebsafeharbor.common.terms_recognizer", "Initializes Hebrew LexiconBasedRecognizer :param name: recognizer's name :param supported_entity: entity", "phrase itself). Empty list (which means prepositions are not allowed)", "str = \"he\", allowed_prepositions: List[str] = None): \"\"\" Initializes Hebrew", "length in terms_offsets: result = RecognizerResult( entity_type=self.supported_entities[0], start=start_offset, end=start_offset +", "from presidio_analyzer import EntityRecognizer, RecognizerResult, AnalysisExplanation from presidio_analyzer.nlp_engine import NlpArtifacts", "the recognizer supports. Hebrew is the default :param allowed_prepositions: prepositions", "str, entities: List[str], nlp_artifacts: NlpArtifacts ) -> List[RecognizerResult]: \"\"\" Recognize", "to the lexicon phrase itself). Empty list (which means prepositions", "name: recognizer's name :param supported_entity: entity type to be associated", "def analyze( self, text: str, entities: List[str], nlp_artifacts: NlpArtifacts )", "import TermsRecognizer class LexiconBasedRecognizer(EntityRecognizer): \"\"\" A class which extends the", "= \"he\", allowed_prepositions: List[str] = None): \"\"\" Initializes Hebrew LexiconBasedRecognizer", "the default \"\"\" super().__init__(name=name, supported_entities=[supported_entity], supported_language=supported_language) self.terms_recognizer = TermsRecognizer(phrase_list) self.allowed_prepositions", "\"\"\" super().__init__(name=name, supported_entities=[supported_entity], supported_language=supported_language) self.terms_recognizer = TermsRecognizer(phrase_list) self.allowed_prepositions = allowed_prepositions", "supports. Hebrew is the default :param allowed_prepositions: prepositions that allowed", "= allowed_prepositions if allowed_prepositions else [] def load(self) -> None:", "phrase_list: lexicon's phrases :param supported_language: the language that the recognizer", "self.allowed_prepositions = allowed_prepositions if allowed_prepositions else [] def load(self) ->", "of entities recognized based on the lexicon \"\"\" results =", "expected confidence level for this recognizer def __init__(self, name: str,", "supported_entity: entity type to be associated with the entities recognized", "text: text for recognition :param entities: supported entities :param nlp_artifacts:", "the default :param allowed_prepositions: prepositions that allowed to be recognized", "List[RecognizerResult]: \"\"\" Recognize entities based on lexicon :param text: text", "allowed_prepositions if allowed_prepositions else [] def load(self) -> None: \"\"\"No", "entities recognized based on the lexicon \"\"\" results = []", "results = [] terms_offsets = self.terms_recognizer(text, prefixes=self.allowed_prepositions) # Iterate over", "nlp engine :return list of entities recognized based on the", "\"he\", allowed_prepositions: List[str] = None): \"\"\" Initializes Hebrew LexiconBasedRecognizer :param", "of the entity (in addition to the lexicon phrase itself).", "NlpArtifacts ) -> List[RecognizerResult]: \"\"\" Recognize entities based on lexicon", "entities based on lexicon :param text: text for recognition :param", "name :param supported_entity: entity type to be associated with the", "to be associated with the entities recognized by the lexicon", "\"\"\" A class which extends the EntityRecognizer (@Presidio) and recognize", "are not allowed) is the default \"\"\" super().__init__(name=name, supported_entities=[supported_entity], supported_language=supported_language)", "engine :return list of entities recognized based on the lexicon", "that the recognizer supports. Hebrew is the default :param allowed_prepositions:", "create Recognizer result for each of them for start_offset, length", "the EntityRecognizer (@Presidio) and recognize entities based on a lexicon", "on the lexicon \"\"\" results = [] terms_offsets = self.terms_recognizer(text,", "of them for start_offset, length in terms_offsets: result = RecognizerResult(", "class which extends the EntityRecognizer (@Presidio) and recognize entities based", "\"\"\" Recognize entities based on lexicon :param text: text for", "for this recognizer def __init__(self, name: str, supported_entity: str, phrase_list:", "is the default \"\"\" super().__init__(name=name, supported_entities=[supported_entity], supported_language=supported_language) self.terms_recognizer = TermsRecognizer(phrase_list)", "part of the entity (in addition to the lexicon phrase", "-> None: \"\"\"No loading is required.\"\"\" pass def analyze( self,", "lexicon based recognizer :param phrase_list: lexicon's phrases :param supported_language: the", "super().__init__(name=name, supported_entities=[supported_entity], supported_language=supported_language) self.terms_recognizer = TermsRecognizer(phrase_list) self.allowed_prepositions = allowed_prepositions if", "length, score=self.DEFAULT_CONFIDENCE_LEVEL, analysis_explanation=AnalysisExplanation(self.name, self.DEFAULT_CONFIDENCE_LEVEL), recognition_metadata={RecognizerResult.RECOGNIZER_NAME_KEY: self.name} ) results.append(result) return results", "the entities recognized by the lexicon based recognizer :param phrase_list:", "presidio_analyzer.nlp_engine import NlpArtifacts from hebsafeharbor.common.terms_recognizer import TermsRecognizer class LexiconBasedRecognizer(EntityRecognizer): \"\"\"", "(in addition to the lexicon phrase itself). Empty list (which", "allowed) is the default \"\"\" super().__init__(name=name, supported_entities=[supported_entity], supported_language=supported_language) self.terms_recognizer =", "recognizer supports. Hebrew is the default :param allowed_prepositions: prepositions that", "pass def analyze( self, text: str, entities: List[str], nlp_artifacts: NlpArtifacts", "list (which means prepositions are not allowed) is the default", "\"\"\" results = [] terms_offsets = self.terms_recognizer(text, prefixes=self.allowed_prepositions) # Iterate", "itself). Empty list (which means prepositions are not allowed) is", "artifacts of the nlp engine :return list of entities recognized", "import NlpArtifacts from hebsafeharbor.common.terms_recognizer import TermsRecognizer class LexiconBasedRecognizer(EntityRecognizer): \"\"\" A", ":param phrase_list: lexicon's phrases :param supported_language: the language that the", "recognized by the lexicon based recognizer :param phrase_list: lexicon's phrases", "if allowed_prepositions else [] def load(self) -> None: \"\"\"No loading", "recognize entities based on a lexicon \"\"\" DEFAULT_CONFIDENCE_LEVEL = 0.7", "AnalysisExplanation from presidio_analyzer.nlp_engine import NlpArtifacts from hebsafeharbor.common.terms_recognizer import TermsRecognizer class", ":param supported_entity: entity type to be associated with the entities", "recognized as part of the entity (in addition to the", "recognition :param entities: supported entities :param nlp_artifacts: artifacts of the", "NlpArtifacts from hebsafeharbor.common.terms_recognizer import TermsRecognizer class LexiconBasedRecognizer(EntityRecognizer): \"\"\" A class", ":param name: recognizer's name :param supported_entity: entity type to be", "str, supported_entity: str, phrase_list: List[str], supported_language: str = \"he\", allowed_prepositions:", "Automaton offsets and create Recognizer result for each of them", "by the lexicon based recognizer :param phrase_list: lexicon's phrases :param", "A class which extends the EntityRecognizer (@Presidio) and recognize entities", "from hebsafeharbor.common.terms_recognizer import TermsRecognizer class LexiconBasedRecognizer(EntityRecognizer): \"\"\" A class which", "the lexicon based recognizer :param phrase_list: lexicon's phrases :param supported_language:", "entities: List[str], nlp_artifacts: NlpArtifacts ) -> List[RecognizerResult]: \"\"\" Recognize entities", "based on lexicon :param text: text for recognition :param entities:", "that allowed to be recognized as part of the entity", "and recognize entities based on a lexicon \"\"\" DEFAULT_CONFIDENCE_LEVEL =", ") -> List[RecognizerResult]: \"\"\" Recognize entities based on lexicon :param", "default \"\"\" super().__init__(name=name, supported_entities=[supported_entity], supported_language=supported_language) self.terms_recognizer = TermsRecognizer(phrase_list) self.allowed_prepositions =", "# Iterate over the Automaton offsets and create Recognizer result", "start_offset, length in terms_offsets: result = RecognizerResult( entity_type=self.supported_entities[0], start=start_offset, end=start_offset", "RecognizerResult, AnalysisExplanation from presidio_analyzer.nlp_engine import NlpArtifacts from hebsafeharbor.common.terms_recognizer import TermsRecognizer", "allowed_prepositions: List[str] = None): \"\"\" Initializes Hebrew LexiconBasedRecognizer :param name:", "end=start_offset + length, score=self.DEFAULT_CONFIDENCE_LEVEL, analysis_explanation=AnalysisExplanation(self.name, self.DEFAULT_CONFIDENCE_LEVEL), recognition_metadata={RecognizerResult.RECOGNIZER_NAME_KEY: self.name} ) results.append(result)", "phrase_list: List[str], supported_language: str = \"he\", allowed_prepositions: List[str] = None):", "__init__(self, name: str, supported_entity: str, phrase_list: List[str], supported_language: str =", "prefixes=self.allowed_prepositions) # Iterate over the Automaton offsets and create Recognizer", "the lexicon \"\"\" results = [] terms_offsets = self.terms_recognizer(text, prefixes=self.allowed_prepositions)", "= [] terms_offsets = self.terms_recognizer(text, prefixes=self.allowed_prepositions) # Iterate over the", "over the Automaton offsets and create Recognizer result for each", "\"\"\" DEFAULT_CONFIDENCE_LEVEL = 0.7 # expected confidence level for this", "TermsRecognizer class LexiconBasedRecognizer(EntityRecognizer): \"\"\" A class which extends the EntityRecognizer", "= TermsRecognizer(phrase_list) self.allowed_prepositions = allowed_prepositions if allowed_prepositions else [] def", ":param text: text for recognition :param entities: supported entities :param", "the entity (in addition to the lexicon phrase itself). Empty", "0.7 # expected confidence level for this recognizer def __init__(self,", "based recognizer :param phrase_list: lexicon's phrases :param supported_language: the language", "str, phrase_list: List[str], supported_language: str = \"he\", allowed_prepositions: List[str] =", "= RecognizerResult( entity_type=self.supported_entities[0], start=start_offset, end=start_offset + length, score=self.DEFAULT_CONFIDENCE_LEVEL, analysis_explanation=AnalysisExplanation(self.name, self.DEFAULT_CONFIDENCE_LEVEL),", "self, text: str, entities: List[str], nlp_artifacts: NlpArtifacts ) -> List[RecognizerResult]:", "and create Recognizer result for each of them for start_offset,", "with the entities recognized by the lexicon based recognizer :param", "phrases :param supported_language: the language that the recognizer supports. Hebrew", "prepositions that allowed to be recognized as part of the", "the nlp engine :return list of entities recognized based on", "list of entities recognized based on the lexicon \"\"\" results", ":param allowed_prepositions: prepositions that allowed to be recognized as part", "entities based on a lexicon \"\"\" DEFAULT_CONFIDENCE_LEVEL = 0.7 #", "terms_offsets: result = RecognizerResult( entity_type=self.supported_entities[0], start=start_offset, end=start_offset + length, score=self.DEFAULT_CONFIDENCE_LEVEL,", "lexicon phrase itself). Empty list (which means prepositions are not", "self.terms_recognizer = TermsRecognizer(phrase_list) self.allowed_prepositions = allowed_prepositions if allowed_prepositions else []", "recognized based on the lexicon \"\"\" results = [] terms_offsets", "result = RecognizerResult( entity_type=self.supported_entities[0], start=start_offset, end=start_offset + length, score=self.DEFAULT_CONFIDENCE_LEVEL, analysis_explanation=AnalysisExplanation(self.name,", "entity_type=self.supported_entities[0], start=start_offset, end=start_offset + length, score=self.DEFAULT_CONFIDENCE_LEVEL, analysis_explanation=AnalysisExplanation(self.name, self.DEFAULT_CONFIDENCE_LEVEL), recognition_metadata={RecognizerResult.RECOGNIZER_NAME_KEY: self.name}", "is the default :param allowed_prepositions: prepositions that allowed to be", "the language that the recognizer supports. Hebrew is the default", "allowed_prepositions: prepositions that allowed to be recognized as part of", "to be recognized as part of the entity (in addition", "the lexicon phrase itself). Empty list (which means prepositions are", "analyze( self, text: str, entities: List[str], nlp_artifacts: NlpArtifacts ) ->", "recognizer :param phrase_list: lexicon's phrases :param supported_language: the language that", "Recognizer result for each of them for start_offset, length in", "# expected confidence level for this recognizer def __init__(self, name:", ":return list of entities recognized based on the lexicon \"\"\"", "[] terms_offsets = self.terms_recognizer(text, prefixes=self.allowed_prepositions) # Iterate over the Automaton", "EntityRecognizer, RecognizerResult, AnalysisExplanation from presidio_analyzer.nlp_engine import NlpArtifacts from hebsafeharbor.common.terms_recognizer import", "confidence level for this recognizer def __init__(self, name: str, supported_entity:" ]
[ "Local::in_line { 'req': ( 'goto.cc', 24, 26 ), 'res': (", "default;' ), 'range': has_entries( { 'start': has_entries( { 'line_num': 54,", "def FixIt_Check_RawStringReplace_Resolved( results ): assert_that( results, has_entries( { 'fixits': contains(", "( 'goto.cc', 36, 25 ), 'res': ( 'goto.cc', 32, 54", "28, 'column_num': 2 } ), } ), } ) ),", "'column_num': 13 } ), 'end' : has_entries( { 'line_num': 16,", "not, see <http://www.gnu.org/licenses/>. from __future__ import absolute_import from __future__ import", "14, 13 ), ( 'goto.cc', 25, 22 ) ] },", "with no fixits assert_that( results, equal_to( { 'fixits': [] }", "while 'message' in diags and 'diagnostics' in diags[ 'message' ].lower():", ") from ycmd.utils import ReadFile # This test is isolated", "}, 'struct Foo &' ], # [ { 'line_num': 28,", "has_entries( { 'line_num': 5, 'column_num': 3 } ) } )", "7 } ), 'end' : has_entries( { 'line_num': 26, 'column_num':", "cfile, FixIt_Check_cpp11_Del ], [ 40, 6, 'cpp11', cfile, FixIt_Check_cpp11_Repl ],", "[ { 'line_num': 46, 'column_num': 13 }, 'const struct Foo", "# [ { 'line_num': 42, 'column_num': 3 }, 'const Foo", "# Another_Unicøde { 'req': ( 'goto.cc', 36, 17 ), 'res':", "{ 'line_num': 25, 'column_num': 8 }, # 'Ns::Type => Ns::BasicType<char>'", "'docstring', requests.codes.ok ], # no docstring [ { 'line_num': 7,", ": ReadFile( filepath ), 'filetype' : 'cpp' } request =", "= test[ 'res' ] if isinstance( response, list ): expect", "[ { 'line_num': 45, 'column_num': 19 }, 'const int' ],", "tests: yield RunRangedFixItTest, test[ 0 ], test[ 1 ] @WithRetry", "), LineColMatcher( 17, 17 ) ), ChunkMatcher( ' ', LineColMatcher(", "), } ) ) } ) ) def FixIt_Check_cuda( results", "for refs & pointers [ { 'line_num': 39, 'column_num': 3", "3 ), LineColMatcher( 83, 17 ) ), ) } )", "'expect': { 'response': requests.codes.ok, 'data': { 'filepath': os.path.abspath( file_path ),", "25, 15 ) ] }, # Expected failure { 'req':", "contains( has_entries( { 'text': \"Expand auto type\", 'chunks': contains( ChunkMatcher(", "'Cannot jump to location' }, { 'req': ( 'main.cpp', 10,", "'line_num': 80, 'column_num': 4 }, } subexpression_extract_range = { 'start':", "{ 'req': ( 'goto.cc', 36, 17 ), 'res': ( 'goto.cc',", "FixIt_Check_MacroExpand_Resolved ], [ subexpression_extract_range, FixIt_Check_SubexprExtract_Resolved ], [ raw_string_range, FixIt_Check_RawStringReplace_Resolved ],", "'const Foo *' ], # [ { 'line_num': 32, 'column_num':", "'goto.cc', 32, 54 ) }, { 'req': ( 'goto.cc', 38,", "language_options = { 'cpp11': { 'filetype' : 'cpp', }, 'cuda':", "results ) def FixIt_Check_cpp11_Ins( results ): # First fixit #", "__future__ import print_function from __future__ import division from hamcrest.core.base_matcher import", "variable', 'chunks': contains( ChunkMatcher( 'auto dummy = foo(i + 3);\\n", "in tests: yield RunFixItTest, test[ 0 ], test[ 1 ],", "), ChunkMatcher( ' ', LineColMatcher( 17, 17 ), LineColMatcher( 17,", "'text': contains_string( 'parentheses around the assignment' ), 'chunks': contains( ChunkMatcher(", "= { 'completer_target' : 'filetype_default', 'command_arguments': command, 'line_num' : 10,", "{ 'start': has_entries( { 'line_num': 54, 'column_num': 64 } ),", "folder, command, test ): filepath = PathToTestFile( folder, test[ 'req'", "'Foo' ], [ { 'line_num': 12, 'column_num': 10 }, 'Foo'", ") language_options = { 'cpp11': { 'filetype' : 'cpp', },", "'column_num': 19 }, 'const int' ], [ { 'line_num': 46,", "}, # Another_Unicøde { 'req': ( 'goto.cc', 36, 17 ),", "{ 'line_num': 48, 'column_num': 4 } ), } ), }", "ufile = PathToTestFile( 'unicode.cc' ) tests = [ # L", "{ 'cpp11': { 'filetype' : 'cpp', }, 'cuda': { 'filetype'", "pprint import requests import os.path from ycmd.tests.clangd import ( IsolatedYcmd,", "48, 'column_num': 9 } ), } ), } ), ),", "'chunks': contains( has_entries( { 'replacement_text': equal_to( '= default;' ), 'range':", "40, 'column_num': 11 }, 'Foo *' ], [ { 'line_num':", "usage # [ { 'line_num': 34, 'column_num': 14 }, 'const", "def FixIt_Check_cpp11_SpellCheck( results ): assert_that( results, has_entries( { 'fixits': contains(", "has_entries( { 'line_num': 16, 'column_num': 13 } ), 'end' :", "has_entries( { 'fixits': contains( # Change to SpellingIsNotMyStrongPoint has_entries( {", "definition/declaration of x { 'req': ( 'goto.cc', 23, 21 ),", "'location': LineColMatcher( 3, 12 ), } ) ) } )", "# Copyright (C) 2018 ycmd contributors # # This file", "# unicode in line for fixit [ 21, 16, 'cpp11',", "} ) ) def FixIt_Check_unicode_Ins( results ): assert_that( results, has_entries(", "'command_arguments': [ 'FixIt' ], 'line_num' : line, 'column_num' : column,", "'goto.cc', 25, 22 ) ] }, # Namespace { 'req':", "has_entries( { 'line_num': 28, 'column_num': 2 } ), 'end' :", "14, 13 ) }, # GoToDeclaration alternates between definition and", "'main.cpp', 5, 11 ), 'res': ( 'system/c.hpp', 1, 1 )", "9 ), } ) ) } ) ) def FixIt_Check_cuda(", "'filepath' : filepath, 'contents' : contents, 'filetype' : filetype }", "{ 'line_num': 54, 'column_num': 15 } ) } ), )", ") ), ) } ) ) } ) ) def", "'command_arguments': [ 'GoToDefinition' ], 'line_num': 10, 'column_num': 3, 'filetype': 'cpp',", "def FixIt_Check_cpp11_InsMultiLine( results ): # Similar to FixIt_Check_cpp11_1 but inserts", "{ 'line_num': 12, 'column_num': 10 }, 'Foo' ], # [", "} ), } ) ), 'location': has_entries( { 'line_num': 21,", "'Foo' ], [ { 'line_num': 39, 'column_num': 11 }, 'Foo", ") ), 'filepath': PathToTestFile( 'basic.cpp' ), 'command_arguments': [ 'RefactorRename', 'Bar'", "12 }, 'Foo *' ], [ { 'line_num': 48, 'column_num':", "contains( *[ LocationMatcher( PathToTestFile( folder, os.path.normpath( location[ 0 ] )", "conversion to}} assert_that( results, has_entries( { 'fixits': contains( has_entries( {", "} ) ) } ) ) def Subcommands_FixIt_all_test(): cfile =", "lang ] ) test = { 'request': args, 'route': '/detailed_diagnostic'", "line for fixit [ 21, 16, 'cpp11', ufile, FixIt_Check_unicode_Ins ],", "isolated to trigger objcpp hooks, rather than fetching completer #", "'replacement_text': equal_to( 'static_cast<int>(' ), 'range': has_entries( { 'start': has_entries( {", "ReadFile( PathToTestFile( 'FixIt_Clang_cpp11.cpp' ) ) args = { 'completer_target' :", "'auto dummy = foo(i + 3);\\n ', LineColMatcher( 84, 3", "[ { 'line_num': 25, 'column_num': 3 }, 'namespace Ns' ],", "tests: yield ( RunGetSemanticTest, PathToTestFile( 'GetType_Clang_test.cc' ), 'cpp', test, [", "'location': has_entries( { 'line_num': 48, 'column_num': 3 } ) }", "12, 'column_num': 10 }, 'Foo' ], # [ { 'line_num':", "5, 'column_num': 3 } ), 'end' : has_entries( { 'line_num':", "{ 'fixits': contains( # Change to SpellingIsNotMyStrongPoint has_entries( { 'text':", "Namespace { 'req': ( 'goto.cc', 24, 17 ), 'res': [", "raw string', 'chunks': contains( ChunkMatcher( 'R\"(\\\\\\\\r\\\\asd\\n\\\\v)\"', LineColMatcher( 80, 19 ),", "FixIt_Check_cpp11_Note ], # FixIt due to forced spell checking [", "test[ 0 ] if response == requests.codes.ok: if not isinstance(", "location' }, ] for test in tests: for cmd in", "'cpp', 'completer_target': 'filetype_default', 'contents': ReadFile( PathToTestFile( 'basic.cpp' ) ), 'filepath':", "1 ] ) else: expected = test[ 1 ] request", "'struct Foo &' ], # [ { 'line_num': 28, 'column_num':", "import absolute_import from __future__ import unicode_literals from __future__ import print_function", "= { 'completer_target' : 'filetype_default', 'contents' : contents, 'filepath' :", "} ) ) def FixIt_Check_SubexprExtract_Resolved( results ): assert_that( results, has_entries(", "48, 'column_num': 12 }, 'Foo *' ], [ { 'line_num':", "'main.cpp', 10, 13 ), 'res': 'Cannot jump to location' },", "{ 'line_num': 48, 'column_num': 17 } ), } ), }", "or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU", "Local::out_of_line -> definition of Local::out_of_line { 'req': ( 'goto.cc', 25,", "Change to SpellingIsNotMyStrongPoint has_entries( { 'text': contains_string( \"change 'SpellingIsNotMyStringPiont' to", "}, 'Foo' ], [ { 'line_num': 12, 'column_num': 9 },", "'request': { 'filetype': 'cpp', 'completer_target': 'filetype_default', 'contents': ReadFile( PathToTestFile( 'basic.cpp'", "{ 'line_num': 16, 'column_num': 10 } ), 'end' : has_entries(", "3 ), LineColMatcher( 84, 3 ) ), ChunkMatcher( 'dummy', LineColMatcher(", "], # [ { 'line_num': 15, 'column_num': 7 }, 'char'", "}, 'struct Foo' ], # [ { 'line_num': 29, 'column_num':", "54,16 has_entries( { 'chunks': contains( has_entries( { 'replacement_text': equal_to( 'foo'", "0 ], test[ 1 ], test[ 2 ], test[ 3", "of the GNU General Public License as published by #", "Cursor on usage [ { 'line_num': 45, 'column_num': 13 },", "' ', LineColMatcher( 17, 17 ), LineColMatcher( 17, 17 )", "[ { 'line_num': 43, 'column_num': 16 }, 'const struct Foo", ") def FixIt_Check_cpp11_SpellCheck( results ): assert_that( results, has_entries( { 'fixits':", "'range': has_entries( { 'start': has_entries( { 'line_num': 48, 'column_num': 15", "'column_num': 18 }, 'int' ], # Auto in declaration #", "Foo &' ], [ { 'line_num': 28, 'column_num': 18 },", "3 }, 'end': { 'line_num': 83, 'column_num': 13 }, }", "1, 'objective-c', mfile, FixIt_Check_objc_NoFixIt ], [ 3, 12, 'cuda', cufile,", "'main.cpp', 1, 6 ), 'res': ( 'a.hpp', 1, 1 )", "This shows up in the type, which isn't ideal, but", "'RefactorRename', 'Bar' ], 'line_num': 17, 'column_num': 4, }, 'expect': {", "17, 19 ), LineColMatcher( 17, 19 ) ), ) }", "'res': ( 'system/c.hpp', 1, 1 ) }, # Expected failures", "at 54,52 has_entries( { 'chunks': contains( has_entries( { 'replacement_text': equal_to(", "'line_num': 54, 'column_num': 15 } ) } ), # second", "location' }, { 'req': ( 'main.cpp', 10, 13 ), 'res':", "'line_num': 40, 'column_num': 6 } ) } ) ) }", "} ) } ), ) } ) ) def FixIt_Check_unicode_Ins(", "FixIt_Check_MacroExpand_Resolved( results ): assert_that( results, has_entries( { 'fixits': contains( has_entries(", "= { 'start': { 'line_num': 83, 'column_num': 3 }, 'end':", "can redistribute it and/or modify # it under the terms", "'column_num': 3 }, 'const Foo *' ], # [ {", "{ 'filetype' : 'objc', }, } args = { 'completer_target'", "'line_num': 46, 'column_num': 20 }, 'const int' ], [ {", ") WaitUntilCompleterServerReady( app, 'cpp' ) response = app.post_json( '/run_completer_command', BuildRequest(", "its # folder is added with -iquote. { 'req': (", "], # [ { 'line_num': 32, 'column_num': 16 }, 'const", "}, { 'req': ( 'goto.cc', 36, 25 ), 'res': (", "if isinstance( response, list ): expect = { 'response': requests.codes.ok,", "), 'location': LineColMatcher( 72, 9 ), } ) ) }", "'column_num': 3, 'filetype': 'cpp', 'filepath': file_path }, 'expect': { 'response':", "} ), 'end' : has_entries( { 'line_num': 54, 'column_num': 67", "{ 'line_num': 54, 'column_num': 51 } ) } ), )", "), 'filepath': PathToTestFile( 'basic.cpp' ), 'command_arguments': [ 'RefactorRename', 'Bar' ],", "), LineColMatcher( 80, 36 ) ), ) } ) )", ": ReadFile( filename ), 'filepath' : filename, 'command_arguments': [ 'FixIt'", "} ) }, 'route': '/run_completer_command' } RunAfterInitialized( app, test )", "with -iquote. { 'req': ( 'main.cpp', 4, 10 ), 'res':", "\"change 'int' to 'void'\" ), 'chunks': contains( ChunkMatcher( 'void', LineColMatcher(", "Auto in usage # [ { 'line_num': 34, 'column_num': 14", "{ 'start': has_entries( { 'line_num': 28, 'column_num': 2 } ),", "54, 'column_num': 51 } ) } ), ) } )", "'=' ), 'range': has_entries( { 'start': has_entries( { 'line_num': 21,", "{ 'line_num': 22, 'column_num': 2 }, 'int main()' ], [", "): assert_that( results, has_entries( { 'fixits': contains( # Change to", "( 'quote/b.hpp', 1, 1 ) }, { 'req': ( 'main.cpp',", "from header [ { 'line_num': 6, 'column_num': 10 }, 'docstring',", "], # [ { 'line_num': 26, 'column_num': 13 }, #", "[ { 'line_num': 29, 'column_num': 18 }, 'Foo' ], #", "9 } ), 'end' : has_entries( { 'line_num': 48, 'column_num':", "'cpp11', cfile, FixIt_Check_cpp11_MultiFirst ], # should put closest fix-it first?", "requests.codes.ok, 'data': has_entries( { 'fixits': contains( has_entries( { 'chunks': contains(", "'column_num': 3 }, 'const Foo &' ], # [ {", "test[ 1 ], BaseMatcher ): expected = has_entry( 'message', contains_string(", "# folder is added with -iquote. { 'req': ( 'main.cpp',", "( 'main.cpp', 7, 1 ), 'res': 'Cannot jump to location'", "'column_num': 16 }, 'const struct Foo &' ], # [", "information.' ), requests.codes.server_error ] ] for subcommand in [ 'GetDoc',", "app.post_json( '/run_completer_command', BuildRequest( **args ) ).json pprint( results ) check(", "} args = test[ 0 ] if response == requests.codes.ok:", "test is isolated to trigger objcpp hooks, rather than fetching", ") ), 'location': has_entries( { 'line_num': 35, 'column_num': 7 }", "} ), 'end' : has_entries( { 'line_num': 21, 'column_num': 11", "20 }, } macro_expand_range = { 'start': { 'line_num': 83,", "3 ), LineColMatcher( 9, 6 ) ), ChunkMatcher( '\\n\\n', LineColMatcher(", "PathToTestFile( folder, test[ 'req' ][ 0 ] ) common_request =", ": 'cpp', }, 'cuda': { 'filetype' : 'cuda', }, 'objective-c':", "'column_num': 3 } ) } ) ) } ) )", "} ) ) def FixIt_Check_cpp11_Del( results ): # Removal of", "}, 'struct Foo &' ], [ { 'line_num': 28, 'column_num':", "12 ) ) ), 'location': LineColMatcher( 60, 1 ), }", "), } ) ), 'location': has_entries( { 'line_num': 5, 'column_num':", "'column_num': 13 }, 'Foo' ], [ { 'line_num': 36, 'column_num':", "{ 'fixits': contains( has_entries( { 'text': 'Extract subexpression to variable',", "LineColMatcher, LocationMatcher, ErrorMatcher, WithRetry, WaitUntilCompleterServerReady ) from ycmd.utils import ReadFile", "the License, or # (at your option) any later version.", "'line_num': 13, 'column_num': 3 }, 'int' ], [ { 'line_num':", "# e l Lang File, Checker [ 16, 0, 'cpp11',", "[ 7, 1, 'objective-c', mfile, FixIt_Check_objc_NoFixIt ], [ 3, 12,", "'const Foo *' ], [ { 'line_num': 43, 'column_num': 16", ") ) def FixIt_Check_MacroExpand_Resolved( results ): assert_that( results, has_entries( {", "CombineRequest( request, { 'event_name': 'FileReadyToParse', } ), expect_errors = True", "] @WithRetry @SharedYcmd def RunRangedFixItTest( app, rng, expected ): contents", "PARTICULAR PURPOSE. See the # GNU General Public License for", "] ) } elif isinstance( response, tuple ): expect =", "{ 'completer_target' : 'filetype_default', 'command_arguments': command, 'line_num' : 10, 'column_num'", "Ns::BasicType<char>' ], # [ { 'line_num': 26, 'column_num': 13 },", "], [ { 'line_num': 36, 'column_num': 13 }, 'Foo' ],", "36, 'column_num': 13 }, 'Foo' ], [ { 'line_num': 36,", "): file_path = PathToTestFile( 'GoTo_Clang_ZeroBasedLineAndColumn_test.cc' ) RunAfterInitialized( app, { 'request':", "'dummy', LineColMatcher( 84, 10 ), LineColMatcher( 84, 22 ) ),", ") ufile = PathToTestFile( 'unicode.cc' ) tests = [ #", "}, 'const int' ], [ { 'line_num': 47, 'column_num': 12", "12 ), } ) ) } ) ) def FixIt_Check_SubexprExtract_Resolved(", "), 'filepath' : filename, 'command_arguments': [ 'FixIt' ], 'line_num' :", "'column_num': 21 }, 'const int' ], # [ { 'line_num':", "'route': '/defined_subcommands', } ) @SharedYcmd def Subcommands_GoTo_ZeroBasedLineAndColumn_test( app ): file_path", "terms of the GNU General Public License as published by", "} ), 'end' : has_entries( { 'line_num': 35, 'column_num': 9", "has_entries( { 'chunks': contains( has_entries( { 'replacement_text': equal_to( 'foo' ),", "[ { 'line_num': 47, 'column_num': 17 }, 'int' ], [", "'line_num': 54, 'column_num': 58 } ), } ), } ),", "6 ), ( 'goto.cc', 23, 14 ), ( 'goto.cc', 24,", ") ), ChunkMatcher( ' ', LineColMatcher( 17, 17 ), LineColMatcher(", "}, 'route': '/defined_subcommands', } ) @SharedYcmd def Subcommands_GoTo_ZeroBasedLineAndColumn_test( app ):", "'route' : '/run_completer_command', 'expect' : expect } ) def Subcommands_GoTo_all_test():", "10 ), LineColMatcher( 84, 22 ) ), ) } )", ": has_entries( { 'line_num': 5, 'column_num': 3 } ), }", "cfile, FixIt_Check_cpp11_MultiSecond ], # unicode in line for fixit [", "} ) ) def FixIt_Check_RawStringReplace_Resolved( results ): assert_that( results, has_entries(", "80, 'column_num': 35 }, } tests = [ [ expand_auto_range,", "}, 'Foo' ], [ { 'line_num': 40, 'column_num': 3 },", "{ 'chunks': contains( has_entries( { 'replacement_text': equal_to( '=' ), 'range':", "], [ { 'line_num': 12, 'column_num': 9 }, 'Foo' ],", "), has_entries( { 'replacement_text': equal_to( ')' ), 'range': has_entries( {", "'Bar' ], 'line_num': 17, 'column_num': 4, }, 'expect': { 'response':", "[ { 'line_num': 8, 'column_num': 1 }, ErrorMatcher( RuntimeError, 'No", "} ), 'end' : has_entries( { 'line_num': 26, 'column_num': 7", "[ { 'line_num': 28, 'column_num': 18 }, 'struct Foo' ],", "'column_num': 16 }, 'const struct Foo *' ], # Cursor", "53 } ), } ), } ), has_entries( { 'replacement_text':", "'main.cpp', 2, 14 ), 'res': ( 'system/a.hpp', 1, 1 )", "} ), 'end' : has_entries( { 'line_num': 16, 'column_num': 10", "}, } tests = [ [ expand_auto_range, FixIt_Check_AutoExpand_Resolved ], [", "{ 'line_num': 25, 'column_num': 15 }, # 'Ns::Type => Ns::BasicType<char>'", "alternates between definition and declaration { 'req': ( 'goto.cc', 14,", "test in tests: yield RunGoToTest_all, '', 'GoToDeclaration', test def Subcommands_GoToInclude_test():", "expected ) request[ 'fixit' ] = expected[ 'fixits' ][ 0", "decl for refs & pointers [ { 'line_num': 39, 'column_num':", "'line_num': 2, 'column_num': 8 } }, 'route': '/run_completer_command', } )", "{ 'line_num': 35, 'column_num': 14 }, 'const Foo *' ],", "second fix-it at 54,52 has_entries( { 'chunks': contains( has_entries( {", "'resolve': True, 'command': has_entries( { 'command': 'clangd.applyTweak' } ) }", "= { 'completer_target' : 'filetype_default', 'contents' : ReadFile( filename ),", "} ) ) } ) }, 'route': '/run_completer_command' } RunAfterInitialized(", "{ 'chunks': contains( ChunkMatcher( 'Bar', LineColMatcher( 1, 8 ), LineColMatcher(", "] for test in tests: for cmd in [ 'GoToDefinition',", "spell checking [ 72, 9, 'cpp11', cfile, FixIt_Check_cpp11_SpellCheck ], ]", "'completer_target': 'filetype_default', 'line_num': 10, 'column_num': 3, 'filetype': 'objcpp', 'filepath': file_path", "= { 'request': args, 'route': '/receive_messages' } RunAfterInitialized( app, receive_diags", "LineColMatcher( 17, 19 ), LineColMatcher( 17, 19 ) ), )", "FixIt_Check_RawStringReplace_Resolved ], ] for test in tests: yield RunRangedFixItTest, test[", "54, 'column_num': 52 } ), 'end' : has_entries( { 'line_num':", "], # [ { 'line_num': 35, 'column_num': 22 }, 'const", "'end' : has_entries( { 'line_num': 28, 'column_num': 2 } ),", "( 'goto.cc', 24, 26 ), 'res': ( 'goto.cc', 6, 10", "3 }, 'Foo' ], # [ { 'line_num': 12, 'column_num':", "'range': has_entries( { 'start': has_entries( { 'line_num': 54, 'column_num': 52", "18 }, 'Foo' ], # [ { 'line_num': 31, 'column_num':", "{ 'req': ( 'goto.cc', 14, 13 ), 'res': ( 'goto.cc',", "Ns:: [ { 'line_num': 25, 'column_num': 3 }, 'namespace Ns'", "'FixIt_Clang_cpp11.cpp' ) mfile = PathToTestFile( 'objc', 'FixIt_Clang_objc.m' ) cufile =", "'completer_target': 'filetype_default', 'contents': ReadFile( PathToTestFile( 'basic.cpp' ) ), 'filepath': PathToTestFile(", "] ) ) }, 'route': '/defined_subcommands', } ) @SharedYcmd def", "[ 'RefactorRename', 'Bar' ], 'line_num': 17, 'column_num': 4, }, 'expect':", "3 }, 'struct Foo &' ], # [ { 'line_num':", "subcommand in [ 'GetType', 'GetTypeImprecise' ]: for test in tests:", "docstring [ { 'line_num': 7, 'column_num': 7 }, 'int x", "print( expected ) request[ 'fixit' ] = expected[ 'fixits' ][", "10 }, 'Foo' ], # [ { 'line_num': 13, 'column_num':", "'goto.cc', 24, 17 ), 'res': [ ( 'goto.cc', 2, 11", ") ) def FixIt_Check_cpp11_Note( results ): assert_that( results, has_entries( {", "( 'system/c.hpp', 1, 1 ) }, # Expected failures {", "13 ), 'res': ( 'goto.cc', 11, 10 ) }, {", "], # [ { 'line_num': 34, 'column_num': 21 }, 'const", "has_entries( { 'text': 'Convert to raw string', 'chunks': contains( ChunkMatcher(", "to 'void'\" ), 'chunks': contains( ChunkMatcher( 'void', LineColMatcher( 3, 12", "'Extract subexpression to variable', 'resolve': True, 'command': has_entries( { 'command':", "11 ) ), ChunkMatcher( ' ', LineColMatcher( 15, 46 ),", "tests: yield RunGoToTest_all, '', 'GoToDeclaration', test def Subcommands_GoToInclude_test(): tests =", "equal_to( 'id' ), 'range': has_entries( { 'start': has_entries( { 'line_num':", "'line_num': 54, 'column_num': 64 } ), 'end' : has_entries( {", "] = expected[ 'fixits' ][ 0 ] actual = app.post_json(", "{ 'req': ( 'goto.cc', 34, 9 ), 'res': ( 'goto.cc',", "'column_num': 13 }, 'const struct Foo *' ], # [", "GNU General Public License # along with ycmd. If not,", "29, 'column_num': 18 }, 'Foo' ], # [ { 'line_num':", "'goto.cc', 11, 10 ), 'res': ( 'goto.cc', 14, 13 )", "'/receive_messages' } RunAfterInitialized( app, receive_diags ) diags = RunAfterInitialized( app,", "), 'location': has_entries( { 'line_num': 5, 'column_num': 3 } )", "fetching completer # from cache. @IsolatedYcmd() def Subcommands_DefinedSubcommands_test( app ):", "from cache. @IsolatedYcmd() def Subcommands_DefinedSubcommands_test( app ): file_path = PathToTestFile(", "folder, os.path.normpath( location[ 0 ] ) ), location[ 1 ],", "'/run_completer_command', 'expect': { 'response': response, 'data': expected } } RunAfterInitialized(", "either version 3 of the License, or # (at your", "contains( # first fix-it at 54,16 has_entries( { 'chunks': contains(", "} ) ) } ) ) def FixIt_Check_SubexprExtract_Resolved( results ):", "expect = { 'response': requests.codes.internal_server_error, 'data': ErrorMatcher( RuntimeError, test[ 'res'", "requires /resolve_fixit request has_entries( { 'text': 'Extract subexpression to variable',", "app ): file_path = PathToTestFile( 'GoTo_Clang_ZeroBasedLineAndColumn_test.cc' ) RunAfterInitialized( app, {", "35, 'column_num': 14 }, 'const Foo *' ], # [", "# ycmd is free software: you can redistribute it and/or", "'const int' ], [ { 'line_num': 46, 'column_num': 13 },", "} ), } ) ), 'location': has_entries( { 'line_num': 5,", "1 ], test[ 2 ], test[ 3 ], test[ 4", "[ macro_expand_range, FixIt_Check_MacroExpand_Resolved ], [ subexpression_extract_range, FixIt_Check_SubexprExtract_Resolved ], [ raw_string_range,", "'Foo' ], [ { 'line_num': 40, 'column_num': 11 }, 'Foo", "b.hpp is included with angled brackets but its # folder", "requests.codes.ok ): contents = ReadFile( filepath ) common_args = {", "15 } ), 'end' : has_entries( { 'line_num': 48, 'column_num':", "LocationMatcher( PathToTestFile( folder, os.path.normpath( location[ 0 ] ) ), location[", "not isinstance( test[ 1 ], BaseMatcher ): expected = has_entry(", "[ { 'line_num': 29, 'column_num': 3 }, 'Foo *' ],", "request = common_args request.update( args ) test = { 'request':", "PathToTestFile, RunAfterInitialized ) from ycmd.tests.test_utils import ( BuildRequest, ChunkMatcher, CombineRequest,", "], [ { 'line_num': 39, 'column_num': 11 }, 'Foo &'", "def FixIt_Check_cpp11_MultiSecond( results ): assert_that( results, has_entries( { 'fixits': contains(", "13 } ), } ), } ) ), 'location': has_entries(", "2 ), LineColMatcher( 15, 1 ) ), ChunkMatcher( 'Bar', LineColMatcher(", "'chunks': contains( ChunkMatcher( 'const char *', LineColMatcher( 80, 1 ),", "), 'cpp', test, [ subcommand ], test[ 2 ] )", ": 'cuda', }, 'objective-c': { 'filetype' : 'objc', }, }", "2 ], test[ 3 ], test[ 4 ] @WithRetry @SharedYcmd", "], [ { 'line_num': 42, 'column_num': 16 }, 'const struct", "'contents' : contents, 'filepath' : PathToTestFile( 'FixIt_Clang_cpp11.cpp' ), 'command_arguments': [", "), 'command_arguments': [ 'FixIt' ], 'range' : rng, 'filetype' :", "'line_num': 21, 'column_num': 9 } ), 'end' : has_entries( {", "def FixIt_Check_objc( results ): assert_that( results, has_entries( { 'fixits': contains(", "], [ { 'line_num': 46, 'column_num': 13 }, 'const struct", "the GNU General Public License # along with ycmd. If", "'text': \"Expand macro 'DECLARE_INT'\", 'chunks': contains( ChunkMatcher( 'int i', LineColMatcher(", ") }, # FIXME: should fail since b.hpp is included", ").json print( 'actual = ' ) print( actual ) assert_that(", "'cpp', test, [ subcommand ], test[ 2 ] ) @SharedYcmd", "36, 17 ), 'res': ( 'goto.cc', 32, 54 ) },", "} ) ), 'location': has_entries( { 'line_num': 40, 'column_num': 6", "47, 'column_num': 17 }, 'int' ], [ { 'line_num': 48,", "{ 'chunks': contains( has_entries( { 'replacement_text': equal_to( '' ), 'range':", "1 ] @WithRetry @SharedYcmd def Subcommands_FixIt_AlreadyResolved_test( app ): filename =", "# Expected failures { 'req': ( 'goto.cc', 13, 1 ),", "tests: for cmd in [ 'GoToDefinition', 'GoTo', 'GoToImprecise' ]: yield", "'objc', 'FixIt_Clang_objc.m' ) cufile = PathToTestFile( 'cuda', 'fixit_test.cu' ) ufile", "{ 'line_num': 54, 'column_num': 15 } ) } ), has_entries(", "19 ), LineColMatcher( 17, 19 ) ), ) } )", "54, 'column_num': 15 } ) } ), # second fix-it", "if response == requests.codes.ok: if not isinstance( test[ 1 ],", "')' ), 'range': has_entries( { 'start': has_entries( { 'line_num': 28,", "{ 'line_num': 83, 'column_num': 13 }, } raw_string_range = {", "3, 'objective-c', mfile, FixIt_Check_objc ], [ 7, 1, 'objective-c', mfile,", "15, 46 ), LineColMatcher( 16, 1 ) ), ChunkMatcher( 'Bar',", "PathToTestFile( 'GetDoc_Clang_test.cc' ), 'cpp', test, [ subcommand ], test[ 2", "3 } ), } ), } ) ), 'location': has_entries(", "34, 'column_num': 21 }, 'const int' ], # [ {", "3 } ) } ), has_entries( { 'chunks': contains( has_entries(", "[ { 'line_num': 47, 'column_num': 12 }, 'Foo' ], [", "from ycmd.tests.clangd import ( IsolatedYcmd, SharedYcmd, PathToTestFile, RunAfterInitialized ) from", "definition and declaration { 'req': ( 'goto.cc', 14, 13 ),", "3 }, 'const Foo &' ], # [ { 'line_num':", "has_entries( { 'line_num': 48, 'column_num': 3 } ), 'end' :", "First note: put parens around it has_entries( { 'text': contains_string(", "'line_num': 80, 'column_num': 1 }, 'end': { 'line_num': 80, 'column_num':", "'actual = ' ) print( actual ) assert_that( actual, equal_to(", "unicode in line for fixit [ 21, 16, 'cpp11', ufile,", "'column_num': 3 }, 'Foo' ], # [ { 'line_num': 12,", "'req' ][ 2 ], } ) response = test[ 'res'", "in [ 'GetDoc', 'GetDocImprecise' ]: for test in tests: yield", "), 'res': 'Cannot jump to location' }, { 'req': (", "'request': request, 'route' : '/run_completer_command', 'expect' : expect } )", "1 ) }, # FIXME: should fail since b.hpp is", ") }, { 'req': ( 'main.cpp', 5, 11 ), 'res':", "'route': '/run_completer_command', 'expect': { 'response': response, 'data': expected } }", "43, 'column_num': 16 }, 'const struct Foo *' ], #", "included with angled brackets but its # folder is added", "'diagnostics' in diags[ 'message' ].lower(): receive_diags = { 'request': args,", "**args ) ).json pprint( results ) check( results ) def", "fix-it first? [ 54, 51, 'cpp11', cfile, FixIt_Check_cpp11_MultiSecond ], #", "FixIt_Check_SubexprExtract_Resolved ], [ raw_string_range, FixIt_Check_RawStringReplace_Resolved ], ] for test in", "1 ] ) ) else: expected = has_entry( 'message', test[", ") }, { 'req': ( 'main.cpp', 6, 11 ), 'res':", "has_entries( { 'line_num': 54, 'column_num': 16 } ), 'end' :", "'line_num': 26, 'column_num': 13 }, # 'Ns::Type => Ns::BasicType<char>' ],", "], # Cursor on usage [ { 'line_num': 45, 'column_num':", "'request': { 'completer_target': 'filetype_default', 'line_num': 10, 'column_num': 3, 'filetype': 'objcpp',", "')', LineColMatcher( 61, 12 ), LineColMatcher( 61, 12 ) )", "17 } ), } ), } ), ), 'location': has_entries(", "change to == has_entries( { 'text': contains_string( '==' ), 'chunks':", "# FixIt due to forced spell checking [ 72, 9,", ") } ) ) } ) }, 'route': '/run_completer_command' }", "LocationMatcher, ErrorMatcher, WithRetry, WaitUntilCompleterServerReady ) from ycmd.utils import ReadFile #", "[ subcommand ], test[ 2 ] ) @SharedYcmd def RunFixItTest(", "11 }, 'Foo *' ], [ { 'line_num': 40, 'column_num':", "4, 10 ), 'res': ( 'quote/b.hpp', 1, 1 ) },", "'req': ( 'main.cpp', 10, 13 ), 'res': 'Cannot jump to", "contains( ChunkMatcher( 'SpellingIsNotMyStrongPoint', LineColMatcher( 72, 9 ), LineColMatcher( 72, 35", "'column_num': 16 } ), 'end' : has_entries( { 'line_num': 54,", "'line_num': 54, 'column_num': 58 } ), 'end' : has_entries( {", "request has_entries( { 'text': 'Extract subexpression to variable', 'resolve': True,", "'res': ( 'goto.cc', 6, 10 ) }, # Local ->", "# but WITHOUT ANY WARRANTY; without even the implied warranty", "'Cannot jump to location' }, { 'req': ( 'goto.cc', 16,", "has_entries( { 'text': contains_string( '==' ), 'chunks': contains( ChunkMatcher( '==',", "}, # Namespace { 'req': ( 'goto.cc', 24, 17 ),", "'res': ( 'goto.cc', 21, 5 ) }, # Unicøde {", "}, { 'req': ( 'main.cpp', 2, 14 ), 'res': (", "'req': ( 'goto.cc', 24, 17 ), 'res': [ ( 'goto.cc',", "{ 'line_num': 37, 'column_num': 20 }, 'int' ], # Unicode", "filepath, 'contents' : contents, 'filetype' : filetype } args =", "# Removal of :: assert_that( results, has_entries( { 'fixits': contains(", "{ 'start': has_entries( { 'line_num': 35, 'column_num': 7 } ),", "} ) ), 'location': has_entries( { 'line_num': 35, 'column_num': 7", "[ 'GoToDefinition' ], 'line_num': 10, 'column_num': 3, 'filetype': 'cpp', 'filepath':", "14 ), 'res': ( 'system/a.hpp', 1, 1 ) }, {", "'start': has_entries( { 'line_num': 54, 'column_num': 16 } ), 'end'", "7, 'cpp11', cfile, FixIt_Check_cpp11_Del ], [ 40, 6, 'cpp11', cfile,", "for subcommand in [ 'GetDoc', 'GetDocImprecise' ]: for test in", "'filetype' : 'objc', }, } args = { 'completer_target' :", "), } ), ), 'location': has_entries( { 'line_num': 48, 'column_num':", "), 'res': ( 'system/a.hpp', 1, 1 ) }, { 'req':", "Ns::BasicType<char>' ], # On \"a\" (Ns::Type) # [ { 'line_num':", "has_entries( { 'line_num': 48, 'column_num': 15 } ), 'end' :", "for test in tests: for cmd in [ 'GoToInclude', 'GoTo',", ") common_args = { 'completer_target' : 'filetype_default', 'command_arguments': command, 'line_num'", "[ { 'line_num': 31, 'column_num': 16 }, 'const Foo &'", "@WithRetry @SharedYcmd def RunRangedFixItTest( app, rng, expected ): contents =", "subexpression to variable', 'resolve': True, 'command': has_entries( { 'command': 'clangd.applyTweak'", "{ 'req': ( 'goto.cc', 19, 5 ), 'res': ( 'goto.cc',", "{ 'start': has_entries( { 'line_num': 5, 'column_num': 3 } ),", "**args ) ).json args[ 'fixit' ] = response[ 'fixits' ][", "test in tests: for cmd in [ 'GoToInclude', 'GoTo', 'GoToImprecise'", ") ) } ) ) def Subcommands_FixIt_all_test(): cfile = PathToTestFile(", "test { 'req': ( 'goto.cc', 21, 5 ), 'res': (", "11 }, 'struct Foo &' ], [ { 'line_num': 28,", "contains_string, equal_to, has_entries, has_entry, matches_regexp ) from pprint import pprint", "has_entries( { 'line_num': 54, 'column_num': 52 } ), 'end' :", "), LineColMatcher( 80, 6 ) ), ) } ) )", "'GoTo', 'GoToImprecise' ]: yield RunGoToTest_all, 'test-include', cmd, test def Subcommands_GoToReferences_test():", "[ subcommand ] ) def Subcommands_GetDoc_test(): tests = [ #", "10 ) }, { 'req': ( 'goto.cc', 11, 10 ),", "14, 13 ), 'res': ( 'goto.cc', 11, 10 ) },", "= 3', requests.codes.ok ], # no hover [ { 'line_num':", "48, 'column_num': 15 } ), 'end' : has_entries( { 'line_num':", "diags = RunAfterInitialized( app, test ) results = app.post_json( '/run_completer_command',", "'message', contains_string( test[ 1 ] ) ) else: expected =", "'line_num': 46, 'column_num': 13 }, 'const struct Foo *' ],", ") tests = [ # L # i C #", "of the License, or # (at your option) any later", "'goto.cc', 25, 27 ), 'res': ( 'goto.cc', 11, 10 )", "= [ # from local file [ { 'line_num': 5,", "48, 'column_num': 3 } ) } ), has_entries( { 'chunks':", "[ { 'line_num': 22, 'column_num': 6 }, 'int main()' ],", "20 }, 'const int' ], [ { 'line_num': 47, 'column_num':", "'response': requests.codes.ok, 'data': contains( *sorted( [ 'ExecuteCommand', 'FixIt', 'Format', 'GetDoc',", ") }, { 'req': ( 'main.cpp', 2, 14 ), 'res':", "31, 'column_num': 16 }, 'const Foo &' ], # [", "}, ErrorMatcher( RuntimeError, 'No hover information.' ), requests.codes.server_error ] ]", "has_entries( { 'line_num': 21, 'column_num': 16 } ) } )", "15, 8 ), LineColMatcher( 15, 11 ) ), ChunkMatcher( '", "), LineColMatcher( 9, 6 ) ), ChunkMatcher( '\\n\\n', LineColMatcher( 12,", "{ 'chunks': contains( has_entries( { 'replacement_text': equal_to( '= default;' ),", "struct Foo *' ], # Cursor on usage [ {", "'Foo' ], [ { 'line_num': 12, 'column_num': 8 }, 'Foo'", "{ 'start': has_entries( { 'line_num': 48, 'column_num': 3 } ),", "LineColMatcher( 84, 22 ) ), ) } ) ) }", "'line_num': 12, 'column_num': 2 }, 'Foo' ], [ { 'line_num':", "both with fixits [ 54, 15, 'cpp11', cfile, FixIt_Check_cpp11_MultiFirst ],", "( 'goto.cc', 11, 10 ), 'res': ( 'goto.cc', 14, 13", "'goto.cc', 6, 10 ) }, # Local -> definition/declaration of", "due to forced spell checking [ 72, 9, 'cpp11', cfile,", "'column_num': 18 }, 'Foo' ], # [ { 'line_num': 42,", "# [ { 'line_num': 31, 'column_num': 3 }, 'const Foo", "FixIt_Check_SubexprExtract_Resolved( results ): assert_that( results, has_entries( { 'fixits': contains( has_entries(", "(C) 2018 ycmd contributors # # This file is part", "has_entries( { 'line_num': 5, 'column_num': 3 } ), } ),", "import ( assert_that, contains, contains_string, equal_to, has_entries, has_entry, matches_regexp )", "'goto.cc', 14, 13 ) }, # test -> definition and", "'completer_target' : 'filetype_default', 'filepath' : filepath, 'command_arguments': [ command ],", "} ) ), 'location': has_entries( { 'line_num': 21, 'column_num': 16", "], # from header [ { 'line_num': 6, 'column_num': 10", "LineColMatcher( 15, 1 ) ), ChunkMatcher( 'Bar', LineColMatcher( 15, 8", "app, { 'request': { 'completer_target': 'filetype_default', 'line_num': 10, 'column_num': 3,", "], 'contents' : ReadFile( filepath ), 'filetype' : 'cpp' }", "}, ] for test in tests: yield RunGoToTest_all, '', 'GoToDeclaration',", "= [ # L # i C # n o", "General Public License as published by # the Free Software", "has_entries( { 'line_num': 16, 'column_num': 0 } ) } )", "def FixIt_Check_cpp11_Note( results ): assert_that( results, has_entries( { 'fixits': contains(", "will be useful, # but WITHOUT ANY WARRANTY; without even", "'Foo' ], [ { 'line_num': 36, 'column_num': 19 }, 'int'", "import print_function from __future__ import division from hamcrest.core.base_matcher import BaseMatcher", "'line_num': 80, 'column_num': 19 }, 'end': { 'line_num': 80, 'column_num':", "requests.codes.internal_server_error, 'data': ErrorMatcher( RuntimeError, test[ 'res' ] ) } RunAfterInitialized(", "} ) ) } ) ) def FixIt_Check_MacroExpand_Resolved( results ):", "'chunks': contains( has_entries( { 'replacement_text': equal_to( 'id' ), 'range': has_entries(", "mfile = PathToTestFile( 'objc', 'FixIt_Clang_objc.m' ) cufile = PathToTestFile( 'cuda',", "def FixIt_Check_MacroExpand_Resolved( results ): assert_that( results, has_entries( { 'fixits': contains(", "32, 'column_num': 3 }, 'const Foo *' ], # [", "-iquote. { 'req': ( 'main.cpp', 4, 10 ), 'res': (", "26, 'column_num': 7 } ), } ), } ), has_entries(", "'line_num': 12, 'column_num': 10 }, 'Foo' ], # [ {", ") ) @SharedYcmd def Subcommands_RefactorRename_test( app ): test = {", "to variable', 'chunks': contains( ChunkMatcher( 'auto dummy = foo(i +", "'line_num': 28, 'column_num': 2 } ), 'end' : has_entries( {", "9 ), LineColMatcher( 72, 35 ) ) ), 'location': LineColMatcher(", "LocationMatcher( PathToTestFile( folder, os.path.normpath( response[ 0 ] ) ), response[", "2 ] ) @SharedYcmd def RunFixItTest( app, line, column, lang,", "'foo' ), 'range': has_entries( { 'start': has_entries( { 'line_num': 54,", "filename = PathToTestFile( 'FixIt_Clang_cpp11.cpp' ) request = { 'completer_target' :", "'fixits': contains( has_entries( { 'text': \"Expand macro 'DECLARE_INT'\", 'chunks': contains(", ").json print( 'Resolved fixit response = ' ) print( response", "'line_num': 40, 'column_num': 11 }, 'Foo *' ], [ {", "BuildRequest, ChunkMatcher, CombineRequest, LineColMatcher, LocationMatcher, ErrorMatcher, WithRetry, WaitUntilCompleterServerReady ) from", "filepath ), 'filetype' : 'cpp' } request = common_request request.update(", "Checker [ 16, 0, 'cpp11', cfile, FixIt_Check_cpp11_Ins ], [ 25,", "FOR A PARTICULAR PURPOSE. See the # GNU General Public", "methods pick up an __attribute__((thiscall)) to annotate their # calling", ") } RunAfterInitialized( app, { 'request': request, 'route' : '/run_completer_command',", "the # GNU General Public License for more details. #", ") ), ChunkMatcher( '\\n\\n', LineColMatcher( 12, 2 ), LineColMatcher( 15,", "} ), has_entries( { 'replacement_text': equal_to( '~' ), 'range': has_entries(", "test ) results = app.post_json( '/run_completer_command', BuildRequest( **args ) ).json", "), 'location': LineColMatcher( 60, 1 ), } ), # Unresolved,", "calling convention. This shows up in the type, which isn't", "L # i C # n o # e l", "'filetype_default', 'command_arguments': command, 'line_num' : 10, 'column_num' : 3, 'filepath'", "response[ 'fixits' ][ 0 ] response = app.post_json( '/resolve_fixit', BuildRequest(", "23, 14 ), ( 'goto.cc', 24, 15 ), ( 'goto.cc',", "main()' ], [ { 'line_num': 22, 'column_num': 6 }, 'int", "19 }, 'end': { 'line_num': 80, 'column_num': 35 }, }", "FixIt_Check_unicode_Ins ], # FixIt attached to a \"child\" diagnostic (i.e.", "'column_num': 17 } ), } ), } ), ), 'location':", "{ 'start': has_entries( { 'line_num': 21, 'column_num': 9 } ),", ") } ), ) } ) ) def FixIt_Check_cpp11_MultiSecond( results", "'goto.cc', 14, 13 ), 'res': ( 'goto.cc', 11, 10 )", "14 ), LineColMatcher( 17, 15 ) ), ChunkMatcher( ' ',", "finally, a warning with no fixits assert_that( results, equal_to( {", "is part of ycmd. # # ycmd is free software:", "11 ) }, # Local::out_of_line -> definition of Local::out_of_line {", "} args = { 'completer_target' : 'filetype_default', 'contents' : contents,", "response ) def Subcommands_FixIt_Ranged_test(): expand_auto_range = { 'start': { 'line_num':", "try and strip out. [ { 'line_num': 53, 'column_num': 15", "{ 'line_num': 84, 'column_num': 14 }, 'end': { 'line_num': 84,", "FixIt_Check_cpp11_DelAdd ], [ 5, 3, 'objective-c', mfile, FixIt_Check_objc ], [", "28, 'column_num': 3 }, 'struct Foo &' ], # [", "contains( has_entries( { 'text': contains_string( \"change 'int' to 'void'\" ),", "1 ], BaseMatcher ): expected = has_entry( 'message', contains_string( test[", "), 'range': has_entries( { 'start': has_entries( { 'line_num': 54, 'column_num':", "True, 'command': has_entries( { 'command': 'clangd.applyTweak' } ) } )", "], # On Type (Type) # [ { 'line_num': 25,", "has_entries( { 'line_num': 26, 'column_num': 7 } ), 'end' :", "command, 'line_num' : 10, 'column_num' : 3, 'filepath' : filepath,", "FixIt_Check_RawStringReplace_Resolved( results ): assert_that( results, has_entries( { 'fixits': contains( has_entries(", "WaitUntilCompleterServerReady( app, 'cpp' ) expected = app.post_json( '/run_completer_command', BuildRequest( **request", "54 ) }, { 'req': ( 'goto.cc', 36, 25 ),", "GoToDeclaration alternates between definition and declaration { 'req': ( 'goto.cc',", "), 'res': [ ( 'goto.cc', 11, 10 ), ( 'goto.cc',", "'start': has_entries( { 'line_num': 54, 'column_num': 64 } ), 'end'", "assert_that( results, equal_to( { 'fixits': [] } ) ) def", "has_entries( { 'start': has_entries( { 'line_num': 21, 'column_num': 9 }", "'req': ( 'goto.cc', 36, 25 ), 'res': ( 'goto.cc', 32,", "'replacement_text': equal_to( '= default;' ), 'range': has_entries( { 'start': has_entries(", "check ): contents = ReadFile( file_path ) language_options = {", "{ 'filetype' : 'cuda', }, 'objective-c': { 'filetype' : 'objc',", "{ 'request': { 'filetype': 'cpp', 'completer_target': 'filetype_default', 'contents': ReadFile( PathToTestFile(", "tests: for cmd in [ 'GoToInclude', 'GoTo', 'GoToImprecise' ]: yield", "Subcommands_DefinedSubcommands_test( app ): file_path = PathToTestFile( 'GoTo_Clang_ZeroBasedLineAndColumn_test.cc' ) RunAfterInitialized( app,", "25, 'column_num': 3 }, 'namespace Ns' ], # On Type", "'cpp11', cfile, FixIt_Check_cpp11_MultiSecond ], # unicode in line for fixit", "61, 12 ) ) ), 'location': LineColMatcher( 60, 1 ),", "app.post_json( '/run_completer_command', BuildRequest( **request ) ).json print( 'expected = '", "'line_num': 47, 'column_num': 17 }, 'int' ], [ { 'line_num':", ") ), 'location': has_entries( { 'line_num': 54, 'column_num': 15 }", "and strip out. [ { 'line_num': 53, 'column_num': 15 },", "definition and declaration of test { 'req': ( 'goto.cc', 21,", "'line_num': 10, 'column_num': 3, 'filetype': 'objcpp', 'filepath': file_path }, 'expect':", "[ { 'line_num': 26, 'column_num': 13 }, # 'Ns::Type =>", "'column_num': 3 }, 'int' ], [ { 'line_num': 13, 'column_num':", "prohibitively complex to try and strip out. [ { 'line_num':", "Foo' ], # [ { 'line_num': 34, 'column_num': 21 },", ") ) def FixIt_Check_SubexprExtract_Resolved( results ): assert_that( results, has_entries( {", "), ChunkMatcher( 'Bar', LineColMatcher( 15, 8 ), LineColMatcher( 15, 11", "'text': contains_string( \"change 'SpellingIsNotMyStringPiont' to \" \"'SpellingIsNotMyStrongPoint'\" ), 'chunks': contains(", "46, 'column_num': 20 }, 'const int' ], [ { 'line_num':", "contains( has_entries( { 'chunks': contains( has_entries( { 'replacement_text': equal_to( ''", "], [ 40, 6, 'cpp11', cfile, FixIt_Check_cpp11_Repl ], [ 48,", "tests = [ # from local file [ { 'line_num':", "# [ { 'line_num': 13, 'column_num': 3 }, 'int' ],", "print_function from __future__ import division from hamcrest.core.base_matcher import BaseMatcher from", "16, 1 ) ), ChunkMatcher( 'Bar', LineColMatcher( 17, 3 ),", "but inserts split across lines # assert_that( results, has_entries( {", "test[ 'req' ][ 2 ], } ) response = test[", "filename ), 'filepath' : filename, 'command_arguments': [ 'FixIt' ], 'line_num'", "software: you can redistribute it and/or modify # it under", "to forced spell checking [ 72, 9, 'cpp11', cfile, FixIt_Check_cpp11_SpellCheck", "[ # from local file [ { 'line_num': 5, 'column_num':", "@SharedYcmd def RunGoToTest_all( app, folder, command, test ): filepath =", "'location': has_entries( { 'line_num': 16, 'column_num': 0 } ) }", "54, 'column_num': 51 } ) } ), # second fix-it", "Win32, methods pick up an __attribute__((thiscall)) to annotate their #", "[ { 'line_num': 45, 'column_num': 13 }, 'const struct Foo'", "'res': ( 'goto.cc', 14, 13 ) }, # GoToDeclaration alternates", "'fixits': contains( # first fix-it at 54,16 has_entries( { 'chunks':", "has_entries( { 'fixits': contains( has_entries( { 'text': \"Expand macro 'DECLARE_INT'\",", "3, 12, 'cuda', cufile, FixIt_Check_cuda ], # multiple errors on", "}, 'expect': { 'response': requests.codes.ok, 'data': contains( *sorted( [ 'ExecuteCommand',", "contains( has_entries( { 'replacement_text': equal_to( '= default;' ), 'range': has_entries(", "{ 'line_num': 28, 'column_num': 2 } ), 'end' : has_entries(", "the assignment' ), 'chunks': contains( ChunkMatcher( '(', LineColMatcher( 59, 8", "'end' : has_entries( { 'line_num': 54, 'column_num': 53 } ),", "'fixits': contains( has_entries( { 'text': contains_string( \"change 'int' to 'void'\"", "[ { 'line_num': 53, 'column_num': 15 }, matches_regexp( r'int bar\\(int", "], # Auto in usage # [ { 'line_num': 34,", "'Foo' ], [ { 'line_num': 40, 'column_num': 3 }, 'Foo'", "3 }, 'const Foo *' ], [ { 'line_num': 43,", "'line_num': 31, 'column_num': 16 }, 'const Foo &' ], #", "RunAfterInitialized( app, { 'request': { 'completer_target': 'filetype_default', 'line_num': 10, 'column_num':", "32, 'column_num': 16 }, 'const Foo *' ], # Auto", ") ) } ) ) def FixIt_Check_cpp11_DelAdd( results ): assert_that(", "19 ), LineColMatcher( 80, 36 ) ), ) } )", "# should put closest fix-it first? [ 54, 51, 'cpp11',", "# [ { 'line_num': 45, 'column_num': 19 }, 'const int'", "@WithRetry @SharedYcmd def Subcommands_FixIt_AlreadyResolved_test( app ): filename = PathToTestFile( 'FixIt_Clang_cpp11.cpp'", "'column_num' : 3, 'filepath' : filepath, 'contents' : contents, 'filetype'", ") ), 'location': LineColMatcher( 72, 9 ), } ) )", "), ), 'location': has_entries( { 'line_num': 54, 'column_num': 15 }", "copy of the GNU General Public License # along with", "][ 1 ], 'column_num': test[ 'req' ][ 2 ], }", "'filetype_default', 'contents' : contents, 'filepath' : file_path, 'command_arguments': [ 'FixIt'", "( RunGetSemanticTest, PathToTestFile( 'GetDoc_Clang_test.cc' ), 'cpp', test, [ subcommand ],", "Subcommands_GetDoc_test(): tests = [ # from local file [ {", "21, 'column_num': 11 } ), } ), } ) ),", "location' }, { 'req': ( 'goto.cc', 16, 6 ), 'res':", "'line_num': 16, 'column_num': 13 } ), 'end' : has_entries( {", "'line_num': 54, 'column_num': 51 } ) } ), ) }", "1, 1 ) }, { 'req': ( 'main.cpp', 6, 11", ") def FixIt_Check_objc_NoFixIt( results ): # and finally, a warning", "'line_num': 26, 'column_num': 7 } ), 'end' : has_entries( {", "{ 'request': { 'contents': ReadFile( file_path ), 'completer_target': 'filetype_default', 'command_arguments':", "] for subcommand in [ 'GetDoc', 'GetDocImprecise' ]: for test", "'line_num': 25, 'column_num': 14 } ) } ) ) }", "} ) ) def FixIt_Check_AutoExpand_Resolved( results ): assert_that( results, has_entries(", "'completer_target' : 'filetype_default', 'contents' : contents, 'filepath' : file_path, 'command_arguments':", "Foo' ], # [ { 'line_num': 29, 'column_num': 3 },", "{ 'line_num': 16, 'column_num': 0 } ) } ) )", "Expected failure { 'req': ( 'goto.cc', 27, 8 ), 'res':", "11, 10 ), ( 'goto.cc', 14, 13 ), ( 'goto.cc',", ") def FixIt_Check_RawStringReplace_Resolved( results ): assert_that( results, has_entries( { 'fixits':", "= PathToTestFile( 'FixIt_Clang_cpp11.cpp' ) mfile = PathToTestFile( 'objc', 'FixIt_Clang_objc.m' )", "1 ), 'res': 'Cannot jump to location' }, { 'req':", "), 'cpp', test, [ subcommand ] ) def Subcommands_GetDoc_test(): tests", "'int x = 3', requests.codes.ok ], # no hover [", "} ) } ) ) } ) ) def FixIt_Check_cpp11_InsMultiLine(", "7 } ), 'end' : has_entries( { 'line_num': 35, 'column_num':", "[ { 'line_num': 35, 'column_num': 14 }, 'const Foo *'", "has_entries( { 'line_num': 54, 'column_num': 15 } ) } ),", "] = response[ 'fixits' ][ 0 ] response = app.post_json(", "contains_string( test[ 1 ] ) ) else: expected = has_entry(", "}, 'Foo *' ], [ { 'line_num': 40, 'column_num': 18", "def Subcommands_DefinedSubcommands_test( app ): file_path = PathToTestFile( 'GoTo_Clang_ZeroBasedLineAndColumn_test.cc' ) RunAfterInitialized(", "54 ) }, { 'req': ( 'goto.cc', 38, 3 ),", "test[ 1 ], test[ 2 ], test[ 3 ], test[", "useful, # but WITHOUT ANY WARRANTY; without even the implied", "test in tests: yield RunGoToTest_all, '', 'GoToReferences', test @SharedYcmd def", "type # On Ns:: [ { 'line_num': 25, 'column_num': 3", "'line_num': 36, 'column_num': 13 }, 'Foo' ], [ { 'line_num':", "'range': has_entries( { 'start': has_entries( { 'line_num': 54, 'column_num': 58", "84, 22 ) ), ) } ) ) } )", "{ 'line_num': 25, 'column_num': 14 } ) } ) )", "'column_num': 52 } ), 'end' : has_entries( { 'line_num': 54,", "], # [ { 'line_num': 31, 'column_num': 3 }, 'const", "'expect': { 'response': response, 'data': expected } } RunAfterInitialized( app,", "}, 'Foo' ], # [ { 'line_num': 12, 'column_num': 2", "'goto.cc', 13, 1 ), 'res': 'Cannot jump to location' },", "3 }, 'const Foo *' ], # [ { 'line_num':", "45, 'column_num': 13 }, 'const struct Foo' ], # [", ") }, # Expected failures { 'req': ( 'main.cpp', 7,", "has_entries( { 'start': has_entries( { 'line_num': 35, 'column_num': 7 }", "'req': ( 'goto.cc', 25, 27 ), 'res': ( 'goto.cc', 11,", "# You should have received a copy of the GNU", "language_options[ lang ] ) test = { 'request': args, 'route':", "), 'end' : has_entries( { 'line_num': 54, 'column_num': 53 }", "to annotate their # calling convention. This shows up in", "'goto.cc', 25, 15 ) ] }, # Expected failure {", "contains( ChunkMatcher( 'void', LineColMatcher( 3, 12 ), LineColMatcher( 3, 15", "mfile, FixIt_Check_objc ], [ 7, 1, 'objective-c', mfile, FixIt_Check_objc_NoFixIt ],", "ChunkMatcher( 'int i', LineColMatcher( 83, 3 ), LineColMatcher( 83, 17", "'contents': ReadFile( file_path ), 'completer_target': 'filetype_default', 'command_arguments': [ 'GoToDefinition' ],", "'range': has_entries( { 'start': has_entries( { 'line_num': 28, 'column_num': 2", "# 'Ns::Type => Ns::BasicType<char>' ], # Cursor on decl for", "'Ns::Type => Ns::BasicType<char>' ], # Cursor on decl for refs", "], [ 25, 14, 'cpp11', cfile, FixIt_Check_cpp11_InsMultiLine ], [ 35,", "'int main()' ], # Declared and canonical type # On", "} app.post_json( '/event_notification', CombineRequest( args, { 'event_name': 'FileReadyToParse', } ),", "{ 'response': response, 'data': expected } } RunAfterInitialized( app, test", "common_request request.update( { 'line_num' : test[ 'req' ][ 1 ],", "'column_num': 15 } ), 'end' : has_entries( { 'line_num': 48,", "pointers [ { 'line_num': 39, 'column_num': 3 }, 'Foo' ],", "{ 'line_num': 16, 'column_num': 13 } ), 'end' : has_entries(", "'line_num': 10, 'column_num': 3, 'filetype': 'cpp', 'filepath': file_path }, 'expect':", "License # along with ycmd. If not, see <http://www.gnu.org/licenses/>. from", "'line_num': 48, 'column_num': 12 }, 'Foo *' ], [ {", "contains( ChunkMatcher( 'auto dummy = foo(i + 3);\\n ', LineColMatcher(", "'line_num': 34, 'column_num': 21 }, 'const int' ], # [", "), 'res': ( 'quote/b.hpp', 1, 1 ) }, { 'req':", "hamcrest import ( assert_that, contains, contains_string, equal_to, has_entries, has_entry, matches_regexp", "'goto.cc', 14, 6 ), ( 'goto.cc', 23, 14 ), (", "FixIt_Check_cpp11_SpellCheck( results ): assert_that( results, has_entries( { 'fixits': contains( #", "26 ) }, # Another_Unicøde { 'req': ( 'goto.cc', 36,", "( 'system/c.hpp', 1, 1 ) }, { 'req': ( 'main.cpp',", "'start': has_entries( { 'line_num': 5, 'column_num': 3 } ), 'end'", "isn't ideal, but # also prohibitively complex to try and", "][ 2 ], } ) response = test[ 'res' ]", "@SharedYcmd def Subcommands_RefactorRename_test( app ): test = { 'request': {", "{ 'completer_target': 'filetype_default', 'line_num': 10, 'column_num': 3, 'filetype': 'objcpp', 'filepath':", "[ # Local::x -> definition/declaration of x { 'req': (", "__attribute__((thiscall)) to annotate their # calling convention. This shows up", "'column_num': 14 } ) } ) ) } ) )", "6, 11 ), 'res': ( 'system/c.hpp', 1, 1 ) },", "[ # Basic pod types [ { 'line_num': 24, 'column_num':", "{ 'start': has_entries( { 'line_num': 54, 'column_num': 58 } ),", "'res': ( 'a.hpp', 1, 1 ) }, { 'req': (", "os.path.abspath( file_path ), 'line_num': 2, 'column_num': 8 } }, 'route':", "equal_to( '=' ), 'range': has_entries( { 'start': has_entries( { 'line_num':", "to location' }, ] for test in tests: for cmd", "0 ], test[ 1 ] @WithRetry @SharedYcmd def Subcommands_FixIt_AlreadyResolved_test( app", "= app.post_json( '/resolve_fixit', BuildRequest( **args ) ).json print( 'Resolved fixit", "), 'res': ( 'goto.cc', 11, 10 ) }, { 'req':", "FixIt_Check_cuda( results ): assert_that( results, has_entries( { 'fixits': contains( has_entries(", "*' ], [ { 'line_num': 29, 'column_num': 18 }, 'Foo'", "'goto.cc', 11, 10 ), ( 'goto.cc', 14, 13 ), (", "Cursor on decl for refs & pointers [ { 'line_num':", ") } ) ) def FixIt_Check_cpp11_Del( results ): # Removal", "], # [ { 'line_num': 32, 'column_num': 3 }, 'const", "'', 'GoToDeclaration', test def Subcommands_GoToInclude_test(): tests = [ { 'req':", ") def Subcommands_FixIt_Ranged_test(): expand_auto_range = { 'start': { 'line_num': 80,", "), 'chunks': contains( ChunkMatcher( 'SpellingIsNotMyStrongPoint', LineColMatcher( 72, 9 ), LineColMatcher(", "ChunkMatcher( 'Bar', LineColMatcher( 1, 8 ), LineColMatcher( 1, 11 )", "'FixIt' ], 'range' : rng, 'filetype' : 'cpp' } app.post_json(", "app ): test = { 'request': { 'filetype': 'cpp', 'completer_target':", "} ) ) def FixIt_Check_MacroExpand_Resolved( results ): assert_that( results, has_entries(", "methods # On Win32, methods pick up an __attribute__((thiscall)) to", "'text': contains_string( '==' ), 'chunks': contains( ChunkMatcher( '==', LineColMatcher( 60,", "test in tests: yield ( RunGetSemanticTest, PathToTestFile( 'GetDoc_Clang_test.cc' ), 'cpp',", ") print( response ) expected( response ) def Subcommands_FixIt_Ranged_test(): expand_auto_range", "fixits assert_that( results, equal_to( { 'fixits': [] } ) )", "'column_num': 2 } ), } ), } ) ), 'location':", "True ) WaitUntilCompleterServerReady( app, 'cpp' ) response = app.post_json( '/run_completer_command',", "ChunkMatcher( 'void', LineColMatcher( 3, 12 ), LineColMatcher( 3, 15 )", "), 'range': has_entries( { 'start': has_entries( { 'line_num': 26, 'column_num':", "), LineColMatcher( 59, 8 ) ), ChunkMatcher( ')', LineColMatcher( 61,", "'GoToDeclaration', test def Subcommands_GoToInclude_test(): tests = [ { 'req': (", "], [ raw_string_range, FixIt_Check_RawStringReplace_Resolved ], ] for test in tests:", ") ) } ) ) def FixIt_Check_objc_NoFixIt( results ): #", "equal_to( '= default;' ), 'range': has_entries( { 'start': has_entries( {", "{ 'start': has_entries( { 'line_num': 26, 'column_num': 7 } ),", "} ) } ), ) } ) ) def FixIt_Check_objc(", "[] } ) ) def FixIt_Check_cpp11_MultiFirst( results ): assert_that( results,", "2018 ycmd contributors # # This file is part of", "\"'SpellingIsNotMyStrongPoint'\" ), 'chunks': contains( ChunkMatcher( 'SpellingIsNotMyStrongPoint', LineColMatcher( 72, 9 ),", "15 ) ) ), 'location': LineColMatcher( 3, 12 ), }", "ChunkMatcher( 'SpellingIsNotMyStrongPoint', LineColMatcher( 72, 9 ), LineColMatcher( 72, 35 )", "[ 'GetDoc', 'GetDocImprecise' ]: for test in tests: yield (", "{ 'line_num': 36, 'column_num': 13 }, 'Foo' ], [ {", "# the Free Software Foundation, either version 3 of the", "), ChunkMatcher( ')', LineColMatcher( 61, 12 ), LineColMatcher( 61, 12", "] for test in tests: yield RunGoToTest_all, '', 'GoToDeclaration', test", "subcommand in [ 'GetDoc', 'GetDocImprecise' ]: for test in tests:", "{ 'start': has_entries( { 'line_num': 54, 'column_num': 16 } ),", "'Bar', LineColMatcher( 15, 8 ), LineColMatcher( 15, 11 ) ),", "test in tests: yield RunRangedFixItTest, test[ 0 ], test[ 1", "# [ { 'line_num': 32, 'column_num': 3 }, 'const Foo", ") ), 'location': has_entries( { 'line_num': 21, 'column_num': 16 }", "common_args = { 'completer_target' : 'filetype_default', 'command_arguments': command, 'line_num' :", "35, 'column_num': 7 } ) } ) ) } )", "**args ) ).json print( 'Resolved fixit response = ' )", "'fixits': contains( has_entries( { 'text': 'Convert to raw string', 'chunks':", "[ { 'line_num': 12, 'column_num': 9 }, 'Foo' ], [", "13 ) }, # GoToDeclaration alternates between definition and declaration", "to try and strip out. [ { 'line_num': 53, 'column_num':", "rng, expected ): contents = ReadFile( PathToTestFile( 'FixIt_Clang_cpp11.cpp' ) )", "} ), } ) ), 'location': has_entries( { 'line_num': 25,", "}, 'Foo' ], # [ { 'line_num': 31, 'column_num': 3", "but WITHOUT ANY WARRANTY; without even the implied warranty of", "test, [ subcommand ], test[ 2 ] ) @SharedYcmd def", "file_path, 'command_arguments': [ 'FixIt' ], 'line_num' : line, 'column_num' :", "], test[ 3 ], test[ 4 ] @WithRetry @SharedYcmd def", "} ), } ) ), 'location': has_entries( { 'line_num': 35,", "{ 'line_num': 32, 'column_num': 3 }, 'const Foo *' ],", "'filetype_default', 'line_num': 10, 'column_num': 3, 'filetype': 'objcpp', 'filepath': file_path },", "'data': contains( *[ LocationMatcher( PathToTestFile( folder, os.path.normpath( location[ 0 ]", "11 }, 'Foo &' ], [ { 'line_num': 39, 'column_num':", "'line_num': 6, 'column_num': 10 }, 'docstring', requests.codes.ok ], # no", "{ 'line_num': 35, 'column_num': 7 } ) } ) )", "'objective-c', mfile, FixIt_Check_objc ], [ 7, 1, 'objective-c', mfile, FixIt_Check_objc_NoFixIt", "'completer_target' : 'filetype_default', 'contents' : contents, 'filepath' : PathToTestFile( 'FixIt_Clang_cpp11.cpp'", "'column_num': 10 } ), } ), } ), has_entries( {", "17 ) ), ) } ) ) } ) )", "= app.post_json( '/run_completer_command', BuildRequest( **args ) ).json args[ 'fixit' ]", "] if response == requests.codes.ok: if not isinstance( test[ 1", "equal_to( 'foo' ), 'range': has_entries( { 'start': has_entries( { 'line_num':", ") } ) ) def FixIt_Check_cpp11_SpellCheck( results ): assert_that( results,", "}, # Expected failures { 'req': ( 'main.cpp', 7, 1", "response[ 2 ] ) } else: expect = { 'response':", "), } ), # Second note: change to == has_entries(", "( 'main.cpp', 3, 1 ), 'res': ( 'quote/b.hpp', 1, 1", "19 }, 'int' ], # [ { 'line_num': 37, 'column_num':", "7, 'column_num': 7 }, 'int x = 3', requests.codes.ok ],", "filetype } args = test[ 0 ] if response ==", "}, 'cuda': { 'filetype' : 'cuda', }, 'objective-c': { 'filetype'", "[ 60, 1, 'cpp11', cfile, FixIt_Check_cpp11_Note ], # FixIt due", "contains( has_entries( { 'text': 'Extract subexpression to variable', 'chunks': contains(", "has_entries( { 'fixits': contains( # First note: put parens around", "results ): assert_that( results, has_entries( { 'fixits': contains( has_entries( {", ") ) def FixIt_Check_cuda( results ): assert_that( results, has_entries( {", "Software Foundation, either version 3 of the License, or #", "Local::out_of_line { 'req': ( 'goto.cc', 25, 27 ), 'res': (", "app, test ) results = app.post_json( '/run_completer_command', BuildRequest( **args )", "46 ), LineColMatcher( 16, 1 ) ), ChunkMatcher( 'Bar', LineColMatcher(", "FixIt attached to a \"child\" diagnostic (i.e. a Note) [", "'fixits': [] } ) ) def FixIt_Check_cpp11_MultiFirst( results ): assert_that(", "equal_to( expected ) ) @SharedYcmd def Subcommands_RefactorRename_test( app ): test", "# Local::x -> definition/declaration of x { 'req': ( 'goto.cc',", "results, has_entries( { 'fixits': contains( has_entries( { 'chunks': contains( has_entries(", "args.update( language_options[ lang ] ) test = { 'request': args,", "), 'res': ( 'goto.cc', 2, 11 ) }, # Local::out_of_line", "'column_num': 12 }, 'Foo *' ], [ { 'line_num': 48,", "21 ), 'res': [ ( 'goto.cc', 11, 10 ), (", "'res': 'Cannot jump to location' }, ] for test in", "], test[ 1 ], test[ 2 ], test[ 3 ],", "37, 'column_num': 20 }, 'int' ], # Unicode [ {", "&' ], [ { 'line_num': 42, 'column_num': 16 }, 'const", "} tests = [ [ expand_auto_range, FixIt_Check_AutoExpand_Resolved ], [ macro_expand_range,", "16 }, 'const struct Foo *' ], # Cursor on", ": filetype } args = test[ 0 ] if response", "'request': args, 'route': '/receive_messages' } RunAfterInitialized( app, receive_diags ) diags", "version 3 of the License, or # (at your option)", "} ), has_entries( { 'chunks': contains( has_entries( { 'replacement_text': equal_to(", "): expected = has_entry( 'message', contains_string( test[ 1 ] )", "24, 'column_num': 3 }, 'Foo' ], # [ { 'line_num':", "3 }, 'int' ], [ { 'line_num': 13, 'column_num': 7", "of Local::in_line { 'req': ( 'goto.cc', 24, 26 ), 'res':", "actual = app.post_json( '/resolve_fixit', BuildRequest( **request ) ).json print( 'actual", "= foo(i + 3);\\n ', LineColMatcher( 84, 3 ), LineColMatcher(", "'req': ( 'goto.cc', 38, 3 ), 'res': ( 'goto.cc', 36,", "e l Lang File, Checker [ 16, 0, 'cpp11', cfile,", "), 'location': has_entries( { 'line_num': 54, 'column_num': 51 } )", "response, 'data': expected } } RunAfterInitialized( app, test ) def", "'column_num': 4 }, } subexpression_extract_range = { 'start': { 'line_num':", "{ 'replacement_text': equal_to( 'id' ), 'range': has_entries( { 'start': has_entries(", "'int' ], [ { 'line_num': 48, 'column_num': 12 }, 'Foo", "RunGoToTest_all, '', cmd, test def Subcommands_GoToDeclaration_all_test(): tests = [ #", "*' ], [ { 'line_num': 43, 'column_num': 16 }, 'const", "'system/c.hpp', 1, 1 ) }, # Expected failures { 'req':", "diags = RunAfterInitialized( app, test ) while 'message' in diags", "{ 'fixits': [] } ) ) def FixIt_Check_cpp11_MultiFirst( results ):", "'line_num': 42, 'column_num': 3 }, 'const Foo &' ], [", "'const Foo *' ], # [ { 'line_num': 35, 'column_num':", "a copy of the GNU General Public License # along", "), 'filetype' : 'cpp' } request = common_request request.update( {", "'column_num': 11 }, 'Foo *' ], [ { 'line_num': 40,", "): contents = ReadFile( filepath ) common_args = { 'completer_target'", "{ 'chunks': contains( has_entries( { 'replacement_text': equal_to( 'id' ), 'range':", "'Foo *' ], [ { 'line_num': 29, 'column_num': 18 },", "'basic.cpp' ) ), 'filepath': PathToTestFile( 'basic.cpp' ), 'command_arguments': [ 'RefactorRename',", "from __future__ import unicode_literals from __future__ import print_function from __future__", "1, 'filetype' : 'cpp' } app.post_json( '/event_notification', CombineRequest( request, {", "yield RunGoToTest_all, 'test-include', cmd, test def Subcommands_GoToReferences_test(): tests = [", "}, 'docstring', requests.codes.ok ], # no docstring [ { 'line_num':", "], # Auto in declaration # [ { 'line_num': 28,", "command, test ): filepath = PathToTestFile( folder, test[ 'req' ][", "= test[ 0 ] if response == requests.codes.ok: if not", "fixit # switch(A()) { // expected-error{{explicit conversion to}} assert_that( results,", "'column_num': 15 }, matches_regexp( r'int bar\\(int i\\)(?: __attribute__\\(\\(thiscall\\)\\))?' ) ],", "on usage [ { 'line_num': 45, 'column_num': 13 }, 'const", "has_entries( { 'replacement_text': equal_to( 'static_cast<int>(' ), 'range': has_entries( { 'start':", "'chunks': contains( ChunkMatcher( 'void', LineColMatcher( 3, 12 ), LineColMatcher( 3,", "'start': { 'line_num': 80, 'column_num': 19 }, 'end': { 'line_num':", "), 'end' : has_entries( { 'line_num': 28, 'column_num': 2 }", ": filename, 'command_arguments': [ 'FixIt' ], 'line_num' : 16, 'column_num'", "def FixIt_Check_cpp11_MultiFirst( results ): assert_that( results, has_entries( { 'fixits': contains(", "), 'end' : has_entries( { 'line_num': 16, 'column_num': 10 }", "'column_num': 16 }, 'const Foo &' ], # [ {", "'req': ( 'main.cpp', 4, 10 ), 'res': ( 'quote/b.hpp', 1,", "'line_num': 16, 'column_num': 10 } ), } ), } ),", "LineColMatcher( 3, 12 ), LineColMatcher( 3, 15 ) ) ),", ") ) } ) ) def FixIt_Check_cuda( results ): assert_that(", "has_entries( { 'chunks': contains( has_entries( { 'replacement_text': equal_to( 'id' ),", "type\", 'chunks': contains( ChunkMatcher( 'const char *', LineColMatcher( 80, 1", "complex to try and strip out. [ { 'line_num': 53,", "'DECLARE_INT'\", 'chunks': contains( ChunkMatcher( 'int i', LineColMatcher( 83, 3 ),", "folder is added with -iquote. { 'req': ( 'main.cpp', 4,", ") ] }, # Expected failure { 'req': ( 'goto.cc',", "test[ 'req' ][ 0 ] ) common_request = { 'completer_target'", "}, 'int main()' ], # Declared and canonical type #", "FIXME: should fail since b.hpp is included with angled brackets", "ChunkMatcher( ' ', LineColMatcher( 17, 17 ), LineColMatcher( 17, 17", "} args.update( language_options[ lang ] ) test = { 'request':", "{ 'start': { 'line_num': 80, 'column_num': 1 }, 'end': {", "6 ), 'res': ( 'a.hpp', 1, 1 ) }, {", "28, 'column_num': 11 }, 'struct Foo &' ], [ {", ") } ) ) def FixIt_Check_MacroExpand_Resolved( results ): assert_that( results,", "expected( response ) def Subcommands_FixIt_Ranged_test(): expand_auto_range = { 'start': {", "11, 10 ), 'res': ( 'goto.cc', 14, 13 ) },", "], # [ { 'line_num': 31, 'column_num': 16 }, 'const", "{ 'start': { 'line_num': 83, 'column_num': 3 }, 'end': {", "'req': ( 'goto.cc', 24, 26 ), 'res': ( 'goto.cc', 6,", "25, 27 ), 'res': ( 'goto.cc', 14, 13 ) },", "# n o # e l Lang File, Checker [", "'column_num': 19 }, 'int' ], # [ { 'line_num': 37,", "'location': has_entries( { 'line_num': 25, 'column_num': 14 } ) }", "'Extract subexpression to variable', 'chunks': contains( ChunkMatcher( 'auto dummy =", "'column_num': 10 }, 'Foo' ], # [ { 'line_num': 13,", "equal_to( ')' ), 'range': has_entries( { 'start': has_entries( { 'line_num':", "'range': has_entries( { 'start': has_entries( { 'line_num': 48, 'column_num': 3", "} ) } ) ) } ) ) def FixIt_Check_cpp11_Repl(", "from hamcrest.core.base_matcher import BaseMatcher from hamcrest import ( assert_that, contains,", "), 'end' : has_entries( { 'line_num': 54, 'column_num': 19 }", "'start': has_entries( { 'line_num': 21, 'column_num': 9 } ), 'end'", "), 'res': ( 'goto.cc', 11, 10 ) }, # GoToDeclaration", "}, 'int' ], # Auto in declaration # [ {", "WARRANTY; without even the implied warranty of # MERCHANTABILITY or", "[ { 'line_num': 15, 'column_num': 7 }, 'char' ], #", "): contents = ReadFile( file_path ) language_options = { 'cpp11':", "14, 21 ), 'res': [ ( 'goto.cc', 11, 10 ),", "} ), } ), } ), has_entries( { 'replacement_text': equal_to(", ") ) def FixIt_Check_cpp11_SpellCheck( results ): assert_that( results, has_entries( {", "}, # Local::in_line -> definition/declaration of Local::in_line { 'req': (", "}, ] for test in tests: yield RunGoToTest_all, '', 'GoToReferences',", "], [ { 'line_num': 13, 'column_num': 7 }, 'int' ],", "at 54,16 has_entries( { 'chunks': contains( has_entries( { 'replacement_text': equal_to(", "{ 'line_num': 22, 'column_num': 6 }, 'int main()' ], #", "has_entries( { 'start': has_entries( { 'line_num': 54, 'column_num': 64 }", "[ { 'line_num': 34, 'column_num': 21 }, 'const int' ],", "contains_string( \"change 'int' to 'void'\" ), 'chunks': contains( ChunkMatcher( 'void',", "LineColMatcher( 9, 3 ), LineColMatcher( 9, 6 ) ), ChunkMatcher(", "16, 'column_num': 10 } ), 'end' : has_entries( { 'line_num':", "} ) ), 'location': has_entries( { 'line_num': 16, 'column_num': 0", "], [ { 'line_num': 36, 'column_num': 19 }, 'int' ],", "First fixit # switch(A()) { // expected-error{{explicit conversion to}} assert_that(", "closest fix-it first? [ 54, 51, 'cpp11', cfile, FixIt_Check_cpp11_MultiSecond ],", "is distributed in the hope that it will be useful,", "request.update( { 'line_num' : test[ 'req' ][ 1 ], 'column_num':", "3 of the License, or # (at your option) any", "'line_num': 34, 'column_num': 14 }, 'const Foo' ], # [", "= common_args request.update( args ) test = { 'request': request,", ") } ) ) } ) ) def FixIt_Check_RawStringReplace_Resolved( results", "= { 'start': { 'line_num': 80, 'column_num': 19 }, 'end':", "isinstance( test[ 1 ], BaseMatcher ): expected = has_entry( 'message',", "test ) def Subcommands_GetType_test(): tests = [ # Basic pod", "has_entries( { 'fixits': contains( # first fix-it at 54,16 has_entries(", "), ) } ) ) } ) ) def FixIt_Check_RawStringReplace_Resolved(", "[ raw_string_range, FixIt_Check_RawStringReplace_Resolved ], ] for test in tests: yield", "} ) ) def FixIt_Check_cpp11_DelAdd( results ): assert_that( results, has_entries(", "'/run_completer_command', BuildRequest( **request ) ).json print( 'expected = ' )", "app, { 'request': request, 'route' : '/run_completer_command', 'expect' : expect", "'expect' : expect } ) def Subcommands_GoTo_all_test(): tests = [", "contains( ChunkMatcher( 'int i', LineColMatcher( 83, 3 ), LineColMatcher( 83,", "{ 'line_num': 5, 'column_num': 10 }, 'docstring', requests.codes.ok ], #", ") } ) ) } ) ) def FixIt_Check_objc_NoFixIt( results", "of the GNU General Public License # along with ycmd.", "for test in tests: yield ( RunGetSemanticTest, PathToTestFile( 'GetType_Clang_test.cc' ),", "int' ], [ { 'line_num': 47, 'column_num': 12 }, 'Foo'", "'column_num': 18 }, matches_regexp( r'int bar\\(int i\\)(?: __attribute__\\(\\(thiscall\\)\\))?' ) ],", "FixIt_Check_AutoExpand_Resolved( results ): assert_that( results, has_entries( { 'fixits': contains( has_entries(", "RunRangedFixItTest( app, rng, expected ): contents = ReadFile( PathToTestFile( 'FixIt_Clang_cpp11.cpp'", "'chunks': contains( ChunkMatcher( '(', LineColMatcher( 59, 8 ), LineColMatcher( 59,", "LineColMatcher( 60, 9 ) ) ), 'location': LineColMatcher( 60, 1", "[ [ expand_auto_range, FixIt_Check_AutoExpand_Resolved ], [ macro_expand_range, FixIt_Check_MacroExpand_Resolved ], [", "'foo' ), 'range': has_entries( { 'start': has_entries( { 'line_num': 40,", "8 ), LineColMatcher( 59, 8 ) ), ChunkMatcher( ')', LineColMatcher(", "{ 'replacement_text': equal_to( 'foo' ), 'range': has_entries( { 'start': has_entries(", "[ { 'line_num': 7, 'column_num': 7 }, 'int x =", "[ { 'line_num': 22, 'column_num': 2 }, 'int main()' ],", "diags and 'diagnostics' in diags[ 'message' ].lower(): receive_diags = {", "auto type\", 'chunks': contains( ChunkMatcher( 'const char *', LineColMatcher( 80,", "for test in tests: yield RunRangedFixItTest, test[ 0 ], test[", "'chunks': contains( ChunkMatcher( 'Bar', LineColMatcher( 1, 8 ), LineColMatcher( 1,", "\" \"'SpellingIsNotMyStrongPoint'\" ), 'chunks': contains( ChunkMatcher( 'SpellingIsNotMyStrongPoint', LineColMatcher( 72, 9", "' ', LineColMatcher( 15, 46 ), LineColMatcher( 16, 1 )", "} # First get diags. diags = RunAfterInitialized( app, test", "), # Second note: change to == has_entries( { 'text':", ") ), ChunkMatcher( 'Bar', LineColMatcher( 17, 3 ), LineColMatcher( 17,", "&' ], # [ { 'line_num': 43, 'column_num': 3 },", "{ 'req': ( 'main.cpp', 2, 14 ), 'res': ( 'system/a.hpp',", "51 } ) } ), ) } ) ) def", "{ 'line_num': 32, 'column_num': 16 }, 'const Foo *' ],", "[ 72, 9, 'cpp11', cfile, FixIt_Check_cpp11_SpellCheck ], ] for test", "'line_num': 35, 'column_num': 14 }, 'const Foo *' ], #", "LineColMatcher( 80, 6 ) ), ) } ) ) }", "declaration of test { 'req': ( 'goto.cc', 21, 5 ),", "} request = common_request request.update( { 'line_num' : test[ 'req'", "= [ # Local::x -> definition/declaration of x { 'req':", "'goto.cc', 36, 25 ), 'res': ( 'goto.cc', 32, 54 )", "WITHOUT ANY WARRANTY; without even the implied warranty of #", "] ) } RunAfterInitialized( app, { 'request': request, 'route' :", "} ), ), 'location': has_entries( { 'line_num': 54, 'column_num': 51", "'line_num': 16, 'column_num': 13 } ), } ), } )", "Subcommands_FixIt_AlreadyResolved_test( app ): filename = PathToTestFile( 'FixIt_Clang_cpp11.cpp' ) request =", "'line_num': 45, 'column_num': 13 }, 'const struct Foo' ], #", "{ 'completer_target' : 'filetype_default', 'filepath' : filepath, 'command_arguments': [ command", "'line_num': 54, 'column_num': 15 } ) } ), ) }", "}, { 'req': ( 'main.cpp', 10, 13 ), 'res': 'Cannot", "'SpellingIsNotMyStringPiont' to \" \"'SpellingIsNotMyStrongPoint'\" ), 'chunks': contains( ChunkMatcher( 'SpellingIsNotMyStrongPoint', LineColMatcher(", "should put closest fix-it first? [ 54, 51, 'cpp11', cfile,", "2 ], } ) response = test[ 'res' ] if", "to}} assert_that( results, has_entries( { 'fixits': contains( has_entries( { 'chunks':", "assert_that( results, has_entries( { 'fixits': contains( # first fix-it at", "), 'end' : has_entries( { 'line_num': 35, 'column_num': 9 }", "), 'range': has_entries( { 'start': has_entries( { 'line_num': 28, 'column_num':", ") ) def FixIt_Check_unicode_Ins( results ): assert_that( results, has_entries( {", "to == has_entries( { 'text': contains_string( '==' ), 'chunks': contains(", "'column_num': 13 }, } raw_string_range = { 'start': { 'line_num':", "'chunks': contains( ChunkMatcher( 'R\"(\\\\\\\\r\\\\asd\\n\\\\v)\"', LineColMatcher( 80, 19 ), LineColMatcher( 80,", "= [ { 'req': ( 'main.cpp', 1, 6 ), 'res':", "( 'goto.cc', 11, 10 ), ( 'goto.cc', 14, 13 ),", "84, 3 ), LineColMatcher( 84, 3 ) ), ChunkMatcher( 'dummy',", "# from local file [ { 'line_num': 5, 'column_num': 10", "{ 'line_num': 40, 'column_num': 18 }, 'Foo' ], # [", "40, 'column_num': 6 } ) } ) ) } )", "3 } ), 'end' : has_entries( { 'line_num': 48, 'column_num':", ": has_entries( { 'line_num': 40, 'column_num': 9 } ), }", "'line_num': 48, 'column_num': 3 } ), 'end' : has_entries( {", "a warning with no fixits assert_that( results, equal_to( { 'fixits':", ": has_entries( { 'line_num': 54, 'column_num': 19 } ), }", "), 'location': has_entries( { 'line_num': 21, 'column_num': 16 } )", "], # no hover [ { 'line_num': 8, 'column_num': 1", "= [ # Function { 'req': ( 'goto.cc', 14, 21", "common_request = { 'completer_target' : 'filetype_default', 'filepath' : filepath, 'command_arguments':", "diags[ 'message' ].lower(): receive_diags = { 'request': args, 'route': '/receive_messages'", "[ subexpression_extract_range, FixIt_Check_SubexprExtract_Resolved ], [ raw_string_range, FixIt_Check_RawStringReplace_Resolved ], ] for", "'line_num': 26, 'column_num': 7 } ), } ), } ),", "or # (at your option) any later version. # #", "} ) ) } ) ) def FixIt_Check_cpp11_Repl( results ):", "'column_num': 9 } ), 'end' : has_entries( { 'line_num': 48,", "): filename = PathToTestFile( 'FixIt_Clang_cpp11.cpp' ) request = { 'completer_target'", "'goto.cc', 36, 17 ), 'res': ( 'goto.cc', 32, 54 )", "has_entries( { 'line_num': 40, 'column_num': 6 } ), 'end' :", "*sorted( [ 'ExecuteCommand', 'FixIt', 'Format', 'GetDoc', 'GetDocImprecise', 'GetType', 'GetTypeImprecise', 'GoTo',", "assert_that( results, has_entries( { 'fixits': contains( has_entries( { 'text': \"Expand", "60, 1 ), } ), # Second note: change to", "51 } ) } ), # second fix-it at 54,52", "'line_num': 43, 'column_num': 3 }, 'const Foo *' ], [", "test[ 1 ] request = common_args request.update( args ) test", ": 3, 'filepath' : filepath, 'contents' : contents, 'filetype' :", "has_entries( { 'start': has_entries( { 'line_num': 54, 'column_num': 58 }", "'cpp' } app.post_json( '/event_notification', CombineRequest( args, { 'event_name': 'FileReadyToParse', }", "to variable', 'resolve': True, 'command': has_entries( { 'command': 'clangd.applyTweak' }", "LineColMatcher( 60, 1 ), } ), # Second note: change", "{ 'line_num': 40, 'column_num': 6 } ) } ) )", "], [ { 'line_num': 48, 'column_num': 12 }, 'Foo *'", "assert_that( results, has_entries( { 'fixits': contains( # Change to SpellingIsNotMyStrongPoint", "'filepath' : filename, 'command_arguments': [ 'FixIt' ], 'line_num' : 16,", "response, list ): expect = { 'response': requests.codes.ok, 'data': contains(", "*' ], # [ { 'line_num': 29, 'column_num': 11 },", "} ), expect_errors = True ) WaitUntilCompleterServerReady( app, 'cpp' )", "}, # Unicøde { 'req': ( 'goto.cc', 34, 9 ),", "], # Declared and canonical type # On Ns:: [", "}, 'int' ], # Unicode [ { 'line_num': 51, 'column_num':", "= { 'response': requests.codes.internal_server_error, 'data': ErrorMatcher( RuntimeError, test[ 'res' ]", "'char' ], # Function # [ { 'line_num': 22, 'column_num':", "'column_num': 8 } }, 'route': '/run_completer_command', } ) @SharedYcmd def", ": test[ 'req' ][ 1 ], 'column_num': test[ 'req' ][", "'res': 'Cannot jump to location' }, { 'req': ( 'goto.cc',", "'contents' : ReadFile( filepath ), 'filetype' : 'cpp' } request", "'goto.cc', 34, 9 ), 'res': ( 'goto.cc', 32, 26 )", "16 }, 'const Foo *' ], # Auto in usage", "'line_num': 54, 'column_num': 51 } ) } ), # second", "[ { 'line_num': 13, 'column_num': 7 }, 'int' ], #", "19, 5 ) }, { 'req': ( 'goto.cc', 19, 5", "} ), # second fix-it at 54,52 has_entries( { 'chunks':", "), ( 'goto.cc', 24, 15 ), ( 'goto.cc', 25, 15", "} ), # Second note: change to == has_entries( {", "), 'completer_target': 'filetype_default', 'command_arguments': [ 'GoToDefinition' ], 'line_num': 10, 'column_num':", ": contents, 'filepath' : PathToTestFile( 'FixIt_Clang_cpp11.cpp' ), 'command_arguments': [ 'FixIt'", "contents = ReadFile( filepath ) common_args = { 'completer_target' :", "'filetype' : 'cpp' } app.post_json( '/event_notification', CombineRequest( request, { 'event_name':", "ideal, but # also prohibitively complex to try and strip", ") ) def FixIt_Check_cpp11_Repl( results ): assert_that( results, has_entries( {", "'start': has_entries( { 'line_num': 26, 'column_num': 7 } ), 'end'", "of ycmd. # # ycmd is free software: you can", "'goto.cc', 32, 26 ) }, # Another_Unicøde { 'req': (", "{ 'text': contains_string( \"change 'SpellingIsNotMyStringPiont' to \" \"'SpellingIsNotMyStrongPoint'\" ), 'chunks':", "'event_name': 'FileReadyToParse', } ), expect_errors = True ) WaitUntilCompleterServerReady( app,", "{ 'fixits': contains( # First note: put parens around it", "15, 1 ) ), ChunkMatcher( 'Bar', LineColMatcher( 15, 8 ),", "6, 10 ) }, # Local -> definition/declaration of Local", "Subcommands_GoToInclude_test(): tests = [ { 'req': ( 'main.cpp', 1, 6", "__attribute__\\(\\(thiscall\\)\\))?' ) ], ] for subcommand in [ 'GetType', 'GetTypeImprecise'", "], # multiple errors on a single line; both with", "and declaration of test { 'req': ( 'goto.cc', 21, 5", "'res': ( 'goto.cc', 32, 54 ) }, { 'req': (", "'/run_completer_command', 'expect' : expect } ) def Subcommands_GoTo_all_test(): tests =", "# Bound methods # On Win32, methods pick up an", "'line_num': 83, 'column_num': 3 }, 'end': { 'line_num': 83, 'column_num':", "), } ), } ) ), 'location': has_entries( { 'line_num':", "39, 'column_num': 11 }, 'Foo &' ], [ { 'line_num':", "16, 'column_num': 0 } ) } ) ) } )", "*' ], # Bound methods # On Win32, methods pick", "= ' ) print( expected ) request[ 'fixit' ] =", "15 } ) } ), ) } ) ) def", "{ 'line_num': 39, 'column_num': 11 }, 'Foo &' ], [", "'GetType', 'GetTypeImprecise', 'GoTo', 'GoToDeclaration', 'GoToDefinition', 'GoToImprecise', 'GoToInclude', 'GoToReferences', 'RefactorRename', 'RestartServer'", "app.post_json( '/resolve_fixit', BuildRequest( **args ) ).json print( 'Resolved fixit response", "'Bar', LineColMatcher( 1, 8 ), LineColMatcher( 1, 11 ) ),", "results ): assert_that( results, has_entries( { 'fixits': contains( # First", "def FixIt_Check_cuda( results ): assert_that( results, has_entries( { 'fixits': contains(", "), ChunkMatcher( 'Bar', LineColMatcher( 9, 3 ), LineColMatcher( 9, 6", "'column_num': 10 } ), 'end' : has_entries( { 'line_num': 16,", "{ 'filepath': os.path.abspath( file_path ), 'line_num': 2, 'column_num': 8 }", "16, 0, 'cpp11', cfile, FixIt_Check_cpp11_Ins ], [ 25, 14, 'cpp11',", "40, 'column_num': 9 } ), } ), } ) ),", "macro_expand_range = { 'start': { 'line_num': 83, 'column_num': 3 },", "ChunkMatcher, CombineRequest, LineColMatcher, LocationMatcher, ErrorMatcher, WithRetry, WaitUntilCompleterServerReady ) from ycmd.utils", "requests.codes.ok, 'data': contains( *sorted( [ 'ExecuteCommand', 'FixIt', 'Format', 'GetDoc', 'GetDocImprecise',", "ReadFile # This test is isolated to trigger objcpp hooks,", ": rng, 'filetype' : 'cpp' } app.post_json( '/event_notification', CombineRequest( args,", "'chunks': contains( has_entries( { 'replacement_text': equal_to( '=' ), 'range': has_entries(", "{ 'line_num': 25, 'column_num': 3 }, 'namespace Ns' ], #", "{ 'line_num': 24, 'column_num': 3 }, 'Foo' ], # [", "[ { 'line_num': 31, 'column_num': 3 }, 'const Foo &'", "FixIt_Check_cpp11_Repl ], [ 48, 3, 'cpp11', cfile, FixIt_Check_cpp11_DelAdd ], [", "52 } ), 'end' : has_entries( { 'line_num': 54, 'column_num':", "), LineColMatcher( 1, 11 ) ), ChunkMatcher( 'Bar', LineColMatcher( 9,", "get diags. diags = RunAfterInitialized( app, test ) while 'message'", "'res': ( 'goto.cc', 4, 9 ) }, # Local::in_line ->", "16, 'column_num' : 1, 'filetype' : 'cpp' } app.post_json( '/event_notification',", "RunFixItTest, test[ 0 ], test[ 1 ], test[ 2 ],", "results, has_entries( { 'fixits': contains( has_entries( { 'text': \"Expand auto", ") from pprint import pprint import requests import os.path from", "5 ) }, # Unicøde { 'req': ( 'goto.cc', 34,", "( 'goto.cc', 6, 10 ) }, # Local -> definition/declaration", "'end' : has_entries( { 'line_num': 16, 'column_num': 13 } ),", "), 'end' : has_entries( { 'line_num': 48, 'column_num': 9 }", "ChunkMatcher( '(', LineColMatcher( 59, 8 ), LineColMatcher( 59, 8 )", "shows up in the type, which isn't ideal, but #", "-> definition/declaration of x { 'req': ( 'goto.cc', 23, 21", "7, 1 ), 'res': 'Cannot jump to location' }, {", "1, 1 ) }, { 'req': ( 'main.cpp', 5, 11", "' ) print( actual ) assert_that( actual, equal_to( expected )", "'cuda', 'fixit_test.cu' ) ufile = PathToTestFile( 'unicode.cc' ) tests =", "Function { 'req': ( 'goto.cc', 14, 21 ), 'res': [", "), 'res': ( 'goto.cc', 32, 26 ) }, # Another_Unicøde", "'column_num': 7 }, 'char' ], # Function # [ {", "{ 'line_num': 39, 'column_num': 15 }, 'Foo' ], [ {", ") } ) ) def FixIt_Check_objc( results ): assert_that( results,", "'command': 'clangd.applyTweak' } ) } ) ) } ) )", "'column_num': 1 }, 'end': { 'line_num': 80, 'column_num': 4 },", "'response': requests.codes.ok, 'data': contains( *[ LocationMatcher( PathToTestFile( folder, os.path.normpath( location[", "-> definition/declaration of Local::in_line { 'req': ( 'goto.cc', 24, 26", "), } ) ), 'location': has_entries( { 'line_num': 54, 'column_num':", "35, 7, 'cpp11', cfile, FixIt_Check_cpp11_Del ], [ 40, 6, 'cpp11',", "27, 8 ), 'res': 'Cannot jump to location' }, ]", "Local::out_of_line -> declaration of Local::out_of_line { 'req': ( 'goto.cc', 25,", "'data': expected } } RunAfterInitialized( app, test ) def Subcommands_GetType_test():", "84, 3 ) ), ChunkMatcher( 'dummy', LineColMatcher( 84, 10 ),", "column, } args.update( language_options[ lang ] ) test = {", "'Convert to raw string', 'chunks': contains( ChunkMatcher( 'R\"(\\\\\\\\r\\\\asd\\n\\\\v)\"', LineColMatcher( 80,", "# Second note: change to == has_entries( { 'text': contains_string(", "'cpp11', cfile, FixIt_Check_cpp11_Note ], # FixIt due to forced spell", "Subcommands_FixIt_all_test(): cfile = PathToTestFile( 'FixIt_Clang_cpp11.cpp' ) mfile = PathToTestFile( 'objc',", "Subcommands_FixIt_Ranged_test(): expand_auto_range = { 'start': { 'line_num': 80, 'column_num': 1", "of Local { 'req': ( 'goto.cc', 24, 16 ), 'res':", "[ { 'line_num': 12, 'column_num': 10 }, 'Foo' ], #", "13, 'column_num': 3 }, 'int' ], [ { 'line_num': 13,", "11, 10 ) }, { 'req': ( 'goto.cc', 11, 10", "'text': 'Extract subexpression to variable', 'resolve': True, 'command': has_entries( {", "'const int' ], # [ { 'line_num': 35, 'column_num': 14", "} ) ) } ) ) def FixIt_Check_cpp11_Del( results ):", "'cpp11', cfile, FixIt_Check_cpp11_Ins ], [ 25, 14, 'cpp11', cfile, FixIt_Check_cpp11_InsMultiLine", "encoding: utf-8 # # Copyright (C) 2018 ycmd contributors #", "fixit [ 21, 16, 'cpp11', ufile, FixIt_Check_unicode_Ins ], # FixIt", ") } ) ) def FixIt_Check_cpp11_MultiSecond( results ): assert_that( results,", "'request': { 'contents': ReadFile( file_path ), 'completer_target': 'filetype_default', 'command_arguments': [", "= { 'response': requests.codes.ok, 'data': LocationMatcher( PathToTestFile( folder, os.path.normpath( response[", "License for more details. # # You should have received", "{ 'line_num': 13, 'column_num': 3 }, 'int' ], [ {", ") } ) ) } ) ) def FixIt_Check_cpp11_Del( results", "26, 'column_num': 7 } ), 'end' : has_entries( { 'line_num':", "72, 9, 'cpp11', cfile, FixIt_Check_cpp11_SpellCheck ], ] for test in", "l Lang File, Checker [ 16, 0, 'cpp11', cfile, FixIt_Check_cpp11_Ins", "LineColMatcher( 59, 8 ) ), ChunkMatcher( ')', LineColMatcher( 61, 12", "80, 1 ), LineColMatcher( 80, 6 ) ), ) }", "42, 'column_num': 3 }, 'const Foo &' ], [ {", "FixIt_Check_cpp11_MultiFirst( results ): assert_that( results, has_entries( { 'fixits': contains( #", "expected ) ) @SharedYcmd def Subcommands_RefactorRename_test( app ): test =", "requests.codes.ok: if not isinstance( test[ 1 ], BaseMatcher ): expected", "] response = app.post_json( '/resolve_fixit', BuildRequest( **args ) ).json print(", "'start': has_entries( { 'line_num': 35, 'column_num': 7 } ), 'end'", "40, 'column_num': 3 }, 'Foo' ], [ { 'line_num': 40,", "13, 1 ), 'res': 'Cannot jump to location' }, {", "{ 'req': ( 'goto.cc', 16, 6 ), 'res': 'Cannot jump", "[ 54, 15, 'cpp11', cfile, FixIt_Check_cpp11_MultiFirst ], # should put", ") @SharedYcmd def Subcommands_GoTo_ZeroBasedLineAndColumn_test( app ): file_path = PathToTestFile( 'GoTo_Clang_ZeroBasedLineAndColumn_test.cc'", ") WaitUntilCompleterServerReady( app, 'cpp' ) expected = app.post_json( '/run_completer_command', BuildRequest(", ") request[ 'fixit' ] = expected[ 'fixits' ][ 0 ]", "in usage # [ { 'line_num': 34, 'column_num': 14 },", "args[ 'fixit' ] = response[ 'fixits' ][ 0 ] response", "[ { 'line_num': 40, 'column_num': 3 }, 'Foo' ], [", "{ 'line_num': 26, 'column_num': 13 }, # 'Ns::Type => Ns::BasicType<char>'", "35, 'column_num': 7 } ), 'end' : has_entries( { 'line_num':", "} ) } ) ) } ) ) def FixIt_Check_cpp11_SpellCheck(", "), 'res': ( 'goto.cc', 6, 10 ) }, # Local", ") mfile = PathToTestFile( 'objc', 'FixIt_Clang_objc.m' ) cufile = PathToTestFile(", "'req': ( 'goto.cc', 34, 9 ), 'res': ( 'goto.cc', 32,", "'cpp11', cfile, FixIt_Check_cpp11_InsMultiLine ], [ 35, 7, 'cpp11', cfile, FixIt_Check_cpp11_Del", "test = { 'request': { 'filetype': 'cpp', 'completer_target': 'filetype_default', 'contents':", "contains( # Change to SpellingIsNotMyStrongPoint has_entries( { 'text': contains_string( \"change", "response = app.post_json( '/resolve_fixit', BuildRequest( **args ) ).json print( 'Resolved", "15 ), ( 'goto.cc', 25, 15 ) ] }, #", "{ 'line_num': 15, 'column_num': 7 }, 'char' ], # Function", "put closest fix-it first? [ 54, 51, 'cpp11', cfile, FixIt_Check_cpp11_MultiSecond", "14 ), ( 'goto.cc', 24, 15 ), ( 'goto.cc', 25,", "], [ subexpression_extract_range, FixIt_Check_SubexprExtract_Resolved ], [ raw_string_range, FixIt_Check_RawStringReplace_Resolved ], ]", "details. # # You should have received a copy of", "has_entries( { 'line_num': 54, 'column_num': 51 } ) } ),", "{ 'req': ( 'goto.cc', 14, 21 ), 'res': [ (", "25, 'column_num': 14 } ) } ) ) } )", "assert_that, contains, contains_string, equal_to, has_entries, has_entry, matches_regexp ) from pprint", "raw_string_range, FixIt_Check_RawStringReplace_Resolved ], ] for test in tests: yield RunRangedFixItTest,", "tests: yield RunGoToTest_all, '', 'GoToReferences', test @SharedYcmd def RunGetSemanticTest( app,", "54, 'column_num': 19 } ), } ), } ) ),", "1 ) ), ChunkMatcher( 'Bar', LineColMatcher( 15, 8 ), LineColMatcher(", "34, 'column_num': 14 }, 'const Foo' ], # [ {", "'int' ], # [ { 'line_num': 37, 'column_num': 13 },", "published by # the Free Software Foundation, either version 3", "PathToTestFile( 'basic.cpp' ) ), 'filepath': PathToTestFile( 'basic.cpp' ), 'command_arguments': [", "] ) @SharedYcmd def RunFixItTest( app, line, column, lang, file_path,", "], # unicode in line for fixit [ 21, 16,", "has_entry, matches_regexp ) from pprint import pprint import requests import", "3, 'filetype': 'cpp', 'filepath': file_path }, 'expect': { 'response': requests.codes.ok,", "], [ { 'line_num': 48, 'column_num': 18 }, 'int' ],", "assert_that( results, has_entries( { 'fixits': contains( has_entries( { 'text': 'Extract", "PathToTestFile( 'FixIt_Clang_cpp11.cpp' ) ) args = { 'completer_target' : 'filetype_default',", ") cufile = PathToTestFile( 'cuda', 'fixit_test.cu' ) ufile = PathToTestFile(", "i\\)(?: __attribute__\\(\\(thiscall\\)\\))?' ) ], ] for subcommand in [ 'GetType',", "] if isinstance( response, list ): expect = { 'response':", "'end': { 'line_num': 83, 'column_num': 13 }, } raw_string_range =", "== requests.codes.ok: if not isinstance( test[ 1 ], BaseMatcher ):", "1 }, ErrorMatcher( RuntimeError, 'No hover information.' ), requests.codes.server_error ]", ") def FixIt_Check_cpp11_Note( results ): assert_that( results, has_entries( { 'fixits':", "FixIt_Check_cpp11_Note( results ): assert_that( results, has_entries( { 'fixits': contains( #", "response = app.post_json( '/run_completer_command', BuildRequest( **args ) ).json args[ 'fixit'", "] actual = app.post_json( '/resolve_fixit', BuildRequest( **request ) ).json print(", "1, 11 ) ), ChunkMatcher( 'Bar', LineColMatcher( 9, 3 ),", ") ), 'location': has_entries( { 'line_num': 40, 'column_num': 6 }", ") }, # Local::out_of_line -> declaration of Local::out_of_line { 'req':", ") } ), ) } ) ) def FixIt_Check_objc( results", "'objective-c': { 'filetype' : 'objc', }, } args = {", "# Local::out_of_line -> declaration of Local::out_of_line { 'req': ( 'goto.cc',", "60, 1, 'cpp11', cfile, FixIt_Check_cpp11_Note ], # FixIt due to", "RunAfterInitialized( app, test ) def Subcommands_GetType_test(): tests = [ #", "declaration # [ { 'line_num': 28, 'column_num': 3 }, 'struct", "test[ 'res' ] ) } RunAfterInitialized( app, { 'request': request,", ") ), ChunkMatcher( '', LineColMatcher( 17, 14 ), LineColMatcher( 17,", "# test -> definition and declaration of test { 'req':", "], [ 5, 3, 'objective-c', mfile, FixIt_Check_objc ], [ 7,", "'column_num': 15 } ) } ), has_entries( { 'chunks': contains(", ") common_request = { 'completer_target' : 'filetype_default', 'filepath' : filepath,", "], # should put closest fix-it first? [ 54, 51,", "]: yield RunGoToTest_all, 'test-include', cmd, test def Subcommands_GoToReferences_test(): tests =", "'column_num': 9 } ), } ), } ) ), 'location':", "'replacement_text': equal_to( '=' ), 'range': has_entries( { 'start': has_entries( {", "{ 'line_num': 54, 'column_num': 19 } ), } ), }", "received a copy of the GNU General Public License #", "} elif isinstance( response, tuple ): expect = { 'response':", "'expect': { 'response': requests.codes.ok, 'data': contains( *sorted( [ 'ExecuteCommand', 'FixIt',", "}, # Local::out_of_line -> definition of Local::out_of_line { 'req': (", "'quote/b.hpp', 1, 1 ) }, { 'req': ( 'main.cpp', 5,", "9 } ), 'end' : has_entries( { 'line_num': 21, 'column_num':", "83, 'column_num': 13 }, } raw_string_range = { 'start': {", "'line_num': 25, 'column_num': 8 }, # 'Ns::Type => Ns::BasicType<char>' ],", "29, 'column_num': 3 }, 'Foo *' ], # [ {", "'column_num': 10 }, 'docstring', requests.codes.ok ], # from header [", "utf-8 # # Copyright (C) 2018 ycmd contributors # #", "'GetDoc', 'GetDocImprecise' ]: for test in tests: yield ( RunGetSemanticTest,", "yield ( RunGetSemanticTest, PathToTestFile( 'GetDoc_Clang_test.cc' ), 'cpp', test, [ subcommand", "'contents' : contents, 'filepath' : file_path, 'command_arguments': [ 'FixIt' ],", "ufile, FixIt_Check_unicode_Ins ], # FixIt attached to a \"child\" diagnostic", "def Subcommands_FixIt_AlreadyResolved_test( app ): filename = PathToTestFile( 'FixIt_Clang_cpp11.cpp' ) request", "'data': contains( *sorted( [ 'ExecuteCommand', 'FixIt', 'Format', 'GetDoc', 'GetDocImprecise', 'GetType',", "'line_num': 35, 'column_num': 7 } ) } ) ) }", "def Subcommands_FixIt_all_test(): cfile = PathToTestFile( 'FixIt_Clang_cpp11.cpp' ) mfile = PathToTestFile(", "'const Foo' ], # [ { 'line_num': 34, 'column_num': 21", "See the # GNU General Public License for more details.", "3, 12 ), } ) ) } ) ) def", "contains( ChunkMatcher( 'Bar', LineColMatcher( 1, 8 ), LineColMatcher( 1, 11", "[ { 'line_num': 39, 'column_num': 3 }, 'Foo' ], [", "{ 'response': requests.codes.ok, 'data': contains( *[ LocationMatcher( PathToTestFile( folder, os.path.normpath(", "{ 'req': ( 'goto.cc', 38, 3 ), 'res': ( 'goto.cc',", "'range': has_entries( { 'start': has_entries( { 'line_num': 26, 'column_num': 7", "54, 51, 'cpp11', cfile, FixIt_Check_cpp11_MultiSecond ], # unicode in line", "36, 'column_num': 19 }, 'int' ], # [ { 'line_num':", "4, 9 ) }, # Local::in_line -> definition/declaration of Local::in_line", "{ 'response': requests.codes.ok, 'data': contains( *sorted( [ 'ExecuteCommand', 'FixIt', 'Format',", "Foo *' ], # [ { 'line_num': 35, 'column_num': 22", "'cpp' ) response = app.post_json( '/run_completer_command', BuildRequest( **args ) ).json", "'start': has_entries( { 'line_num': 48, 'column_num': 9 } ), 'end'", "app, receive_diags ) diags = RunAfterInitialized( app, test ) results", "that it will be useful, # but WITHOUT ANY WARRANTY;", "' ', LineColMatcher( 17, 19 ), LineColMatcher( 17, 19 )", "), ) } ) ) } ) ) def Subcommands_FixIt_all_test():", "16 }, 'const Foo &' ], # [ { 'line_num':", "}, { 'req': ( 'goto.cc', 38, 3 ), 'res': (", "}, matches_regexp( r'int bar\\(int i\\)(?: __attribute__\\(\\(thiscall\\)\\))?' ) ], ] for", "31, 'column_num': 3 }, 'const Foo &' ], # [", ").json args[ 'fixit' ] = response[ 'fixits' ][ 0 ]", ") } ) ) def FixIt_Check_cpp11_InsMultiLine( results ): # Similar", "print( 'Resolved fixit response = ' ) print( response )", "3', requests.codes.ok ], # no hover [ { 'line_num': 8,", "'goto.cc', 23, 21 ), 'res': ( 'goto.cc', 4, 9 )", "'end' : has_entries( { 'line_num': 16, 'column_num': 10 } ),", "response ] ) } elif isinstance( response, tuple ): expect", "'data': ErrorMatcher( RuntimeError, test[ 'res' ] ) } RunAfterInitialized( app,", "'Foo &' ], [ { 'line_num': 39, 'column_num': 15 },", "location in response ] ) } elif isinstance( response, tuple", "around the assignment' ), 'chunks': contains( ChunkMatcher( '(', LineColMatcher( 59,", "cfile, FixIt_Check_cpp11_Ins ], [ 25, 14, 'cpp11', cfile, FixIt_Check_cpp11_InsMultiLine ],", "contains( has_entries( { 'text': 'Convert to raw string', 'chunks': contains(", ": 'cpp' } app.post_json( '/event_notification', CombineRequest( request, { 'event_name': 'FileReadyToParse',", "83, 17 ) ), ) } ) ) } )", "= { 'request': request, 'route': '/run_completer_command', 'expect': { 'response': response,", "# [ { 'line_num': 28, 'column_num': 3 }, 'struct Foo", "} else: expect = { 'response': requests.codes.internal_server_error, 'data': ErrorMatcher( RuntimeError,", "contains_string( '==' ), 'chunks': contains( ChunkMatcher( '==', LineColMatcher( 60, 8", "Foo *' ], # Cursor on usage [ { 'line_num':", "), 'location': has_entries( { 'line_num': 35, 'column_num': 7 } )", ") def FixIt_Check_cpp11_InsMultiLine( results ): # Similar to FixIt_Check_cpp11_1 but", "11 ), 'res': ( 'system/c.hpp', 1, 1 ) }, #", "'line_num': 5, 'column_num': 3 } ), } ), } )", "subexpression to variable', 'chunks': contains( ChunkMatcher( 'auto dummy = foo(i", "struct Foo' ], # [ { 'line_num': 45, 'column_num': 19", "{ 'line_num': 34, 'column_num': 14 }, 'const Foo' ], #", "'GetDocImprecise' ]: for test in tests: yield ( RunGetSemanticTest, PathToTestFile(", "'FixIt_Clang_cpp11.cpp' ), 'command_arguments': [ 'FixIt' ], 'range' : rng, 'filetype'", "LineColMatcher( 72, 9 ), LineColMatcher( 72, 35 ) ) ),", "FixIt_Check_cpp11_InsMultiLine( results ): # Similar to FixIt_Check_cpp11_1 but inserts split", "} macro_expand_range = { 'start': { 'line_num': 83, 'column_num': 3", "has_entries( { 'fixits': contains( has_entries( { 'chunks': contains( has_entries( {", "expected = has_entry( 'message', contains_string( test[ 1 ] ) )", "]: for test in tests: yield ( RunGetSemanticTest, PathToTestFile( 'GetDoc_Clang_test.cc'", "( 'goto.cc', 25, 27 ), 'res': ( 'goto.cc', 14, 13", "*' ], # [ { 'line_num': 32, 'column_num': 16 },", "{ 'request': args, 'route': '/detailed_diagnostic' } # First get diags.", "3 } ), 'end' : has_entries( { 'line_num': 5, 'column_num':", "list ): expect = { 'response': requests.codes.ok, 'data': contains( *[", "{ 'line_num': 54, 'column_num': 53 } ), } ), }", "), 'chunks': contains( ChunkMatcher( 'void', LineColMatcher( 3, 12 ), LineColMatcher(", "RunAfterInitialized( app, { 'request': request, 'route' : '/run_completer_command', 'expect' :", "expected } } RunAfterInitialized( app, test ) def Subcommands_GetType_test(): tests", "= RunAfterInitialized( app, test ) while 'message' in diags and", "args ) test = { 'request': request, 'route': '/run_completer_command', 'expect':", "and 'diagnostics' in diags[ 'message' ].lower(): receive_diags = { 'request':", "test[ 2 ] ) @SharedYcmd def RunFixItTest( app, line, column,", "} ), } ) ), 'location': has_entries( { 'line_num': 40,", "'filepath' : PathToTestFile( 'FixIt_Clang_cpp11.cpp' ), 'command_arguments': [ 'FixIt' ], 'range'", "print( 'actual = ' ) print( actual ) assert_that( actual,", "11, 10 ) }, # GoToDeclaration alternates between definition and", "'line_num': 54, 'column_num': 15 } ) } ), has_entries( {", "{ 'replacement_text': equal_to( '' ), 'range': has_entries( { 'start': has_entries(", ") } ) ) } ) ) def FixIt_Check_cpp11_InsMultiLine( results", "{ 'line_num': 5, 'column_num': 3 } ), 'end' : has_entries(", "requests.codes.ok ], # from header [ { 'line_num': 6, 'column_num':", "{ 'response': requests.codes.ok, 'data': { 'filepath': os.path.abspath( file_path ), 'line_num':", "'cpp11', cfile, FixIt_Check_cpp11_SpellCheck ], ] for test in tests: yield", "10, 13 ), 'res': 'Cannot jump to location' }, ]", "} ) ) } ) ) def FixIt_Check_objc_NoFixIt( results ):", "], # Cursor on decl for refs & pointers [", "for fixit [ 21, 16, 'cpp11', ufile, FixIt_Check_unicode_Ins ], #", "Expected failures { 'req': ( 'main.cpp', 7, 1 ), 'res':", "'int' ], # Unicode [ { 'line_num': 51, 'column_num': 13", "Free Software Foundation, either version 3 of the License, or", "# [ { 'line_num': 43, 'column_num': 3 }, 'const Foo", "'end': { 'line_num': 84, 'column_num': 20 }, } macro_expand_range =", "# (at your option) any later version. # # ycmd", "= RunAfterInitialized( app, test ) results = app.post_json( '/run_completer_command', BuildRequest(", ") assert_that( actual, equal_to( expected ) ) @SharedYcmd def Subcommands_RefactorRename_test(", "and/or modify # it under the terms of the GNU", "implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR", "'location': LineColMatcher( 60, 1 ), } ), # Second note:", "= app.post_json( '/run_completer_command', BuildRequest( **request ) ).json print( 'expected =", "an __attribute__((thiscall)) to annotate their # calling convention. This shows", "}, 'int' ], [ { 'line_num': 48, 'column_num': 12 },", "'line_num': 47, 'column_num': 12 }, 'Foo' ], [ { 'line_num':", "app, test ) while 'message' in diags and 'diagnostics' in", "# calling convention. This shows up in the type, which", "test @SharedYcmd def RunGetSemanticTest( app, filepath, filetype, test, command, response", "SpellingIsNotMyStrongPoint has_entries( { 'text': contains_string( \"change 'SpellingIsNotMyStringPiont' to \" \"'SpellingIsNotMyStrongPoint'\"", "), ) } ) ) def FixIt_Check_objc( results ): assert_that(", "{ 'line_num': 54, 'column_num': 64 } ), 'end' : has_entries(", "a \"child\" diagnostic (i.e. a Note) [ 60, 1, 'cpp11',", "has_entries( { 'line_num': 16, 'column_num': 13 } ), } ),", "), } ), } ), has_entries( { 'replacement_text': equal_to( '~'", "it and/or modify # it under the terms of the", "'==', LineColMatcher( 60, 8 ), LineColMatcher( 60, 9 ) )", "'const Foo &' ], # [ { 'line_num': 31, 'column_num':", "( 'goto.cc', 25, 15 ) ] }, # Expected failure", "21, 'column_num': 9 } ), 'end' : has_entries( { 'line_num':", "r'int bar\\(int i\\)(?: __attribute__\\(\\(thiscall\\)\\))?' ) ], ] for subcommand in", "), 'res': ( 'goto.cc', 14, 13 ) }, # test", "), ( 'goto.cc', 14, 13 ), ( 'goto.cc', 25, 22", "x = 3', requests.codes.ok ], # no hover [ {", "), 'range': has_entries( { 'start': has_entries( { 'line_num': 40, 'column_num':", "has_entries( { 'text': \"Expand auto type\", 'chunks': contains( ChunkMatcher( 'const", "'const struct Foo &' ], # [ { 'line_num': 43,", "): assert_that( results, has_entries( { 'fixits': contains( # First note:", "'start': has_entries( { 'line_num': 48, 'column_num': 15 } ), 'end'", "SharedYcmd, PathToTestFile, RunAfterInitialized ) from ycmd.tests.test_utils import ( BuildRequest, ChunkMatcher,", "# Namespace { 'req': ( 'goto.cc', 24, 17 ), 'res':", "Bound methods # On Win32, methods pick up an __attribute__((thiscall))", "'start': has_entries( { 'line_num': 48, 'column_num': 3 } ), 'end'", "'column_num': 6 } ) } ) ) } ) )", "} ) @SharedYcmd def RunGoToTest_all( app, folder, command, test ):", ") response = test[ 'res' ] if isinstance( response, list", "'~' ), 'range': has_entries( { 'start': has_entries( { 'line_num': 48,", "} ) ) } ) ) def FixIt_Check_cpp11_SpellCheck( results ):", "( 'goto.cc', 24, 15 ), ( 'goto.cc', 25, 15 )", "it under the terms of the GNU General Public License", "test def Subcommands_GoToDeclaration_all_test(): tests = [ # Local::x -> definition/declaration", "], BaseMatcher ): expected = has_entry( 'message', contains_string( test[ 1", "lines # assert_that( results, has_entries( { 'fixits': contains( has_entries( {", "'line_num': 48, 'column_num': 15 } ), 'end' : has_entries( {", ") RunAfterInitialized( app, { 'request': { 'completer_target': 'filetype_default', 'line_num': 10,", ": 'filetype_default', 'contents' : ReadFile( filename ), 'filepath' : filename,", "# Local -> definition/declaration of Local { 'req': ( 'goto.cc',", "# [ { 'line_num': 25, 'column_num': 8 }, # 'Ns::Type", "{ 'line_num': 40, 'column_num': 6 } ), 'end' : has_entries(", ") }, # Unicøde { 'req': ( 'goto.cc', 34, 9", "46, 'column_num': 13 }, 'const struct Foo *' ], #", "'line_num': 54, 'column_num': 52 } ), 'end' : has_entries( {", "), ChunkMatcher( 'dummy', LineColMatcher( 84, 10 ), LineColMatcher( 84, 22", "ChunkMatcher( 'Bar', LineColMatcher( 17, 3 ), LineColMatcher( 17, 6 )", "'GetType_Clang_test.cc' ), 'cpp', test, [ subcommand ] ) def Subcommands_GetDoc_test():", "# assert_that( results, has_entries( { 'fixits': contains( has_entries( { 'chunks':", "app, test ) def Subcommands_GetType_test(): tests = [ # Basic", "'column_num' : 1, 'filetype' : 'cpp' } app.post_json( '/event_notification', CombineRequest(", "[ { 'line_num': 36, 'column_num': 13 }, 'Foo' ], [", "} ), 'end' : has_entries( { 'line_num': 5, 'column_num': 3", "'goto.cc', 14, 21 ), 'res': [ ( 'goto.cc', 11, 10", "'start': { 'line_num': 84, 'column_num': 14 }, 'end': { 'line_num':", "has_entries( { 'line_num': 16, 'column_num': 10 } ), } ),", "} ) ) def FixIt_Check_cpp11_Note( results ): assert_that( results, has_entries(", "] ) ), response[ 1 ], response[ 2 ] )", "FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General", ": has_entries( { 'line_num': 26, 'column_num': 7 } ), }", "'clangd.applyTweak' } ) } ) ) } ) ) def", "'column_num': 8 }, 'Foo' ], [ { 'line_num': 12, 'column_num':", "LineColMatcher( 59, 8 ), LineColMatcher( 59, 8 ) ), ChunkMatcher(", "{ 'command': 'clangd.applyTweak' } ) } ) ) } )", ": contents, 'filetype' : filetype } args = test[ 0", ") } ) ) } ) ) def Subcommands_FixIt_all_test(): cfile", "21, 16, 'cpp11', ufile, FixIt_Check_unicode_Ins ], # FixIt attached to", "4, }, 'expect': { 'response': requests.codes.ok, 'data': has_entries( { 'fixits':", ") else: expected = has_entry( 'message', test[ 1 ] )", "23, 21 ), 'res': ( 'goto.cc', 4, 9 ) },", ") ), ChunkMatcher( 'Bar', LineColMatcher( 9, 3 ), LineColMatcher( 9,", "'contents': ReadFile( PathToTestFile( 'basic.cpp' ) ), 'filepath': PathToTestFile( 'basic.cpp' ),", "10 ) }, # GoToDeclaration alternates between definition and declaration", "} ), has_entries( { 'replacement_text': equal_to( ')' ), 'range': has_entries(", "has_entries( { 'replacement_text': equal_to( '~' ), 'range': has_entries( { 'start':", "{ 'replacement_text': equal_to( 'static_cast<int>(' ), 'range': has_entries( { 'start': has_entries(", "test[ 0 ], test[ 1 ], test[ 2 ], test[", "test def Subcommands_GoToInclude_test(): tests = [ { 'req': ( 'main.cpp',", "1 ], 'column_num': test[ 'req' ][ 2 ], } )", "'column_num': 6 }, 'int main()' ], # Declared and canonical", "isinstance( response, list ): expect = { 'response': requests.codes.ok, 'data':", "'contents' : ReadFile( filename ), 'filepath' : filename, 'command_arguments': [", "), } ) ), 'location': has_entries( { 'line_num': 25, 'column_num':", "with ycmd. If not, see <http://www.gnu.org/licenses/>. from __future__ import absolute_import", "'column_num': 3 }, 'struct Foo &' ], # [ {", "60, 9 ) ) ), 'location': LineColMatcher( 60, 1 ),", "{ 'fixits': contains( has_entries( { 'text': \"Expand macro 'DECLARE_INT'\", 'chunks':", "BuildRequest( **args ) ).json args[ 'fixit' ] = response[ 'fixits'", "), 'end' : has_entries( { 'line_num': 54, 'column_num': 58 }", "def FixIt_Check_cpp11_Del( results ): # Removal of :: assert_that( results,", "LineColMatcher( 84, 10 ), LineColMatcher( 84, 22 ) ), )", "[ command ], 'contents' : ReadFile( filepath ), 'filetype' :", "test def Subcommands_GoToReferences_test(): tests = [ # Function { 'req':", "int' ], # [ { 'line_num': 35, 'column_num': 14 },", "LineColMatcher( 17, 17 ), LineColMatcher( 17, 17 ) ), ChunkMatcher(", "'req': ( 'main.cpp', 2, 14 ), 'res': ( 'system/a.hpp', 1,", "25, 14, 'cpp11', cfile, FixIt_Check_cpp11_InsMultiLine ], [ 35, 7, 'cpp11',", "'column_num': 15 }, # 'Ns::Type => Ns::BasicType<char>' ], # [", "'GoToImprecise', 'GoToInclude', 'GoToReferences', 'RefactorRename', 'RestartServer' ] ) ) }, 'route':", "'column_num': 15 } ) } ), ) } ) )", "'res' ] ) } RunAfterInitialized( app, { 'request': request, 'route'", "2 }, 'int main()' ], [ { 'line_num': 22, 'column_num':", "}, 'Foo' ], [ { 'line_num': 39, 'column_num': 11 },", "}, 'const Foo *' ], # [ { 'line_num': 32,", "'Foo' ], [ { 'line_num': 12, 'column_num': 9 }, 'Foo'", "'cpp11', cfile, FixIt_Check_cpp11_Repl ], [ 48, 3, 'cpp11', cfile, FixIt_Check_cpp11_DelAdd", "main()' ], # Declared and canonical type # On Ns::", "( 'goto.cc', 14, 13 ), 'res': ( 'goto.cc', 11, 10", "'res': ( 'goto.cc', 11, 10 ) }, # GoToDeclaration alternates", "{ 'line_num': 28, 'column_num': 11 }, 'struct Foo &' ],", "13 ), 'res': 'Cannot jump to location' }, ] for", "'range': has_entries( { 'start': has_entries( { 'line_num': 48, 'column_num': 9", "32, 54 ) }, { 'req': ( 'goto.cc', 36, 25", "# [ { 'line_num': 37, 'column_num': 13 }, 'Foo *'", "{ 'start': has_entries( { 'line_num': 16, 'column_num': 13 } ),", "for more details. # # You should have received a", "'int' ], # Auto in declaration # [ { 'line_num':", "LineColMatcher( 80, 36 ) ), ) } ) ) }", "3, 15 ) ) ), 'location': LineColMatcher( 3, 12 ),", "hamcrest.core.base_matcher import BaseMatcher from hamcrest import ( assert_that, contains, contains_string,", "Removal of :: assert_that( results, has_entries( { 'fixits': contains( has_entries(", "= { 'response': requests.codes.ok, 'data': contains( *[ LocationMatcher( PathToTestFile( folder,", "results, has_entries( { 'fixits': contains( # First note: put parens", "], [ { 'line_num': 40, 'column_num': 11 }, 'Foo *'", "# also prohibitively complex to try and strip out. [", ") expected = app.post_json( '/run_completer_command', BuildRequest( **request ) ).json print(", "{ 'line_num': 48, 'column_num': 12 }, 'Foo *' ], [", "test, [ subcommand ] ) def Subcommands_GetDoc_test(): tests = [", "6 } ), 'end' : has_entries( { 'line_num': 40, 'column_num':", "\"Expand auto type\", 'chunks': contains( ChunkMatcher( 'const char *', LineColMatcher(", "'res': [ ( 'goto.cc', 2, 11 ), ( 'goto.cc', 14,", "Second note: change to == has_entries( { 'text': contains_string( '=='", "'column_num': 14 }, 'const Foo' ], # [ { 'line_num':", ") ) } ) ) def FixIt_Check_cpp11_Del( results ): #", "'(', LineColMatcher( 59, 8 ), LineColMatcher( 59, 8 ) ),", "Ns::BasicType<char>' ], # Cursor on decl for refs & pointers", "}, # FIXME: should fail since b.hpp is included with", "), 'location': has_entries( { 'line_num': 54, 'column_num': 15 } )", ") } ), ) } ) ) def FixIt_Check_unicode_Ins( results", "has_entries( { 'fixits': contains( has_entries( { 'text': 'Convert to raw", "-> definition/declaration of Local { 'req': ( 'goto.cc', 24, 16", "[ { 'line_num': 48, 'column_num': 12 }, 'Foo *' ],", "): assert_that( results, has_entries( { 'fixits': contains( # first fix-it", "13 }, 'Unicøde *' ], # Bound methods # On", "filepath, 'command_arguments': [ command ], 'contents' : ReadFile( filepath ),", "'start': has_entries( { 'line_num': 54, 'column_num': 52 } ), 'end'", "ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY", "5, 11 ), 'res': ( 'system/c.hpp', 1, 1 ) },", "8, 'column_num': 1 }, ErrorMatcher( RuntimeError, 'No hover information.' ),", "'main.cpp', 7, 1 ), 'res': 'Cannot jump to location' },", "'column_num': 67 } ), } ), } ) ), 'location':", "has_entries( { 'text': 'Extract subexpression to variable', 'resolve': True, 'command':", "), 'end' : has_entries( { 'line_num': 16, 'column_num': 13 }", "raw_string_range = { 'start': { 'line_num': 80, 'column_num': 19 },", "{ 'line_num': 13, 'column_num': 7 }, 'int' ], # [", "} ) @SharedYcmd def Subcommands_GoTo_ZeroBasedLineAndColumn_test( app ): file_path = PathToTestFile(", ": file_path, 'command_arguments': [ 'FixIt' ], 'line_num' : line, 'column_num'", "54,52 has_entries( { 'chunks': contains( has_entries( { 'replacement_text': equal_to( ''", "= { 'request': args, 'route': '/detailed_diagnostic' } # First get", "requests.codes.server_error ] ] for subcommand in [ 'GetDoc', 'GetDocImprecise' ]:", "7 } ), } ), } ), has_entries( { 'replacement_text':", "tests = [ # L # i C # n", "35, 'column_num': 22 }, 'const int' ], [ { 'line_num':", "[ { 'line_num': 28, 'column_num': 11 }, 'struct Foo &'", "LineColMatcher( 17, 19 ) ), ) } ) ) }", "[ 35, 7, 'cpp11', cfile, FixIt_Check_cpp11_Del ], [ 40, 6,", "], # [ { 'line_num': 46, 'column_num': 20 }, 'const", "else: expected = has_entry( 'message', test[ 1 ] ) else:", "'GetDocImprecise', 'GetType', 'GetTypeImprecise', 'GoTo', 'GoToDeclaration', 'GoToDefinition', 'GoToImprecise', 'GoToInclude', 'GoToReferences', 'RefactorRename',", ": has_entries( { 'line_num': 54, 'column_num': 67 } ), }", "'GetDoc_Clang_test.cc' ), 'cpp', test, [ subcommand ], test[ 2 ]", "'line_num': 25, 'column_num': 15 }, # 'Ns::Type => Ns::BasicType<char>' ],", "Subcommands_GoTo_all_test(): tests = [ # Local::x -> definition/declaration of x", "'line_num': 39, 'column_num': 3 }, 'Foo' ], [ { 'line_num':", "FixIt_Check_cpp11_MultiFirst ], # should put closest fix-it first? [ 54,", "13 } ), 'end' : has_entries( { 'line_num': 16, 'column_num':", "'location': LineColMatcher( 72, 9 ), } ) ) } )", "'response': requests.codes.ok, 'data': has_entries( { 'fixits': contains( has_entries( { 'chunks':", "} ) ) def FixIt_Check_cpp11_MultiSecond( results ): assert_that( results, has_entries(", "completer # from cache. @IsolatedYcmd() def Subcommands_DefinedSubcommands_test( app ): file_path", "'start': has_entries( { 'line_num': 16, 'column_num': 10 } ), 'end'", "{ 'line_num': 46, 'column_num': 13 }, 'const struct Foo *'", ": filepath, 'contents' : contents, 'filetype' : filetype } args", "}, 'int x = 3', requests.codes.ok ], # no hover", "'int' to 'void'\" ), 'chunks': contains( ChunkMatcher( 'void', LineColMatcher( 3,", "RunGetSemanticTest, PathToTestFile( 'GetDoc_Clang_test.cc' ), 'cpp', test, [ subcommand ], test[", "), 'location': has_entries( { 'line_num': 16, 'column_num': 0 } )", "80, 'column_num': 4 }, } subexpression_extract_range = { 'start': {", "IsolatedYcmd, SharedYcmd, PathToTestFile, RunAfterInitialized ) from ycmd.tests.test_utils import ( BuildRequest,", "}, # Local::out_of_line -> declaration of Local::out_of_line { 'req': (", ") ), 'location': has_entries( { 'line_num': 16, 'column_num': 0 }", "test = { 'request': request, 'route': '/run_completer_command', 'expect': { 'response':", "'line_num': 40, 'column_num': 18 }, 'Foo' ], # [ {", "9, 'cpp11', cfile, FixIt_Check_cpp11_SpellCheck ], ] for test in tests:", "to SpellingIsNotMyStrongPoint has_entries( { 'text': contains_string( \"change 'SpellingIsNotMyStringPiont' to \"", "'expect': { 'response': requests.codes.ok, 'data': has_entries( { 'fixits': contains( has_entries(", "has_entries( { 'chunks': contains( has_entries( { 'replacement_text': equal_to( '= default;'", "LineColMatcher( 9, 6 ) ), ChunkMatcher( '\\n\\n', LineColMatcher( 12, 2", "assert_that( results, has_entries( { 'fixits': contains( has_entries( { 'text': contains_string(", "16 } ), 'end' : has_entries( { 'line_num': 54, 'column_num':", "2 ] ) for location in response ] ) }", "'res': ( 'goto.cc', 2, 11 ) }, # Local::out_of_line ->", "requests.codes.ok, 'data': contains( *[ LocationMatcher( PathToTestFile( folder, os.path.normpath( location[ 0", "ChunkMatcher( 'Bar', LineColMatcher( 15, 8 ), LineColMatcher( 15, 11 )", "'line_num': 28, 'column_num': 18 }, 'struct Foo' ], # [", "'column_num': 9 } ), 'end' : has_entries( { 'line_num': 21,", "28, 'column_num': 2 } ), 'end' : has_entries( { 'line_num':", "4 } ), } ), } ), has_entries( { 'replacement_text':", "fix-it at 54,16 has_entries( { 'chunks': contains( has_entries( { 'replacement_text':", "os.path.normpath( location[ 0 ] ) ), location[ 1 ], location[", ") ), 'location': has_entries( { 'line_num': 25, 'column_num': 14 }", ") def FixIt_Check_cpp11_MultiFirst( results ): assert_that( results, has_entries( { 'fixits':", "app, 'cpp' ) response = app.post_json( '/run_completer_command', BuildRequest( **args )", "contains( has_entries( { 'chunks': contains( has_entries( { 'replacement_text': equal_to( 'static_cast<int>('", "( 'goto.cc', 24, 17 ), 'res': [ ( 'goto.cc', 2,", "has_entries( { 'line_num': 48, 'column_num': 4 } ), } ),", "'cpp' ) expected = app.post_json( '/run_completer_command', BuildRequest( **request ) ).json", "app, line, column, lang, file_path, check ): contents = ReadFile(", "equal_to, has_entries, has_entry, matches_regexp ) from pprint import pprint import", "(at your option) any later version. # # ycmd is", "} ) ) } ) ) def FixIt_Check_cpp11_InsMultiLine( results ):", "11 ) ), ChunkMatcher( 'Bar', LineColMatcher( 9, 3 ), LineColMatcher(", "FixIt_Check_AutoExpand_Resolved ], [ macro_expand_range, FixIt_Check_MacroExpand_Resolved ], [ subexpression_extract_range, FixIt_Check_SubexprExtract_Resolved ],", "}, 'int main()' ], [ { 'line_num': 22, 'column_num': 6", "[ { 'line_num': 39, 'column_num': 11 }, 'Foo &' ],", "(Ns::Type) # [ { 'line_num': 25, 'column_num': 15 }, #", "has_entries( { 'replacement_text': equal_to( '= default;' ), 'range': has_entries( {", "24, 16 ), 'res': ( 'goto.cc', 2, 11 ) },", "'FixIt' ], 'line_num' : line, 'column_num' : column, } args.update(", "has_entries( { 'start': has_entries( { 'line_num': 48, 'column_num': 15 }", "), LineColMatcher( 17, 6 ) ), ChunkMatcher( '', LineColMatcher( 17,", "requests.codes.ok ], # no hover [ { 'line_num': 8, 'column_num':", "{ 'line_num': 54, 'column_num': 18 }, matches_regexp( r'int bar\\(int i\\)(?:", "of x { 'req': ( 'goto.cc', 23, 21 ), 'res':", "19, 5 ), 'res': ( 'goto.cc', 21, 5 ) },", "( 'goto.cc', 11, 10 ) }, # GoToDeclaration alternates between", "{ 'line_num': 84, 'column_num': 20 }, } macro_expand_range = {", "{ 'line_num': 51, 'column_num': 13 }, 'Unicøde *' ], #", "', LineColMatcher( 84, 3 ), LineColMatcher( 84, 3 ) ),", "'column_num': 58 } ), } ), } ), ), 'location':", "'completer_target' : 'filetype_default', 'command_arguments': command, 'line_num' : 10, 'column_num' :", "location[ 2 ] ) for location in response ] )", "48, 'column_num': 18 }, 'int' ], # Auto in declaration", "yield RunRangedFixItTest, test[ 0 ], test[ 1 ] @WithRetry @SharedYcmd", "Subcommands_GoToReferences_test(): tests = [ # Function { 'req': ( 'goto.cc',", "), } ), has_entries( { 'replacement_text': equal_to( '~' ), 'range':", "definition/declaration of Local { 'req': ( 'goto.cc', 24, 16 ),", "tests = [ # Basic pod types [ { 'line_num':", "{ 'start': has_entries( { 'line_num': 54, 'column_num': 52 } ),", "def FixIt_Check_objc_NoFixIt( results ): # and finally, a warning with", "{ 'request': request, 'route': '/run_completer_command', 'expect': { 'response': response, 'data':", "contents = ReadFile( PathToTestFile( 'FixIt_Clang_cpp11.cpp' ) ) args = {", "BuildRequest( **args ) ).json print( 'Resolved fixit response = '", "LineColMatcher( 1, 8 ), LineColMatcher( 1, 11 ) ), ChunkMatcher(", "Local::in_line -> definition/declaration of Local::in_line { 'req': ( 'goto.cc', 24,", "def Subcommands_GoToReferences_test(): tests = [ # Function { 'req': (", "# [ { 'line_num': 12, 'column_num': 2 }, 'Foo' ],", "file_path ) language_options = { 'cpp11': { 'filetype' : 'cpp',", "'filepath' : file_path, 'command_arguments': [ 'FixIt' ], 'line_num' : line,", "bar\\(int i\\)(?: __attribute__\\(\\(thiscall\\)\\))?' ) ], ] for subcommand in [", "} ) ) def FixIt_Check_cpp11_InsMultiLine( results ): # Similar to", "FixIt_Check_cpp11_1 but inserts split across lines # assert_that( results, has_entries(", "], 'column_num': test[ 'req' ][ 2 ], } ) response", "contributors # # This file is part of ycmd. #", "'res': ( 'goto.cc', 32, 26 ) }, # Another_Unicøde {", "17, 17 ), LineColMatcher( 17, 17 ) ), ChunkMatcher( '", ") }, { 'req': ( 'goto.cc', 11, 10 ), 'res':", "5 ) }, { 'req': ( 'goto.cc', 19, 5 ),", "{ 'line_num': 83, 'column_num': 3 }, 'end': { 'line_num': 83,", ") def FixIt_Check_cpp11_DelAdd( results ): assert_that( results, has_entries( { 'fixits':", ": 'filetype_default', 'contents' : contents, 'filepath' : file_path, 'command_arguments': [", "your option) any later version. # # ycmd is distributed", ") ) def FixIt_Check_objc_NoFixIt( results ): # and finally, a", ") } else: expect = { 'response': requests.codes.internal_server_error, 'data': ErrorMatcher(", "'line_num': 51, 'column_num': 13 }, 'Unicøde *' ], # Bound", "'line_num': 40, 'column_num': 3 }, 'Foo' ], [ { 'line_num':", "for test in tests: yield ( RunGetSemanticTest, PathToTestFile( 'GetDoc_Clang_test.cc' ),", "app, rng, expected ): contents = ReadFile( PathToTestFile( 'FixIt_Clang_cpp11.cpp' )", "'response': requests.codes.ok, 'data': LocationMatcher( PathToTestFile( folder, os.path.normpath( response[ 0 ]", "equal_to( '' ), 'range': has_entries( { 'start': has_entries( { 'line_num':", "'line_num': 28, 'column_num': 2 } ), } ), } )", "43, 'column_num': 3 }, 'const Foo *' ], [ {", "'text': contains_string( \"change 'int' to 'void'\" ), 'chunks': contains( ChunkMatcher(", "}, 'const int' ], [ { 'line_num': 46, 'column_num': 13", ") diags = RunAfterInitialized( app, test ) results = app.post_json(", "24, 26 ), 'res': ( 'goto.cc', 6, 10 ) },", "'line_num': 45, 'column_num': 19 }, 'const int' ], [ {", "response ) expected( response ) def Subcommands_FixIt_Ranged_test(): expand_auto_range = {", "multiple errors on a single line; both with fixits [", "( 'main.cpp', 2, 14 ), 'res': ( 'system/a.hpp', 1, 1", "should have received a copy of the GNU General Public", "{ 'req': ( 'goto.cc', 27, 8 ), 'res': 'Cannot jump", "BuildRequest( **request ) ).json print( 'actual = ' ) print(", "{ 'line_num': 48, 'column_num': 9 } ), 'end' : has_entries(", "request = { 'completer_target' : 'filetype_default', 'contents' : ReadFile( filename", "], [ { 'line_num': 22, 'column_num': 6 }, 'int main()'", ") while 'message' in diags and 'diagnostics' in diags[ 'message'", "equal_to( '~' ), 'range': has_entries( { 'start': has_entries( { 'line_num':", "filetype, test, command, response = requests.codes.ok ): contents = ReadFile(", "filename, 'command_arguments': [ 'FixIt' ], 'line_num' : 16, 'column_num' :", "9, 6 ) ), ChunkMatcher( '\\n\\n', LineColMatcher( 12, 2 ),", "'line_num': 32, 'column_num': 16 }, 'const Foo *' ], #", "] ) def Subcommands_GetDoc_test(): tests = [ # from local", "has_entries( { 'line_num': 54, 'column_num': 64 } ), 'end' :", "48, 'column_num': 3 } ), 'end' : has_entries( { 'line_num':", "13 }, 'const struct Foo *' ], # [ {", "'line_num': 21, 'column_num': 16 } ) } ) ) }", "9 ) ) ), 'location': LineColMatcher( 60, 1 ), }", "WaitUntilCompleterServerReady( app, 'cpp' ) response = app.post_json( '/run_completer_command', BuildRequest( **args", "'column_num': 15 }, 'Foo' ], [ { 'line_num': 40, 'column_num':", "has_entries( { 'line_num': 48, 'column_num': 17 } ), } ),", "def RunFixItTest( app, line, column, lang, file_path, check ): contents", "expand_auto_range, FixIt_Check_AutoExpand_Resolved ], [ macro_expand_range, FixIt_Check_MacroExpand_Resolved ], [ subexpression_extract_range, FixIt_Check_SubexprExtract_Resolved", "RunGoToTest_all, '', 'GoToReferences', test @SharedYcmd def RunGetSemanticTest( app, filepath, filetype,", "# FixIt attached to a \"child\" diagnostic (i.e. a Note)", "LineColMatcher( 15, 46 ), LineColMatcher( 16, 1 ) ), ChunkMatcher(", "Ns' ], # On Type (Type) # [ { 'line_num':", ") }, # GoToDeclaration alternates between definition and declaration {", "'Foo *' ], [ { 'line_num': 48, 'column_num': 18 },", "'cpp' } request = common_request request.update( { 'line_num' : test[", "15 } ) } ), # second fix-it at 54,52", "*' ], [ { 'line_num': 40, 'column_num': 18 }, 'Foo'", "version. # # ycmd is distributed in the hope that", ") ).json print( 'actual = ' ) print( actual )", "'req' ][ 0 ] ) common_request = { 'completer_target' :", "( 'goto.cc', 2, 11 ) }, # Local::out_of_line -> definition", "'GoToImprecise' ]: yield RunGoToTest_all, 'test-include', cmd, test def Subcommands_GoToReferences_test(): tests", "3 }, 'const Foo &' ], [ { 'line_num': 42,", "# # This file is part of ycmd. # #", "2, 11 ) }, # Local::out_of_line -> declaration of Local::out_of_line", "results ): # Similar to FixIt_Check_cpp11_1 but inserts split across", "'column_num': 11 }, 'Foo *' ], [ { 'line_num': 29,", "): filepath = PathToTestFile( folder, test[ 'req' ][ 0 ]", "], # [ { 'line_num': 29, 'column_num': 11 }, 'Foo", "# [ { 'line_num': 29, 'column_num': 3 }, 'Foo *'", "} ), 'end' : has_entries( { 'line_num': 54, 'column_num': 19", ") }, { 'req': ( 'goto.cc', 19, 5 ), 'res':", "58 } ), 'end' : has_entries( { 'line_num': 54, 'column_num':", "2, 14 ), 'res': ( 'system/a.hpp', 1, 1 ) },", "1 ), 'res': ( 'quote/b.hpp', 1, 1 ) }, #", "'column_num': 19 }, 'end': { 'line_num': 80, 'column_num': 35 },", "ErrorMatcher, WithRetry, WaitUntilCompleterServerReady ) from ycmd.utils import ReadFile # This", "'column_num': 3 } ) } ), ) } ) )", "'line_num': 22, 'column_num': 6 }, 'int main()' ], # Declared", "fix-it at 54,52 has_entries( { 'chunks': contains( has_entries( { 'replacement_text':", "{ 'text': 'Extract subexpression to variable', 'resolve': True, 'command': has_entries(", "'struct Foo &' ], [ { 'line_num': 28, 'column_num': 18", "LineColMatcher( 17, 3 ), LineColMatcher( 17, 6 ) ), ChunkMatcher(", "'goto.cc', 11, 10 ) }, # GoToDeclaration alternates between definition", "( 'goto.cc', 2, 11 ), ( 'goto.cc', 14, 6 ),", "&' ], # [ { 'line_num': 31, 'column_num': 16 },", "), LineColMatcher( 72, 35 ) ) ), 'location': LineColMatcher( 72,", "else: expect = { 'response': requests.codes.internal_server_error, 'data': ErrorMatcher( RuntimeError, test[", "LineColMatcher( 15, 11 ) ), ChunkMatcher( ' ', LineColMatcher( 15,", "] for test in tests: for cmd in [ 'GoToInclude',", "test ): filepath = PathToTestFile( folder, test[ 'req' ][ 0", "'line_num': 48, 'column_num': 4 } ), } ), } ),", "'line_num': 5, 'column_num': 3 } ), 'end' : has_entries( {", "from pprint import pprint import requests import os.path from ycmd.tests.clangd", "Public License for more details. # # You should have", "has_entries( { 'line_num': 35, 'column_num': 7 } ), 'end' :", "[ ( 'goto.cc', 2, 11 ), ( 'goto.cc', 14, 6", "args = test[ 0 ] if response == requests.codes.ok: if", "83, 3 ), LineColMatcher( 83, 17 ) ), ) }", "{ 'line_num': 29, 'column_num': 18 }, 'Foo' ], # [", ": has_entries( { 'line_num': 54, 'column_num': 53 } ), }", "( 'goto.cc', 23, 21 ), 'res': ( 'goto.cc', 4, 9", "), ( 'goto.cc', 25, 22 ) ] }, # Namespace", "} ) } ) ) } ) ) def FixIt_Check_cpp11_Note(", "If not, see <http://www.gnu.org/licenses/>. from __future__ import absolute_import from __future__", "], [ { 'line_num': 47, 'column_num': 12 }, 'Foo' ],", "in [ 'GetType', 'GetTypeImprecise' ]: for test in tests: yield", "RunGetSemanticTest, PathToTestFile( 'GetType_Clang_test.cc' ), 'cpp', test, [ subcommand ] )", "12, 'cuda', cufile, FixIt_Check_cuda ], # multiple errors on a", "'goto.cc', 23, 14 ), ( 'goto.cc', 24, 15 ), (", "rng, 'filetype' : 'cpp' } app.post_json( '/event_notification', CombineRequest( args, {", "# Unicode [ { 'line_num': 51, 'column_num': 13 }, 'Unicøde", ") def FixIt_Check_cpp11_Ins( results ): # First fixit # switch(A())", "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #", "no hover [ { 'line_num': 8, 'column_num': 1 }, ErrorMatcher(", "{ 'start': has_entries( { 'line_num': 16, 'column_num': 10 } ),", "'column_num': 13 } ), } ), } ) ), 'location':", "'goto.cc', 14, 13 ) }, # GoToDeclaration alternates between definition", "{ 'line_num': 54, 'column_num': 51 } ) } ), has_entries(", "'column_num': 20 }, 'int' ], # Unicode [ { 'line_num':", ": has_entries( { 'line_num': 48, 'column_num': 4 } ), }", ") } ) ) } ) ) def FixIt_Check_MacroExpand_Resolved( results", "'const int' ], [ { 'line_num': 36, 'column_num': 13 },", "WaitUntilCompleterServerReady ) from ycmd.utils import ReadFile # This test is", "3 }, 'namespace Ns' ], # On Type (Type) #", "contents, 'filepath' : file_path, 'command_arguments': [ 'FixIt' ], 'line_num' :", "def FixIt_Check_cpp11_Repl( results ): assert_that( results, has_entries( { 'fixits': contains(", "app.post_json( '/run_completer_command', BuildRequest( **args ) ).json args[ 'fixit' ] =", "{ 'line_num': 39, 'column_num': 3 }, 'Foo' ], [ {", "'column_num': 58 } ), 'end' : has_entries( { 'line_num': 54,", "file [ { 'line_num': 5, 'column_num': 10 }, 'docstring', requests.codes.ok", "'replacement_text': equal_to( 'foo' ), 'range': has_entries( { 'start': has_entries( {", "{ 'line_num': 45, 'column_num': 19 }, 'const int' ], [", "], test[ 4 ] @WithRetry @SharedYcmd def RunRangedFixItTest( app, rng,", "}, { 'req': ( 'main.cpp', 6, 11 ), 'res': (", "], # Unicode [ { 'line_num': 51, 'column_num': 13 },", "def FixIt_Check_cpp11_Ins( results ): # First fixit # switch(A()) {", "3 }, 'Foo' ], [ { 'line_num': 40, 'column_num': 11", "expected ): contents = ReadFile( PathToTestFile( 'FixIt_Clang_cpp11.cpp' ) ) args", "( 'goto.cc', 21, 5 ) }, # Unicøde { 'req':", "'', 'GoToReferences', test @SharedYcmd def RunGetSemanticTest( app, filepath, filetype, test,", "in tests: for cmd in [ 'GoToDefinition', 'GoTo', 'GoToImprecise' ]:", "RunGetSemanticTest( app, filepath, filetype, test, command, response = requests.codes.ok ):", "', LineColMatcher( 17, 17 ), LineColMatcher( 17, 17 ) ),", ") ), ChunkMatcher( ' ', LineColMatcher( 15, 46 ), LineColMatcher(", "{ 'req': ( 'goto.cc', 13, 1 ), 'res': 'Cannot jump", "note: change to == has_entries( { 'text': contains_string( '==' ),", "\"child\" diagnostic (i.e. a Note) [ 60, 1, 'cpp11', cfile,", "39, 'column_num': 3 }, 'Foo' ], [ { 'line_num': 39,", "} RunAfterInitialized( app, receive_diags ) diags = RunAfterInitialized( app, test", "folder, os.path.normpath( response[ 0 ] ) ), response[ 1 ],", "12 }, 'Foo' ], [ { 'line_num': 47, 'column_num': 17", "tuple ): expect = { 'response': requests.codes.ok, 'data': LocationMatcher( PathToTestFile(", "'fixits': contains( # First note: put parens around it has_entries(", "has_entries( { 'text': contains_string( \"change 'int' to 'void'\" ), 'chunks':", "'/event_notification', CombineRequest( request, { 'event_name': 'FileReadyToParse', } ), expect_errors =", "split across lines # assert_that( results, has_entries( { 'fixits': contains(", "), ( 'goto.cc', 14, 6 ), ( 'goto.cc', 23, 14", "), ( 'goto.cc', 25, 15 ) ] }, # Expected", ") ) def FixIt_Check_objc( results ): assert_that( results, has_entries( {", "'req': ( 'goto.cc', 24, 16 ), 'res': ( 'goto.cc', 2,", "WithRetry, WaitUntilCompleterServerReady ) from ycmd.utils import ReadFile # This test", "attached to a \"child\" diagnostic (i.e. a Note) [ 60,", "test[ 1 ] ) ) else: expected = has_entry( 'message',", "( 'goto.cc', 34, 9 ), 'res': ( 'goto.cc', 32, 26", "', LineColMatcher( 17, 19 ), LineColMatcher( 17, 19 ) ),", "option) any later version. # # ycmd is distributed in", "'cpp', 'filepath': file_path }, 'expect': { 'response': requests.codes.ok, 'data': {", ") ), ChunkMatcher( ' ', LineColMatcher( 17, 19 ), LineColMatcher(", "has_entries( { 'start': has_entries( { 'line_num': 28, 'column_num': 2 }", "'req' ][ 1 ], 'column_num': test[ 'req' ][ 2 ],", "'cpp', test, [ subcommand ] ) def Subcommands_GetDoc_test(): tests =", "] ) for location in response ] ) } elif", "for test in tests: yield RunGoToTest_all, '', 'GoToDeclaration', test def", "0 ] if response == requests.codes.ok: if not isinstance( test[", "'struct Foo' ], # [ { 'line_num': 29, 'column_num': 3", "'range': has_entries( { 'start': has_entries( { 'line_num': 16, 'column_num': 13", "ChunkMatcher( '', LineColMatcher( 17, 14 ), LineColMatcher( 17, 15 )", "{ 'line_num': 16, 'column_num': 10 } ), } ), }", "( 'goto.cc', 25, 22 ) ] }, # Namespace {", "'goto.cc', 14, 13 ), ( 'goto.cc', 25, 22 ) ]", "refs & pointers [ { 'line_num': 39, 'column_num': 3 },", "Note) [ 60, 1, 'cpp11', cfile, FixIt_Check_cpp11_Note ], # FixIt", "'line_num': 16, 'column_num': 10 } ), 'end' : has_entries( {", "== has_entries( { 'text': contains_string( '==' ), 'chunks': contains( ChunkMatcher(", "'replacement_text': equal_to( '~' ), 'range': has_entries( { 'start': has_entries( {", "], # On \"a\" (Ns::Type) # [ { 'line_num': 25,", "__future__ import unicode_literals from __future__ import print_function from __future__ import", "Local::x -> definition/declaration of x { 'req': ( 'goto.cc', 23,", "], [ { 'line_num': 28, 'column_num': 18 }, 'struct Foo'", "# First get diags. diags = RunAfterInitialized( app, test )", "25, 'column_num': 15 }, # 'Ns::Type => Ns::BasicType<char>' ], #", "& pointers [ { 'line_num': 39, 'column_num': 3 }, 'Foo'", "args, { 'event_name': 'FileReadyToParse', } ), expect_errors = True )", "= True ) WaitUntilCompleterServerReady( app, 'cpp' ) response = app.post_json(", "}, 'const Foo' ], # [ { 'line_num': 34, 'column_num':", "{ 'req': ( 'goto.cc', 25, 27 ), 'res': ( 'goto.cc',", ": has_entries( { 'line_num': 54, 'column_num': 58 } ), }", "contains( ChunkMatcher( '==', LineColMatcher( 60, 8 ), LineColMatcher( 60, 9", "has_entries( { 'line_num': 5, 'column_num': 3 } ), 'end' :", "'column_num': 14 }, 'const Foo *' ], # [ {", "'' ), 'range': has_entries( { 'start': has_entries( { 'line_num': 35,", "hover [ { 'line_num': 8, 'column_num': 1 }, ErrorMatcher( RuntimeError,", "test in tests: yield RunFixItTest, test[ 0 ], test[ 1", "( 'goto.cc', 11, 10 ) }, { 'req': ( 'goto.cc',", "# L # i C # n o # e", "PathToTestFile( 'FixIt_Clang_cpp11.cpp' ) mfile = PathToTestFile( 'objc', 'FixIt_Clang_objc.m' ) cufile", "15 ) ), ChunkMatcher( ' ', LineColMatcher( 17, 17 ),", "{ 'line_num': 54, 'column_num': 16 } ), 'end' : has_entries(", "( 'goto.cc', 16, 6 ), 'res': 'Cannot jump to location'", "'end' : has_entries( { 'line_num': 26, 'column_num': 7 } ),", "from __future__ import division from hamcrest.core.base_matcher import BaseMatcher from hamcrest", "} ), # Unresolved, requires /resolve_fixit request has_entries( { 'text':", "], # [ { 'line_num': 28, 'column_num': 11 }, 'struct", "{ 'line_num': 53, 'column_num': 15 }, matches_regexp( r'int bar\\(int i\\)(?:", "), LineColMatcher( 16, 1 ) ), ChunkMatcher( 'Bar', LineColMatcher( 17,", "fixits [ 54, 15, 'cpp11', cfile, FixIt_Check_cpp11_MultiFirst ], # should", "'start': { 'line_num': 80, 'column_num': 1 }, 'end': { 'line_num':", ") ), 'location': LineColMatcher( 3, 12 ), } ) )", "'res': ( 'goto.cc', 36, 28 ) }, # Expected failures", "17 ), 'res': [ ( 'goto.cc', 2, 11 ), (", ") } ) ) } ) ) def FixIt_Check_AutoExpand_Resolved( results", "# [ { 'line_num': 22, 'column_num': 2 }, 'int main()'", "contains( has_entries( { 'text': \"Expand macro 'DECLARE_INT'\", 'chunks': contains( ChunkMatcher(", "0 ] actual = app.post_json( '/resolve_fixit', BuildRequest( **request ) ).json", "'filetype' : filetype } args = test[ 0 ] if", "}, 'expect': { 'response': requests.codes.ok, 'data': { 'filepath': os.path.abspath( file_path", "'line_num': 5, 'column_num': 3 } ) } ) ) }", "Foo &' ], # [ { 'line_num': 28, 'column_num': 11", "'cpp11': { 'filetype' : 'cpp', }, 'cuda': { 'filetype' :", "}, 'char' ], # Function # [ { 'line_num': 22,", "] @WithRetry @SharedYcmd def Subcommands_FixIt_AlreadyResolved_test( app ): filename = PathToTestFile(", "8 ), LineColMatcher( 1, 11 ) ), ChunkMatcher( 'Bar', LineColMatcher(", "{ 'line_num': 12, 'column_num': 9 }, 'Foo' ], [ {", "'location': has_entries( { 'line_num': 54, 'column_num': 15 } ) }", "13 }, 'Foo *' ], [ { 'line_num': 37, 'column_num':", "= PathToTestFile( folder, test[ 'req' ][ 0 ] ) common_request", "contains( # First note: put parens around it has_entries( {", "), 'range': has_entries( { 'start': has_entries( { 'line_num': 16, 'column_num':", "results, equal_to( { 'fixits': [] } ) ) def FixIt_Check_cpp11_MultiFirst(", "14, 13 ) }, # test -> definition and declaration", "'column_num': 7 }, 'int' ], # [ { 'line_num': 15,", "}, 'Foo &' ], [ { 'line_num': 39, 'column_num': 15", "'line_num': 36, 'column_num': 19 }, 'int' ], # [ {", "request, 'route': '/run_completer_command', 'expect': { 'response': response, 'data': expected }", "[ { 'line_num': 54, 'column_num': 18 }, matches_regexp( r'int bar\\(int", "/resolve_fixit request has_entries( { 'text': 'Extract subexpression to variable', 'resolve':", "FixIt_Check_cuda ], # multiple errors on a single line; both", "45, 'column_num': 19 }, 'const int' ], [ { 'line_num':", "actual ) assert_that( actual, equal_to( expected ) ) @SharedYcmd def", "tests = [ [ expand_auto_range, FixIt_Check_AutoExpand_Resolved ], [ macro_expand_range, FixIt_Check_MacroExpand_Resolved", "'fixit' ] = response[ 'fixits' ][ 0 ] response =", "'location': has_entries( { 'line_num': 54, 'column_num': 51 } ) }", "10 ), ( 'goto.cc', 14, 13 ), ( 'goto.cc', 25,", "results ): # Removal of :: assert_that( results, has_entries( {", "LineColMatcher( 84, 3 ) ), ChunkMatcher( 'dummy', LineColMatcher( 84, 10", "} ), } ), ), 'location': has_entries( { 'line_num': 54,", "On Win32, methods pick up an __attribute__((thiscall)) to annotate their", ") } ) ) } ) ) def FixIt_Check_cpp11_DelAdd( results", "{ 'completer_target' : 'filetype_default', 'contents' : contents, 'filepath' : file_path,", "# no hover [ { 'line_num': 8, 'column_num': 1 },", "'', LineColMatcher( 17, 14 ), LineColMatcher( 17, 15 ) ),", ": has_entries( { 'line_num': 48, 'column_num': 17 } ), }", "declaration { 'req': ( 'goto.cc', 14, 13 ), 'res': (", "'goto.cc', 27, 8 ), 'res': 'Cannot jump to location' },", "}, 'int' ], # [ { 'line_num': 15, 'column_num': 7", "<http://www.gnu.org/licenses/>. from __future__ import absolute_import from __future__ import unicode_literals from", "{ 'filetype' : 'cpp', }, 'cuda': { 'filetype' : 'cuda',", ") args = { 'completer_target' : 'filetype_default', 'contents' : contents,", "command ], 'contents' : ReadFile( filepath ), 'filetype' : 'cpp'", "( 'goto.cc', 23, 14 ), ( 'goto.cc', 24, 15 ),", "{ 'line_num': 80, 'column_num': 4 }, } subexpression_extract_range = {", "1, 1 ) }, { 'req': ( 'main.cpp', 2, 14", "has_entries( { 'text': contains_string( 'parentheses around the assignment' ), 'chunks':", "{ 'line_num': 46, 'column_num': 20 }, 'const int' ], [", "forced spell checking [ 72, 9, 'cpp11', cfile, FixIt_Check_cpp11_SpellCheck ],", "}, 'end': { 'line_num': 83, 'column_num': 13 }, } raw_string_range", ") def Subcommands_FixIt_all_test(): cfile = PathToTestFile( 'FixIt_Clang_cpp11.cpp' ) mfile =", "), 'location': has_entries( { 'line_num': 25, 'column_num': 14 } )", "'goto.cc', 19, 5 ), 'res': ( 'goto.cc', 21, 5 )", "', LineColMatcher( 15, 46 ), LineColMatcher( 16, 1 ) ),", "], 'line_num' : 16, 'column_num' : 1, 'filetype' : 'cpp'", "'column_num': 3 }, 'end': { 'line_num': 83, 'column_num': 13 },", "], [ { 'line_num': 47, 'column_num': 17 }, 'int' ],", "[ { 'line_num': 25, 'column_num': 15 }, # 'Ns::Type =>", "11 }, 'Foo *' ], [ { 'line_num': 29, 'column_num':", "'goto.cc', 24, 26 ), 'res': ( 'goto.cc', 6, 10 )", "14, 6 ), ( 'goto.cc', 23, 14 ), ( 'goto.cc',", "results ): assert_that( results, has_entries( { 'fixits': contains( # Change", ") def Subcommands_GoTo_all_test(): tests = [ # Local::x -> definition/declaration", "'res': ( 'goto.cc', 11, 10 ) }, { 'req': (", "assert_that( results, has_entries( { 'fixits': contains( has_entries( { 'text': 'Convert", "{ 'replacement_text': equal_to( '= default;' ), 'range': has_entries( { 'start':", "'goto.cc', 24, 15 ), ( 'goto.cc', 25, 15 ) ]", "14, 'cpp11', cfile, FixIt_Check_cpp11_InsMultiLine ], [ 35, 7, 'cpp11', cfile,", "'column_num': 3 }, 'const Foo &' ], [ { 'line_num':", "'goto.cc', 32, 54 ) }, { 'req': ( 'goto.cc', 36,", "cfile, FixIt_Check_cpp11_DelAdd ], [ 5, 3, 'objective-c', mfile, FixIt_Check_objc ],", "{ 'start': has_entries( { 'line_num': 48, 'column_num': 15 } ),", "22, 'column_num': 2 }, 'int main()' ], [ { 'line_num':", "expect = { 'response': requests.codes.ok, 'data': LocationMatcher( PathToTestFile( folder, os.path.normpath(", "'ExecuteCommand', 'FixIt', 'Format', 'GetDoc', 'GetDocImprecise', 'GetType', 'GetTypeImprecise', 'GoTo', 'GoToDeclaration', 'GoToDefinition',", "[ { 'line_num': 36, 'column_num': 19 }, 'int' ], #", "# GNU General Public License for more details. # #", "'contents' : contents, 'filetype' : filetype } args = test[", "Subcommands_RefactorRename_test( app ): test = { 'request': { 'filetype': 'cpp',", ") ) ), 'location': LineColMatcher( 60, 1 ), } ),", ": 16, 'column_num' : 1, 'filetype' : 'cpp' } app.post_json(", "absolute_import from __future__ import unicode_literals from __future__ import print_function from", ") ) } ) ) def FixIt_Check_cpp11_Repl( results ): assert_that(", "Local -> definition/declaration of Local { 'req': ( 'goto.cc', 24,", "3 ], test[ 4 ] @WithRetry @SharedYcmd def RunRangedFixItTest( app,", "}, 'Foo' ], # [ { 'line_num': 13, 'column_num': 3", "request, 'route' : '/run_completer_command', 'expect' : expect } ) def", "and finally, a warning with no fixits assert_that( results, equal_to(", "ycmd. If not, see <http://www.gnu.org/licenses/>. from __future__ import absolute_import from", "and canonical type # On Ns:: [ { 'line_num': 25,", "[ 'GoToDefinition', 'GoTo', 'GoToImprecise' ]: yield RunGoToTest_all, '', cmd, test", "expect = { 'response': requests.codes.ok, 'data': contains( *[ LocationMatcher( PathToTestFile(", "'column_num': 1 }, ErrorMatcher( RuntimeError, 'No hover information.' ), requests.codes.server_error", "FixIt_Check_objc( results ): assert_that( results, has_entries( { 'fixits': contains( has_entries(", "= requests.codes.ok ): contents = ReadFile( filepath ) common_args =", "'line_num': 54, 'column_num': 53 } ), } ), } ),", "contents, 'filetype' : filetype } args = test[ 0 ]", "Foundation, either version 3 of the License, or # (at", "] ) common_request = { 'completer_target' : 'filetype_default', 'filepath' :", "bar\\(int i\\)(?: __attribute__\\(\\(thiscall\\)\\))?' ) ], [ { 'line_num': 54, 'column_num':", "6, 'cpp11', cfile, FixIt_Check_cpp11_Repl ], [ 48, 3, 'cpp11', cfile,", "), } ) ), 'location': has_entries( { 'line_num': 40, 'column_num':", "], # [ { 'line_num': 12, 'column_num': 2 }, 'Foo'", ") ) def FixIt_Check_cpp11_MultiFirst( results ): assert_that( results, has_entries( {", "'res': ( 'goto.cc', 19, 5 ) }, { 'req': (", "'goto.cc', 16, 6 ), 'res': 'Cannot jump to location' },", "{ // expected-error{{explicit conversion to}} assert_that( results, has_entries( { 'fixits':", "), ChunkMatcher( '', LineColMatcher( 17, 14 ), LineColMatcher( 17, 15", "'No hover information.' ), requests.codes.server_error ] ] for subcommand in", "51, 'cpp11', cfile, FixIt_Check_cpp11_MultiSecond ], # unicode in line for", "contains( ChunkMatcher( 'const char *', LineColMatcher( 80, 1 ), LineColMatcher(", "1, 1 ) }, { 'req': ( 'main.cpp', 3, 1", "# First note: put parens around it has_entries( { 'text':", "'line_num': 48, 'column_num': 17 } ), } ), } ),", "}, 'const Foo &' ], [ { 'line_num': 42, 'column_num':", ") } ) ) } ) ) def FixIt_Check_cpp11_Repl( results", "], ] for test in tests: yield RunFixItTest, test[ 0", "'main.cpp', 4, 10 ), 'res': ( 'quote/b.hpp', 1, 1 )", "'line_num': 54, 'column_num': 67 } ), } ), } )", "{ 'start': { 'line_num': 80, 'column_num': 19 }, 'end': {", "'line_num': 17, 'column_num': 4, }, 'expect': { 'response': requests.codes.ok, 'data':", ") ], [ { 'line_num': 54, 'column_num': 18 }, matches_regexp(", "-> declaration of Local::out_of_line { 'req': ( 'goto.cc', 25, 27", "General Public License for more details. # # You should", "'line_num': 13, 'column_num': 7 }, 'int' ], # [ {", "} ) } ), # second fix-it at 54,52 has_entries(", "( 'goto.cc', 36, 17 ), 'res': ( 'goto.cc', 32, 54", "@SharedYcmd def Subcommands_FixIt_AlreadyResolved_test( app ): filename = PathToTestFile( 'FixIt_Clang_cpp11.cpp' )", "'command_arguments': [ command ], 'contents' : ReadFile( filepath ), 'filetype'", "errors on a single line; both with fixits [ 54,", "# from header [ { 'line_num': 6, 'column_num': 10 },", "header [ { 'line_num': 6, 'column_num': 10 }, 'docstring', requests.codes.ok", "assert_that( results, has_entries( { 'fixits': contains( has_entries( { 'chunks': contains(", "'command_arguments': [ 'FixIt' ], 'range' : rng, 'filetype' : 'cpp'", "contains, contains_string, equal_to, has_entries, has_entry, matches_regexp ) from pprint import", "even the implied warranty of # MERCHANTABILITY or FITNESS FOR", "&' ], [ { 'line_num': 28, 'column_num': 18 }, 'struct", "3 }, 'Foo *' ], # [ { 'line_num': 29,", "'start': has_entries( { 'line_num': 54, 'column_num': 58 } ), 'end'", "BuildRequest( **args ) ).json pprint( results ) check( results )", "'void'\" ), 'chunks': contains( ChunkMatcher( 'void', LineColMatcher( 3, 12 ),", "'cpp' } app.post_json( '/event_notification', CombineRequest( request, { 'event_name': 'FileReadyToParse', }", "Foo' ], # [ { 'line_num': 45, 'column_num': 19 },", "], # [ { 'line_num': 45, 'column_num': 19 }, 'const", "], [ { 'line_num': 40, 'column_num': 18 }, 'Foo' ],", "0, 'cpp11', cfile, FixIt_Check_cpp11_Ins ], [ 25, 14, 'cpp11', cfile,", "' ) print( expected ) request[ 'fixit' ] = expected[", "requests import os.path from ycmd.tests.clangd import ( IsolatedYcmd, SharedYcmd, PathToTestFile,", "'cpp11', ufile, FixIt_Check_unicode_Ins ], # FixIt attached to a \"child\"", "} ), ), 'location': has_entries( { 'line_num': 54, 'column_num': 15", "'line_num': 40, 'column_num': 6 } ), 'end' : has_entries( {", "'column_num' : column, } args.update( language_options[ lang ] ) test", "} ), 'end' : has_entries( { 'line_num': 54, 'column_num': 53", "'line_num': 43, 'column_num': 16 }, 'const struct Foo *' ],", "*' ], # [ { 'line_num': 46, 'column_num': 20 },", "4 ] @WithRetry @SharedYcmd def RunRangedFixItTest( app, rng, expected ):", "), 'location': LineColMatcher( 3, 12 ), } ) ) }", "'GoToReferences', 'RefactorRename', 'RestartServer' ] ) ) }, 'route': '/defined_subcommands', }", "# and finally, a warning with no fixits assert_that( results,", "], # FixIt attached to a \"child\" diagnostic (i.e. a", "{ 'text': \"Expand auto type\", 'chunks': contains( ChunkMatcher( 'const char", "by # the Free Software Foundation, either version 3 of", "61, 12 ), LineColMatcher( 61, 12 ) ) ), 'location':", "), LineColMatcher( 84, 22 ) ), ) } ) )", "in diags[ 'message' ].lower(): receive_diags = { 'request': args, 'route':", "Foo &' ], # [ { 'line_num': 32, 'column_num': 3", "8 ) ), ChunkMatcher( ')', LineColMatcher( 61, 12 ), LineColMatcher(", "67 } ), } ), } ) ), 'location': has_entries(", "# Local::out_of_line -> definition of Local::out_of_line { 'req': ( 'goto.cc',", ") print( actual ) assert_that( actual, equal_to( expected ) )", "cfile, FixIt_Check_cpp11_SpellCheck ], ] for test in tests: yield RunFixItTest,", "): # Removal of :: assert_that( results, has_entries( { 'fixits':", "= { 'cpp11': { 'filetype' : 'cpp', }, 'cuda': {", "'objcpp', 'filepath': file_path }, 'expect': { 'response': requests.codes.ok, 'data': contains(", "], [ { 'line_num': 43, 'column_num': 16 }, 'const struct", "'column_num': 8 }, # 'Ns::Type => Ns::BasicType<char>' ], # On", "switch(A()) { // expected-error{{explicit conversion to}} assert_that( results, has_entries( {", "'range': has_entries( { 'start': has_entries( { 'line_num': 54, 'column_num': 16", "'location': has_entries( { 'line_num': 40, 'column_num': 6 } ) }", "40, 6, 'cpp11', cfile, FixIt_Check_cpp11_Repl ], [ 48, 3, 'cpp11',", "{ 'line_num': 48, 'column_num': 3 } ) } ), has_entries(", "][ 0 ] actual = app.post_json( '/resolve_fixit', BuildRequest( **request )", "in diags and 'diagnostics' in diags[ 'message' ].lower(): receive_diags =", "( 'main.cpp', 6, 11 ), 'res': ( 'system/c.hpp', 1, 1", "], [ 7, 1, 'objective-c', mfile, FixIt_Check_objc_NoFixIt ], [ 3,", "], [ macro_expand_range, FixIt_Check_MacroExpand_Resolved ], [ subexpression_extract_range, FixIt_Check_SubexprExtract_Resolved ], [", "'a.hpp', 1, 1 ) }, { 'req': ( 'main.cpp', 2,", "}, # 'Ns::Type => Ns::BasicType<char>' ], # [ { 'line_num':", "): assert_that( results, has_entries( { 'fixits': contains( has_entries( { 'chunks':", "'chunks': contains( has_entries( { 'replacement_text': equal_to( 'foo' ), 'range': has_entries(", "app.post_json( '/resolve_fixit', BuildRequest( **request ) ).json print( 'actual = '", "PathToTestFile( folder, os.path.normpath( location[ 0 ] ) ), location[ 1", "file is part of ycmd. # # ycmd is free", "], [ 3, 12, 'cuda', cufile, FixIt_Check_cuda ], # multiple", "36, 28 ) }, # Expected failures { 'req': (", "[ { 'line_num': 40, 'column_num': 11 }, 'Foo *' ],", "around it has_entries( { 'text': contains_string( 'parentheses around the assignment'", "{ 'fixits': contains( has_entries( { 'text': contains_string( \"change 'int' to", "diagnostic (i.e. a Note) [ 60, 1, 'cpp11', cfile, FixIt_Check_cpp11_Note", "'Foo *' ], [ { 'line_num': 37, 'column_num': 20 },", "'filetype' : 'cpp', }, 'cuda': { 'filetype' : 'cuda', },", "This file is part of ycmd. # # ycmd is", "PathToTestFile( 'GoTo_Clang_ZeroBasedLineAndColumn_test.cc' ) RunAfterInitialized( app, { 'request': { 'contents': ReadFile(", "def Subcommands_GoToDeclaration_all_test(): tests = [ # Local::x -> definition/declaration of", "), 'end' : has_entries( { 'line_num': 48, 'column_num': 4 }", "than fetching completer # from cache. @IsolatedYcmd() def Subcommands_DefinedSubcommands_test( app", "failures { 'req': ( 'goto.cc', 13, 1 ), 'res': 'Cannot", "1 ) }, { 'req': ( 'main.cpp', 3, 1 ),", "LineColMatcher( 17, 15 ) ), ChunkMatcher( ' ', LineColMatcher( 17,", "'column_num': 18 }, 'Foo' ], # [ { 'line_num': 31,", "'GoToInclude', 'GoToReferences', 'RefactorRename', 'RestartServer' ] ) ) }, 'route': '/defined_subcommands',", "'command_arguments': [ 'RefactorRename', 'Bar' ], 'line_num': 17, 'column_num': 4, },", "} }, 'route': '/run_completer_command', } ) @SharedYcmd def RunGoToTest_all( app,", ") @SharedYcmd def Subcommands_RefactorRename_test( app ): test = { 'request':", "( 'main.cpp', 4, 10 ), 'res': ( 'quote/b.hpp', 1, 1", "5, 'column_num': 10 }, 'docstring', requests.codes.ok ], # from header", "[ { 'line_num': 32, 'column_num': 16 }, 'const Foo *'", "results ): # and finally, a warning with no fixits", "'filetype_default', 'contents': ReadFile( PathToTestFile( 'basic.cpp' ) ), 'filepath': PathToTestFile( 'basic.cpp'", "), ) } ) ) def FixIt_Check_cpp11_MultiSecond( results ): assert_that(", "25, 27 ), 'res': ( 'goto.cc', 11, 10 ) },", "*' ], # Cursor on usage [ { 'line_num': 45,", "= [ # Basic pod types [ { 'line_num': 24,", "# first fix-it at 54,16 has_entries( { 'chunks': contains( has_entries(", "with fixits [ 54, 15, 'cpp11', cfile, FixIt_Check_cpp11_MultiFirst ], #", "modify # it under the terms of the GNU General", "} ), } ), ), 'location': has_entries( { 'line_num': 48,", "83, 'column_num': 3 }, 'end': { 'line_num': 83, 'column_num': 13", "for cmd in [ 'GoToInclude', 'GoTo', 'GoToImprecise' ]: yield RunGoToTest_all,", "parens around it has_entries( { 'text': contains_string( 'parentheses around the", "def Subcommands_GoTo_ZeroBasedLineAndColumn_test( app ): file_path = PathToTestFile( 'GoTo_Clang_ZeroBasedLineAndColumn_test.cc' ) RunAfterInitialized(", "15, 'column_num': 7 }, 'char' ], # Function # [", "@SharedYcmd def Subcommands_GoTo_ZeroBasedLineAndColumn_test( app ): file_path = PathToTestFile( 'GoTo_Clang_ZeroBasedLineAndColumn_test.cc' )", "jump to location' }, { 'req': ( 'goto.cc', 16, 6", "has_entries( { 'text': \"Expand macro 'DECLARE_INT'\", 'chunks': contains( ChunkMatcher( 'int", "'response': response, 'data': expected } } RunAfterInitialized( app, test )", "and declaration { 'req': ( 'goto.cc', 14, 13 ), 'res':", "'column_num': 16 } ) } ) ) } ) )", "cmd in [ 'GoToInclude', 'GoTo', 'GoToImprecise' ]: yield RunGoToTest_all, 'test-include',", "( 'goto.cc', 25, 27 ), 'res': ( 'goto.cc', 11, 10", "'Bar', LineColMatcher( 17, 3 ), LineColMatcher( 17, 6 ) ),", "macro 'DECLARE_INT'\", 'chunks': contains( ChunkMatcher( 'int i', LineColMatcher( 83, 3", "in the type, which isn't ideal, but # also prohibitively", "'main.cpp', 6, 11 ), 'res': ( 'system/c.hpp', 1, 1 )", "16, 6 ), 'res': 'Cannot jump to location' }, ]", "test in tests: for cmd in [ 'GoToDefinition', 'GoTo', 'GoToImprecise'", "[ { 'line_num': 25, 'column_num': 8 }, # 'Ns::Type =>", ": expect } ) def Subcommands_GoTo_all_test(): tests = [ #", "( 'goto.cc', 32, 54 ) }, { 'req': ( 'goto.cc',", "27 ), 'res': ( 'goto.cc', 14, 13 ) }, #", "60, 8 ), LineColMatcher( 60, 9 ) ) ), 'location':", "6 } ) } ) ) } ) ) def", "'replacement_text': equal_to( 'id' ), 'range': has_entries( { 'start': has_entries( {", "'message', test[ 1 ] ) else: expected = test[ 1", "subexpression_extract_range = { 'start': { 'line_num': 84, 'column_num': 14 },", "58 } ), } ), } ), ), 'location': has_entries(", "'end' : has_entries( { 'line_num': 48, 'column_num': 4 } ),", "'column_num': 3 }, 'Foo' ], [ { 'line_num': 40, 'column_num':", "cufile, FixIt_Check_cuda ], # multiple errors on a single line;", ": PathToTestFile( 'FixIt_Clang_cpp11.cpp' ), 'command_arguments': [ 'FixIt' ], 'range' :", "11 ), ( 'goto.cc', 14, 6 ), ( 'goto.cc', 23,", "test[ 1 ] @WithRetry @SharedYcmd def Subcommands_FixIt_AlreadyResolved_test( app ): filename", "# switch(A()) { // expected-error{{explicit conversion to}} assert_that( results, has_entries(", ") print( expected ) request[ 'fixit' ] = expected[ 'fixits'", "34, 9 ), 'res': ( 'goto.cc', 32, 26 ) },", "16, 'column_num': 13 } ), 'end' : has_entries( { 'line_num':", "in [ 'GoToDefinition', 'GoTo', 'GoToImprecise' ]: yield RunGoToTest_all, '', cmd,", "contains( has_entries( { 'replacement_text': equal_to( '' ), 'range': has_entries( {", "failures { 'req': ( 'main.cpp', 7, 1 ), 'res': 'Cannot", "48, 'column_num': 17 } ), } ), } ), ),", "mfile, FixIt_Check_objc_NoFixIt ], [ 3, 12, 'cuda', cufile, FixIt_Check_cuda ],", "'FixIt_Clang_cpp11.cpp' ) request = { 'completer_target' : 'filetype_default', 'contents' :", "], [ 35, 7, 'cpp11', cfile, FixIt_Check_cpp11_Del ], [ 40,", "], test[ 2 ], test[ 3 ], test[ 4 ]", "18 }, 'struct Foo' ], # [ { 'line_num': 29,", "'filepath': file_path }, 'expect': { 'response': requests.codes.ok, 'data': contains( *sorted(", "= { 'completer_target' : 'filetype_default', 'filepath' : filepath, 'command_arguments': [", "'unicode.cc' ) tests = [ # L # i C", "} ) ) def FixIt_Check_objc_NoFixIt( results ): # and finally,", "'end' : has_entries( { 'line_num': 48, 'column_num': 17 } ),", "cfile, FixIt_Check_cpp11_Note ], # FixIt due to forced spell checking", "] for test in tests: yield RunFixItTest, test[ 0 ],", ") } ) ) def FixIt_Check_SubexprExtract_Resolved( results ): assert_that( results,", "PathToTestFile( 'GetType_Clang_test.cc' ), 'cpp', test, [ subcommand ] ) def", "19 ) ), ) } ) ) } ) },", "has_entries( { 'text': contains_string( \"change 'SpellingIsNotMyStringPiont' to \" \"'SpellingIsNotMyStrongPoint'\" ),", "of Local::out_of_line { 'req': ( 'goto.cc', 25, 27 ), 'res':", "Similar to FixIt_Check_cpp11_1 but inserts split across lines # assert_that(", "5, 'column_num': 3 } ) } ) ) } )", "usage [ { 'line_num': 45, 'column_num': 13 }, 'const struct", "'column_num': 13 }, 'Unicøde *' ], # Bound methods #", "'column_num': 7 } ), } ), } ), has_entries( {", "(i.e. a Note) [ 60, 1, 'cpp11', cfile, FixIt_Check_cpp11_Note ],", "'Foo *' ], [ { 'line_num': 40, 'column_num': 18 },", "17, 6 ) ), ChunkMatcher( '', LineColMatcher( 17, 14 ),", "')' ), 'range': has_entries( { 'start': has_entries( { 'line_num': 16,", "1 ) }, # Expected failures { 'req': ( 'main.cpp',", "'goto.cc', 11, 10 ) }, { 'req': ( 'goto.cc', 11,", "'text': \"Expand auto type\", 'chunks': contains( ChunkMatcher( 'const char *',", "[ 21, 16, 'cpp11', ufile, FixIt_Check_unicode_Ins ], # FixIt attached", "{ 'text': 'Convert to raw string', 'chunks': contains( ChunkMatcher( 'R\"(\\\\\\\\r\\\\asd\\n\\\\v)\"',", "'response': requests.codes.internal_server_error, 'data': ErrorMatcher( RuntimeError, test[ 'res' ] ) }", "'route': '/detailed_diagnostic' } # First get diags. diags = RunAfterInitialized(", "trigger objcpp hooks, rather than fetching completer # from cache.", "'fixit' ] = expected[ 'fixits' ][ 0 ] actual =", "72, 9 ), LineColMatcher( 72, 35 ) ) ), 'location':", "cufile = PathToTestFile( 'cuda', 'fixit_test.cu' ) ufile = PathToTestFile( 'unicode.cc'", "3 } ) } ), ) } ) ) def", "], [ { 'line_num': 40, 'column_num': 3 }, 'Foo' ],", "19 }, 'const int' ], [ { 'line_num': 46, 'column_num':", "1 ) }, { 'req': ( 'main.cpp', 5, 11 ),", "# 'Ns::Type => Ns::BasicType<char>' ], # On \"a\" (Ns::Type) #", "'line_num': 84, 'column_num': 14 }, 'end': { 'line_num': 84, 'column_num':", "contains_string( \"change 'SpellingIsNotMyStringPiont' to \" \"'SpellingIsNotMyStrongPoint'\" ), 'chunks': contains( ChunkMatcher(", "21 }, 'const int' ], # [ { 'line_num': 35,", "FixIt_Check_objc_NoFixIt ], [ 3, 12, 'cuda', cufile, FixIt_Check_cuda ], #", "], # Bound methods # On Win32, methods pick up", "import BaseMatcher from hamcrest import ( assert_that, contains, contains_string, equal_to,", "}, 'route': '/run_completer_command', } ) @SharedYcmd def RunGoToTest_all( app, folder,", "{ 'line_num': 48, 'column_num': 9 } ), } ), }", "'id' ), 'range': has_entries( { 'start': has_entries( { 'line_num': 5,", "51 } ) } ), has_entries( { 'chunks': contains( has_entries(", "+ 3);\\n ', LineColMatcher( 84, 3 ), LineColMatcher( 84, 3", "test ) while 'message' in diags and 'diagnostics' in diags[", "has_entries( { 'chunks': contains( has_entries( { 'replacement_text': equal_to( 'static_cast<int>(' ),", "def Subcommands_RefactorRename_test( app ): test = { 'request': { 'filetype':", "# Cursor on usage [ { 'line_num': 45, 'column_num': 13", ") response = app.post_json( '/run_completer_command', BuildRequest( **args ) ).json args[", "'line_num': 80, 'column_num': 35 }, } tests = [ [", "{ 'line_num': 40, 'column_num': 3 }, 'Foo' ], [ {", "rather than fetching completer # from cache. @IsolatedYcmd() def Subcommands_DefinedSubcommands_test(", "# [ { 'line_num': 34, 'column_num': 21 }, 'const int'", "out. [ { 'line_num': 53, 'column_num': 15 }, matches_regexp( r'int", "], [ { 'line_num': 54, 'column_num': 18 }, matches_regexp( r'int", "84, 'column_num': 20 }, } macro_expand_range = { 'start': {", "}, 'docstring', requests.codes.ok ], # from header [ { 'line_num':", "] for test in tests: yield RunRangedFixItTest, test[ 0 ],", "1 ) ), ChunkMatcher( 'Bar', LineColMatcher( 17, 3 ), LineColMatcher(", ") }, # Local::out_of_line -> definition of Local::out_of_line { 'req':", "fail since b.hpp is included with angled brackets but its", "15 }, # 'Ns::Type => Ns::BasicType<char>' ], # [ {", "26 ), 'res': ( 'goto.cc', 6, 10 ) }, #", "# Basic pod types [ { 'line_num': 24, 'column_num': 3", "6 ), 'res': 'Cannot jump to location' }, ] for", ") ) ), 'location': LineColMatcher( 3, 12 ), } )", ") }, # Another_Unicøde { 'req': ( 'goto.cc', 36, 17", ") } ) ) def FixIt_Check_AutoExpand_Resolved( results ): assert_that( results,", "in tests: yield RunGoToTest_all, '', 'GoToDeclaration', test def Subcommands_GoToInclude_test(): tests", "'column_num': 13 }, # 'Ns::Type => Ns::BasicType<char>' ], # Cursor", "}, ] for test in tests: for cmd in [", "8 }, 'Foo' ], [ { 'line_num': 12, 'column_num': 9", "], } ) response = test[ 'res' ] if isinstance(", "13, 'column_num': 7 }, 'int' ], # [ { 'line_num':", "( 'goto.cc', 19, 5 ) }, { 'req': ( 'goto.cc',", "# [ { 'line_num': 25, 'column_num': 15 }, # 'Ns::Type", "40, 'column_num': 6 } ), 'end' : has_entries( { 'line_num':", "'goto.cc', 21, 5 ), 'res': ( 'goto.cc', 19, 5 )", "), 'range': has_entries( { 'start': has_entries( { 'line_num': 21, 'column_num':", ": 'cpp' } request = common_request request.update( { 'line_num' :", "} ) } ), ) } ) ) def FixIt_Check_cpp11_MultiSecond(", "RunFixItTest( app, line, column, lang, file_path, check ): contents =", "), has_entries( { 'chunks': contains( has_entries( { 'replacement_text': equal_to( '=", "RunAfterInitialized( app, test ) while 'message' in diags and 'diagnostics'", "RunRangedFixItTest, test[ 0 ], test[ 1 ] @WithRetry @SharedYcmd def", "), ) } ) ) } ) ) def FixIt_Check_AutoExpand_Resolved(", "'column_num': 2 }, 'int main()' ], [ { 'line_num': 22,", "&' ], # [ { 'line_num': 32, 'column_num': 3 },", ": has_entries( { 'line_num': 16, 'column_num': 10 } ), }", "'line_num': 29, 'column_num': 18 }, 'Foo' ], # [ {", ") ) } ) ) def FixIt_Check_cpp11_SpellCheck( results ): assert_that(", "'res': 'Cannot jump to location' }, { 'req': ( 'main.cpp',", "brackets but its # folder is added with -iquote. {", "2 }, 'Foo' ], [ { 'line_num': 12, 'column_num': 8", "'column_num': 20 }, 'const int' ], [ { 'line_num': 47,", "1, 'cpp11', cfile, FixIt_Check_cpp11_Note ], # FixIt due to forced", "'end' : has_entries( { 'line_num': 54, 'column_num': 58 } ),", "import ( IsolatedYcmd, SharedYcmd, PathToTestFile, RunAfterInitialized ) from ycmd.tests.test_utils import", "test[ 0 ], test[ 1 ] @WithRetry @SharedYcmd def Subcommands_FixIt_AlreadyResolved_test(", "'start': has_entries( { 'line_num': 16, 'column_num': 13 } ), 'end'", "LineColMatcher( 83, 17 ) ), ) } ) ) }", ") } ) ) def FixIt_Check_cpp11_Note( results ): assert_that( results,", ") ), ChunkMatcher( 'Bar', LineColMatcher( 15, 8 ), LineColMatcher( 15,", "LineColMatcher( 83, 3 ), LineColMatcher( 83, 17 ) ), )", "39, 'column_num': 15 }, 'Foo' ], [ { 'line_num': 40,", "Foo *' ], # [ { 'line_num': 46, 'column_num': 20", ") }, { 'req': ( 'goto.cc', 38, 3 ), 'res':", "it will be useful, # but WITHOUT ANY WARRANTY; without", "'namespace Ns' ], # On Type (Type) # [ {", "test in tests: yield ( RunGetSemanticTest, PathToTestFile( 'GetType_Clang_test.cc' ), 'cpp',", "{ 'event_name': 'FileReadyToParse', } ), expect_errors = True ) WaitUntilCompleterServerReady(", "&' ], # [ { 'line_num': 28, 'column_num': 11 },", "failure { 'req': ( 'goto.cc', 27, 8 ), 'res': 'Cannot", "'Unicøde *' ], # Bound methods # On Win32, methods", "app.post_json( '/event_notification', CombineRequest( args, { 'event_name': 'FileReadyToParse', } ), expect_errors", "'req': ( 'goto.cc', 16, 6 ), 'res': 'Cannot jump to", "LineColMatcher( 61, 12 ) ) ), 'location': LineColMatcher( 60, 1", "# Unresolved, requires /resolve_fixit request has_entries( { 'text': 'Extract subexpression", "22 }, 'const int' ], [ { 'line_num': 36, 'column_num':", "# it under the terms of the GNU General Public", "expect } ) def Subcommands_GoTo_all_test(): tests = [ # Local::x", "[ 'GoToInclude', 'GoTo', 'GoToImprecise' ]: yield RunGoToTest_all, 'test-include', cmd, test", "up an __attribute__((thiscall)) to annotate their # calling convention. This", "][ 0 ] response = app.post_json( '/resolve_fixit', BuildRequest( **args )", "'const int' ], [ { 'line_num': 47, 'column_num': 12 },", "'const Foo *' ], # Auto in usage # [", "}, 'Foo' ], # [ { 'line_num': 42, 'column_num': 3", "'chunks': contains( has_entries( { 'replacement_text': equal_to( '' ), 'range': has_entries(", "6 ) ), ChunkMatcher( '\\n\\n', LineColMatcher( 12, 2 ), LineColMatcher(", "), 'end' : has_entries( { 'line_num': 21, 'column_num': 11 }", "hope that it will be useful, # but WITHOUT ANY", "'/run_completer_command', } ) @SharedYcmd def RunGoToTest_all( app, folder, command, test", "( 'goto.cc', 14, 21 ), 'res': [ ( 'goto.cc', 11,", "15 }, matches_regexp( r'int bar\\(int i\\)(?: __attribute__\\(\\(thiscall\\)\\))?' ) ], [", "'column_num': 3 } ), 'end' : has_entries( { 'line_num': 5,", "6 ) ), ) } ) ) } ) )", "# [ { 'line_num': 32, 'column_num': 16 }, 'const Foo", "os.path.normpath( response[ 0 ] ) ), response[ 1 ], response[", "'static_cast<int>(' ), 'range': has_entries( { 'start': has_entries( { 'line_num': 26,", "), 'res': ( 'goto.cc', 32, 54 ) }, { 'req':", "), 'line_num': 2, 'column_num': 8 } }, 'route': '/run_completer_command', }", "= PathToTestFile( 'objc', 'FixIt_Clang_objc.m' ) cufile = PathToTestFile( 'cuda', 'fixit_test.cu'", "inserts split across lines # assert_that( results, has_entries( { 'fixits':", "'req': ( 'goto.cc', 27, 8 ), 'res': 'Cannot jump to", "] for subcommand in [ 'GetType', 'GetTypeImprecise' ]: for test", "'line_num': 32, 'column_num': 3 }, 'const Foo *' ], #", "}, 'const Foo *' ], # Auto in usage #", "in tests: yield ( RunGetSemanticTest, PathToTestFile( 'GetDoc_Clang_test.cc' ), 'cpp', test,", "59, 8 ) ), ChunkMatcher( ')', LineColMatcher( 61, 12 ),", "35 ) ) ), 'location': LineColMatcher( 72, 9 ), }", "{ 'text': \"Expand macro 'DECLARE_INT'\", 'chunks': contains( ChunkMatcher( 'int i',", ") ) } ) ) def FixIt_Check_RawStringReplace_Resolved( results ): assert_that(", ": 'filetype_default', 'contents' : contents, 'filepath' : PathToTestFile( 'FixIt_Clang_cpp11.cpp' ),", "), 'range': has_entries( { 'start': has_entries( { 'line_num': 48, 'column_num':", "Foo &' ], # [ { 'line_num': 43, 'column_num': 3", "'line_num' : 16, 'column_num' : 1, 'filetype' : 'cpp' }", "( 'a.hpp', 1, 1 ) }, { 'req': ( 'main.cpp',", "'line_num': 25, 'column_num': 3 }, 'namespace Ns' ], # On", "response == requests.codes.ok: if not isinstance( test[ 1 ], BaseMatcher", "matches_regexp( r'int bar\\(int i\\)(?: __attribute__\\(\\(thiscall\\)\\))?' ) ], [ { 'line_num':", "RunAfterInitialized( app, test ) results = app.post_json( '/run_completer_command', BuildRequest( **args", "), 'chunks': contains( ChunkMatcher( '==', LineColMatcher( 60, 8 ), LineColMatcher(", "CombineRequest( args, { 'event_name': 'FileReadyToParse', } ), expect_errors = True", "Declared and canonical type # On Ns:: [ { 'line_num':", "38, 3 ), 'res': ( 'goto.cc', 36, 28 ) },", "has_entries( { 'start': has_entries( { 'line_num': 5, 'column_num': 3 }", "10 ), 'res': ( 'quote/b.hpp', 1, 1 ) }, {", "# FIXME: should fail since b.hpp is included with angled", "48, 3, 'cpp11', cfile, FixIt_Check_cpp11_DelAdd ], [ 5, 3, 'objective-c',", "has_entries( { 'line_num': 25, 'column_num': 14 } ) } )", "72, 9 ), } ) ) } ) ) def", "jump to location' }, ] for test in tests: yield", "11 ), 'res': ( 'system/c.hpp', 1, 1 ) }, {", "(Type) # [ { 'line_num': 25, 'column_num': 8 }, #", "}, 'Foo' ], [ { 'line_num': 47, 'column_num': 17 },", "), expect_errors = True ) WaitUntilCompleterServerReady( app, 'cpp' ) expected", "test[ 'res' ] if isinstance( response, list ): expect =", "'req': ( 'main.cpp', 1, 6 ), 'res': ( 'a.hpp', 1,", "), 'res': ( 'system/c.hpp', 1, 1 ) }, { 'req':", "), 'end' : has_entries( { 'line_num': 48, 'column_num': 17 }", "contents = ReadFile( file_path ) language_options = { 'cpp11': {", "[ 5, 3, 'objective-c', mfile, FixIt_Check_objc ], [ 7, 1,", "18 }, 'int' ], # Auto in declaration # [", "'goto.cc', 25, 27 ), 'res': ( 'goto.cc', 14, 13 )", "location' }, ] for test in tests: yield RunGoToTest_all, '',", "3, 'cpp11', cfile, FixIt_Check_cpp11_DelAdd ], [ 5, 3, 'objective-c', mfile,", "21, 5 ), 'res': ( 'goto.cc', 19, 5 ) },", ") expected( response ) def Subcommands_FixIt_Ranged_test(): expand_auto_range = { 'start':", "has_entries( { 'line_num': 54, 'column_num': 19 } ), } ),", "{ 'line_num': 45, 'column_num': 13 }, 'const struct Foo' ],", "PURPOSE. See the # GNU General Public License for more", "{ 'line_num': 36, 'column_num': 19 }, 'int' ], # [", "# First fixit # switch(A()) { // expected-error{{explicit conversion to}}", "2 } ), } ), } ) ), 'location': has_entries(", "17 ), LineColMatcher( 17, 17 ) ), ChunkMatcher( ' ',", "48, 'column_num': 4 } ), } ), } ), has_entries(", "'end' : has_entries( { 'line_num': 48, 'column_num': 9 } ),", ": has_entries( { 'line_num': 16, 'column_num': 13 } ), }", "'replacement_text': equal_to( ')' ), 'range': has_entries( { 'start': has_entries( {", ") test = { 'request': args, 'route': '/detailed_diagnostic' } #", "'FixIt_Clang_objc.m' ) cufile = PathToTestFile( 'cuda', 'fixit_test.cu' ) ufile =", "contains( has_entries( { 'replacement_text': equal_to( '=' ), 'range': has_entries( {", "response = test[ 'res' ] if isinstance( response, list ):", "'GoTo', 'GoToImprecise' ]: yield RunGoToTest_all, '', cmd, test def Subcommands_GoToDeclaration_all_test():", "3);\\n ', LineColMatcher( 84, 3 ), LineColMatcher( 84, 3 )", "variable', 'resolve': True, 'command': has_entries( { 'command': 'clangd.applyTweak' } )", "'FixIt_Clang_cpp11.cpp' ) ) args = { 'completer_target' : 'filetype_default', 'contents'", "cfile, FixIt_Check_cpp11_InsMultiLine ], [ 35, 7, 'cpp11', cfile, FixIt_Check_cpp11_Del ],", "'GetTypeImprecise' ]: for test in tests: yield ( RunGetSemanticTest, PathToTestFile(", "'column_num': 35 }, } tests = [ [ expand_auto_range, FixIt_Check_AutoExpand_Resolved", "= PathToTestFile( 'GoTo_Clang_ZeroBasedLineAndColumn_test.cc' ) RunAfterInitialized( app, { 'request': { 'completer_target':", "], # Function # [ { 'line_num': 22, 'column_num': 2", "{ 'start': { 'line_num': 84, 'column_num': 14 }, 'end': {", "redistribute it and/or modify # it under the terms of", "app, folder, command, test ): filepath = PathToTestFile( folder, test[", "25, 'column_num': 8 }, # 'Ns::Type => Ns::BasicType<char>' ], #", "but # also prohibitively complex to try and strip out.", "ChunkMatcher( 'dummy', LineColMatcher( 84, 10 ), LineColMatcher( 84, 22 )", "} ) } ) ) } ) ) def FixIt_Check_objc_NoFixIt(", ") ) def Subcommands_FixIt_all_test(): cfile = PathToTestFile( 'FixIt_Clang_cpp11.cpp' ) mfile", "**request ) ).json print( 'expected = ' ) print( expected", "'req': ( 'goto.cc', 36, 17 ), 'res': ( 'goto.cc', 32,", "in tests: for cmd in [ 'GoToInclude', 'GoTo', 'GoToImprecise' ]:", "12, 'column_num': 9 }, 'Foo' ], [ { 'line_num': 12,", "to FixIt_Check_cpp11_1 but inserts split across lines # assert_that( results,", "'filetype_default', 'contents' : ReadFile( filename ), 'filepath' : filename, 'command_arguments':", "{ 'line_num': 54, 'column_num': 15 } ) } ), #", "annotate their # calling convention. This shows up in the", "{ 'filetype': 'cpp', 'completer_target': 'filetype_default', 'contents': ReadFile( PathToTestFile( 'basic.cpp' )", "ChunkMatcher( 'auto dummy = foo(i + 3);\\n ', LineColMatcher( 84,", "( 'goto.cc', 38, 3 ), 'res': ( 'goto.cc', 36, 28", "'/detailed_diagnostic' } # First get diags. diags = RunAfterInitialized( app,", "later version. # # ycmd is distributed in the hope", "'line_num': 42, 'column_num': 16 }, 'const struct Foo &' ],", "@SharedYcmd def RunRangedFixItTest( app, rng, expected ): contents = ReadFile(", "no docstring [ { 'line_num': 7, 'column_num': 7 }, 'int", "'res': [ ( 'goto.cc', 11, 10 ), ( 'goto.cc', 14,", "] ) test = { 'request': args, 'route': '/detailed_diagnostic' }", "), 'range': has_entries( { 'start': has_entries( { 'line_num': 5, 'column_num':", ") ), location[ 1 ], location[ 2 ] ) for", "BaseMatcher ): expected = has_entry( 'message', contains_string( test[ 1 ]", "21, 5 ) }, # Unicøde { 'req': ( 'goto.cc',", "}, matches_regexp( r'int bar\\(int i\\)(?: __attribute__\\(\\(thiscall\\)\\))?' ) ], [ {", "has_entries( { 'replacement_text': equal_to( ')' ), 'range': has_entries( { 'start':", "LineColMatcher( 72, 35 ) ) ), 'location': LineColMatcher( 72, 9", "ReadFile( file_path ), 'completer_target': 'filetype_default', 'command_arguments': [ 'GoToDefinition' ], 'line_num':", "pprint( results ) check( results ) def FixIt_Check_cpp11_Ins( results ):", "{ 'line_num': 26, 'column_num': 7 } ), } ), }", "'replacement_text': equal_to( '' ), 'range': has_entries( { 'start': has_entries( {", "), # second fix-it at 54,52 has_entries( { 'chunks': contains(", "51, 'column_num': 13 }, 'Unicøde *' ], # Bound methods", "PathToTestFile( 'FixIt_Clang_cpp11.cpp' ), 'command_arguments': [ 'FixIt' ], 'range' : rng,", "'column_num': 20 }, } macro_expand_range = { 'start': { 'line_num':", "}, 'Foo' ], [ { 'line_num': 12, 'column_num': 10 },", "# On Type (Type) # [ { 'line_num': 25, 'column_num':", "ErrorMatcher( RuntimeError, 'No hover information.' ), requests.codes.server_error ] ] for", "'' ), 'range': has_entries( { 'start': has_entries( { 'line_num': 48,", "# [ { 'line_num': 35, 'column_num': 14 }, 'const Foo", "LineColMatcher( 17, 17 ) ), ChunkMatcher( ' ', LineColMatcher( 17,", "the hope that it will be useful, # but WITHOUT", "'line_num': 48, 'column_num': 9 } ), } ), } ),", "contains( ChunkMatcher( '(', LineColMatcher( 59, 8 ), LineColMatcher( 59, 8", "12, 'column_num': 8 }, 'Foo' ], [ { 'line_num': 12,", "On Type (Type) # [ { 'line_num': 25, 'column_num': 8", "{ 'line_num': 54, 'column_num': 52 } ), 'end' : has_entries(", "def Subcommands_GoToInclude_test(): tests = [ { 'req': ( 'main.cpp', 1,", "matches_regexp ) from pprint import pprint import requests import os.path", "location[ 0 ] ) ), location[ 1 ], location[ 2", "Expected failures { 'req': ( 'goto.cc', 13, 1 ), 'res':", "14 }, 'const Foo' ], # [ { 'line_num': 34,", "'Foo' ], # [ { 'line_num': 13, 'column_num': 3 },", "}, } subexpression_extract_range = { 'start': { 'line_num': 84, 'column_num':", "{ 'line_num': 21, 'column_num': 9 } ), 'end' : has_entries(", "without even the implied warranty of # MERCHANTABILITY or FITNESS", "13 }, 'Foo' ], [ { 'line_num': 36, 'column_num': 19", "16 } ) } ) ) } ) ) def", "80, 19 ), LineColMatcher( 80, 36 ) ), ) }", "PathToTestFile( 'GoTo_Clang_ZeroBasedLineAndColumn_test.cc' ) RunAfterInitialized( app, { 'request': { 'completer_target': 'filetype_default',", "# Declared and canonical type # On Ns:: [ {", "54, 'column_num': 64 } ), 'end' : has_entries( { 'line_num':", "common_args request.update( args ) test = { 'request': request, 'route':", "request = common_request request.update( { 'line_num' : test[ 'req' ][", "PathToTestFile( 'FixIt_Clang_cpp11.cpp' ) request = { 'completer_target' : 'filetype_default', 'contents'", "( 'goto.cc', 36, 28 ) }, # Expected failures {", "# multiple errors on a single line; both with fixits", "response = requests.codes.ok ): contents = ReadFile( filepath ) common_args", "35, 'column_num': 9 } ), } ), } ) ),", "Basic pod types [ { 'line_num': 24, 'column_num': 3 },", "# On Win32, methods pick up an __attribute__((thiscall)) to annotate", "'/run_completer_command', BuildRequest( **args ) ).json args[ 'fixit' ] = response[", "5 ), 'res': ( 'goto.cc', 21, 5 ) }, #", "27 ), 'res': ( 'goto.cc', 11, 10 ) }, #", "response[ 1 ], response[ 2 ] ) } else: expect", "contains( has_entries( { 'chunks': contains( ChunkMatcher( 'Bar', LineColMatcher( 1, 8", "} ), 'end' : has_entries( { 'line_num': 48, 'column_num': 4", "'main.cpp', 3, 1 ), 'res': ( 'quote/b.hpp', 1, 1 )", "{ 'req': ( 'main.cpp', 6, 11 ), 'res': ( 'system/c.hpp',", ") } ) }, 'route': '/run_completer_command' } RunAfterInitialized( app, test", "'Foo *' ], # [ { 'line_num': 29, 'column_num': 11", "8 ), 'res': 'Cannot jump to location' }, ] for", "( 'goto.cc', 4, 9 ) }, # Local::in_line -> definition/declaration", "On Ns:: [ { 'line_num': 25, 'column_num': 3 }, 'namespace", "RuntimeError, 'No hover information.' ), requests.codes.server_error ] ] for subcommand", "] ) else: expected = test[ 1 ] request =", "'fixits': contains( has_entries( { 'chunks': contains( ChunkMatcher( 'Bar', LineColMatcher( 1,", "16 }, 'const struct Foo &' ], # [ {", "} ), ), 'location': has_entries( { 'line_num': 48, 'column_num': 3", "{ 'line_num': 35, 'column_num': 7 } ), 'end' : has_entries(", "] ) } else: expect = { 'response': requests.codes.internal_server_error, 'data':", "'req': ( 'goto.cc', 19, 5 ), 'res': ( 'goto.cc', 21,", "16, 'column_num': 13 } ), } ), } ) ),", "0 ] ) ), response[ 1 ], response[ 2 ]", "C # n o # e l Lang File, Checker", "distributed in the hope that it will be useful, #", "has_entries( { 'line_num': 21, 'column_num': 9 } ), 'end' :", "if not isinstance( test[ 1 ], BaseMatcher ): expected =", "( 'goto.cc', 2, 11 ) }, # Local::out_of_line -> declaration", "License, or # (at your option) any later version. #", "22 ) ), ) } ) ) } ) )", "'goto.cc', 4, 9 ) }, # Local::in_line -> definition/declaration of", ") RunAfterInitialized( app, { 'request': { 'contents': ReadFile( file_path ),", "'filetype': 'cpp', 'completer_target': 'filetype_default', 'contents': ReadFile( PathToTestFile( 'basic.cpp' ) ),", "'R\"(\\\\\\\\r\\\\asd\\n\\\\v)\"', LineColMatcher( 80, 19 ), LineColMatcher( 80, 36 ) ),", "] }, # Namespace { 'req': ( 'goto.cc', 24, 17", "Subcommands_GoTo_ZeroBasedLineAndColumn_test( app ): file_path = PathToTestFile( 'GoTo_Clang_ZeroBasedLineAndColumn_test.cc' ) RunAfterInitialized( app,", "{ 'line_num': 54, 'column_num': 51 } ) } ), #", "You should have received a copy of the GNU General", "[ 'FixIt' ], 'line_num' : 16, 'column_num' : 1, 'filetype'", ": 'objc', }, } args = { 'completer_target' : 'filetype_default',", "'= default;' ), 'range': has_entries( { 'start': has_entries( { 'line_num':", "], # no docstring [ { 'line_num': 7, 'column_num': 7", "request[ 'fixit' ] = expected[ 'fixits' ][ 0 ] actual", "[ { 'line_num': 42, 'column_num': 16 }, 'const struct Foo", "line, column, lang, file_path, check ): contents = ReadFile( file_path", "'column_num': 18 }, 'struct Foo' ], # [ { 'line_num':", "in tests: yield RunRangedFixItTest, test[ 0 ], test[ 1 ]", "'const struct Foo' ], # [ { 'line_num': 45, 'column_num':", "cmd, test def Subcommands_GoToDeclaration_all_test(): tests = [ # Local::x ->", "print( response ) expected( response ) def Subcommands_FixIt_Ranged_test(): expand_auto_range =", "} ), } ), has_entries( { 'replacement_text': equal_to( '~' ),", "i\\)(?: __attribute__\\(\\(thiscall\\)\\))?' ) ], [ { 'line_num': 54, 'column_num': 18", "6, 'column_num': 10 }, 'docstring', requests.codes.ok ], # no docstring", "is included with angled brackets but its # folder is", "you can redistribute it and/or modify # it under the", "'line_num': 8, 'column_num': 1 }, ErrorMatcher( RuntimeError, 'No hover information.'", "24, 17 ), 'res': [ ( 'goto.cc', 2, 11 ),", "{ 'contents': ReadFile( file_path ), 'completer_target': 'filetype_default', 'command_arguments': [ 'GoToDefinition'", "'req': ( 'goto.cc', 11, 10 ), 'res': ( 'goto.cc', 14,", "has_entries( { 'replacement_text': equal_to( 'id' ), 'range': has_entries( { 'start':", "'cuda', cufile, FixIt_Check_cuda ], # multiple errors on a single", "Foo *' ], [ { 'line_num': 43, 'column_num': 16 },", "} ) response = test[ 'res' ] if isinstance( response,", "'GoToDefinition' ], 'line_num': 10, 'column_num': 3, 'filetype': 'cpp', 'filepath': file_path", "11 ) }, # Local::out_of_line -> declaration of Local::out_of_line {", "} ), } ), } ) ), 'location': has_entries( {", "9 } ), } ), } ), ), 'location': has_entries(", "), response[ 1 ], response[ 2 ] ) } else:", "'line_num': 12, 'column_num': 8 }, 'Foo' ], [ { 'line_num':", "}, 'Foo *' ], [ { 'line_num': 48, 'column_num': 18", "tests = [ # Function { 'req': ( 'goto.cc', 14,", "__future__ import division from hamcrest.core.base_matcher import BaseMatcher from hamcrest import", ") test = { 'request': request, 'route': '/run_completer_command', 'expect': {", "{ 'replacement_text': equal_to( ')' ), 'range': has_entries( { 'start': has_entries(", "'const struct Foo *' ], # Cursor on usage [", "'location': has_entries( { 'line_num': 35, 'column_num': 7 } ) }", "'FixIt' ], 'line_num' : 16, 'column_num' : 1, 'filetype' :", "'column_num': 7 } ) } ) ) } ) )", ") def Subcommands_GetType_test(): tests = [ # Basic pod types", "17, 'column_num': 4, }, 'expect': { 'response': requests.codes.ok, 'data': has_entries(", "def Subcommands_FixIt_Ranged_test(): expand_auto_range = { 'start': { 'line_num': 80, 'column_num':", "RunGoToTest_all, '', 'GoToDeclaration', test def Subcommands_GoToInclude_test(): tests = [ {", "has_entries( { 'line_num': 35, 'column_num': 9 } ), } ),", "LineColMatcher( 17, 14 ), LineColMatcher( 17, 15 ) ), ChunkMatcher(", "} ), 'end' : has_entries( { 'line_num': 48, 'column_num': 9", "{ 'line_num': 47, 'column_num': 17 }, 'int' ], [ {", "cmd, test def Subcommands_GoToReferences_test(): tests = [ # Function {", "'filepath': file_path }, 'expect': { 'response': requests.codes.ok, 'data': { 'filepath':", "is isolated to trigger objcpp hooks, rather than fetching completer", "see <http://www.gnu.org/licenses/>. from __future__ import absolute_import from __future__ import unicode_literals", "} ) } ) ) } ) ) def FixIt_Check_cpp11_DelAdd(", ": column, } args.update( language_options[ lang ] ) test =", "contains( has_entries( { 'replacement_text': equal_to( 'foo' ), 'range': has_entries( {", "'column_num': 64 } ), 'end' : has_entries( { 'line_num': 54,", "15 } ) } ), has_entries( { 'chunks': contains( has_entries(", "has_entries( { 'replacement_text': equal_to( 'foo' ), 'range': has_entries( { 'start':", "'const Foo &' ], [ { 'line_num': 42, 'column_num': 16", "'location': has_entries( { 'line_num': 21, 'column_num': 16 } ) }", "[ { 'line_num': 28, 'column_num': 3 }, 'struct Foo &'", "'req': ( 'goto.cc', 13, 1 ), 'res': 'Cannot jump to", ") def FixIt_Check_AutoExpand_Resolved( results ): assert_that( results, has_entries( { 'fixits':", "import pprint import requests import os.path from ycmd.tests.clangd import (", ") ) } ) ) def FixIt_Check_SubexprExtract_Resolved( results ): assert_that(", "{ 'line_num': 29, 'column_num': 3 }, 'Foo *' ], #", ": 'cpp' } app.post_json( '/event_notification', CombineRequest( args, { 'event_name': 'FileReadyToParse',", "), } ) ), 'location': has_entries( { 'line_num': 21, 'column_num':", ") } ) ) def FixIt_Check_unicode_Ins( results ): assert_that( results,", "FixIt_Check_cpp11_InsMultiLine ], [ 35, 7, 'cpp11', cfile, FixIt_Check_cpp11_Del ], [", "}, 'expect': { 'response': requests.codes.ok, 'data': has_entries( { 'fixits': contains(", ": 'filetype_default', 'command_arguments': command, 'line_num' : 10, 'column_num' : 3,", "ErrorMatcher( RuntimeError, test[ 'res' ] ) } RunAfterInitialized( app, {", "'request': args, 'route': '/detailed_diagnostic' } # First get diags. diags", "'goto.cc', 19, 5 ) }, { 'req': ( 'goto.cc', 19,", "10, 'column_num' : 3, 'filepath' : filepath, 'contents' : contents,", "[ { 'line_num': 13, 'column_num': 3 }, 'int' ], [", "FixIt_Check_objc_NoFixIt( results ): # and finally, a warning with no", "} ), } ) ), 'location': has_entries( { 'line_num': 16,", "], 'line_num': 10, 'column_num': 3, 'filetype': 'cpp', 'filepath': file_path },", ") } ), # second fix-it at 54,52 has_entries( {", "32, 54 ) }, { 'req': ( 'goto.cc', 38, 3", "[ { 'line_num': 32, 'column_num': 3 }, 'const Foo *'", "} ) } ) ) } ) ) def FixIt_Check_cpp11_Del(", "{ 'line_num' : test[ 'req' ][ 1 ], 'column_num': test[", ") ), response[ 1 ], response[ 2 ] ) }", "local file [ { 'line_num': 5, 'column_num': 10 }, 'docstring',", "'column_num': 9 } ), } ), } ), ), 'location':", "request.update( args ) test = { 'request': request, 'route': '/run_completer_command',", "], # [ { 'line_num': 35, 'column_num': 14 }, 'const", "results, has_entries( { 'fixits': contains( has_entries( { 'text': 'Convert to", "GNU General Public License as published by # the Free", "'text': 'Convert to raw string', 'chunks': contains( ChunkMatcher( 'R\"(\\\\\\\\r\\\\asd\\n\\\\v)\"', LineColMatcher(", "'fixits' ][ 0 ] actual = app.post_json( '/resolve_fixit', BuildRequest( **request", "ycmd.utils import ReadFile # This test is isolated to trigger", "], # [ { 'line_num': 37, 'column_num': 13 }, 'Foo", "also prohibitively complex to try and strip out. [ {", "'Resolved fixit response = ' ) print( response ) expected(", "'column_num': 14 }, 'end': { 'line_num': 84, 'column_num': 20 },", "]: yield RunGoToTest_all, '', cmd, test def Subcommands_GoToDeclaration_all_test(): tests =", "'res': ( 'system/a.hpp', 1, 1 ) }, { 'req': (", "n o # e l Lang File, Checker [ 16,", "struct Foo *' ], # [ { 'line_num': 46, 'column_num':", "'line_num': 54, 'column_num': 19 } ), } ), } )", "54, 'column_num': 58 } ), } ), } ), ),", "contains( has_entries( { 'chunks': contains( has_entries( { 'replacement_text': equal_to( 'id'", "13 }, } raw_string_range = { 'start': { 'line_num': 80,", ") else: expected = test[ 1 ] request = common_args", "] ) ) else: expected = has_entry( 'message', test[ 1", "'res': ( 'quote/b.hpp', 1, 1 ) }, { 'req': (", "[ { 'line_num': 35, 'column_num': 22 }, 'const int' ],", "elif isinstance( response, tuple ): expect = { 'response': requests.codes.ok,", "}, # Expected failure { 'req': ( 'goto.cc', 27, 8", "}, { 'req': ( 'goto.cc', 16, 6 ), 'res': 'Cannot", "7 }, 'char' ], # Function # [ { 'line_num':", "'column_num': 3 }, 'namespace Ns' ], # On Type (Type)", "{ 'line_num': 37, 'column_num': 13 }, 'Foo *' ], [", "'command': has_entries( { 'command': 'clangd.applyTweak' } ) } ) )", "'filepath': PathToTestFile( 'basic.cpp' ), 'command_arguments': [ 'RefactorRename', 'Bar' ], 'line_num':", ": '/run_completer_command', 'expect' : expect } ) def Subcommands_GoTo_all_test(): tests", ":: assert_that( results, has_entries( { 'fixits': contains( has_entries( { 'chunks':", "}, 'const struct Foo *' ], # Cursor on usage", "3 ) ), ChunkMatcher( 'dummy', LineColMatcher( 84, 10 ), LineColMatcher(", "{ 'request': request, 'route' : '/run_completer_command', 'expect' : expect }", "expected = test[ 1 ] request = common_args request.update( args", "[ { 'line_num': 24, 'column_num': 3 }, 'Foo' ], #", "'', cmd, test def Subcommands_GoToDeclaration_all_test(): tests = [ # Local::x", "# [ { 'line_num': 29, 'column_num': 11 }, 'Foo *'", "'column_num': 17 }, 'int' ], [ { 'line_num': 48, 'column_num':", "'fixits' ][ 0 ] response = app.post_json( '/resolve_fixit', BuildRequest( **args", "17, 3 ), LineColMatcher( 17, 6 ) ), ChunkMatcher( '',", "'end' : has_entries( { 'line_num': 21, 'column_num': 11 } ),", "], 'range' : rng, 'filetype' : 'cpp' } app.post_json( '/event_notification',", "'req': ( 'main.cpp', 3, 1 ), 'res': ( 'quote/b.hpp', 1,", "'completer_target': 'filetype_default', 'command_arguments': [ 'GoToDefinition' ], 'line_num': 10, 'column_num': 3,", "{ 'req': ( 'goto.cc', 24, 17 ), 'res': [ (", "'start': { 'line_num': 83, 'column_num': 3 }, 'end': { 'line_num':", "1 ) }, { 'req': ( 'main.cpp', 2, 14 ),", "Function # [ { 'line_num': 22, 'column_num': 2 }, 'int", "has_entries( { 'start': has_entries( { 'line_num': 40, 'column_num': 6 }", "*' ], [ { 'line_num': 48, 'column_num': 18 }, 'int'", "cfile, FixIt_Check_cpp11_Repl ], [ 48, 3, 'cpp11', cfile, FixIt_Check_cpp11_DelAdd ],", "'column_num': 3 }, 'Foo' ], [ { 'line_num': 39, 'column_num':", "{ 'req': ( 'goto.cc', 24, 16 ), 'res': ( 'goto.cc',", "} ) ), 'location': has_entries( { 'line_num': 54, 'column_num': 15", "72, 35 ) ) ), 'location': LineColMatcher( 72, 9 ),", "), 'res': ( 'goto.cc', 21, 5 ) }, # Unicøde", "has_entries( { 'replacement_text': equal_to( '=' ), 'range': has_entries( { 'start':", "of test { 'req': ( 'goto.cc', 21, 5 ), 'res':", "# [ { 'line_num': 26, 'column_num': 13 }, # 'Ns::Type", "( 'main.cpp', 1, 6 ), 'res': ( 'a.hpp', 1, 1", "LineColMatcher( 17, 6 ) ), ChunkMatcher( '', LineColMatcher( 17, 14", "'column_num': 2 }, 'Foo' ], [ { 'line_num': 12, 'column_num':", "28, 'column_num': 18 }, 'struct Foo' ], # [ {", "{ 'line_num': 48, 'column_num': 15 } ), 'end' : has_entries(", "= PathToTestFile( 'GoTo_Clang_ZeroBasedLineAndColumn_test.cc' ) RunAfterInitialized( app, { 'request': { 'contents':", "Type (Type) # [ { 'line_num': 25, 'column_num': 8 },", "} ) ), 'location': has_entries( { 'line_num': 5, 'column_num': 3", "= has_entry( 'message', test[ 1 ] ) else: expected =", "}, 'const Foo &' ], # [ { 'line_num': 32,", "): # and finally, a warning with no fixits assert_that(", "} RunAfterInitialized( app, test ) def Subcommands_GetType_test(): tests = [", "'range': has_entries( { 'start': has_entries( { 'line_num': 35, 'column_num': 7", "strip out. [ { 'line_num': 53, 'column_num': 15 }, matches_regexp(", "contains( ChunkMatcher( 'R\"(\\\\\\\\r\\\\asd\\n\\\\v)\"', LineColMatcher( 80, 19 ), LineColMatcher( 80, 36", "receive_diags ) diags = RunAfterInitialized( app, test ) results =", "as published by # the Free Software Foundation, either version", "] for test in tests: yield RunGoToTest_all, '', 'GoToReferences', test", "test, command, response = requests.codes.ok ): contents = ReadFile( filepath", "in [ 'GoToInclude', 'GoTo', 'GoToImprecise' ]: yield RunGoToTest_all, 'test-include', cmd,", "has_entries( { 'text': 'Extract subexpression to variable', 'chunks': contains( ChunkMatcher(", "'Ns::Type => Ns::BasicType<char>' ], # On \"a\" (Ns::Type) # [", "3 ), 'res': ( 'goto.cc', 36, 28 ) }, #", "}, # GoToDeclaration alternates between definition and declaration { 'req':", "has_entries( { 'line_num': 26, 'column_num': 7 } ), } ),", ") }, # test -> definition and declaration of test", "54, 'column_num': 53 } ), } ), } ), has_entries(", "}, # Expected failures { 'req': ( 'goto.cc', 13, 1", "{ 'line_num': 26, 'column_num': 7 } ), 'end' : has_entries(", "'line_num': 24, 'column_num': 3 }, 'Foo' ], # [ {", "contains( has_entries( { 'chunks': contains( has_entries( { 'replacement_text': equal_to( 'foo'", "'chunks': contains( ChunkMatcher( 'SpellingIsNotMyStrongPoint', LineColMatcher( 72, 9 ), LineColMatcher( 72,", "'/resolve_fixit', BuildRequest( **request ) ).json print( 'actual = ' )", "in response ] ) } elif isinstance( response, tuple ):", ") ) } ) ) def FixIt_Check_AutoExpand_Resolved( results ): assert_that(", "'route': '/receive_messages' } RunAfterInitialized( app, receive_diags ) diags = RunAfterInitialized(", "}, 'Unicøde *' ], # Bound methods # On Win32,", "import division from hamcrest.core.base_matcher import BaseMatcher from hamcrest import (", "80, 'column_num': 19 }, 'end': { 'line_num': 80, 'column_num': 35", "ycmd.tests.test_utils import ( BuildRequest, ChunkMatcher, CombineRequest, LineColMatcher, LocationMatcher, ErrorMatcher, WithRetry,", "test[ 1 ] ) else: expected = test[ 1 ]", "'end' : has_entries( { 'line_num': 5, 'column_num': 3 } ),", "Public License as published by # the Free Software Foundation,", "PathToTestFile( 'basic.cpp' ), 'command_arguments': [ 'RefactorRename', 'Bar' ], 'line_num': 17,", ") ), ) } ) ) } ) }, 'route':", "test[ 3 ], test[ 4 ] @WithRetry @SharedYcmd def RunRangedFixItTest(", "( 'goto.cc', 13, 1 ), 'res': 'Cannot jump to location'", "'Foo' ], # [ { 'line_num': 12, 'column_num': 2 },", "{ 'start': has_entries( { 'line_num': 40, 'column_num': 6 } ),", "54, 15, 'cpp11', cfile, FixIt_Check_cpp11_MultiFirst ], # should put closest", "CombineRequest, LineColMatcher, LocationMatcher, ErrorMatcher, WithRetry, WaitUntilCompleterServerReady ) from ycmd.utils import", "'line_num': 28, 'column_num': 3 }, 'struct Foo &' ], #", "'line_num': 21, 'column_num': 11 } ), } ), } )", "canonical type # On Ns:: [ { 'line_num': 25, 'column_num':", ") check( results ) def FixIt_Check_cpp11_Ins( results ): # First", "'Bar', LineColMatcher( 9, 3 ), LineColMatcher( 9, 6 ) ),", "36, 25 ), 'res': ( 'goto.cc', 32, 54 ) },", "have received a copy of the GNU General Public License", "{ 'line_num': 12, 'column_num': 2 }, 'Foo' ], [ {", "'int i', LineColMatcher( 83, 3 ), LineColMatcher( 83, 17 )", "'line_num': 29, 'column_num': 11 }, 'Foo *' ], [ {", "}, } macro_expand_range = { 'start': { 'line_num': 83, 'column_num':", "[ 'FixIt' ], 'line_num' : line, 'column_num' : column, }", ") ) ), 'location': LineColMatcher( 72, 9 ), } )", "= ReadFile( PathToTestFile( 'FixIt_Clang_cpp11.cpp' ) ) args = { 'completer_target'", "Local { 'req': ( 'goto.cc', 24, 16 ), 'res': (", "in the hope that it will be useful, # but", "( 'goto.cc', 27, 8 ), 'res': 'Cannot jump to location'", "), 'end' : has_entries( { 'line_num': 40, 'column_num': 9 }", "), 'location': has_entries( { 'line_num': 40, 'column_num': 6 } )", ") } ) ) def Subcommands_FixIt_all_test(): cfile = PathToTestFile( 'FixIt_Clang_cpp11.cpp'", "-> definition and declaration of test { 'req': ( 'goto.cc',", "ReadFile( filename ), 'filepath' : filename, 'command_arguments': [ 'FixIt' ],", "17, 14 ), LineColMatcher( 17, 15 ) ), ChunkMatcher( '", "), ) } ) ) } ) }, 'route': '/run_completer_command'", "2 } ), 'end' : has_entries( { 'line_num': 28, 'column_num':", "), 'res': ( 'goto.cc', 19, 5 ) }, { 'req':", "RunAfterInitialized( app, { 'request': { 'contents': ReadFile( file_path ), 'completer_target':", "FixIt_Check_cpp11_Repl( results ): assert_that( results, has_entries( { 'fixits': contains( has_entries(", "'line_num': 37, 'column_num': 13 }, 'Foo *' ], [ {", "'column_num': 11 }, 'struct Foo &' ], [ { 'line_num':", "[ { 'line_num': 12, 'column_num': 8 }, 'Foo' ], [", "'line_num': 39, 'column_num': 15 }, 'Foo' ], [ { 'line_num':", "'res' ] if isinstance( response, list ): expect = {", "ReadFile( file_path ) language_options = { 'cpp11': { 'filetype' :", "{ 'req': ( 'main.cpp', 7, 1 ), 'res': 'Cannot jump", "'location': LineColMatcher( 60, 1 ), } ), # Unresolved, requires", "}, 'Foo' ], [ { 'line_num': 40, 'column_num': 11 },", "'column_num': 3 } ), } ), } ) ), 'location':", "{ 'line_num': 80, 'column_num': 35 }, } tests = [", "@SharedYcmd def RunFixItTest( app, line, column, lang, file_path, check ):", "{ 'line_num': 42, 'column_num': 16 }, 'const struct Foo &'", "54, 'column_num': 16 } ), 'end' : has_entries( { 'line_num':", "'line_num': 83, 'column_num': 13 }, } raw_string_range = { 'start':", "'response': requests.codes.ok, 'data': { 'filepath': os.path.abspath( file_path ), 'line_num': 2,", "to location' }, { 'req': ( 'goto.cc', 16, 6 ),", "'req': ( 'main.cpp', 5, 11 ), 'res': ( 'system/c.hpp', 1,", "{ 'line_num': 54, 'column_num': 67 } ), } ), }", "), ) } ) ) def FixIt_Check_unicode_Ins( results ): assert_that(", "} ) ) def Subcommands_FixIt_all_test(): cfile = PathToTestFile( 'FixIt_Clang_cpp11.cpp' )", "note: put parens around it has_entries( { 'text': contains_string( 'parentheses", "any later version. # # ycmd is distributed in the", "'start': has_entries( { 'line_num': 40, 'column_num': 6 } ), 'end'", "'text': 'Extract subexpression to variable', 'chunks': contains( ChunkMatcher( 'auto dummy", "'req': ( 'main.cpp', 6, 11 ), 'res': ( 'system/c.hpp', 1,", "0 } ) } ) ) } ) ) def", "'line_num': 48, 'column_num': 9 } ), 'end' : has_entries( {", "[ { 'line_num': 39, 'column_num': 15 }, 'Foo' ], [", "}, 'const Foo *' ], # [ { 'line_num': 35,", "# Similar to FixIt_Check_cpp11_1 but inserts split across lines #", "contents, 'filepath' : PathToTestFile( 'FixIt_Clang_cpp11.cpp' ), 'command_arguments': [ 'FixIt' ],", "'req': ( 'goto.cc', 21, 5 ), 'res': ( 'goto.cc', 19,", "37, 'column_num': 13 }, 'Foo *' ], [ { 'line_num':", "), LineColMatcher( 61, 12 ) ) ), 'location': LineColMatcher( 60,", "{ 'req': ( 'main.cpp', 1, 6 ), 'res': ( 'a.hpp',", "&' ], [ { 'line_num': 39, 'column_num': 15 }, 'Foo'", "isinstance( response, tuple ): expect = { 'response': requests.codes.ok, 'data':", "{ 'req': ( 'goto.cc', 36, 25 ), 'res': ( 'goto.cc',", "GNU General Public License for more details. # # You", "), ) } ) ) } ) ) def FixIt_Check_MacroExpand_Resolved(", ") ) } ) ) def FixIt_Check_cpp11_Note( results ): assert_that(", "1 ), } ), # Unresolved, requires /resolve_fixit request has_entries(", "), LineColMatcher( 17, 15 ) ), ChunkMatcher( ' ', LineColMatcher(", "test -> definition and declaration of test { 'req': (", "their # calling convention. This shows up in the type,", "), 'res': ( 'goto.cc', 14, 13 ) }, # GoToDeclaration", "# Function { 'req': ( 'goto.cc', 14, 21 ), 'res':", "'req': ( 'main.cpp', 7, 1 ), 'res': 'Cannot jump to", "check( results ) def FixIt_Check_cpp11_Ins( results ): # First fixit", "has_entries( { 'line_num': 54, 'column_num': 58 } ), 'end' :", "17, 19 ) ), ) } ) ) } )", "file_path ), 'line_num': 2, 'column_num': 8 } }, 'route': '/run_completer_command',", "], # [ { 'line_num': 42, 'column_num': 3 }, 'const", "test = { 'request': args, 'route': '/detailed_diagnostic' } # First", "# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the", "has_entry( 'message', contains_string( test[ 1 ] ) ) else: expected", "added with -iquote. { 'req': ( 'main.cpp', 4, 10 ),", "# encoding: utf-8 # # Copyright (C) 2018 ycmd contributors", ") }, # Expected failures { 'req': ( 'goto.cc', 13,", "[ 'GetType', 'GetTypeImprecise' ]: for test in tests: yield (", "'column_num': 13 }, 'const struct Foo' ], # [ {", "} ), ) } ) ) def FixIt_Check_unicode_Ins( results ):", ") def FixIt_Check_cpp11_Del( results ): # Removal of :: assert_that(", "is free software: you can redistribute it and/or modify #", "First get diags. diags = RunAfterInitialized( app, test ) while", "[ 40, 6, 'cpp11', cfile, FixIt_Check_cpp11_Repl ], [ 48, 3,", "'command_arguments': command, 'line_num' : 10, 'column_num' : 3, 'filepath' :", "filepath ) common_args = { 'completer_target' : 'filetype_default', 'command_arguments': command,", "80, 36 ) ), ) } ) ) } )", "# [ { 'line_num': 46, 'column_num': 20 }, 'const int'", "} subexpression_extract_range = { 'start': { 'line_num': 84, 'column_num': 14", "'/resolve_fixit', BuildRequest( **args ) ).json print( 'Resolved fixit response =", "'column_num': 10 }, 'docstring', requests.codes.ok ], # no docstring [", "48, 'column_num': 3 } ) } ), ) } )", "), LineColMatcher( 84, 3 ) ), ChunkMatcher( 'dummy', LineColMatcher( 84,", "{ 'line_num': 47, 'column_num': 12 }, 'Foo' ], [ {", "command, response = requests.codes.ok ): contents = ReadFile( filepath )", "{ 'response': requests.codes.internal_server_error, 'data': ErrorMatcher( RuntimeError, test[ 'res' ] )", "8 ), LineColMatcher( 15, 11 ) ), ChunkMatcher( ' ',", "[ { 'line_num': 29, 'column_num': 11 }, 'Foo *' ],", "], # [ { 'line_num': 43, 'column_num': 3 }, 'const", "}, 'int' ], # [ { 'line_num': 37, 'column_num': 13", "app ): filename = PathToTestFile( 'FixIt_Clang_cpp11.cpp' ) request = {", "to trigger objcpp hooks, rather than fetching completer # from", "contains_string( 'parentheses around the assignment' ), 'chunks': contains( ChunkMatcher( '(',", "LineColMatcher( 84, 3 ), LineColMatcher( 84, 3 ) ), ChunkMatcher(", "{ 'completer_target' : 'filetype_default', 'contents' : ReadFile( filename ), 'filepath'", "), requests.codes.server_error ] ] for subcommand in [ 'GetDoc', 'GetDocImprecise'", "put parens around it has_entries( { 'text': contains_string( 'parentheses around", ") ), ChunkMatcher( ')', LineColMatcher( 61, 12 ), LineColMatcher( 61,", "[ { 'line_num': 37, 'column_num': 13 }, 'Foo *' ],", "FixIt_Check_cpp11_Del( results ): # Removal of :: assert_that( results, has_entries(", "{ 'req': ( 'main.cpp', 5, 11 ), 'res': ( 'system/c.hpp',", "under the terms of the GNU General Public License as", "in tests: yield ( RunGetSemanticTest, PathToTestFile( 'GetType_Clang_test.cc' ), 'cpp', test,", "}, 'const int' ], [ { 'line_num': 36, 'column_num': 13", "ChunkMatcher( 'Bar', LineColMatcher( 9, 3 ), LineColMatcher( 9, 6 )", "yield RunFixItTest, test[ 0 ], test[ 1 ], test[ 2", "], test[ 1 ] @WithRetry @SharedYcmd def Subcommands_FixIt_AlreadyResolved_test( app ):", "1, 1 ) }, # Expected failures { 'req': (", ") def Subcommands_GetDoc_test(): tests = [ # from local file", "equal_to( { 'fixits': [] } ) ) def FixIt_Check_cpp11_MultiFirst( results", "'request': request, 'route': '/run_completer_command', 'expect': { 'response': response, 'data': expected", "0 ] response = app.post_json( '/resolve_fixit', BuildRequest( **args ) ).json", "{ 'replacement_text': equal_to( '~' ), 'range': has_entries( { 'start': has_entries(", "# Expected failure { 'req': ( 'goto.cc', 27, 8 ),", "warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.", "{ 'line_num': 48, 'column_num': 18 }, 'int' ], # Auto", "[ 48, 3, 'cpp11', cfile, FixIt_Check_cpp11_DelAdd ], [ 5, 3,", "7 }, 'int x = 3', requests.codes.ok ], # no", "{ 'req': ( 'goto.cc', 21, 5 ), 'res': ( 'goto.cc',", "'data': has_entries( { 'fixits': contains( has_entries( { 'chunks': contains( ChunkMatcher(", "in line for fixit [ 21, 16, 'cpp11', ufile, FixIt_Check_unicode_Ins", "file_path = PathToTestFile( 'GoTo_Clang_ZeroBasedLineAndColumn_test.cc' ) RunAfterInitialized( app, { 'request': {", "{ 'req': ( 'goto.cc', 24, 26 ), 'res': ( 'goto.cc',", "} ) ) } ) ) def FixIt_Check_cuda( results ):", "} RunAfterInitialized( app, { 'request': request, 'route' : '/run_completer_command', 'expect'", "requests.codes.ok, 'data': { 'filepath': os.path.abspath( file_path ), 'line_num': 2, 'column_num':", "'Foo' ], [ { 'line_num': 47, 'column_num': 17 }, 'int'", "'line_num': 54, 'column_num': 18 }, matches_regexp( r'int bar\\(int i\\)(?: __attribute__\\(\\(thiscall\\)\\))?'", "}, } args = { 'completer_target' : 'filetype_default', 'contents' :", "diags. diags = RunAfterInitialized( app, test ) while 'message' in", "has_entries( { 'line_num': 35, 'column_num': 7 } ) } )", "), } ), # Unresolved, requires /resolve_fixit request has_entries( {", "type, which isn't ideal, but # also prohibitively complex to", "i', LineColMatcher( 83, 3 ), LineColMatcher( 83, 17 ) ),", "'fixits': contains( has_entries( { 'text': 'Extract subexpression to variable', 'chunks':", "'GoToInclude', 'GoTo', 'GoToImprecise' ]: yield RunGoToTest_all, 'test-include', cmd, test def", ") } ) ) } ) ) def FixIt_Check_cpp11_Note( results", "} app.post_json( '/event_notification', CombineRequest( request, { 'event_name': 'FileReadyToParse', } ),", "'end' : has_entries( { 'line_num': 35, 'column_num': 9 } ),", "receive_diags = { 'request': args, 'route': '/receive_messages' } RunAfterInitialized( app,", "8 } }, 'route': '/run_completer_command', } ) @SharedYcmd def RunGoToTest_all(", "), } ) ), 'location': has_entries( { 'line_num': 35, 'column_num':", "( 'goto.cc', 19, 5 ), 'res': ( 'goto.cc', 21, 5", ": 'filetype_default', 'filepath' : filepath, 'command_arguments': [ command ], 'contents'", "= [ [ expand_auto_range, FixIt_Check_AutoExpand_Resolved ], [ macro_expand_range, FixIt_Check_MacroExpand_Resolved ],", "2 ] ) } else: expect = { 'response': requests.codes.internal_server_error,", "17, 17 ) ), ChunkMatcher( ' ', LineColMatcher( 17, 19", "should fail since b.hpp is included with angled brackets but", "'goto.cc', 2, 11 ) }, # Local::out_of_line -> definition of", "), } ), has_entries( { 'replacement_text': equal_to( ')' ), 'range':", "convention. This shows up in the type, which isn't ideal,", "to a \"child\" diagnostic (i.e. a Note) [ 60, 1,", "{ 'req': ( 'main.cpp', 4, 10 ), 'res': ( 'quote/b.hpp',", "ycmd is free software: you can redistribute it and/or modify", "line; both with fixits [ 54, 15, 'cpp11', cfile, FixIt_Check_cpp11_MultiFirst", "'GoToReferences', test @SharedYcmd def RunGetSemanticTest( app, filepath, filetype, test, command,", "} ) def Subcommands_GoTo_all_test(): tests = [ # Local::x ->", "[ 25, 14, 'cpp11', cfile, FixIt_Check_cpp11_InsMultiLine ], [ 35, 7,", "1 ), LineColMatcher( 80, 6 ) ), ) } )", "first fix-it at 54,16 has_entries( { 'chunks': contains( has_entries( {", "'filetype': 'objcpp', 'filepath': file_path }, 'expect': { 'response': requests.codes.ok, 'data':", "), 'end' : has_entries( { 'line_num': 54, 'column_num': 67 }", "'Format', 'GetDoc', 'GetDocImprecise', 'GetType', 'GetTypeImprecise', 'GoTo', 'GoToDeclaration', 'GoToDefinition', 'GoToImprecise', 'GoToInclude',", ").json print( 'expected = ' ) print( expected ) request[", "], 'line_num' : line, 'column_num' : column, } args.update( language_options[", "def FixIt_Check_AutoExpand_Resolved( results ): assert_that( results, has_entries( { 'fixits': contains(", "1, 8 ), LineColMatcher( 1, 11 ) ), ChunkMatcher( 'Bar',", "14 } ) } ) ) } ) ) def", "# # Copyright (C) 2018 ycmd contributors # # This", "types [ { 'line_num': 24, 'column_num': 3 }, 'Foo' ],", "across lines # assert_that( results, has_entries( { 'fixits': contains( has_entries(", "has_entries( { 'line_num': 54, 'column_num': 58 } ), } ),", "has_entries( { 'start': has_entries( { 'line_num': 26, 'column_num': 7 }", "), 'res': ( 'goto.cc', 36, 28 ) }, # Expected", "} ), ) } ) ) def FixIt_Check_objc( results ):", "Unicode [ { 'line_num': 51, 'column_num': 13 }, 'Unicøde *'", "# no docstring [ { 'line_num': 7, 'column_num': 7 },", "A PARTICULAR PURPOSE. See the # GNU General Public License", "the Free Software Foundation, either version 3 of the License,", "int' ], [ { 'line_num': 46, 'column_num': 13 }, 'const", "struct Foo &' ], # [ { 'line_num': 43, 'column_num':", "{ 'line_num': 28, 'column_num': 2 } ), } ), }", "'column_num': test[ 'req' ][ 2 ], } ) response =", "[ { 'line_num': 40, 'column_num': 18 }, 'Foo' ], #", "[ expand_auto_range, FixIt_Check_AutoExpand_Resolved ], [ macro_expand_range, FixIt_Check_MacroExpand_Resolved ], [ subexpression_extract_range,", "[ { 'line_num': 46, 'column_num': 20 }, 'const int' ],", "[ { 'line_num': 5, 'column_num': 10 }, 'docstring', requests.codes.ok ],", "'column_num': 0 } ) } ) ) } ) )", "80, 'column_num': 1 }, 'end': { 'line_num': 80, 'column_num': 4", "'cuda', }, 'objective-c': { 'filetype' : 'objc', }, } args", "), LineColMatcher( 15, 1 ) ), ChunkMatcher( 'Bar', LineColMatcher( 15,", "has_entries( { 'fixits': contains( has_entries( { 'text': 'Extract subexpression to", "FixIt_Check_cpp11_Ins ], [ 25, 14, 'cpp11', cfile, FixIt_Check_cpp11_InsMultiLine ], [", "'filetype_default', 'filepath' : filepath, 'command_arguments': [ command ], 'contents' :", "{ 'line_num': 43, 'column_num': 16 }, 'const struct Foo *'", "free software: you can redistribute it and/or modify # it", "), 'res': ( 'system/c.hpp', 1, 1 ) }, # Expected", ") ) def FixIt_Check_AutoExpand_Resolved( results ): assert_that( results, has_entries( {", "{ 'line_num': 7, 'column_num': 7 }, 'int x = 3',", ") ) def FixIt_Check_cpp11_MultiSecond( results ): assert_that( results, has_entries( {", "*', LineColMatcher( 80, 1 ), LineColMatcher( 80, 6 ) ),", "the implied warranty of # MERCHANTABILITY or FITNESS FOR A", "'RefactorRename', 'RestartServer' ] ) ) }, 'route': '/defined_subcommands', } )", "{ 'line_num': 5, 'column_num': 3 } ) } ) )", "'column_num': 22 }, 'const int' ], [ { 'line_num': 36,", "def Subcommands_GetType_test(): tests = [ # Basic pod types [", "60, 1 ), } ), # Unresolved, requires /resolve_fixit request", "# [ { 'line_num': 28, 'column_num': 11 }, 'struct Foo", "definition of Local::out_of_line { 'req': ( 'goto.cc', 25, 27 ),", "), } ) ) } ) ) def FixIt_Check_SubexprExtract_Resolved( results", "has_entries( { 'fixits': contains( has_entries( { 'text': \"Expand auto type\",", "LineColMatcher( 16, 1 ) ), ChunkMatcher( 'Bar', LineColMatcher( 17, 3", "Copyright (C) 2018 ycmd contributors # # This file is", "has_entries( { 'start': has_entries( { 'line_num': 16, 'column_num': 13 }", "# Expected failures { 'req': ( 'main.cpp', 7, 1 ),", "{ 'fixits': contains( has_entries( { 'chunks': contains( has_entries( { 'replacement_text':", "'const struct Foo *' ], # [ { 'line_num': 46,", "), has_entries( { 'replacement_text': equal_to( '~' ), 'range': has_entries( {", "}, 'namespace Ns' ], # On Type (Type) # [", "part of ycmd. # # ycmd is free software: you", "1 ] request = common_args request.update( args ) test =", "} ) ) def FixIt_Check_cuda( results ): assert_that( results, has_entries(", "6 ) ), ChunkMatcher( '', LineColMatcher( 17, 14 ), LineColMatcher(", ") }, # Local -> definition/declaration of Local { 'req':", "] }, # Expected failure { 'req': ( 'goto.cc', 27,", "15 ) ] }, # Expected failure { 'req': (", "3 } ) } ) ) } ) ) def", "# second fix-it at 54,52 has_entries( { 'chunks': contains( has_entries(", "ChunkMatcher( '==', LineColMatcher( 60, 8 ), LineColMatcher( 60, 9 )", "} ) ) } ) ) def FixIt_Check_AutoExpand_Resolved( results ):", "'res': ( 'system/c.hpp', 1, 1 ) }, { 'req': (", "' ) print( response ) expected( response ) def Subcommands_FixIt_Ranged_test():", "'filetype_default', 'contents' : contents, 'filepath' : PathToTestFile( 'FixIt_Clang_cpp11.cpp' ), 'command_arguments':", "# ycmd is distributed in the hope that it will", "} ), } ), has_entries( { 'replacement_text': equal_to( ')' ),", "= { 'request': { 'filetype': 'cpp', 'completer_target': 'filetype_default', 'contents': ReadFile(", "__future__ import absolute_import from __future__ import unicode_literals from __future__ import", "13 }, # 'Ns::Type => Ns::BasicType<char>' ], # Cursor on", "{ 'req': ( 'main.cpp', 3, 1 ), 'res': ( 'quote/b.hpp',", "# Unicøde { 'req': ( 'goto.cc', 34, 9 ), 'res':", "[ 16, 0, 'cpp11', cfile, FixIt_Check_cpp11_Ins ], [ 25, 14,", "21 ), 'res': ( 'goto.cc', 4, 9 ) }, #", ") ), ChunkMatcher( 'dummy', LineColMatcher( 84, 10 ), LineColMatcher( 84,", "from __future__ import print_function from __future__ import division from hamcrest.core.base_matcher", "54, 'column_num': 15 } ) } ), ) } )", "cache. @IsolatedYcmd() def Subcommands_DefinedSubcommands_test( app ): file_path = PathToTestFile( 'GoTo_Clang_ZeroBasedLineAndColumn_test.cc'", "= test[ 1 ] request = common_args request.update( args )", "expect_errors = True ) WaitUntilCompleterServerReady( app, 'cpp' ) response =", "first? [ 54, 51, 'cpp11', cfile, FixIt_Check_cpp11_MultiSecond ], # unicode", "7 } ) } ) ) } ) ) def", "} ), 'end' : has_entries( { 'line_num': 28, 'column_num': 2", "'quote/b.hpp', 1, 1 ) }, # FIXME: should fail since", "'column_num': 51 } ) } ), ) } ) )", "has_entries( { 'line_num': 21, 'column_num': 11 } ), } ),", ") } ) ) def FixIt_Check_objc_NoFixIt( results ): # and", "# On Ns:: [ { 'line_num': 25, 'column_num': 3 },", "# along with ycmd. If not, see <http://www.gnu.org/licenses/>. from __future__", ") }, { 'req': ( 'goto.cc', 36, 25 ), 'res':", "'goto.cc', 36, 28 ) }, # Expected failures { 'req':", "results ): # First fixit # switch(A()) { // expected-error{{explicit", ": 1, 'filetype' : 'cpp' } app.post_json( '/event_notification', CombineRequest( request,", "1, 1 ) }, # FIXME: should fail since b.hpp", "'column_num': 4, }, 'expect': { 'response': requests.codes.ok, 'data': has_entries( {", "'end' : has_entries( { 'line_num': 54, 'column_num': 67 } ),", "= app.post_json( '/resolve_fixit', BuildRequest( **request ) ).json print( 'actual =", "9 ), 'res': ( 'goto.cc', 32, 26 ) }, #", "'range': has_entries( { 'start': has_entries( { 'line_num': 40, 'column_num': 6", "'column_num': 11 } ), } ), } ) ), 'location':", "{ 'line_num': 54, 'column_num': 58 } ), 'end' : has_entries(", "angled brackets but its # folder is added with -iquote.", "'res': ( 'quote/b.hpp', 1, 1 ) }, # FIXME: should", "def FixIt_Check_cpp11_DelAdd( results ): assert_that( results, has_entries( { 'fixits': contains(", "response[ 0 ] ) ), response[ 1 ], response[ 2", "# Local::in_line -> definition/declaration of Local::in_line { 'req': ( 'goto.cc',", "} ) ) def FixIt_Check_cpp11_Repl( results ): assert_that( results, has_entries(", "'line_num': 35, 'column_num': 9 } ), } ), } )", "12 ), LineColMatcher( 61, 12 ) ) ), 'location': LineColMatcher(", "dummy = foo(i + 3);\\n ', LineColMatcher( 84, 3 ),", "'message' ].lower(): receive_diags = { 'request': args, 'route': '/receive_messages' }", "results, has_entries( { 'fixits': contains( has_entries( { 'text': contains_string( \"change", ": has_entries( { 'line_num': 48, 'column_num': 9 } ), }", "tests = [ { 'req': ( 'main.cpp', 1, 6 ),", "2, 11 ), ( 'goto.cc', 14, 6 ), ( 'goto.cc',", ") } ) ) def FixIt_Check_RawStringReplace_Resolved( results ): assert_that( results,", "), 'res': ( 'goto.cc', 4, 9 ) }, # Local::in_line", "= ReadFile( file_path ) language_options = { 'cpp11': { 'filetype'", "{ 'line_num': 8, 'column_num': 1 }, ErrorMatcher( RuntimeError, 'No hover", ") ) def FixIt_Check_RawStringReplace_Resolved( results ): assert_that( results, has_entries( {", "objcpp hooks, rather than fetching completer # from cache. @IsolatedYcmd()", "requests.codes.ok, 'data': LocationMatcher( PathToTestFile( folder, os.path.normpath( response[ 0 ] )", "}, # test -> definition and declaration of test {", "PathToTestFile( 'unicode.cc' ) tests = [ # L # i", ") } ) ) } ) ) def FixIt_Check_cpp11_SpellCheck( results", "PathToTestFile( folder, os.path.normpath( response[ 0 ] ) ), response[ 1", "*' ], # [ { 'line_num': 35, 'column_num': 22 },", "from __future__ import absolute_import from __future__ import unicode_literals from __future__", "'system/a.hpp', 1, 1 ) }, { 'req': ( 'main.cpp', 3,", "{ 'req': ( 'goto.cc', 11, 10 ), 'res': ( 'goto.cc',", "'filepath' : filepath, 'command_arguments': [ command ], 'contents' : ReadFile(", "], [ { 'line_num': 39, 'column_num': 15 }, 'Foo' ],", "= PathToTestFile( 'cuda', 'fixit_test.cu' ) ufile = PathToTestFile( 'unicode.cc' )", "13 ), ( 'goto.cc', 25, 22 ) ] }, #", "location[ 1 ], location[ 2 ] ) for location in", "for subcommand in [ 'GetType', 'GetTypeImprecise' ]: for test in", "LineColMatcher( 15, 8 ), LineColMatcher( 15, 11 ) ), ChunkMatcher(", "# # ycmd is distributed in the hope that it", ") request = { 'completer_target' : 'filetype_default', 'contents' : ReadFile(", "{ 'start': has_entries( { 'line_num': 48, 'column_num': 9 } ),", "'line_num': 15, 'column_num': 7 }, 'char' ], # Function #", "in declaration # [ { 'line_num': 28, 'column_num': 3 },", "( 'goto.cc', 14, 6 ), ( 'goto.cc', 23, 14 ),", "'chunks': contains( ChunkMatcher( 'int i', LineColMatcher( 83, 3 ), LineColMatcher(", "'column_num': 12 }, 'Foo' ], [ { 'line_num': 47, 'column_num':", "], ] for test in tests: yield RunRangedFixItTest, test[ 0", "which isn't ideal, but # also prohibitively complex to try", "], test[ 2 ] ) @SharedYcmd def RunFixItTest( app, line,", "}, 'const Foo &' ], # [ { 'line_num': 31,", "test[ 'req' ][ 1 ], 'column_num': test[ 'req' ][ 2", "\"a\" (Ns::Type) # [ { 'line_num': 25, 'column_num': 15 },", "has_entries( { 'line_num': 28, 'column_num': 2 } ), } ),", "has_entries( { 'line_num': 48, 'column_num': 9 } ), 'end' :", "results, has_entries( { 'fixits': contains( has_entries( { 'text': 'Extract subexpression", "'/event_notification', CombineRequest( args, { 'event_name': 'FileReadyToParse', } ), expect_errors =", "[ { 'line_num': 37, 'column_num': 20 }, 'int' ], #", "'line_num': 48, 'column_num': 3 } ) } ), has_entries( {", "'column_num': 11 }, 'Foo &' ], [ { 'line_num': 39,", "# from cache. @IsolatedYcmd() def Subcommands_DefinedSubcommands_test( app ): file_path =", "'goto.cc', 2, 11 ), ( 'goto.cc', 14, 6 ), (", "), location[ 1 ], location[ 2 ] ) for location", "# Cursor on decl for refs & pointers [ {", "} ), 'end' : has_entries( { 'line_num': 16, 'column_num': 13", "{ 'req': ( 'main.cpp', 10, 13 ), 'res': 'Cannot jump", "): expect = { 'response': requests.codes.ok, 'data': contains( *[ LocationMatcher(", "'line_num' : 10, 'column_num' : 3, 'filepath' : filepath, 'contents'", "'void', LineColMatcher( 3, 12 ), LineColMatcher( 3, 15 ) )", "6 }, 'int main()' ], # Declared and canonical type", "# GoToDeclaration alternates between definition and declaration { 'req': (", "def Subcommands_GetDoc_test(): tests = [ # from local file [", "80, 6 ) ), ) } ) ) } )", "Auto in declaration # [ { 'line_num': 28, 'column_num': 3", "'req': ( 'goto.cc', 14, 13 ), 'res': ( 'goto.cc', 11,", "'GoToDefinition', 'GoTo', 'GoToImprecise' ]: yield RunGoToTest_all, '', cmd, test def", "{ 'line_num': 40, 'column_num': 11 }, 'Foo *' ], [", "file_path, check ): contents = ReadFile( file_path ) language_options =", "}, 'const Foo *' ], [ { 'line_num': 43, 'column_num':", "tests = [ # Local::x -> definition/declaration of x {", "License as published by # the Free Software Foundation, either", "in tests: yield RunGoToTest_all, '', 'GoToReferences', test @SharedYcmd def RunGetSemanticTest(", "import unicode_literals from __future__ import print_function from __future__ import division", "app, 'cpp' ) expected = app.post_json( '/run_completer_command', BuildRequest( **request )", "1 ], location[ 2 ] ) for location in response", "'column_num': 3, 'filetype': 'objcpp', 'filepath': file_path }, 'expect': { 'response':", "ChunkMatcher( ' ', LineColMatcher( 15, 46 ), LineColMatcher( 16, 1", "Foo *' ], # Auto in usage # [ {", "]: for test in tests: yield ( RunGetSemanticTest, PathToTestFile( 'GetType_Clang_test.cc'", "def FixIt_Check_unicode_Ins( results ): assert_that( results, has_entries( { 'fixits': contains(", "], response[ 2 ] ) } else: expect = {", "for location in response ] ) } elif isinstance( response,", "# On \"a\" (Ns::Type) # [ { 'line_num': 25, 'column_num':", "'line_num': 29, 'column_num': 3 }, 'Foo *' ], # [", "'chunks': contains( ChunkMatcher( '==', LineColMatcher( 60, 8 ), LineColMatcher( 60,", "import os.path from ycmd.tests.clangd import ( IsolatedYcmd, SharedYcmd, PathToTestFile, RunAfterInitialized", "column, lang, file_path, check ): contents = ReadFile( file_path )", "warning with no fixits assert_that( results, equal_to( { 'fixits': []", ") ) else: expected = has_entry( 'message', test[ 1 ]", "} ), 'end' : has_entries( { 'line_num': 48, 'column_num': 17", "pod types [ { 'line_num': 24, 'column_num': 3 }, 'Foo'", "'fixits': contains( has_entries( { 'chunks': contains( has_entries( { 'replacement_text': equal_to(", "{ 'line_num': 5, 'column_num': 3 } ), } ), }", "}, 'const struct Foo' ], # [ { 'line_num': 45,", "test[ 4 ] @WithRetry @SharedYcmd def RunRangedFixItTest( app, rng, expected", "'cpp', }, 'cuda': { 'filetype' : 'cuda', }, 'objective-c': {", "7 }, 'int' ], # [ { 'line_num': 15, 'column_num':", "'line_num': 39, 'column_num': 11 }, 'Foo &' ], [ {", "{ 'chunks': contains( has_entries( { 'replacement_text': equal_to( 'static_cast<int>(' ), 'range':", "'cpp11', cfile, FixIt_Check_cpp11_Del ], [ 40, 6, 'cpp11', cfile, FixIt_Check_cpp11_Repl", "0 ] ) common_request = { 'completer_target' : 'filetype_default', 'filepath'", "RuntimeError, test[ 'res' ] ) } RunAfterInitialized( app, { 'request':", "On \"a\" (Ns::Type) # [ { 'line_num': 25, 'column_num': 15", "}, # 'Ns::Type => Ns::BasicType<char>' ], # On \"a\" (Ns::Type)", "args, 'route': '/detailed_diagnostic' } # First get diags. diags =", "12, 2 ), LineColMatcher( 15, 1 ) ), ChunkMatcher( 'Bar',", "has_entries( { 'line_num': 48, 'column_num': 9 } ), } ),", "16 ), 'res': ( 'goto.cc', 2, 11 ) }, #", "'end' : has_entries( { 'line_num': 54, 'column_num': 19 } ),", "more details. # # You should have received a copy", "@SharedYcmd def RunGetSemanticTest( app, filepath, filetype, test, command, response =", "), 'res': [ ( 'goto.cc', 2, 11 ), ( 'goto.cc',", "[ { 'line_num': 42, 'column_num': 3 }, 'const Foo &'", "hover information.' ), requests.codes.server_error ] ] for subcommand in [", "16, 'cpp11', ufile, FixIt_Check_unicode_Ins ], # FixIt attached to a", "ChunkMatcher( 'R\"(\\\\\\\\r\\\\asd\\n\\\\v)\"', LineColMatcher( 80, 19 ), LineColMatcher( 80, 36 )", "be useful, # but WITHOUT ANY WARRANTY; without even the", "Subcommands_GetType_test(): tests = [ # Basic pod types [ {", "Foo &' ], [ { 'line_num': 42, 'column_num': 16 },", "has_entries, has_entry, matches_regexp ) from pprint import pprint import requests", "10 } ), } ), } ), has_entries( { 'replacement_text':", "'column_num': 7 } ), 'end' : has_entries( { 'line_num': 35,", "FixIt_Check_cpp11_SpellCheck ], ] for test in tests: yield RunFixItTest, test[", "LineColMatcher( 60, 1 ), } ), # Unresolved, requires /resolve_fixit", "to \" \"'SpellingIsNotMyStrongPoint'\" ), 'chunks': contains( ChunkMatcher( 'SpellingIsNotMyStrongPoint', LineColMatcher( 72,", "), LineColMatcher( 15, 11 ) ), ChunkMatcher( ' ', LineColMatcher(", "ycmd contributors # # This file is part of ycmd.", "'GoToDeclaration', 'GoToDefinition', 'GoToImprecise', 'GoToInclude', 'GoToReferences', 'RefactorRename', 'RestartServer' ] ) )", "'req': ( 'goto.cc', 25, 27 ), 'res': ( 'goto.cc', 14,", "9 }, 'Foo' ], [ { 'line_num': 12, 'column_num': 10", "[ { 'line_num': 34, 'column_num': 14 }, 'const Foo' ],", "args, 'route': '/receive_messages' } RunAfterInitialized( app, receive_diags ) diags =", "'int' ], [ { 'line_num': 13, 'column_num': 7 }, 'int'", "on decl for refs & pointers [ { 'line_num': 39,", "'column_num': 3 }, 'const Foo *' ], [ { 'line_num':", "10 ), 'res': ( 'goto.cc', 14, 13 ) }, #", "{ 'line_num': 43, 'column_num': 3 }, 'const Foo *' ],", "has_entries( { 'chunks': contains( ChunkMatcher( 'Bar', LineColMatcher( 1, 8 ),", "17 ), 'res': ( 'goto.cc', 32, 54 ) }, {", "results, has_entries( { 'fixits': contains( has_entries( { 'text': \"Expand macro", ") }, 'route': '/defined_subcommands', } ) @SharedYcmd def Subcommands_GoTo_ZeroBasedLineAndColumn_test( app", "with angled brackets but its # folder is added with", "'message' in diags and 'diagnostics' in diags[ 'message' ].lower(): receive_diags", "'objective-c', mfile, FixIt_Check_objc_NoFixIt ], [ 3, 12, 'cuda', cufile, FixIt_Check_cuda", "'system/c.hpp', 1, 1 ) }, { 'req': ( 'main.cpp', 6,", "'GetDoc', 'GetDocImprecise', 'GetType', 'GetTypeImprecise', 'GoTo', 'GoToDeclaration', 'GoToDefinition', 'GoToImprecise', 'GoToInclude', 'GoToReferences',", "FixIt_Check_cpp11_MultiSecond( results ): assert_that( results, has_entries( { 'fixits': contains( #", "15, 'cpp11', cfile, FixIt_Check_cpp11_MultiFirst ], # should put closest fix-it", "'objc', }, } args = { 'completer_target' : 'filetype_default', 'contents'", "}, 'const int' ], # [ { 'line_num': 35, 'column_num':", ") def FixIt_Check_objc( results ): assert_that( results, has_entries( { 'fixits':", ") def FixIt_Check_cpp11_Repl( results ): assert_that( results, has_entries( { 'fixits':", "( IsolatedYcmd, SharedYcmd, PathToTestFile, RunAfterInitialized ) from ycmd.tests.test_utils import (", "'static_cast<int>(' ), 'range': has_entries( { 'start': has_entries( { 'line_num': 16,", "'' ), 'range': has_entries( { 'start': has_entries( { 'line_num': 54,", "unicode_literals from __future__ import print_function from __future__ import division from", "} ) ) def FixIt_Check_objc( results ): assert_that( results, has_entries(", "84, 10 ), LineColMatcher( 84, 22 ) ), ) }", "cfile, FixIt_Check_cpp11_MultiFirst ], # should put closest fix-it first? [", "expected-error{{explicit conversion to}} assert_that( results, has_entries( { 'fixits': contains( has_entries(", "} ), 'end' : has_entries( { 'line_num': 54, 'column_num': 58", "), ChunkMatcher( 'Bar', LineColMatcher( 17, 3 ), LineColMatcher( 17, 6", "# [ { 'line_num': 35, 'column_num': 22 }, 'const int'", "{ 'req': ( 'goto.cc', 23, 21 ), 'res': ( 'goto.cc',", "} } RunAfterInitialized( app, test ) def Subcommands_GetType_test(): tests =", "): contents = ReadFile( PathToTestFile( 'FixIt_Clang_cpp11.cpp' ) ) args =", "= common_request request.update( { 'line_num' : test[ 'req' ][ 1", "[ { 'line_num': 12, 'column_num': 2 }, 'Foo' ], [", "'route': '/run_completer_command', } ) @SharedYcmd def RunGoToTest_all( app, folder, command,", "25, 22 ) ] }, # Namespace { 'req': (", "but its # folder is added with -iquote. { 'req':", "12 ), LineColMatcher( 3, 15 ) ) ), 'location': LineColMatcher(", "( 'goto.cc', 32, 26 ) }, # Another_Unicøde { 'req':", "'line_num': 35, 'column_num': 22 }, 'const int' ], [ {", "'line_num': 48, 'column_num': 18 }, 'int' ], # Auto in", "4 }, } subexpression_extract_range = { 'start': { 'line_num': 84,", "def RunGoToTest_all( app, folder, command, test ): filepath = PathToTestFile(", "{ 'line_num': 31, 'column_num': 3 }, 'const Foo &' ],", "}, } raw_string_range = { 'start': { 'line_num': 80, 'column_num':", "22 ) ] }, # Namespace { 'req': ( 'goto.cc',", "17 ) ), ChunkMatcher( ' ', LineColMatcher( 17, 19 ),", "LineColMatcher( 61, 12 ), LineColMatcher( 61, 12 ) ) ),", "), LineColMatcher( 17, 19 ) ), ) } ) )", "ChunkMatcher( ' ', LineColMatcher( 17, 19 ), LineColMatcher( 17, 19", "=> Ns::BasicType<char>' ], # [ { 'line_num': 26, 'column_num': 13", ") ) def FixIt_Check_cpp11_DelAdd( results ): assert_that( results, has_entries( {", "Unresolved, requires /resolve_fixit request has_entries( { 'text': 'Extract subexpression to", "FixIt_Check_objc ], [ 7, 1, 'objective-c', mfile, FixIt_Check_objc_NoFixIt ], [", "'line_num': 16, 'column_num': 0 } ) } ) ) }", "# [ { 'line_num': 31, 'column_num': 16 }, 'const Foo", "] ] for subcommand in [ 'GetDoc', 'GetDocImprecise' ]: for", ") ) def FixIt_Check_cpp11_Del( results ): # Removal of ::", "{ 'line_num': 35, 'column_num': 9 } ), } ), }", "} ), } ) ), 'location': has_entries( { 'line_num': 54,", "8 }, # 'Ns::Type => Ns::BasicType<char>' ], # On \"a\"", "9 ) }, # Local::in_line -> definition/declaration of Local::in_line {", "'int main()' ], [ { 'line_num': 22, 'column_num': 6 },", "'column_num': 13 }, 'Foo *' ], [ { 'line_num': 37,", ") } ) ) def FixIt_Check_cuda( results ): assert_that( results,", "( 'goto.cc', 21, 5 ), 'res': ( 'goto.cc', 19, 5", "'column_num': 9 }, 'Foo' ], [ { 'line_num': 12, 'column_num':", "{ 'line_num': 35, 'column_num': 22 }, 'const int' ], [", "'filetype': 'cpp', 'filepath': file_path }, 'expect': { 'response': requests.codes.ok, 'data':", "54, 'column_num': 51 } ) } ), has_entries( { 'chunks':", "'fixits': contains( # Change to SpellingIsNotMyStrongPoint has_entries( { 'text': contains_string(", ": contents, 'filepath' : file_path, 'command_arguments': [ 'FixIt' ], 'line_num'", "ycmd is distributed in the hope that it will be", "), 'range': has_entries( { 'start': has_entries( { 'line_num': 35, 'column_num':", "=> Ns::BasicType<char>' ], # On \"a\" (Ns::Type) # [ {", "folder, test[ 'req' ][ 0 ] ) common_request = {", ": has_entries( { 'line_num': 21, 'column_num': 11 } ), }", "{ 'line_num': 80, 'column_num': 19 }, 'end': { 'line_num': 80,", "'column_num': 7 }, 'int x = 3', requests.codes.ok ], #", "1 ) }, { 'req': ( 'main.cpp', 6, 11 ),", "'docstring', requests.codes.ok ], # from header [ { 'line_num': 6,", "from ycmd.tests.test_utils import ( BuildRequest, ChunkMatcher, CombineRequest, LineColMatcher, LocationMatcher, ErrorMatcher,", ") } ) ) def FixIt_Check_cpp11_DelAdd( results ): assert_that( results,", "}, 'const struct Foo &' ], # [ { 'line_num':", "): # Similar to FixIt_Check_cpp11_1 but inserts split across lines", "'column_num': 3 } ) } ), has_entries( { 'chunks': contains(", "def RunGetSemanticTest( app, filepath, filetype, test, command, response = requests.codes.ok", "def FixIt_Check_SubexprExtract_Resolved( results ): assert_that( results, has_entries( { 'fixits': contains(", "BuildRequest( **request ) ).json print( 'expected = ' ) print(", "}, { 'req': ( 'goto.cc', 19, 5 ), 'res': (", "} ), 'end' : has_entries( { 'line_num': 40, 'column_num': 9", "definition/declaration of Local::in_line { 'req': ( 'goto.cc', 24, 26 ),", "}, { 'req': ( 'main.cpp', 3, 1 ), 'res': (", "yield RunGoToTest_all, '', 'GoToReferences', test @SharedYcmd def RunGetSemanticTest( app, filepath,", "], [ { 'line_num': 29, 'column_num': 18 }, 'Foo' ],", "ReadFile( PathToTestFile( 'basic.cpp' ) ), 'filepath': PathToTestFile( 'basic.cpp' ), 'command_arguments':", "'chunks': contains( ChunkMatcher( 'auto dummy = foo(i + 3);\\n ',", "is added with -iquote. { 'req': ( 'main.cpp', 4, 10", "from hamcrest import ( assert_that, contains, contains_string, equal_to, has_entries, has_entry,", "on a single line; both with fixits [ 54, 15,", "2, 'column_num': 8 } }, 'route': '/run_completer_command', } ) @SharedYcmd", "}, 'Foo' ], [ { 'line_num': 12, 'column_num': 8 },", "{ 'line_num': 40, 'column_num': 9 } ), } ), }", "13 }, 'const struct Foo' ], # [ { 'line_num':", "{ 'request': args, 'route': '/receive_messages' } RunAfterInitialized( app, receive_diags )", ") ], ] for subcommand in [ 'GetType', 'GetTypeImprecise' ]:", "the GNU General Public License as published by # the", "14 }, 'const Foo *' ], # [ { 'line_num':", "assignment' ), 'chunks': contains( ChunkMatcher( '(', LineColMatcher( 59, 8 ),", "'data': { 'filepath': os.path.abspath( file_path ), 'line_num': 2, 'column_num': 8", "9 } ), } ), } ) ), 'location': has_entries(", "filepath, filetype, test, command, response = requests.codes.ok ): contents =", "{ 'line_num': 21, 'column_num': 11 } ), } ), }", "'cpp11', cfile, FixIt_Check_cpp11_DelAdd ], [ 5, 3, 'objective-c', mfile, FixIt_Check_objc", "Subcommands_GoToDeclaration_all_test(): tests = [ # Local::x -> definition/declaration of x", "Unicøde { 'req': ( 'goto.cc', 34, 9 ), 'res': (", "has_entries( { 'line_num': 40, 'column_num': 6 } ) } )", "print( actual ) assert_that( actual, equal_to( expected ) ) @SharedYcmd", "{ 'line_num': 28, 'column_num': 18 }, 'struct Foo' ], #", "LineColMatcher( 80, 19 ), LineColMatcher( 80, 36 ) ), )", "import requests import os.path from ycmd.tests.clangd import ( IsolatedYcmd, SharedYcmd,", "[ { 'req': ( 'main.cpp', 1, 6 ), 'res': (", "results, has_entries( { 'fixits': contains( # first fix-it at 54,16", "( 'system/a.hpp', 1, 1 ) }, { 'req': ( 'main.cpp',", "# [ { 'line_num': 34, 'column_num': 14 }, 'const Foo'", "'/run_completer_command', BuildRequest( **args ) ).json pprint( results ) check( results", "0 ] ) ), location[ 1 ], location[ 2 ]", "'line_num': 12, 'column_num': 9 }, 'Foo' ], [ { 'line_num':", "54, 'column_num': 58 } ), 'end' : has_entries( { 'line_num':", "FixIt due to forced spell checking [ 72, 9, 'cpp11',", "10 }, 'docstring', requests.codes.ok ], # from header [ {", "'range': has_entries( { 'start': has_entries( { 'line_num': 16, 'column_num': 10", "}, 'objective-c': { 'filetype' : 'objc', }, } args =", "35 }, } tests = [ [ expand_auto_range, FixIt_Check_AutoExpand_Resolved ],", "), } ), ), 'location': has_entries( { 'line_num': 54, 'column_num':", "25 ), 'res': ( 'goto.cc', 32, 54 ) }, {", ") def FixIt_Check_SubexprExtract_Resolved( results ): assert_that( results, has_entries( { 'fixits':", "], # [ { 'line_num': 13, 'column_num': 3 }, 'int'", "single line; both with fixits [ 54, 15, 'cpp11', cfile,", "'line_num': 22, 'column_num': 2 }, 'int main()' ], [ {", "), # Unresolved, requires /resolve_fixit request has_entries( { 'text': 'Extract", "{ 'line_num': 6, 'column_num': 10 }, 'docstring', requests.codes.ok ], #", "2, 11 ) }, # Local::out_of_line -> definition of Local::out_of_line", "-> definition of Local::out_of_line { 'req': ( 'goto.cc', 25, 27", "RunAfterInitialized ) from ycmd.tests.test_utils import ( BuildRequest, ChunkMatcher, CombineRequest, LineColMatcher,", "1, 6 ), 'res': ( 'a.hpp', 1, 1 ) },", "subexpression_extract_range, FixIt_Check_SubexprExtract_Resolved ], [ raw_string_range, FixIt_Check_RawStringReplace_Resolved ], ] for test", "10 ) }, # Local -> definition/declaration of Local {", "} raw_string_range = { 'start': { 'line_num': 80, 'column_num': 19", "Lang File, Checker [ 16, 0, 'cpp11', cfile, FixIt_Check_cpp11_Ins ],", "has_entries( { 'line_num': 40, 'column_num': 9 } ), } ),", "macro_expand_range, FixIt_Check_MacroExpand_Resolved ], [ subexpression_extract_range, FixIt_Check_SubexprExtract_Resolved ], [ raw_string_range, FixIt_Check_RawStringReplace_Resolved", "This test is isolated to trigger objcpp hooks, rather than", "( 'goto.cc', 14, 13 ), ( 'goto.cc', 25, 22 )", "{ 'line_num': 48, 'column_num': 3 } ), 'end' : has_entries(", "{ 'completer_target' : 'filetype_default', 'contents' : contents, 'filepath' : PathToTestFile(", "def Subcommands_GoTo_all_test(): tests = [ # Local::x -> definition/declaration of", "{ 'line_num': 42, 'column_num': 3 }, 'const Foo &' ],", "'line_num': 31, 'column_num': 3 }, 'const Foo &' ], #", "), } ), } ), ), 'location': has_entries( { 'line_num':", "it has_entries( { 'text': contains_string( 'parentheses around the assignment' ),", "'column_num': 53 } ), } ), } ), has_entries( {", "), 'end' : has_entries( { 'line_num': 5, 'column_num': 3 }", "32, 26 ) }, # Another_Unicøde { 'req': ( 'goto.cc',", "# This test is isolated to trigger objcpp hooks, rather", "53, 'column_num': 15 }, matches_regexp( r'int bar\\(int i\\)(?: __attribute__\\(\\(thiscall\\)\\))?' )", "'end': { 'line_num': 80, 'column_num': 35 }, } tests =", "to location' }, { 'req': ( 'main.cpp', 10, 13 ),", ") results = app.post_json( '/run_completer_command', BuildRequest( **args ) ).json pprint(", "FixIt_Check_cpp11_Del ], [ 40, 6, 'cpp11', cfile, FixIt_Check_cpp11_Repl ], [", "}, 'end': { 'line_num': 80, 'column_num': 4 }, } subexpression_extract_range", "from local file [ { 'line_num': 5, 'column_num': 10 },", "'range' : rng, 'filetype' : 'cpp' } app.post_json( '/event_notification', CombineRequest(", "cfile = PathToTestFile( 'FixIt_Clang_cpp11.cpp' ) mfile = PathToTestFile( 'objc', 'FixIt_Clang_objc.m'", "'line_num': 7, 'column_num': 7 }, 'int x = 3', requests.codes.ok", "{ 'replacement_text': equal_to( '=' ), 'range': has_entries( { 'start': has_entries(", "19 } ), } ), } ) ), 'location': has_entries(", ") ) def FixIt_Check_cpp11_InsMultiLine( results ): # Similar to FixIt_Check_cpp11_1", ": has_entries( { 'line_num': 28, 'column_num': 2 } ), }", "__attribute__\\(\\(thiscall\\)\\))?' ) ], [ { 'line_num': 54, 'column_num': 18 },", "'column_num': 15 } ) } ), # second fix-it at", "47, 'column_num': 12 }, 'Foo' ], [ { 'line_num': 47,", "3, 'filepath' : filepath, 'contents' : contents, 'filetype' : filetype", "{ 'line_num': 21, 'column_num': 16 } ) } ) )", "LineColMatcher( 1, 11 ) ), ChunkMatcher( 'Bar', LineColMatcher( 9, 3", "has_entries( { 'fixits': contains( has_entries( { 'text': contains_string( \"change 'int'", "{ 'line_num': 28, 'column_num': 3 }, 'struct Foo &' ],", "'data': LocationMatcher( PathToTestFile( folder, os.path.normpath( response[ 0 ] ) ),", "17, 15 ) ), ChunkMatcher( ' ', LineColMatcher( 17, 17", "ChunkMatcher( 'const char *', LineColMatcher( 80, 1 ), LineColMatcher( 80,", "# Auto in usage # [ { 'line_num': 34, 'column_num':", "**request ) ).json print( 'actual = ' ) print( actual", "}, 'Foo *' ], [ { 'line_num': 29, 'column_num': 18", "default;' ), 'range': has_entries( { 'start': has_entries( { 'line_num': 48,", ") ) } ) }, 'route': '/run_completer_command' } RunAfterInitialized( app,", "has_entries( { 'command': 'clangd.applyTweak' } ) } ) ) }", "'filetype_default', 'command_arguments': [ 'GoToDefinition' ], 'line_num': 10, 'column_num': 3, 'filetype':", "13 ) }, # test -> definition and declaration of", ": filepath, 'command_arguments': [ command ], 'contents' : ReadFile( filepath", "3, 1 ), 'res': ( 'quote/b.hpp', 1, 1 ) },", "), ChunkMatcher( ' ', LineColMatcher( 17, 19 ), LineColMatcher( 17,", "'GetTypeImprecise', 'GoTo', 'GoToDeclaration', 'GoToDefinition', 'GoToImprecise', 'GoToInclude', 'GoToReferences', 'RefactorRename', 'RestartServer' ]", "# This file is part of ycmd. # # ycmd", "'const char *', LineColMatcher( 80, 1 ), LineColMatcher( 80, 6", "'FixIt', 'Format', 'GetDoc', 'GetDocImprecise', 'GetType', 'GetTypeImprecise', 'GoTo', 'GoToDeclaration', 'GoToDefinition', 'GoToImprecise',", "'column_num': 19 } ), } ), } ) ), 'location':", "} ) ) def FixIt_Check_cpp11_SpellCheck( results ): assert_that( results, has_entries(", "'SpellingIsNotMyStrongPoint', LineColMatcher( 72, 9 ), LineColMatcher( 72, 35 ) )", "'cuda': { 'filetype' : 'cuda', }, 'objective-c': { 'filetype' :", "= app.post_json( '/run_completer_command', BuildRequest( **args ) ).json pprint( results )", ") ) } ) ) def FixIt_Check_MacroExpand_Resolved( results ): assert_that(", "{ 'line_num': 12, 'column_num': 8 }, 'Foo' ], [ {", "# Function # [ { 'line_num': 22, 'column_num': 2 },", "( 'main.cpp', 10, 13 ), 'res': 'Cannot jump to location'", ") @SharedYcmd def RunGoToTest_all( app, folder, command, test ): filepath", "], 'line_num': 17, 'column_num': 4, }, 'expect': { 'response': requests.codes.ok,", "'column_num': 3 } ), 'end' : has_entries( { 'line_num': 48,", "'line_num' : line, 'column_num' : column, } args.update( language_options[ lang", "contains( has_entries( { 'chunks': contains( has_entries( { 'replacement_text': equal_to( '='", "} ) ) } ) ) def FixIt_Check_RawStringReplace_Resolved( results ):", "tests: yield ( RunGetSemanticTest, PathToTestFile( 'GetDoc_Clang_test.cc' ), 'cpp', test, [", "has_entries( { 'line_num': 48, 'column_num': 3 } ) } ),", "10, 'column_num': 3, 'filetype': 'objcpp', 'filepath': file_path }, 'expect': {", "'/defined_subcommands', } ) @SharedYcmd def Subcommands_GoTo_ZeroBasedLineAndColumn_test( app ): file_path =", "test[ 2 ], test[ 3 ], test[ 4 ] @WithRetry", "), 'command_arguments': [ 'RefactorRename', 'Bar' ], 'line_num': 17, 'column_num': 4,", "expected = has_entry( 'message', test[ 1 ] ) else: expected", "results ) check( results ) def FixIt_Check_cpp11_Ins( results ): #", "'line_num': 28, 'column_num': 11 }, 'struct Foo &' ], [", "5, 'column_num': 3 } ), } ), } ) ),", "3, 12 ), LineColMatcher( 3, 15 ) ) ), 'location':", "= PathToTestFile( 'unicode.cc' ) tests = [ # L #", "'column_num': 16 }, 'const Foo *' ], # Auto in", "( 'quote/b.hpp', 1, 1 ) }, # FIXME: should fail", "'GoTo_Clang_ZeroBasedLineAndColumn_test.cc' ) RunAfterInitialized( app, { 'request': { 'completer_target': 'filetype_default', 'line_num':", "{ 'line_num': 48, 'column_num': 3 } ) } ), )", "5, 3, 'objective-c', mfile, FixIt_Check_objc ], [ 7, 1, 'objective-c',", "contains( has_entries( { 'replacement_text': equal_to( 'id' ), 'range': has_entries( {", "'filetype' : 'cpp' } app.post_json( '/event_notification', CombineRequest( args, { 'event_name':", "'line_num': 5, 'column_num': 10 }, 'docstring', requests.codes.ok ], # from", "1 ), } ), # Second note: change to ==", ") ), 'location': has_entries( { 'line_num': 5, 'column_num': 3 }", "File, Checker [ 16, 0, 'cpp11', cfile, FixIt_Check_cpp11_Ins ], [", "file_path }, 'expect': { 'response': requests.codes.ok, 'data': { 'filepath': os.path.abspath(", "equal_to( 'static_cast<int>(' ), 'range': has_entries( { 'start': has_entries( { 'line_num':", "has_entry( 'message', test[ 1 ] ) else: expected = test[", ") ).json print( 'Resolved fixit response = ' ) print(", "[ 'ExecuteCommand', 'FixIt', 'Format', 'GetDoc', 'GetDocImprecise', 'GetType', 'GetTypeImprecise', 'GoTo', 'GoToDeclaration',", "\"change 'SpellingIsNotMyStringPiont' to \" \"'SpellingIsNotMyStrongPoint'\" ), 'chunks': contains( ChunkMatcher( 'SpellingIsNotMyStrongPoint',", "} ) ) } ) ) def FixIt_Check_cpp11_Note( results ):", "[ 54, 51, 'cpp11', cfile, FixIt_Check_cpp11_MultiSecond ], # unicode in", "), } ), } ), has_entries( { 'replacement_text': equal_to( ')'", "3 }, 'Foo' ], [ { 'line_num': 39, 'column_num': 11", ") ] }, # Namespace { 'req': ( 'goto.cc', 24,", "14 }, 'end': { 'line_num': 84, 'column_num': 20 }, }", "12, 'column_num': 2 }, 'Foo' ], [ { 'line_num': 12,", "assert_that( actual, equal_to( expected ) ) @SharedYcmd def Subcommands_RefactorRename_test( app", "( 'main.cpp', 5, 11 ), 'res': ( 'system/c.hpp', 1, 1", "], location[ 2 ] ) for location in response ]", "), LineColMatcher( 60, 9 ) ) ), 'location': LineColMatcher( 60,", "'range': has_entries( { 'start': has_entries( { 'line_num': 54, 'column_num': 64", "subcommand ] ) def Subcommands_GetDoc_test(): tests = [ # from", "'column_num': 6 } ), 'end' : has_entries( { 'line_num': 40,", "'goto.cc', 24, 16 ), 'res': ( 'goto.cc', 2, 11 )", "20 }, 'int' ], # Unicode [ { 'line_num': 51,", "\"Expand macro 'DECLARE_INT'\", 'chunks': contains( ChunkMatcher( 'int i', LineColMatcher( 83,", "no fixits assert_that( results, equal_to( { 'fixits': [] } )", "tests: yield RunFixItTest, test[ 0 ], test[ 1 ], test[", "matches_regexp( r'int bar\\(int i\\)(?: __attribute__\\(\\(thiscall\\)\\))?' ) ], ] for subcommand", "has_entries( { 'line_num': 54, 'column_num': 53 } ), } ),", "} ) ) } ) ) def FixIt_Check_cpp11_DelAdd( results ):", "int' ], [ { 'line_num': 36, 'column_num': 13 }, 'Foo'", "'command_arguments': [ 'FixIt' ], 'line_num' : 16, 'column_num' : 1,", "= expected[ 'fixits' ][ 0 ] actual = app.post_json( '/resolve_fixit',", "subcommand ], test[ 2 ] ) @SharedYcmd def RunFixItTest( app,", "} ), ) } ) ) def FixIt_Check_cpp11_MultiSecond( results ):", "= response[ 'fixits' ][ 0 ] response = app.post_json( '/resolve_fixit',", "), LineColMatcher( 83, 17 ) ), ) } ) )", "cmd in [ 'GoToDefinition', 'GoTo', 'GoToImprecise' ]: yield RunGoToTest_all, '',", ") ) } ) ) def FixIt_Check_cpp11_InsMultiLine( results ): #", "to location' }, ] for test in tests: yield RunGoToTest_all,", "'range': has_entries( { 'start': has_entries( { 'line_num': 21, 'column_num': 9", "pprint import pprint import requests import os.path from ycmd.tests.clangd import", "RunAfterInitialized( app, receive_diags ) diags = RunAfterInitialized( app, test )", "has_entries( { 'replacement_text': equal_to( '' ), 'range': has_entries( { 'start':", "'GetType', 'GetTypeImprecise' ]: for test in tests: yield ( RunGetSemanticTest,", "'req': ( 'goto.cc', 14, 21 ), 'res': [ ( 'goto.cc',", "ycmd. # # ycmd is free software: you can redistribute", "'column_num': 3 }, 'Foo *' ], # [ { 'line_num':", ") ).json print( 'expected = ' ) print( expected )", "}, 'Foo' ], [ { 'line_num': 36, 'column_num': 19 },", "): assert_that( results, has_entries( { 'fixits': contains( has_entries( { 'text':", "ChunkMatcher( ')', LineColMatcher( 61, 12 ), LineColMatcher( 61, 12 )", "'filetype' : 'cuda', }, 'objective-c': { 'filetype' : 'objc', },", "a single line; both with fixits [ 54, 15, 'cpp11',", "app, { 'request': { 'contents': ReadFile( file_path ), 'completer_target': 'filetype_default',", "yield RunGoToTest_all, '', 'GoToDeclaration', test def Subcommands_GoToInclude_test(): tests = [", "{ 'line_num': 80, 'column_num': 1 }, 'end': { 'line_num': 80,", ") for location in response ] ) } elif isinstance(", "'FileReadyToParse', } ), expect_errors = True ) WaitUntilCompleterServerReady( app, 'cpp'", ") def FixIt_Check_cuda( results ): assert_that( results, has_entries( { 'fixits':", "].lower(): receive_diags = { 'request': args, 'route': '/receive_messages' } RunAfterInitialized(", "'line_num' : test[ 'req' ][ 1 ], 'column_num': test[ 'req'", "10 }, 'docstring', requests.codes.ok ], # no docstring [ {", "} ) ), 'location': has_entries( { 'line_num': 54, 'column_num': 51", "}, { 'req': ( 'main.cpp', 5, 11 ), 'res': (", "{ 'text': contains_string( '==' ), 'chunks': contains( ChunkMatcher( '==', LineColMatcher(", "), 'location': has_entries( { 'line_num': 48, 'column_num': 3 } )", "{ 'text': 'Extract subexpression to variable', 'chunks': contains( ChunkMatcher( 'auto", "'line_num': 48, 'column_num': 3 } ) } ), ) }", "3, 'filetype': 'objcpp', 'filepath': file_path }, 'expect': { 'response': requests.codes.ok,", "} ) } ), has_entries( { 'chunks': contains( has_entries( {", "# i C # n o # e l Lang", "= ' ) print( actual ) assert_that( actual, equal_to( expected", "# Change to SpellingIsNotMyStrongPoint has_entries( { 'text': contains_string( \"change 'SpellingIsNotMyStringPiont'", ": line, 'column_num' : column, } args.update( language_options[ lang ]", "o # e l Lang File, Checker [ 16, 0,", "{ 'fixits': contains( has_entries( { 'chunks': contains( ChunkMatcher( 'Bar', LineColMatcher(", "args = { 'completer_target' : 'filetype_default', 'contents' : contents, 'filepath'", "}, 'Foo *' ], [ { 'line_num': 37, 'column_num': 20", "{ 'fixits': contains( has_entries( { 'text': 'Convert to raw string',", "{ 'fixits': contains( has_entries( { 'text': \"Expand auto type\", 'chunks':", "expected = app.post_json( '/run_completer_command', BuildRequest( **request ) ).json print( 'expected", "29, 'column_num': 11 }, 'Foo *' ], [ { 'line_num':", "LineColMatcher( 80, 1 ), LineColMatcher( 80, 6 ) ), )", "x { 'req': ( 'goto.cc', 23, 21 ), 'res': (", "}, 'int' ], [ { 'line_num': 13, 'column_num': 7 },", "from ycmd.utils import ReadFile # This test is isolated to", "26, 'column_num': 13 }, # 'Ns::Type => Ns::BasicType<char>' ], #", "15 }, 'Foo' ], [ { 'line_num': 40, 'column_num': 3", ") @SharedYcmd def RunFixItTest( app, line, column, lang, file_path, check", "'column_num': 2 } ), 'end' : has_entries( { 'line_num': 28,", "'end': { 'line_num': 80, 'column_num': 4 }, } subexpression_extract_range =", "*' ], [ { 'line_num': 37, 'column_num': 20 }, 'int'", "), ( 'goto.cc', 23, 14 ), ( 'goto.cc', 24, 15", "{ 'line_num': 31, 'column_num': 16 }, 'const Foo &' ],", ") def FixIt_Check_MacroExpand_Resolved( results ): assert_that( results, has_entries( { 'fixits':", "for test in tests: yield RunFixItTest, test[ 0 ], test[", ") ).json args[ 'fixit' ] = response[ 'fixits' ][ 0", "response = ' ) print( response ) expected( response )", "[ # Function { 'req': ( 'goto.cc', 14, 21 ),", "has_entries( { 'start': has_entries( { 'line_num': 48, 'column_num': 3 }", "LineColMatcher( 72, 9 ), } ) ) } ) )", "), LineColMatcher( 3, 15 ) ) ), 'location': LineColMatcher( 3,", "[ 3, 12, 'cuda', cufile, FixIt_Check_cuda ], # multiple errors", "has_entries( { 'chunks': contains( has_entries( { 'replacement_text': equal_to( '=' ),", "yield RunGoToTest_all, '', cmd, test def Subcommands_GoToDeclaration_all_test(): tests = [", "True ) WaitUntilCompleterServerReady( app, 'cpp' ) expected = app.post_json( '/run_completer_command',", "'fixits': contains( has_entries( { 'text': \"Expand auto type\", 'chunks': contains(", "( 'goto.cc', 14, 13 ) }, # test -> definition", "}, 'end': { 'line_num': 84, 'column_num': 20 }, } macro_expand_range", "requests.codes.ok ], # no docstring [ { 'line_num': 7, 'column_num':", "): test = { 'request': { 'filetype': 'cpp', 'completer_target': 'filetype_default',", "{ 'response': requests.codes.ok, 'data': LocationMatcher( PathToTestFile( folder, os.path.normpath( response[ 0", "], [ { 'line_num': 12, 'column_num': 10 }, 'Foo' ],", "[ ( 'goto.cc', 11, 10 ), ( 'goto.cc', 14, 13", "10, 'column_num': 3, 'filetype': 'cpp', 'filepath': file_path }, 'expect': {", "( RunGetSemanticTest, PathToTestFile( 'GetType_Clang_test.cc' ), 'cpp', test, [ subcommand ]", "{ 'text': contains_string( 'parentheses around the assignment' ), 'chunks': contains(", "'goto.cc', 38, 3 ), 'res': ( 'goto.cc', 36, 28 )", ") ) }, 'route': '/defined_subcommands', } ) @SharedYcmd def Subcommands_GoTo_ZeroBasedLineAndColumn_test(", "18 }, matches_regexp( r'int bar\\(int i\\)(?: __attribute__\\(\\(thiscall\\)\\))?' ) ], ]", "'line_num': 35, 'column_num': 7 } ), 'end' : has_entries( {", "11 } ), } ), } ) ), 'location': has_entries(", "else: expected = test[ 1 ] request = common_args request.update(", "{ 'request': { 'completer_target': 'filetype_default', 'line_num': 10, 'column_num': 3, 'filetype':", "contains( *sorted( [ 'ExecuteCommand', 'FixIt', 'Format', 'GetDoc', 'GetDocImprecise', 'GetType', 'GetTypeImprecise',", "}, # 'Ns::Type => Ns::BasicType<char>' ], # Cursor on decl", "'line_num': 53, 'column_num': 15 }, matches_regexp( r'int bar\\(int i\\)(?: __attribute__\\(\\(thiscall\\)\\))?'", "), 'location': LineColMatcher( 60, 1 ), } ), # Second", "app, filepath, filetype, test, command, response = requests.codes.ok ): contents", "'line_num': 84, 'column_num': 20 }, } macro_expand_range = { 'start':", "'RestartServer' ] ) ) }, 'route': '/defined_subcommands', } ) @SharedYcmd", "RunGoToTest_all( app, folder, command, test ): filepath = PathToTestFile( folder,", "Another_Unicøde { 'req': ( 'goto.cc', 36, 17 ), 'res': (", "'line_num': 40, 'column_num': 9 } ), } ), } )", "}, 'const struct Foo *' ], # [ { 'line_num':", "'filetype' : 'cpp' } request = common_request request.update( { 'line_num'", "10 } ), 'end' : has_entries( { 'line_num': 16, 'column_num':", "'fixit_test.cu' ) ufile = PathToTestFile( 'unicode.cc' ) tests = [", "{ 'text': contains_string( \"change 'int' to 'void'\" ), 'chunks': contains(", "( 'goto.cc', 14, 13 ) }, # GoToDeclaration alternates between", "i C # n o # e l Lang File,", "=> Ns::BasicType<char>' ], # Cursor on decl for refs &", "has_entries( { 'start': has_entries( { 'line_num': 48, 'column_num': 9 }", "{ 'response': requests.codes.ok, 'data': has_entries( { 'fixits': contains( has_entries( {", "= ' ) print( response ) expected( response ) def", "General Public License # along with ycmd. If not, see", "'basic.cpp' ), 'command_arguments': [ 'RefactorRename', 'Bar' ], 'line_num': 17, 'column_num':", "), 'res': ( 'a.hpp', 1, 1 ) }, { 'req':", "# # ycmd is free software: you can redistribute it", "'const Foo &' ], # [ { 'line_num': 32, 'column_num':", "app.post_json( '/event_notification', CombineRequest( request, { 'event_name': 'FileReadyToParse', } ), expect_errors", "'location': has_entries( { 'line_num': 5, 'column_num': 3 } ) }", "{ 'fixits': contains( # first fix-it at 54,16 has_entries( {", "FixIt_Check_unicode_Ins( results ): assert_that( results, has_entries( { 'fixits': contains( has_entries(", "= ReadFile( filepath ) common_args = { 'completer_target' : 'filetype_default',", "has_entries( { 'line_num': 16, 'column_num': 10 } ), 'end' :", "'Foo' ], # [ { 'line_num': 31, 'column_num': 3 },", "of :: assert_that( results, has_entries( { 'fixits': contains( has_entries( {", "{ 'line_num': 34, 'column_num': 21 }, 'const int' ], #", "ReadFile( filepath ) common_args = { 'completer_target' : 'filetype_default', 'command_arguments':", "( 'goto.cc', 24, 16 ), 'res': ( 'goto.cc', 2, 11", "'GoToImprecise' ]: yield RunGoToTest_all, '', cmd, test def Subcommands_GoToDeclaration_all_test(): tests", ": 10, 'column_num' : 3, 'filepath' : filepath, 'contents' :", "], [ 48, 3, 'cpp11', cfile, FixIt_Check_cpp11_DelAdd ], [ 5,", "lang, file_path, check ): contents = ReadFile( file_path ) language_options", "PathToTestFile( 'objc', 'FixIt_Clang_objc.m' ) cufile = PathToTestFile( 'cuda', 'fixit_test.cu' )", ") ) args = { 'completer_target' : 'filetype_default', 'contents' :", "24, 15 ), ( 'goto.cc', 25, 15 ) ] },", "'filepath': os.path.abspath( file_path ), 'line_num': 2, 'column_num': 8 } },", "= { 'start': { 'line_num': 84, 'column_num': 14 }, 'end':", "5 ), 'res': ( 'goto.cc', 19, 5 ) }, {", "declaration of Local::out_of_line { 'req': ( 'goto.cc', 25, 27 ),", "21, 'column_num': 16 } ) } ) ) } )", "a Note) [ 60, 1, 'cpp11', cfile, FixIt_Check_cpp11_Note ], #", "jump to location' }, ] for test in tests: for", "'goto.cc', 2, 11 ) }, # Local::out_of_line -> declaration of", "} ), } ), } ), ), 'location': has_entries( {", "36 ) ), ) } ) ) } ) )", "// expected-error{{explicit conversion to}} assert_that( results, has_entries( { 'fixits': contains(", "char *', LineColMatcher( 80, 1 ), LineColMatcher( 80, 6 )", "PathToTestFile( 'cuda', 'fixit_test.cu' ) ufile = PathToTestFile( 'unicode.cc' ) tests", "of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See", "'column_num': 4 } ), } ), } ), has_entries( {", "), ), 'location': has_entries( { 'line_num': 48, 'column_num': 3 }", "): # First fixit # switch(A()) { // expected-error{{explicit conversion", "'column_num': 51 } ) } ), # second fix-it at", "), 'res': ( 'quote/b.hpp', 1, 1 ) }, # FIXME:", "# Auto in declaration # [ { 'line_num': 28, 'column_num':", "os.path from ycmd.tests.clangd import ( IsolatedYcmd, SharedYcmd, PathToTestFile, RunAfterInitialized )", "@IsolatedYcmd() def Subcommands_DefinedSubcommands_test( app ): file_path = PathToTestFile( 'GoTo_Clang_ZeroBasedLineAndColumn_test.cc' )", "= True ) WaitUntilCompleterServerReady( app, 'cpp' ) expected = app.post_json(", "has_entries( { 'chunks': contains( has_entries( { 'replacement_text': equal_to( '' ),", "1 ], response[ 2 ] ) } else: expect =", "import ( BuildRequest, ChunkMatcher, CombineRequest, LineColMatcher, LocationMatcher, ErrorMatcher, WithRetry, WaitUntilCompleterServerReady", ") } ) ) def FixIt_Check_cpp11_Repl( results ): assert_that( results,", ") ), 'location': LineColMatcher( 60, 1 ), } ), #", ") }, # Local::in_line -> definition/declaration of Local::in_line { 'req':", "jump to location' }, { 'req': ( 'main.cpp', 10, 13", "'==' ), 'chunks': contains( ChunkMatcher( '==', LineColMatcher( 60, 8 ),", "results, has_entries( { 'fixits': contains( # Change to SpellingIsNotMyStrongPoint has_entries(", "the terms of the GNU General Public License as published", ") } elif isinstance( response, tuple ): expect = {", "], # FixIt due to forced spell checking [ 72,", "for test in tests: yield RunGoToTest_all, '', 'GoToReferences', test @SharedYcmd", "'Foo' ], # [ { 'line_num': 42, 'column_num': 3 },", "], [ { 'line_num': 37, 'column_num': 20 }, 'int' ],", "15, 11 ) ), ChunkMatcher( ' ', LineColMatcher( 15, 46", "28 ) }, # Expected failures { 'req': ( 'goto.cc',", "'parentheses around the assignment' ), 'chunks': contains( ChunkMatcher( '(', LineColMatcher(", "for test in tests: for cmd in [ 'GoToDefinition', 'GoTo',", "= PathToTestFile( 'FixIt_Clang_cpp11.cpp' ) request = { 'completer_target' : 'filetype_default',", "'int' ], # [ { 'line_num': 15, 'column_num': 7 },", ") def FixIt_Check_unicode_Ins( results ): assert_that( results, has_entries( { 'fixits':", "since b.hpp is included with angled brackets but its #", "FixIt_Check_cpp11_Ins( results ): # First fixit # switch(A()) { //", "), ChunkMatcher( ' ', LineColMatcher( 15, 46 ), LineColMatcher( 16,", "17 }, 'int' ], [ { 'line_num': 48, 'column_num': 12", "string', 'chunks': contains( ChunkMatcher( 'R\"(\\\\\\\\r\\\\asd\\n\\\\v)\"', LineColMatcher( 80, 19 ), LineColMatcher(", "'goto.cc', 21, 5 ) }, # Unicøde { 'req': (", "40, 'column_num': 18 }, 'Foo' ], # [ { 'line_num':", "[ 'FixIt' ], 'range' : rng, 'filetype' : 'cpp' }", "file_path ), 'completer_target': 'filetype_default', 'command_arguments': [ 'GoToDefinition' ], 'line_num': 10,", "] ) ), location[ 1 ], location[ 2 ] )", "*' ], # Auto in usage # [ { 'line_num':", "'expected = ' ) print( expected ) request[ 'fixit' ]", "ChunkMatcher( '\\n\\n', LineColMatcher( 12, 2 ), LineColMatcher( 15, 1 )", "[ { 'line_num': 51, 'column_num': 13 }, 'Unicøde *' ],", "ReadFile( filepath ), 'filetype' : 'cpp' } request = common_request", "'Cannot jump to location' }, ] for test in tests:", "LineColMatcher( 3, 12 ), } ) ) } ) )", "} ) ), 'location': has_entries( { 'line_num': 25, 'column_num': 14", "LineColMatcher( 12, 2 ), LineColMatcher( 15, 1 ) ), ChunkMatcher(", "{ 'line_num': 16, 'column_num': 13 } ), } ), }", "Public License # along with ycmd. If not, see <http://www.gnu.org/licenses/>.", "), } ) ), 'location': has_entries( { 'line_num': 16, 'column_num':", "FixIt_Check_cpp11_DelAdd( results ): assert_that( results, has_entries( { 'fixits': contains( has_entries(", "), ), 'location': has_entries( { 'line_num': 54, 'column_num': 51 }", "84, 'column_num': 14 }, 'end': { 'line_num': 84, 'column_num': 20", "'res': ( 'goto.cc', 14, 13 ) }, # test ->", "hooks, rather than fetching completer # from cache. @IsolatedYcmd() def", "BaseMatcher from hamcrest import ( assert_that, contains, contains_string, equal_to, has_entries,", "{ 'line_num': 29, 'column_num': 11 }, 'Foo *' ], [", "], ] for subcommand in [ 'GetType', 'GetTypeImprecise' ]: for", "division from hamcrest.core.base_matcher import BaseMatcher from hamcrest import ( assert_that,", "}, # Local -> definition/declaration of Local { 'req': (", "pick up an __attribute__((thiscall)) to annotate their # calling convention.", "] request = common_args request.update( args ) test = {", "= has_entry( 'message', contains_string( test[ 1 ] ) ) else:", "has_entries( { 'fixits': contains( has_entries( { 'chunks': contains( ChunkMatcher( 'Bar',", "for cmd in [ 'GoToDefinition', 'GoTo', 'GoToImprecise' ]: yield RunGoToTest_all,", "'Ns::Type => Ns::BasicType<char>' ], # [ { 'line_num': 26, 'column_num':", "'range': has_entries( { 'start': has_entries( { 'line_num': 5, 'column_num': 3", "64 } ), 'end' : has_entries( { 'line_num': 54, 'column_num':", "FixIt_Check_cpp11_MultiSecond ], # unicode in line for fixit [ 21,", "actual, equal_to( expected ) ) @SharedYcmd def Subcommands_RefactorRename_test( app ):", "'end' : has_entries( { 'line_num': 40, 'column_num': 9 } ),", "} ) ) def FixIt_Check_cpp11_MultiFirst( results ): assert_that( results, has_entries(", "expand_auto_range = { 'start': { 'line_num': 80, 'column_num': 1 },", "up in the type, which isn't ideal, but # also", "r'int bar\\(int i\\)(?: __attribute__\\(\\(thiscall\\)\\))?' ) ], [ { 'line_num': 54,", "to raw string', 'chunks': contains( ChunkMatcher( 'R\"(\\\\\\\\r\\\\asd\\n\\\\v)\"', LineColMatcher( 80, 19", "= { 'start': { 'line_num': 80, 'column_num': 1 }, 'end':", "request, { 'event_name': 'FileReadyToParse', } ), expect_errors = True )", "][ 0 ] ) common_request = { 'completer_target' : 'filetype_default',", "7, 1, 'objective-c', mfile, FixIt_Check_objc_NoFixIt ], [ 3, 12, 'cuda',", "LineColMatcher( 3, 15 ) ) ), 'location': LineColMatcher( 3, 12", ") from ycmd.tests.test_utils import ( BuildRequest, ChunkMatcher, CombineRequest, LineColMatcher, LocationMatcher,", "59, 8 ), LineColMatcher( 59, 8 ) ), ChunkMatcher( ')',", "line, 'column_num' : column, } args.update( language_options[ lang ] )", "import ReadFile # This test is isolated to trigger objcpp", "'completer_target' : 'filetype_default', 'contents' : ReadFile( filename ), 'filepath' :", "Foo &' ], # [ { 'line_num': 31, 'column_num': 16", "the type, which isn't ideal, but # also prohibitively complex", "}, { 'req': ( 'goto.cc', 11, 10 ), 'res': (", "ycmd.tests.clangd import ( IsolatedYcmd, SharedYcmd, PathToTestFile, RunAfterInitialized ) from ycmd.tests.test_utils", "3 ), LineColMatcher( 17, 6 ) ), ChunkMatcher( '', LineColMatcher(", "'req': ( 'goto.cc', 23, 21 ), 'res': ( 'goto.cc', 4,", "}, 'Foo *' ], # [ { 'line_num': 29, 'column_num':", "file_path }, 'expect': { 'response': requests.codes.ok, 'data': contains( *sorted( [", "filepath = PathToTestFile( folder, test[ 'req' ][ 0 ] )", ": has_entries( { 'line_num': 35, 'column_num': 9 } ), }", "48, 'column_num': 9 } ), 'end' : has_entries( { 'line_num':", "contains( has_entries( { 'replacement_text': equal_to( 'static_cast<int>(' ), 'range': has_entries( {", "has_entries( { 'start': has_entries( { 'line_num': 54, 'column_num': 16 }", "54, 'column_num': 67 } ), } ), } ) ),", "LineColMatcher( 60, 8 ), LineColMatcher( 60, 9 ) ) ),", "( BuildRequest, ChunkMatcher, CombineRequest, LineColMatcher, LocationMatcher, ErrorMatcher, WithRetry, WaitUntilCompleterServerReady )", "), 'end' : has_entries( { 'line_num': 26, 'column_num': 7 }", "9, 3 ), LineColMatcher( 9, 6 ) ), ChunkMatcher( '\\n\\n',", "}, 'end': { 'line_num': 80, 'column_num': 35 }, } tests", "'GoToDefinition', 'GoToImprecise', 'GoToInclude', 'GoToReferences', 'RefactorRename', 'RestartServer' ] ) ) },", "along with ycmd. If not, see <http://www.gnu.org/licenses/>. from __future__ import", "yield ( RunGetSemanticTest, PathToTestFile( 'GetType_Clang_test.cc' ), 'cpp', test, [ subcommand", "'start': has_entries( { 'line_num': 28, 'column_num': 2 } ), 'end'", "), ChunkMatcher( '\\n\\n', LineColMatcher( 12, 2 ), LineColMatcher( 15, 1", "54, 'column_num': 15 } ) } ), has_entries( { 'chunks':", "fixit response = ' ) print( response ) expected( response", "'line_num': 54, 'column_num': 51 } ) } ), has_entries( {", ") } ), has_entries( { 'chunks': contains( has_entries( { 'replacement_text':", "'GoTo', 'GoToDeclaration', 'GoToDefinition', 'GoToImprecise', 'GoToInclude', 'GoToReferences', 'RefactorRename', 'RestartServer' ] )", "): expect = { 'response': requests.codes.ok, 'data': LocationMatcher( PathToTestFile( folder,", "[ { 'line_num': 48, 'column_num': 18 }, 'int' ], #", "has_entries( { 'start': has_entries( { 'line_num': 16, 'column_num': 10 }", "16, 'column_num': 10 } ), } ), } ), has_entries(", "), 'chunks': contains( ChunkMatcher( '(', LineColMatcher( 59, 8 ), LineColMatcher(", "checking [ 72, 9, 'cpp11', cfile, FixIt_Check_cpp11_SpellCheck ], ] for", "def RunRangedFixItTest( app, rng, expected ): contents = ReadFile( PathToTestFile(", "has_entries( { 'start': has_entries( { 'line_num': 54, 'column_num': 52 }", ") }, { 'req': ( 'main.cpp', 3, 1 ), 'res':", "results = app.post_json( '/run_completer_command', BuildRequest( **args ) ).json pprint( results", "# 'Ns::Type => Ns::BasicType<char>' ], # [ { 'line_num': 26,", "has_entries( { 'line_num': 54, 'column_num': 67 } ), } ),", "[ { 'line_num': 6, 'column_num': 10 }, 'docstring', requests.codes.ok ],", "expect_errors = True ) WaitUntilCompleterServerReady( app, 'cpp' ) expected =", "'line_num': 54, 'column_num': 16 } ), 'end' : has_entries( {", "response, tuple ): expect = { 'response': requests.codes.ok, 'data': LocationMatcher(", "1 }, 'end': { 'line_num': 80, 'column_num': 4 }, }", "results ): assert_that( results, has_entries( { 'fixits': contains( # first", ").json pprint( results ) check( results ) def FixIt_Check_cpp11_Ins( results", "'\\n\\n', LineColMatcher( 12, 2 ), LineColMatcher( 15, 1 ) ),", "'line_num': 37, 'column_num': 20 }, 'int' ], # Unicode [", "[ # L # i C # n o #", "# [ { 'line_num': 15, 'column_num': 7 }, 'char' ],", "42, 'column_num': 16 }, 'const struct Foo &' ], #", "'column_num': 7 } ), 'end' : has_entries( { 'line_num': 26,", "], [ { 'line_num': 12, 'column_num': 8 }, 'Foo' ],", "assert_that( results, has_entries( { 'fixits': contains( # First note: put", "{ 'chunks': contains( has_entries( { 'replacement_text': equal_to( 'foo' ), 'range':", "Foo *' ], # [ { 'line_num': 32, 'column_num': 16", "'test-include', cmd, test def Subcommands_GoToReferences_test(): tests = [ # Function", "RunGoToTest_all, 'test-include', cmd, test def Subcommands_GoToReferences_test(): tests = [ #", "), expect_errors = True ) WaitUntilCompleterServerReady( app, 'cpp' ) response", ") ).json pprint( results ) check( results ) def FixIt_Check_cpp11_Ins(", "foo(i + 3);\\n ', LineColMatcher( 84, 3 ), LineColMatcher( 84,", "54, 'column_num': 18 }, matches_regexp( r'int bar\\(int i\\)(?: __attribute__\\(\\(thiscall\\)\\))?' )", ") ), 'location': has_entries( { 'line_num': 54, 'column_num': 51 }", "[ { 'line_num': 43, 'column_num': 3 }, 'const Foo *'", "print( 'expected = ' ) print( expected ) request[ 'fixit'", "expected[ 'fixits' ][ 0 ] actual = app.post_json( '/resolve_fixit', BuildRequest(", "{ 'line_num': 54, 'column_num': 58 } ), } ), }", ") def FixIt_Check_cpp11_MultiSecond( results ): assert_that( results, has_entries( { 'fixits':", "# # You should have received a copy of the", "( assert_that, contains, contains_string, equal_to, has_entries, has_entry, matches_regexp ) from", "), 'res': 'Cannot jump to location' }, ] for test", "18 }, 'Foo' ], # [ { 'line_num': 42, 'column_num':", "], # [ { 'line_num': 29, 'column_num': 3 }, 'Foo", "'~' ), 'range': has_entries( { 'start': has_entries( { 'line_num': 54,", "'column_num': 51 } ) } ), has_entries( { 'chunks': contains(", "'GoTo_Clang_ZeroBasedLineAndColumn_test.cc' ) RunAfterInitialized( app, { 'request': { 'contents': ReadFile( file_path", "*[ LocationMatcher( PathToTestFile( folder, os.path.normpath( location[ 0 ] ) ),", "22, 'column_num': 6 }, 'int main()' ], # Declared and", "8 ), LineColMatcher( 60, 9 ) ) ), 'location': LineColMatcher(", "'chunks': contains( has_entries( { 'replacement_text': equal_to( 'static_cast<int>(' ), 'range': has_entries(", "between definition and declaration { 'req': ( 'goto.cc', 14, 13" ]
[ "#Elasticsearch settings self.elasticsearch_host = \"\" self.elasticsearch_verify_certs = False self.elasticsearch_index_name =", "of the JSON file. \"\"\" with open(filepath, \"r\") as file:", "\"\"\"Loads the config from a JSON file. Args: filepath: path", "JSON file. Args: filepath: path of the JSON file. \"\"\"", "= 512 self.sleep_idle_secs = 5 self.sleep_not_idle_secs = 0.01 self.log_level =", "scoring tool \"\"\" import jsonpickle class Config(object): \"\"\"Container for sentiment", "\"\"\" with open(filepath, \"r\") as file: json = file.read() config", "\"\"\" import jsonpickle class Config(object): \"\"\"Container for sentiment scoring tool", "file. Args: filepath: path of the JSON file. \"\"\" with", "the config from a JSON file. Args: filepath: path of", "a JSON file. Args: filepath: path of the JSON file.", "import jsonpickle class Config(object): \"\"\"Container for sentiment scoring tool settings.", "jsonpickle class Config(object): \"\"\"Container for sentiment scoring tool settings. \"\"\"", "False self.elasticsearch_index_name = \"\" self.elasticsearch_batch_size = 500 self.elasticsearch_timeout_secs = 30", "settings self.elasticsearch_host = \"\" self.elasticsearch_verify_certs = False self.elasticsearch_index_name = \"\"", "self.elasticsearch_index_name = \"\" self.elasticsearch_batch_size = 500 self.elasticsearch_timeout_secs = 30 #Processing", "\"\" self.elasticsearch_verify_certs = False self.elasticsearch_index_name = \"\" self.elasticsearch_batch_size = 500", "tool settings. \"\"\" def __init__(self): \"\"\"Initializes the Config instance. \"\"\"", "filepath: path of the JSON file. \"\"\" with open(filepath, \"r\")", "#Processing settings self.sentiment_modelpath = \"\" self.sentiment_max_seq_length = 512 self.sleep_idle_secs =", "self.elasticsearch_timeout_secs = 30 #Processing settings self.sentiment_modelpath = \"\" self.sentiment_max_seq_length =", "self.log_level = \"ERROR\" @staticmethod def load(filepath): \"\"\"Loads the config from", "path of the JSON file. \"\"\" with open(filepath, \"r\") as", "the Config instance. \"\"\" #Elasticsearch settings self.elasticsearch_host = \"\" self.elasticsearch_verify_certs", "with open(filepath, \"r\") as file: json = file.read() config =", "= 5 self.sleep_not_idle_secs = 0.01 self.log_level = \"ERROR\" @staticmethod def", "settings for running sentiment scoring tool \"\"\" import jsonpickle class", "self.sleep_idle_secs = 5 self.sleep_not_idle_secs = 0.01 self.log_level = \"ERROR\" @staticmethod", "= \"\" self.sentiment_max_seq_length = 512 self.sleep_idle_secs = 5 self.sleep_not_idle_secs =", "class containing all the settings for running sentiment scoring tool", "settings. \"\"\" def __init__(self): \"\"\"Initializes the Config instance. \"\"\" #Elasticsearch", "Config(object): \"\"\"Container for sentiment scoring tool settings. \"\"\" def __init__(self):", "= \"\" self.elasticsearch_verify_certs = False self.elasticsearch_index_name = \"\" self.elasticsearch_batch_size =", "30 #Processing settings self.sentiment_modelpath = \"\" self.sentiment_max_seq_length = 512 self.sleep_idle_secs", "JSON file. \"\"\" with open(filepath, \"r\") as file: json =", "class Config(object): \"\"\"Container for sentiment scoring tool settings. \"\"\" def", "512 self.sleep_idle_secs = 5 self.sleep_not_idle_secs = 0.01 self.log_level = \"ERROR\"", "def __init__(self): \"\"\"Initializes the Config instance. \"\"\" #Elasticsearch settings self.elasticsearch_host", "Args: filepath: path of the JSON file. \"\"\" with open(filepath,", "= \"\" self.elasticsearch_batch_size = 500 self.elasticsearch_timeout_secs = 30 #Processing settings", "\"r\") as file: json = file.read() config = jsonpickle.decode(json) return", "scoring tool settings. \"\"\" def __init__(self): \"\"\"Initializes the Config instance.", "load(filepath): \"\"\"Loads the config from a JSON file. Args: filepath:", "from a JSON file. Args: filepath: path of the JSON", "self.sentiment_max_seq_length = 512 self.sleep_idle_secs = 5 self.sleep_not_idle_secs = 0.01 self.log_level", "__init__(self): \"\"\"Initializes the Config instance. \"\"\" #Elasticsearch settings self.elasticsearch_host =", "the JSON file. \"\"\" with open(filepath, \"r\") as file: json", "containing all the settings for running sentiment scoring tool \"\"\"", "= 30 #Processing settings self.sentiment_modelpath = \"\" self.sentiment_max_seq_length = 512", "instance. \"\"\" #Elasticsearch settings self.elasticsearch_host = \"\" self.elasticsearch_verify_certs = False", "@staticmethod def load(filepath): \"\"\"Loads the config from a JSON file.", "config from a JSON file. Args: filepath: path of the", "\"\"\" #Elasticsearch settings self.elasticsearch_host = \"\" self.elasticsearch_verify_certs = False self.elasticsearch_index_name", "self.sleep_not_idle_secs = 0.01 self.log_level = \"ERROR\" @staticmethod def load(filepath): \"\"\"Loads", "self.elasticsearch_verify_certs = False self.elasticsearch_index_name = \"\" self.elasticsearch_batch_size = 500 self.elasticsearch_timeout_secs", "\"\"\"Container for sentiment scoring tool settings. \"\"\" def __init__(self): \"\"\"Initializes", "running sentiment scoring tool \"\"\" import jsonpickle class Config(object): \"\"\"Container", "\"\"\" def __init__(self): \"\"\"Initializes the Config instance. \"\"\" #Elasticsearch settings", "\"\"\" Config class containing all the settings for running sentiment", "file. \"\"\" with open(filepath, \"r\") as file: json = file.read()", "tool \"\"\" import jsonpickle class Config(object): \"\"\"Container for sentiment scoring", "self.sentiment_modelpath = \"\" self.sentiment_max_seq_length = 512 self.sleep_idle_secs = 5 self.sleep_not_idle_secs", "0.01 self.log_level = \"ERROR\" @staticmethod def load(filepath): \"\"\"Loads the config", "\"\" self.elasticsearch_batch_size = 500 self.elasticsearch_timeout_secs = 30 #Processing settings self.sentiment_modelpath", "\"ERROR\" @staticmethod def load(filepath): \"\"\"Loads the config from a JSON", "\"\" self.sentiment_max_seq_length = 512 self.sleep_idle_secs = 5 self.sleep_not_idle_secs = 0.01", "for sentiment scoring tool settings. \"\"\" def __init__(self): \"\"\"Initializes the", "for running sentiment scoring tool \"\"\" import jsonpickle class Config(object):", "Config instance. \"\"\" #Elasticsearch settings self.elasticsearch_host = \"\" self.elasticsearch_verify_certs =", "5 self.sleep_not_idle_secs = 0.01 self.log_level = \"ERROR\" @staticmethod def load(filepath):", "the settings for running sentiment scoring tool \"\"\" import jsonpickle", "self.elasticsearch_batch_size = 500 self.elasticsearch_timeout_secs = 30 #Processing settings self.sentiment_modelpath =", "self.elasticsearch_host = \"\" self.elasticsearch_verify_certs = False self.elasticsearch_index_name = \"\" self.elasticsearch_batch_size", "sentiment scoring tool \"\"\" import jsonpickle class Config(object): \"\"\"Container for", "\"\"\"Initializes the Config instance. \"\"\" #Elasticsearch settings self.elasticsearch_host = \"\"", "def load(filepath): \"\"\"Loads the config from a JSON file. Args:", "= 0.01 self.log_level = \"ERROR\" @staticmethod def load(filepath): \"\"\"Loads the", "= 500 self.elasticsearch_timeout_secs = 30 #Processing settings self.sentiment_modelpath = \"\"", "all the settings for running sentiment scoring tool \"\"\" import", "as file: json = file.read() config = jsonpickle.decode(json) return config", "500 self.elasticsearch_timeout_secs = 30 #Processing settings self.sentiment_modelpath = \"\" self.sentiment_max_seq_length", "settings self.sentiment_modelpath = \"\" self.sentiment_max_seq_length = 512 self.sleep_idle_secs = 5", "= False self.elasticsearch_index_name = \"\" self.elasticsearch_batch_size = 500 self.elasticsearch_timeout_secs =", "sentiment scoring tool settings. \"\"\" def __init__(self): \"\"\"Initializes the Config", "Config class containing all the settings for running sentiment scoring", "open(filepath, \"r\") as file: json = file.read() config = jsonpickle.decode(json)", "= \"ERROR\" @staticmethod def load(filepath): \"\"\"Loads the config from a" ]
[ "Invert Images data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False) transform_invert = [C.Decode(), C.Resize(size=[224,", "range(num_samples): mse[i] = diff_mse(images_p_invert[i], images_c_invert[i]) logger.info(\"MSE= {}\".format(str(np.mean(mse)))) if plot: visualize_list(images_c_invert,", "Invert Python op\") # Original Images data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False)", "data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False) transforms_invert = [C.Decode(), C.Resize(size=[224, 224]), C.Invert(),", "With One Channel Images\") c_op = C.Invert() try: data_set =", "_) in enumerate(ds_p_invert): if idx == 0: images_p_invert = image.asnumpy()", "np.zeros(num_samples) for i in range(num_samples): mse[i] = diff_mse(images_invert[i], images_original[i]) logger.info(\"MSE=", "try: data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False) data_set = data_set.map(operations=[C.Decode(), C.Resize((224, 224)),", "check \"\"\" logger.info(\"Test Invert python op with md5 check\") #", "op and python op \"\"\" logger.info(\"Test Invert cpp and python", "channel image \"\"\" logger.info(\"Test Invert C Op With One Channel", "2.0 (the \"License\"); # you may not use this file", "i in range(num_samples): mse[i] = np.mean((images_invert[i] - images_original[i]) ** 2)", "\"\"\" logger.info(\"Test Invert C Op With One Channel Images\") c_op", "DE \"\"\" import numpy as np import mindspore.dataset as ds", "transforms_original = [C.Decode(), C.Resize(size=[224, 224])] ds_original = data_set.map(operations=transforms_original, input_columns=\"image\") ds_original", "axis=0) # invert images in python data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False)", "python op\") # Invert Images in cpp data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR,", "filename = \"invert_01_result_py.npz\" save_and_check_md5(data, filename, generate_golden=GENERATE_GOLDEN) def test_invert_md5_c(): \"\"\" Test", "ds_invert = data_set.map(operations=transforms_invert, input_columns=\"image\") ds_invert = ds_invert.batch(512) for idx, (image,", "3, 1)), axis=0) # Color Inverted Images data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR,", "test_invert_py(plot=False): \"\"\" Test Invert python op \"\"\" logger.info(\"Test Invert Python", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "as F import mindspore.dataset.vision.c_transforms as C from mindspore import log", "Images in cpp data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False) data_set = data_set.map(operations=[C.Decode(),", "num_samples = images_original.shape[0] mse = np.zeros(num_samples) for i in range(num_samples):", "image \"\"\" logger.info(\"Test Invert C Op With One Channel Images\")", "shuffle=False) transforms_original = [C.Decode(), C.Resize(size=[224, 224])] ds_original = data_set.map(operations=transforms_original, input_columns=\"image\")", "filename = \"invert_01_result_c.npz\" save_and_check_md5(data, filename, generate_golden=GENERATE_GOLDEN) if __name__ == \"__main__\":", "if idx == 0: images_c_invert = image.asnumpy() else: images_c_invert =", "image.asnumpy() else: images_p_invert = np.append(images_p_invert, image.asnumpy(), axis=0) num_samples = images_c_invert.shape[0]", "mse = np.zeros(num_samples) for i in range(num_samples): mse[i] = diff_mse(images_invert[i],", "= ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False) data_set = data_set.map(operations=[C.Decode(), C.Resize((224, 224))], input_columns=[\"image\"]) ds_c_invert", "ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False) data_set = data_set.map(operations=[C.Decode(), C.Resize((224, 224))], input_columns=[\"image\"]) transforms_p_invert =", "= [C.Decode(), C.Resize(size=[224, 224]), C.Invert()] ds_invert = data_set.map(operations=transform_invert, input_columns=\"image\") ds_invert", "range(num_samples): mse[i] = np.mean((images_invert[i] - images_original[i]) ** 2) logger.info(\"MSE= {}\".format(str(np.mean(mse))))", "== 0: images_p_invert = image.asnumpy() else: images_p_invert = np.append(images_p_invert, image.asnumpy(),", "License. # ============================================================================== \"\"\" Testing Invert op in DE \"\"\"", "C.Resize(size=[224, 224])] ds_original = data_set.map(operations=transforms_original, input_columns=\"image\") ds_original = ds_original.batch(512) for", "use this file except in compliance with the License. #", "C.Resize((224, 224))], input_columns=[\"image\"]) transforms_p_invert = mindspore.dataset.transforms.py_transforms.Compose([lambda img: img.astype(np.uint8), F.ToPIL(), F.Invert(),", "mindspore.dataset.transforms.py_transforms.Compose([lambda img: img.astype(np.uint8), F.ToPIL(), F.Invert(), np.array]) ds_p_invert = data_set.map(operations=transforms_p_invert, input_columns=\"image\")", "op with md5 check \"\"\" logger.info(\"Test Invert python op with", "shuffle=False) transforms_invert = mindspore.dataset.transforms.py_transforms.Compose([F.Decode(), F.Resize((224, 224)), F.Invert(), F.ToTensor()]) ds_invert =", "and python op \"\"\" logger.info(\"Test Invert cpp and python op\")", "from mindspore import log as logger from util import visualize_list,", "ds_original.batch(512) for idx, (image, _) in enumerate(ds_original): if idx ==", "in enumerate(ds_invert): if idx == 0: images_invert = np.transpose(image.asnumpy(), (0,", "in range(num_samples): mse[i] = diff_mse(images_invert[i], images_original[i]) logger.info(\"MSE= {}\".format(str(np.mean(mse)))) def test_invert_py_c(plot=False):", "\"\"\" import numpy as np import mindspore.dataset as ds import", "= ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False) transforms_invert = mindspore.dataset.transforms.py_transforms.Compose([F.Decode(), F.Resize((224, 224)), F.Invert(), F.ToTensor()])", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "Invert Images in cpp data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False) data_set =", "if plot: visualize_list(images_c_invert, images_p_invert, visualize_mode=2) def test_invert_one_channel(): \"\"\" Test Invert", "One Channel Images\") c_op = C.Invert() try: data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR,", "if plot: visualize_list(images_original, images_invert) num_samples = images_original.shape[0] mse = np.zeros(num_samples)", "(image, _) in enumerate(ds_invert): if idx == 0: images_invert =", "Invert cpp op\") # Original Images data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False)", "License. # You may obtain a copy of the License", "== 0: images_invert = np.transpose(image.asnumpy(), (0, 2, 3, 1)) else:", "mindspore.dataset as ds import mindspore.dataset.transforms.py_transforms import mindspore.dataset.vision.py_transforms as F import", "Invert cpp op with one channel image \"\"\" logger.info(\"Test Invert", "\"invert_01_result_py.npz\" save_and_check_md5(data, filename, generate_golden=GENERATE_GOLDEN) def test_invert_md5_c(): \"\"\" Test Invert cpp", "under the License is distributed on an \"AS IS\" BASIS,", "input_columns=\"image\") ds_invert = ds_invert.batch(512) for idx, (image, _) in enumerate(ds_invert):", "License for the specific language governing permissions and # limitations", "input_columns=[\"image\"]) transforms_p_invert = mindspore.dataset.transforms.py_transforms.Compose([lambda img: img.astype(np.uint8), F.ToPIL(), F.Invert(), np.array]) ds_p_invert", "cpp op with one channel image \"\"\" logger.info(\"Test Invert C", "for idx, (image, _) in enumerate(ds_invert): if idx == 0:", "np import mindspore.dataset as ds import mindspore.dataset.transforms.py_transforms import mindspore.dataset.vision.py_transforms as", "# Generate dataset data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False) transforms_invert = [C.Decode(),", "= np.append(images_original, image.asnumpy(), axis=0) # Invert Images data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR,", "if idx == 0: images_original = image.asnumpy() else: images_original =", "image.asnumpy(), axis=0) num_samples = images_c_invert.shape[0] mse = np.zeros(num_samples) for i", "images filename = \"invert_01_result_py.npz\" save_and_check_md5(data, filename, generate_golden=GENERATE_GOLDEN) def test_invert_md5_c(): \"\"\"", "in range(num_samples): mse[i] = np.mean((images_invert[i] - images_original[i]) ** 2) logger.info(\"MSE=", "governing permissions and # limitations under the License. # ==============================================================================", "enumerate(ds_p_invert): if idx == 0: images_p_invert = image.asnumpy() else: images_p_invert", "= \"invert_01_result_c.npz\" save_and_check_md5(data, filename, generate_golden=GENERATE_GOLDEN) if __name__ == \"__main__\": test_invert_py(plot=False)", "logger.info(\"Test Invert cpp and python op\") # Invert Images in", "np.zeros(num_samples) for i in range(num_samples): mse[i] = diff_mse(images_p_invert[i], images_c_invert[i]) logger.info(\"MSE=", "np.mean((images_invert[i] - images_original[i]) ** 2) logger.info(\"MSE= {}\".format(str(np.mean(mse)))) if plot: visualize_list(images_original,", "== 0: images_original = np.transpose(image.asnumpy(), (0, 2, 3, 1)) else:", "visualize_list(images_c_invert, images_p_invert, visualize_mode=2) def test_invert_one_channel(): \"\"\" Test Invert cpp op", "plot: visualize_list(images_original, images_invert) num_samples = images_original.shape[0] mse = np.zeros(num_samples) for", "np.transpose(image.asnumpy(), (0, 2, 3, 1)) else: images_original = np.append(images_original, np.transpose(image.asnumpy(),", "224]), C.Invert(), F.ToTensor()] data = data_set.map(operations=transforms_invert, input_columns=\"image\") # Compare with", "c_op = C.Invert() try: data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False) data_set =", "md5 check \"\"\" logger.info(\"Test Invert python op with md5 check\")", "images_c_invert = np.append(images_c_invert, image.asnumpy(), axis=0) # invert images in python", "expected md5 from images filename = \"invert_01_result_py.npz\" save_and_check_md5(data, filename, generate_golden=GENERATE_GOLDEN)", "in compliance with the License. # You may obtain a", "else: images_invert = np.append(images_invert, image.asnumpy(), axis=0) if plot: visualize_list(images_original, images_invert)", "data_set.map(operations=C.Invert(), input_columns=\"image\") ds_c_invert = ds_c_invert.batch(512) for idx, (image, _) in", "F.Invert(), F.ToTensor()]) ds_invert = data_set.map(operations=transforms_invert, input_columns=\"image\") ds_invert = ds_invert.batch(512) for", "shuffle=False) transforms_invert = mindspore.dataset.transforms.py_transforms.Compose([F.Decode(), F.Invert(), F.ToTensor()]) data = data_set.map(operations=transforms_invert, input_columns=\"image\")", "software # distributed under the License is distributed on an", "= data_set.map(operations=transforms_invert, input_columns=\"image\") # Compare with expected md5 from images", "idx == 0: images_invert = np.transpose(image.asnumpy(), (0, 2, 3, 1))", "Huawei Technologies Co., Ltd # # Licensed under the Apache", "np.transpose(image.asnumpy(), (0, 2, 3, 1)), axis=0) num_samples = images_original.shape[0] mse", "cpp data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False) data_set = data_set.map(operations=[C.Decode(), C.Resize((224, 224))],", "test_invert_one_channel(): \"\"\" Test Invert cpp op with one channel image", "= diff_mse(images_invert[i], images_original[i]) logger.info(\"MSE= {}\".format(str(np.mean(mse)))) def test_invert_py_c(plot=False): \"\"\" Test Invert", "ds_p_invert.batch(512) for idx, (image, _) in enumerate(ds_p_invert): if idx ==", "python op \"\"\" logger.info(\"Test Invert Python op\") # Original Images", "= np.append(images_p_invert, image.asnumpy(), axis=0) num_samples = images_c_invert.shape[0] mse = np.zeros(num_samples)", "if plot: visualize_list(images_original, images_invert) def test_invert_c(plot=False): \"\"\" Test Invert Cpp", "Testing Invert op in DE \"\"\" import numpy as np", "ds_invert.batch(512) for idx, (image, _) in enumerate(ds_invert): if idx ==", "ds_c_invert.batch(512) for idx, (image, _) in enumerate(ds_c_invert): if idx ==", "save_and_check_md5(data, filename, generate_golden=GENERATE_GOLDEN) def test_invert_md5_c(): \"\"\" Test Invert cpp op", "input_columns=[\"image\"]) ds_c_invert = data_set.map(operations=C.Invert(), input_columns=\"image\") ds_c_invert = ds_c_invert.batch(512) for idx,", "transforms_invert = mindspore.dataset.transforms.py_transforms.Compose([F.Decode(), F.Invert(), F.ToTensor()]) data = data_set.map(operations=transforms_invert, input_columns=\"image\") #", "idx, (image, _) in enumerate(ds_invert): if idx == 0: images_invert", "{}\".format(str(np.mean(mse)))) if plot: visualize_list(images_c_invert, images_p_invert, visualize_mode=2) def test_invert_one_channel(): \"\"\" Test", "Co., Ltd # # Licensed under the Apache License, Version", "import visualize_list, save_and_check_md5, diff_mse DATA_DIR = \"../data/dataset/testImageNetData/train/\" GENERATE_GOLDEN = False", "mindspore.dataset.transforms.py_transforms.Compose([F.Decode(), F.Resize((224, 224)), F.Invert(), F.ToTensor()]) ds_invert = data_set.map(operations=transforms_invert, input_columns=\"image\") ds_invert", "2, 3, 1)), axis=0) # Color Inverted Images data_set =", "logger.info(\"Test Invert C Op With One Channel Images\") c_op =", "expected md5 from images filename = \"invert_01_result_c.npz\" save_and_check_md5(data, filename, generate_golden=GENERATE_GOLDEN)", "images_c_invert.shape[0] mse = np.zeros(num_samples) for i in range(num_samples): mse[i] =", "mindspore.dataset.transforms.py_transforms.Compose([F.Decode(), F.Invert(), F.ToTensor()]) data = data_set.map(operations=transforms_invert, input_columns=\"image\") # Compare with", "if idx == 0: images_invert = image.asnumpy() else: images_invert =", "Test Invert cpp op with one channel image \"\"\" logger.info(\"Test", "2) logger.info(\"MSE= {}\".format(str(np.mean(mse)))) if plot: visualize_list(images_original, images_invert) def test_invert_c(plot=False): \"\"\"", "\"invert_01_result_c.npz\" save_and_check_md5(data, filename, generate_golden=GENERATE_GOLDEN) if __name__ == \"__main__\": test_invert_py(plot=False) test_invert_c(plot=False)", "224)), lambda img: np.array(img[:, :, 0])], input_columns=[\"image\"]) data_set.map(operations=c_op, input_columns=\"image\") except", "ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False) transforms_original = mindspore.dataset.transforms.py_transforms.Compose([F.Decode(), F.Resize((224, 224)), F.ToTensor()]) ds_original =", "ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False) transforms_invert = mindspore.dataset.transforms.py_transforms.Compose([F.Decode(), F.Invert(), F.ToTensor()]) data = data_set.map(operations=transforms_invert,", "check \"\"\" logger.info(\"Test Invert cpp op with md5 check\") #", "if idx == 0: images_invert = np.transpose(image.asnumpy(), (0, 2, 3,", "image.asnumpy() else: images_original = np.append(images_original, image.asnumpy(), axis=0) # Invert Images", "permissions and # limitations under the License. # ============================================================================== \"\"\"", "2, 3, 1)) else: images_original = np.append(images_original, np.transpose(image.asnumpy(), (0, 2,", "visualize_list(images_original, images_invert) def test_invert_c(plot=False): \"\"\" Test Invert Cpp op \"\"\"", "shuffle=False) data_set = data_set.map(operations=[C.Decode(), C.Resize((224, 224)), lambda img: np.array(img[:, :,", "OF ANY KIND, either express or implied. # See the", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "exception in DE: {}\".format(str(e))) assert \"The shape\" in str(e) def", "ANY KIND, either express or implied. # See the License", "See the License for the specific language governing permissions and", "= data_set.map(operations=transforms_p_invert, input_columns=\"image\") ds_p_invert = ds_p_invert.batch(512) for idx, (image, _)", "from images filename = \"invert_01_result_py.npz\" save_and_check_md5(data, filename, generate_golden=GENERATE_GOLDEN) def test_invert_md5_c():", "idx, (image, _) in enumerate(ds_original): if idx == 0: images_original", "the License. # You may obtain a copy of the", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "for the specific language governing permissions and # limitations under", "transforms_original = mindspore.dataset.transforms.py_transforms.Compose([F.Decode(), F.Resize((224, 224)), F.ToTensor()]) ds_original = data_set.map(operations=transforms_original, input_columns=\"image\")", "= ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False) transforms_invert = mindspore.dataset.transforms.py_transforms.Compose([F.Decode(), F.Invert(), F.ToTensor()]) data =", "to in writing, software # distributed under the License is", "logger.info(\"Test Invert python op with md5 check\") # Generate dataset", "ds import mindspore.dataset.transforms.py_transforms import mindspore.dataset.vision.py_transforms as F import mindspore.dataset.vision.c_transforms as", "diff_mse DATA_DIR = \"../data/dataset/testImageNetData/train/\" GENERATE_GOLDEN = False def test_invert_py(plot=False): \"\"\"", "224))], input_columns=[\"image\"]) ds_c_invert = data_set.map(operations=C.Invert(), input_columns=\"image\") ds_c_invert = ds_c_invert.batch(512) for", "# See the License for the specific language governing permissions", "data_set.map(operations=[C.Decode(), C.Resize((224, 224)), lambda img: np.array(img[:, :, 0])], input_columns=[\"image\"]) data_set.map(operations=c_op,", "# Invert Images in cpp data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False) data_set", "Compare with expected md5 from images filename = \"invert_01_result_c.npz\" save_and_check_md5(data,", "Test Invert Cpp op and python op \"\"\" logger.info(\"Test Invert", "language governing permissions and # limitations under the License. #", "images_original[i]) ** 2) logger.info(\"MSE= {}\".format(str(np.mean(mse)))) if plot: visualize_list(images_original, images_invert) def", "or agreed to in writing, software # distributed under the", "required by applicable law or agreed to in writing, software", "data_set.map(operations=transforms_original, input_columns=\"image\") ds_original = ds_original.batch(512) for idx, (image, _) in", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "0: images_original = np.transpose(image.asnumpy(), (0, 2, 3, 1)) else: images_original", "images_original = np.transpose(image.asnumpy(), (0, 2, 3, 1)) else: images_original =", "with the License. # You may obtain a copy of", "= np.zeros(num_samples) for i in range(num_samples): mse[i] = np.mean((images_invert[i] -", "Test Invert python op with md5 check \"\"\" logger.info(\"Test Invert", "shuffle=False) data_set = data_set.map(operations=[C.Decode(), C.Resize((224, 224))], input_columns=[\"image\"]) ds_c_invert = data_set.map(operations=C.Invert(),", "diff_mse(images_invert[i], images_original[i]) logger.info(\"MSE= {}\".format(str(np.mean(mse)))) def test_invert_py_c(plot=False): \"\"\" Test Invert Cpp", "dataset data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False) transforms_invert = mindspore.dataset.transforms.py_transforms.Compose([F.Decode(), F.Invert(), F.ToTensor()])", "axis=0) num_samples = images_original.shape[0] mse = np.zeros(num_samples) for i in", "# Original Images data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False) transforms_original = mindspore.dataset.transforms.py_transforms.Compose([F.Decode(),", "str(e) def test_invert_md5_py(): \"\"\" Test Invert python op with md5", "data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False) data_set = data_set.map(operations=[C.Decode(), C.Resize((224, 224)), lambda", "{}\".format(str(np.mean(mse)))) def test_invert_py_c(plot=False): \"\"\" Test Invert Cpp op and python", "images filename = \"invert_01_result_c.npz\" save_and_check_md5(data, filename, generate_golden=GENERATE_GOLDEN) if __name__ ==", "input_columns=\"image\") ds_original = ds_original.batch(512) for idx, (image, _) in enumerate(ds_original):", "{}\".format(str(e))) assert \"The shape\" in str(e) def test_invert_md5_py(): \"\"\" Test", "compliance with the License. # You may obtain a copy", "agreed to in writing, software # distributed under the License", "Images data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False) transforms_invert = mindspore.dataset.transforms.py_transforms.Compose([F.Decode(), F.Resize((224, 224)),", "(image, _) in enumerate(ds_c_invert): if idx == 0: images_c_invert =", "filename, generate_golden=GENERATE_GOLDEN) if __name__ == \"__main__\": test_invert_py(plot=False) test_invert_c(plot=False) test_invert_py_c(plot=False) test_invert_one_channel()", "C.Resize((224, 224))], input_columns=[\"image\"]) ds_c_invert = data_set.map(operations=C.Invert(), input_columns=\"image\") ds_c_invert = ds_c_invert.batch(512)", "util import visualize_list, save_and_check_md5, diff_mse DATA_DIR = \"../data/dataset/testImageNetData/train/\" GENERATE_GOLDEN =", "images_c_invert = image.asnumpy() else: images_c_invert = np.append(images_c_invert, image.asnumpy(), axis=0) #", "distributed under the License is distributed on an \"AS IS\"", "3, 1)) else: images_invert = np.append(images_invert, np.transpose(image.asnumpy(), (0, 2, 3,", "= mindspore.dataset.transforms.py_transforms.Compose([F.Decode(), F.Invert(), F.ToTensor()]) data = data_set.map(operations=transforms_invert, input_columns=\"image\") # Compare", "data_set.map(operations=transforms_p_invert, input_columns=\"image\") ds_p_invert = ds_p_invert.batch(512) for idx, (image, _) in", "op with md5 check\") # Generate dataset data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR,", "= image.asnumpy() else: images_invert = np.append(images_invert, image.asnumpy(), axis=0) if plot:", "op\") # Original Images data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False) transforms_original =", "data_set.map(operations=transform_invert, input_columns=\"image\") ds_invert = ds_invert.batch(512) for idx, (image, _) in", "def test_invert_md5_c(): \"\"\" Test Invert cpp op with md5 check", "express or implied. # See the License for the specific", "Original Images data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False) transforms_original = [C.Decode(), C.Resize(size=[224,", "except in compliance with the License. # You may obtain", "python op with md5 check\") # Generate dataset data_set =", "= images_original.shape[0] mse = np.zeros(num_samples) for i in range(num_samples): mse[i]", "if idx == 0: images_p_invert = image.asnumpy() else: images_p_invert =", "Test Invert cpp op with md5 check \"\"\" logger.info(\"Test Invert", "3, 1)) else: images_original = np.append(images_original, np.transpose(image.asnumpy(), (0, 2, 3,", "data_set = data_set.map(operations=[C.Decode(), C.Resize((224, 224)), lambda img: np.array(img[:, :, 0])],", "Licensed under the Apache License, Version 2.0 (the \"License\"); #", "not use this file except in compliance with the License.", "np.append(images_original, np.transpose(image.asnumpy(), (0, 2, 3, 1)), axis=0) # Color Inverted", "writing, software # distributed under the License is distributed on", "\"\"\" Test Invert python op \"\"\" logger.info(\"Test Invert Python op\")", "= np.transpose(image.asnumpy(), (0, 2, 3, 1)) else: images_invert = np.append(images_invert,", "= [C.Decode(), C.Resize(size=[224, 224])] ds_original = data_set.map(operations=transforms_original, input_columns=\"image\") ds_original =", "you may not use this file except in compliance with", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False) transforms_invert = mindspore.dataset.transforms.py_transforms.Compose([F.Decode(), F.Resize((224, 224)), F.Invert(), F.ToTensor()]) ds_invert", "else: images_invert = np.append(images_invert, np.transpose(image.asnumpy(), (0, 2, 3, 1)), axis=0)", "axis=0) # Invert Images data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False) transform_invert =", "def test_invert_one_channel(): \"\"\" Test Invert cpp op with one channel", "lambda img: np.array(img[:, :, 0])], input_columns=[\"image\"]) data_set.map(operations=c_op, input_columns=\"image\") except RuntimeError", "idx, (image, _) in enumerate(ds_c_invert): if idx == 0: images_c_invert", "# invert images in python data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False) data_set", "in range(num_samples): mse[i] = diff_mse(images_p_invert[i], images_c_invert[i]) logger.info(\"MSE= {}\".format(str(np.mean(mse)))) if plot:", "Invert python op with md5 check \"\"\" logger.info(\"Test Invert python", "idx, (image, _) in enumerate(ds_p_invert): if idx == 0: images_p_invert", "images_original = image.asnumpy() else: images_original = np.append(images_original, image.asnumpy(), axis=0) #", "C.Invert(), F.ToTensor()] data = data_set.map(operations=transforms_invert, input_columns=\"image\") # Compare with expected", "and # limitations under the License. # ============================================================================== \"\"\" Testing", "images_original = np.append(images_original, image.asnumpy(), axis=0) # Invert Images data_set =", "CONDITIONS OF ANY KIND, either express or implied. # See", "else: images_c_invert = np.append(images_c_invert, image.asnumpy(), axis=0) # invert images in", "Ltd # # Licensed under the Apache License, Version 2.0", "= False def test_invert_py(plot=False): \"\"\" Test Invert python op \"\"\"", "0: images_p_invert = image.asnumpy() else: images_p_invert = np.append(images_p_invert, image.asnumpy(), axis=0)", "data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False) transforms_invert = mindspore.dataset.transforms.py_transforms.Compose([F.Decode(), F.Resize((224, 224)), F.Invert(),", "transforms_invert = mindspore.dataset.transforms.py_transforms.Compose([F.Decode(), F.Resize((224, 224)), F.Invert(), F.ToTensor()]) ds_invert = data_set.map(operations=transforms_invert,", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "= data_set.map(operations=transforms_original, input_columns=\"image\") ds_original = ds_original.batch(512) for idx, (image, _)", "test_invert_py_c(plot=False): \"\"\" Test Invert Cpp op and python op \"\"\"", "python data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False) data_set = data_set.map(operations=[C.Decode(), C.Resize((224, 224))],", "= data_set.map(operations=C.Invert(), input_columns=\"image\") ds_c_invert = ds_c_invert.batch(512) for idx, (image, _)", "np.array(img[:, :, 0])], input_columns=[\"image\"]) data_set.map(operations=c_op, input_columns=\"image\") except RuntimeError as e:", "0])], input_columns=[\"image\"]) data_set.map(operations=c_op, input_columns=\"image\") except RuntimeError as e: logger.info(\"Got an", "= ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False) transforms_invert = [C.Decode(), C.Resize(size=[224, 224]), C.Invert(), F.ToTensor()]", "ds_p_invert = ds_p_invert.batch(512) for idx, (image, _) in enumerate(ds_p_invert): if", "False def test_invert_py(plot=False): \"\"\" Test Invert python op \"\"\" logger.info(\"Test", "= mindspore.dataset.transforms.py_transforms.Compose([lambda img: img.astype(np.uint8), F.ToPIL(), F.Invert(), np.array]) ds_p_invert = data_set.map(operations=transforms_p_invert,", "(image, _) in enumerate(ds_original): if idx == 0: images_original =", "= image.asnumpy() else: images_original = np.append(images_original, image.asnumpy(), axis=0) # Invert", "logger.info(\"MSE= {}\".format(str(np.mean(mse)))) def test_invert_py_c(plot=False): \"\"\" Test Invert Cpp op and", "1)) else: images_original = np.append(images_original, np.transpose(image.asnumpy(), (0, 2, 3, 1)),", "md5 check\") # Generate dataset data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False) transforms_invert", "Invert cpp op with md5 check \"\"\" logger.info(\"Test Invert cpp", "cpp op with md5 check\") # Generate dataset data_set =", "= C.Invert() try: data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False) data_set = data_set.map(operations=[C.Decode(),", "= ds_original.batch(512) for idx, (image, _) in enumerate(ds_original): if idx", "images_original.shape[0] mse = np.zeros(num_samples) for i in range(num_samples): mse[i] =", "for idx, (image, _) in enumerate(ds_c_invert): if idx == 0:", "Images data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False) transforms_original = [C.Decode(), C.Resize(size=[224, 224])]", "shuffle=False) transform_invert = [C.Decode(), C.Resize(size=[224, 224]), C.Invert()] ds_invert = data_set.map(operations=transform_invert,", "_) in enumerate(ds_invert): if idx == 0: images_invert = np.transpose(image.asnumpy(),", "F.ToTensor()]) ds_original = data_set.map(operations=transforms_original, input_columns=\"image\") ds_original = ds_original.batch(512) for idx,", "= diff_mse(images_p_invert[i], images_c_invert[i]) logger.info(\"MSE= {}\".format(str(np.mean(mse)))) if plot: visualize_list(images_c_invert, images_p_invert, visualize_mode=2)", "OR CONDITIONS OF ANY KIND, either express or implied. #", "\"../data/dataset/testImageNetData/train/\" GENERATE_GOLDEN = False def test_invert_py(plot=False): \"\"\" Test Invert python", "ds_c_invert = ds_c_invert.batch(512) for idx, (image, _) in enumerate(ds_c_invert): if", "shape\" in str(e) def test_invert_md5_py(): \"\"\" Test Invert python op", "= ds_p_invert.batch(512) for idx, (image, _) in enumerate(ds_p_invert): if idx", "the License is distributed on an \"AS IS\" BASIS, #", "# ============================================================================== \"\"\" Testing Invert op in DE \"\"\" import", "ds_original = ds_original.batch(512) for idx, (image, _) in enumerate(ds_original): if", "\"\"\" Test Invert Cpp op and python op \"\"\" logger.info(\"Test", "Test Invert python op \"\"\" logger.info(\"Test Invert Python op\") #", "RuntimeError as e: logger.info(\"Got an exception in DE: {}\".format(str(e))) assert", "F.Invert(), np.array]) ds_p_invert = data_set.map(operations=transforms_p_invert, input_columns=\"image\") ds_p_invert = ds_p_invert.batch(512) for", "\"\"\" Testing Invert op in DE \"\"\" import numpy as", "\"\"\" Test Invert cpp op with md5 check \"\"\" logger.info(\"Test", "Invert cpp op with md5 check\") # Generate dataset data_set", "== 0: images_invert = image.asnumpy() else: images_invert = np.append(images_invert, image.asnumpy(),", "in DE \"\"\" import numpy as np import mindspore.dataset as", "np.append(images_p_invert, image.asnumpy(), axis=0) num_samples = images_c_invert.shape[0] mse = np.zeros(num_samples) for", "images_p_invert = np.append(images_p_invert, image.asnumpy(), axis=0) num_samples = images_c_invert.shape[0] mse =", "\"\"\" logger.info(\"Test Invert cpp and python op\") # Invert Images", "\"\"\" logger.info(\"Test Invert cpp op with md5 check\") # Generate", "under the License. # ============================================================================== \"\"\" Testing Invert op in", "= ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False) data_set = data_set.map(operations=[C.Decode(), C.Resize((224, 224)), lambda img:", "DATA_DIR = \"../data/dataset/testImageNetData/train/\" GENERATE_GOLDEN = False def test_invert_py(plot=False): \"\"\" Test", "as e: logger.info(\"Got an exception in DE: {}\".format(str(e))) assert \"The", "law or agreed to in writing, software # distributed under", "axis=0) if plot: visualize_list(images_original, images_invert) num_samples = images_original.shape[0] mse =", "ds_original = data_set.map(operations=transforms_original, input_columns=\"image\") ds_original = ds_original.batch(512) for idx, (image,", "= [C.Decode(), C.Resize(size=[224, 224]), C.Invert(), F.ToTensor()] data = data_set.map(operations=transforms_invert, input_columns=\"image\")", "[C.Decode(), C.Resize(size=[224, 224]), C.Invert()] ds_invert = data_set.map(operations=transform_invert, input_columns=\"image\") ds_invert =", "Images data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False) transform_invert = [C.Decode(), C.Resize(size=[224, 224]),", "save_and_check_md5(data, filename, generate_golden=GENERATE_GOLDEN) if __name__ == \"__main__\": test_invert_py(plot=False) test_invert_c(plot=False) test_invert_py_c(plot=False)", "import numpy as np import mindspore.dataset as ds import mindspore.dataset.transforms.py_transforms", "Invert C Op With One Channel Images\") c_op = C.Invert()", "C from mindspore import log as logger from util import", "data_set.map(operations=transforms_invert, input_columns=\"image\") ds_invert = ds_invert.batch(512) for idx, (image, _) in", "logger.info(\"Test Invert cpp op with md5 check\") # Generate dataset", "\"\"\" logger.info(\"Test Invert python op with md5 check\") # Generate", "may obtain a copy of the License at # #", "Copyright 2020 Huawei Technologies Co., Ltd # # Licensed under", "(image, _) in enumerate(ds_p_invert): if idx == 0: images_p_invert =", "\"\"\" Test Invert cpp op with one channel image \"\"\"", "= data_set.map(operations=transform_invert, input_columns=\"image\") ds_invert = ds_invert.batch(512) for idx, (image, _)", "limitations under the License. # ============================================================================== \"\"\" Testing Invert op", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "for i in range(num_samples): mse[i] = np.mean((images_invert[i] - images_original[i]) **", "ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False) data_set = data_set.map(operations=[C.Decode(), C.Resize((224, 224))], input_columns=[\"image\"]) ds_c_invert =", "else: images_p_invert = np.append(images_p_invert, image.asnumpy(), axis=0) num_samples = images_c_invert.shape[0] mse", "ds_invert = ds_invert.batch(512) for idx, (image, _) in enumerate(ds_invert): if", "else: images_original = np.append(images_original, image.asnumpy(), axis=0) # Invert Images data_set", "Original Images data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False) transforms_original = mindspore.dataset.transforms.py_transforms.Compose([F.Decode(), F.Resize((224,", "may not use this file except in compliance with the", "ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False) transforms_original = [C.Decode(), C.Resize(size=[224, 224])] ds_original = data_set.map(operations=transforms_original,", "shuffle=False) data_set = data_set.map(operations=[C.Decode(), C.Resize((224, 224))], input_columns=[\"image\"]) transforms_p_invert = mindspore.dataset.transforms.py_transforms.Compose([lambda", "as C from mindspore import log as logger from util", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "this file except in compliance with the License. # You", "image.asnumpy(), axis=0) # Invert Images data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False) transform_invert", "idx == 0: images_invert = image.asnumpy() else: images_invert = np.append(images_invert,", "in str(e) def test_invert_md5_py(): \"\"\" Test Invert python op with", "images_invert = np.append(images_invert, image.asnumpy(), axis=0) if plot: visualize_list(images_original, images_invert) num_samples", "= np.mean((images_invert[i] - images_original[i]) ** 2) logger.info(\"MSE= {}\".format(str(np.mean(mse)))) if plot:", "except RuntimeError as e: logger.info(\"Got an exception in DE: {}\".format(str(e)))", "# Generate dataset data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False) transforms_invert = mindspore.dataset.transforms.py_transforms.Compose([F.Decode(),", "F import mindspore.dataset.vision.c_transforms as C from mindspore import log as", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "= mindspore.dataset.transforms.py_transforms.Compose([F.Decode(), F.Resize((224, 224)), F.ToTensor()]) ds_original = data_set.map(operations=transforms_original, input_columns=\"image\") ds_original", "# # Licensed under the Apache License, Version 2.0 (the", "F.ToTensor()]) ds_invert = data_set.map(operations=transforms_invert, input_columns=\"image\") ds_invert = ds_invert.batch(512) for idx,", "** 2) logger.info(\"MSE= {}\".format(str(np.mean(mse)))) if plot: visualize_list(images_original, images_invert) def test_invert_c(plot=False):", "in enumerate(ds_c_invert): if idx == 0: images_c_invert = image.asnumpy() else:", "file except in compliance with the License. # You may", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "i in range(num_samples): mse[i] = diff_mse(images_p_invert[i], images_c_invert[i]) logger.info(\"MSE= {}\".format(str(np.mean(mse)))) if", "224)), F.Invert(), F.ToTensor()]) ds_invert = data_set.map(operations=transforms_invert, input_columns=\"image\") ds_invert = ds_invert.batch(512)", "op with md5 check \"\"\" logger.info(\"Test Invert cpp op with", "1)) else: images_invert = np.append(images_invert, np.transpose(image.asnumpy(), (0, 2, 3, 1)),", "images_original[i]) logger.info(\"MSE= {}\".format(str(np.mean(mse)))) def test_invert_py_c(plot=False): \"\"\" Test Invert Cpp op", "Channel Images\") c_op = C.Invert() try: data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False)", "image.asnumpy() else: images_invert = np.append(images_invert, image.asnumpy(), axis=0) if plot: visualize_list(images_original,", "\"\"\" logger.info(\"Test Invert Python op\") # Original Images data_set =", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "data = data_set.map(operations=transforms_invert, input_columns=\"image\") # Compare with expected md5 from", "data_set.map(operations=c_op, input_columns=\"image\") except RuntimeError as e: logger.info(\"Got an exception in", "if __name__ == \"__main__\": test_invert_py(plot=False) test_invert_c(plot=False) test_invert_py_c(plot=False) test_invert_one_channel() test_invert_md5_py() test_invert_md5_c()", "224)), F.ToTensor()]) ds_original = data_set.map(operations=transforms_original, input_columns=\"image\") ds_original = ds_original.batch(512) for", "0: images_invert = np.transpose(image.asnumpy(), (0, 2, 3, 1)) else: images_invert", "= np.append(images_original, np.transpose(image.asnumpy(), (0, 2, 3, 1)), axis=0) # Color", "range(num_samples): mse[i] = diff_mse(images_invert[i], images_original[i]) logger.info(\"MSE= {}\".format(str(np.mean(mse)))) def test_invert_py_c(plot=False): \"\"\"", "data_set.map(operations=transforms_invert, input_columns=\"image\") # Compare with expected md5 from images filename", "enumerate(ds_original): if idx == 0: images_original = image.asnumpy() else: images_original", "data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False) transforms_original = [C.Decode(), C.Resize(size=[224, 224])] ds_original", "Python op\") # Original Images data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False) transforms_original", "Cpp op and python op \"\"\" logger.info(\"Test Invert cpp and", "in python data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False) data_set = data_set.map(operations=[C.Decode(), C.Resize((224,", "input_columns=\"image\") except RuntimeError as e: logger.info(\"Got an exception in DE:", "for i in range(num_samples): mse[i] = diff_mse(images_p_invert[i], images_c_invert[i]) logger.info(\"MSE= {}\".format(str(np.mean(mse))))", "img.astype(np.uint8), F.ToPIL(), F.Invert(), np.array]) ds_p_invert = data_set.map(operations=transforms_p_invert, input_columns=\"image\") ds_p_invert =", "visualize_list, save_and_check_md5, diff_mse DATA_DIR = \"../data/dataset/testImageNetData/train/\" GENERATE_GOLDEN = False def", "\"The shape\" in str(e) def test_invert_md5_py(): \"\"\" Test Invert python", "3, 1)), axis=0) num_samples = images_original.shape[0] mse = np.zeros(num_samples) for", "= ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False) transforms_original = [C.Decode(), C.Resize(size=[224, 224])] ds_original =", "224]), C.Invert()] ds_invert = data_set.map(operations=transform_invert, input_columns=\"image\") ds_invert = ds_invert.batch(512) for", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "2, 3, 1)), axis=0) num_samples = images_original.shape[0] mse = np.zeros(num_samples)", "test_invert_md5_py(): \"\"\" Test Invert python op with md5 check \"\"\"", "logger.info(\"MSE= {}\".format(str(np.mean(mse)))) if plot: visualize_list(images_original, images_invert) def test_invert_c(plot=False): \"\"\" Test", "img: img.astype(np.uint8), F.ToPIL(), F.Invert(), np.array]) ds_p_invert = data_set.map(operations=transforms_p_invert, input_columns=\"image\") ds_p_invert", "or implied. # See the License for the specific language", "= \"../data/dataset/testImageNetData/train/\" GENERATE_GOLDEN = False def test_invert_py(plot=False): \"\"\" Test Invert", "= mindspore.dataset.transforms.py_transforms.Compose([F.Decode(), F.Resize((224, 224)), F.Invert(), F.ToTensor()]) ds_invert = data_set.map(operations=transforms_invert, input_columns=\"image\")", "Invert python op \"\"\" logger.info(\"Test Invert Python op\") # Original", "1)), axis=0) num_samples = images_original.shape[0] mse = np.zeros(num_samples) for i", "KIND, either express or implied. # See the License for", "specific language governing permissions and # limitations under the License.", "_) in enumerate(ds_invert): if idx == 0: images_invert = image.asnumpy()", "for i in range(num_samples): mse[i] = diff_mse(images_invert[i], images_original[i]) logger.info(\"MSE= {}\".format(str(np.mean(mse))))", "data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False) transforms_invert = mindspore.dataset.transforms.py_transforms.Compose([F.Decode(), F.Invert(), F.ToTensor()]) data", "import mindspore.dataset.vision.c_transforms as C from mindspore import log as logger", "log as logger from util import visualize_list, save_and_check_md5, diff_mse DATA_DIR", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "idx == 0: images_p_invert = image.asnumpy() else: images_p_invert = np.append(images_p_invert,", "import mindspore.dataset.transforms.py_transforms import mindspore.dataset.vision.py_transforms as F import mindspore.dataset.vision.c_transforms as C", "_) in enumerate(ds_c_invert): if idx == 0: images_c_invert = image.asnumpy()", "an exception in DE: {}\".format(str(e))) assert \"The shape\" in str(e)", "mindspore.dataset.transforms.py_transforms.Compose([F.Decode(), F.Resize((224, 224)), F.ToTensor()]) ds_original = data_set.map(operations=transforms_original, input_columns=\"image\") ds_original =", "F.Resize((224, 224)), F.Invert(), F.ToTensor()]) ds_invert = data_set.map(operations=transforms_invert, input_columns=\"image\") ds_invert =", "op \"\"\" logger.info(\"Test Invert cpp and python op\") # Invert", "mindspore.dataset.vision.c_transforms as C from mindspore import log as logger from", "Invert op in DE \"\"\" import numpy as np import", "in DE: {}\".format(str(e))) assert \"The shape\" in str(e) def test_invert_md5_py():", "(the \"License\"); # you may not use this file except", "[C.Decode(), C.Resize(size=[224, 224])] ds_original = data_set.map(operations=transforms_original, input_columns=\"image\") ds_original = ds_original.batch(512)", "Invert Cpp op \"\"\" logger.info(\"Test Invert cpp op\") # Original", "in cpp data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False) data_set = data_set.map(operations=[C.Decode(), C.Resize((224,", "# you may not use this file except in compliance", "images in python data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False) data_set = data_set.map(operations=[C.Decode(),", "C.Resize(size=[224, 224]), C.Invert(), F.ToTensor()] data = data_set.map(operations=transforms_invert, input_columns=\"image\") # Compare", "diff_mse(images_p_invert[i], images_c_invert[i]) logger.info(\"MSE= {}\".format(str(np.mean(mse)))) if plot: visualize_list(images_c_invert, images_p_invert, visualize_mode=2) def", "op\") # Invert Images in cpp data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False)", "np.append(images_invert, image.asnumpy(), axis=0) if plot: visualize_list(images_original, images_invert) num_samples = images_original.shape[0]", "images_p_invert = image.asnumpy() else: images_p_invert = np.append(images_p_invert, image.asnumpy(), axis=0) num_samples", "C.Invert() try: data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False) data_set = data_set.map(operations=[C.Decode(), C.Resize((224,", "# Color Inverted Images data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False) transforms_invert =", "C Op With One Channel Images\") c_op = C.Invert() try:", "= image.asnumpy() else: images_p_invert = np.append(images_p_invert, image.asnumpy(), axis=0) num_samples =", "Op With One Channel Images\") c_op = C.Invert() try: data_set", "# # Unless required by applicable law or agreed to", "== 0: images_original = image.asnumpy() else: images_original = np.append(images_original, image.asnumpy(),", "images_invert) num_samples = images_original.shape[0] mse = np.zeros(num_samples) for i in", "C.Resize((224, 224)), lambda img: np.array(img[:, :, 0])], input_columns=[\"image\"]) data_set.map(operations=c_op, input_columns=\"image\")", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "save_and_check_md5, diff_mse DATA_DIR = \"../data/dataset/testImageNetData/train/\" GENERATE_GOLDEN = False def test_invert_py(plot=False):", "import mindspore.dataset.vision.py_transforms as F import mindspore.dataset.vision.c_transforms as C from mindspore", "np.array]) ds_p_invert = data_set.map(operations=transforms_p_invert, input_columns=\"image\") ds_p_invert = ds_p_invert.batch(512) for idx,", "numpy as np import mindspore.dataset as ds import mindspore.dataset.transforms.py_transforms import", "Version 2.0 (the \"License\"); # you may not use this", "i in range(num_samples): mse[i] = diff_mse(images_invert[i], images_original[i]) logger.info(\"MSE= {}\".format(str(np.mean(mse)))) def", "Generate dataset data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False) transforms_invert = [C.Decode(), C.Resize(size=[224,", "logger.info(\"Got an exception in DE: {}\".format(str(e))) assert \"The shape\" in", "Inverted Images data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False) transforms_invert = mindspore.dataset.transforms.py_transforms.Compose([F.Decode(), F.Resize((224,", "data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False) transforms_original = mindspore.dataset.transforms.py_transforms.Compose([F.Decode(), F.Resize((224, 224)), F.ToTensor()])", "(0, 2, 3, 1)), axis=0) # Color Inverted Images data_set", "generate_golden=GENERATE_GOLDEN) def test_invert_md5_c(): \"\"\" Test Invert cpp op with md5", "in enumerate(ds_original): if idx == 0: images_original = image.asnumpy() else:", "Invert Cpp op and python op \"\"\" logger.info(\"Test Invert cpp", "logger from util import visualize_list, save_and_check_md5, diff_mse DATA_DIR = \"../data/dataset/testImageNetData/train/\"", "and python op\") # Invert Images in cpp data_set =", "enumerate(ds_invert): if idx == 0: images_invert = image.asnumpy() else: images_invert", "(0, 2, 3, 1)) else: images_invert = np.append(images_invert, np.transpose(image.asnumpy(), (0,", "images_invert = np.transpose(image.asnumpy(), (0, 2, 3, 1)) else: images_invert =", "implied. # See the License for the specific language governing", "{}\".format(str(np.mean(mse)))) if plot: visualize_list(images_original, images_invert) def test_invert_c(plot=False): \"\"\" Test Invert", "under the Apache License, Version 2.0 (the \"License\"); # you", "= np.append(images_invert, np.transpose(image.asnumpy(), (0, 2, 3, 1)), axis=0) num_samples =", "transforms_invert = [C.Decode(), C.Resize(size=[224, 224]), C.Invert(), F.ToTensor()] data = data_set.map(operations=transforms_invert,", "image.asnumpy(), axis=0) if plot: visualize_list(images_original, images_invert) num_samples = images_original.shape[0] mse", "np.transpose(image.asnumpy(), (0, 2, 3, 1)), axis=0) # Color Inverted Images", "with md5 check\") # Generate dataset data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False)", "ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False) transform_invert = [C.Decode(), C.Resize(size=[224, 224]), C.Invert()] ds_invert =", "dataset data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False) transforms_invert = [C.Decode(), C.Resize(size=[224, 224]),", "by applicable law or agreed to in writing, software #", "enumerate(ds_c_invert): if idx == 0: images_c_invert = image.asnumpy() else: images_c_invert", "F.Resize((224, 224)), F.ToTensor()]) ds_original = data_set.map(operations=transforms_original, input_columns=\"image\") ds_original = ds_original.batch(512)", "data_set.map(operations=[C.Decode(), C.Resize((224, 224))], input_columns=[\"image\"]) transforms_p_invert = mindspore.dataset.transforms.py_transforms.Compose([lambda img: img.astype(np.uint8), F.ToPIL(),", "2020 Huawei Technologies Co., Ltd # # Licensed under the", "= images_c_invert.shape[0] mse = np.zeros(num_samples) for i in range(num_samples): mse[i]", "np.append(images_invert, np.transpose(image.asnumpy(), (0, 2, 3, 1)), axis=0) num_samples = images_original.shape[0]", "data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False) transform_invert = [C.Decode(), C.Resize(size=[224, 224]), C.Invert()]", "image.asnumpy() else: images_c_invert = np.append(images_c_invert, image.asnumpy(), axis=0) # invert images", "ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False) transforms_invert = [C.Decode(), C.Resize(size=[224, 224]), C.Invert(), F.ToTensor()] data", "_) in enumerate(ds_original): if idx == 0: images_original = np.transpose(image.asnumpy(),", "num_samples = images_c_invert.shape[0] mse = np.zeros(num_samples) for i in range(num_samples):", "np.transpose(image.asnumpy(), (0, 2, 3, 1)) else: images_invert = np.append(images_invert, np.transpose(image.asnumpy(),", "mindspore.dataset.transforms.py_transforms import mindspore.dataset.vision.py_transforms as F import mindspore.dataset.vision.c_transforms as C from", "ds_invert = data_set.map(operations=transform_invert, input_columns=\"image\") ds_invert = ds_invert.batch(512) for idx, (image,", "= image.asnumpy() else: images_c_invert = np.append(images_c_invert, image.asnumpy(), axis=0) # invert", "image.asnumpy(), axis=0) # invert images in python data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR,", "from util import visualize_list, save_and_check_md5, diff_mse DATA_DIR = \"../data/dataset/testImageNetData/train/\" GENERATE_GOLDEN", "def test_invert_py(plot=False): \"\"\" Test Invert python op \"\"\" logger.info(\"Test Invert", "= data_set.map(operations=[C.Decode(), C.Resize((224, 224)), lambda img: np.array(img[:, :, 0])], input_columns=[\"image\"])", "Generate dataset data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False) transforms_invert = mindspore.dataset.transforms.py_transforms.Compose([F.Decode(), F.Invert(),", "F.ToTensor()] data = data_set.map(operations=transforms_invert, input_columns=\"image\") # Compare with expected md5", "Images\") c_op = C.Invert() try: data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False) data_set", "ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False) data_set = data_set.map(operations=[C.Decode(), C.Resize((224, 224)), lambda img: np.array(img[:,", "as np import mindspore.dataset as ds import mindspore.dataset.transforms.py_transforms import mindspore.dataset.vision.py_transforms", "visualize_list(images_original, images_invert) num_samples = images_original.shape[0] mse = np.zeros(num_samples) for i", "as ds import mindspore.dataset.transforms.py_transforms import mindspore.dataset.vision.py_transforms as F import mindspore.dataset.vision.c_transforms", "test_invert_c(plot=False): \"\"\" Test Invert Cpp op \"\"\" logger.info(\"Test Invert cpp", "axis=0) num_samples = images_c_invert.shape[0] mse = np.zeros(num_samples) for i in", "images_original = np.append(images_original, np.transpose(image.asnumpy(), (0, 2, 3, 1)), axis=0) #", "with md5 check \"\"\" logger.info(\"Test Invert python op with md5", "Test Invert Cpp op \"\"\" logger.info(\"Test Invert cpp op\") #", "F.ToTensor()]) data = data_set.map(operations=transforms_invert, input_columns=\"image\") # Compare with expected md5", "\"\"\" Test Invert Cpp op \"\"\" logger.info(\"Test Invert cpp op\")", "Invert cpp and python op\") # Invert Images in cpp", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "data_set.map(operations=[C.Decode(), C.Resize((224, 224))], input_columns=[\"image\"]) ds_c_invert = data_set.map(operations=C.Invert(), input_columns=\"image\") ds_c_invert =", "Unless required by applicable law or agreed to in writing,", "data_set = data_set.map(operations=[C.Decode(), C.Resize((224, 224))], input_columns=[\"image\"]) transforms_p_invert = mindspore.dataset.transforms.py_transforms.Compose([lambda img:", "224))], input_columns=[\"image\"]) transforms_p_invert = mindspore.dataset.transforms.py_transforms.Compose([lambda img: img.astype(np.uint8), F.ToPIL(), F.Invert(), np.array])", "mse[i] = diff_mse(images_invert[i], images_original[i]) logger.info(\"MSE= {}\".format(str(np.mean(mse)))) def test_invert_py_c(plot=False): \"\"\" Test", "input_columns=\"image\") ds_p_invert = ds_p_invert.batch(512) for idx, (image, _) in enumerate(ds_p_invert):", "= ds_c_invert.batch(512) for idx, (image, _) in enumerate(ds_c_invert): if idx", "cpp op with md5 check \"\"\" logger.info(\"Test Invert cpp op", "with one channel image \"\"\" logger.info(\"Test Invert C Op With", "== 0: images_c_invert = image.asnumpy() else: images_c_invert = np.append(images_c_invert, image.asnumpy(),", "Technologies Co., Ltd # # Licensed under the Apache License,", "the specific language governing permissions and # limitations under the", "op in DE \"\"\" import numpy as np import mindspore.dataset", "test_invert_md5_c(): \"\"\" Test Invert cpp op with md5 check \"\"\"", "as logger from util import visualize_list, save_and_check_md5, diff_mse DATA_DIR =", "np.zeros(num_samples) for i in range(num_samples): mse[i] = np.mean((images_invert[i] - images_original[i])", "mse = np.zeros(num_samples) for i in range(num_samples): mse[i] = diff_mse(images_p_invert[i],", "ds_c_invert = data_set.map(operations=C.Invert(), input_columns=\"image\") ds_c_invert = ds_c_invert.batch(512) for idx, (image,", "applicable law or agreed to in writing, software # distributed", "C.Invert()] ds_invert = data_set.map(operations=transform_invert, input_columns=\"image\") ds_invert = ds_invert.batch(512) for idx,", "= np.append(images_invert, image.asnumpy(), axis=0) if plot: visualize_list(images_original, images_invert) num_samples =", "op with one channel image \"\"\" logger.info(\"Test Invert C Op", "enumerate(ds_invert): if idx == 0: images_invert = np.transpose(image.asnumpy(), (0, 2,", "with md5 check \"\"\" logger.info(\"Test Invert cpp op with md5", "shuffle=False) transforms_original = mindspore.dataset.transforms.py_transforms.Compose([F.Decode(), F.Resize((224, 224)), F.ToTensor()]) ds_original = data_set.map(operations=transforms_original,", "2, 3, 1)) else: images_invert = np.append(images_invert, np.transpose(image.asnumpy(), (0, 2,", "op \"\"\" logger.info(\"Test Invert Python op\") # Original Images data_set", "else: images_original = np.append(images_original, np.transpose(image.asnumpy(), (0, 2, 3, 1)), axis=0)", "in writing, software # distributed under the License is distributed", "transforms_p_invert = mindspore.dataset.transforms.py_transforms.Compose([lambda img: img.astype(np.uint8), F.ToPIL(), F.Invert(), np.array]) ds_p_invert =", "filename, generate_golden=GENERATE_GOLDEN) def test_invert_md5_c(): \"\"\" Test Invert cpp op with", "= ds_invert.batch(512) for idx, (image, _) in enumerate(ds_invert): if idx", "visualize_mode=2) def test_invert_one_channel(): \"\"\" Test Invert cpp op with one", "[C.Decode(), C.Resize(size=[224, 224]), C.Invert(), F.ToTensor()] data = data_set.map(operations=transforms_invert, input_columns=\"image\") #", "for idx, (image, _) in enumerate(ds_original): if idx == 0:", "mindspore.dataset.vision.py_transforms as F import mindspore.dataset.vision.c_transforms as C from mindspore import", "def test_invert_c(plot=False): \"\"\" Test Invert Cpp op \"\"\" logger.info(\"Test Invert", "input_columns=\"image\") ds_c_invert = ds_c_invert.batch(512) for idx, (image, _) in enumerate(ds_c_invert):", "Compare with expected md5 from images filename = \"invert_01_result_py.npz\" save_and_check_md5(data,", "mse[i] = diff_mse(images_p_invert[i], images_c_invert[i]) logger.info(\"MSE= {}\".format(str(np.mean(mse)))) if plot: visualize_list(images_c_invert, images_p_invert,", "e: logger.info(\"Got an exception in DE: {}\".format(str(e))) assert \"The shape\"", "ds_p_invert = data_set.map(operations=transforms_p_invert, input_columns=\"image\") ds_p_invert = ds_p_invert.batch(512) for idx, (image,", "= data_set.map(operations=transforms_invert, input_columns=\"image\") ds_invert = ds_invert.batch(512) for idx, (image, _)", "input_columns=[\"image\"]) data_set.map(operations=c_op, input_columns=\"image\") except RuntimeError as e: logger.info(\"Got an exception", "python op with md5 check \"\"\" logger.info(\"Test Invert python op", "License is distributed on an \"AS IS\" BASIS, # WITHOUT", "License, Version 2.0 (the \"License\"); # you may not use", "idx == 0: images_original = np.transpose(image.asnumpy(), (0, 2, 3, 1))", "= np.transpose(image.asnumpy(), (0, 2, 3, 1)) else: images_original = np.append(images_original,", "# You may obtain a copy of the License at", "python op \"\"\" logger.info(\"Test Invert cpp and python op\") #", "# Compare with expected md5 from images filename = \"invert_01_result_py.npz\"", "# Copyright 2020 Huawei Technologies Co., Ltd # # Licensed", "images_invert = image.asnumpy() else: images_invert = np.append(images_invert, image.asnumpy(), axis=0) if", "Cpp op \"\"\" logger.info(\"Test Invert cpp op\") # Original Images", "\"\"\" Test Invert python op with md5 check \"\"\" logger.info(\"Test", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "the License. # ============================================================================== \"\"\" Testing Invert op in DE", "= np.zeros(num_samples) for i in range(num_samples): mse[i] = diff_mse(images_p_invert[i], images_c_invert[i])", "\"\"\" logger.info(\"Test Invert cpp op\") # Original Images data_set =", "_) in enumerate(ds_original): if idx == 0: images_original = image.asnumpy()", "data_set = data_set.map(operations=[C.Decode(), C.Resize((224, 224))], input_columns=[\"image\"]) ds_c_invert = data_set.map(operations=C.Invert(), input_columns=\"image\")", "import log as logger from util import visualize_list, save_and_check_md5, diff_mse", "logger.info(\"MSE= {}\".format(str(np.mean(mse)))) if plot: visualize_list(images_c_invert, images_p_invert, visualize_mode=2) def test_invert_one_channel(): \"\"\"", "the License for the specific language governing permissions and #", "Apache License, Version 2.0 (the \"License\"); # you may not", "plot: visualize_list(images_original, images_invert) def test_invert_c(plot=False): \"\"\" Test Invert Cpp op", "images_p_invert, visualize_mode=2) def test_invert_one_channel(): \"\"\" Test Invert cpp op with", "transform_invert = [C.Decode(), C.Resize(size=[224, 224]), C.Invert()] ds_invert = data_set.map(operations=transform_invert, input_columns=\"image\")", "either express or implied. # See the License for the", "op \"\"\" logger.info(\"Test Invert cpp op\") # Original Images data_set", "one channel image \"\"\" logger.info(\"Test Invert C Op With One", "enumerate(ds_original): if idx == 0: images_original = np.transpose(image.asnumpy(), (0, 2,", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "C.Resize(size=[224, 224]), C.Invert()] ds_invert = data_set.map(operations=transform_invert, input_columns=\"image\") ds_invert = ds_invert.batch(512)", "= \"invert_01_result_py.npz\" save_and_check_md5(data, filename, generate_golden=GENERATE_GOLDEN) def test_invert_md5_c(): \"\"\" Test Invert", "0: images_original = image.asnumpy() else: images_original = np.append(images_original, image.asnumpy(), axis=0)", "0: images_invert = image.asnumpy() else: images_invert = np.append(images_invert, image.asnumpy(), axis=0)", "from images filename = \"invert_01_result_c.npz\" save_and_check_md5(data, filename, generate_golden=GENERATE_GOLDEN) if __name__", "data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False) data_set = data_set.map(operations=[C.Decode(), C.Resize((224, 224))], input_columns=[\"image\"])", "# limitations under the License. # ============================================================================== \"\"\" Testing Invert", "idx == 0: images_c_invert = image.asnumpy() else: images_c_invert = np.append(images_c_invert,", "in enumerate(ds_invert): if idx == 0: images_invert = image.asnumpy() else:", "def test_invert_md5_py(): \"\"\" Test Invert python op with md5 check", "GENERATE_GOLDEN = False def test_invert_py(plot=False): \"\"\" Test Invert python op", "= ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False) data_set = data_set.map(operations=[C.Decode(), C.Resize((224, 224))], input_columns=[\"image\"]) transforms_p_invert", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "in enumerate(ds_original): if idx == 0: images_original = np.transpose(image.asnumpy(), (0,", "= data_set.map(operations=[C.Decode(), C.Resize((224, 224))], input_columns=[\"image\"]) ds_c_invert = data_set.map(operations=C.Invert(), input_columns=\"image\") ds_c_invert", "(0, 2, 3, 1)), axis=0) num_samples = images_original.shape[0] mse =", "# Compare with expected md5 from images filename = \"invert_01_result_c.npz\"", "224])] ds_original = data_set.map(operations=transforms_original, input_columns=\"image\") ds_original = ds_original.batch(512) for idx,", "np.append(images_original, image.asnumpy(), axis=0) # Invert Images data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False)", "plot: visualize_list(images_c_invert, images_p_invert, visualize_mode=2) def test_invert_one_channel(): \"\"\" Test Invert cpp", "md5 check \"\"\" logger.info(\"Test Invert cpp op with md5 check\")", "images_invert = np.append(images_invert, np.transpose(image.asnumpy(), (0, 2, 3, 1)), axis=0) num_samples", "md5 from images filename = \"invert_01_result_c.npz\" save_and_check_md5(data, filename, generate_golden=GENERATE_GOLDEN) if", "md5 from images filename = \"invert_01_result_py.npz\" save_and_check_md5(data, filename, generate_golden=GENERATE_GOLDEN) def", "Invert python op with md5 check\") # Generate dataset data_set", "mse[i] = np.mean((images_invert[i] - images_original[i]) ** 2) logger.info(\"MSE= {}\".format(str(np.mean(mse)))) if", "with expected md5 from images filename = \"invert_01_result_py.npz\" save_and_check_md5(data, filename,", "- images_original[i]) ** 2) logger.info(\"MSE= {}\".format(str(np.mean(mse)))) if plot: visualize_list(images_original, images_invert)", "for idx, (image, _) in enumerate(ds_p_invert): if idx == 0:", "logger.info(\"Test Invert Python op\") # Original Images data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR,", "def test_invert_py_c(plot=False): \"\"\" Test Invert Cpp op and python op", "F.ToPIL(), F.Invert(), np.array]) ds_p_invert = data_set.map(operations=transforms_p_invert, input_columns=\"image\") ds_p_invert = ds_p_invert.batch(512)", "in enumerate(ds_p_invert): if idx == 0: images_p_invert = image.asnumpy() else:", "= np.append(images_c_invert, image.asnumpy(), axis=0) # invert images in python data_set", "\"License\"); # you may not use this file except in", "============================================================================== \"\"\" Testing Invert op in DE \"\"\" import numpy", "shuffle=False) transforms_invert = [C.Decode(), C.Resize(size=[224, 224]), C.Invert(), F.ToTensor()] data =", "check\") # Generate dataset data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False) transforms_invert =", "np.append(images_c_invert, image.asnumpy(), axis=0) # invert images in python data_set =", "# Original Images data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False) transforms_original = [C.Decode(),", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "idx == 0: images_original = image.asnumpy() else: images_original = np.append(images_original,", "import mindspore.dataset as ds import mindspore.dataset.transforms.py_transforms import mindspore.dataset.vision.py_transforms as F", "= ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False) transform_invert = [C.Decode(), C.Resize(size=[224, 224]), C.Invert()] ds_invert", "mindspore import log as logger from util import visualize_list, save_and_check_md5,", "# distributed under the License is distributed on an \"AS", "= ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False) transforms_original = mindspore.dataset.transforms.py_transforms.Compose([F.Decode(), F.Resize((224, 224)), F.ToTensor()]) ds_original", "1)), axis=0) # Color Inverted Images data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False)", "cpp and python op\") # Invert Images in cpp data_set", "# Unless required by applicable law or agreed to in", "logger.info(\"Test Invert cpp op\") # Original Images data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR,", "input_columns=\"image\") # Compare with expected md5 from images filename =", "img: np.array(img[:, :, 0])], input_columns=[\"image\"]) data_set.map(operations=c_op, input_columns=\"image\") except RuntimeError as", "(0, 2, 3, 1)) else: images_original = np.append(images_original, np.transpose(image.asnumpy(), (0,", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "assert \"The shape\" in str(e) def test_invert_md5_py(): \"\"\" Test Invert", "with expected md5 from images filename = \"invert_01_result_c.npz\" save_and_check_md5(data, filename,", "images_c_invert[i]) logger.info(\"MSE= {}\".format(str(np.mean(mse)))) if plot: visualize_list(images_c_invert, images_p_invert, visualize_mode=2) def test_invert_one_channel():", "You may obtain a copy of the License at #", "if idx == 0: images_original = np.transpose(image.asnumpy(), (0, 2, 3,", "DE: {}\".format(str(e))) assert \"The shape\" in str(e) def test_invert_md5_py(): \"\"\"", "# Invert Images data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False) transform_invert = [C.Decode(),", "invert images in python data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False) data_set =", "0: images_c_invert = image.asnumpy() else: images_c_invert = np.append(images_c_invert, image.asnumpy(), axis=0)", "= data_set.map(operations=[C.Decode(), C.Resize((224, 224))], input_columns=[\"image\"]) transforms_p_invert = mindspore.dataset.transforms.py_transforms.Compose([lambda img: img.astype(np.uint8),", "images_invert) def test_invert_c(plot=False): \"\"\" Test Invert Cpp op \"\"\" logger.info(\"Test", "cpp op\") # Original Images data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False) transforms_original", ":, 0])], input_columns=[\"image\"]) data_set.map(operations=c_op, input_columns=\"image\") except RuntimeError as e: logger.info(\"Got", "F.Invert(), F.ToTensor()]) data = data_set.map(operations=transforms_invert, input_columns=\"image\") # Compare with expected", "mse = np.zeros(num_samples) for i in range(num_samples): mse[i] = np.mean((images_invert[i]", "the Apache License, Version 2.0 (the \"License\"); # you may", "generate_golden=GENERATE_GOLDEN) if __name__ == \"__main__\": test_invert_py(plot=False) test_invert_c(plot=False) test_invert_py_c(plot=False) test_invert_one_channel() test_invert_md5_py()", "= np.zeros(num_samples) for i in range(num_samples): mse[i] = diff_mse(images_invert[i], images_original[i])", "Color Inverted Images data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False) transforms_invert = mindspore.dataset.transforms.py_transforms.Compose([F.Decode(),", "axis=0) # Color Inverted Images data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False) transforms_invert", "Images data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False) transforms_original = mindspore.dataset.transforms.py_transforms.Compose([F.Decode(), F.Resize((224, 224))," ]
[ "[(1, 0), (0, 1)]], [(4, 4), [(3, 4), (4, 3)]]]:", "0), [(1, 0), (0, 1)]], [(4, 4), [(3, 4), (4,", "1)]], [(4, 4), [(3, 4), (4, 3)]]]: self.assertListEqual( collector.get_next_positions(pos), expected", "m, t, candies) for pos, expected in [[(1, 1), [(0,", "1, 1, 1, 1], [2, 2, 1, 1, 1], [1,", "(1, 0), (1, 2)]], [(0, 0), [(1, 0), (0, 1)]],", "(2, 1), (1, 0), (1, 2)]], [(0, 0), [(1, 0),", "[1, 2, 1, 1, 1], [2, 2, 1, 1, 3],", "expected in [[(1, 1), [(0, 1), (2, 1), (1, 0),", ") def test_candy(self, n, m, t, candies): collector = candy.CollectCandies(n,", "[(3, 4), (4, 3)]]]: self.assertListEqual( collector.get_next_positions(pos), expected + [pos]) self.assertEqual(collector.get_max_sum(),", "1], [2, 2, 1, 1, 1], [1, 2, 1, 1,", "class TestCollectCandies(TestCase): @parameterized.expand( [(5, 5, 12, [[2, 1, 1, 1,", "4), [(3, 4), (4, 3)]]]: self.assertListEqual( collector.get_next_positions(pos), expected + [pos])", "2, 1, 1, 3], [2, 2, 2, 2, 2]])] )", "(0, 1)]], [(4, 4), [(3, 4), (4, 3)]]]: self.assertListEqual( collector.get_next_positions(pos),", "pos, expected in [[(1, 1), [(0, 1), (2, 1), (1,", "for pos, expected in [[(1, 1), [(0, 1), (2, 1),", "import TestCase from .. import candy class TestCollectCandies(TestCase): @parameterized.expand( [(5,", "1), [(0, 1), (2, 1), (1, 0), (1, 2)]], [(0,", "[[(1, 1), [(0, 1), (2, 1), (1, 0), (1, 2)]],", "0), (1, 2)]], [(0, 0), [(1, 0), (0, 1)]], [(4,", "1, 1, 1], [1, 2, 1, 1, 1], [2, 2,", "1, 1, 3], [2, 2, 2, 2, 2]])] ) def", "= candy.CollectCandies(n, m, t, candies) for pos, expected in [[(1,", "12, [[2, 1, 1, 1, 1], [2, 2, 1, 1,", "[(4, 4), [(3, 4), (4, 3)]]]: self.assertListEqual( collector.get_next_positions(pos), expected +", "[2, 2, 1, 1, 1], [1, 2, 1, 1, 1],", "1), (1, 0), (1, 2)]], [(0, 0), [(1, 0), (0,", "@parameterized.expand( [(5, 5, 12, [[2, 1, 1, 1, 1], [2,", "5, 12, [[2, 1, 1, 1, 1], [2, 2, 1,", "2)]], [(0, 0), [(1, 0), (0, 1)]], [(4, 4), [(3,", "[(0, 1), (2, 1), (1, 0), (1, 2)]], [(0, 0),", "[[2, 1, 1, 1, 1], [2, 2, 1, 1, 1],", "(1, 2)]], [(0, 0), [(1, 0), (0, 1)]], [(4, 4),", "1, 1], [2, 2, 1, 1, 3], [2, 2, 2,", "numpy.testing import TestCase from .. import candy class TestCollectCandies(TestCase): @parameterized.expand(", "1], [1, 2, 1, 1, 1], [2, 2, 1, 1,", "candies) for pos, expected in [[(1, 1), [(0, 1), (2,", "0), (0, 1)]], [(4, 4), [(3, 4), (4, 3)]]]: self.assertListEqual(", "import candy class TestCollectCandies(TestCase): @parameterized.expand( [(5, 5, 12, [[2, 1,", ".. import candy class TestCollectCandies(TestCase): @parameterized.expand( [(5, 5, 12, [[2,", "parameterized from numpy.testing import TestCase from .. import candy class", "2, 2, 2, 2]])] ) def test_candy(self, n, m, t,", "candies): collector = candy.CollectCandies(n, m, t, candies) for pos, expected", "2, 2]])] ) def test_candy(self, n, m, t, candies): collector", "m, t, candies): collector = candy.CollectCandies(n, m, t, candies) for", "def test_candy(self, n, m, t, candies): collector = candy.CollectCandies(n, m,", "TestCollectCandies(TestCase): @parameterized.expand( [(5, 5, 12, [[2, 1, 1, 1, 1],", "from .. import candy class TestCollectCandies(TestCase): @parameterized.expand( [(5, 5, 12,", "2, 1, 1, 1], [2, 2, 1, 1, 3], [2,", "[(0, 0), [(1, 0), (0, 1)]], [(4, 4), [(3, 4),", "1), (2, 1), (1, 0), (1, 2)]], [(0, 0), [(1,", "1, 1], [2, 2, 1, 1, 1], [1, 2, 1,", "candy.CollectCandies(n, m, t, candies) for pos, expected in [[(1, 1),", "2]])] ) def test_candy(self, n, m, t, candies): collector =", "collector = candy.CollectCandies(n, m, t, candies) for pos, expected in", "t, candies) for pos, expected in [[(1, 1), [(0, 1),", "from parameterized import parameterized from numpy.testing import TestCase from ..", "[2, 2, 2, 2, 2]])] ) def test_candy(self, n, m,", "4), (4, 3)]]]: self.assertListEqual( collector.get_next_positions(pos), expected + [pos]) self.assertEqual(collector.get_max_sum(), 27)", "2, 1, 1, 1], [1, 2, 1, 1, 1], [2,", "candy class TestCollectCandies(TestCase): @parameterized.expand( [(5, 5, 12, [[2, 1, 1,", "t, candies): collector = candy.CollectCandies(n, m, t, candies) for pos,", "1, 3], [2, 2, 2, 2, 2]])] ) def test_candy(self,", "[2, 2, 1, 1, 3], [2, 2, 2, 2, 2]])]", "n, m, t, candies): collector = candy.CollectCandies(n, m, t, candies)", "import parameterized from numpy.testing import TestCase from .. import candy", "parameterized import parameterized from numpy.testing import TestCase from .. import", "test_candy(self, n, m, t, candies): collector = candy.CollectCandies(n, m, t,", "TestCase from .. import candy class TestCollectCandies(TestCase): @parameterized.expand( [(5, 5,", "from numpy.testing import TestCase from .. import candy class TestCollectCandies(TestCase):", "3], [2, 2, 2, 2, 2]])] ) def test_candy(self, n,", "1], [2, 2, 1, 1, 3], [2, 2, 2, 2,", "1, 1, 1], [2, 2, 1, 1, 1], [1, 2,", "in [[(1, 1), [(0, 1), (2, 1), (1, 0), (1,", "1, 1], [1, 2, 1, 1, 1], [2, 2, 1,", "2, 2, 2]])] ) def test_candy(self, n, m, t, candies):", "1, 1, 1], [2, 2, 1, 1, 3], [2, 2,", "[(5, 5, 12, [[2, 1, 1, 1, 1], [2, 2," ]
[ "os.uname()[0].startswith(\"Darw\"): import pygame pygame.mixer.init() # Plays a song def playSong(filename):", "\"play song\" if not os.uname()[0].startswith(\"Darw\"): pygame.mixer.music.fadeout(1000) #fadeout current music over", "music over 1 sec. pygame.mixer.music.load(\"music/\" + filename) pygame.mixer.music.play() else: subprocess.call([\"afplay\",", "os print os.uname() if not os.uname()[0].startswith(\"Darw\"): import pygame pygame.mixer.init() #", "subprocess import os print os.uname() if not os.uname()[0].startswith(\"Darw\"): import pygame", "sec. pygame.mixer.music.load(\"music/\" + filename) pygame.mixer.music.play() else: subprocess.call([\"afplay\", \"music/\" + filename])", "#fadeout current music over 1 sec. pygame.mixer.music.load(\"music/\" + filename) pygame.mixer.music.play()", "current music over 1 sec. pygame.mixer.music.load(\"music/\" + filename) pygame.mixer.music.play() else:", "os.uname()[0].startswith(\"Darw\"): pygame.mixer.music.fadeout(1000) #fadeout current music over 1 sec. pygame.mixer.music.load(\"music/\" +", "song def playSong(filename): print \"play song\" if not os.uname()[0].startswith(\"Darw\"): pygame.mixer.music.fadeout(1000)", "import subprocess import os print os.uname() if not os.uname()[0].startswith(\"Darw\"): import", "print os.uname() if not os.uname()[0].startswith(\"Darw\"): import pygame pygame.mixer.init() # Plays", "if not os.uname()[0].startswith(\"Darw\"): pygame.mixer.music.fadeout(1000) #fadeout current music over 1 sec.", "over 1 sec. pygame.mixer.music.load(\"music/\" + filename) pygame.mixer.music.play() else: subprocess.call([\"afplay\", \"music/\"", "not os.uname()[0].startswith(\"Darw\"): pygame.mixer.music.fadeout(1000) #fadeout current music over 1 sec. pygame.mixer.music.load(\"music/\"", "a song def playSong(filename): print \"play song\" if not os.uname()[0].startswith(\"Darw\"):", "time import subprocess import os print os.uname() if not os.uname()[0].startswith(\"Darw\"):", "playSong(filename): print \"play song\" if not os.uname()[0].startswith(\"Darw\"): pygame.mixer.music.fadeout(1000) #fadeout current", "pygame.mixer.music.fadeout(1000) #fadeout current music over 1 sec. pygame.mixer.music.load(\"music/\" + filename)", "1 sec. pygame.mixer.music.load(\"music/\" + filename) pygame.mixer.music.play() else: subprocess.call([\"afplay\", \"music/\" +", "pygame pygame.mixer.init() # Plays a song def playSong(filename): print \"play", "not os.uname()[0].startswith(\"Darw\"): import pygame pygame.mixer.init() # Plays a song def", "# Plays a song def playSong(filename): print \"play song\" if", "print \"play song\" if not os.uname()[0].startswith(\"Darw\"): pygame.mixer.music.fadeout(1000) #fadeout current music", "pygame.mixer.init() # Plays a song def playSong(filename): print \"play song\"", "Plays a song def playSong(filename): print \"play song\" if not", "song\" if not os.uname()[0].startswith(\"Darw\"): pygame.mixer.music.fadeout(1000) #fadeout current music over 1", "import time import subprocess import os print os.uname() if not", "def playSong(filename): print \"play song\" if not os.uname()[0].startswith(\"Darw\"): pygame.mixer.music.fadeout(1000) #fadeout", "import os print os.uname() if not os.uname()[0].startswith(\"Darw\"): import pygame pygame.mixer.init()", "if not os.uname()[0].startswith(\"Darw\"): import pygame pygame.mixer.init() # Plays a song", "os.uname() if not os.uname()[0].startswith(\"Darw\"): import pygame pygame.mixer.init() # Plays a", "import pygame pygame.mixer.init() # Plays a song def playSong(filename): print" ]
[ "this is a failure self.assertTrue(False, err_msg) except Exception as e:", "of `get_item`.\"\"\" self.handler.table.get_item.return_value = { \"TheWrongKey\": dict(field1=\"1\", field2=\"2\") } self.assertIsNone(self.handler.get_item(\"key\"))", "mock.MagicMock() def setUp(self): self.handler.table.reset_mock() def test_get_item(self): \"\"\"Test a successful invocation", "three=3) self.handler.insert_item(data) self.handler.table.put_item.assert_called_once_with(Item=data) def test_update_item(self): \"\"\"Test a successful invocation of", "\"\"\"Test a successful invocation of `delete_item`.\"\"\" key = {\"id\": 1234}", "aws_tools.dynamodb_handler.DynamoDBHandler(\"table_name\") cls.handler.table = mock.MagicMock() def setUp(self): self.handler.table.reset_mock() def test_get_item(self): \"\"\"Test", "FilterExpression parameter for table.scan() but non found' try: self.handler.table.scan.assert_called_once_with() #", "\"is_in\", \"contains\"): self.handler.table.reset_mock() query = { \"ready\": False } data", "err_msg in str(e): raise e def test_query_item_no_query(self): \"\"\"Test a invocation", "test_update_item(self): \"\"\"Test a successful invocation of `update_item`.\"\"\" key = {\"id\":", "_, kwargs = self.handler.table.update_item.call_args self.assertIn(\"Key\", kwargs) self.assertEqual(kwargs[\"Key\"], key) self.assertIn(\"UpdateExpression\", kwargs)", "\"ready\": False} self.handler.table.scan.return_value = {\"Items\": data} self.assertEqual(self.handler.query_items(query), data) self.handler.table.scan.assert_called_once() err_msg", "a successful invocation of `insert_item`.\"\"\" data = dict(x=\"x\", y=\"y\", three=3)", "data = {\"age\": 30, \"full_name\": \"<NAME>\"} self.handler.table.scan.return_value = {\"Items\": data}", "def test_query_bool_item(self): \"\"\" Test a successful invocation of `query_item`. with", "1234} self.handler.delete_item(key) self.handler.table.delete_item.assert_called_once_with(Key=key) def test_query_item(self): \"\"\" Test a successful invocation", "Test a successful invocation of `query_item`. with a False boolean", "{\"age\": 30, \"full_name\": \"<NAME>\"} self.handler.table.scan.return_value = {\"Items\": data} self.assertEqual(self.handler.query_items(), data)", "\"<NAME>\"} self.handler.update_item(key, data) self.handler.table.update_item.assert_called_once() _, kwargs = self.handler.table.update_item.call_args self.assertIn(\"Key\", kwargs)", "self.assertIsNone(self.handler.get_item(\"key\")) def test_insert_item(self): \"\"\"Test a successful invocation of `insert_item`.\"\"\" data", "40, \"name\": \"<NAME>\"} self.handler.update_item(key, data) self.handler.table.update_item.assert_called_once() _, kwargs = self.handler.table.update_item.call_args", "{\"age\": 30, \"full_name\": \"<NAME>\", \"ready\": False} self.handler.table.scan.return_value = {\"Items\": data}", "} } data = {\"age\": 30, \"full_name\": \"<NAME>\"} self.handler.table.scan.return_value =", "query\"\"\" for cond in (\"ne\", \"lt\", \"lte\", \"gt\", \"gte\", \"begins_with\",", "non found' try: self.handler.table.scan.assert_called_once_with() # If the scan ran without", "whitespace and order of assignments expr = kwargs[\"UpdateExpression\"].replace(\" \", \"\")", "\"begins_with\", \"is_in\", \"contains\"): self.handler.table.reset_mock() query = { \"ready\": False }", "data = dict(x=\"x\", y=\"y\", three=3) self.handler.insert_item(data) self.handler.table.put_item.assert_called_once_with(Item=data) def test_update_item(self): \"\"\"Test", "data = {\"age\": 40, \"name\": \"<NAME>\"} self.handler.update_item(key, data) self.handler.table.update_item.assert_called_once() _,", "\"contains\"): self.handler.table.reset_mock() query = { \"ready\": False } data =", "test_query_bool_item(self): \"\"\" Test a successful invocation of `query_item`. with a", "mock.MagicMock()): cls.handler = aws_tools.dynamodb_handler.DynamoDBHandler(\"table_name\") cls.handler.table = mock.MagicMock() def setUp(self): self.handler.table.reset_mock()", "= dict(field1=\"1\", field2=\"2\") self.handler.table.get_item.return_value = { \"Item\": expected } self.assertEqual(self.handler.get_item(\"key\"),", "invocation of `insert_item`.\"\"\" data = dict(x=\"x\", y=\"y\", three=3) self.handler.insert_item(data) self.handler.table.put_item.assert_called_once_with(Item=data)", "= {\"id\": 1} data = {\"age\": 40, \"name\": \"<NAME>\"} self.handler.update_item(key,", "\"\"\" Test a successful invocation of `query_item`.\"\"\" for cond in", "data) self.handler.table.scan.assert_called_once() def test_query_bool_item(self): \"\"\" Test a successful invocation of", "from boto3.dynamodb.conditions import Attr class DynamoDBHandlerTests(unittest.TestCase): @classmethod def setUpClass(cls): with", "{\"#item_name\": \"name\"}) def test_delete_item(self): \"\"\"Test a successful invocation of `delete_item`.\"\"\"", "with a False boolean query\"\"\" for cond in (\"ne\", \"lt\",", "of `delete_item`.\"\"\" key = {\"id\": 1234} self.handler.delete_item(key) self.handler.table.delete_item.assert_called_once_with(Key=key) def test_query_item(self):", "= { \"TheWrongKey\": dict(field1=\"1\", field2=\"2\") } self.assertIsNone(self.handler.get_item(\"key\")) def test_insert_item(self): \"\"\"Test", "30, \"full_name\": \"<NAME>\"} self.handler.table.scan.return_value = {\"Items\": data} self.assertEqual(self.handler.query_items(query), data) self.handler.table.scan.assert_called_once()", "# If the scan ran without an argument this is", "= aws_tools.dynamodb_handler.DynamoDBHandler(\"table_name\") cls.handler.table = mock.MagicMock() def setUp(self): self.handler.table.reset_mock() def test_get_item(self):", "from __future__ import absolute_import, unicode_literals, print_function import mock import unittest", "\"<NAME>\", \"ready\": False} self.handler.table.scan.return_value = {\"Items\": data} self.assertEqual(self.handler.query_items(query), data) self.handler.table.scan.assert_called_once()", "query.\"\"\" data = {\"age\": 30, \"full_name\": \"<NAME>\"} self.handler.table.scan.return_value = {\"Items\":", "30, \"full_name\": \"<NAME>\"} self.handler.table.scan.return_value = {\"Items\": data} self.assertEqual(self.handler.query_items(), data) self.handler.table.scan.assert_called_once_with()", "err_msg = 'query_items: Expecting FilterExpression parameter for table.scan() but non", "# ignore whitespace and order of assignments expr = kwargs[\"UpdateExpression\"].replace(\"", "query = { \"age\": { \"condition\": \"eq\", \"value\": 25 },", "self.handler.table.scan.assert_called_once() def test_query_bool_item(self): \"\"\" Test a successful invocation of `query_item`.", "self.assertIn(\"age=:age\", expr) self.assertIn(\"#item_name=:name\", expr) self.assertIn(\"ExpressionAttributeValues\", kwargs) self.assertEqual(kwargs[\"ExpressionAttributeValues\"], {\":age\": 40, \":name\":", "self.assertIn(\"ExpressionAttributeNames\", kwargs) self.assertEqual(kwargs[\"ExpressionAttributeNames\"], {\"#item_name\": \"name\"}) def test_delete_item(self): \"\"\"Test a successful", "in str(e): raise e def test_query_item_no_query(self): \"\"\"Test a invocation of", "\"is_in\", \"contains\"): self.handler.table.reset_mock() query = { \"age\": { \"condition\": \"eq\",", "False boolean query\"\"\" for cond in (\"ne\", \"lt\", \"lte\", \"gt\",", "def test_insert_item(self): \"\"\"Test a successful invocation of `insert_item`.\"\"\" data =", "self.assertEqual(kwargs[\"ExpressionAttributeValues\"], {\":age\": 40, \":name\": \"<NAME>\"}) self.assertIn(\"ExpressionAttributeNames\", kwargs) self.assertEqual(kwargs[\"ExpressionAttributeNames\"], {\"#item_name\": \"name\"})", "err_msg) except Exception as e: if err_msg in str(e): raise", "except Exception as e: if err_msg in str(e): raise e", "parameter for table.scan() but non found' try: self.handler.table.scan.assert_called_once_with() # If", "raise e def test_query_item_no_query(self): \"\"\"Test a invocation of `query_item` with", "class DynamoDBHandlerTests(unittest.TestCase): @classmethod def setUpClass(cls): with mock.patch(\"d43_aws_tools.dynamodb_handler.boto3\", mock.MagicMock()): cls.handler =", "`delete_item`.\"\"\" key = {\"id\": 1234} self.handler.delete_item(key) self.handler.table.delete_item.assert_called_once_with(Key=key) def test_query_item(self): \"\"\"", "dict(field1=\"1\", field2=\"2\") self.handler.table.get_item.return_value = { \"Item\": expected } self.assertEqual(self.handler.get_item(\"key\"), expected)", "\"\"\"Test a successful invocation of `insert_item`.\"\"\" data = dict(x=\"x\", y=\"y\",", "= {\"age\": 40, \"name\": \"<NAME>\"} self.handler.update_item(key, data) self.handler.table.update_item.assert_called_once() _, kwargs", "self.assertTrue(expr.startswith(\"SET\")) self.assertIn(\"age=:age\", expr) self.assertIn(\"#item_name=:name\", expr) self.assertIn(\"ExpressionAttributeValues\", kwargs) self.assertEqual(kwargs[\"ExpressionAttributeValues\"], {\":age\": 40,", "40, \":name\": \"<NAME>\"}) self.assertIn(\"ExpressionAttributeNames\", kwargs) self.assertEqual(kwargs[\"ExpressionAttributeNames\"], {\"#item_name\": \"name\"}) def test_delete_item(self):", "cond in (\"ne\", \"lt\", \"lte\", \"gt\", \"gte\", \"begins_with\", \"is_in\", \"contains\"):", "self.handler.table.delete_item.assert_called_once_with(Key=key) def test_query_item(self): \"\"\" Test a successful invocation of `query_item`.\"\"\"", "unsuccessful invocation of `get_item`.\"\"\" self.handler.table.get_item.return_value = { \"TheWrongKey\": dict(field1=\"1\", field2=\"2\")", "`get_item`.\"\"\" self.handler.table.get_item.return_value = { \"TheWrongKey\": dict(field1=\"1\", field2=\"2\") } self.assertIsNone(self.handler.get_item(\"key\")) def", "(\"ne\", \"lt\", \"lte\", \"gt\", \"gte\", \"begins_with\", \"is_in\", \"contains\"): self.handler.table.reset_mock() query", "\", \"\") self.assertTrue(expr.startswith(\"SET\")) self.assertIn(\"age=:age\", expr) self.assertIn(\"#item_name=:name\", expr) self.assertIn(\"ExpressionAttributeValues\", kwargs) self.assertEqual(kwargs[\"ExpressionAttributeValues\"],", "{ \"age\": { \"condition\": \"eq\", \"value\": 25 }, \"full_name\": {", "cond, \"value\": \"<NAME>\" } } data = {\"age\": 30, \"full_name\":", "self.handler.table.update_item.assert_called_once() _, kwargs = self.handler.table.update_item.call_args self.assertIn(\"Key\", kwargs) self.assertEqual(kwargs[\"Key\"], key) self.assertIn(\"UpdateExpression\",", "test_get_item(self): \"\"\"Test a successful invocation of `get_item`.\"\"\" expected = dict(field1=\"1\",", "\"full_name\": { \"condition\": cond, \"value\": \"<NAME>\" } } data =", "'query_items: Expecting FilterExpression parameter for table.scan() but non found' try:", "= 'query_items: Expecting FilterExpression parameter for table.scan() but non found'", "import d43_aws_tools as aws_tools from boto3.dynamodb.conditions import Attr class DynamoDBHandlerTests(unittest.TestCase):", "invocation of `delete_item`.\"\"\" key = {\"id\": 1234} self.handler.delete_item(key) self.handler.table.delete_item.assert_called_once_with(Key=key) def", "self.handler.update_item(key, data) self.handler.table.update_item.assert_called_once() _, kwargs = self.handler.table.update_item.call_args self.assertIn(\"Key\", kwargs) self.assertEqual(kwargs[\"Key\"],", "Test a successful invocation of `query_item`.\"\"\" for cond in (\"ne\",", "\"ready\": False } data = {\"age\": 30, \"full_name\": \"<NAME>\", \"ready\":", "expected = dict(field1=\"1\", field2=\"2\") self.handler.table.get_item.return_value = { \"Item\": expected }", "self.handler.insert_item(data) self.handler.table.put_item.assert_called_once_with(Item=data) def test_update_item(self): \"\"\"Test a successful invocation of `update_item`.\"\"\"", "= {\"age\": 30, \"full_name\": \"<NAME>\", \"ready\": False} self.handler.table.scan.return_value = {\"Items\":", "invocation of `get_item`.\"\"\" expected = dict(field1=\"1\", field2=\"2\") self.handler.table.get_item.return_value = {", "successful invocation of `delete_item`.\"\"\" key = {\"id\": 1234} self.handler.delete_item(key) self.handler.table.delete_item.assert_called_once_with(Key=key)", "\"eq\", \"value\": 25 }, \"full_name\": { \"condition\": cond, \"value\": \"<NAME>\"", "{\"Items\": data} self.assertEqual(self.handler.query_items(query), data) self.handler.table.scan.assert_called_once() err_msg = 'query_items: Expecting FilterExpression", "{ \"condition\": cond, \"value\": \"<NAME>\" } } data = {\"age\":", "def test_query_item_no_query(self): \"\"\"Test a invocation of `query_item` with no query.\"\"\"", "data} self.assertEqual(self.handler.query_items(query), data) self.handler.table.scan.assert_called_once() err_msg = 'query_items: Expecting FilterExpression parameter", "y=\"y\", three=3) self.handler.insert_item(data) self.handler.table.put_item.assert_called_once_with(Item=data) def test_update_item(self): \"\"\"Test a successful invocation", "Attr class DynamoDBHandlerTests(unittest.TestCase): @classmethod def setUpClass(cls): with mock.patch(\"d43_aws_tools.dynamodb_handler.boto3\", mock.MagicMock()): cls.handler", "def setUpClass(cls): with mock.patch(\"d43_aws_tools.dynamodb_handler.boto3\", mock.MagicMock()): cls.handler = aws_tools.dynamodb_handler.DynamoDBHandler(\"table_name\") cls.handler.table =", "`query_item` with no query.\"\"\" data = {\"age\": 30, \"full_name\": \"<NAME>\"}", "str(e): raise e def test_query_item_no_query(self): \"\"\"Test a invocation of `query_item`", "\"lt\", \"lte\", \"gt\", \"gte\", \"begins_with\", \"is_in\", \"contains\"): self.handler.table.reset_mock() query =", "= dict(x=\"x\", y=\"y\", three=3) self.handler.insert_item(data) self.handler.table.put_item.assert_called_once_with(Item=data) def test_update_item(self): \"\"\"Test a", "False} self.handler.table.scan.return_value = {\"Items\": data} self.assertEqual(self.handler.query_items(query), data) self.handler.table.scan.assert_called_once() err_msg =", "self.handler.table.scan.assert_called_once() err_msg = 'query_items: Expecting FilterExpression parameter for table.scan() but", "`insert_item`.\"\"\" data = dict(x=\"x\", y=\"y\", three=3) self.handler.insert_item(data) self.handler.table.put_item.assert_called_once_with(Item=data) def test_update_item(self):", "{\"age\": 40, \"name\": \"<NAME>\"} self.handler.update_item(key, data) self.handler.table.update_item.assert_called_once() _, kwargs =", "for cond in (\"ne\", \"lt\", \"lte\", \"gt\", \"gte\", \"begins_with\", \"is_in\",", "a successful invocation of `query_item`.\"\"\" for cond in (\"ne\", \"lt\",", "a failure self.assertTrue(False, err_msg) except Exception as e: if err_msg", "invocation of `update_item`.\"\"\" key = {\"id\": 1} data = {\"age\":", "def test_delete_item(self): \"\"\"Test a successful invocation of `delete_item`.\"\"\" key =", "= {\"age\": 30, \"full_name\": \"<NAME>\"} self.handler.table.scan.return_value = {\"Items\": data} self.assertEqual(self.handler.query_items(query),", "{\"id\": 1} data = {\"age\": 40, \"name\": \"<NAME>\"} self.handler.update_item(key, data)", "\"age\": { \"condition\": \"eq\", \"value\": 25 }, \"full_name\": { \"condition\":", "25 }, \"full_name\": { \"condition\": cond, \"value\": \"<NAME>\" } }", "{ \"TheWrongKey\": dict(field1=\"1\", field2=\"2\") } self.assertIsNone(self.handler.get_item(\"key\")) def test_insert_item(self): \"\"\"Test a", "of `query_item`.\"\"\" for cond in (\"ne\", \"lt\", \"lte\", \"gt\", \"gte\",", "kwargs[\"UpdateExpression\"].replace(\" \", \"\") self.assertTrue(expr.startswith(\"SET\")) self.assertIn(\"age=:age\", expr) self.assertIn(\"#item_name=:name\", expr) self.assertIn(\"ExpressionAttributeValues\", kwargs)", "\"TheWrongKey\": dict(field1=\"1\", field2=\"2\") } self.assertIsNone(self.handler.get_item(\"key\")) def test_insert_item(self): \"\"\"Test a successful", "def test_get_item_malformed(self): \"\"\"Test an unsuccessful invocation of `get_item`.\"\"\" self.handler.table.get_item.return_value =", "query = { \"ready\": False } data = {\"age\": 30,", "key = {\"id\": 1234} self.handler.delete_item(key) self.handler.table.delete_item.assert_called_once_with(Key=key) def test_query_item(self): \"\"\" Test", "\"begins_with\", \"is_in\", \"contains\"): self.handler.table.reset_mock() query = { \"age\": { \"condition\":", "and order of assignments expr = kwargs[\"UpdateExpression\"].replace(\" \", \"\") self.assertTrue(expr.startswith(\"SET\"))", "of `get_item`.\"\"\" expected = dict(field1=\"1\", field2=\"2\") self.handler.table.get_item.return_value = { \"Item\":", "= { \"Item\": expected } self.assertEqual(self.handler.get_item(\"key\"), expected) def test_get_item_malformed(self): \"\"\"Test", "the scan ran without an argument this is a failure", "successful invocation of `get_item`.\"\"\" expected = dict(field1=\"1\", field2=\"2\") self.handler.table.get_item.return_value =", "= {\"age\": 30, \"full_name\": \"<NAME>\"} self.handler.table.scan.return_value = {\"Items\": data} self.assertEqual(self.handler.query_items(),", "order of assignments expr = kwargs[\"UpdateExpression\"].replace(\" \", \"\") self.assertTrue(expr.startswith(\"SET\")) self.assertIn(\"age=:age\",", "setUpClass(cls): with mock.patch(\"d43_aws_tools.dynamodb_handler.boto3\", mock.MagicMock()): cls.handler = aws_tools.dynamodb_handler.DynamoDBHandler(\"table_name\") cls.handler.table = mock.MagicMock()", "\"Item\": expected } self.assertEqual(self.handler.get_item(\"key\"), expected) def test_get_item_malformed(self): \"\"\"Test an unsuccessful", "self.assertEqual(self.handler.query_items(query), data) self.handler.table.scan.assert_called_once() err_msg = 'query_items: Expecting FilterExpression parameter for", "invocation of `get_item`.\"\"\" self.handler.table.get_item.return_value = { \"TheWrongKey\": dict(field1=\"1\", field2=\"2\") }", "found' try: self.handler.table.scan.assert_called_once_with() # If the scan ran without an", "of `update_item`.\"\"\" key = {\"id\": 1} data = {\"age\": 40,", "cls.handler.table = mock.MagicMock() def setUp(self): self.handler.table.reset_mock() def test_get_item(self): \"\"\"Test a", "e def test_query_item_no_query(self): \"\"\"Test a invocation of `query_item` with no", "d43_aws_tools as aws_tools from boto3.dynamodb.conditions import Attr class DynamoDBHandlerTests(unittest.TestCase): @classmethod", "as aws_tools from boto3.dynamodb.conditions import Attr class DynamoDBHandlerTests(unittest.TestCase): @classmethod def", "import unittest import d43_aws_tools as aws_tools from boto3.dynamodb.conditions import Attr", "assignments expr = kwargs[\"UpdateExpression\"].replace(\" \", \"\") self.assertTrue(expr.startswith(\"SET\")) self.assertIn(\"age=:age\", expr) self.assertIn(\"#item_name=:name\",", "\"gte\", \"begins_with\", \"is_in\", \"contains\"): self.handler.table.reset_mock() query = { \"ready\": False", "`get_item`.\"\"\" expected = dict(field1=\"1\", field2=\"2\") self.handler.table.get_item.return_value = { \"Item\": expected", "data = {\"age\": 30, \"full_name\": \"<NAME>\", \"ready\": False} self.handler.table.scan.return_value =", "of `insert_item`.\"\"\" data = dict(x=\"x\", y=\"y\", three=3) self.handler.insert_item(data) self.handler.table.put_item.assert_called_once_with(Item=data) def", "data) self.handler.table.update_item.assert_called_once() _, kwargs = self.handler.table.update_item.call_args self.assertIn(\"Key\", kwargs) self.assertEqual(kwargs[\"Key\"], key)", "{\":age\": 40, \":name\": \"<NAME>\"}) self.assertIn(\"ExpressionAttributeNames\", kwargs) self.assertEqual(kwargs[\"ExpressionAttributeNames\"], {\"#item_name\": \"name\"}) def", "test_get_item_malformed(self): \"\"\"Test an unsuccessful invocation of `get_item`.\"\"\" self.handler.table.get_item.return_value = {", "invocation of `query_item`. with a False boolean query\"\"\" for cond", "aws_tools from boto3.dynamodb.conditions import Attr class DynamoDBHandlerTests(unittest.TestCase): @classmethod def setUpClass(cls):", "= kwargs[\"UpdateExpression\"].replace(\" \", \"\") self.assertTrue(expr.startswith(\"SET\")) self.assertIn(\"age=:age\", expr) self.assertIn(\"#item_name=:name\", expr) self.assertIn(\"ExpressionAttributeValues\",", "test_query_item(self): \"\"\" Test a successful invocation of `query_item`.\"\"\" for cond", "@classmethod def setUpClass(cls): with mock.patch(\"d43_aws_tools.dynamodb_handler.boto3\", mock.MagicMock()): cls.handler = aws_tools.dynamodb_handler.DynamoDBHandler(\"table_name\") cls.handler.table", "kwargs = self.handler.table.update_item.call_args self.assertIn(\"Key\", kwargs) self.assertEqual(kwargs[\"Key\"], key) self.assertIn(\"UpdateExpression\", kwargs) #", "\"gte\", \"begins_with\", \"is_in\", \"contains\"): self.handler.table.reset_mock() query = { \"age\": {", "a successful invocation of `query_item`. with a False boolean query\"\"\"", "self.handler.table.scan.return_value = {\"Items\": data} self.assertEqual(self.handler.query_items(query), data) self.handler.table.scan.assert_called_once() err_msg = 'query_items:", "boto3.dynamodb.conditions import Attr class DynamoDBHandlerTests(unittest.TestCase): @classmethod def setUpClass(cls): with mock.patch(\"d43_aws_tools.dynamodb_handler.boto3\",", "= mock.MagicMock() def setUp(self): self.handler.table.reset_mock() def test_get_item(self): \"\"\"Test a successful", "mock import unittest import d43_aws_tools as aws_tools from boto3.dynamodb.conditions import", "If the scan ran without an argument this is a", "without an argument this is a failure self.assertTrue(False, err_msg) except", "self.assertIn(\"Key\", kwargs) self.assertEqual(kwargs[\"Key\"], key) self.assertIn(\"UpdateExpression\", kwargs) # ignore whitespace and", "as e: if err_msg in str(e): raise e def test_query_item_no_query(self):", "field2=\"2\") } self.assertIsNone(self.handler.get_item(\"key\")) def test_insert_item(self): \"\"\"Test a successful invocation of", "successful invocation of `query_item`.\"\"\" for cond in (\"ne\", \"lt\", \"lte\",", "\"\"\"Test a successful invocation of `update_item`.\"\"\" key = {\"id\": 1}", "\"contains\"): self.handler.table.reset_mock() query = { \"age\": { \"condition\": \"eq\", \"value\":", "with mock.patch(\"d43_aws_tools.dynamodb_handler.boto3\", mock.MagicMock()): cls.handler = aws_tools.dynamodb_handler.DynamoDBHandler(\"table_name\") cls.handler.table = mock.MagicMock() def", "table.scan() but non found' try: self.handler.table.scan.assert_called_once_with() # If the scan", "self.assertIn(\"#item_name=:name\", expr) self.assertIn(\"ExpressionAttributeValues\", kwargs) self.assertEqual(kwargs[\"ExpressionAttributeValues\"], {\":age\": 40, \":name\": \"<NAME>\"}) self.assertIn(\"ExpressionAttributeNames\",", "\"full_name\": \"<NAME>\", \"ready\": False} self.handler.table.scan.return_value = {\"Items\": data} self.assertEqual(self.handler.query_items(query), data)", "if err_msg in str(e): raise e def test_query_item_no_query(self): \"\"\"Test a", "but non found' try: self.handler.table.scan.assert_called_once_with() # If the scan ran", "no query.\"\"\" data = {\"age\": 30, \"full_name\": \"<NAME>\"} self.handler.table.scan.return_value =", "self.handler.table.scan.return_value = {\"Items\": data} self.assertEqual(self.handler.query_items(query), data) self.handler.table.scan.assert_called_once() def test_query_bool_item(self): \"\"\"", "{ \"Item\": expected } self.assertEqual(self.handler.get_item(\"key\"), expected) def test_get_item_malformed(self): \"\"\"Test an", "expr) self.assertIn(\"#item_name=:name\", expr) self.assertIn(\"ExpressionAttributeValues\", kwargs) self.assertEqual(kwargs[\"ExpressionAttributeValues\"], {\":age\": 40, \":name\": \"<NAME>\"})", "ran without an argument this is a failure self.assertTrue(False, err_msg)", "invocation of `query_item` with no query.\"\"\" data = {\"age\": 30,", "`update_item`.\"\"\" key = {\"id\": 1} data = {\"age\": 40, \"name\":", "dict(x=\"x\", y=\"y\", three=3) self.handler.insert_item(data) self.handler.table.put_item.assert_called_once_with(Item=data) def test_update_item(self): \"\"\"Test a successful", "= {\"Items\": data} self.assertEqual(self.handler.query_items(query), data) self.handler.table.scan.assert_called_once() def test_query_bool_item(self): \"\"\" Test", "data} self.assertEqual(self.handler.query_items(query), data) self.handler.table.scan.assert_called_once() def test_query_bool_item(self): \"\"\" Test a successful", "self.handler.table.scan.assert_called_once_with() # If the scan ran without an argument this", "unittest import d43_aws_tools as aws_tools from boto3.dynamodb.conditions import Attr class", "} self.assertEqual(self.handler.get_item(\"key\"), expected) def test_get_item_malformed(self): \"\"\"Test an unsuccessful invocation of", "a successful invocation of `get_item`.\"\"\" expected = dict(field1=\"1\", field2=\"2\") self.handler.table.get_item.return_value", "a False boolean query\"\"\" for cond in (\"ne\", \"lt\", \"lte\",", "expr = kwargs[\"UpdateExpression\"].replace(\" \", \"\") self.assertTrue(expr.startswith(\"SET\")) self.assertIn(\"age=:age\", expr) self.assertIn(\"#item_name=:name\", expr)", "try: self.handler.table.scan.assert_called_once_with() # If the scan ran without an argument", "\"name\": \"<NAME>\"} self.handler.update_item(key, data) self.handler.table.update_item.assert_called_once() _, kwargs = self.handler.table.update_item.call_args self.assertIn(\"Key\",", "a successful invocation of `delete_item`.\"\"\" key = {\"id\": 1234} self.handler.delete_item(key)", "import mock import unittest import d43_aws_tools as aws_tools from boto3.dynamodb.conditions", "self.handler.table.reset_mock() query = { \"ready\": False } data = {\"age\":", "expected } self.assertEqual(self.handler.get_item(\"key\"), expected) def test_get_item_malformed(self): \"\"\"Test an unsuccessful invocation", "kwargs) self.assertEqual(kwargs[\"Key\"], key) self.assertIn(\"UpdateExpression\", kwargs) # ignore whitespace and order", "= {\"id\": 1234} self.handler.delete_item(key) self.handler.table.delete_item.assert_called_once_with(Key=key) def test_query_item(self): \"\"\" Test a", "\"value\": \"<NAME>\" } } data = {\"age\": 30, \"full_name\": \"<NAME>\"}", "\"value\": 25 }, \"full_name\": { \"condition\": cond, \"value\": \"<NAME>\" }", "print_function import mock import unittest import d43_aws_tools as aws_tools from", "self.assertIn(\"ExpressionAttributeValues\", kwargs) self.assertEqual(kwargs[\"ExpressionAttributeValues\"], {\":age\": 40, \":name\": \"<NAME>\"}) self.assertIn(\"ExpressionAttributeNames\", kwargs) self.assertEqual(kwargs[\"ExpressionAttributeNames\"],", "\"gt\", \"gte\", \"begins_with\", \"is_in\", \"contains\"): self.handler.table.reset_mock() query = { \"ready\":", "an unsuccessful invocation of `get_item`.\"\"\" self.handler.table.get_item.return_value = { \"TheWrongKey\": dict(field1=\"1\",", "{\"Items\": data} self.assertEqual(self.handler.query_items(query), data) self.handler.table.scan.assert_called_once() def test_query_bool_item(self): \"\"\" Test a", "is a failure self.assertTrue(False, err_msg) except Exception as e: if", "expected) def test_get_item_malformed(self): \"\"\"Test an unsuccessful invocation of `get_item`.\"\"\" self.handler.table.get_item.return_value", "\"\"\"Test a invocation of `query_item` with no query.\"\"\" data =", "\"\"\"Test a successful invocation of `get_item`.\"\"\" expected = dict(field1=\"1\", field2=\"2\")", "1} data = {\"age\": 40, \"name\": \"<NAME>\"} self.handler.update_item(key, data) self.handler.table.update_item.assert_called_once()", "kwargs) # ignore whitespace and order of assignments expr =", "unicode_literals, print_function import mock import unittest import d43_aws_tools as aws_tools", "invocation of `query_item`.\"\"\" for cond in (\"ne\", \"lt\", \"lte\", \"gt\",", "self.assertTrue(False, err_msg) except Exception as e: if err_msg in str(e):", "import Attr class DynamoDBHandlerTests(unittest.TestCase): @classmethod def setUpClass(cls): with mock.patch(\"d43_aws_tools.dynamodb_handler.boto3\", mock.MagicMock()):", "self.assertEqual(kwargs[\"ExpressionAttributeNames\"], {\"#item_name\": \"name\"}) def test_delete_item(self): \"\"\"Test a successful invocation of", "\"<NAME>\"} self.handler.table.scan.return_value = {\"Items\": data} self.assertEqual(self.handler.query_items(query), data) self.handler.table.scan.assert_called_once() def test_query_bool_item(self):", "with no query.\"\"\" data = {\"age\": 30, \"full_name\": \"<NAME>\"} self.handler.table.scan.return_value", "`query_item`.\"\"\" for cond in (\"ne\", \"lt\", \"lte\", \"gt\", \"gte\", \"begins_with\",", "\"full_name\": \"<NAME>\"} self.handler.table.scan.return_value = {\"Items\": data} self.assertEqual(self.handler.query_items(query), data) self.handler.table.scan.assert_called_once() def", "\"\"\" Test a successful invocation of `query_item`. with a False", "key = {\"id\": 1} data = {\"age\": 40, \"name\": \"<NAME>\"}", "30, \"full_name\": \"<NAME>\", \"ready\": False} self.handler.table.scan.return_value = {\"Items\": data} self.assertEqual(self.handler.query_items(query),", "self.assertEqual(self.handler.get_item(\"key\"), expected) def test_get_item_malformed(self): \"\"\"Test an unsuccessful invocation of `get_item`.\"\"\"", "\"\") self.assertTrue(expr.startswith(\"SET\")) self.assertIn(\"age=:age\", expr) self.assertIn(\"#item_name=:name\", expr) self.assertIn(\"ExpressionAttributeValues\", kwargs) self.assertEqual(kwargs[\"ExpressionAttributeValues\"], {\":age\":", "False } data = {\"age\": 30, \"full_name\": \"<NAME>\", \"ready\": False}", "}, \"full_name\": { \"condition\": cond, \"value\": \"<NAME>\" } } data", "\"<NAME>\"}) self.assertIn(\"ExpressionAttributeNames\", kwargs) self.assertEqual(kwargs[\"ExpressionAttributeNames\"], {\"#item_name\": \"name\"}) def test_delete_item(self): \"\"\"Test a", "boolean query\"\"\" for cond in (\"ne\", \"lt\", \"lte\", \"gt\", \"gte\",", "} data = {\"age\": 30, \"full_name\": \"<NAME>\", \"ready\": False} self.handler.table.scan.return_value", "Expecting FilterExpression parameter for table.scan() but non found' try: self.handler.table.scan.assert_called_once_with()", "__future__ import absolute_import, unicode_literals, print_function import mock import unittest import", "def test_get_item(self): \"\"\"Test a successful invocation of `get_item`.\"\"\" expected =", "data) self.handler.table.scan.assert_called_once() err_msg = 'query_items: Expecting FilterExpression parameter for table.scan()", "for table.scan() but non found' try: self.handler.table.scan.assert_called_once_with() # If the", "setUp(self): self.handler.table.reset_mock() def test_get_item(self): \"\"\"Test a successful invocation of `get_item`.\"\"\"", "= {\"Items\": data} self.assertEqual(self.handler.query_items(query), data) self.handler.table.scan.assert_called_once() err_msg = 'query_items: Expecting", "\"condition\": cond, \"value\": \"<NAME>\" } } data = {\"age\": 30,", "successful invocation of `update_item`.\"\"\" key = {\"id\": 1} data =", "successful invocation of `query_item`. with a False boolean query\"\"\" for", "{\"age\": 30, \"full_name\": \"<NAME>\"} self.handler.table.scan.return_value = {\"Items\": data} self.assertEqual(self.handler.query_items(query), data)", "= { \"ready\": False } data = {\"age\": 30, \"full_name\":", "of assignments expr = kwargs[\"UpdateExpression\"].replace(\" \", \"\") self.assertTrue(expr.startswith(\"SET\")) self.assertIn(\"age=:age\", expr)", "self.handler.table.reset_mock() def test_get_item(self): \"\"\"Test a successful invocation of `get_item`.\"\"\" expected", "scan ran without an argument this is a failure self.assertTrue(False,", "{ \"condition\": \"eq\", \"value\": 25 }, \"full_name\": { \"condition\": cond,", "e: if err_msg in str(e): raise e def test_query_item_no_query(self): \"\"\"Test", "def setUp(self): self.handler.table.reset_mock() def test_get_item(self): \"\"\"Test a successful invocation of", "self.handler.table.get_item.return_value = { \"Item\": expected } self.assertEqual(self.handler.get_item(\"key\"), expected) def test_get_item_malformed(self):", "kwargs) self.assertEqual(kwargs[\"ExpressionAttributeValues\"], {\":age\": 40, \":name\": \"<NAME>\"}) self.assertIn(\"ExpressionAttributeNames\", kwargs) self.assertEqual(kwargs[\"ExpressionAttributeNames\"], {\"#item_name\":", "self.handler.delete_item(key) self.handler.table.delete_item.assert_called_once_with(Key=key) def test_query_item(self): \"\"\" Test a successful invocation of", "} self.assertIsNone(self.handler.get_item(\"key\")) def test_insert_item(self): \"\"\"Test a successful invocation of `insert_item`.\"\"\"", "import absolute_import, unicode_literals, print_function import mock import unittest import d43_aws_tools", "mock.patch(\"d43_aws_tools.dynamodb_handler.boto3\", mock.MagicMock()): cls.handler = aws_tools.dynamodb_handler.DynamoDBHandler(\"table_name\") cls.handler.table = mock.MagicMock() def setUp(self):", "\"lte\", \"gt\", \"gte\", \"begins_with\", \"is_in\", \"contains\"): self.handler.table.reset_mock() query = {", "{ \"ready\": False } data = {\"age\": 30, \"full_name\": \"<NAME>\",", "an argument this is a failure self.assertTrue(False, err_msg) except Exception", "self.handler.table.update_item.call_args self.assertIn(\"Key\", kwargs) self.assertEqual(kwargs[\"Key\"], key) self.assertIn(\"UpdateExpression\", kwargs) # ignore whitespace", "of `query_item`. with a False boolean query\"\"\" for cond in", "field2=\"2\") self.handler.table.get_item.return_value = { \"Item\": expected } self.assertEqual(self.handler.get_item(\"key\"), expected) def", "\"name\"}) def test_delete_item(self): \"\"\"Test a successful invocation of `delete_item`.\"\"\" key", "self.handler.table.get_item.return_value = { \"TheWrongKey\": dict(field1=\"1\", field2=\"2\") } self.assertIsNone(self.handler.get_item(\"key\")) def test_insert_item(self):", "= self.handler.table.update_item.call_args self.assertIn(\"Key\", kwargs) self.assertEqual(kwargs[\"Key\"], key) self.assertIn(\"UpdateExpression\", kwargs) # ignore", "\"gt\", \"gte\", \"begins_with\", \"is_in\", \"contains\"): self.handler.table.reset_mock() query = { \"age\":", "self.handler.table.reset_mock() query = { \"age\": { \"condition\": \"eq\", \"value\": 25", "test_insert_item(self): \"\"\"Test a successful invocation of `insert_item`.\"\"\" data = dict(x=\"x\",", "argument this is a failure self.assertTrue(False, err_msg) except Exception as", "absolute_import, unicode_literals, print_function import mock import unittest import d43_aws_tools as", "def test_update_item(self): \"\"\"Test a successful invocation of `update_item`.\"\"\" key =", "self.assertEqual(kwargs[\"Key\"], key) self.assertIn(\"UpdateExpression\", kwargs) # ignore whitespace and order of", "in (\"ne\", \"lt\", \"lte\", \"gt\", \"gte\", \"begins_with\", \"is_in\", \"contains\"): self.handler.table.reset_mock()", "self.handler.table.put_item.assert_called_once_with(Item=data) def test_update_item(self): \"\"\"Test a successful invocation of `update_item`.\"\"\" key", "test_delete_item(self): \"\"\"Test a successful invocation of `delete_item`.\"\"\" key = {\"id\":", "= { \"age\": { \"condition\": \"eq\", \"value\": 25 }, \"full_name\":", "test_query_item_no_query(self): \"\"\"Test a invocation of `query_item` with no query.\"\"\" data", "\"condition\": \"eq\", \"value\": 25 }, \"full_name\": { \"condition\": cond, \"value\":", "a successful invocation of `update_item`.\"\"\" key = {\"id\": 1} data", "a invocation of `query_item` with no query.\"\"\" data = {\"age\":", "def test_query_item(self): \"\"\" Test a successful invocation of `query_item`.\"\"\" for", "ignore whitespace and order of assignments expr = kwargs[\"UpdateExpression\"].replace(\" \",", "successful invocation of `insert_item`.\"\"\" data = dict(x=\"x\", y=\"y\", three=3) self.handler.insert_item(data)", "key) self.assertIn(\"UpdateExpression\", kwargs) # ignore whitespace and order of assignments", "self.assertIn(\"UpdateExpression\", kwargs) # ignore whitespace and order of assignments expr", "expr) self.assertIn(\"ExpressionAttributeValues\", kwargs) self.assertEqual(kwargs[\"ExpressionAttributeValues\"], {\":age\": 40, \":name\": \"<NAME>\"}) self.assertIn(\"ExpressionAttributeNames\", kwargs)", "kwargs) self.assertEqual(kwargs[\"ExpressionAttributeNames\"], {\"#item_name\": \"name\"}) def test_delete_item(self): \"\"\"Test a successful invocation", "\":name\": \"<NAME>\"}) self.assertIn(\"ExpressionAttributeNames\", kwargs) self.assertEqual(kwargs[\"ExpressionAttributeNames\"], {\"#item_name\": \"name\"}) def test_delete_item(self): \"\"\"Test", "{\"id\": 1234} self.handler.delete_item(key) self.handler.table.delete_item.assert_called_once_with(Key=key) def test_query_item(self): \"\"\" Test a successful", "} data = {\"age\": 30, \"full_name\": \"<NAME>\"} self.handler.table.scan.return_value = {\"Items\":", "dict(field1=\"1\", field2=\"2\") } self.assertIsNone(self.handler.get_item(\"key\")) def test_insert_item(self): \"\"\"Test a successful invocation", "self.assertEqual(self.handler.query_items(query), data) self.handler.table.scan.assert_called_once() def test_query_bool_item(self): \"\"\" Test a successful invocation", "failure self.assertTrue(False, err_msg) except Exception as e: if err_msg in", "`query_item`. with a False boolean query\"\"\" for cond in (\"ne\",", "cls.handler = aws_tools.dynamodb_handler.DynamoDBHandler(\"table_name\") cls.handler.table = mock.MagicMock() def setUp(self): self.handler.table.reset_mock() def", "\"\"\"Test an unsuccessful invocation of `get_item`.\"\"\" self.handler.table.get_item.return_value = { \"TheWrongKey\":", "DynamoDBHandlerTests(unittest.TestCase): @classmethod def setUpClass(cls): with mock.patch(\"d43_aws_tools.dynamodb_handler.boto3\", mock.MagicMock()): cls.handler = aws_tools.dynamodb_handler.DynamoDBHandler(\"table_name\")", "Exception as e: if err_msg in str(e): raise e def", "of `query_item` with no query.\"\"\" data = {\"age\": 30, \"full_name\":", "\"<NAME>\" } } data = {\"age\": 30, \"full_name\": \"<NAME>\"} self.handler.table.scan.return_value" ]
[ "\"Amount\": [4, 1, 2, 2, 4, 5], \"City\": [\"SF\", \"SF\",", "as pd app = Dash(__name__) server = app.server # assume", "2, 4, 5], \"City\": [\"SF\", \"SF\", \"SF\", \"Montreal\", \"Montreal\", \"Montreal\"]", "# see https://plotly.com/python/px-arguments/ for more options df = pd.DataFrame({ \"Fruit\":", "fig = px.bar(df, x=\"Fruit\", y=\"Amount\", color=\"City\", barmode=\"group\") app.layout = html.Div(children=[", "https://plotly.com/python/px-arguments/ for more options df = pd.DataFrame({ \"Fruit\": [\"Apples\", \"Oranges\",", "<filename>app.py from dash import Dash, html, dcc import plotly.express as", "= app.server # assume you have a \"long-form\" data frame", "px import pandas as pd app = Dash(__name__) server =", "= pd.DataFrame({ \"Fruit\": [\"Apples\", \"Oranges\", \"Bananas\", \"Apples\", \"Oranges\", \"Bananas\"], \"Amount\":", "A web application framework for your data. '''), dcc.Graph( id='example-graph',", "pandas as pd app = Dash(__name__) server = app.server #", "\"SF\", \"SF\", \"Montreal\", \"Montreal\", \"Montreal\"] }) fig = px.bar(df, x=\"Fruit\",", "barmode=\"group\") app.layout = html.Div(children=[ html.H1(children='Hello Dash'), html.Div(children=''' Dash: A web", "dcc import plotly.express as px import pandas as pd app", "\"SF\", \"Montreal\", \"Montreal\", \"Montreal\"] }) fig = px.bar(df, x=\"Fruit\", y=\"Amount\",", "= px.bar(df, x=\"Fruit\", y=\"Amount\", color=\"City\", barmode=\"group\") app.layout = html.Div(children=[ html.H1(children='Hello", "have a \"long-form\" data frame # see https://plotly.com/python/px-arguments/ for more", "px.bar(df, x=\"Fruit\", y=\"Amount\", color=\"City\", barmode=\"group\") app.layout = html.Div(children=[ html.H1(children='Hello Dash'),", "html.Div(children=[ html.H1(children='Hello Dash'), html.Div(children=''' Dash: A web application framework for", "your data. '''), dcc.Graph( id='example-graph', figure=fig ) ]) if __name__", "\"Bananas\"], \"Amount\": [4, 1, 2, 2, 4, 5], \"City\": [\"SF\",", "= html.Div(children=[ html.H1(children='Hello Dash'), html.Div(children=''' Dash: A web application framework", "for more options df = pd.DataFrame({ \"Fruit\": [\"Apples\", \"Oranges\", \"Bananas\",", "\"Oranges\", \"Bananas\", \"Apples\", \"Oranges\", \"Bananas\"], \"Amount\": [4, 1, 2, 2,", "df = pd.DataFrame({ \"Fruit\": [\"Apples\", \"Oranges\", \"Bananas\", \"Apples\", \"Oranges\", \"Bananas\"],", "\"Montreal\"] }) fig = px.bar(df, x=\"Fruit\", y=\"Amount\", color=\"City\", barmode=\"group\") app.layout", "x=\"Fruit\", y=\"Amount\", color=\"City\", barmode=\"group\") app.layout = html.Div(children=[ html.H1(children='Hello Dash'), html.Div(children='''", "\"Oranges\", \"Bananas\"], \"Amount\": [4, 1, 2, 2, 4, 5], \"City\":", "Dash, html, dcc import plotly.express as px import pandas as", "see https://plotly.com/python/px-arguments/ for more options df = pd.DataFrame({ \"Fruit\": [\"Apples\",", "import pandas as pd app = Dash(__name__) server = app.server", "\"Bananas\", \"Apples\", \"Oranges\", \"Bananas\"], \"Amount\": [4, 1, 2, 2, 4,", "you have a \"long-form\" data frame # see https://plotly.com/python/px-arguments/ for", "app = Dash(__name__) server = app.server # assume you have", "color=\"City\", barmode=\"group\") app.layout = html.Div(children=[ html.H1(children='Hello Dash'), html.Div(children=''' Dash: A", "= Dash(__name__) server = app.server # assume you have a", "data. '''), dcc.Graph( id='example-graph', figure=fig ) ]) if __name__ ==", "5], \"City\": [\"SF\", \"SF\", \"SF\", \"Montreal\", \"Montreal\", \"Montreal\"] }) fig", "\"Montreal\", \"Montreal\", \"Montreal\"] }) fig = px.bar(df, x=\"Fruit\", y=\"Amount\", color=\"City\",", "dcc.Graph( id='example-graph', figure=fig ) ]) if __name__ == '__main__': app.run_server(debug=True)", "from dash import Dash, html, dcc import plotly.express as px", "html.H1(children='Hello Dash'), html.Div(children=''' Dash: A web application framework for your", "pd app = Dash(__name__) server = app.server # assume you", "import plotly.express as px import pandas as pd app =", "web application framework for your data. '''), dcc.Graph( id='example-graph', figure=fig", "pd.DataFrame({ \"Fruit\": [\"Apples\", \"Oranges\", \"Bananas\", \"Apples\", \"Oranges\", \"Bananas\"], \"Amount\": [4,", "2, 2, 4, 5], \"City\": [\"SF\", \"SF\", \"SF\", \"Montreal\", \"Montreal\",", "\"City\": [\"SF\", \"SF\", \"SF\", \"Montreal\", \"Montreal\", \"Montreal\"] }) fig =", "y=\"Amount\", color=\"City\", barmode=\"group\") app.layout = html.Div(children=[ html.H1(children='Hello Dash'), html.Div(children=''' Dash:", "app.layout = html.Div(children=[ html.H1(children='Hello Dash'), html.Div(children=''' Dash: A web application", "data frame # see https://plotly.com/python/px-arguments/ for more options df =", "# assume you have a \"long-form\" data frame # see", "a \"long-form\" data frame # see https://plotly.com/python/px-arguments/ for more options", "options df = pd.DataFrame({ \"Fruit\": [\"Apples\", \"Oranges\", \"Bananas\", \"Apples\", \"Oranges\",", "Dash(__name__) server = app.server # assume you have a \"long-form\"", "'''), dcc.Graph( id='example-graph', figure=fig ) ]) if __name__ == '__main__':", "\"long-form\" data frame # see https://plotly.com/python/px-arguments/ for more options df", "server = app.server # assume you have a \"long-form\" data", "\"Montreal\", \"Montreal\"] }) fig = px.bar(df, x=\"Fruit\", y=\"Amount\", color=\"City\", barmode=\"group\")", "}) fig = px.bar(df, x=\"Fruit\", y=\"Amount\", color=\"City\", barmode=\"group\") app.layout =", "[4, 1, 2, 2, 4, 5], \"City\": [\"SF\", \"SF\", \"SF\",", "1, 2, 2, 4, 5], \"City\": [\"SF\", \"SF\", \"SF\", \"Montreal\",", "[\"SF\", \"SF\", \"SF\", \"Montreal\", \"Montreal\", \"Montreal\"] }) fig = px.bar(df,", "4, 5], \"City\": [\"SF\", \"SF\", \"SF\", \"Montreal\", \"Montreal\", \"Montreal\"] })", "plotly.express as px import pandas as pd app = Dash(__name__)", "dash import Dash, html, dcc import plotly.express as px import", "application framework for your data. '''), dcc.Graph( id='example-graph', figure=fig )", "\"Apples\", \"Oranges\", \"Bananas\"], \"Amount\": [4, 1, 2, 2, 4, 5],", "for your data. '''), dcc.Graph( id='example-graph', figure=fig ) ]) if", "app.server # assume you have a \"long-form\" data frame #", "as px import pandas as pd app = Dash(__name__) server", "frame # see https://plotly.com/python/px-arguments/ for more options df = pd.DataFrame({", "assume you have a \"long-form\" data frame # see https://plotly.com/python/px-arguments/", "more options df = pd.DataFrame({ \"Fruit\": [\"Apples\", \"Oranges\", \"Bananas\", \"Apples\",", "framework for your data. '''), dcc.Graph( id='example-graph', figure=fig ) ])", "import Dash, html, dcc import plotly.express as px import pandas", "\"Fruit\": [\"Apples\", \"Oranges\", \"Bananas\", \"Apples\", \"Oranges\", \"Bananas\"], \"Amount\": [4, 1,", "Dash: A web application framework for your data. '''), dcc.Graph(", "[\"Apples\", \"Oranges\", \"Bananas\", \"Apples\", \"Oranges\", \"Bananas\"], \"Amount\": [4, 1, 2,", "html.Div(children=''' Dash: A web application framework for your data. '''),", "Dash'), html.Div(children=''' Dash: A web application framework for your data.", "html, dcc import plotly.express as px import pandas as pd" ]
[ "= self.formStash # ------------------- # do a quick parse... requirements_either_or", "None le_pkey_jsons = None le_reg_jsons = None private_key_cycle_id = None", "we use `jsonS` to indicate a string self.le_meta_jsons = getcreate_args[", "tracked acme_account_provider_id = None account_key_pem = None le_meta_jsons = None", "{ \"http-01\": \"domain_names_http01\", \"dns-01\": \"domain_names_dns01\", } class AcmeAccountUploadParser(object): \"\"\" An", "provider submitted.\" ) self.upload_type = \"pem\" self.acme_account_provider_id = getcreate_args[ \"acme_account_provider_id\"", "formhandling.slurp_file_field(formStash, \"account_key_file_le_pkey\") self.le_reg_jsons = getcreate_args[ \"le_reg_jsons\" ] = formhandling.slurp_file_field(formStash, \"account_key_file_le_reg\")", "privateKeySelection.private_key_strategy__requested = ( model_utils.PrivateKeySelection_2_PrivateKeyStrategy[ \"private_key_for_account_key\" ] ) return privateKeySelection else:", "if not dbPrivateKey: # `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=private_key_option,", "formStash self.getcreate_args = {} def require_new(self, require_contact=None, require_technology=True): \"\"\" routine", "\"none\": if not allow_none: # `formStash.fatal_form()` will raise `FormInvalid()` formStash.fatal_form(", "\"none\" account_key_pem_md5 = None return acmeAccountSelection else: formStash.fatal_form( message=\"Invalid `account_key_option`\",", "uploading a PEM file if formStash.results[\"account_key_file_pem\"] is not None: require_contact", "pypi import six # local from ...lib import db as", "getcreate_args = None formStash = None # tracked private_key_pem =", "instance of AcmeAccountUploadParser or None AcmeAccount = None class _PrivateKeySelection(object):", "None return acmeAccountSelection else: formStash.fatal_form( message=\"Invalid `account_key_option`\", ) if not", "== \"none\": if not allow_none: # `formStash.fatal_form()` will raise `FormInvalid()`", "there are domains if not domain_names_all: # `formStash.fatal_field()` will raise", "= _PrivateKeyUploadParser(formStash) parser.require_upload() # update our object privateKeySelection.selection = \"upload\"", "names detected\" ) return domains_challenged def form_single_domain_challenge_typed(request, formStash, challenge_type=\"http-01\"): domains_challenged", "= getcreate_args[\"contact\"] = contact self.acme_account_provider_id = getcreate_args[ \"acme_account_provider_id\" ] =", "None @property def private_key_strategy_id__requested(self): return model_utils.PrivateKeyStrategy.from_string( self.private_key_strategy__requested ) def parse_AcmeAccountSelection(", "or failures: # `formStash.fatal_form()` will raise `FormInvalid()` formStash.fatal_form( \"You must", "# pem def __init__(self, formStash): self.formStash = formStash self.getcreate_args =", "raise `FormInvalid()` formStash.fatal_form( \"This form does not support no AcmeAccount", "formStash, http01_only=False): domains_challenged = model_utils.DomainsChallenged() domain_names_all = [] try: #", "`formStash.fatal_form()` will raise `FormInvalid()` formStash.fatal_form(\"There was an error validating your", "= formStash.results.get( \"acme_account_provider_id\", None ) if acme_account_provider_id is None: #", "for uploading an exiting PrivateKey \"\"\" formStash = self.formStash getcreate_args", "on a validated FormEncode results object (via `pyramid_formencode_classic`) \"\"\" #", "= formStash.results.get( \"account__private_key_technology\", None ) if private_key_technology: private_key_technology_id = model_utils.KeyTechnology.from_string(", "domain_names_all = [] try: # 1: iterate over the submitted", "= private_key_technology_id self.getcreate_args = decode_args(getcreate_args) def require_upload(self, require_contact=None, require_technology=None): \"\"\"", "is not the current default.\", ) acmeAccountSelection.AcmeAccount = dbAcmeAccount return", "model_utils.PrivateKeySelection_2_PrivateKeyStrategy[\"reuse\"] ) private_key_pem_md5 = formStash.results[\"private_key_reuse\"] elif private_key_option in ( \"private_key_generate\",", ") # 3: ensure there is no overlap domain_names_all_set =", "message=\"a domain name can only be associated to one challenge", "None le_meta_jsons = None le_pkey_jsons = None le_reg_jsons = None", "`FormInvalid()` formStash.fatal_form(\"There was an error validating your form.\") def form_key_selection(request,", "message=\"The selected AcmeAccount is not enrolled in the system.\", )", ":param formStash: an instance of `pyramid_formencode_classic.FormStash` :param require_contact: ``True`` if", "selection = None upload_parsed = None # instance of AcmeAccountUploadParser", "not enrolled in the system.\", ) if is_global_default and not", "formStash.results[\"account_key_reuse\"] elif account_key_option == \"none\": if not allow_none: # `formStash.fatal_form()`", "is not a complex upload to parse itself This code", "an error validating your form.\") def parse_PrivateKeySelection(request, formStash, private_key_option=None): private_key_pem", "\"acme_account_provider_id\" ] = acme_account_provider_id self.private_key_cycle_id = getcreate_args[ \"private_key_cycle_id\" ] =", "if is_global_default and not dbAcmeAccount.is_global_default: # `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)`", "this function checks the domain names match a simple regex", "4: maybe we only want http01 domains submitted? if http01_only:", "self.acme_account_provider_id = getcreate_args[ \"acme_account_provider_id\" ] = acme_account_provider_id self.private_key_cycle_id = getcreate_args[", "raise `FormInvalid()` formStash.fatal_form(\"There was an error validating your form.\") def", "# local from ...lib import db as lib_db from ...lib", "# pypi import six # local from ...lib import db", "routine for creating a NEW AcmeAccount (peter_sslers generates the credentials)", "`FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=\"Error_Main\", message=\"only http-01 domains are accepted by this", "formhandling.slurp_file_field(formStash, \"private_key_file_pem\") self.getcreate_args = decode_args(getcreate_args) class _AcmeAccountSelection(object): \"\"\" Class used", "value\" ) dbPrivateKey = lib_db.get.get__PrivateKey__by_pemMd5( request.api_context, private_key_pem_md5, is_active=True ) if", "raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=account_key_option, message=\"You did not provide a value\"", "= getcreate_args[ \"key_pem\" ] = formhandling.slurp_file_field(formStash, \"account_key_file_pem\") else: # note", "request.api_context, private_key_pem_md5, is_active=True ) if not dbPrivateKey: # `formStash.fatal_field()` will", "is None: # `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=\"acme_account_provider_id\", message=\"No", "a validated FormEncode results object (via `pyramid_formencode_classic`) \"\"\" # overwritten", "============================================================================== def decode_args(getcreate_args): \"\"\" support for Python2/3 \"\"\" if six.PY3:", "checks the domain names match a simple regex domain_names =", "def decode_args(getcreate_args): \"\"\" support for Python2/3 \"\"\" if six.PY3: for", "\"acme_account_provider_id\" ] = acme_account_provider_id self.account_key_pem = getcreate_args[ \"key_pem\" ] =", "= parse_PrivateKeySelection( request, formStash, private_key_option=formStash.results[\"private_key_option\"], ) if privateKeySelection.selection == \"upload\":", "private_key_technology_id = None private_key_technology = formStash.results.get( \"account__private_key_technology\", None ) if", "\"generate\": dbPrivateKey = lib_db.get.get__PrivateKey__by_id(request.api_context, 0) if not dbPrivateKey: formStash.fatal_field( field=\"private_key_option\",", "logic :param require_technology: ``True`` if required; ``False`` if not; ``None``", "from ...model import utils as model_utils from . import formhandling", "\"pem\" self.private_key_pem = getcreate_args[ \"key_pem\" ] = formhandling.slurp_file_field(formStash, \"private_key_file_pem\") self.getcreate_args", "# ============================================================================== def decode_args(getcreate_args): \"\"\" support for Python2/3 \"\"\" if", "= decode_args(getcreate_args) class _AcmeAccountSelection(object): \"\"\" Class used to manage an", "domain_names_all: # `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=\"Error_Main\", message=\"no domain", "all must be provided.\" % str(option_set) ) else: passes.append(idx) if", "acme_account_provider_id = formStash.results.get( \"acme_account_provider_id\", None ) private_key_cycle = formStash.results.get(\"account__private_key_cycle\", None)", "field=\"Error_Main\", message=\"no domain names submitted\", ) # 3: ensure there", "private_key_pem_md5 = formStash.results[\"private_key_existing\"] elif private_key_option == \"private_key_reuse\": privateKeySelection.selection = \"reuse\"", "return (acmeAccountSelection, privateKeySelection) def form_domains_challenge_typed(request, formStash, http01_only=False): domains_challenged = model_utils.DomainsChallenged()", "\"account_key_file_le_reg\", ), ) failures = [] passes = [] for", "not dbAcmeAccount.is_global_default: # `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=account_key_option, message=\"The", "is not None: require_contact = True contact = formStash.results.get(\"account__contact\") if", "will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=\"domain_name\", message=\"This endpoint currently supports only", "acmeAccountSelection.AcmeAccount = dbAcmeAccount return acmeAccountSelection # `formStash.fatal_form()` will raise `FormInvalid()`", "`FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=\"account__private_key_technology\", message=\"No PrivateKey technology submitted.\", ) # require", "message=\"no domain names submitted\", ) # 3: ensure there is", "submitted.\", ) private_key_cycle_id = model_utils.PrivateKeyCycle.from_string( private_key_cycle ) private_key_technology_id = None", "if account_key_option == \"account_key_file\": # this will handle form validation", "from a Certbot installation This parser operates on a validated", "no domain names\") if len(domain_names) != 1: # `formStash.fatal_field()` will", "self.le_pkey_jsons = getcreate_args[ \"le_pkey_jsons\" ] = formhandling.slurp_file_field(formStash, \"account_key_file_le_pkey\") self.le_reg_jsons =", "OR letsencrypt def __init__(self, formStash): self.formStash = formStash self.getcreate_args =", "PrivateKey technology submitted.\", ) # require `contact` when uploading a", "passes.append(idx) if (len(passes) != 1) or failures: # `formStash.fatal_form()` will", "in __init__ getcreate_args = None formStash = None # tracked", "= utils.domains_from_string(submitted_) if submitted_: domain_names_all.extend(submitted_) domains_challenged[target_] = submitted_ # 2:", "instance of AcmeAccountUploadParser or None private_key_strategy__requested = None PrivateKey =", "parse_AcmeAccountSelection( request, formStash, account_key_option=None, allow_none=None, require_contact=None, ): \"\"\" :param formStash:", "domains are accepted by this form\", ) except ValueError as", "\"If any of %s is provided, all must be provided.\"", "privateKeySelection.selection = \"generate\" privateKeySelection.private_key_strategy__requested = ( model_utils.PrivateKeySelection_2_PrivateKeyStrategy[\"generate\"] ) elif private_key_option", "will be None unless a pem is uploaded # required", "domain names match a simple regex domain_names = utils.domains_from_string(formStash.results[\"domain_name\"]) if", "is provided, all must be provided.\" % str(option_set) ) else:", "= private_key_technology_id if formStash.results[\"account_key_file_pem\"] is not None: if acme_account_provider_id is", "dbAcmeAccount: # `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=account_key_option, message=\"The selected", "\"This form does not support no AcmeAccount selection.\" ) #", "AcmeAccount uploading. \"\"\" # overwritten in __init__ getcreate_args = None", "dbPrivateKey return privateKeySelection # `formStash.fatal_form()` will raise `FormInvalid()` formStash.fatal_form(\"There was", "raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=private_key_option, message=\"You did not provide a value\"", "= lib_db.get.get__AcmeAccount__by_pemMd5( request.api_context, account_key_pem_md5, is_active=True ) if not dbAcmeAccount: #", "None private_key_technology_id = None upload_type = None # pem OR", "elif account_key_option == \"none\": if not allow_none: # `formStash.fatal_form()` will", "lib_db.get.get__PrivateKey__by_id(request.api_context, 0) if not dbPrivateKey: formStash.fatal_field( field=\"private_key_option\", message=\"Could not load", "message=\"Invalid `account_key_option`\", ) if not account_key_pem_md5: # `formStash.fatal_field()` will raise", "for idx, option_set in enumerate(requirements_either_or): option_set_results = [ True if", "dbPrivateKey = lib_db.get.get__PrivateKey__by_id(request.api_context, 0) if not dbPrivateKey: formStash.fatal_field( field=\"private_key_option\", message=\"Could", "privateKeySelection.PrivateKey = dbPrivateKey return (acmeAccountSelection, privateKeySelection) def form_domains_challenge_typed(request, formStash, http01_only=False):", "# instance of AcmeAccountUploadParser or None AcmeAccount = None class", "getcreate_args[ \"key_pem\" ] = formhandling.slurp_file_field(formStash, \"private_key_file_pem\") self.getcreate_args = decode_args(getcreate_args) class", "raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=account_key_option, message=\"The selected AcmeAccount is not enrolled", "def __init__(self, formStash): self.formStash = formStash self.getcreate_args = {} def", "uploading an exiting AcmeAccount+AcmeAccountKey :param require_contact: ``True`` if required; ``False``", "self.formStash # ------------------- # do a quick parse... requirements_either_or =", "account_key_option == \"account_key_global_default\": acmeAccountSelection.selection = \"global_default\" account_key_pem_md5 = formStash.results[\"account_key_global_default\"] is_global_default", "self.getcreate_args = decode_args(getcreate_args) class _AcmeAccountSelection(object): \"\"\" Class used to manage", "item\" selection # only certain routes allow this acmeAccountSelection.selection =", "(target_, source_) in DOMAINS_CHALLENGED_FIELDS.items(): submitted_ = formStash.results.get(source_) if submitted_: #", "= ( model_utils.PrivateKeySelection_2_PrivateKeyStrategy[ \"private_key_for_account_key\" ] ) return privateKeySelection else: #", "acmeAccountSelection # `formStash.fatal_form()` will raise `FormInvalid()` formStash.fatal_form(\"There was an error", "`account_key_file_le_pkey`, `account_key_file_le_reg`).\" ) # ------------------- # validate the provider option", "an uploaded AcmeAccount \"\"\" selection = None upload_parsed = None", "``False`` if not; ``None`` for conditional logic \"\"\" acmeAccountSelection =", "we have any item, we need all of them if", "account_key_option=None, allow_none=None, require_contact=None, ): \"\"\" :param formStash: an instance of", "None private_key_technology = formStash.results.get( \"account__private_key_technology\", None ) if private_key_technology: private_key_technology_id", "your form.\") def form_key_selection(request, formStash, require_contact=None): \"\"\" :param formStash: an", "getcreate_args[ \"acme_account_provider_id\" ] = acme_account_provider_id self.private_key_cycle_id = getcreate_args[ \"private_key_cycle_id\" ]", "] = acme_account_provider_id self.account_key_pem = getcreate_args[ \"key_pem\" ] = formhandling.slurp_file_field(formStash,", "__init__ getcreate_args = None formStash = None # tracked private_key_pem", "decode_args(getcreate_args) class _AcmeAccountSelection(object): \"\"\" Class used to manage an uploaded", "privateKeySelection.selection = \"reuse\" privateKeySelection.private_key_strategy__requested = ( model_utils.PrivateKeySelection_2_PrivateKeyStrategy[\"reuse\"] ) private_key_pem_md5 =", "None # :class:`model.objects.PrivateKey` # handle the explicit-option privateKeySelection = _PrivateKeySelection()", "* an intra-associated three file triplet from a Certbot installation", "acme_account_provider_id is None: # `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=\"acme_account_provider_id\",", "message=\"You did not provide a value\" ) dbAcmeAccount = lib_db.get.get__AcmeAccount__by_pemMd5(", ") # ------------------- # validate the provider option # will", "submitted_ # 2: ensure there are domains if not domain_names_all:", "formStash.results[\"private_key_existing\"] elif private_key_option == \"private_key_reuse\": privateKeySelection.selection = \"reuse\" privateKeySelection.private_key_strategy__requested =", "domains if not domain_names_all: # `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field(", "le_pkey_jsons = None le_reg_jsons = None private_key_cycle_id = None private_key_technology_id", "challenge_type=\"http-01\"): domains_challenged = model_utils.DomainsChallenged() # this function checks the domain", "= lib_db.get.get__PrivateKey__by_id(request.api_context, 0) if not dbPrivateKey: formStash.fatal_field( field=\"private_key_option\", message=\"Could not", "for conditional logic \"\"\" acmeAccountSelection = parse_AcmeAccountSelection( request, formStash, account_key_option=formStash.results[\"account_key_option\"],", "``False`` if not; ``None`` for conditional logic \"\"\" formStash =", "formStash): self.formStash = formStash self.getcreate_args = {} def require_new(self, require_contact=None,", ":param require_contact: ``True`` if required; ``False`` if not; ``None`` for", "self.upload_type = \"pem\" self.acme_account_provider_id = getcreate_args[ \"acme_account_provider_id\" ] = acme_account_provider_id", "parser privateKeySelection.private_key_strategy__requested = ( model_utils.PrivateKeySelection_2_PrivateKeyStrategy[\"upload\"] ) return privateKeySelection else: if", "`private_key_option`\") if not private_key_pem_md5: # `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field(", "= \"upload\" acmeAccountSelection.upload_parsed = parser return acmeAccountSelection else: if account_key_option", "PrivateKey is not a complex upload to parse itself This", "(dbAcmeAccount, _is_created,) = lib_db.getcreate.getcreate__AcmeAccount( request.api_context, **key_create_args ) acmeAccountSelection.AcmeAccount = dbAcmeAccount", "for conditional logic \"\"\" formStash = self.formStash acme_account_provider_id = formStash.results.get(", "private_key_technology: private_key_technology_id = model_utils.KeyTechnology.from_string( private_key_technology ) if not private_key_technology_id and", "will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=\"Error_Main\", message=\"invalid domain names detected\" )", "= self.formStash acme_account_provider_id = formStash.results.get( \"acme_account_provider_id\", None ) if acme_account_provider_id", "raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=\"Error_Main\", message=\"invalid domain names detected\" ) return", "privateKeySelection.upload_parsed = parser privateKeySelection.private_key_strategy__requested = ( model_utils.PrivateKeySelection_2_PrivateKeyStrategy[\"upload\"] ) return privateKeySelection", "`FormInvalid()` formStash.fatal_form( \"This form does not support no AcmeAccount selection.\"", "= None le_reg_jsons = None private_key_cycle_id = None private_key_technology_id =", "errors. parser = _PrivateKeyUploadParser(formStash) parser.require_upload() # update our object privateKeySelection.selection", "submitted_ = formStash.results.get(source_) if submitted_: # this function checks the", "# 4: maybe we only want http01 domains submitted? if", "`ValueError(\"invalid domain\")` on the first invalid domain submitted_ = utils.domains_from_string(submitted_)", "), ( \"account_key_file_le_meta\", \"account_key_file_le_pkey\", \"account_key_file_le_reg\", ), ) failures = []", "# ------------------- # do a quick parse... requirements_either_or = (", "or all of (`account_key_file_le_meta`, `account_key_file_le_pkey`, `account_key_file_le_reg`).\" ) # ------------------- #", "unless a pem is uploaded # required for PEM, ignored", "account_key_option == \"account_key_reuse\": acmeAccountSelection.selection = \"reuse\" account_key_pem_md5 = formStash.results[\"account_key_reuse\"] elif", "ensure there is no overlap domain_names_all_set = set(domain_names_all) if len(domain_names_all)", "AcmeAccountUploadParser(formStash) # this will have: `contact`, `private_key_cycle`, `private_key_technology` parser.require_upload(require_contact=require_contact) #", "None ) if private_key_technology: private_key_technology_id = model_utils.KeyTechnology.from_string( private_key_technology ) if", "== \"account_key_file\": # this will handle form validation and raise", "if not dbPrivateKey: formStash.fatal_field( field=private_key_option, message=\"Could not load the placeholder", "# this function checks the domain names match a simple", "( \"account_key_file_le_meta\", \"account_key_file_le_pkey\", \"account_key_file_le_reg\", ), ) failures = [] passes", "require_contact = True contact = formStash.results.get(\"account__contact\") if not contact and", "field=\"acme_account_provider_id\", message=\"No provider submitted.\" ) self.upload_type = \"pem\" self.acme_account_provider_id =", "\"acme_account_provider_id\", None ) private_key_cycle = formStash.results.get(\"account__private_key_cycle\", None) if private_key_cycle is", "return model_utils.PrivateKeyStrategy.from_string( self.private_key_strategy__requested ) def parse_AcmeAccountSelection( request, formStash, account_key_option=None, allow_none=None,", "six.PY3: for (k, v) in list(getcreate_args.items()): if isinstance(v, bytes): getcreate_args[k]", "# instance of AcmeAccountUploadParser or None private_key_strategy__requested = None PrivateKey", "PrivateKey is not enrolled in the system.\", ) privateKeySelection.PrivateKey =", "!= len(domain_names_all_set): # `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=\"Error_Main\", message=\"a", "object privateKeySelection.selection = \"upload\" privateKeySelection.upload_parsed = parser privateKeySelection.private_key_strategy__requested = (", "`formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=account_key_option, message=\"You did not provide", "logic \"\"\" formStash = self.formStash # ------------------- # do a", "we need all of them if any(option_set_results): if not all(option_set_results):", "= dbPrivateKey elif privateKeySelection.selection == \"generate\": dbPrivateKey = lib_db.get.get__PrivateKey__by_id(request.api_context, 0)", "None private_key_strategy__requested = None PrivateKey = None @property def private_key_strategy_id__requested(self):", "formStash.fatal_field( field=\"acme_account_provider_id\", message=\"No provider submitted.\" ) self.upload_type = \"pem\" self.acme_account_provider_id", "not; ``None`` for conditional logic :param require_technology: ``True`` if required;", "\"account_key_file_le_meta\", \"account_key_file_le_pkey\", \"account_key_file_le_reg\", ), ) failures = [] passes =", "if not account_key_pem_md5: # `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=account_key_option,", "the first invalid domain submitted_ = utils.domains_from_string(submitted_) if submitted_: domain_names_all.extend(submitted_)", "only want http01 domains submitted? if http01_only: for (k, v)", "= \"reuse\" privateKeySelection.private_key_strategy__requested = ( model_utils.PrivateKeySelection_2_PrivateKeyStrategy[\"reuse\"] ) private_key_pem_md5 = formStash.results[\"private_key_reuse\"]", "want http01 domains submitted? if http01_only: for (k, v) in", "= None upload_type = None # pem OR letsencrypt def", "first invalid domain submitted_ = utils.domains_from_string(submitted_) if submitted_: domain_names_all.extend(submitted_) domains_challenged[target_]", "a complex upload to parse itself This code exists to", "ensure there are domains if not domain_names_all: # `formStash.fatal_field()` will", "elif account_key_option == \"account_key_reuse\": acmeAccountSelection.selection = \"reuse\" account_key_pem_md5 = formStash.results[\"account_key_reuse\"]", "do a quick parse... requirements_either_or = ( ( \"account_key_file_pem\", #", "uploaded AcmeAccount \"\"\" selection = None upload_parsed = None #", "selected AcmeAccount is not enrolled in the system.\", ) if", "= model_utils.DomainsChallenged() # this function checks the domain names match", "_is_created, ) = lib_db.getcreate.getcreate__PrivateKey__by_pem_text( request.api_context, **key_create_args ) privateKeySelection.PrivateKey = dbPrivateKey", "in option_set ] # if we have any item, we", "request.api_context, **key_create_args ) acmeAccountSelection.AcmeAccount = dbAcmeAccount privateKeySelection = parse_PrivateKeySelection( request,", "a value\" ) dbPrivateKey = lib_db.get.get__PrivateKey__by_pemMd5( request.api_context, private_key_pem_md5, is_active=True )", "None # tracked acme_account_provider_id = None account_key_pem = None le_meta_jsons", "self.formStash acme_account_provider_id = formStash.results.get( \"acme_account_provider_id\", None ) if acme_account_provider_id is", "enrolled in the system.\", ) if is_global_default and not dbAcmeAccount.is_global_default:", "to manage an uploaded AcmeAccount \"\"\" selection = None upload_parsed", "formStash, private_key_option=formStash.results[\"private_key_option\"], ) if privateKeySelection.selection == \"upload\": key_create_args = privateKeySelection.upload_parsed.getcreate_args", "# `formStash.fatal_form()` will raise `FormInvalid()` formStash.fatal_form( \"This form does not", "= None # tracked acme_account_provider_id = None account_key_pem = None", "``False`` if not; ``None`` for conditional logic :param require_technology: ``True``", "require_technology=True): \"\"\" routine for creating a NEW AcmeAccount (peter_sslers generates", "`formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=private_key_option, message=\"You did not provide", "iterate over the submitted domains by segment for (target_, source_)", "private_key_pem_md5, is_active=True ) if not dbPrivateKey: # `formStash.fatal_field()` will raise", "`FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=account_key_option, message=\"The selected AcmeAccount is not the current", "key_create_args[ \"private_key_source_id\" ] = model_utils.PrivateKeySource.from_string(\"imported\") key_create_args[\"private_key_type_id\"] = model_utils.PrivateKeyType.from_string( \"standard\" )", "), ) failures = [] passes = [] for idx,", "`formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=\"account__private_key_technology\", message=\"No PrivateKey technology submitted.\",", "None formStash = None # tracked acme_account_provider_id = None account_key_pem", "raise `FormInvalid()` formStash.fatal_form( \"You must upload `account_key_file_pem` or all of", "source_) in DOMAINS_CHALLENGED_FIELDS.items(): submitted_ = formStash.results.get(source_) if submitted_: # this", "parser = _PrivateKeyUploadParser(formStash) parser.require_upload() # update our object privateKeySelection.selection =", ") if is_global_default and not dbAcmeAccount.is_global_default: # `formStash.fatal_field()` will raise", "formStash.fatal_field( field=\"Error_Main\", message=\"a domain name can only be associated to", "required for PEM, ignored otherwise acme_account_provider_id = formStash.results.get( \"acme_account_provider_id\", None", "upload to parse itself This code exists to mimic the", "the submitted domains by segment for (target_, source_) in DOMAINS_CHALLENGED_FIELDS.items():", "this is an explicit \"no item\" selection # only certain", "form does not support no AcmeAccount selection.\" ) # note", "to mimic the AcmeAccount uploading. \"\"\" # overwritten in __init__", "if submitted_: # this function checks the domain names match", "there is no overlap domain_names_all_set = set(domain_names_all) if len(domain_names_all) !=", ") def parse_AcmeAccountSelection( request, formStash, account_key_option=None, allow_none=None, require_contact=None, ): \"\"\"", "= getcreate_args[ \"acme_account_provider_id\" ] = acme_account_provider_id self.account_key_pem = getcreate_args[ \"key_pem\"", "# will be None unless a pem is uploaded #", "and not dbAcmeAccount.is_global_default: # `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=account_key_option,", "None upload_parsed = None # instance of AcmeAccountUploadParser or None", "formStash.results.get( \"account__private_key_technology\", None ) if private_key_technology: private_key_technology_id = model_utils.KeyTechnology.from_string( private_key_technology", "not all(option_set_results): failures.append( \"If any of %s is provided, all", "= \"upload\" privateKeySelection.upload_parsed = parser privateKeySelection.private_key_strategy__requested = ( model_utils.PrivateKeySelection_2_PrivateKeyStrategy[\"upload\"] )", "account_key_option == \"account_key_existing\": acmeAccountSelection.selection = \"existing\" account_key_pem_md5 = formStash.results[\"account_key_existing\"] elif", "] = private_key_cycle_id self.private_key_technology_id = getcreate_args[ \"private_key_technology_id\" ] = private_key_technology_id", "le_meta_jsons = None le_pkey_jsons = None le_reg_jsons = None private_key_cycle_id", "operates on a validated FormEncode results object (via `pyramid_formencode_classic`) \"\"\"", "True elif account_key_option == \"account_key_existing\": acmeAccountSelection.selection = \"existing\" account_key_pem_md5 =", "[] try: # 1: iterate over the submitted domains by", "field=\"account__contact\", message=\"`account__contact` is required.\", ) getcreate_args = {} self.contact =", "= formStash.results[\"private_key_existing\"] elif private_key_option == \"private_key_reuse\": privateKeySelection.selection = \"reuse\" privateKeySelection.private_key_strategy__requested", "note the lowercase \"none\"; this is an explicit \"no item\"", "have any item, we need all of them if any(option_set_results):", "a Certbot installation This parser operates on a validated FormEncode", "private_key_option=formStash.results[\"private_key_option\"], ) if privateKeySelection.selection == \"upload\": key_create_args = privateKeySelection.upload_parsed.getcreate_args key_create_args[\"event_type\"]", "required; ``False`` if not; ``None`` for conditional logic \"\"\" account_key_pem", "\"\"\" :param formStash: an instance of `pyramid_formencode_classic.FormStash` :param require_contact: ``True``", "dbAcmeAccount.is_global_default: # `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=account_key_option, message=\"The selected", "selected PrivateKey is not enrolled in the system.\", ) privateKeySelection.PrivateKey", "`formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=private_key_option, message=\"The selected PrivateKey is", "require_contact=None, ): \"\"\" :param formStash: an instance of `pyramid_formencode_classic.FormStash` :param", "raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=\"domain_name\", message=\"This endpoint currently supports only 1", "object (via `pyramid_formencode_classic`) \"\"\" # overwritten in __init__ getcreate_args =", "`formStash.fatal_form()` will raise `FormInvalid()` formStash.fatal_form(\"Invalid `private_key_option`\") if not private_key_pem_md5: #", "detected\" ) return domains_challenged def form_single_domain_challenge_typed(request, formStash, challenge_type=\"http-01\"): domains_challenged =", "= \"pem\" self.acme_account_provider_id = getcreate_args[ \"acme_account_provider_id\" ] = acme_account_provider_id self.account_key_pem", "# handle the explicit-option privateKeySelection = _PrivateKeySelection() if private_key_option ==", "failures: # `formStash.fatal_form()` will raise `FormInvalid()` formStash.fatal_form( \"You must upload", "...model import utils as model_utils from . import formhandling #", "getcreate_args[ \"key_pem\" ] = formhandling.slurp_file_field(formStash, \"account_key_file_pem\") else: # note that", "are accepted by this form\", ) except ValueError as exc:", "( \"account_key_file_pem\", # \"acme_account_provider_id\", ), ( \"account_key_file_le_meta\", \"account_key_file_le_pkey\", \"account_key_file_le_reg\", ),", "= getcreate_args[\"contact\"] = contact self.private_key_cycle_id = getcreate_args[ \"private_key_cycle_id\" ] =", "form_domains_challenge_typed(request, formStash, http01_only=False): domains_challenged = model_utils.DomainsChallenged() domain_names_all = [] try:", "not enrolled in the system.\", ) privateKeySelection.PrivateKey = dbPrivateKey return", "return acmeAccountSelection else: if account_key_option == \"account_key_global_default\": acmeAccountSelection.selection = \"global_default\"", "= None private_key_pem_md5 = None PrivateKey = None # :class:`model.objects.PrivateKey`", "= formStash self.getcreate_args = {} def require_new(self, require_contact=None, require_technology=True): \"\"\"", "formStash.fatal_field( field=\"Error_Main\", message=\"no domain names submitted\", ) # 3: ensure", "the placeholder PrivateKey for autogeneration.\", ) privateKeySelection.PrivateKey = dbPrivateKey return", "\"private_key_for_account_key\" ] ) return privateKeySelection else: # `formStash.fatal_form()` will raise", "if private_key_technology: private_key_technology_id = model_utils.KeyTechnology.from_string( private_key_technology ) if not private_key_technology_id", "passes = [] for idx, option_set in enumerate(requirements_either_or): option_set_results =", "message=\"No provider submitted.\" ) self.upload_type = \"pem\" self.acme_account_provider_id = getcreate_args[", "message=\"No provider submitted.\" ) private_key_cycle = formStash.results.get(\"account__private_key_cycle\", None) if private_key_cycle", "placeholder PrivateKey.\", ) privateKeySelection.PrivateKey = dbPrivateKey if private_key_option == \"private_key_generate\":", "field=account_key_option, message=\"The selected AcmeAccount is not the current default.\", )", "getcreate_args[ \"private_key_cycle_id\" ] = private_key_cycle_id self.private_key_technology_id = getcreate_args[ \"private_key_technology_id\" ]", "if private_key_cycle is None: # `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field(", "= {} self.contact = getcreate_args[\"contact\"] = contact self.acme_account_provider_id = getcreate_args[", "http01 domains submitted? if http01_only: for (k, v) in domains_challenged.items():", "will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=\"account__private_key_cycle\", message=\"No PrivateKey cycle submitted.\", )", "raise a `ValueError(\"invalid domain\")` on the first invalid domain submitted_", "] ) return privateKeySelection else: # `formStash.fatal_form()` will raise `FormInvalid()`", "formhandling.slurp_file_field(formStash, \"account_key_file_le_reg\") self.getcreate_args = decode_args(getcreate_args) class _PrivateKeyUploadParser(object): \"\"\" A PrivateKey", "acmeAccountSelection.AcmeAccount = dbAcmeAccount privateKeySelection = parse_PrivateKeySelection( request, formStash, private_key_option=formStash.results[\"private_key_option\"], )", ") failures = [] passes = [] for idx, option_set", "submitted.\" ) self.upload_type = \"pem\" self.acme_account_provider_id = getcreate_args[ \"acme_account_provider_id\" ]", "= ( model_utils.PrivateKeySelection_2_PrivateKeyStrategy[\"upload\"] ) return privateKeySelection else: if private_key_option ==", "import utils as model_utils from . import formhandling # ==============================================================================", "= v.decode(\"utf8\") return getcreate_args # standardized mapping for `model_utils.DomainsChallenged` to", "v.decode(\"utf8\") return getcreate_args # standardized mapping for `model_utils.DomainsChallenged` to a", "private_key_option in ( \"private_key_generate\", \"private_key_for_account_key\", ): dbPrivateKey = lib_db.get.get__PrivateKey__by_id(request.api_context, 0)", "formStash.fatal_field( field=account_key_option, message=\"The selected AcmeAccount is not enrolled in the", "self.le_meta_jsons = getcreate_args[ \"le_meta_jsons\" ] = formhandling.slurp_file_field(formStash, \"account_key_file_le_meta\") self.le_pkey_jsons =", "formStash.fatal_form( message=\"Invalid `account_key_option`\", ) if not account_key_pem_md5: # `formStash.fatal_field()` will", "if not contact and require_contact: # `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)`", "(via `pyramid_formencode_classic`) \"\"\" # overwritten in __init__ getcreate_args = None", "`FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=account_key_option, message=\"You did not provide a value\" )", "private_key_technology = formStash.results.get( \"account__private_key_technology\", None ) if private_key_technology is not", "the domain names match a simple regex # it will", "acmeAccountSelection.selection = \"reuse\" account_key_pem_md5 = formStash.results[\"account_key_reuse\"] elif account_key_option == \"none\":", "dbPrivateKey if private_key_option == \"private_key_generate\": privateKeySelection.selection = \"generate\" privateKeySelection.private_key_strategy__requested =", "1) or failures: # `formStash.fatal_form()` will raise `FormInvalid()` formStash.fatal_form( \"You", "contact self.private_key_cycle_id = getcreate_args[ \"private_key_cycle_id\" ] = private_key_cycle_id self.private_key_technology_id =", "private_key_option=None): private_key_pem = None private_key_pem_md5 = None PrivateKey = None", "formStash.results.get(\"account__contact\", None) if not contact and require_contact: # `formStash.fatal_field()` will", "getcreate_args = {} self.contact = getcreate_args[\"contact\"] = contact self.acme_account_provider_id =", "lowercase \"none\"; this is an explicit \"no item\" selection #", "require_new(self, require_contact=None, require_technology=True): \"\"\" routine for creating a NEW AcmeAccount", "= None account_key_pem = None le_meta_jsons = None le_pkey_jsons =", "upload `account_key_file_pem` or all of (`account_key_file_le_meta`, `account_key_file_le_pkey`, `account_key_file_le_reg`).\" ) #", "your form.\") def parse_PrivateKeySelection(request, formStash, private_key_option=None): private_key_pem = None private_key_pem_md5", ") except ValueError as exc: # `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)`", "option # will be None unless a pem is uploaded", "self.contact = getcreate_args[\"contact\"] = contact self.acme_account_provider_id = getcreate_args[ \"acme_account_provider_id\" ]", "!= 1: # `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=\"domain_name\", message=\"This", "credentials) :param require_contact: ``True`` if required; ``False`` if not; ``None``", "our object privateKeySelection.selection = \"upload\" privateKeySelection.upload_parsed = parser privateKeySelection.private_key_strategy__requested =", "= None # pem OR letsencrypt def __init__(self, formStash): self.formStash", "# it will raise a `ValueError(\"invalid domain\")` on the first", ") if privateKeySelection.selection == \"upload\": key_create_args = privateKeySelection.upload_parsed.getcreate_args key_create_args[\"event_type\"] =", "ways: * a single PEM file * an intra-associated three", "names submitted\", ) # 3: ensure there is no overlap", "an error validating your form.\") def form_key_selection(request, formStash, require_contact=None): \"\"\"", "selected AcmeAccount is not the current default.\", ) acmeAccountSelection.AcmeAccount =", "] = model_utils.AcmeAccountKeySource.from_string(\"imported\") (dbAcmeAccount, _is_created,) = lib_db.getcreate.getcreate__AcmeAccount( request.api_context, **key_create_args )", "= dbPrivateKey return (acmeAccountSelection, privateKeySelection) def form_domains_challenge_typed(request, formStash, http01_only=False): domains_challenged", "associated to one challenge type\", ) # 4: maybe we", "generates the credentials) :param require_contact: ``True`` if required; ``False`` if", "for Python2/3 \"\"\" if six.PY3: for (k, v) in list(getcreate_args.items()):", "------------------- # do a quick parse... requirements_either_or = ( (", "them if any(option_set_results): if not all(option_set_results): failures.append( \"If any of", "= private_key_cycle_id self.private_key_technology_id = getcreate_args[ \"private_key_technology_id\" ] = private_key_technology_id if", "privateKeySelection else: # `formStash.fatal_form()` will raise `FormInvalid()` formStash.fatal_form(\"Invalid `private_key_option`\") if", "return getcreate_args # standardized mapping for `model_utils.DomainsChallenged` to a formStash", "names match a simple regex domain_names = utils.domains_from_string(formStash.results[\"domain_name\"]) if not", "as exc: # `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=\"Error_Main\", message=\"invalid", "# `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=\"account__contact\", message=\"`account__contact` is required.\",", "`formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=\"Error_Main\", message=\"invalid domain names detected\"", "key_create_args[\"private_key_type_id\"] = model_utils.PrivateKeyType.from_string( \"standard\" ) ( dbPrivateKey, _is_created, ) =", "None ) if acme_account_provider_id is None: # `formStash.fatal_field()` will raise", "not contact and require_contact: # `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field(", ":param formStash: an instance of `pyramid_formencode_classic.FormStash` :param account_key_option: :param allow_none:", "conditional logic :param require_technology: ``True`` if required; ``False`` if not;", "pem def __init__(self, formStash): self.formStash = formStash self.getcreate_args = {}", "None PrivateKey = None @property def private_key_strategy_id__requested(self): return model_utils.PrivateKeyStrategy.from_string( self.private_key_strategy__requested", "if not dbPrivateKey: formStash.fatal_field( field=\"private_key_option\", message=\"Could not load the placeholder", "self.formStash = formStash self.getcreate_args = {} def require_upload(self): \"\"\" routine", "model_utils from . import formhandling # ============================================================================== def decode_args(getcreate_args): \"\"\"", "An AcmeAccount may be uploaded multiple ways: * a single", "# note that we use `jsonS` to indicate a string", "to a formStash DOMAINS_CHALLENGED_FIELDS = { \"http-01\": \"domain_names_http01\", \"dns-01\": \"domain_names_dns01\",", "upload_type = None # pem OR letsencrypt def __init__(self, formStash):", "formStash.results[\"account_key_global_default\"] is_global_default = True elif account_key_option == \"account_key_existing\": acmeAccountSelection.selection =", "model_utils.PrivateKeyStrategy.from_string( self.private_key_strategy__requested ) def parse_AcmeAccountSelection( request, formStash, account_key_option=None, allow_none=None, require_contact=None,", "will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=\"account__contact\", message=\"`account__contact` is required.\", ) getcreate_args", "None # instance of AcmeAccountUploadParser or None private_key_strategy__requested = None", "# `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=account_key_option, message=\"The selected AcmeAccount", "upload_type = None # pem def __init__(self, formStash): self.formStash =", "AcmeAccount may be uploaded multiple ways: * a single PEM", "== \"private_key_reuse\": privateKeySelection.selection = \"reuse\" privateKeySelection.private_key_strategy__requested = ( model_utils.PrivateKeySelection_2_PrivateKeyStrategy[\"reuse\"] )", "] = formhandling.slurp_file_field(formStash, \"private_key_file_pem\") self.getcreate_args = decode_args(getcreate_args) class _AcmeAccountSelection(object): \"\"\"", "as lib_db from ...lib import utils from ...model import objects", "= contact self.acme_account_provider_id = getcreate_args[ \"acme_account_provider_id\" ] = acme_account_provider_id self.private_key_cycle_id", "\"account_key_file_le_meta\") self.le_pkey_jsons = getcreate_args[ \"le_pkey_jsons\" ] = formhandling.slurp_file_field(formStash, \"account_key_file_le_pkey\") self.le_reg_jsons", "\"\"\" An AcmeAccount may be uploaded multiple ways: * a", "the explicit-option acmeAccountSelection = _AcmeAccountSelection() if account_key_option == \"account_key_file\": #", "None formStash = None # tracked private_key_pem = None upload_type", "privateKeySelection.PrivateKey = dbPrivateKey if private_key_option == \"private_key_generate\": privateKeySelection.selection = \"generate\"", "in domains_challenged.items(): if k == \"http-01\": continue if v: #", "field=private_key_option, message=\"You did not provide a value\" ) dbPrivateKey =", "selection.\" ) # note the lowercase \"none\"; this is an", "private_key_strategy_id__requested(self): return model_utils.PrivateKeyStrategy.from_string( self.private_key_strategy__requested ) def parse_AcmeAccountSelection( request, formStash, account_key_option=None,", "all of (`account_key_file_le_meta`, `account_key_file_le_pkey`, `account_key_file_le_reg`).\" ) # ------------------- # validate", "PrivateKey \"\"\" formStash = self.formStash getcreate_args = {} if formStash.results[\"private_key_file_pem\"]", "load the placeholder PrivateKey for autogeneration.\", ) privateKeySelection.PrivateKey = dbPrivateKey", "formStash.fatal_field( field=\"account__private_key_cycle\", message=\"No PrivateKey cycle submitted.\", ) private_key_cycle_id = model_utils.PrivateKeyCycle.from_string(", "`formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=\"Error_Main\", message=\"only http-01 domains are", "formStash.fatal_field( field=\"acme_account_provider_id\", message=\"No provider submitted.\" ) private_key_cycle = formStash.results.get(\"account__private_key_cycle\", None)", "v: # `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=\"Error_Main\", message=\"only http-01", "`FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=private_key_option, message=\"You did not provide a value\" )", "did not provide a value\" ) dbAcmeAccount = lib_db.get.get__AcmeAccount__by_pemMd5( request.api_context,", "# required for PEM, ignored otherwise acme_account_provider_id = formStash.results.get( \"acme_account_provider_id\",", "key_create_args[\"event_type\"] = \"PrivateKey__insert\" key_create_args[ \"private_key_source_id\" ] = model_utils.PrivateKeySource.from_string(\"imported\") key_create_args[\"private_key_type_id\"] =", "* a single PEM file * an intra-associated three file", "return domains_challenged def form_single_domain_challenge_typed(request, formStash, challenge_type=\"http-01\"): domains_challenged = model_utils.DomainsChallenged() #", "= _AcmeAccountSelection() if account_key_option == \"account_key_file\": # this will handle", "option_set_results = [ True if formStash.results[option_set_item] is not None else", "== \"account_key_existing\": acmeAccountSelection.selection = \"existing\" account_key_pem_md5 = formStash.results[\"account_key_existing\"] elif account_key_option", ") if not private_key_technology_id and require_technology: # `formStash.fatal_field()` will raise", "if not; ``None`` for conditional logic :param require_technology: ``True`` if", "\"upload\": key_create_args = acmeAccountSelection.upload_parsed.getcreate_args key_create_args[\"event_type\"] = \"AcmeAccount__insert\" key_create_args[ \"acme_account_key_source_id\" ]", "% str(option_set) ) else: passes.append(idx) if (len(passes) != 1) or", "privateKeySelection.selection = \"upload\" privateKeySelection.upload_parsed = parser privateKeySelection.private_key_strategy__requested = ( model_utils.PrivateKeySelection_2_PrivateKeyStrategy[\"upload\"]", "a string self.le_meta_jsons = getcreate_args[ \"le_meta_jsons\" ] = formhandling.slurp_file_field(formStash, \"account_key_file_le_meta\")", "= formhandling.slurp_file_field(formStash, \"private_key_file_pem\") self.getcreate_args = decode_args(getcreate_args) class _AcmeAccountSelection(object): \"\"\" Class", "= decode_args(getcreate_args) class _PrivateKeyUploadParser(object): \"\"\" A PrivateKey is not a", "not; ``None`` for conditional logic \"\"\" formStash = self.formStash #", "formStash, private_key_option=None): private_key_pem = None private_key_pem_md5 = None PrivateKey =", "account_key_pem = None account_key_pem_md5 = None dbAcmeAccount = None is_global_default", "the explicit-option privateKeySelection = _PrivateKeySelection() if private_key_option == \"private_key_file\": #", "is not enrolled in the system.\", ) if is_global_default and", "# overwritten in __init__ getcreate_args = None formStash = None", "\"generate\" privateKeySelection.private_key_strategy__requested = ( model_utils.PrivateKeySelection_2_PrivateKeyStrategy[\"generate\"] ) elif private_key_option == \"private_key_for_account_key\":", "bytes): getcreate_args[k] = v.decode(\"utf8\") return getcreate_args # standardized mapping for", "private_key_cycle ) private_key_technology_id = None private_key_technology = formStash.results.get( \"account__private_key_technology\", None", "message=\"Could not load the placeholder PrivateKey for autogeneration.\", ) privateKeySelection.PrivateKey", "\"PrivateKey__insert\" key_create_args[ \"private_key_source_id\" ] = model_utils.PrivateKeySource.from_string(\"imported\") key_create_args[\"private_key_type_id\"] = model_utils.PrivateKeyType.from_string( \"standard\"", "== \"account_key_reuse\": acmeAccountSelection.selection = \"reuse\" account_key_pem_md5 = formStash.results[\"account_key_reuse\"] elif account_key_option", "\"acme_account_key_source_id\" ] = model_utils.AcmeAccountKeySource.from_string(\"imported\") (dbAcmeAccount, _is_created,) = lib_db.getcreate.getcreate__AcmeAccount( request.api_context, **key_create_args", "if not; ``None`` for conditional logic \"\"\" account_key_pem = None", "= \"global_default\" account_key_pem_md5 = formStash.results[\"account_key_global_default\"] is_global_default = True elif account_key_option", "= None PrivateKey = None # :class:`model.objects.PrivateKey` # handle the", "option_set in enumerate(requirements_either_or): option_set_results = [ True if formStash.results[option_set_item] is", "from ...lib import utils from ...model import objects as model_objects", "= formStash.results.get( \"account__private_key_technology\", None ) if private_key_technology is not None:", "return privateKeySelection else: # `formStash.fatal_form()` will raise `FormInvalid()` formStash.fatal_form(\"Invalid `private_key_option`\")", "handle the explicit-option acmeAccountSelection = _AcmeAccountSelection() if account_key_option == \"account_key_file\":", "== \"generate\": dbPrivateKey = lib_db.get.get__PrivateKey__by_id(request.api_context, 0) if not dbPrivateKey: formStash.fatal_field(", "domain name can only be associated to one challenge type\",", "require_technology: ``True`` if required; ``False`` if not; ``None`` for conditional", "submitted domains by segment for (target_, source_) in DOMAINS_CHALLENGED_FIELDS.items(): submitted_", "file if formStash.results[\"account_key_file_pem\"] is not None: require_contact = True contact", "privateKeySelection.selection = \"existing\" privateKeySelection.private_key_strategy__requested = ( model_utils.PrivateKeySelection_2_PrivateKeyStrategy[\"existing\"] ) private_key_pem_md5 =", "creating a NEW AcmeAccount (peter_sslers generates the credentials) :param require_contact:", "if any(option_set_results): if not all(option_set_results): failures.append( \"If any of %s", "in DOMAINS_CHALLENGED_FIELDS.items(): submitted_ = formStash.results.get(source_) if submitted_: # this function", "an exiting AcmeAccount+AcmeAccountKey :param require_contact: ``True`` if required; ``False`` if", "def require_new(self, require_contact=None, require_technology=True): \"\"\" routine for creating a NEW", "will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=account_key_option, message=\"The selected AcmeAccount is not", "# ------------------- # validate the provider option # will be", "= _PrivateKeySelection() if private_key_option == \"private_key_file\": # this will handle", "= ( ( \"account_key_file_pem\", # \"acme_account_provider_id\", ), ( \"account_key_file_le_meta\", \"account_key_file_le_pkey\",", "elif private_key_option == \"private_key_reuse\": privateKeySelection.selection = \"reuse\" privateKeySelection.private_key_strategy__requested = (", "raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=\"Error_Main\", message=\"only http-01 domains are accepted by", "domain names\") if len(domain_names) != 1: # `formStash.fatal_field()` will raise", "tracked private_key_pem = None upload_type = None # pem def", "None: if acme_account_provider_id is None: # `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)`", "is uploaded # required for PEM, ignored otherwise acme_account_provider_id =", "not domain_names_all: # `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=\"Error_Main\", message=\"no", "`formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=\"Error_Main\", message=\"a domain name can", "return privateKeySelection else: if private_key_option == \"private_key_existing\": privateKeySelection.selection = \"existing\"", "dbPrivateKey, _is_created, ) = lib_db.getcreate.getcreate__PrivateKey__by_pem_text( request.api_context, **key_create_args ) privateKeySelection.PrivateKey =", "no overlap domain_names_all_set = set(domain_names_all) if len(domain_names_all) != len(domain_names_all_set): #", "submitted_: domain_names_all.extend(submitted_) domains_challenged[target_] = submitted_ # 2: ensure there are", "else: if private_key_option == \"private_key_existing\": privateKeySelection.selection = \"existing\" privateKeySelection.private_key_strategy__requested =", "not provide a value\" ) dbPrivateKey = lib_db.get.get__PrivateKey__by_pemMd5( request.api_context, private_key_pem_md5,", "private_key_option == \"private_key_reuse\": privateKeySelection.selection = \"reuse\" privateKeySelection.private_key_strategy__requested = ( model_utils.PrivateKeySelection_2_PrivateKeyStrategy[\"reuse\"]", "not; ``None`` for conditional logic \"\"\" acmeAccountSelection = parse_AcmeAccountSelection( request,", "getcreate_args[ \"le_pkey_jsons\" ] = formhandling.slurp_file_field(formStash, \"account_key_file_le_pkey\") self.le_reg_jsons = getcreate_args[ \"le_reg_jsons\"", "a simple regex # it will raise a `ValueError(\"invalid domain\")`", "== \"private_key_for_account_key\": privateKeySelection.selection = \"private_key_for_account_key\" privateKeySelection.private_key_strategy__requested = ( model_utils.PrivateKeySelection_2_PrivateKeyStrategy[ \"private_key_for_account_key\"", "autogeneration.\", ) privateKeySelection.PrivateKey = dbPrivateKey return (acmeAccountSelection, privateKeySelection) def form_domains_challenge_typed(request,", "\"\"\" formStash = self.formStash # ------------------- # do a quick", "intra-associated three file triplet from a Certbot installation This parser", "\"\"\" routine for uploading an exiting PrivateKey \"\"\" formStash =", "option_set ] # if we have any item, we need", "provided, all must be provided.\" % str(option_set) ) else: passes.append(idx)", "if (len(passes) != 1) or failures: # `formStash.fatal_form()` will raise", "private_key_cycle_id self.private_key_technology_id = getcreate_args[ \"private_key_technology_id\" ] = private_key_technology_id if formStash.results[\"account_key_file_pem\"]", "= getcreate_args[ \"key_pem\" ] = formhandling.slurp_file_field(formStash, \"private_key_file_pem\") self.getcreate_args = decode_args(getcreate_args)", "raise `FormInvalid()` formStash.fatal_form(\"Invalid `private_key_option`\") if not private_key_pem_md5: # `formStash.fatal_field()` will", "mimic the AcmeAccount uploading. \"\"\" # overwritten in __init__ getcreate_args", "exc: # `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=\"Error_Main\", message=\"invalid domain", "for (target_, source_) in DOMAINS_CHALLENGED_FIELDS.items(): submitted_ = formStash.results.get(source_) if submitted_:", "form\", ) except ValueError as exc: # `formStash.fatal_field()` will raise", "by this form\", ) except ValueError as exc: # `formStash.fatal_field()`", "\"private_key_reuse\": privateKeySelection.selection = \"reuse\" privateKeySelection.private_key_strategy__requested = ( model_utils.PrivateKeySelection_2_PrivateKeyStrategy[\"reuse\"] ) private_key_pem_md5", "<filename>peter_sslers/web/lib/form_utils.py # pypi import six # local from ...lib import", "quick parse... requirements_either_or = ( ( \"account_key_file_pem\", # \"acme_account_provider_id\", ),", "= getcreate_args[ \"le_pkey_jsons\" ] = formhandling.slurp_file_field(formStash, \"account_key_file_le_pkey\") self.le_reg_jsons = getcreate_args[", "= None private_key_cycle_id = None private_key_technology_id = None upload_type =", "= model_utils.AcmeAccountKeySource.from_string(\"imported\") (dbAcmeAccount, _is_created,) = lib_db.getcreate.getcreate__AcmeAccount( request.api_context, **key_create_args ) acmeAccountSelection.AcmeAccount", ") privateKeySelection.PrivateKey = dbPrivateKey return (acmeAccountSelection, privateKeySelection) def form_domains_challenge_typed(request, formStash,", "\"private_key_cycle_id\" ] = private_key_cycle_id self.private_key_technology_id = getcreate_args[ \"private_key_technology_id\" ] =", "\"AcmeAccount__insert\" key_create_args[ \"acme_account_key_source_id\" ] = model_utils.AcmeAccountKeySource.from_string(\"imported\") (dbAcmeAccount, _is_created,) = lib_db.getcreate.getcreate__AcmeAccount(", "\"account__private_key_technology\", None ) if private_key_technology: private_key_technology_id = model_utils.KeyTechnology.from_string( private_key_technology )", "private_key_option == \"private_key_for_account_key\": privateKeySelection.selection = \"private_key_for_account_key\" privateKeySelection.private_key_strategy__requested = ( model_utils.PrivateKeySelection_2_PrivateKeyStrategy[", "class AcmeAccountUploadParser(object): \"\"\" An AcmeAccount may be uploaded multiple ways:", "privateKeySelection.selection = \"private_key_for_account_key\" privateKeySelection.private_key_strategy__requested = ( model_utils.PrivateKeySelection_2_PrivateKeyStrategy[ \"private_key_for_account_key\" ] )", "( ( \"account_key_file_pem\", # \"acme_account_provider_id\", ), ( \"account_key_file_le_meta\", \"account_key_file_le_pkey\", \"account_key_file_le_reg\",", "domains by segment for (target_, source_) in DOMAINS_CHALLENGED_FIELDS.items(): submitted_ =", "# `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=\"domain_name\", message=\"This endpoint currently", "raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=\"acme_account_provider_id\", message=\"No provider submitted.\" ) self.upload_type =", "`account_key_file_pem` or all of (`account_key_file_le_meta`, `account_key_file_le_pkey`, `account_key_file_le_reg`).\" ) # -------------------", "form validation and raise errors. parser = AcmeAccountUploadParser(formStash) # this", "# :class:`model.objects.PrivateKey` # handle the explicit-option privateKeySelection = _PrivateKeySelection() if", "import utils from ...model import objects as model_objects from ...model", "model_utils.PrivateKeyType.from_string( \"standard\" ) ( dbPrivateKey, _is_created, ) = lib_db.getcreate.getcreate__PrivateKey__by_pem_text( request.api_context,", "`formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=\"Error_Main\", message=\"no domain names submitted\",", "getcreate_args = {} if formStash.results[\"private_key_file_pem\"] is not None: self.upload_type =", "handle the explicit-option privateKeySelection = _PrivateKeySelection() if private_key_option == \"private_key_file\":", "and require_contact: # `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=\"account__contact\", message=\"`account__contact`", "is not None: if acme_account_provider_id is None: # `formStash.fatal_field()` will", "single PEM file * an intra-associated three file triplet from", "formhandling.slurp_file_field(formStash, \"account_key_file_le_meta\") self.le_pkey_jsons = getcreate_args[ \"le_pkey_jsons\" ] = formhandling.slurp_file_field(formStash, \"account_key_file_le_pkey\")", "be associated to one challenge type\", ) # 4: maybe", ") return privateKeySelection else: # `formStash.fatal_form()` will raise `FormInvalid()` formStash.fatal_form(\"Invalid", "formStash = self.formStash # ------------------- # do a quick parse...", "= [] for idx, option_set in enumerate(requirements_either_or): option_set_results = [", "message=\"`account__contact` is required.\", ) getcreate_args = {} self.contact = getcreate_args[\"contact\"]", "item, we need all of them if any(option_set_results): if not", "dbPrivateKey return (acmeAccountSelection, privateKeySelection) def form_domains_challenge_typed(request, formStash, http01_only=False): domains_challenged =", "None ) if private_key_technology is not None: private_key_technology_id = model_utils.KeyTechnology.from_string(", "# tracked private_key_pem = None upload_type = None # pem", "= None # tracked private_key_pem = None upload_type = None", "= \"generate\" privateKeySelection.private_key_strategy__requested = ( model_utils.PrivateKeySelection_2_PrivateKeyStrategy[\"generate\"] ) elif private_key_option ==", "formStash self.getcreate_args = {} def require_upload(self): \"\"\" routine for uploading", "not None: self.upload_type = \"pem\" self.private_key_pem = getcreate_args[ \"key_pem\" ]", "from ...lib import db as lib_db from ...lib import utils", "privateKeySelection.private_key_strategy__requested = ( model_utils.PrivateKeySelection_2_PrivateKeyStrategy[\"reuse\"] ) private_key_pem_md5 = formStash.results[\"private_key_reuse\"] elif private_key_option", "= \"none\" account_key_pem_md5 = None return acmeAccountSelection else: formStash.fatal_form( message=\"Invalid", "None private_key_technology = formStash.results.get( \"account__private_key_technology\", None ) if private_key_technology is", "required.\", ) getcreate_args = {} self.contact = getcreate_args[\"contact\"] = contact", "message=\"The selected AcmeAccount is not the current default.\", ) acmeAccountSelection.AcmeAccount", "= formStash.results.get(source_) if submitted_: # this function checks the domain", "field=\"account__private_key_technology\", message=\"No PrivateKey technology submitted.\", ) contact = formStash.results.get(\"account__contact\", None)", "handle form validation and raise errors. parser = AcmeAccountUploadParser(formStash) #", "if formStash.results[\"private_key_file_pem\"] is not None: self.upload_type = \"pem\" self.private_key_pem =", "require_technology: # `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=\"account__private_key_technology\", message=\"No PrivateKey", ") if acmeAccountSelection.selection == \"upload\": key_create_args = acmeAccountSelection.upload_parsed.getcreate_args key_create_args[\"event_type\"] =", "= getcreate_args[ \"private_key_technology_id\" ] = private_key_technology_id if formStash.results[\"account_key_file_pem\"] is not", "self.private_key_strategy__requested ) def parse_AcmeAccountSelection( request, formStash, account_key_option=None, allow_none=None, require_contact=None, ):", "\"You must upload `account_key_file_pem` or all of (`account_key_file_le_meta`, `account_key_file_le_pkey`, `account_key_file_le_reg`).\"", "None unless a pem is uploaded # required for PEM,", "None PrivateKey = None # :class:`model.objects.PrivateKey` # handle the explicit-option", "any(option_set_results): if not all(option_set_results): failures.append( \"If any of %s is", "allow_none=None, require_contact=None, ): \"\"\" :param formStash: an instance of `pyramid_formencode_classic.FormStash`", "= contact self.private_key_cycle_id = getcreate_args[ \"private_key_cycle_id\" ] = private_key_cycle_id self.private_key_technology_id", "lib_db.get.get__AcmeAccount__by_pemMd5( request.api_context, account_key_pem_md5, is_active=True ) if not dbAcmeAccount: # `formStash.fatal_field()`", "instance of `pyramid_formencode_classic.FormStash` :param account_key_option: :param allow_none: :param require_contact: ``True``", "= model_utils.PrivateKeyType.from_string( \"standard\" ) ( dbPrivateKey, _is_created, ) = lib_db.getcreate.getcreate__PrivateKey__by_pem_text(", "uploaded multiple ways: * a single PEM file * an", "= acme_account_provider_id self.account_key_pem = getcreate_args[ \"key_pem\" ] = formhandling.slurp_file_field(formStash, \"account_key_file_pem\")", "formStash = None # tracked private_key_pem = None upload_type =", "if private_key_option == \"private_key_existing\": privateKeySelection.selection = \"existing\" privateKeySelection.private_key_strategy__requested = (", "privateKeySelection = _PrivateKeySelection() if private_key_option == \"private_key_file\": # this will", "private_key_cycle_id = model_utils.PrivateKeyCycle.from_string( private_key_cycle ) private_key_technology_id = None private_key_technology =", "parser.require_upload() # update our object privateKeySelection.selection = \"upload\" privateKeySelection.upload_parsed =", "# require `contact` when uploading a PEM file if formStash.results[\"account_key_file_pem\"]", ") getcreate_args = {} self.contact = getcreate_args[\"contact\"] = contact self.private_key_cycle_id", "our object acmeAccountSelection.selection = \"upload\" acmeAccountSelection.upload_parsed = parser return acmeAccountSelection", "acmeAccountSelection else: formStash.fatal_form( message=\"Invalid `account_key_option`\", ) if not account_key_pem_md5: #", "\"upload\": key_create_args = privateKeySelection.upload_parsed.getcreate_args key_create_args[\"event_type\"] = \"PrivateKey__insert\" key_create_args[ \"private_key_source_id\" ]", "`FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=\"Error_Main\", message=\"a domain name can only be associated", "getcreate_args[ \"private_key_technology_id\" ] = private_key_technology_id if formStash.results[\"account_key_file_pem\"] is not None:", "class _AcmeAccountSelection(object): \"\"\" Class used to manage an uploaded AcmeAccount", "key_create_args[ \"acme_account_key_source_id\" ] = model_utils.AcmeAccountKeySource.from_string(\"imported\") (dbAcmeAccount, _is_created,) = lib_db.getcreate.getcreate__AcmeAccount( request.api_context,", "uploading. \"\"\" # overwritten in __init__ getcreate_args = None formStash", "self.getcreate_args = {} def require_new(self, require_contact=None, require_technology=True): \"\"\" routine for", "if privateKeySelection.selection == \"upload\": key_create_args = privateKeySelection.upload_parsed.getcreate_args key_create_args[\"event_type\"] = \"PrivateKey__insert\"", "require_upload(self): \"\"\" routine for uploading an exiting PrivateKey \"\"\" formStash", "...model import objects as model_objects from ...model import utils as", "require_contact=None, require_technology=None): \"\"\" routine for uploading an exiting AcmeAccount+AcmeAccountKey :param", "\"account_key_file_pem\") else: # note that we use `jsonS` to indicate", "will handle form validation and raise errors. parser = _PrivateKeyUploadParser(formStash)", "match a simple regex domain_names = utils.domains_from_string(formStash.results[\"domain_name\"]) if not domain_names:", "is_global_default = None # handle the explicit-option acmeAccountSelection = _AcmeAccountSelection()", "we only want http01 domains submitted? if http01_only: for (k,", "None: self.upload_type = \"pem\" self.private_key_pem = getcreate_args[ \"key_pem\" ] =", "`private_key_technology` parser.require_upload(require_contact=require_contact) # update our object acmeAccountSelection.selection = \"upload\" acmeAccountSelection.upload_parsed", "getcreate_args[k] = v.decode(\"utf8\") return getcreate_args # standardized mapping for `model_utils.DomainsChallenged`", "( model_utils.PrivateKeySelection_2_PrivateKeyStrategy[\"upload\"] ) return privateKeySelection else: if private_key_option == \"private_key_existing\":", "not a complex upload to parse itself This code exists", "not domain_names: # `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field(field=\"domain_name\", message=\"Found no", "raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=\"account__private_key_technology\", message=\"No PrivateKey technology submitted.\", ) #", "mapping for `model_utils.DomainsChallenged` to a formStash DOMAINS_CHALLENGED_FIELDS = { \"http-01\":", "only 1 domain name\", ) domains_challenged[challenge_type] = domain_names return domains_challenged", "submitted.\", ) contact = formStash.results.get(\"account__contact\", None) if not contact and", "account_key_pem_md5 = formStash.results[\"account_key_reuse\"] elif account_key_option == \"none\": if not allow_none:", "# this will handle form validation and raise errors. parser", "allow_none: :param require_contact: ``True`` if required; ``False`` if not; ``None``", "require_upload(self, require_contact=None, require_technology=None): \"\"\" routine for uploading an exiting AcmeAccount+AcmeAccountKey", "handle form validation and raise errors. parser = _PrivateKeyUploadParser(formStash) parser.require_upload()", "model_utils.DomainsChallenged() domain_names_all = [] try: # 1: iterate over the", "formStash.fatal_field( field=\"Error_Main\", message=\"invalid domain names detected\" ) return domains_challenged def", "is not enrolled in the system.\", ) privateKeySelection.PrivateKey = dbPrivateKey", "provided.\" % str(option_set) ) else: passes.append(idx) if (len(passes) != 1)", "parse_PrivateKeySelection( request, formStash, private_key_option=formStash.results[\"private_key_option\"], ) if privateKeySelection.selection == \"upload\": key_create_args", "have: `contact`, `private_key_cycle`, `private_key_technology` parser.require_upload(require_contact=require_contact) # update our object acmeAccountSelection.selection", "True if formStash.results[option_set_item] is not None else False for option_set_item", "is_global_default = True elif account_key_option == \"account_key_existing\": acmeAccountSelection.selection = \"existing\"", "except ValueError as exc: # `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field(", "None # instance of AcmeAccountUploadParser or None AcmeAccount = None", "will raise `FormInvalid()` formStash.fatal_form( \"This form does not support no", "request.api_context, account_key_pem_md5, is_active=True ) if not dbAcmeAccount: # `formStash.fatal_field()` will", "message=\"The selected PrivateKey is not enrolled in the system.\", )", ") ( dbPrivateKey, _is_created, ) = lib_db.getcreate.getcreate__PrivateKey__by_pem_text( request.api_context, **key_create_args )", "return acmeAccountSelection # `formStash.fatal_form()` will raise `FormInvalid()` formStash.fatal_form(\"There was an", "for conditional logic \"\"\" account_key_pem = None account_key_pem_md5 = None", "= dbPrivateKey return privateKeySelection # `formStash.fatal_form()` will raise `FormInvalid()` formStash.fatal_form(\"There", "provide a value\" ) dbAcmeAccount = lib_db.get.get__AcmeAccount__by_pemMd5( request.api_context, account_key_pem_md5, is_active=True", "formStash.fatal_field( field=private_key_option, message=\"The selected PrivateKey is not enrolled in the", "if v: # `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=\"Error_Main\", message=\"only", "private_key_technology_id and require_technology: # `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=\"account__private_key_technology\",", "else: passes.append(idx) if (len(passes) != 1) or failures: # `formStash.fatal_form()`", "None: # `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=\"account__private_key_cycle\", message=\"No PrivateKey", "# note the lowercase \"none\"; this is an explicit \"no", "account_key_pem_md5 = formStash.results[\"account_key_existing\"] elif account_key_option == \"account_key_reuse\": acmeAccountSelection.selection = \"reuse\"", "is an explicit \"no item\" selection # only certain routes", "\"dns-01\": \"domain_names_dns01\", } class AcmeAccountUploadParser(object): \"\"\" An AcmeAccount may be", "(k, v) in list(getcreate_args.items()): if isinstance(v, bytes): getcreate_args[k] = v.decode(\"utf8\")", "private_key_technology_id = None upload_type = None # pem OR letsencrypt", "self.contact = getcreate_args[\"contact\"] = contact self.private_key_cycle_id = getcreate_args[ \"private_key_cycle_id\" ]", "currently supports only 1 domain name\", ) domains_challenged[challenge_type] = domain_names", "raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=\"Error_Main\", message=\"a domain name can only be", "formStash.results.get( \"acme_account_provider_id\", None ) private_key_cycle = formStash.results.get(\"account__private_key_cycle\", None) if private_key_cycle", "PrivateKey cycle submitted.\", ) private_key_cycle_id = model_utils.PrivateKeyCycle.from_string( private_key_cycle ) private_key_technology_id", "isinstance(v, bytes): getcreate_args[k] = v.decode(\"utf8\") return getcreate_args # standardized mapping", "self.formStash = formStash self.getcreate_args = {} def require_new(self, require_contact=None, require_technology=True):", "will raise `FormInvalid()` formStash.fatal_form(\"Invalid `private_key_option`\") if not private_key_pem_md5: # `formStash.fatal_field()`", "import objects as model_objects from ...model import utils as model_utils", "private_key_technology = formStash.results.get( \"account__private_key_technology\", None ) if private_key_technology: private_key_technology_id =", "# \"acme_account_provider_id\", ), ( \"account_key_file_le_meta\", \"account_key_file_le_pkey\", \"account_key_file_le_reg\", ), ) failures", "None # tracked private_key_pem = None upload_type = None #", "= formStash.results[\"private_key_reuse\"] elif private_key_option in ( \"private_key_generate\", \"private_key_for_account_key\", ): dbPrivateKey", "[] passes = [] for idx, option_set in enumerate(requirements_either_or): option_set_results", "= utils.domains_from_string(formStash.results[\"domain_name\"]) if not domain_names: # `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)`", "be None unless a pem is uploaded # required for", "overwritten in __init__ getcreate_args = None formStash = None #", "``None`` for conditional logic :param require_technology: ``True`` if required; ``False``", "# this will have: `contact`, `private_key_cycle`, `private_key_technology` parser.require_upload(require_contact=require_contact) # update", "privateKeySelection.PrivateKey = dbPrivateKey return privateKeySelection # `formStash.fatal_form()` will raise `FormInvalid()`", "] = acme_account_provider_id self.private_key_cycle_id = getcreate_args[ \"private_key_cycle_id\" ] = private_key_cycle_id", "if not; ``None`` for conditional logic \"\"\" formStash = self.formStash", "privateKeySelection # `formStash.fatal_form()` will raise `FormInvalid()` formStash.fatal_form(\"There was an error", "conditional logic \"\"\" account_key_pem = None account_key_pem_md5 = None dbAcmeAccount", "\"existing\" account_key_pem_md5 = formStash.results[\"account_key_existing\"] elif account_key_option == \"account_key_reuse\": acmeAccountSelection.selection =", "= None # instance of AcmeAccountUploadParser or None AcmeAccount =", "`pyramid_formencode_classic`) \"\"\" # overwritten in __init__ getcreate_args = None formStash", "= dbAcmeAccount privateKeySelection = parse_PrivateKeySelection( request, formStash, private_key_option=formStash.results[\"private_key_option\"], ) if", "\"global_default\" account_key_pem_md5 = formStash.results[\"account_key_global_default\"] is_global_default = True elif account_key_option ==", "dbAcmeAccount = None is_global_default = None # handle the explicit-option", "`FormFieldInvalid(FormInvalid)` formStash.fatal_field(field=\"domain_name\", message=\"Found no domain names\") if len(domain_names) != 1:", "required; ``False`` if not; ``None`` for conditional logic \"\"\" formStash", "any of %s is provided, all must be provided.\" %", "will raise a `ValueError(\"invalid domain\")` on the first invalid domain", "challenge type\", ) # 4: maybe we only want http01", "account_key_option: :param allow_none: :param require_contact: ``True`` if required; ``False`` if", "): dbPrivateKey = lib_db.get.get__PrivateKey__by_id(request.api_context, 0) if not dbPrivateKey: formStash.fatal_field( field=private_key_option,", "private_key_technology is not None: private_key_technology_id = model_utils.KeyTechnology.from_string( private_key_technology ) if", "None: # `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=\"acme_account_provider_id\", message=\"No provider", "\"acme_account_provider_id\", None ) if acme_account_provider_id is None: # `formStash.fatal_field()` will", "exiting AcmeAccount+AcmeAccountKey :param require_contact: ``True`` if required; ``False`` if not;", "= {} self.contact = getcreate_args[\"contact\"] = contact self.private_key_cycle_id = getcreate_args[", "_AcmeAccountSelection() if account_key_option == \"account_key_file\": # this will handle form", "= [] passes = [] for idx, option_set in enumerate(requirements_either_or):", "type\", ) # 4: maybe we only want http01 domains", "field=\"Error_Main\", message=\"invalid domain names detected\" ) return domains_challenged def form_single_domain_challenge_typed(request,", "acme_account_provider_id self.private_key_cycle_id = getcreate_args[ \"private_key_cycle_id\" ] = private_key_cycle_id self.private_key_technology_id =", "is no overlap domain_names_all_set = set(domain_names_all) if len(domain_names_all) != len(domain_names_all_set):", "provide a value\" ) dbPrivateKey = lib_db.get.get__PrivateKey__by_pemMd5( request.api_context, private_key_pem_md5, is_active=True", "private_key_pem = None private_key_pem_md5 = None PrivateKey = None #", "`pyramid_formencode_classic.FormStash` :param account_key_option: :param allow_none: :param require_contact: ``True`` if required;", "self.getcreate_args = decode_args(getcreate_args) class _PrivateKeyUploadParser(object): \"\"\" A PrivateKey is not", "\"account_key_file_le_pkey\", \"account_key_file_le_reg\", ), ) failures = [] passes = []", "PrivateKey = None # :class:`model.objects.PrivateKey` # handle the explicit-option privateKeySelection", "\"pem\" self.acme_account_provider_id = getcreate_args[ \"acme_account_provider_id\" ] = acme_account_provider_id self.account_key_pem =", "message=\"No PrivateKey cycle submitted.\", ) private_key_cycle_id = model_utils.PrivateKeyCycle.from_string( private_key_cycle )", "the provider option # will be None unless a pem", "current default.\", ) acmeAccountSelection.AcmeAccount = dbAcmeAccount return acmeAccountSelection # `formStash.fatal_form()`", "support for Python2/3 \"\"\" if six.PY3: for (k, v) in", "PEM file if formStash.results[\"account_key_file_pem\"] is not None: require_contact = True", "will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=private_key_option, message=\"You did not provide a", "option_set_item in option_set ] # if we have any item,", "] = private_key_technology_id self.getcreate_args = decode_args(getcreate_args) def require_upload(self, require_contact=None, require_technology=None):", ") return domains_challenged def form_single_domain_challenge_typed(request, formStash, challenge_type=\"http-01\"): domains_challenged = model_utils.DomainsChallenged()", "domain_names = utils.domains_from_string(formStash.results[\"domain_name\"]) if not domain_names: # `formStash.fatal_field()` will raise", "account_key_pem = None le_meta_jsons = None le_pkey_jsons = None le_reg_jsons", "is_global_default and not dbAcmeAccount.is_global_default: # `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field(", "overlap domain_names_all_set = set(domain_names_all) if len(domain_names_all) != len(domain_names_all_set): # `formStash.fatal_field()`", "will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=private_key_option, message=\"The selected PrivateKey is not", "model_utils.PrivateKeySelection_2_PrivateKeyStrategy[\"existing\"] ) private_key_pem_md5 = formStash.results[\"private_key_existing\"] elif private_key_option == \"private_key_reuse\": privateKeySelection.selection", "will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=\"Error_Main\", message=\"a domain name can only", "not provide a value\" ) dbAcmeAccount = lib_db.get.get__AcmeAccount__by_pemMd5( request.api_context, account_key_pem_md5,", "v) in domains_challenged.items(): if k == \"http-01\": continue if v:", "not account_key_pem_md5: # `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=account_key_option, message=\"You", "parser return acmeAccountSelection else: if account_key_option == \"account_key_global_default\": acmeAccountSelection.selection =", ") return privateKeySelection else: if private_key_option == \"private_key_existing\": privateKeySelection.selection =", "the lowercase \"none\"; this is an explicit \"no item\" selection", "len(domain_names_all) != len(domain_names_all_set): # `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=\"Error_Main\",", "self.private_key_pem = getcreate_args[ \"key_pem\" ] = formhandling.slurp_file_field(formStash, \"private_key_file_pem\") self.getcreate_args =", "= model_utils.PrivateKeyCycle.from_string( private_key_cycle ) private_key_technology_id = None private_key_technology = formStash.results.get(", "= private_key_cycle_id self.private_key_technology_id = getcreate_args[ \"private_key_technology_id\" ] = private_key_technology_id self.getcreate_args", "= None formStash = None # tracked acme_account_provider_id = None", "= formStash.results.get( \"acme_account_provider_id\", None ) private_key_cycle = formStash.results.get(\"account__private_key_cycle\", None) if", ") if acme_account_provider_id is None: # `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)`", "= {} def require_new(self, require_contact=None, require_technology=True): \"\"\" routine for creating", "return privateKeySelection # `formStash.fatal_form()` will raise `FormInvalid()` formStash.fatal_form(\"There was an", "this acmeAccountSelection.selection = \"none\" account_key_pem_md5 = None return acmeAccountSelection else:", "# only certain routes allow this acmeAccountSelection.selection = \"none\" account_key_pem_md5", "= ( model_utils.PrivateKeySelection_2_PrivateKeyStrategy[\"generate\"] ) elif private_key_option == \"private_key_for_account_key\": privateKeySelection.selection =", "if acmeAccountSelection.selection == \"upload\": key_create_args = acmeAccountSelection.upload_parsed.getcreate_args key_create_args[\"event_type\"] = \"AcmeAccount__insert\"", "if submitted_: domain_names_all.extend(submitted_) domains_challenged[target_] = submitted_ # 2: ensure there", "routine for uploading an exiting PrivateKey \"\"\" formStash = self.formStash", "ValueError as exc: # `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=\"Error_Main\",", "\"\"\" A PrivateKey is not a complex upload to parse", "acmeAccountSelection.upload_parsed.getcreate_args key_create_args[\"event_type\"] = \"AcmeAccount__insert\" key_create_args[ \"acme_account_key_source_id\" ] = model_utils.AcmeAccountKeySource.from_string(\"imported\") (dbAcmeAccount,", "if private_key_option == \"private_key_file\": # this will handle form validation", "not dbPrivateKey: formStash.fatal_field( field=\"private_key_option\", message=\"Could not load the placeholder PrivateKey", "This parser operates on a validated FormEncode results object (via", "not allow_none: # `formStash.fatal_form()` will raise `FormInvalid()` formStash.fatal_form( \"This form", "if private_key_option == \"private_key_generate\": privateKeySelection.selection = \"generate\" privateKeySelection.private_key_strategy__requested = (", "self.private_key_technology_id = getcreate_args[ \"private_key_technology_id\" ] = private_key_technology_id if formStash.results[\"account_key_file_pem\"] is", "for `model_utils.DomainsChallenged` to a formStash DOMAINS_CHALLENGED_FIELDS = { \"http-01\": \"domain_names_http01\",", "account_key_pem_md5, is_active=True ) if not dbAcmeAccount: # `formStash.fatal_field()` will raise", "formStash.fatal_field( field=account_key_option, message=\"The selected AcmeAccount is not the current default.\",", "formStash, require_contact=None): \"\"\" :param formStash: an instance of `pyramid_formencode_classic.FormStash` :param", "raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=\"account__private_key_cycle\", message=\"No PrivateKey cycle submitted.\", ) private_key_cycle_id", "`formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=\"acme_account_provider_id\", message=\"No provider submitted.\" )", "`FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=\"domain_name\", message=\"This endpoint currently supports only 1 domain", "\"private_key_generate\", \"private_key_for_account_key\", ): dbPrivateKey = lib_db.get.get__PrivateKey__by_id(request.api_context, 0) if not dbPrivateKey:", "raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=\"account__contact\", message=\"`account__contact` is required.\", ) getcreate_args =", "None private_key_cycle_id = None private_key_technology_id = None upload_type = None", "\"le_pkey_jsons\" ] = formhandling.slurp_file_field(formStash, \"account_key_file_le_pkey\") self.le_reg_jsons = getcreate_args[ \"le_reg_jsons\" ]", "...lib import db as lib_db from ...lib import utils from", "\"account_key_file_le_pkey\") self.le_reg_jsons = getcreate_args[ \"le_reg_jsons\" ] = formhandling.slurp_file_field(formStash, \"account_key_file_le_reg\") self.getcreate_args", "decode_args(getcreate_args): \"\"\" support for Python2/3 \"\"\" if six.PY3: for (k,", ") else: passes.append(idx) if (len(passes) != 1) or failures: #", "\"\"\" Class used to manage an uploaded AcmeAccount \"\"\" selection", "\"\"\" acmeAccountSelection = parse_AcmeAccountSelection( request, formStash, account_key_option=formStash.results[\"account_key_option\"], require_contact=require_contact, ) if", "no AcmeAccount selection.\" ) # note the lowercase \"none\"; this", "request, formStash, account_key_option=formStash.results[\"account_key_option\"], require_contact=require_contact, ) if acmeAccountSelection.selection == \"upload\": key_create_args", "update our object privateKeySelection.selection = \"upload\" privateKeySelection.upload_parsed = parser privateKeySelection.private_key_strategy__requested", "http-01 domains are accepted by this form\", ) except ValueError", "Certbot installation This parser operates on a validated FormEncode results", "supports only 1 domain name\", ) domains_challenged[challenge_type] = domain_names return", "in the system.\", ) privateKeySelection.PrivateKey = dbPrivateKey return privateKeySelection #", "the system.\", ) privateKeySelection.PrivateKey = dbPrivateKey return privateKeySelection # `formStash.fatal_form()`", "if k == \"http-01\": continue if v: # `formStash.fatal_field()` will", "getcreate_args[\"contact\"] = contact self.acme_account_provider_id = getcreate_args[ \"acme_account_provider_id\" ] = acme_account_provider_id", "a quick parse... requirements_either_or = ( ( \"account_key_file_pem\", # \"acme_account_provider_id\",", "code exists to mimic the AcmeAccount uploading. \"\"\" # overwritten", "= set(domain_names_all) if len(domain_names_all) != len(domain_names_all_set): # `formStash.fatal_field()` will raise", "== \"upload\": key_create_args = acmeAccountSelection.upload_parsed.getcreate_args key_create_args[\"event_type\"] = \"AcmeAccount__insert\" key_create_args[ \"acme_account_key_source_id\"", "will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=\"account__private_key_technology\", message=\"No PrivateKey technology submitted.\", )", ":class:`model.objects.PrivateKey` # handle the explicit-option privateKeySelection = _PrivateKeySelection() if private_key_option", "all(option_set_results): failures.append( \"If any of %s is provided, all must", "submitted\", ) # 3: ensure there is no overlap domain_names_all_set", "from . import formhandling # ============================================================================== def decode_args(getcreate_args): \"\"\" support", "`pyramid_formencode_classic.FormStash` :param require_contact: ``True`` if required; ``False`` if not; ``None``", "account_key_pem_md5 = formStash.results[\"account_key_global_default\"] is_global_default = True elif account_key_option == \"account_key_existing\":", "\"existing\" privateKeySelection.private_key_strategy__requested = ( model_utils.PrivateKeySelection_2_PrivateKeyStrategy[\"existing\"] ) private_key_pem_md5 = formStash.results[\"private_key_existing\"] elif", "private_key_option == \"private_key_existing\": privateKeySelection.selection = \"existing\" privateKeySelection.private_key_strategy__requested = ( model_utils.PrivateKeySelection_2_PrivateKeyStrategy[\"existing\"]", "\"\"\" selection = None upload_parsed = None # instance of", "= formStash.results[\"account_key_existing\"] elif account_key_option == \"account_key_reuse\": acmeAccountSelection.selection = \"reuse\" account_key_pem_md5", "`FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=\"acme_account_provider_id\", message=\"No provider submitted.\" ) private_key_cycle = formStash.results.get(\"account__private_key_cycle\",", "0) if not dbPrivateKey: formStash.fatal_field( field=\"private_key_option\", message=\"Could not load the", ") private_key_cycle_id = model_utils.PrivateKeyCycle.from_string( private_key_cycle ) private_key_technology_id = None private_key_technology", "= AcmeAccountUploadParser(formStash) # this will have: `contact`, `private_key_cycle`, `private_key_technology` parser.require_upload(require_contact=require_contact)", "# update our object privateKeySelection.selection = \"upload\" privateKeySelection.upload_parsed = parser", "Python2/3 \"\"\" if six.PY3: for (k, v) in list(getcreate_args.items()): if", "def private_key_strategy_id__requested(self): return model_utils.PrivateKeyStrategy.from_string( self.private_key_strategy__requested ) def parse_AcmeAccountSelection( request, formStash,", "lib_db.get.get__PrivateKey__by_pemMd5( request.api_context, private_key_pem_md5, is_active=True ) if not dbPrivateKey: # `formStash.fatal_field()`", "DOMAINS_CHALLENGED_FIELDS = { \"http-01\": \"domain_names_http01\", \"dns-01\": \"domain_names_dns01\", } class AcmeAccountUploadParser(object):", "(`account_key_file_le_meta`, `account_key_file_le_pkey`, `account_key_file_le_reg`).\" ) # ------------------- # validate the provider", "PrivateKey.\", ) privateKeySelection.PrivateKey = dbPrivateKey if private_key_option == \"private_key_generate\": privateKeySelection.selection", "set(domain_names_all) if len(domain_names_all) != len(domain_names_all_set): # `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)`", "model_utils.PrivateKeySelection_2_PrivateKeyStrategy[\"generate\"] ) elif private_key_option == \"private_key_for_account_key\": privateKeySelection.selection = \"private_key_for_account_key\" privateKeySelection.private_key_strategy__requested", "None is_global_default = None # handle the explicit-option acmeAccountSelection =", "formStash.fatal_field( field=\"private_key_option\", message=\"Could not load the placeholder PrivateKey for autogeneration.\",", "if formStash.results[\"account_key_file_pem\"] is not None: require_contact = True contact =", "# update our object acmeAccountSelection.selection = \"upload\" acmeAccountSelection.upload_parsed = parser", "parser = AcmeAccountUploadParser(formStash) # this will have: `contact`, `private_key_cycle`, `private_key_technology`", "allow this acmeAccountSelection.selection = \"none\" account_key_pem_md5 = None return acmeAccountSelection", "in the system.\", ) if is_global_default and not dbAcmeAccount.is_global_default: #", "...lib import utils from ...model import objects as model_objects from", "formStash.results.get( \"account__private_key_technology\", None ) if private_key_technology is not None: private_key_technology_id", "acme_account_provider_id = None account_key_pem = None le_meta_jsons = None le_pkey_jsons", "= formStash.results.get(\"account__contact\", None) if not contact and require_contact: # `formStash.fatal_field()`", "return acmeAccountSelection else: formStash.fatal_form( message=\"Invalid `account_key_option`\", ) if not account_key_pem_md5:", "if required; ``False`` if not; ``None`` for conditional logic \"\"\"", "`contact` when uploading a PEM file if formStash.results[\"account_key_file_pem\"] is not", "validating your form.\") def form_key_selection(request, formStash, require_contact=None): \"\"\" :param formStash:", "will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=\"Error_Main\", message=\"no domain names submitted\", )", "= None private_key_technology = formStash.results.get( \"account__private_key_technology\", None ) if private_key_technology:", "regex # it will raise a `ValueError(\"invalid domain\")` on the", "model_utils.DomainsChallenged() # this function checks the domain names match a", ") dbPrivateKey = lib_db.get.get__PrivateKey__by_pemMd5( request.api_context, private_key_pem_md5, is_active=True ) if not", "= submitted_ # 2: ensure there are domains if not", "= acme_account_provider_id self.private_key_cycle_id = getcreate_args[ \"private_key_cycle_id\" ] = private_key_cycle_id self.private_key_technology_id", "`formStash.fatal_form()` will raise `FormInvalid()` formStash.fatal_form( \"You must upload `account_key_file_pem` or", "1: iterate over the submitted domains by segment for (target_,", "if not domain_names: # `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field(field=\"domain_name\", message=\"Found", "= getcreate_args[ \"private_key_technology_id\" ] = private_key_technology_id self.getcreate_args = decode_args(getcreate_args) def", "None AcmeAccount = None class _PrivateKeySelection(object): selection = None upload_parsed", "if six.PY3: for (k, v) in list(getcreate_args.items()): if isinstance(v, bytes):", "privateKeySelection.private_key_strategy__requested = ( model_utils.PrivateKeySelection_2_PrivateKeyStrategy[\"generate\"] ) elif private_key_option == \"private_key_for_account_key\": privateKeySelection.selection", "`FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=\"Error_Main\", message=\"invalid domain names detected\" ) return domains_challenged", "= model_utils.DomainsChallenged() domain_names_all = [] try: # 1: iterate over", "technology submitted.\", ) # require `contact` when uploading a PEM", "= lib_db.getcreate.getcreate__PrivateKey__by_pem_text( request.api_context, **key_create_args ) privateKeySelection.PrivateKey = dbPrivateKey elif privateKeySelection.selection", "message=\"Could not load the placeholder PrivateKey.\", ) privateKeySelection.PrivateKey = dbPrivateKey", "formStash.results[\"private_key_file_pem\"] is not None: self.upload_type = \"pem\" self.private_key_pem = getcreate_args[", "# `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=\"Error_Main\", message=\"a domain name", "= {} def require_upload(self): \"\"\" routine for uploading an exiting", "domain names submitted\", ) # 3: ensure there is no", "logic \"\"\" account_key_pem = None account_key_pem_md5 = None dbAcmeAccount =", "for uploading an exiting AcmeAccount+AcmeAccountKey :param require_contact: ``True`` if required;", "len(domain_names) != 1: # `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=\"domain_name\",", "objects as model_objects from ...model import utils as model_utils from", ") if private_key_technology is not None: private_key_technology_id = model_utils.KeyTechnology.from_string( private_key_technology", "formStash, challenge_type=\"http-01\"): domains_challenged = model_utils.DomainsChallenged() # this function checks the", "`formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=\"account__contact\", message=\"`account__contact` is required.\", )", "is not None else False for option_set_item in option_set ]", "elif account_key_option == \"account_key_existing\": acmeAccountSelection.selection = \"existing\" account_key_pem_md5 = formStash.results[\"account_key_existing\"]", "if account_key_option == \"account_key_global_default\": acmeAccountSelection.selection = \"global_default\" account_key_pem_md5 = formStash.results[\"account_key_global_default\"]", "in ( \"private_key_generate\", \"private_key_for_account_key\", ): dbPrivateKey = lib_db.get.get__PrivateKey__by_id(request.api_context, 0) if", "\"le_reg_jsons\" ] = formhandling.slurp_file_field(formStash, \"account_key_file_le_reg\") self.getcreate_args = decode_args(getcreate_args) class _PrivateKeyUploadParser(object):", "formStash.results[\"private_key_reuse\"] elif private_key_option in ( \"private_key_generate\", \"private_key_for_account_key\", ): dbPrivateKey =", "of AcmeAccountUploadParser or None AcmeAccount = None class _PrivateKeySelection(object): selection", "`account_key_option`\", ) if not account_key_pem_md5: # `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)`", "instance of `pyramid_formencode_classic.FormStash` :param require_contact: ``True`` if required; ``False`` if", "cycle submitted.\", ) private_key_cycle_id = model_utils.PrivateKeyCycle.from_string( private_key_cycle ) private_key_technology_id =", "acmeAccountSelection.selection == \"upload\": key_create_args = acmeAccountSelection.upload_parsed.getcreate_args key_create_args[\"event_type\"] = \"AcmeAccount__insert\" key_create_args[", "in list(getcreate_args.items()): if isinstance(v, bytes): getcreate_args[k] = v.decode(\"utf8\") return getcreate_args", "function checks the domain names match a simple regex #", "and raise errors. parser = _PrivateKeyUploadParser(formStash) parser.require_upload() # update our", "message=\"No PrivateKey technology submitted.\", ) # require `contact` when uploading", "formStash.fatal_field( field=account_key_option, message=\"You did not provide a value\" ) dbAcmeAccount", "for (k, v) in domains_challenged.items(): if k == \"http-01\": continue", "PEM file * an intra-associated three file triplet from a", "will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=\"Error_Main\", message=\"only http-01 domains are accepted", "# `formStash.fatal_form()` will raise `FormInvalid()` formStash.fatal_form( \"You must upload `account_key_file_pem`", "validation and raise errors. parser = _PrivateKeyUploadParser(formStash) parser.require_upload() # update", "allow_none: # `formStash.fatal_form()` will raise `FormInvalid()` formStash.fatal_form( \"This form does", "is not None: self.upload_type = \"pem\" self.private_key_pem = getcreate_args[ \"key_pem\"", "account_key_option == \"account_key_file\": # this will handle form validation and", "does not support no AcmeAccount selection.\" ) # note the", "routine for uploading an exiting AcmeAccount+AcmeAccountKey :param require_contact: ``True`` if", "model_utils.AcmeAccountKeySource.from_string(\"imported\") (dbAcmeAccount, _is_created,) = lib_db.getcreate.getcreate__AcmeAccount( request.api_context, **key_create_args ) acmeAccountSelection.AcmeAccount =", "six # local from ...lib import db as lib_db from", "# if we have any item, we need all of", "= [] try: # 1: iterate over the submitted domains", "for autogeneration.\", ) privateKeySelection.PrivateKey = dbPrivateKey return (acmeAccountSelection, privateKeySelection) def", "# tracked acme_account_provider_id = None account_key_pem = None le_meta_jsons =", "errors. parser = AcmeAccountUploadParser(formStash) # this will have: `contact`, `private_key_cycle`,", "contact = formStash.results.get(\"account__contact\") if not contact and require_contact: # `formStash.fatal_field()`", "= None PrivateKey = None @property def private_key_strategy_id__requested(self): return model_utils.PrivateKeyStrategy.from_string(", "that we use `jsonS` to indicate a string self.le_meta_jsons =", "le_reg_jsons = None private_key_cycle_id = None private_key_technology_id = None upload_type", "`FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=account_key_option, message=\"The selected AcmeAccount is not enrolled in", "field=\"Error_Main\", message=\"only http-01 domains are accepted by this form\", )", "# 2: ensure there are domains if not domain_names_all: #", "# `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=\"account__private_key_cycle\", message=\"No PrivateKey cycle", "dbPrivateKey elif privateKeySelection.selection == \"generate\": dbPrivateKey = lib_db.get.get__PrivateKey__by_id(request.api_context, 0) if", "= formStash self.getcreate_args = {} def require_upload(self): \"\"\" routine for", "private_key_cycle = formStash.results.get(\"account__private_key_cycle\", None) if private_key_cycle is None: # `formStash.fatal_field()`", "key_create_args = privateKeySelection.upload_parsed.getcreate_args key_create_args[\"event_type\"] = \"PrivateKey__insert\" key_create_args[ \"private_key_source_id\" ] =", "over the submitted domains by segment for (target_, source_) in", "None upload_type = None # pem OR letsencrypt def __init__(self,", "\"none\"; this is an explicit \"no item\" selection # only", "parser operates on a validated FormEncode results object (via `pyramid_formencode_classic`)", "not None: private_key_technology_id = model_utils.KeyTechnology.from_string( private_key_technology ) if not private_key_technology_id", ") privateKeySelection.PrivateKey = dbPrivateKey return privateKeySelection # `formStash.fatal_form()` will raise", "not load the placeholder PrivateKey.\", ) privateKeySelection.PrivateKey = dbPrivateKey if", "= model_utils.PrivateKeySource.from_string(\"imported\") key_create_args[\"private_key_type_id\"] = model_utils.PrivateKeyType.from_string( \"standard\" ) ( dbPrivateKey, _is_created,", "(k, v) in domains_challenged.items(): if k == \"http-01\": continue if", "= dbAcmeAccount return acmeAccountSelection # `formStash.fatal_form()` will raise `FormInvalid()` formStash.fatal_form(\"There", "lib_db.get.get__PrivateKey__by_id(request.api_context, 0) if not dbPrivateKey: formStash.fatal_field( field=private_key_option, message=\"Could not load", "= formStash.results.get(\"account__private_key_cycle\", None) if private_key_cycle is None: # `formStash.fatal_field()` will", "\"private_key_technology_id\" ] = private_key_technology_id self.getcreate_args = decode_args(getcreate_args) def require_upload(self, require_contact=None,", "note that we use `jsonS` to indicate a string self.le_meta_jsons", "str(option_set) ) else: passes.append(idx) if (len(passes) != 1) or failures:", "# `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=\"account__private_key_technology\", message=\"No PrivateKey technology", "[ True if formStash.results[option_set_item] is not None else False for", "= formhandling.slurp_file_field(formStash, \"account_key_file_pem\") else: # note that we use `jsonS`", "the current default.\", ) acmeAccountSelection.AcmeAccount = dbAcmeAccount return acmeAccountSelection #", "decode_args(getcreate_args) def require_upload(self, require_contact=None, require_technology=None): \"\"\" routine for uploading an", "for PEM, ignored otherwise acme_account_provider_id = formStash.results.get( \"acme_account_provider_id\", None )", "# `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=private_key_option, message=\"You did not", "domain_names_all.extend(submitted_) domains_challenged[target_] = submitted_ # 2: ensure there are domains", "formStash: an instance of `pyramid_formencode_classic.FormStash` :param account_key_option: :param allow_none: :param", "[] for idx, option_set in enumerate(requirements_either_or): option_set_results = [ True", "0) if not dbPrivateKey: formStash.fatal_field( field=private_key_option, message=\"Could not load the", "model_utils.PrivateKeySource.from_string(\"imported\") key_create_args[\"private_key_type_id\"] = model_utils.PrivateKeyType.from_string( \"standard\" ) ( dbPrivateKey, _is_created, )", "( dbPrivateKey, _is_created, ) = lib_db.getcreate.getcreate__PrivateKey__by_pem_text( request.api_context, **key_create_args ) privateKeySelection.PrivateKey", "== \"upload\": key_create_args = privateKeySelection.upload_parsed.getcreate_args key_create_args[\"event_type\"] = \"PrivateKey__insert\" key_create_args[ \"private_key_source_id\"", "not None else False for option_set_item in option_set ] #", "= None @property def private_key_strategy_id__requested(self): return model_utils.PrivateKeyStrategy.from_string( self.private_key_strategy__requested ) def", "\"no item\" selection # only certain routes allow this acmeAccountSelection.selection", "raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=\"acme_account_provider_id\", message=\"No provider submitted.\" ) private_key_cycle =", "require_technology=None): \"\"\" routine for uploading an exiting AcmeAccount+AcmeAccountKey :param require_contact:", ":param require_technology: ``True`` if required; ``False`` if not; ``None`` for", "3: ensure there is no overlap domain_names_all_set = set(domain_names_all) if", "AcmeAccountUploadParser(object): \"\"\" An AcmeAccount may be uploaded multiple ways: *", "\"account_key_file_pem\", # \"acme_account_provider_id\", ), ( \"account_key_file_le_meta\", \"account_key_file_le_pkey\", \"account_key_file_le_reg\", ), )", "endpoint currently supports only 1 domain name\", ) domains_challenged[challenge_type] =", "= None # handle the explicit-option acmeAccountSelection = _AcmeAccountSelection() if", "results object (via `pyramid_formencode_classic`) \"\"\" # overwritten in __init__ getcreate_args", "acmeAccountSelection.selection = \"none\" account_key_pem_md5 = None return acmeAccountSelection else: formStash.fatal_form(", "system.\", ) privateKeySelection.PrivateKey = dbPrivateKey return privateKeySelection # `formStash.fatal_form()` will", "must be provided.\" % str(option_set) ) else: passes.append(idx) if (len(passes)", "\"private_key_for_account_key\": privateKeySelection.selection = \"private_key_for_account_key\" privateKeySelection.private_key_strategy__requested = ( model_utils.PrivateKeySelection_2_PrivateKeyStrategy[ \"private_key_for_account_key\" ]", "not private_key_technology_id and require_technology: # `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field(", "Class used to manage an uploaded AcmeAccount \"\"\" selection =", "account_key_pem_md5: # `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=account_key_option, message=\"You did", "= None dbAcmeAccount = None is_global_default = None # handle", "private_key_pem = None upload_type = None # pem def __init__(self,", "{} def require_new(self, require_contact=None, require_technology=True): \"\"\" routine for creating a", "= self.formStash getcreate_args = {} if formStash.results[\"private_key_file_pem\"] is not None:", "utils as model_utils from . import formhandling # ============================================================================== def", "field=\"Error_Main\", message=\"a domain name can only be associated to one", "NEW AcmeAccount (peter_sslers generates the credentials) :param require_contact: ``True`` if", "if len(domain_names) != 1: # `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field(", "private_key_cycle_id = None private_key_technology_id = None upload_type = None #", "\"\"\" :param formStash: an instance of `pyramid_formencode_classic.FormStash` :param account_key_option: :param", "elif private_key_option in ( \"private_key_generate\", \"private_key_for_account_key\", ): dbPrivateKey = lib_db.get.get__PrivateKey__by_id(request.api_context,", "= formStash.results[\"account_key_reuse\"] elif account_key_option == \"none\": if not allow_none: #", "formStash.fatal_form( \"You must upload `account_key_file_pem` or all of (`account_key_file_le_meta`, `account_key_file_le_pkey`,", "formStash.fatal_field( field=\"account__contact\", message=\"`account__contact` is required.\", ) getcreate_args = {} self.contact", "the domain names match a simple regex domain_names = utils.domains_from_string(formStash.results[\"domain_name\"])", "use `jsonS` to indicate a string self.le_meta_jsons = getcreate_args[ \"le_meta_jsons\"", "segment for (target_, source_) in DOMAINS_CHALLENGED_FIELDS.items(): submitted_ = formStash.results.get(source_) if", "lib_db.getcreate.getcreate__PrivateKey__by_pem_text( request.api_context, **key_create_args ) privateKeySelection.PrivateKey = dbPrivateKey elif privateKeySelection.selection ==", "function checks the domain names match a simple regex domain_names", "list(getcreate_args.items()): if isinstance(v, bytes): getcreate_args[k] = v.decode(\"utf8\") return getcreate_args #", "formStash.results[option_set_item] is not None else False for option_set_item in option_set", "`FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=\"acme_account_provider_id\", message=\"No provider submitted.\" ) self.upload_type = \"pem\"", "form.\") def form_key_selection(request, formStash, require_contact=None): \"\"\" :param formStash: an instance", "db as lib_db from ...lib import utils from ...model import", "# do a quick parse... requirements_either_or = ( ( \"account_key_file_pem\",", "private_key_cycle is None: # `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=\"account__private_key_cycle\",", "else: # note that we use `jsonS` to indicate a", "key_create_args = acmeAccountSelection.upload_parsed.getcreate_args key_create_args[\"event_type\"] = \"AcmeAccount__insert\" key_create_args[ \"acme_account_key_source_id\" ] =", "will raise `FormInvalid()` formStash.fatal_form( \"You must upload `account_key_file_pem` or all", "form.\") def parse_PrivateKeySelection(request, formStash, private_key_option=None): private_key_pem = None private_key_pem_md5 =", "exiting PrivateKey \"\"\" formStash = self.formStash getcreate_args = {} if", "can only be associated to one challenge type\", ) #", "a pem is uploaded # required for PEM, ignored otherwise", "did not provide a value\" ) dbPrivateKey = lib_db.get.get__PrivateKey__by_pemMd5( request.api_context,", "_PrivateKeyUploadParser(formStash) parser.require_upload() # update our object privateKeySelection.selection = \"upload\" privateKeySelection.upload_parsed", "if not private_key_pem_md5: # `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=private_key_option,", "match a simple regex # it will raise a `ValueError(\"invalid", "= formhandling.slurp_file_field(formStash, \"account_key_file_le_reg\") self.getcreate_args = decode_args(getcreate_args) class _PrivateKeyUploadParser(object): \"\"\" A", "key_create_args[\"event_type\"] = \"AcmeAccount__insert\" key_create_args[ \"acme_account_key_source_id\" ] = model_utils.AcmeAccountKeySource.from_string(\"imported\") (dbAcmeAccount, _is_created,)", "not None: if acme_account_provider_id is None: # `formStash.fatal_field()` will raise", "formStash.fatal_form(\"Invalid `private_key_option`\") if not private_key_pem_md5: # `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)`", "selection # only certain routes allow this acmeAccountSelection.selection = \"none\"", "(len(passes) != 1) or failures: # `formStash.fatal_form()` will raise `FormInvalid()`", "`FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=private_key_option, message=\"The selected PrivateKey is not enrolled in", "formStash = self.formStash acme_account_provider_id = formStash.results.get( \"acme_account_provider_id\", None ) if", "_PrivateKeySelection(object): selection = None upload_parsed = None # instance of", "`FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=\"account__contact\", message=\"`account__contact` is required.\", ) getcreate_args = {}", "] # if we have any item, we need all", "simple regex domain_names = utils.domains_from_string(formStash.results[\"domain_name\"]) if not domain_names: # `formStash.fatal_field()`", "this will handle form validation and raise errors. parser =", "object acmeAccountSelection.selection = \"upload\" acmeAccountSelection.upload_parsed = parser return acmeAccountSelection else:", "was an error validating your form.\") def parse_PrivateKeySelection(request, formStash, private_key_option=None):", "field=\"domain_name\", message=\"This endpoint currently supports only 1 domain name\", )", "formStash = self.formStash getcreate_args = {} if formStash.results[\"private_key_file_pem\"] is not", "or None private_key_strategy__requested = None PrivateKey = None @property def", "contact self.acme_account_provider_id = getcreate_args[ \"acme_account_provider_id\" ] = acme_account_provider_id self.private_key_cycle_id =", "# `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=private_key_option, message=\"The selected PrivateKey", "error validating your form.\") def form_key_selection(request, formStash, require_contact=None): \"\"\" :param", "if len(domain_names_all) != len(domain_names_all_set): # `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field(", "\"private_key_file\": # this will handle form validation and raise errors.", "must upload `account_key_file_pem` or all of (`account_key_file_le_meta`, `account_key_file_le_pkey`, `account_key_file_le_reg`).\" )", "# `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=\"Error_Main\", message=\"invalid domain names", "\"le_meta_jsons\" ] = formhandling.slurp_file_field(formStash, \"account_key_file_le_meta\") self.le_pkey_jsons = getcreate_args[ \"le_pkey_jsons\" ]", "class _PrivateKeySelection(object): selection = None upload_parsed = None # instance", "= \"AcmeAccount__insert\" key_create_args[ \"acme_account_key_source_id\" ] = model_utils.AcmeAccountKeySource.from_string(\"imported\") (dbAcmeAccount, _is_created,) =", "``True`` if required; ``False`` if not; ``None`` for conditional logic", "private_key_strategy__requested = None PrivateKey = None @property def private_key_strategy_id__requested(self): return", "= lib_db.get.get__PrivateKey__by_id(request.api_context, 0) if not dbPrivateKey: formStash.fatal_field( field=private_key_option, message=\"Could not", "**key_create_args ) acmeAccountSelection.AcmeAccount = dbAcmeAccount privateKeySelection = parse_PrivateKeySelection( request, formStash,", "`private_key_cycle`, `private_key_technology` parser.require_upload(require_contact=require_contact) # update our object acmeAccountSelection.selection = \"upload\"", "== \"private_key_file\": # this will handle form validation and raise", "= None class _PrivateKeySelection(object): selection = None upload_parsed = None", ") dbAcmeAccount = lib_db.get.get__AcmeAccount__by_pemMd5( request.api_context, account_key_pem_md5, is_active=True ) if not", "# `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field(field=\"domain_name\", message=\"Found no domain names\")", "upload_parsed = None # instance of AcmeAccountUploadParser or None AcmeAccount", "formStash.fatal_field(field=\"domain_name\", message=\"Found no domain names\") if len(domain_names) != 1: #", "== \"private_key_existing\": privateKeySelection.selection = \"existing\" privateKeySelection.private_key_strategy__requested = ( model_utils.PrivateKeySelection_2_PrivateKeyStrategy[\"existing\"] )", "request, formStash, private_key_option=formStash.results[\"private_key_option\"], ) if privateKeySelection.selection == \"upload\": key_create_args =", "the placeholder PrivateKey.\", ) privateKeySelection.PrivateKey = dbPrivateKey if private_key_option ==", "indicate a string self.le_meta_jsons = getcreate_args[ \"le_meta_jsons\" ] = formhandling.slurp_file_field(formStash,", "= None is_global_default = None # handle the explicit-option acmeAccountSelection", "if isinstance(v, bytes): getcreate_args[k] = v.decode(\"utf8\") return getcreate_args # standardized", "parser.require_upload(require_contact=require_contact) # update our object acmeAccountSelection.selection = \"upload\" acmeAccountSelection.upload_parsed =", ":param account_key_option: :param allow_none: :param require_contact: ``True`` if required; ``False``", ") # require `contact` when uploading a PEM file if", "lib_db from ...lib import utils from ...model import objects as", "raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=private_key_option, message=\"The selected PrivateKey is not enrolled", "\"reuse\" account_key_pem_md5 = formStash.results[\"account_key_reuse\"] elif account_key_option == \"none\": if not", "2: ensure there are domains if not domain_names_all: # `formStash.fatal_field()`", "(peter_sslers generates the credentials) :param require_contact: ``True`` if required; ``False``", "will have: `contact`, `private_key_cycle`, `private_key_technology` parser.require_upload(require_contact=require_contact) # update our object", "maybe we only want http01 domains submitted? if http01_only: for", "] = formhandling.slurp_file_field(formStash, \"account_key_file_le_reg\") self.getcreate_args = decode_args(getcreate_args) class _PrivateKeyUploadParser(object): \"\"\"", "field=\"acme_account_provider_id\", message=\"No provider submitted.\" ) private_key_cycle = formStash.results.get(\"account__private_key_cycle\", None) if", "\"upload\" acmeAccountSelection.upload_parsed = parser return acmeAccountSelection else: if account_key_option ==", "__init__ getcreate_args = None formStash = None # tracked acme_account_provider_id", "account_key_pem_md5 = None return acmeAccountSelection else: formStash.fatal_form( message=\"Invalid `account_key_option`\", )", "= \"existing\" privateKeySelection.private_key_strategy__requested = ( model_utils.PrivateKeySelection_2_PrivateKeyStrategy[\"existing\"] ) private_key_pem_md5 = formStash.results[\"private_key_existing\"]", "and raise errors. parser = AcmeAccountUploadParser(formStash) # this will have:", "names\") if len(domain_names) != 1: # `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)`", ") getcreate_args = {} self.contact = getcreate_args[\"contact\"] = contact self.acme_account_provider_id", "\"domain_names_dns01\", } class AcmeAccountUploadParser(object): \"\"\" An AcmeAccount may be uploaded", "def require_upload(self): \"\"\" routine for uploading an exiting PrivateKey \"\"\"", "privateKeySelection.PrivateKey = dbPrivateKey elif privateKeySelection.selection == \"generate\": dbPrivateKey = lib_db.get.get__PrivateKey__by_id(request.api_context,", "will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field(field=\"domain_name\", message=\"Found no domain names\") if len(domain_names)", "formStash.fatal_field( field=\"domain_name\", message=\"This endpoint currently supports only 1 domain name\",", "message=\"This endpoint currently supports only 1 domain name\", ) domains_challenged[challenge_type]", "not the current default.\", ) acmeAccountSelection.AcmeAccount = dbAcmeAccount return acmeAccountSelection", "= ( model_utils.PrivateKeySelection_2_PrivateKeyStrategy[\"existing\"] ) private_key_pem_md5 = formStash.results[\"private_key_existing\"] elif private_key_option ==", "submitted_: # this function checks the domain names match a", "domain_names: # `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field(field=\"domain_name\", message=\"Found no domain", "or None AcmeAccount = None class _PrivateKeySelection(object): selection = None", "_PrivateKeySelection() if private_key_option == \"private_key_file\": # this will handle form", "an intra-associated three file triplet from a Certbot installation This", "= getcreate_args[ \"acme_account_provider_id\" ] = acme_account_provider_id self.private_key_cycle_id = getcreate_args[ \"private_key_cycle_id\"", "formStash.fatal_field( field=\"Error_Main\", message=\"only http-01 domains are accepted by this form\",", "{} def require_upload(self): \"\"\" routine for uploading an exiting PrivateKey", "upload_parsed = None # instance of AcmeAccountUploadParser or None private_key_strategy__requested", "\"private_key_for_account_key\", ): dbPrivateKey = lib_db.get.get__PrivateKey__by_id(request.api_context, 0) if not dbPrivateKey: formStash.fatal_field(", ") contact = formStash.results.get(\"account__contact\", None) if not contact and require_contact:", "to parse itself This code exists to mimic the AcmeAccount", "domains_challenged def form_single_domain_challenge_typed(request, formStash, challenge_type=\"http-01\"): domains_challenged = model_utils.DomainsChallenged() # this", "raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field(field=\"domain_name\", message=\"Found no domain names\") if len(domain_names) !=", "PrivateKey technology submitted.\", ) contact = formStash.results.get(\"account__contact\", None) if not", "= None private_key_technology_id = None upload_type = None # pem", "for (k, v) in list(getcreate_args.items()): if isinstance(v, bytes): getcreate_args[k] =", "= formhandling.slurp_file_field(formStash, \"account_key_file_le_pkey\") self.le_reg_jsons = getcreate_args[ \"le_reg_jsons\" ] = formhandling.slurp_file_field(formStash,", "formStash.fatal_field( field=private_key_option, message=\"You did not provide a value\" ) dbPrivateKey", "will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=\"acme_account_provider_id\", message=\"No provider submitted.\" ) self.upload_type", "= None le_pkey_jsons = None le_reg_jsons = None private_key_cycle_id =", "private_key_technology_id self.getcreate_args = decode_args(getcreate_args) def require_upload(self, require_contact=None, require_technology=None): \"\"\" routine", "``None`` for conditional logic \"\"\" formStash = self.formStash # -------------------", "True contact = formStash.results.get(\"account__contact\") if not contact and require_contact: #", "self.formStash getcreate_args = {} if formStash.results[\"private_key_file_pem\"] is not None: self.upload_type", "def require_upload(self, require_contact=None, require_technology=None): \"\"\" routine for uploading an exiting", "= formStash.results.get(\"account__contact\") if not contact and require_contact: # `formStash.fatal_field()` will", "privateKeySelection.upload_parsed.getcreate_args key_create_args[\"event_type\"] = \"PrivateKey__insert\" key_create_args[ \"private_key_source_id\" ] = model_utils.PrivateKeySource.from_string(\"imported\") key_create_args[\"private_key_type_id\"]", "private_key_technology ) if not private_key_technology_id and require_technology: # `formStash.fatal_field()` will", "= None # instance of AcmeAccountUploadParser or None private_key_strategy__requested =", "= None upload_parsed = None # instance of AcmeAccountUploadParser or", "when uploading a PEM file if formStash.results[\"account_key_file_pem\"] is not None:", "= \"pem\" self.private_key_pem = getcreate_args[ \"key_pem\" ] = formhandling.slurp_file_field(formStash, \"private_key_file_pem\")", "a formStash DOMAINS_CHALLENGED_FIELDS = { \"http-01\": \"domain_names_http01\", \"dns-01\": \"domain_names_dns01\", }", "only certain routes allow this acmeAccountSelection.selection = \"none\" account_key_pem_md5 =", "uploading an exiting PrivateKey \"\"\" formStash = self.formStash getcreate_args =", "= None formStash = None # tracked private_key_pem = None", "`jsonS` to indicate a string self.le_meta_jsons = getcreate_args[ \"le_meta_jsons\" ]", "\"\"\" routine for uploading an exiting AcmeAccount+AcmeAccountKey :param require_contact: ``True``", "self.upload_type = \"pem\" self.private_key_pem = getcreate_args[ \"key_pem\" ] = formhandling.slurp_file_field(formStash,", "\"account_key_file\": # this will handle form validation and raise errors.", "] = formhandling.slurp_file_field(formStash, \"account_key_file_le_pkey\") self.le_reg_jsons = getcreate_args[ \"le_reg_jsons\" ] =", "`formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=\"account__private_key_cycle\", message=\"No PrivateKey cycle submitted.\",", "AcmeAccountUploadParser or None AcmeAccount = None class _PrivateKeySelection(object): selection =", "system.\", ) if is_global_default and not dbAcmeAccount.is_global_default: # `formStash.fatal_field()` will", "`formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=account_key_option, message=\"The selected AcmeAccount is", "domains_challenged[target_] = submitted_ # 2: ensure there are domains if", ") private_key_pem_md5 = formStash.results[\"private_key_existing\"] elif private_key_option == \"private_key_reuse\": privateKeySelection.selection =", "getcreate_args = {} self.contact = getcreate_args[\"contact\"] = contact self.private_key_cycle_id =", "= \"private_key_for_account_key\" privateKeySelection.private_key_strategy__requested = ( model_utils.PrivateKeySelection_2_PrivateKeyStrategy[ \"private_key_for_account_key\" ] ) return", "`FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=\"account__private_key_technology\", message=\"No PrivateKey technology submitted.\", ) contact =", "used to manage an uploaded AcmeAccount \"\"\" selection = None", "dbAcmeAccount = lib_db.get.get__AcmeAccount__by_pemMd5( request.api_context, account_key_pem_md5, is_active=True ) if not dbAcmeAccount:", "load the placeholder PrivateKey.\", ) privateKeySelection.PrivateKey = dbPrivateKey if private_key_option", "privateKeySelection.selection == \"upload\": key_create_args = privateKeySelection.upload_parsed.getcreate_args key_create_args[\"event_type\"] = \"PrivateKey__insert\" key_create_args[", "formStash.fatal_form(\"There was an error validating your form.\") def parse_PrivateKeySelection(request, formStash,", "dbPrivateKey: formStash.fatal_field( field=private_key_option, message=\"Could not load the placeholder PrivateKey.\", )", "dbPrivateKey: # `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=private_key_option, message=\"The selected", "\"private_key_source_id\" ] = model_utils.PrivateKeySource.from_string(\"imported\") key_create_args[\"private_key_type_id\"] = model_utils.PrivateKeyType.from_string( \"standard\" ) (", "elif privateKeySelection.selection == \"generate\": dbPrivateKey = lib_db.get.get__PrivateKey__by_id(request.api_context, 0) if not", "the credentials) :param require_contact: ``True`` if required; ``False`` if not;", "= [ True if formStash.results[option_set_item] is not None else False", "of them if any(option_set_results): if not all(option_set_results): failures.append( \"If any", ") if private_key_technology: private_key_technology_id = model_utils.KeyTechnology.from_string( private_key_technology ) if not", "conditional logic \"\"\" acmeAccountSelection = parse_AcmeAccountSelection( request, formStash, account_key_option=formStash.results[\"account_key_option\"], require_contact=require_contact,", "support no AcmeAccount selection.\" ) # note the lowercase \"none\";", "an instance of `pyramid_formencode_classic.FormStash` :param require_contact: ``True`` if required; ``False``", "formStash.results[\"account_key_file_pem\"] is not None: if acme_account_provider_id is None: # `formStash.fatal_field()`", "This code exists to mimic the AcmeAccount uploading. \"\"\" #", "for conditional logic \"\"\" formStash = self.formStash # ------------------- #", "} class AcmeAccountUploadParser(object): \"\"\" An AcmeAccount may be uploaded multiple", "PrivateKey for autogeneration.\", ) privateKeySelection.PrivateKey = dbPrivateKey return (acmeAccountSelection, privateKeySelection)", ") self.upload_type = \"pem\" self.acme_account_provider_id = getcreate_args[ \"acme_account_provider_id\" ] =", "provider submitted.\" ) private_key_cycle = formStash.results.get(\"account__private_key_cycle\", None) if private_key_cycle is", "in enumerate(requirements_either_or): option_set_results = [ True if formStash.results[option_set_item] is not", "self.account_key_pem = getcreate_args[ \"key_pem\" ] = formhandling.slurp_file_field(formStash, \"account_key_file_pem\") else: #", "value\" ) dbAcmeAccount = lib_db.get.get__AcmeAccount__by_pemMd5( request.api_context, account_key_pem_md5, is_active=True ) if", "] = private_key_technology_id if formStash.results[\"account_key_file_pem\"] is not None: if acme_account_provider_id", "if not dbAcmeAccount: # `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=account_key_option,", "``None`` for conditional logic \"\"\" formStash = self.formStash acme_account_provider_id =", "validation and raise errors. parser = AcmeAccountUploadParser(formStash) # this will", "# `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=\"Error_Main\", message=\"no domain names", "= None return acmeAccountSelection else: formStash.fatal_form( message=\"Invalid `account_key_option`\", ) if", "`FormInvalid()` formStash.fatal_form(\"There was an error validating your form.\") def parse_PrivateKeySelection(request,", "v) in list(getcreate_args.items()): if isinstance(v, bytes): getcreate_args[k] = v.decode(\"utf8\") return", "( model_utils.PrivateKeySelection_2_PrivateKeyStrategy[\"existing\"] ) private_key_pem_md5 = formStash.results[\"private_key_existing\"] elif private_key_option == \"private_key_reuse\":", "field=private_key_option, message=\"The selected PrivateKey is not enrolled in the system.\",", "\"\"\" routine for creating a NEW AcmeAccount (peter_sslers generates the", "pem OR letsencrypt def __init__(self, formStash): self.formStash = formStash self.getcreate_args", "require_contact: # `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=\"account__contact\", message=\"`account__contact` is", ") acmeAccountSelection.AcmeAccount = dbAcmeAccount privateKeySelection = parse_PrivateKeySelection( request, formStash, private_key_option=formStash.results[\"private_key_option\"],", "raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=account_key_option, message=\"The selected AcmeAccount is not the", "dbPrivateKey: formStash.fatal_field( field=\"private_key_option\", message=\"Could not load the placeholder PrivateKey for", "== \"http-01\": continue if v: # `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)`", "privateKeySelection.private_key_strategy__requested = ( model_utils.PrivateKeySelection_2_PrivateKeyStrategy[\"existing\"] ) private_key_pem_md5 = formStash.results[\"private_key_existing\"] elif private_key_option", "as model_objects from ...model import utils as model_utils from .", "\"\"\" support for Python2/3 \"\"\" if six.PY3: for (k, v)", "standardized mapping for `model_utils.DomainsChallenged` to a formStash DOMAINS_CHALLENGED_FIELDS = {", "# `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=account_key_option, message=\"You did not", "not support no AcmeAccount selection.\" ) # note the lowercase", "@property def private_key_strategy_id__requested(self): return model_utils.PrivateKeyStrategy.from_string( self.private_key_strategy__requested ) def parse_AcmeAccountSelection( request,", "explicit \"no item\" selection # only certain routes allow this", "( model_utils.PrivateKeySelection_2_PrivateKeyStrategy[ \"private_key_for_account_key\" ] ) return privateKeySelection else: # `formStash.fatal_form()`", "error validating your form.\") def parse_PrivateKeySelection(request, formStash, private_key_option=None): private_key_pem =", "\"account_key_existing\": acmeAccountSelection.selection = \"existing\" account_key_pem_md5 = formStash.results[\"account_key_existing\"] elif account_key_option ==", "( \"private_key_generate\", \"private_key_for_account_key\", ): dbPrivateKey = lib_db.get.get__PrivateKey__by_id(request.api_context, 0) if not", "to indicate a string self.le_meta_jsons = getcreate_args[ \"le_meta_jsons\" ] =", "parse... requirements_either_or = ( ( \"account_key_file_pem\", # \"acme_account_provider_id\", ), (", "complex upload to parse itself This code exists to mimic", "the system.\", ) if is_global_default and not dbAcmeAccount.is_global_default: # `formStash.fatal_field()`", "= decode_args(getcreate_args) def require_upload(self, require_contact=None, require_technology=None): \"\"\" routine for uploading", ") if not account_key_pem_md5: # `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field(", "\"\"\" formStash = self.formStash acme_account_provider_id = formStash.results.get( \"acme_account_provider_id\", None )", "logic \"\"\" acmeAccountSelection = parse_AcmeAccountSelection( request, formStash, account_key_option=formStash.results[\"account_key_option\"], require_contact=require_contact, )", "multiple ways: * a single PEM file * an intra-associated", "{} self.contact = getcreate_args[\"contact\"] = contact self.acme_account_provider_id = getcreate_args[ \"acme_account_provider_id\"", "model_utils.PrivateKeyCycle.from_string( private_key_cycle ) private_key_technology_id = None private_key_technology = formStash.results.get( \"account__private_key_technology\",", "raise errors. parser = AcmeAccountUploadParser(formStash) # this will have: `contact`,", "= parser privateKeySelection.private_key_strategy__requested = ( model_utils.PrivateKeySelection_2_PrivateKeyStrategy[\"upload\"] ) return privateKeySelection else:", "dbAcmeAccount return acmeAccountSelection # `formStash.fatal_form()` will raise `FormInvalid()` formStash.fatal_form(\"There was", ") privateKeySelection.PrivateKey = dbPrivateKey if private_key_option == \"private_key_generate\": privateKeySelection.selection =", "domains_challenged.items(): if k == \"http-01\": continue if v: # `formStash.fatal_field()`", "== \"private_key_generate\": privateKeySelection.selection = \"generate\" privateKeySelection.private_key_strategy__requested = ( model_utils.PrivateKeySelection_2_PrivateKeyStrategy[\"generate\"] )", "any item, we need all of them if any(option_set_results): if", "formStash.fatal_form( \"This form does not support no AcmeAccount selection.\" )", "None else False for option_set_item in option_set ] # if", "privateKeySelection = parse_PrivateKeySelection( request, formStash, private_key_option=formStash.results[\"private_key_option\"], ) if privateKeySelection.selection ==", "model_objects from ...model import utils as model_utils from . import", "conditional logic \"\"\" formStash = self.formStash # ------------------- # do", ") privateKeySelection.PrivateKey = dbPrivateKey elif privateKeySelection.selection == \"generate\": dbPrivateKey =", "submitted? if http01_only: for (k, v) in domains_challenged.items(): if k", "\"acme_account_provider_id\", ), ( \"account_key_file_le_meta\", \"account_key_file_le_pkey\", \"account_key_file_le_reg\", ), ) failures =", "three file triplet from a Certbot installation This parser operates", "AcmeAccount = None class _PrivateKeySelection(object): selection = None upload_parsed =", "privateKeySelection else: if private_key_option == \"private_key_existing\": privateKeySelection.selection = \"existing\" privateKeySelection.private_key_strategy__requested", "False for option_set_item in option_set ] # if we have", "if required; ``False`` if not; ``None`` for conditional logic :param", "\"\"\" if six.PY3: for (k, v) in list(getcreate_args.items()): if isinstance(v,", "if acme_account_provider_id is None: # `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field(", "required; ``False`` if not; ``None`` for conditional logic \"\"\" acmeAccountSelection", "\"account_key_reuse\": acmeAccountSelection.selection = \"reuse\" account_key_pem_md5 = formStash.results[\"account_key_reuse\"] elif account_key_option ==", "# 1: iterate over the submitted domains by segment for", "is not None: private_key_technology_id = model_utils.KeyTechnology.from_string( private_key_technology ) if not", "names match a simple regex # it will raise a", "**key_create_args ) privateKeySelection.PrivateKey = dbPrivateKey elif privateKeySelection.selection == \"generate\": dbPrivateKey", "checks the domain names match a simple regex # it", "default.\", ) acmeAccountSelection.AcmeAccount = dbAcmeAccount return acmeAccountSelection # `formStash.fatal_form()` will", ") # note the lowercase \"none\"; this is an explicit", "account_key_pem_md5 = None dbAcmeAccount = None is_global_default = None #", "`FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=\"Error_Main\", message=\"no domain names submitted\", ) # 3:", "request.api_context, **key_create_args ) privateKeySelection.PrivateKey = dbPrivateKey elif privateKeySelection.selection == \"generate\":", "submitted_ = utils.domains_from_string(submitted_) if submitted_: domain_names_all.extend(submitted_) domains_challenged[target_] = submitted_ #", "domain_names_all_set = set(domain_names_all) if len(domain_names_all) != len(domain_names_all_set): # `formStash.fatal_field()` will", ") if not dbAcmeAccount: # `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field(", ") if not dbPrivateKey: # `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field(", "of `pyramid_formencode_classic.FormStash` :param account_key_option: :param allow_none: :param require_contact: ``True`` if", "def form_key_selection(request, formStash, require_contact=None): \"\"\" :param formStash: an instance of", "A PrivateKey is not a complex upload to parse itself", "= getcreate_args[ \"le_reg_jsons\" ] = formhandling.slurp_file_field(formStash, \"account_key_file_le_reg\") self.getcreate_args = decode_args(getcreate_args)", "domains_challenged = model_utils.DomainsChallenged() domain_names_all = [] try: # 1: iterate", "\"upload\" privateKeySelection.upload_parsed = parser privateKeySelection.private_key_strategy__requested = ( model_utils.PrivateKeySelection_2_PrivateKeyStrategy[\"upload\"] ) return", "may be uploaded multiple ways: * a single PEM file", "\"standard\" ) ( dbPrivateKey, _is_created, ) = lib_db.getcreate.getcreate__PrivateKey__by_pem_text( request.api_context, **key_create_args", "elif private_key_option == \"private_key_for_account_key\": privateKeySelection.selection = \"private_key_for_account_key\" privateKeySelection.private_key_strategy__requested = (", "None) if private_key_cycle is None: # `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)`", "the AcmeAccount uploading. \"\"\" # overwritten in __init__ getcreate_args =", "``False`` if not; ``None`` for conditional logic \"\"\" account_key_pem =", "= getcreate_args[ \"le_meta_jsons\" ] = formhandling.slurp_file_field(formStash, \"account_key_file_le_meta\") self.le_pkey_jsons = getcreate_args[", "%s is provided, all must be provided.\" % str(option_set) )", "continue if v: # `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=\"Error_Main\",", "one challenge type\", ) # 4: maybe we only want", "private_key_option == \"private_key_file\": # this will handle form validation and", "triplet from a Certbot installation This parser operates on a", "will raise `FormInvalid()` formStash.fatal_form(\"There was an error validating your form.\")", "field=\"private_key_option\", message=\"Could not load the placeholder PrivateKey for autogeneration.\", )", "idx, option_set in enumerate(requirements_either_or): option_set_results = [ True if formStash.results[option_set_item]", "if http01_only: for (k, v) in domains_challenged.items(): if k ==", "a NEW AcmeAccount (peter_sslers generates the credentials) :param require_contact: ``True``", "] = model_utils.PrivateKeySource.from_string(\"imported\") key_create_args[\"private_key_type_id\"] = model_utils.PrivateKeyType.from_string( \"standard\" ) ( dbPrivateKey,", "formStash.results.get(\"account__contact\") if not contact and require_contact: # `formStash.fatal_field()` will raise", "= True elif account_key_option == \"account_key_existing\": acmeAccountSelection.selection = \"existing\" account_key_pem_md5", "all of them if any(option_set_results): if not all(option_set_results): failures.append( \"If", "local from ...lib import db as lib_db from ...lib import", "else False for option_set_item in option_set ] # if we", "formhandling.slurp_file_field(formStash, \"account_key_file_pem\") else: # note that we use `jsonS` to", "self.private_key_cycle_id = getcreate_args[ \"private_key_cycle_id\" ] = private_key_cycle_id self.private_key_technology_id = getcreate_args[", "if we have any item, we need all of them", "\"key_pem\" ] = formhandling.slurp_file_field(formStash, \"private_key_file_pem\") self.getcreate_args = decode_args(getcreate_args) class _AcmeAccountSelection(object):", "required; ``False`` if not; ``None`` for conditional logic :param require_technology:", "def parse_AcmeAccountSelection( request, formStash, account_key_option=None, allow_none=None, require_contact=None, ): \"\"\" :param", "None # pem def __init__(self, formStash): self.formStash = formStash self.getcreate_args", "= None private_key_technology = formStash.results.get( \"account__private_key_technology\", None ) if private_key_technology", "= None account_key_pem_md5 = None dbAcmeAccount = None is_global_default =", "None) if not contact and require_contact: # `formStash.fatal_field()` will raise", "validated FormEncode results object (via `pyramid_formencode_classic`) \"\"\" # overwritten in", "private_key_cycle_id self.private_key_technology_id = getcreate_args[ \"private_key_technology_id\" ] = private_key_technology_id self.getcreate_args =", "``None`` for conditional logic \"\"\" acmeAccountSelection = parse_AcmeAccountSelection( request, formStash,", "_AcmeAccountSelection(object): \"\"\" Class used to manage an uploaded AcmeAccount \"\"\"", "__init__(self, formStash): self.formStash = formStash self.getcreate_args = {} def require_new(self,", "# `formStash.fatal_form()` will raise `FormInvalid()` formStash.fatal_form(\"Invalid `private_key_option`\") if not private_key_pem_md5:", "parse_AcmeAccountSelection( request, formStash, account_key_option=formStash.results[\"account_key_option\"], require_contact=require_contact, ) if acmeAccountSelection.selection == \"upload\":", "by segment for (target_, source_) in DOMAINS_CHALLENGED_FIELDS.items(): submitted_ = formStash.results.get(source_)", "this will have: `contact`, `private_key_cycle`, `private_key_technology` parser.require_upload(require_contact=require_contact) # update our", "None le_reg_jsons = None private_key_cycle_id = None private_key_technology_id = None", "for option_set_item in option_set ] # if we have any", "def form_domains_challenge_typed(request, formStash, http01_only=False): domains_challenged = model_utils.DomainsChallenged() domain_names_all = []", "failures = [] passes = [] for idx, option_set in", "None dbAcmeAccount = None is_global_default = None # handle the", "not dbAcmeAccount: # `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=account_key_option, message=\"The", "message=\"Found no domain names\") if len(domain_names) != 1: # `formStash.fatal_field()`", "http01_only: for (k, v) in domains_challenged.items(): if k == \"http-01\":", "`FormInvalid()` formStash.fatal_form( \"You must upload `account_key_file_pem` or all of (`account_key_file_le_meta`,", "exists to mimic the AcmeAccount uploading. \"\"\" # overwritten in", "only be associated to one challenge type\", ) # 4:", "regex domain_names = utils.domains_from_string(formStash.results[\"domain_name\"]) if not domain_names: # `formStash.fatal_field()` will", "a single PEM file * an intra-associated three file triplet", "raise errors. parser = _PrivateKeyUploadParser(formStash) parser.require_upload() # update our object", "technology submitted.\", ) contact = formStash.results.get(\"account__contact\", None) if not contact", "\"\"\" account_key_pem = None account_key_pem_md5 = None dbAcmeAccount = None", "\"account__private_key_technology\", None ) if private_key_technology is not None: private_key_technology_id =", "= None upload_type = None # pem def __init__(self, formStash):", "require_contact=None, require_technology=True): \"\"\" routine for creating a NEW AcmeAccount (peter_sslers", "acme_account_provider_id = formStash.results.get( \"acme_account_provider_id\", None ) if acme_account_provider_id is None:", "None: private_key_technology_id = model_utils.KeyTechnology.from_string( private_key_technology ) if not private_key_technology_id and", "1: # `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=\"domain_name\", message=\"This endpoint", "\"\"\" # overwritten in __init__ getcreate_args = None formStash =", "validating your form.\") def parse_PrivateKeySelection(request, formStash, private_key_option=None): private_key_pem = None", "simple regex # it will raise a `ValueError(\"invalid domain\")` on", "`formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=\"domain_name\", message=\"This endpoint currently supports", "acme_account_provider_id self.account_key_pem = getcreate_args[ \"key_pem\" ] = formhandling.slurp_file_field(formStash, \"account_key_file_pem\") else:", "formStash.results.get(source_) if submitted_: # this function checks the domain names", "formStash, account_key_option=None, allow_none=None, require_contact=None, ): \"\"\" :param formStash: an instance", "not dbPrivateKey: # `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=private_key_option, message=\"The", "AcmeAccountUploadParser or None private_key_strategy__requested = None PrivateKey = None @property", ":param allow_none: :param require_contact: ``True`` if required; ``False`` if not;", "is_active=True ) if not dbAcmeAccount: # `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)`", "`FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=\"account__private_key_cycle\", message=\"No PrivateKey cycle submitted.\", ) private_key_cycle_id =", "a `ValueError(\"invalid domain\")` on the first invalid domain submitted_ =", "# `formStash.fatal_form()` will raise `FormInvalid()` formStash.fatal_form(\"There was an error validating", "!= 1) or failures: # `formStash.fatal_form()` will raise `FormInvalid()` formStash.fatal_form(", "model_utils.PrivateKeySelection_2_PrivateKeyStrategy[ \"private_key_for_account_key\" ] ) return privateKeySelection else: # `formStash.fatal_form()` will", "# 3: ensure there is no overlap domain_names_all_set = set(domain_names_all)", "and require_technology: # `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=\"account__private_key_technology\", message=\"No", "private_key_pem_md5 = formStash.results[\"private_key_reuse\"] elif private_key_option in ( \"private_key_generate\", \"private_key_for_account_key\", ):", "{} if formStash.results[\"private_key_file_pem\"] is not None: self.upload_type = \"pem\" self.private_key_pem", "FormEncode results object (via `pyramid_formencode_classic`) \"\"\" # overwritten in __init__", "= {} if formStash.results[\"private_key_file_pem\"] is not None: self.upload_type = \"pem\"", "not; ``None`` for conditional logic \"\"\" formStash = self.formStash acme_account_provider_id", "DOMAINS_CHALLENGED_FIELDS.items(): submitted_ = formStash.results.get(source_) if submitted_: # this function checks", "of %s is provided, all must be provided.\" % str(option_set)", "\"private_key_file_pem\") self.getcreate_args = decode_args(getcreate_args) class _AcmeAccountSelection(object): \"\"\" Class used to", "from ...model import objects as model_objects from ...model import utils", "( model_utils.PrivateKeySelection_2_PrivateKeyStrategy[\"generate\"] ) elif private_key_option == \"private_key_for_account_key\": privateKeySelection.selection = \"private_key_for_account_key\"", "if formStash.results[option_set_item] is not None else False for option_set_item in", "if not private_key_technology_id and require_technology: # `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)`", "will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=account_key_option, message=\"You did not provide a", "formhandling # ============================================================================== def decode_args(getcreate_args): \"\"\" support for Python2/3 \"\"\"", "field=private_key_option, message=\"Could not load the placeholder PrivateKey.\", ) privateKeySelection.PrivateKey =", "\"private_key_existing\": privateKeySelection.selection = \"existing\" privateKeySelection.private_key_strategy__requested = ( model_utils.PrivateKeySelection_2_PrivateKeyStrategy[\"existing\"] ) private_key_pem_md5", "`contact`, `private_key_cycle`, `private_key_technology` parser.require_upload(require_contact=require_contact) # update our object acmeAccountSelection.selection =", ") elif private_key_option == \"private_key_for_account_key\": privateKeySelection.selection = \"private_key_for_account_key\" privateKeySelection.private_key_strategy__requested =", "domain names detected\" ) return domains_challenged def form_single_domain_challenge_typed(request, formStash, challenge_type=\"http-01\"):", "None account_key_pem = None le_meta_jsons = None le_pkey_jsons = None", "= None # pem def __init__(self, formStash): self.formStash = formStash", "invalid domain submitted_ = utils.domains_from_string(submitted_) if submitted_: domain_names_all.extend(submitted_) domains_challenged[target_] =", ") private_key_technology_id = None private_key_technology = formStash.results.get( \"account__private_key_technology\", None )", "acmeAccountSelection = _AcmeAccountSelection() if account_key_option == \"account_key_file\": # this will", "formStash: an instance of `pyramid_formencode_classic.FormStash` :param require_contact: ``True`` if required;", "# standardized mapping for `model_utils.DomainsChallenged` to a formStash DOMAINS_CHALLENGED_FIELDS =", "routes allow this acmeAccountSelection.selection = \"none\" account_key_pem_md5 = None return", "request, formStash, account_key_option=None, allow_none=None, require_contact=None, ): \"\"\" :param formStash: an", "= parser return acmeAccountSelection else: if account_key_option == \"account_key_global_default\": acmeAccountSelection.selection", "of `pyramid_formencode_classic.FormStash` :param require_contact: ``True`` if required; ``False`` if not;", "conditional logic \"\"\" formStash = self.formStash acme_account_provider_id = formStash.results.get( \"acme_account_provider_id\",", "== \"account_key_global_default\": acmeAccountSelection.selection = \"global_default\" account_key_pem_md5 = formStash.results[\"account_key_global_default\"] is_global_default =", "AcmeAccount selection.\" ) # note the lowercase \"none\"; this is", "file triplet from a Certbot installation This parser operates on", "uploaded # required for PEM, ignored otherwise acme_account_provider_id = formStash.results.get(", "\"http-01\": \"domain_names_http01\", \"dns-01\": \"domain_names_dns01\", } class AcmeAccountUploadParser(object): \"\"\" An AcmeAccount", "contact and require_contact: # `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=\"account__contact\",", "requirements_either_or = ( ( \"account_key_file_pem\", # \"acme_account_provider_id\", ), ( \"account_key_file_le_meta\",", "message=\"No PrivateKey technology submitted.\", ) contact = formStash.results.get(\"account__contact\", None) if", "lib_db.getcreate.getcreate__AcmeAccount( request.api_context, **key_create_args ) acmeAccountSelection.AcmeAccount = dbAcmeAccount privateKeySelection = parse_PrivateKeySelection(", "domains_challenged = model_utils.DomainsChallenged() # this function checks the domain names", "formStash.fatal_field( field=private_key_option, message=\"Could not load the placeholder PrivateKey.\", ) privateKeySelection.PrivateKey", "private_key_option == \"private_key_generate\": privateKeySelection.selection = \"generate\" privateKeySelection.private_key_strategy__requested = ( model_utils.PrivateKeySelection_2_PrivateKeyStrategy[\"generate\"]", "import db as lib_db from ...lib import utils from ...model", "= acmeAccountSelection.upload_parsed.getcreate_args key_create_args[\"event_type\"] = \"AcmeAccount__insert\" key_create_args[ \"acme_account_key_source_id\" ] = model_utils.AcmeAccountKeySource.from_string(\"imported\")", "raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=\"account__private_key_technology\", message=\"No PrivateKey technology submitted.\", ) contact", ". import formhandling # ============================================================================== def decode_args(getcreate_args): \"\"\" support for", "formStash): self.formStash = formStash self.getcreate_args = {} def require_upload(self): \"\"\"", "logic \"\"\" formStash = self.formStash acme_account_provider_id = formStash.results.get( \"acme_account_provider_id\", None", "acmeAccountSelection else: if account_key_option == \"account_key_global_default\": acmeAccountSelection.selection = \"global_default\" account_key_pem_md5", "AcmeAccount is not the current default.\", ) acmeAccountSelection.AcmeAccount = dbAcmeAccount", "None upload_type = None # pem def __init__(self, formStash): self.formStash", "= parse_AcmeAccountSelection( request, formStash, account_key_option=formStash.results[\"account_key_option\"], require_contact=require_contact, ) if acmeAccountSelection.selection ==", "private_key_pem_md5: # `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=private_key_option, message=\"You did", "`model_utils.DomainsChallenged` to a formStash DOMAINS_CHALLENGED_FIELDS = { \"http-01\": \"domain_names_http01\", \"dns-01\":", "manage an uploaded AcmeAccount \"\"\" selection = None upload_parsed =", "\"account_key_global_default\": acmeAccountSelection.selection = \"global_default\" account_key_pem_md5 = formStash.results[\"account_key_global_default\"] is_global_default = True", "__init__(self, formStash): self.formStash = formStash self.getcreate_args = {} def require_upload(self):", "formStash.results.get(\"account__private_key_cycle\", None) if private_key_cycle is None: # `formStash.fatal_field()` will raise", "PEM, ignored otherwise acme_account_provider_id = formStash.results.get( \"acme_account_provider_id\", None ) private_key_cycle", "if not; ``None`` for conditional logic \"\"\" acmeAccountSelection = parse_AcmeAccountSelection(", "\"key_pem\" ] = formhandling.slurp_file_field(formStash, \"account_key_file_pem\") else: # note that we", "getcreate_args # standardized mapping for `model_utils.DomainsChallenged` to a formStash DOMAINS_CHALLENGED_FIELDS", "parse_PrivateKeySelection(request, formStash, private_key_option=None): private_key_pem = None private_key_pem_md5 = None PrivateKey", "form_single_domain_challenge_typed(request, formStash, challenge_type=\"http-01\"): domains_challenged = model_utils.DomainsChallenged() # this function checks", "formStash.results[\"account_key_existing\"] elif account_key_option == \"account_key_reuse\": acmeAccountSelection.selection = \"reuse\" account_key_pem_md5 =", "self.acme_account_provider_id = getcreate_args[ \"acme_account_provider_id\" ] = acme_account_provider_id self.account_key_pem = getcreate_args[", "if not all(option_set_results): failures.append( \"If any of %s is provided,", "self.private_key_technology_id = getcreate_args[ \"private_key_technology_id\" ] = private_key_technology_id self.getcreate_args = decode_args(getcreate_args)", "acmeAccountSelection.selection = \"global_default\" account_key_pem_md5 = formStash.results[\"account_key_global_default\"] is_global_default = True elif", "= formStash.results[\"account_key_global_default\"] is_global_default = True elif account_key_option == \"account_key_existing\": acmeAccountSelection.selection", "certain routes allow this acmeAccountSelection.selection = \"none\" account_key_pem_md5 = None", "getcreate_args[ \"le_reg_jsons\" ] = formhandling.slurp_file_field(formStash, \"account_key_file_le_reg\") self.getcreate_args = decode_args(getcreate_args) class", "{} self.contact = getcreate_args[\"contact\"] = contact self.private_key_cycle_id = getcreate_args[ \"private_key_cycle_id\"", "be provided.\" % str(option_set) ) else: passes.append(idx) if (len(passes) !=", "= formhandling.slurp_file_field(formStash, \"account_key_file_le_meta\") self.le_pkey_jsons = getcreate_args[ \"le_pkey_jsons\" ] = formhandling.slurp_file_field(formStash,", "class _PrivateKeyUploadParser(object): \"\"\" A PrivateKey is not a complex upload", "AcmeAccount \"\"\" selection = None upload_parsed = None # instance", "else: # `formStash.fatal_form()` will raise `FormInvalid()` formStash.fatal_form(\"Invalid `private_key_option`\") if not", "`formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field(field=\"domain_name\", message=\"Found no domain names\") if", "message=\"You did not provide a value\" ) dbPrivateKey = lib_db.get.get__PrivateKey__by_pemMd5(", "message=\"only http-01 domains are accepted by this form\", ) except", "None account_key_pem_md5 = None dbAcmeAccount = None is_global_default = None", "None # pem OR letsencrypt def __init__(self, formStash): self.formStash =", "parse itself This code exists to mimic the AcmeAccount uploading.", "contact = formStash.results.get(\"account__contact\", None) if not contact and require_contact: #", "= lib_db.get.get__PrivateKey__by_pemMd5( request.api_context, private_key_pem_md5, is_active=True ) if not dbPrivateKey: #", "dbAcmeAccount privateKeySelection = parse_PrivateKeySelection( request, formStash, private_key_option=formStash.results[\"private_key_option\"], ) if privateKeySelection.selection", "enumerate(requirements_either_or): option_set_results = [ True if formStash.results[option_set_item] is not None", "self.getcreate_args = decode_args(getcreate_args) def require_upload(self, require_contact=None, require_technology=None): \"\"\" routine for", "None # handle the explicit-option acmeAccountSelection = _AcmeAccountSelection() if account_key_option", "= \"PrivateKey__insert\" key_create_args[ \"private_key_source_id\" ] = model_utils.PrivateKeySource.from_string(\"imported\") key_create_args[\"private_key_type_id\"] = model_utils.PrivateKeyType.from_string(", "else: if account_key_option == \"account_key_global_default\": acmeAccountSelection.selection = \"global_default\" account_key_pem_md5 =", "try: # 1: iterate over the submitted domains by segment", "form validation and raise errors. parser = _PrivateKeyUploadParser(formStash) parser.require_upload() #", "not load the placeholder PrivateKey for autogeneration.\", ) privateKeySelection.PrivateKey =", "PrivateKey = None @property def private_key_strategy_id__requested(self): return model_utils.PrivateKeyStrategy.from_string( self.private_key_strategy__requested )", "privateKeySelection) def form_domains_challenge_typed(request, formStash, http01_only=False): domains_challenged = model_utils.DomainsChallenged() domain_names_all =", "formStash.fatal_form(\"There was an error validating your form.\") def form_key_selection(request, formStash,", "= \"reuse\" account_key_pem_md5 = formStash.results[\"account_key_reuse\"] elif account_key_option == \"none\": if", "] = formhandling.slurp_file_field(formStash, \"account_key_file_le_meta\") self.le_pkey_jsons = getcreate_args[ \"le_pkey_jsons\" ] =", "self.le_reg_jsons = getcreate_args[ \"le_reg_jsons\" ] = formhandling.slurp_file_field(formStash, \"account_key_file_le_reg\") self.getcreate_args =", "submitted.\" ) private_key_cycle = formStash.results.get(\"account__private_key_cycle\", None) if private_key_cycle is None:", "dbPrivateKey = lib_db.get.get__PrivateKey__by_pemMd5( request.api_context, private_key_pem_md5, is_active=True ) if not dbPrivateKey:", "privateKeySelection.private_key_strategy__requested = ( model_utils.PrivateKeySelection_2_PrivateKeyStrategy[\"upload\"] ) return privateKeySelection else: if private_key_option", "= ( model_utils.PrivateKeySelection_2_PrivateKeyStrategy[\"reuse\"] ) private_key_pem_md5 = formStash.results[\"private_key_reuse\"] elif private_key_option in", "getcreate_args = None formStash = None # tracked acme_account_provider_id =", "not private_key_pem_md5: # `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=private_key_option, message=\"You", "acmeAccountSelection.selection = \"upload\" acmeAccountSelection.upload_parsed = parser return acmeAccountSelection else: if", "formStash DOMAINS_CHALLENGED_FIELDS = { \"http-01\": \"domain_names_http01\", \"dns-01\": \"domain_names_dns01\", } class", "on the first invalid domain submitted_ = utils.domains_from_string(submitted_) if submitted_:", "a value\" ) dbAcmeAccount = lib_db.get.get__AcmeAccount__by_pemMd5( request.api_context, account_key_pem_md5, is_active=True )", "as model_utils from . import formhandling # ============================================================================== def decode_args(getcreate_args):", ") # 4: maybe we only want http01 domains submitted?", "if formStash.results[\"account_key_file_pem\"] is not None: if acme_account_provider_id is None: #", "of (`account_key_file_le_meta`, `account_key_file_le_pkey`, `account_key_file_le_reg`).\" ) # ------------------- # validate the", "this form\", ) except ValueError as exc: # `formStash.fatal_field()` will", "utils.domains_from_string(submitted_) if submitted_: domain_names_all.extend(submitted_) domains_challenged[target_] = submitted_ # 2: ensure", "for conditional logic :param require_technology: ``True`` if required; ``False`` if", "\"account_key_file_le_reg\") self.getcreate_args = decode_args(getcreate_args) class _PrivateKeyUploadParser(object): \"\"\" A PrivateKey is", "require_contact=None): \"\"\" :param formStash: an instance of `pyramid_formencode_classic.FormStash` :param require_contact:", "itself This code exists to mimic the AcmeAccount uploading. \"\"\"", "dbPrivateKey = lib_db.get.get__PrivateKey__by_id(request.api_context, 0) if not dbPrivateKey: formStash.fatal_field( field=private_key_option, message=\"Could", "formStash.results[\"account_key_file_pem\"] is not None: require_contact = True contact = formStash.results.get(\"account__contact\")", "for creating a NEW AcmeAccount (peter_sslers generates the credentials) :param", "] = formhandling.slurp_file_field(formStash, \"account_key_file_pem\") else: # note that we use", "`account_key_file_le_reg`).\" ) # ------------------- # validate the provider option #", "account_key_option == \"none\": if not allow_none: # `formStash.fatal_form()` will raise", "be uploaded multiple ways: * a single PEM file *", "will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=\"acme_account_provider_id\", message=\"No provider submitted.\" ) private_key_cycle", "\"http-01\": continue if v: # `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field(", "k == \"http-01\": continue if v: # `formStash.fatal_field()` will raise", "= True contact = formStash.results.get(\"account__contact\") if not contact and require_contact:", "an explicit \"no item\" selection # only certain routes allow", "getcreate_args[ \"le_meta_jsons\" ] = formhandling.slurp_file_field(formStash, \"account_key_file_le_meta\") self.le_pkey_jsons = getcreate_args[ \"le_pkey_jsons\"", "_PrivateKeyUploadParser(object): \"\"\" A PrivateKey is not a complex upload to", "of AcmeAccountUploadParser or None private_key_strategy__requested = None PrivateKey = None", "an instance of `pyramid_formencode_classic.FormStash` :param account_key_option: :param allow_none: :param require_contact:", "= privateKeySelection.upload_parsed.getcreate_args key_create_args[\"event_type\"] = \"PrivateKey__insert\" key_create_args[ \"private_key_source_id\" ] = model_utils.PrivateKeySource.from_string(\"imported\")", "raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=\"Error_Main\", message=\"no domain names submitted\", ) #", "None private_key_pem_md5 = None PrivateKey = None # :class:`model.objects.PrivateKey` #", "# `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=\"acme_account_provider_id\", message=\"No provider submitted.\"", "= { \"http-01\": \"domain_names_http01\", \"dns-01\": \"domain_names_dns01\", } class AcmeAccountUploadParser(object): \"\"\"", "require `contact` when uploading a PEM file if formStash.results[\"account_key_file_pem\"] is", "model_utils.PrivateKeySelection_2_PrivateKeyStrategy[\"upload\"] ) return privateKeySelection else: if private_key_option == \"private_key_existing\": privateKeySelection.selection", "AcmeAccount (peter_sslers generates the credentials) :param require_contact: ``True`` if required;", "# `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=\"Error_Main\", message=\"only http-01 domains", "is_active=True ) if not dbPrivateKey: # `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)`", "utils.domains_from_string(formStash.results[\"domain_name\"]) if not domain_names: # `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field(field=\"domain_name\",", "update our object acmeAccountSelection.selection = \"upload\" acmeAccountSelection.upload_parsed = parser return", "form_key_selection(request, formStash, require_contact=None): \"\"\" :param formStash: an instance of `pyramid_formencode_classic.FormStash`", "getcreate_args[ \"acme_account_provider_id\" ] = acme_account_provider_id self.account_key_pem = getcreate_args[ \"key_pem\" ]", "if private_key_technology is not None: private_key_technology_id = model_utils.KeyTechnology.from_string( private_key_technology )", "None: require_contact = True contact = formStash.results.get(\"account__contact\") if not contact", "\"private_key_for_account_key\" privateKeySelection.private_key_strategy__requested = ( model_utils.PrivateKeySelection_2_PrivateKeyStrategy[ \"private_key_for_account_key\" ] ) return privateKeySelection", "domain names match a simple regex # it will raise", "= dbPrivateKey if private_key_option == \"private_key_generate\": privateKeySelection.selection = \"generate\" privateKeySelection.private_key_strategy__requested", "`FormInvalid()` formStash.fatal_form(\"Invalid `private_key_option`\") if not private_key_pem_md5: # `formStash.fatal_field()` will raise", "failures.append( \"If any of %s is provided, all must be", "= lib_db.getcreate.getcreate__AcmeAccount( request.api_context, **key_create_args ) acmeAccountSelection.AcmeAccount = dbAcmeAccount privateKeySelection =", "import formhandling # ============================================================================== def decode_args(getcreate_args): \"\"\" support for Python2/3", "if not domain_names_all: # `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=\"Error_Main\",", "explicit-option privateKeySelection = _PrivateKeySelection() if private_key_option == \"private_key_file\": # this", "acmeAccountSelection.upload_parsed = parser return acmeAccountSelection else: if account_key_option == \"account_key_global_default\":", "account_key_option=formStash.results[\"account_key_option\"], require_contact=require_contact, ) if acmeAccountSelection.selection == \"upload\": key_create_args = acmeAccountSelection.upload_parsed.getcreate_args", "formStash.results.get( \"acme_account_provider_id\", None ) if acme_account_provider_id is None: # `formStash.fatal_field()`", "private_key_technology_id = model_utils.KeyTechnology.from_string( private_key_technology ) if not private_key_technology_id and require_technology:", "= None # :class:`model.objects.PrivateKey` # handle the explicit-option privateKeySelection =", "not dbPrivateKey: formStash.fatal_field( field=private_key_option, message=\"Could not load the placeholder PrivateKey.\",", "pem is uploaded # required for PEM, ignored otherwise acme_account_provider_id", "provider option # will be None unless a pem is", "is None: # `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=\"account__private_key_cycle\", message=\"No", "utils from ...model import objects as model_objects from ...model import", "\"private_key_technology_id\" ] = private_key_technology_id if formStash.results[\"account_key_file_pem\"] is not None: if", "formStash.fatal_field( field=\"account__private_key_technology\", message=\"No PrivateKey technology submitted.\", ) contact = formStash.results.get(\"account__contact\",", "to one challenge type\", ) # 4: maybe we only", "name can only be associated to one challenge type\", )", "= getcreate_args[ \"private_key_cycle_id\" ] = private_key_cycle_id self.private_key_technology_id = getcreate_args[ \"private_key_technology_id\"", "private_key_technology_id if formStash.results[\"account_key_file_pem\"] is not None: if acme_account_provider_id is None:", "def parse_PrivateKeySelection(request, formStash, private_key_option=None): private_key_pem = None private_key_pem_md5 = None", "``None`` for conditional logic \"\"\" account_key_pem = None account_key_pem_md5 =", "formStash.fatal_field( field=\"account__private_key_technology\", message=\"No PrivateKey technology submitted.\", ) # require `contact`", "\"domain_names_http01\", \"dns-01\": \"domain_names_dns01\", } class AcmeAccountUploadParser(object): \"\"\" An AcmeAccount may", "= \"existing\" account_key_pem_md5 = formStash.results[\"account_key_existing\"] elif account_key_option == \"account_key_reuse\": acmeAccountSelection.selection", "`formStash.fatal_form()` will raise `FormInvalid()` formStash.fatal_form( \"This form does not support", "field=account_key_option, message=\"You did not provide a value\" ) dbAcmeAccount =", "if not allow_none: # `formStash.fatal_form()` will raise `FormInvalid()` formStash.fatal_form( \"This", "else: formStash.fatal_form( message=\"Invalid `account_key_option`\", ) if not account_key_pem_md5: # `formStash.fatal_field()`", ") acmeAccountSelection.AcmeAccount = dbAcmeAccount return acmeAccountSelection # `formStash.fatal_form()` will raise", "None ) private_key_cycle = formStash.results.get(\"account__private_key_cycle\", None) if private_key_cycle is None:", "a PEM file if formStash.results[\"account_key_file_pem\"] is not None: require_contact =", "domains submitted? if http01_only: for (k, v) in domains_challenged.items(): if", "was an error validating your form.\") def form_key_selection(request, formStash, require_contact=None):", "\"reuse\" privateKeySelection.private_key_strategy__requested = ( model_utils.PrivateKeySelection_2_PrivateKeyStrategy[\"reuse\"] ) private_key_pem_md5 = formStash.results[\"private_key_reuse\"] elif", "self.getcreate_args = {} def require_upload(self): \"\"\" routine for uploading an", ") = lib_db.getcreate.getcreate__PrivateKey__by_pem_text( request.api_context, **key_create_args ) privateKeySelection.PrivateKey = dbPrivateKey elif", "getcreate_args[ \"private_key_technology_id\" ] = private_key_technology_id self.getcreate_args = decode_args(getcreate_args) def require_upload(self,", "field=\"account__private_key_cycle\", message=\"No PrivateKey cycle submitted.\", ) private_key_cycle_id = model_utils.PrivateKeyCycle.from_string( private_key_cycle", "acmeAccountSelection = parse_AcmeAccountSelection( request, formStash, account_key_option=formStash.results[\"account_key_option\"], require_contact=require_contact, ) if acmeAccountSelection.selection", "installation This parser operates on a validated FormEncode results object", "are domains if not domain_names_all: # `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)`", "# handle the explicit-option acmeAccountSelection = _AcmeAccountSelection() if account_key_option ==", "AcmeAccount is not enrolled in the system.\", ) if is_global_default", "# pem OR letsencrypt def __init__(self, formStash): self.formStash = formStash", "ignored otherwise acme_account_provider_id = formStash.results.get( \"acme_account_provider_id\", None ) private_key_cycle =", "a simple regex domain_names = utils.domains_from_string(formStash.results[\"domain_name\"]) if not domain_names: #", "= None le_meta_jsons = None le_pkey_jsons = None le_reg_jsons =", "validate the provider option # will be None unless a", "require_contact: ``True`` if required; ``False`` if not; ``None`` for conditional", "# validate the provider option # will be None unless", "letsencrypt def __init__(self, formStash): self.formStash = formStash self.getcreate_args = {}", "explicit-option acmeAccountSelection = _AcmeAccountSelection() if account_key_option == \"account_key_file\": # this", "decode_args(getcreate_args) class _PrivateKeyUploadParser(object): \"\"\" A PrivateKey is not a complex", "\"private_key_generate\": privateKeySelection.selection = \"generate\" privateKeySelection.private_key_strategy__requested = ( model_utils.PrivateKeySelection_2_PrivateKeyStrategy[\"generate\"] ) elif", "domain\")` on the first invalid domain submitted_ = utils.domains_from_string(submitted_) if", "): \"\"\" :param formStash: an instance of `pyramid_formencode_classic.FormStash` :param account_key_option:", "need all of them if any(option_set_results): if not all(option_set_results): failures.append(", "will handle form validation and raise errors. parser = AcmeAccountUploadParser(formStash)", "formStash = None # tracked acme_account_provider_id = None account_key_pem =", "acmeAccountSelection.selection = \"existing\" account_key_pem_md5 = formStash.results[\"account_key_existing\"] elif account_key_option == \"account_key_reuse\":", "submitted.\", ) # require `contact` when uploading a PEM file", "_is_created,) = lib_db.getcreate.getcreate__AcmeAccount( request.api_context, **key_create_args ) acmeAccountSelection.AcmeAccount = dbAcmeAccount privateKeySelection", "(acmeAccountSelection, privateKeySelection) def form_domains_challenge_typed(request, formStash, http01_only=False): domains_challenged = model_utils.DomainsChallenged() domain_names_all", "AcmeAccount+AcmeAccountKey :param require_contact: ``True`` if required; ``False`` if not; ``None``", "------------------- # validate the provider option # will be None", "placeholder PrivateKey for autogeneration.\", ) privateKeySelection.PrivateKey = dbPrivateKey return (acmeAccountSelection,", "( model_utils.PrivateKeySelection_2_PrivateKeyStrategy[\"reuse\"] ) private_key_pem_md5 = formStash.results[\"private_key_reuse\"] elif private_key_option in (", ") private_key_pem_md5 = formStash.results[\"private_key_reuse\"] elif private_key_option in ( \"private_key_generate\", \"private_key_for_account_key\",", "privateKeySelection.selection == \"generate\": dbPrivateKey = lib_db.get.get__PrivateKey__by_id(request.api_context, 0) if not dbPrivateKey:", "= model_utils.KeyTechnology.from_string( private_key_technology ) if not private_key_technology_id and require_technology: #", "len(domain_names_all_set): # `formStash.fatal_field()` will raise `FormFieldInvalid(FormInvalid)` formStash.fatal_field( field=\"Error_Main\", message=\"a domain", "not None: require_contact = True contact = formStash.results.get(\"account__contact\") if not", "def form_single_domain_challenge_typed(request, formStash, challenge_type=\"http-01\"): domains_challenged = model_utils.DomainsChallenged() # this function", "accepted by this form\", ) except ValueError as exc: #", "require_contact=require_contact, ) if acmeAccountSelection.selection == \"upload\": key_create_args = acmeAccountSelection.upload_parsed.getcreate_args key_create_args[\"event_type\"]", "formStash, account_key_option=formStash.results[\"account_key_option\"], require_contact=require_contact, ) if acmeAccountSelection.selection == \"upload\": key_create_args =", "it will raise a `ValueError(\"invalid domain\")` on the first invalid", "message=\"invalid domain names detected\" ) return domains_challenged def form_single_domain_challenge_typed(request, formStash,", "enrolled in the system.\", ) privateKeySelection.PrivateKey = dbPrivateKey return privateKeySelection", "string self.le_meta_jsons = getcreate_args[ \"le_meta_jsons\" ] = formhandling.slurp_file_field(formStash, \"account_key_file_le_meta\") self.le_pkey_jsons", "an exiting PrivateKey \"\"\" formStash = self.formStash getcreate_args = {}", "private_key_pem_md5 = None PrivateKey = None # :class:`model.objects.PrivateKey` # handle", ") private_key_cycle = formStash.results.get(\"account__private_key_cycle\", None) if private_key_cycle is None: #", "file * an intra-associated three file triplet from a Certbot", "not; ``None`` for conditional logic \"\"\" account_key_pem = None account_key_pem_md5", "is required.\", ) getcreate_args = {} self.contact = getcreate_args[\"contact\"] =", "getcreate_args[\"contact\"] = contact self.private_key_cycle_id = getcreate_args[ \"private_key_cycle_id\" ] = private_key_cycle_id", "field=\"account__private_key_technology\", message=\"No PrivateKey technology submitted.\", ) # require `contact` when", "http01_only=False): domains_challenged = model_utils.DomainsChallenged() domain_names_all = [] try: # 1:", "import six # local from ...lib import db as lib_db", "\"\"\" formStash = self.formStash getcreate_args = {} if formStash.results[\"private_key_file_pem\"] is", "otherwise acme_account_provider_id = formStash.results.get( \"acme_account_provider_id\", None ) private_key_cycle = formStash.results.get(\"account__private_key_cycle\",", "None class _PrivateKeySelection(object): selection = None upload_parsed = None #", "domain submitted_ = utils.domains_from_string(submitted_) if submitted_: domain_names_all.extend(submitted_) domains_challenged[target_] = submitted_", "model_utils.KeyTechnology.from_string( private_key_technology ) if not private_key_technology_id and require_technology: # `formStash.fatal_field()`", "field=account_key_option, message=\"The selected AcmeAccount is not enrolled in the system.\"," ]
[ "(NStreams == 1): #Creates list of filenames for Phi in", "'Dirac'): vr = 0 vi = 0 if(k%151 == 1):", "table to associate data to streams NSamplesIn128bits = int(128/NBitsData )", "2.0 (the \"License\"); # you may not use this file", "and SequenceType != 'Random' and SequenceType != 'Dirac'): print ('Unknown", "data to streams NSamplesIn128bits = int(128/NBitsData ) H = np.zeros((int(NSamples1/NPhases/2),2))", "',SeqType_s.get()) print('Base filename : ',Basename_s.get()) NPhases = int(NPhases_s.get()) NStreams =", "GUI # SequenceType ='Linear' # 'SinCos' 'Linear' 'Random' 'Dirac' #", "k%2 # Which streams H[index[i],i] = s index[i] = index[i]+1", "delay in streams NBitsData = 32; if( dtval.get() == 'int16'):", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "that should be in the GUI # SequenceType ='Linear' #", "p in range (NPhases): k = i*NPhases+p if (SequenceType ==", "vi PLIOwidth = int(pliow.get()) NSamplesPerLine = int(PLIOwidth/NBitsData) # Data are", "will be distributed over all streams # it is already", ": ',Basename_s.get()) NPhases = int(NPhases_s.get()) NStreams = int(NStreams_s.get()) LFrame =", "NSamplesPerLine = int(PLIOwidth/NBitsData) # Data are read in blocks of", "TestInputS.txt FileNames = []; # Easiest case: 1 stream per", "# Create the overall signal that will be distributed over", "use this file except in compliance with the License. #", "signal that will be distributed over all streams # it", "files fds = [open(path, 'w') for path in FileNames] #Fill", "path in FileNames] #Fill all files with the right data", "cint16) # Create an Input test Vector in TestInputS.txt FileNames", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "the GUI # SequenceType ='Linear' # 'SinCos' 'Linear' 'Random' 'Dirac'", "License. # You may obtain a copy of the License", "1 # S[p,i,0] = # if(HasImag==1): # S[p,i,1] = int(5000*sin(6.28*5/(NPhases*NStreams*LFrame)*k))", "= fds[2*p+stream] for s in range(int(NSamples1/NPhases/NSamplesPerLine/NStreams)): for d in range(NSamplesPerLine):", "under the License is distributed on an \"AS IS\" BASIS,", "list of filenames for Phi in range(NPhases): FileNames.append(Basename+'_'+str(Phi)+'.txt') #Open all", "d fd.write(str(int(S[p,index,0]))+' ') if(HasImag): fd.write(str(int(S[p,index,1]))+' ') fd.write('\\n') for fd in", "License for the specific language governing permissions and # limitations", "little longer to allow for delay in streams NBitsData =", "'Random' 'Dirac' # Basename = 'PhaseIn' NSamples = NPhases*NStreams*LFrame*NFrames; NSamples1", "in TestInputS.txt FileNames = []; # Easiest case: 1 stream", "# if(k%311 == 50): # vr = 1 # S[p,i,0]", "'w') for path in FileNames] #Fill all files with the", "per AI Engine if (NStreams == 1): #Creates list of", "separated in phases S = np.zeros((NPhases,int(NSamples1/NPhases),1+HasImag)) for i in range(int(NSamples1/NPhases)):", "over all streams # it is already separated in phases", "list of filenames for Phi in range(NPhases): for Stream in", "as np from math import * import random def GenerateTestVector(dtval,pliow,NPhases_s,NStreams_s,NSamples_s,NFrames_s,SeqType_s,Basename_s):", "= 0 if(k%151 == 1): vr = 1 elif(k%151 ==", "1 elif(k%151 == 40): vi = 1 elif(k%151 == 81):", "0 vi = 0 if(k%151 == 1): vr = 1", "= k vi = -k elif (SequenceType == 'Random'): vr", "range(int(NSamples1/NPhases/NSamplesPerLine/NStreams)): for d in range(NSamplesPerLine): index = s*NSamplesPerLine + d", "# Block order i = k%2 # Which streams H[index[i],i]", "in range(2): fd = fds[2*p+stream] for s in range(int(NSamples1/NPhases/NSamplesPerLine/NStreams)): for", "NFrames = int(NFrames_s.get()) SequenceType = SeqType_s.get() Basename = Basename_s.get() #parameters", "in compliance with the License. # You may obtain a", "= 0 vi = 0 if(k%151 == 1): vr =", "print ('Unknown Sequence Type') return # Create the overall signal", "0 if(k%151 == 1): vr = 1 elif(k%151 == 40):", "software # distributed under the License is distributed on an", "in range(NPhases): FileNames.append(Basename+'_'+str(Phi)+'.txt') #Open all files fds = [open(path, 'w')", "s in range(int(NSamples1/NPhases/NSamplesPerLine)): for d in range(NSamplesPerLine): index = s*NSamplesPerLine", "for s in range(int(NSamples1/NPhases/NSamplesPerLine)): for d in range(NSamplesPerLine): index =", "should be in the GUI # SequenceType ='Linear' # 'SinCos'", "the License. # import numpy as np from math import", "NSamples = NPhases*NStreams*LFrame*NFrames; NSamples1 = NPhases*NStreams*LFrame*(NFrames+1); # A little longer", "data in cint16) # Create an Input test Vector in", "',NStreams_s.get()) print('NSamples : ',NSamples_s.get()) print('NFrames : ',NFrames_s.get()) print('Type of Sequence", "for i in range(int(NSamples1/NPhases)): for p in range (NPhases): k", "s in range(int(NSamples1/NPhases)): k = int(s/NSamplesIn128bits) # Block order i", "'Dirac' # Basename = 'PhaseIn' NSamples = NPhases*NStreams*LFrame*NFrames; NSamples1 =", "d fd.write(str(int(S[p,H[index,stream],0]))+' ') if(HasImag): fd.write(str(int(S[p,H[index,stream],1]))+' ') fd.write('\\n') for fd in", "!= 'Dirac'): print ('Unknown Sequence Type') return # Create the", "case: 1 stream per AI Engine if (NStreams == 1):", "== 1): #Creates list of filenames for Phi in range(NPhases):", "!= 'Random' and SequenceType != 'Dirac'): print ('Unknown Sequence Type')", "= s index[i] = index[i]+1 #Open all files fds =", "fds[2*p+stream] for s in range(int(NSamples1/NPhases/NSamplesPerLine/NStreams)): for d in range(NSamplesPerLine): index", "# Create an Input test Vector in TestInputS.txt FileNames =", "= vr if (HasImag == 1 ): S[p,i,1] = vi", "Hash table to associate data to streams NSamplesIn128bits = int(128/NBitsData", "Xilinx, Inc. # # Licensed under the Apache License, Version", "= NPhases*NStreams*LFrame*NFrames; NSamples1 = NPhases*NStreams*LFrame*(NFrames+1); # A little longer to", "read in blocks of 128 bits (4 data in cint16)", "blocks of 128 bits (4 data in cint16) # Create", "i in range(int(NSamples1/NPhases)): for p in range (NPhases): k =", "= int(5000*cos(6.28*5/(NPhases*NStreams*LFrame)*k)) vi = int(5000*sin(6.28*5/(NPhases*NStreams*LFrame)*k)) elif (SequenceType == 'Linear'): vr", "if (dtval.get() == 'cint16'): HasImag = 1 if(SequenceType != 'SinCos'", "for Stream in range(NStreams): FileNames.append('PhaseIn_'+str(Phi)+'_'+str(Stream)+'.txt') # Hash table to associate", "range(int(NSamples1/NPhases)): k = int(s/NSamplesIn128bits) # Block order i = k%2", "index[i]+1 #Open all files fds = [open(path, 'w') for path", "print('Base filename : ',Basename_s.get()) NPhases = int(NPhases_s.get()) NStreams = int(NStreams_s.get())", "range (NPhases): k = i*NPhases+p if (SequenceType == 'SinCos'): vr", "#Fill all files with the right data for p in", "in cint16) # Create an Input test Vector in TestInputS.txt", "40): vi = 1 elif(k%151 == 81): vr = 2", "range(NSamplesPerLine): index = s*NSamplesPerLine + d fd.write(str(int(S[p,index,0]))+' ') if(HasImag): fd.write(str(int(S[p,index,1]))+'", "OF ANY KIND, either express or implied. # See the", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "ANY KIND, either express or implied. # See the License", "See the License for the specific language governing permissions and", "SeqType_s.get() Basename = Basename_s.get() #parameters that should be in the", "H.astype('int32') index = np.zeros(2) index = index.astype('int32') for s in", "== 115): vi = -2 # if(k%311 == 50): #", "in range(NSamplesPerLine): index = s*NSamplesPerLine + d fd.write(str(int(S[p,H[index,stream],0]))+' ') if(HasImag):", "the License. # You may obtain a copy of the", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "for the specific language governing permissions and # limitations under", "to in writing, software # distributed under the License is", "index = s*NSamplesPerLine + d fd.write(str(int(S[p,H[index,stream],0]))+' ') if(HasImag): fd.write(str(int(S[p,H[index,stream],1]))+' ')", "Create an Input test Vector in TestInputS.txt FileNames = [];", "# See the License for the specific language governing permissions", "NPhases = int(NPhases_s.get()) NStreams = int(NStreams_s.get()) LFrame = int(NSamples_s.get()) NFrames", "p in range(NPhases): for stream in range(2): fd = fds[2*p+stream]", "elif (SequenceType == 'Linear'): vr = k vi = -k", "(SequenceType == 'Dirac'): vr = 0 vi = 0 if(k%151", "+ d fd.write(str(int(S[p,H[index,stream],0]))+' ') if(HasImag): fd.write(str(int(S[p,H[index,stream],1]))+' ') fd.write('\\n') for fd", "language governing permissions and # limitations under the License. #", "or agreed to in writing, software # distributed under the", "int(pliow.get()) NSamplesPerLine = int(PLIOwidth/NBitsData) # Data are read in blocks", "for fd in fds: fd.close() if (NStreams == 2): #Creates", "required by applicable law or agreed to in writing, software", "NPhases*NStreams*LFrame*(NFrames+1); # A little longer to allow for delay in", "of 128 bits (4 data in cint16) # Create an", "all streams # it is already separated in phases S", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "1 elif(k%151 == 81): vr = 2 elif(k%151 == 115):", "1): vr = 1 elif(k%151 == 40): vi = 1", "fd.write('\\n') for fd in fds: fd.close() if (NStreams == 2):", "with the License. # You may obtain a copy of", "= s*NSamplesPerLine + d fd.write(str(int(S[p,H[index,stream],0]))+' ') if(HasImag): fd.write(str(int(S[p,H[index,stream],1]))+' ') fd.write('\\n')", "== 2): #Creates list of filenames for Phi in range(NPhases):", "for p in range (NPhases): k = i*NPhases+p if (SequenceType", "GenerateTestVector(dtval,pliow,NPhases_s,NStreams_s,NSamples_s,NFrames_s,SeqType_s,Basename_s): print('DtVal : ',dtval.get()) print('PLIO width : ',pliow.get()) print('NPhases :", "Phi in range(NPhases): for Stream in range(NStreams): FileNames.append('PhaseIn_'+str(Phi)+'_'+str(Stream)+'.txt') # Hash", "NBitsData = 16 HasImag = 0 if (dtval.get() == 'cint16'):", "def GenerateTestVector(dtval,pliow,NPhases_s,NStreams_s,NSamples_s,NFrames_s,SeqType_s,Basename_s): print('DtVal : ',dtval.get()) print('PLIO width : ',pliow.get()) print('NPhases", "Data are read in blocks of 128 bits (4 data", "if(HasImag==1): # S[p,i,1] = int(5000*sin(6.28*5/(NPhases*NStreams*LFrame)*k)) S[p,i,0] = vr if (HasImag", "and SequenceType != 'Dirac'): print ('Unknown Sequence Type') return #", "compliance with the License. # You may obtain a copy", "# S[p,i,0] = # if(HasImag==1): # S[p,i,1] = int(5000*sin(6.28*5/(NPhases*NStreams*LFrame)*k)) S[p,i,0]", "agreed to in writing, software # distributed under the License", "for Phi in range(NPhases): FileNames.append(Basename+'_'+str(Phi)+'.txt') #Open all files fds =", "if(k%151 == 1): vr = 1 elif(k%151 == 40): vi", "np.zeros(2) index = index.astype('int32') for s in range(int(NSamples1/NPhases)): k =", "distributed under the License is distributed on an \"AS IS\"", "s in range(int(NSamples1/NPhases/NSamplesPerLine/NStreams)): for d in range(NSamplesPerLine): index = s*NSamplesPerLine", "# # Copyright 2020–2021 Xilinx, Inc. # # Licensed under", "= int(pliow.get()) NSamplesPerLine = int(PLIOwidth/NBitsData) # Data are read in", "Input test Vector in TestInputS.txt FileNames = []; # Easiest", "(NPhases): k = i*NPhases+p if (SequenceType == 'SinCos'): vr =", "express or implied. # See the License for the specific", "except in compliance with the License. # You may obtain", "in range(NStreams): FileNames.append('PhaseIn_'+str(Phi)+'_'+str(Stream)+'.txt') # Hash table to associate data to", "= int(PLIOwidth/NBitsData) # Data are read in blocks of 128", "streams NSamplesIn128bits = int(128/NBitsData ) H = np.zeros((int(NSamples1/NPhases/2),2)) H =", "Licensed under the Apache License, Version 2.0 (the \"License\"); #", "LFrame = int(NSamples_s.get()) NFrames = int(NFrames_s.get()) SequenceType = SeqType_s.get() Basename", "fd.write(str(int(S[p,H[index,stream],0]))+' ') if(HasImag): fd.write(str(int(S[p,H[index,stream],1]))+' ') fd.write('\\n') for fd in fds:", "not use this file except in compliance with the License.", "FileNames.append('PhaseIn_'+str(Phi)+'_'+str(Stream)+'.txt') # Hash table to associate data to streams NSamplesIn128bits", "writing, software # distributed under the License is distributed on", "import random def GenerateTestVector(dtval,pliow,NPhases_s,NStreams_s,NSamples_s,NFrames_s,SeqType_s,Basename_s): print('DtVal : ',dtval.get()) print('PLIO width :", "print('NStreams : ',NStreams_s.get()) print('NSamples : ',NSamples_s.get()) print('NFrames : ',NFrames_s.get()) print('Type", "you may not use this file except in compliance with", "S[p,i,0] = vr if (HasImag == 1 ): S[p,i,1] =", "= int(5000*sin(6.28*5/(NPhases*NStreams*LFrame)*k)) elif (SequenceType == 'Linear'): vr = k vi", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "(HasImag == 1 ): S[p,i,1] = vi PLIOwidth = int(pliow.get())", "already separated in phases S = np.zeros((NPhases,int(NSamples1/NPhases),1+HasImag)) for i in", "int(128/NBitsData ) H = np.zeros((int(NSamples1/NPhases/2),2)) H = H.astype('int32') index =", "vr if (HasImag == 1 ): S[p,i,1] = vi PLIOwidth", "associate data to streams NSamplesIn128bits = int(128/NBitsData ) H =", "that will be distributed over all streams # it is", "in fds: fd.close() if (NStreams == 2): #Creates list of", "0 if (dtval.get() == 'cint16'): HasImag = 1 if(SequenceType !=", "HasImag = 1 if(SequenceType != 'SinCos' and SequenceType != 'Linear'", "= s*NSamplesPerLine + d fd.write(str(int(S[p,index,0]))+' ') if(HasImag): fd.write(str(int(S[p,index,1]))+' ') fd.write('\\n')", "CONDITIONS OF ANY KIND, either express or implied. # See", "phases S = np.zeros((NPhases,int(NSamples1/NPhases),1+HasImag)) for i in range(int(NSamples1/NPhases)): for p", ": ',NStreams_s.get()) print('NSamples : ',NSamples_s.get()) print('NFrames : ',NFrames_s.get()) print('Type of", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "vr = 1 elif(k%151 == 40): vi = 1 elif(k%151", "for p in range(NPhases): for stream in range(2): fd =", "range(NStreams): FileNames.append('PhaseIn_'+str(Phi)+'_'+str(Stream)+'.txt') # Hash table to associate data to streams", "'int16'): NBitsData = 16 HasImag = 0 if (dtval.get() ==", "= random.randint(-5000,5000) vi = random.randint(-5000,5000) elif (SequenceType == 'Dirac'): vr", "if (NStreams == 1): #Creates list of filenames for Phi", "= int(s/NSamplesIn128bits) # Block order i = k%2 # Which", "print('NPhases : ',NPhases_s.get()) print('NStreams : ',NStreams_s.get()) print('NSamples : ',NSamples_s.get()) print('NFrames", "= int(128/NBitsData ) H = np.zeros((int(NSamples1/NPhases/2),2)) H = H.astype('int32') index", "files with the right data for p in range(NPhases): for", "#Creates list of filenames for Phi in range(NPhases): for Stream", "in phases S = np.zeros((NPhases,int(NSamples1/NPhases),1+HasImag)) for i in range(int(NSamples1/NPhases)): for", "S[p,i,0] = # if(HasImag==1): # S[p,i,1] = int(5000*sin(6.28*5/(NPhases*NStreams*LFrame)*k)) S[p,i,0] =", "filenames for Phi in range(NPhases): for Stream in range(NStreams): FileNames.append('PhaseIn_'+str(Phi)+'_'+str(Stream)+'.txt')", "# A little longer to allow for delay in streams", "= i*NPhases+p if (SequenceType == 'SinCos'): vr = int(5000*cos(6.28*5/(NPhases*NStreams*LFrame)*k)) vi", "= index[i]+1 #Open all files fds = [open(path, 'w') for", "#parameters that should be in the GUI # SequenceType ='Linear'", "#Creates list of filenames for Phi in range(NPhases): FileNames.append(Basename+'_'+str(Phi)+'.txt') #Open", "range(NPhases): for Stream in range(NStreams): FileNames.append('PhaseIn_'+str(Phi)+'_'+str(Stream)+'.txt') # Hash table to", "i = k%2 # Which streams H[index[i],i] = s index[i]", "2 elif(k%151 == 115): vi = -2 # if(k%311 ==", "Engine if (NStreams == 1): #Creates list of filenames for", "in FileNames] #Fill all files with the right data for", "'SinCos' 'Linear' 'Random' 'Dirac' # Basename = 'PhaseIn' NSamples =", "A little longer to allow for delay in streams NBitsData", "# it is already separated in phases S = np.zeros((NPhases,int(NSamples1/NPhases),1+HasImag))", "H = np.zeros((int(NSamples1/NPhases/2),2)) H = H.astype('int32') index = np.zeros(2) index", "index = s*NSamplesPerLine + d fd.write(str(int(S[p,index,0]))+' ') if(HasImag): fd.write(str(int(S[p,index,1]))+' ')", "OR CONDITIONS OF ANY KIND, either express or implied. #", "(SequenceType == 'SinCos'): vr = int(5000*cos(6.28*5/(NPhases*NStreams*LFrame)*k)) vi = int(5000*sin(6.28*5/(NPhases*NStreams*LFrame)*k)) elif", "') if(HasImag): fd.write(str(int(S[p,H[index,stream],1]))+' ') fd.write('\\n') for fd in fds: fd.close()", "= 2 elif(k%151 == 115): vi = -2 # if(k%311", "the License is distributed on an \"AS IS\" BASIS, #", "of Sequence : ',SeqType_s.get()) print('Base filename : ',Basename_s.get()) NPhases =", "# import numpy as np from math import * import", "print('NFrames : ',NFrames_s.get()) print('Type of Sequence : ',SeqType_s.get()) print('Base filename", "int(NSamples_s.get()) NFrames = int(NFrames_s.get()) SequenceType = SeqType_s.get() Basename = Basename_s.get()", "',pliow.get()) print('NPhases : ',NPhases_s.get()) print('NStreams : ',NStreams_s.get()) print('NSamples : ',NSamples_s.get())", "vr = 0 vi = 0 if(k%151 == 1): vr", "== 'Linear'): vr = k vi = -k elif (SequenceType", "elif (SequenceType == 'Dirac'): vr = 0 vi = 0", "vr = int(5000*cos(6.28*5/(NPhases*NStreams*LFrame)*k)) vi = int(5000*sin(6.28*5/(NPhases*NStreams*LFrame)*k)) elif (SequenceType == 'Linear'):", ": ',NSamples_s.get()) print('NFrames : ',NFrames_s.get()) print('Type of Sequence : ',SeqType_s.get())", "vi = random.randint(-5000,5000) elif (SequenceType == 'Dirac'): vr = 0", "in range(NPhases): for Stream in range(NStreams): FileNames.append('PhaseIn_'+str(Phi)+'_'+str(Stream)+'.txt') # Hash table", "in range(NSamplesPerLine): index = s*NSamplesPerLine + d fd.write(str(int(S[p,index,0]))+' ') if(HasImag):", "stream in range(2): fd = fds[2*p+stream] for s in range(int(NSamples1/NPhases/NSamplesPerLine/NStreams)):", "range(int(NSamples1/NPhases)): for p in range (NPhases): k = i*NPhases+p if", "'Linear' and SequenceType != 'Random' and SequenceType != 'Dirac'): print", "= 1 if(SequenceType != 'SinCos' and SequenceType != 'Linear' and", "int(5000*sin(6.28*5/(NPhases*NStreams*LFrame)*k)) elif (SequenceType == 'Linear'): vr = k vi =", "to streams NSamplesIn128bits = int(128/NBitsData ) H = np.zeros((int(NSamples1/NPhases/2),2)) H", "it is already separated in phases S = np.zeros((NPhases,int(NSamples1/NPhases),1+HasImag)) for", "to allow for delay in streams NBitsData = 32; if(", "law or agreed to in writing, software # distributed under", "AI Engine if (NStreams == 1): #Creates list of filenames", "Sequence Type') return # Create the overall signal that will", "governing permissions and # limitations under the License. # import", "int(NStreams_s.get()) LFrame = int(NSamples_s.get()) NFrames = int(NFrames_s.get()) SequenceType = SeqType_s.get()", "= index.astype('int32') for s in range(int(NSamples1/NPhases)): k = int(s/NSamplesIn128bits) #", "range(NPhases): for stream in range(2): fd = fds[2*p+stream] for s", "= int(NSamples_s.get()) NFrames = int(NFrames_s.get()) SequenceType = SeqType_s.get() Basename =", "elif (SequenceType == 'Random'): vr = random.randint(-5000,5000) vi = random.randint(-5000,5000)", "= 16 HasImag = 0 if (dtval.get() == 'cint16'): HasImag", "NSamples1 = NPhases*NStreams*LFrame*(NFrames+1); # A little longer to allow for", "in blocks of 128 bits (4 data in cint16) #", "for s in range(int(NSamples1/NPhases/NSamplesPerLine/NStreams)): for d in range(NSamplesPerLine): index =", "index = np.zeros(2) index = index.astype('int32') for s in range(int(NSamples1/NPhases)):", ": ',pliow.get()) print('NPhases : ',NPhases_s.get()) print('NStreams : ',NStreams_s.get()) print('NSamples :", "elif(k%151 == 115): vi = -2 # if(k%311 == 50):", "of filenames for Phi in range(NPhases): for Stream in range(NStreams):", "be in the GUI # SequenceType ='Linear' # 'SinCos' 'Linear'", "s*NSamplesPerLine + d fd.write(str(int(S[p,index,0]))+' ') if(HasImag): fd.write(str(int(S[p,index,1]))+' ') fd.write('\\n') for", "# if(HasImag==1): # S[p,i,1] = int(5000*sin(6.28*5/(NPhases*NStreams*LFrame)*k)) S[p,i,0] = vr if", "all files with the right data for p in range(NPhases):", "for p in range(NPhases): fd = fds[p] for s in", "* import random def GenerateTestVector(dtval,pliow,NPhases_s,NStreams_s,NSamples_s,NFrames_s,SeqType_s,Basename_s): print('DtVal : ',dtval.get()) print('PLIO width", "may obtain a copy of the License at # #", "vr = 2 elif(k%151 == 115): vi = -2 #", "= 1 elif(k%151 == 81): vr = 2 elif(k%151 ==", "int(s/NSamplesIn128bits) # Block order i = k%2 # Which streams", "order i = k%2 # Which streams H[index[i],i] = s", "in the GUI # SequenceType ='Linear' # 'SinCos' 'Linear' 'Random'", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "Inc. # # Licensed under the Apache License, Version 2.0", "fd.write(str(int(S[p,index,1]))+' ') fd.write('\\n') for fd in fds: fd.close() if (NStreams", ": ',NFrames_s.get()) print('Type of Sequence : ',SeqType_s.get()) print('Base filename :", "== 'cint16'): HasImag = 1 if(SequenceType != 'SinCos' and SequenceType", "bits (4 data in cint16) # Create an Input test", "# Basename = 'PhaseIn' NSamples = NPhases*NStreams*LFrame*NFrames; NSamples1 = NPhases*NStreams*LFrame*(NFrames+1);", "filenames for Phi in range(NPhases): FileNames.append(Basename+'_'+str(Phi)+'.txt') #Open all files fds", "# S[p,i,1] = int(5000*sin(6.28*5/(NPhases*NStreams*LFrame)*k)) S[p,i,0] = vr if (HasImag ==", "= NPhases*NStreams*LFrame*(NFrames+1); # A little longer to allow for delay", "may not use this file except in compliance with the", "index.astype('int32') for s in range(int(NSamples1/NPhases)): k = int(s/NSamplesIn128bits) # Block", "(dtval.get() == 'cint16'): HasImag = 1 if(SequenceType != 'SinCos' and", "2020–2021 Xilinx, Inc. # # Licensed under the Apache License,", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "== 50): # vr = 1 # S[p,i,0] = #", "range(NPhases): FileNames.append(Basename+'_'+str(Phi)+'.txt') #Open all files fds = [open(path, 'w') for", ") H = np.zeros((int(NSamples1/NPhases/2),2)) H = H.astype('int32') index = np.zeros(2)", "allow for delay in streams NBitsData = 32; if( dtval.get()", "(4 data in cint16) # Create an Input test Vector", "this file except in compliance with the License. # You", "streams NBitsData = 32; if( dtval.get() == 'int16'): NBitsData =", "Which streams H[index[i],i] = s index[i] = index[i]+1 #Open all", "int(5000*cos(6.28*5/(NPhases*NStreams*LFrame)*k)) vi = int(5000*sin(6.28*5/(NPhases*NStreams*LFrame)*k)) elif (SequenceType == 'Linear'): vr =", "== 1 ): S[p,i,1] = vi PLIOwidth = int(pliow.get()) NSamplesPerLine", "int(NPhases_s.get()) NStreams = int(NStreams_s.get()) LFrame = int(NSamples_s.get()) NFrames = int(NFrames_s.get())", "# SequenceType ='Linear' # 'SinCos' 'Linear' 'Random' 'Dirac' # Basename", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "# # Licensed under the Apache License, Version 2.0 (the", "file except in compliance with the License. # You may", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "the overall signal that will be distributed over all streams", "p in range(NPhases): fd = fds[p] for s in range(int(NSamples1/NPhases/NSamplesPerLine)):", ": ',SeqType_s.get()) print('Base filename : ',Basename_s.get()) NPhases = int(NPhases_s.get()) NStreams", "Sequence : ',SeqType_s.get()) print('Base filename : ',Basename_s.get()) NPhases = int(NPhases_s.get())", "',Basename_s.get()) NPhases = int(NPhases_s.get()) NStreams = int(NStreams_s.get()) LFrame = int(NSamples_s.get())", "Copyright 2020–2021 Xilinx, Inc. # # Licensed under the Apache", "== 40): vi = 1 elif(k%151 == 81): vr =", "(SequenceType == 'Random'): vr = random.randint(-5000,5000) vi = random.randint(-5000,5000) elif", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "(NStreams == 2): #Creates list of filenames for Phi in", "np.zeros((int(NSamples1/NPhases/2),2)) H = H.astype('int32') index = np.zeros(2) index = index.astype('int32')", "if (SequenceType == 'SinCos'): vr = int(5000*cos(6.28*5/(NPhases*NStreams*LFrame)*k)) vi = int(5000*sin(6.28*5/(NPhases*NStreams*LFrame)*k))", "'Random'): vr = random.randint(-5000,5000) vi = random.randint(-5000,5000) elif (SequenceType ==", "NSamplesIn128bits = int(128/NBitsData ) H = np.zeros((int(NSamples1/NPhases/2),2)) H = H.astype('int32')", "range(NPhases): fd = fds[p] for s in range(int(NSamples1/NPhases/NSamplesPerLine)): for d", "= -2 # if(k%311 == 50): # vr = 1", "= np.zeros((NPhases,int(NSamples1/NPhases),1+HasImag)) for i in range(int(NSamples1/NPhases)): for p in range", "('Unknown Sequence Type') return # Create the overall signal that", "= vi PLIOwidth = int(pliow.get()) NSamplesPerLine = int(PLIOwidth/NBitsData) # Data", "= SeqType_s.get() Basename = Basename_s.get() #parameters that should be in", "permissions and # limitations under the License. # import numpy", "Basename_s.get() #parameters that should be in the GUI # SequenceType", "<reponame>jlamperez/Vitis-Tutorials<filename>AI_Engine_Development/Feature_Tutorials/07-AI-Engine-Floating-Point/Utils/GenerationLib.py # # Copyright 2020–2021 Xilinx, Inc. # # Licensed", "d in range(NSamplesPerLine): index = s*NSamplesPerLine + d fd.write(str(int(S[p,index,0]))+' ')", "-k elif (SequenceType == 'Random'): vr = random.randint(-5000,5000) vi =", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "filename : ',Basename_s.get()) NPhases = int(NPhases_s.get()) NStreams = int(NStreams_s.get()) LFrame", "-2 # if(k%311 == 50): # vr = 1 #", "# limitations under the License. # import numpy as np", "in range(int(NSamples1/NPhases/NSamplesPerLine/NStreams)): for d in range(NSamplesPerLine): index = s*NSamplesPerLine +", "FileNames = []; # Easiest case: 1 stream per AI", "data for p in range(NPhases): for stream in range(2): fd", "print('NSamples : ',NSamples_s.get()) print('NFrames : ',NFrames_s.get()) print('Type of Sequence :", "') if(HasImag): fd.write(str(int(S[p,index,1]))+' ') fd.write('\\n') for fd in fds: fd.close()", "or implied. # See the License for the specific language", "Basename = 'PhaseIn' NSamples = NPhases*NStreams*LFrame*NFrames; NSamples1 = NPhases*NStreams*LFrame*(NFrames+1); #", "KIND, either express or implied. # See the License for", "specific language governing permissions and # limitations under the License.", "License. # import numpy as np from math import *", "numpy as np from math import * import random def", "vi = 0 if(k%151 == 1): vr = 1 elif(k%151", "HasImag = 0 if (dtval.get() == 'cint16'): HasImag = 1", "import * import random def GenerateTestVector(dtval,pliow,NPhases_s,NStreams_s,NSamples_s,NFrames_s,SeqType_s,Basename_s): print('DtVal : ',dtval.get()) print('PLIO", "for Phi in range(NPhases): for Stream in range(NStreams): FileNames.append('PhaseIn_'+str(Phi)+'_'+str(Stream)+'.txt') #", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "NPhases*NStreams*LFrame*NFrames; NSamples1 = NPhases*NStreams*LFrame*(NFrames+1); # A little longer to allow", "= int(NFrames_s.get()) SequenceType = SeqType_s.get() Basename = Basename_s.get() #parameters that", "is already separated in phases S = np.zeros((NPhases,int(NSamples1/NPhases),1+HasImag)) for i", "= int(NPhases_s.get()) NStreams = int(NStreams_s.get()) LFrame = int(NSamples_s.get()) NFrames =", "i*NPhases+p if (SequenceType == 'SinCos'): vr = int(5000*cos(6.28*5/(NPhases*NStreams*LFrame)*k)) vi =", "in range(NPhases): fd = fds[p] for s in range(int(NSamples1/NPhases/NSamplesPerLine)): for", "(the \"License\"); # you may not use this file except", "# you may not use this file except in compliance", "!= 'SinCos' and SequenceType != 'Linear' and SequenceType != 'Random'", "1): #Creates list of filenames for Phi in range(NPhases): FileNames.append(Basename+'_'+str(Phi)+'.txt')", "in streams NBitsData = 32; if( dtval.get() == 'int16'): NBitsData", "SequenceType != 'Linear' and SequenceType != 'Random' and SequenceType !=", "# Data are read in blocks of 128 bits (4", "files with the right data for p in range(NPhases): fd", "in range (NPhases): k = i*NPhases+p if (SequenceType == 'SinCos'):", "np.zeros((NPhases,int(NSamples1/NPhases),1+HasImag)) for i in range(int(NSamples1/NPhases)): for p in range (NPhases):", "fds[p] for s in range(int(NSamples1/NPhases/NSamplesPerLine)): for d in range(NSamplesPerLine): index", "vi = -2 # if(k%311 == 50): # vr =", "# # Unless required by applicable law or agreed to", "== 'Dirac'): vr = 0 vi = 0 if(k%151 ==", "= int(NStreams_s.get()) LFrame = int(NSamples_s.get()) NFrames = int(NFrames_s.get()) SequenceType =", "test Vector in TestInputS.txt FileNames = []; # Easiest case:", "81): vr = 2 elif(k%151 == 115): vi = -2", "= np.zeros((int(NSamples1/NPhases/2),2)) H = H.astype('int32') index = np.zeros(2) index =", "H[index[i],i] = s index[i] = index[i]+1 #Open all files fds", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "',NFrames_s.get()) print('Type of Sequence : ',SeqType_s.get()) print('Base filename : ',Basename_s.get())", "distributed over all streams # it is already separated in", "print('DtVal : ',dtval.get()) print('PLIO width : ',pliow.get()) print('NPhases : ',NPhases_s.get())", "vi = int(5000*sin(6.28*5/(NPhases*NStreams*LFrame)*k)) elif (SequenceType == 'Linear'): vr = k", "in range(int(NSamples1/NPhases)): for p in range (NPhases): k = i*NPhases+p", "Version 2.0 (the \"License\"); # you may not use this", "# vr = 1 # S[p,i,0] = # if(HasImag==1): #", "vr = k vi = -k elif (SequenceType == 'Random'):", "',NSamples_s.get()) print('NFrames : ',NFrames_s.get()) print('Type of Sequence : ',SeqType_s.get()) print('Base", "data for p in range(NPhases): fd = fds[p] for s", "128 bits (4 data in cint16) # Create an Input", "right data for p in range(NPhases): for stream in range(2):", "[]; # Easiest case: 1 stream per AI Engine if", "if(k%311 == 50): # vr = 1 # S[p,i,0] =", "vi = 1 elif(k%151 == 81): vr = 2 elif(k%151", "Create the overall signal that will be distributed over all", "= # if(HasImag==1): # S[p,i,1] = int(5000*sin(6.28*5/(NPhases*NStreams*LFrame)*k)) S[p,i,0] = vr", "with the right data for p in range(NPhases): fd =", "# 'SinCos' 'Linear' 'Random' 'Dirac' # Basename = 'PhaseIn' NSamples", "for path in FileNames] #Fill all files with the right", "d in range(NSamplesPerLine): index = s*NSamplesPerLine + d fd.write(str(int(S[p,H[index,stream],0]))+' ')", "): S[p,i,1] = vi PLIOwidth = int(pliow.get()) NSamplesPerLine = int(PLIOwidth/NBitsData)", "if(SequenceType != 'SinCos' and SequenceType != 'Linear' and SequenceType !=", "implied. # See the License for the specific language governing", "longer to allow for delay in streams NBitsData = 32;", "in range(int(NSamples1/NPhases)): k = int(s/NSamplesIn128bits) # Block order i =", "all files fds = [open(path, 'w') for path in FileNames]", "for d in range(NSamplesPerLine): index = s*NSamplesPerLine + d fd.write(str(int(S[p,H[index,stream],0]))+'", "under the Apache License, Version 2.0 (the \"License\"); # you", "= -k elif (SequenceType == 'Random'): vr = random.randint(-5000,5000) vi", "NStreams = int(NStreams_s.get()) LFrame = int(NSamples_s.get()) NFrames = int(NFrames_s.get()) SequenceType", "index = index.astype('int32') for s in range(int(NSamples1/NPhases)): k = int(s/NSamplesIn128bits)", "random.randint(-5000,5000) vi = random.randint(-5000,5000) elif (SequenceType == 'Dirac'): vr =", "= np.zeros(2) index = index.astype('int32') for s in range(int(NSamples1/NPhases)): k", "fd.write(str(int(S[p,index,0]))+' ') if(HasImag): fd.write(str(int(S[p,index,1]))+' ') fd.write('\\n') for fd in fds:", "by applicable law or agreed to in writing, software #", "2): #Creates list of filenames for Phi in range(NPhases): for", "#Open all files fds = [open(path, 'w') for path in", "= [open(path, 'w') for path in FileNames] #Fill all files", "an Input test Vector in TestInputS.txt FileNames = []; #", "'SinCos'): vr = int(5000*cos(6.28*5/(NPhases*NStreams*LFrame)*k)) vi = int(5000*sin(6.28*5/(NPhases*NStreams*LFrame)*k)) elif (SequenceType ==", "= fds[p] for s in range(int(NSamples1/NPhases/NSamplesPerLine)): for d in range(NSamplesPerLine):", "are read in blocks of 128 bits (4 data in", "in range(NPhases): for stream in range(2): fd = fds[2*p+stream] for", "== 'SinCos'): vr = int(5000*cos(6.28*5/(NPhases*NStreams*LFrame)*k)) vi = int(5000*sin(6.28*5/(NPhases*NStreams*LFrame)*k)) elif (SequenceType", "int(5000*sin(6.28*5/(NPhases*NStreams*LFrame)*k)) S[p,i,0] = vr if (HasImag == 1 ): S[p,i,1]", "s index[i] = index[i]+1 #Open all files fds = [open(path,", "fds = [open(path, 'w') for path in FileNames] #Fill all", "if( dtval.get() == 'int16'): NBitsData = 16 HasImag = 0", "SequenceType != 'Dirac'): print ('Unknown Sequence Type') return # Create", "32; if( dtval.get() == 'int16'): NBitsData = 16 HasImag =", "SequenceType != 'Random' and SequenceType != 'Dirac'): print ('Unknown Sequence", "index[i] = index[i]+1 #Open all files fds = [open(path, 'w')", "np from math import * import random def GenerateTestVector(dtval,pliow,NPhases_s,NStreams_s,NSamples_s,NFrames_s,SeqType_s,Basename_s): print('DtVal", "# Hash table to associate data to streams NSamplesIn128bits =", "int(NFrames_s.get()) SequenceType = SeqType_s.get() Basename = Basename_s.get() #parameters that should", "Block order i = k%2 # Which streams H[index[i],i] =", "range(NSamplesPerLine): index = s*NSamplesPerLine + d fd.write(str(int(S[p,H[index,stream],0]))+' ') if(HasImag): fd.write(str(int(S[p,H[index,stream],1]))+'", "Easiest case: 1 stream per AI Engine if (NStreams ==", "in range(int(NSamples1/NPhases/NSamplesPerLine)): for d in range(NSamplesPerLine): index = s*NSamplesPerLine +", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "fd = fds[2*p+stream] for s in range(int(NSamples1/NPhases/NSamplesPerLine/NStreams)): for d in", "k = int(s/NSamplesIn128bits) # Block order i = k%2 #", "Unless required by applicable law or agreed to in writing,", "= 32; if( dtval.get() == 'int16'): NBitsData = 16 HasImag", "streams H[index[i],i] = s index[i] = index[i]+1 #Open all files", "and SequenceType != 'Linear' and SequenceType != 'Random' and SequenceType", "='Linear' # 'SinCos' 'Linear' 'Random' 'Dirac' # Basename = 'PhaseIn'", "if(HasImag): fd.write(str(int(S[p,index,1]))+' ') fd.write('\\n') for fd in fds: fd.close() if", "the specific language governing permissions and # limitations under the", "(SequenceType == 'Linear'): vr = k vi = -k elif", "fd = fds[p] for s in range(int(NSamples1/NPhases/NSamplesPerLine)): for d in", "if (NStreams == 2): #Creates list of filenames for Phi", "applicable law or agreed to in writing, software # distributed", "1 stream per AI Engine if (NStreams == 1): #Creates", "NBitsData = 32; if( dtval.get() == 'int16'): NBitsData = 16", ": ',dtval.get()) print('PLIO width : ',pliow.get()) print('NPhases : ',NPhases_s.get()) print('NStreams", "== 'Random'): vr = random.randint(-5000,5000) vi = random.randint(-5000,5000) elif (SequenceType", "of filenames for Phi in range(NPhases): FileNames.append(Basename+'_'+str(Phi)+'.txt') #Open all files", "for stream in range(2): fd = fds[2*p+stream] for s in", "in writing, software # distributed under the License is distributed", "to associate data to streams NSamplesIn128bits = int(128/NBitsData ) H", "k = i*NPhases+p if (SequenceType == 'SinCos'): vr = int(5000*cos(6.28*5/(NPhases*NStreams*LFrame)*k))", "= 1 elif(k%151 == 40): vi = 1 elif(k%151 ==", "= random.randint(-5000,5000) elif (SequenceType == 'Dirac'): vr = 0 vi", "Vector in TestInputS.txt FileNames = []; # Easiest case: 1", "math import * import random def GenerateTestVector(dtval,pliow,NPhases_s,NStreams_s,NSamples_s,NFrames_s,SeqType_s,Basename_s): print('DtVal : ',dtval.get())", "int(PLIOwidth/NBitsData) # Data are read in blocks of 128 bits", "overall signal that will be distributed over all streams #", "and # limitations under the License. # import numpy as", "== 'int16'): NBitsData = 16 HasImag = 0 if (dtval.get()", "'PhaseIn' NSamples = NPhases*NStreams*LFrame*NFrames; NSamples1 = NPhases*NStreams*LFrame*(NFrames+1); # A little", "be distributed over all streams # it is already separated", "115): vi = -2 # if(k%311 == 50): # vr", "dtval.get() == 'int16'): NBitsData = 16 HasImag = 0 if", "if (HasImag == 1 ): S[p,i,1] = vi PLIOwidth =", "= H.astype('int32') index = np.zeros(2) index = index.astype('int32') for s", "the right data for p in range(NPhases): fd = fds[p]", "1 ): S[p,i,1] = vi PLIOwidth = int(pliow.get()) NSamplesPerLine =", "License is distributed on an \"AS IS\" BASIS, # WITHOUT", "= k%2 # Which streams H[index[i],i] = s index[i] =", "License, Version 2.0 (the \"License\"); # you may not use", "50): # vr = 1 # S[p,i,0] = # if(HasImag==1):", "# You may obtain a copy of the License at", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "'Linear' 'Random' 'Dirac' # Basename = 'PhaseIn' NSamples = NPhases*NStreams*LFrame*NFrames;", "= 1 # S[p,i,0] = # if(HasImag==1): # S[p,i,1] =", "FileNames.append(Basename+'_'+str(Phi)+'.txt') #Open all files fds = [open(path, 'w') for path", "right data for p in range(NPhases): fd = fds[p] for", ": ',NPhases_s.get()) print('NStreams : ',NStreams_s.get()) print('NSamples : ',NSamples_s.get()) print('NFrames :", "== 81): vr = 2 elif(k%151 == 115): vi =", "'cint16'): HasImag = 1 if(SequenceType != 'SinCos' and SequenceType !=", "SequenceType = SeqType_s.get() Basename = Basename_s.get() #parameters that should be", "from math import * import random def GenerateTestVector(dtval,pliow,NPhases_s,NStreams_s,NSamples_s,NFrames_s,SeqType_s,Basename_s): print('DtVal :", "the License for the specific language governing permissions and #", "S = np.zeros((NPhases,int(NSamples1/NPhases),1+HasImag)) for i in range(int(NSamples1/NPhases)): for p in", "Apache License, Version 2.0 (the \"License\"); # you may not", "Phi in range(NPhases): FileNames.append(Basename+'_'+str(Phi)+'.txt') #Open all files fds = [open(path,", "# Which streams H[index[i],i] = s index[i] = index[i]+1 #Open", "either express or implied. # See the License for the", "stream per AI Engine if (NStreams == 1): #Creates list", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "vi = -k elif (SequenceType == 'Random'): vr = random.randint(-5000,5000)", "k vi = -k elif (SequenceType == 'Random'): vr =", "= []; # Easiest case: 1 stream per AI Engine", "elif(k%151 == 40): vi = 1 elif(k%151 == 81): vr", "1 if(SequenceType != 'SinCos' and SequenceType != 'Linear' and SequenceType", "+ d fd.write(str(int(S[p,index,0]))+' ') if(HasImag): fd.write(str(int(S[p,index,1]))+' ') fd.write('\\n') for fd", "fd in fds: fd.close() if (NStreams == 2): #Creates list", "import numpy as np from math import * import random", "under the License. # import numpy as np from math", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "width : ',pliow.get()) print('NPhases : ',NPhases_s.get()) print('NStreams : ',NStreams_s.get()) print('NSamples", "fds: fd.close() if (NStreams == 2): #Creates list of filenames", "PLIOwidth = int(pliow.get()) NSamplesPerLine = int(PLIOwidth/NBitsData) # Data are read", "= 0 if (dtval.get() == 'cint16'): HasImag = 1 if(SequenceType", "for s in range(int(NSamples1/NPhases)): k = int(s/NSamplesIn128bits) # Block order", "print('Type of Sequence : ',SeqType_s.get()) print('Base filename : ',Basename_s.get()) NPhases", "'Random' and SequenceType != 'Dirac'): print ('Unknown Sequence Type') return", "',NPhases_s.get()) print('NStreams : ',NStreams_s.get()) print('NSamples : ',NSamples_s.get()) print('NFrames : ',NFrames_s.get())", "Type') return # Create the overall signal that will be", "limitations under the License. # import numpy as np from", "elif(k%151 == 81): vr = 2 elif(k%151 == 115): vi", "\"License\"); # you may not use this file except in", "random.randint(-5000,5000) elif (SequenceType == 'Dirac'): vr = 0 vi =", "[open(path, 'w') for path in FileNames] #Fill all files with", "== 1): vr = 1 elif(k%151 == 40): vi =", "16 HasImag = 0 if (dtval.get() == 'cint16'): HasImag =", "fd.close() if (NStreams == 2): #Creates list of filenames for", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "FileNames] #Fill all files with the right data for p", "SequenceType ='Linear' # 'SinCos' 'Linear' 'Random' 'Dirac' # Basename =", "S[p,i,1] = int(5000*sin(6.28*5/(NPhases*NStreams*LFrame)*k)) S[p,i,0] = vr if (HasImag == 1", "range(2): fd = fds[2*p+stream] for s in range(int(NSamples1/NPhases/NSamplesPerLine/NStreams)): for d", "# distributed under the License is distributed on an \"AS", "Basename = Basename_s.get() #parameters that should be in the GUI", "# Unless required by applicable law or agreed to in", "'SinCos' and SequenceType != 'Linear' and SequenceType != 'Random' and", "random def GenerateTestVector(dtval,pliow,NPhases_s,NStreams_s,NSamples_s,NFrames_s,SeqType_s,Basename_s): print('DtVal : ',dtval.get()) print('PLIO width : ',pliow.get())", "vr = 1 # S[p,i,0] = # if(HasImag==1): # S[p,i,1]", "= int(5000*sin(6.28*5/(NPhases*NStreams*LFrame)*k)) S[p,i,0] = vr if (HasImag == 1 ):", "the right data for p in range(NPhases): for stream in", "!= 'Linear' and SequenceType != 'Random' and SequenceType != 'Dirac'):", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "for d in range(NSamplesPerLine): index = s*NSamplesPerLine + d fd.write(str(int(S[p,index,0]))+'", "'Linear'): vr = k vi = -k elif (SequenceType ==", "H = H.astype('int32') index = np.zeros(2) index = index.astype('int32') for", "= Basename_s.get() #parameters that should be in the GUI #", "= 'PhaseIn' NSamples = NPhases*NStreams*LFrame*NFrames; NSamples1 = NPhases*NStreams*LFrame*(NFrames+1); # A", "for delay in streams NBitsData = 32; if( dtval.get() ==", "You may obtain a copy of the License at #", "s*NSamplesPerLine + d fd.write(str(int(S[p,H[index,stream],0]))+' ') if(HasImag): fd.write(str(int(S[p,H[index,stream],1]))+' ') fd.write('\\n') for", "'Dirac'): print ('Unknown Sequence Type') return # Create the overall", "print('PLIO width : ',pliow.get()) print('NPhases : ',NPhases_s.get()) print('NStreams : ',NStreams_s.get())", "range(int(NSamples1/NPhases/NSamplesPerLine)): for d in range(NSamplesPerLine): index = s*NSamplesPerLine + d", "with the right data for p in range(NPhases): for stream", "# Copyright 2020–2021 Xilinx, Inc. # # Licensed under the", "# Easiest case: 1 stream per AI Engine if (NStreams", "streams # it is already separated in phases S =", "') fd.write('\\n') for fd in fds: fd.close() if (NStreams ==", "the Apache License, Version 2.0 (the \"License\"); # you may", "vr = random.randint(-5000,5000) vi = random.randint(-5000,5000) elif (SequenceType == 'Dirac'):", "',dtval.get()) print('PLIO width : ',pliow.get()) print('NPhases : ',NPhases_s.get()) print('NStreams :", "return # Create the overall signal that will be distributed", "S[p,i,1] = vi PLIOwidth = int(pliow.get()) NSamplesPerLine = int(PLIOwidth/NBitsData) #", "Stream in range(NStreams): FileNames.append('PhaseIn_'+str(Phi)+'_'+str(Stream)+'.txt') # Hash table to associate data" ]
[ "5 item1_price_total = item1_price * item1_quantity print(type(item1)) # str print(type(item1_price))", "item1='phone' item1_price = 100 item1_quantity = 5 item1_price_total = item1_price", "print(type(item1_price)) # int print(type(item1_quantity)) # int print(type(item1_price_total)) # int #", "output: # <class 'str'> # <class 'int'> # <class 'int'>", "print(type(item1_price_total)) # int # output: # <class 'str'> # <class", "# str print(type(item1_price)) # int print(type(item1_quantity)) # int print(type(item1_price_total)) #", "= 5 item1_price_total = item1_price * item1_quantity print(type(item1)) # str", "int print(type(item1_price_total)) # int # output: # <class 'str'> #", "<class 'str'> # <class 'int'> # <class 'int'> # <class", "# int # output: # <class 'str'> # <class 'int'>", "# int print(type(item1_price_total)) # int # output: # <class 'str'>", "item1_price_total = item1_price * item1_quantity print(type(item1)) # str print(type(item1_price)) #", "# <class 'str'> # <class 'int'> # <class 'int'> #", "item1_quantity = 5 item1_price_total = item1_price * item1_quantity print(type(item1)) #", "= 100 item1_quantity = 5 item1_price_total = item1_price * item1_quantity", "# output: # <class 'str'> # <class 'int'> # <class", "100 item1_quantity = 5 item1_price_total = item1_price * item1_quantity print(type(item1))", "print(type(item1)) # str print(type(item1_price)) # int print(type(item1_quantity)) # int print(type(item1_price_total))", "item1_quantity print(type(item1)) # str print(type(item1_price)) # int print(type(item1_quantity)) # int", "int # output: # <class 'str'> # <class 'int'> #", "print(type(item1_quantity)) # int print(type(item1_price_total)) # int # output: # <class", "'str'> # <class 'int'> # <class 'int'> # <class 'int'>", "# int print(type(item1_quantity)) # int print(type(item1_price_total)) # int # output:", "str print(type(item1_price)) # int print(type(item1_quantity)) # int print(type(item1_price_total)) # int", "* item1_quantity print(type(item1)) # str print(type(item1_price)) # int print(type(item1_quantity)) #", "item1_price = 100 item1_quantity = 5 item1_price_total = item1_price *", "= item1_price * item1_quantity print(type(item1)) # str print(type(item1_price)) # int", "item1_price * item1_quantity print(type(item1)) # str print(type(item1_price)) # int print(type(item1_quantity))", "int print(type(item1_quantity)) # int print(type(item1_price_total)) # int # output: #" ]
[ "<gh_stars>10-100 _base_ = \"./FlowNet512_1.5AugCosyAAEGray_NoiseRandom_AggressiveR_ClipGrad_fxfy1_Dtw01_LogDz_PM10_Flat_Pbr_01_02MasterChefCan.py\" OUTPUT_DIR = \"output/deepim/ycbvPbrSO/FlowNet512_1.5AugCosyAAEGray_NoiseRandom_AggressiveR_ClipGrad_fxfy1_Dtw01_LogDz_PM10_Flat_ycbvPbr_SO/16_36WoodBlock\" DATASETS = dict(TRAIN=(\"ycbv_036_wood_block_train_pbr\",))" ]
[ "import get_page, select_page, process_args from .results import serialize_bookmark, unserialize_bookmark, Page,", "import serialize_bookmark, unserialize_bookmark, Page, Paging __all__ = [ 'OC', 'get_page',", ".paging import get_page, select_page, process_args from .results import serialize_bookmark, unserialize_bookmark,", "unserialize_bookmark, Page, Paging __all__ = [ 'OC', 'get_page', 'select_page', 'serialize_bookmark',", "process_args from .results import serialize_bookmark, unserialize_bookmark, Page, Paging __all__ =", ".columns import OC from .paging import get_page, select_page, process_args from", "serialize_bookmark, unserialize_bookmark, Page, Paging __all__ = [ 'OC', 'get_page', 'select_page',", "import OC from .paging import get_page, select_page, process_args from .results", "[ 'OC', 'get_page', 'select_page', 'serialize_bookmark', 'unserialize_bookmark', 'Page', 'Paging', 'process_args' ]", "__all__ = [ 'OC', 'get_page', 'select_page', 'serialize_bookmark', 'unserialize_bookmark', 'Page', 'Paging',", ".results import serialize_bookmark, unserialize_bookmark, Page, Paging __all__ = [ 'OC',", "OC from .paging import get_page, select_page, process_args from .results import", "<filename>sqlakeyset/__init__.py from .columns import OC from .paging import get_page, select_page,", "select_page, process_args from .results import serialize_bookmark, unserialize_bookmark, Page, Paging __all__", "= [ 'OC', 'get_page', 'select_page', 'serialize_bookmark', 'unserialize_bookmark', 'Page', 'Paging', 'process_args'", "Page, Paging __all__ = [ 'OC', 'get_page', 'select_page', 'serialize_bookmark', 'unserialize_bookmark',", "from .columns import OC from .paging import get_page, select_page, process_args", "from .paging import get_page, select_page, process_args from .results import serialize_bookmark,", "Paging __all__ = [ 'OC', 'get_page', 'select_page', 'serialize_bookmark', 'unserialize_bookmark', 'Page',", "get_page, select_page, process_args from .results import serialize_bookmark, unserialize_bookmark, Page, Paging", "from .results import serialize_bookmark, unserialize_bookmark, Page, Paging __all__ = [" ]
[ "if pass_is_training else layer(net) endpoints['layer%d' % i] = net tf.add_to_collection(tf.GraphKeys.UPDATE_OPS,", "padding=padding, activation=None, use_bias=True, # not self.config.batch_norm, name=os.path.join(self.variable_scope, 'layer%d' %i, layer_type),", "= layers.LowRankLocallyConnected2D( filters=chout, kernel_size=(kernel_size, kernel_size), strides=(strides, strides), padding=padding, activation=None, use_bias=not", "= net tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, layer.updates) self.add_update(layer.updates) logits = net return logits,", "2.0 (the \"License\"); # you may not use this file", "images for i, (pass_is_training, layer) in enumerate( zip(self.pass_is_training_list, self.layers_list)): net", "# Append position channels. net = tf.concat([images, utils.position_channels(images)], axis=3) else:", "from __future__ import print_function import copy import os import tensorflow.compat.v1", "* self.config.rank), kernel_size=kernel_size, strides=(strides, strides), padding=padding, activation=None, use_bias=not self.config.batch_norm, kernel_initializer=self.config.kernel_initializer,", "from __future__ import division from __future__ import print_function import copy", "> 0 for %s layer.' % layer_type) chout = int((self.config.rank", "chin = chout self.layers_list.append(layer) self.pass_is_training_list.append(False) if self.config.batch_norm: layer = tf.keras.layers.BatchNormalization(", "from low_rank_local_connectivity import utils MOMENTUM = 0.9 EPS = 1e-5", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "by a fully connected layer. Changes to the model architecture", "% i] = net tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, layer.updates) self.add_update(layer.updates) logits = net", "if self.config.batch_norm: layer = tf.keras.layers.BatchNormalization( trainable=True, momentum=MOMENTUM, epsilon=EPS) self.layers_list.append(layer) self.pass_is_training_list.append(True)", "Copyright 2022 The Google Research Authors. # # Licensed under", "activation=None, use_bias=True, # not self.config.batch_norm, name=os.path.join(self.variable_scope, 'layer%d' %i, layer_type), kernel_initializer=self.config.kernel_initializer)", "> 0 for %s layer.' % layer_type) chout = num_filters", "self.config.coord_conv: # Append position channels. net = tf.concat([images, utils.position_channels(images)], axis=3)", "%i, layer_type), kernel_initializer=self.config.kernel_initializer, combining_weights_initializer=( self.config.combining_weights_initializer), spatial_rank=self.config.rank, normalize_weights=self.config.normalize_weights, input_dependent=config.input_dependent, share_row_combining_weights=self.config.share_row_combining_weights, share_col_combining_weights=self.config.share_col_combining_weights)", "division from __future__ import print_function import copy import os import", "self.pass_is_training_list.append(False) def __call__(self, images, is_training): endpoints = {} if self.config.coord_conv:", "layer.' % layer_type) chout = num_filters layer = layers.LowRankLocallyConnected2D( filters=chout,", "config, variable_scope='simple_network'): super(SimpleNetwork, self).__init__() self.variable_scope = variable_scope self.config = copy.deepcopy(config)", "import os import tensorflow.compat.v1 as tf from low_rank_local_connectivity import layers", "layer = tf.keras.layers.LocallyConnected2D( filters=chout, kernel_size=(kernel_size, kernel_size), strides=(strides, strides), padding=padding, activation=None,", "self.config.batch_norm, name=os.path.join(self.variable_scope, 'layer%d' %i, layer_type), kernel_initializer=self.config.kernel_initializer) elif layer_type == 'low_rank_locally_connected2d':", "kernel_initializer=self.config.kernel_initializer, name=os.path.join(self.variable_scope, 'layer%d' %i, layer_type)) elif layer_type == 'locally_connected2d': #", "use this file except in compliance with the License. #", "use_bias=True, name='logits')) self.pass_is_training_list.append(False) def __call__(self, images, is_training): endpoints = {}", "two coordinate conv channels. input_channels = input_channels + 2 if", "% layer_type) chout = int((self.config.rank * chin + num_filters) /", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "= self.config.num_filters_list depth = len(filters_list) self.pass_is_training_list = [] self.layers_list =", "MOMENTUM = 0.9 EPS = 1e-5 class SimpleNetwork(tf.keras.Model): \"\"\"Locally Connected", "License. # You may obtain a copy of the License", "%i, layer_type), kernel_initializer=self.config.kernel_initializer) elif layer_type == 'low_rank_locally_connected2d': if self.config.rank <", "layers from low_rank_local_connectivity import utils MOMENTUM = 0.9 EPS =", "elif layer_type == 'low_rank_locally_connected2d': if self.config.rank < 1: raise ValueError('rank", "kernel_initializer=self.config.kernel_initializer) elif layer_type == 'low_rank_locally_connected2d': if self.config.rank < 1: raise", "under the License is distributed on an \"AS IS\" BASIS,", "License for the specific language governing permissions and # limitations", "name=os.path.join(self.variable_scope, 'layer%d' %i, layer_type)) elif layer_type == 'wide_conv2d': # Conv.", "to the model architecture can be made by modifying simple_model_config.py", "conv/locally_connected/wide_conv/low_rank_locally_connected layers followed by a fully connected layer. Changes to", "layer_type == 'conv2d': chout = num_filters layer = tf.keras.layers.Conv2D( filters=chout,", "image classification. The model is multiple conv/locally_connected/wide_conv/low_rank_locally_connected layers followed by", "(pass_is_training, layer) in enumerate( zip(self.pass_is_training_list, self.layers_list)): net = layer(net, training=is_training)", "Changes to the model architecture can be made by modifying", "len(self.config.layer_types) < depth: self.config.layer_types.extend( ['conv2d'] * (depth - len(self.config.layer_types))) chin", "% layer_type) chin = chout self.layers_list.append(layer) self.pass_is_training_list.append(False) if self.config.batch_norm: layer", "self.layers_list)): net = layer(net, training=is_training) if pass_is_training else layer(net) endpoints['layer%d'", "variable_scope='simple_network'): super(SimpleNetwork, self).__init__() self.variable_scope = variable_scope self.config = copy.deepcopy(config) filters_list", "num_filters layer = tf.keras.layers.Conv2D( filters=chout, kernel_size=kernel_size, strides=(strides, strides), padding=padding, activation=None,", "self.config.num_channels if self.config.coord_conv: # Add two coordinate conv channels. input_channels", "depth = len(filters_list) self.pass_is_training_list = [] self.layers_list = [] if", "= self.config.num_channels if self.config.coord_conv: # Add two coordinate conv channels.", "layer_type == 'wide_conv2d': # Conv. layer with equivalent params to", "enumerate(zip( self.config.kernel_size_list, filters_list, self.config.strides_list, self.config.layer_types)): padding = 'valid' if layer_type", "by modifying simple_model_config.py file. \"\"\" from __future__ import absolute_import from", "# Conv. layer with equivalent params to low rank locally", "filters_list, self.config.strides_list, self.config.layer_types)): padding = 'valid' if layer_type == 'conv2d':", "chout = num_filters layer = layers.LowRankLocallyConnected2D( filters=chout, kernel_size=(kernel_size, kernel_size), strides=(strides,", "/ float( chin + num_filters) * num_filters) layer = tf.keras.layers.Conv2D(", "classification. The model is multiple conv/locally_connected/wide_conv/low_rank_locally_connected layers followed by a", "from __future__ import absolute_import from __future__ import division from __future__", "in compliance with the License. # You may obtain a", "= 1e-5 class SimpleNetwork(tf.keras.Model): \"\"\"Locally Connected Network.\"\"\" def __init__(self, config,", "chin + num_filters) / float( chin + num_filters) * num_filters)", "self.config.combining_weights_initializer), spatial_rank=self.config.rank, normalize_weights=self.config.normalize_weights, input_dependent=config.input_dependent, share_row_combining_weights=self.config.share_row_combining_weights, share_col_combining_weights=self.config.share_col_combining_weights) else: raise ValueError('Can not", "int(num_filters * self.config.rank), kernel_size=kernel_size, strides=(strides, strides), padding=padding, activation=None, use_bias=not self.config.batch_norm,", "software # distributed under the License is distributed on an", "for i, (kernel_size, num_filters, strides, layer_type) in enumerate(zip( self.config.kernel_size_list, filters_list,", "i < (depth-1) else int(num_filters * self.config.rank), kernel_size=kernel_size, strides=(strides, strides),", "i, (kernel_size, num_filters, strides, layer_type) in enumerate(zip( self.config.kernel_size_list, filters_list, self.config.strides_list,", "layer_type) in enumerate(zip( self.config.kernel_size_list, filters_list, self.config.strides_list, self.config.layer_types)): padding = 'valid'", "i, (pass_is_training, layer) in enumerate( zip(self.pass_is_training_list, self.layers_list)): net = layer(net,", "tf.concat([images, utils.position_channels(images)], axis=3) else: net = images for i, (pass_is_training,", "depth: self.config.layer_types.extend( ['conv2d'] * (depth - len(self.config.layer_types))) chin = input_channels", "strides=(strides, strides), padding=padding, activation=None, use_bias=not self.config.batch_norm, kernel_initializer=self.config.kernel_initializer, name=os.path.join(self.variable_scope, 'layer%d' %i,", "images, is_training): endpoints = {} if self.config.coord_conv: # Append position", "__future__ import division from __future__ import print_function import copy import", "filters_list = self.config.num_filters_list depth = len(filters_list) self.pass_is_training_list = [] self.layers_list", "file. \"\"\" from __future__ import absolute_import from __future__ import division", "= 0.9 EPS = 1e-5 class SimpleNetwork(tf.keras.Model): \"\"\"Locally Connected Network.\"\"\"", "num_filters layer = tf.keras.layers.LocallyConnected2D( filters=chout, kernel_size=(kernel_size, kernel_size), strides=(strides, strides), padding=padding,", "self.layers_list.append(layer) self.pass_is_training_list.append(False) if self.config.global_avg_pooling: self.layers_list.append(tf.keras.layers.GlobalAveragePooling2D()) else: self.layers_list.append(tf.keras.layers.Flatten()) self.pass_is_training_list.append(False) self.layers_list.append(tf.keras.layers.Dense( units=self.config.num_classes,", "Google Research Authors. # # Licensed under the Apache License,", "= len(filters_list) self.pass_is_training_list = [] self.layers_list = [] if self.config.num_channels", "Conv. layer with equivalent params to low rank locally connected.", "i] = net tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, layer.updates) self.add_update(layer.updates) logits = net return", "made by modifying simple_model_config.py file. \"\"\" from __future__ import absolute_import", "and # limitations under the License. \"\"\"Simple model for image", "layer = tf.keras.layers.Conv2D( filters=chout if i < (depth-1) else int(num_filters", "* num_filters) layer = tf.keras.layers.Conv2D( filters=chout if i < (depth-1)", "'conv2d': chout = num_filters layer = tf.keras.layers.Conv2D( filters=chout, kernel_size=kernel_size, strides=(strides,", "= variable_scope self.config = copy.deepcopy(config) filters_list = self.config.num_filters_list depth =", "layer_type)) elif layer_type == 'wide_conv2d': # Conv. layer with equivalent", "be > 0 for %s layer.' % layer_type) chout =", "OF ANY KIND, either express or implied. # See the", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "ANY KIND, either express or implied. # See the License", "See the License for the specific language governing permissions and", "conv channels. input_channels = input_channels + 2 if len(self.config.layer_types) <", "layer %s type.' % layer_type) chin = chout self.layers_list.append(layer) self.pass_is_training_list.append(False)", "+ 2 if len(self.config.layer_types) < depth: self.config.layer_types.extend( ['conv2d'] * (depth", "the License. # You may obtain a copy of the", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "for the specific language governing permissions and # limitations under", "%s layer.' % layer_type) chout = int((self.config.rank * chin +", "simple_model_config.py file. \"\"\" from __future__ import absolute_import from __future__ import", "= copy.deepcopy(config) filters_list = self.config.num_filters_list depth = len(filters_list) self.pass_is_training_list =", "to in writing, software # distributed under the License is", "'layer%d' %i, layer_type)) elif layer_type == 'wide_conv2d': # Conv. layer", "# See the License for the specific language governing permissions", "be made by modifying simple_model_config.py file. \"\"\" from __future__ import", "or agreed to in writing, software # distributed under the", "0.9 EPS = 1e-5 class SimpleNetwork(tf.keras.Model): \"\"\"Locally Connected Network.\"\"\" def", "# Add two coordinate conv channels. input_channels = input_channels +", "required by applicable law or agreed to in writing, software", "model is multiple conv/locally_connected/wide_conv/low_rank_locally_connected layers followed by a fully connected", "net = images for i, (pass_is_training, layer) in enumerate( zip(self.pass_is_training_list,", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "with the License. # You may obtain a copy of", "else: self.layers_list.append(tf.keras.layers.Flatten()) self.pass_is_training_list.append(False) self.layers_list.append(tf.keras.layers.Dense( units=self.config.num_classes, activation=None, use_bias=True, name='logits')) self.pass_is_training_list.append(False) def", "__init__(self, config, variable_scope='simple_network'): super(SimpleNetwork, self).__init__() self.variable_scope = variable_scope self.config =", "is multiple conv/locally_connected/wide_conv/low_rank_locally_connected layers followed by a fully connected layer.", "layer_type) chout = int((self.config.rank * chin + num_filters) / float(", "the License. \"\"\"Simple model for image classification. The model is", "compliance with the License. # You may obtain a copy", "layer_type)) elif layer_type == 'locally_connected2d': # Full locally connected layer.", "agreed to in writing, software # distributed under the License", "class SimpleNetwork(tf.keras.Model): \"\"\"Locally Connected Network.\"\"\" def __init__(self, config, variable_scope='simple_network'): super(SimpleNetwork,", "self.config.strides_list, self.config.layer_types)): padding = 'valid' if layer_type == 'conv2d': chout", "distributed under the License is distributed on an \"AS IS\"", "connected. if self.config.rank < 1: raise ValueError('rank should be >", "tf.keras.layers.LocallyConnected2D( filters=chout, kernel_size=(kernel_size, kernel_size), strides=(strides, strides), padding=padding, activation=None, use_bias=True, #", "endpoints['layer%d' % i] = net tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, layer.updates) self.add_update(layer.updates) logits =", "raise ValueError('num_channels should be > 0') input_channels = self.config.num_channels if", "raise ValueError('Can not recognize layer %s type.' % layer_type) chin", "elif layer_type == 'locally_connected2d': # Full locally connected layer. chout", "be > 0') input_channels = self.config.num_channels if self.config.coord_conv: # Add", "express or implied. # See the License for the specific", "net = layer(net, training=is_training) if pass_is_training else layer(net) endpoints['layer%d' %", "% layer_type) chout = num_filters layer = layers.LowRankLocallyConnected2D( filters=chout, kernel_size=(kernel_size,", "except in compliance with the License. # You may obtain", "%s type.' % layer_type) chin = chout self.layers_list.append(layer) self.pass_is_training_list.append(False) if", "Licensed under the Apache License, Version 2.0 (the \"License\"); #", "rank locally connected. if self.config.rank < 1: raise ValueError('rank should", "not use this file except in compliance with the License.", "EPS = 1e-5 class SimpleNetwork(tf.keras.Model): \"\"\"Locally Connected Network.\"\"\" def __init__(self,", "if layer_type == 'conv2d': chout = num_filters layer = tf.keras.layers.Conv2D(", "writing, software # distributed under the License is distributed on", "equivalent params to low rank locally connected. if self.config.rank <", "copy import os import tensorflow.compat.v1 as tf from low_rank_local_connectivity import", "kernel_size=(kernel_size, kernel_size), strides=(strides, strides), padding=padding, activation=None, use_bias=not self.config.batch_norm, name=os.path.join(self.variable_scope, 'layer%d'", "you may not use this file except in compliance with", "self.layers_list.append(tf.keras.layers.GlobalAveragePooling2D()) else: self.layers_list.append(tf.keras.layers.Flatten()) self.pass_is_training_list.append(False) self.layers_list.append(tf.keras.layers.Dense( units=self.config.num_classes, activation=None, use_bias=True, name='logits')) self.pass_is_training_list.append(False)", "position channels. net = tf.concat([images, utils.position_channels(images)], axis=3) else: net =", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "in enumerate( zip(self.pass_is_training_list, self.layers_list)): net = layer(net, training=is_training) if pass_is_training", "2022 The Google Research Authors. # # Licensed under the", "else: raise ValueError('Can not recognize layer %s type.' % layer_type)", "self.pass_is_training_list = [] self.layers_list = [] if self.config.num_channels < 1:", "model for image classification. The model is multiple conv/locally_connected/wide_conv/low_rank_locally_connected layers", "kernel_size=(kernel_size, kernel_size), strides=(strides, strides), padding=padding, activation=None, use_bias=True, # not self.config.batch_norm,", "low rank locally connected. if self.config.rank < 1: raise ValueError('rank", "CONDITIONS OF ANY KIND, either express or implied. # See", "not recognize layer %s type.' % layer_type) chin = chout", "use_bias=not self.config.batch_norm, name=os.path.join(self.variable_scope, 'layer%d' %i, layer_type), kernel_initializer=self.config.kernel_initializer, combining_weights_initializer=( self.config.combining_weights_initializer), spatial_rank=self.config.rank,", "zip(self.pass_is_training_list, self.layers_list)): net = layer(net, training=is_training) if pass_is_training else layer(net)", "layer_type == 'locally_connected2d': # Full locally connected layer. chout =", "'layer%d' %i, layer_type), kernel_initializer=self.config.kernel_initializer, combining_weights_initializer=( self.config.combining_weights_initializer), spatial_rank=self.config.rank, normalize_weights=self.config.normalize_weights, input_dependent=config.input_dependent, share_row_combining_weights=self.config.share_row_combining_weights,", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "as tf from low_rank_local_connectivity import layers from low_rank_local_connectivity import utils", "(depth-1) else int(num_filters * self.config.rank), kernel_size=kernel_size, strides=(strides, strides), padding=padding, activation=None,", "not self.config.batch_norm, name=os.path.join(self.variable_scope, 'layer%d' %i, layer_type), kernel_initializer=self.config.kernel_initializer) elif layer_type ==", "self.config.batch_norm, kernel_initializer=self.config.kernel_initializer, name=os.path.join(self.variable_scope, 'layer%d' %i, layer_type)) elif layer_type == 'locally_connected2d':", "strides=(strides, strides), padding=padding, activation=None, use_bias=not self.config.batch_norm, name=os.path.join(self.variable_scope, 'layer%d' %i, layer_type),", "chin + num_filters) * num_filters) layer = tf.keras.layers.Conv2D( filters=chout if", "def __init__(self, config, variable_scope='simple_network'): super(SimpleNetwork, self).__init__() self.variable_scope = variable_scope self.config", "if self.config.coord_conv: # Add two coordinate conv channels. input_channels =", "# limitations under the License. \"\"\"Simple model for image classification.", "governing permissions and # limitations under the License. \"\"\"Simple model", "permissions and # limitations under the License. \"\"\"Simple model for", "epsilon=EPS) self.layers_list.append(layer) self.pass_is_training_list.append(True) layer = tf.keras.layers.ReLU() self.layers_list.append(layer) self.pass_is_training_list.append(False) if self.config.global_avg_pooling:", "kernel_size), strides=(strides, strides), padding=padding, activation=None, use_bias=not self.config.batch_norm, name=os.path.join(self.variable_scope, 'layer%d' %i,", "channels. net = tf.concat([images, utils.position_channels(images)], axis=3) else: net = images", "= tf.concat([images, utils.position_channels(images)], axis=3) else: net = images for i,", "activation=None, use_bias=not self.config.batch_norm, name=os.path.join(self.variable_scope, 'layer%d' %i, layer_type), kernel_initializer=self.config.kernel_initializer, combining_weights_initializer=( self.config.combining_weights_initializer),", "low_rank_local_connectivity import layers from low_rank_local_connectivity import utils MOMENTUM = 0.9", "len(self.config.layer_types))) chin = input_channels for i, (kernel_size, num_filters, strides, layer_type)", "OR CONDITIONS OF ANY KIND, either express or implied. #", "filters=chout, kernel_size=(kernel_size, kernel_size), strides=(strides, strides), padding=padding, activation=None, use_bias=True, # not", "multiple conv/locally_connected/wide_conv/low_rank_locally_connected layers followed by a fully connected layer. Changes", "__future__ import print_function import copy import os import tensorflow.compat.v1 as", "Add two coordinate conv channels. input_channels = input_channels + 2", "the License is distributed on an \"AS IS\" BASIS, #", "should be > 0 for %s layer.' % layer_type) chout", "Connected Network.\"\"\" def __init__(self, config, variable_scope='simple_network'): super(SimpleNetwork, self).__init__() self.variable_scope =", "0') input_channels = self.config.num_channels if self.config.coord_conv: # Add two coordinate", "> 0') input_channels = self.config.num_channels if self.config.coord_conv: # Add two", "name=os.path.join(self.variable_scope, 'layer%d' %i, layer_type), kernel_initializer=self.config.kernel_initializer) elif layer_type == 'low_rank_locally_connected2d': if", "if self.config.global_avg_pooling: self.layers_list.append(tf.keras.layers.GlobalAveragePooling2D()) else: self.layers_list.append(tf.keras.layers.Flatten()) self.pass_is_training_list.append(False) self.layers_list.append(tf.keras.layers.Dense( units=self.config.num_classes, activation=None, use_bias=True,", "= num_filters layer = tf.keras.layers.LocallyConnected2D( filters=chout, kernel_size=(kernel_size, kernel_size), strides=(strides, strides),", "for image classification. The model is multiple conv/locally_connected/wide_conv/low_rank_locally_connected layers followed", "= [] self.layers_list = [] if self.config.num_channels < 1: raise", "'layer%d' %i, layer_type), kernel_initializer=self.config.kernel_initializer) elif layer_type == 'low_rank_locally_connected2d': if self.config.rank", "= tf.keras.layers.LocallyConnected2D( filters=chout, kernel_size=(kernel_size, kernel_size), strides=(strides, strides), padding=padding, activation=None, use_bias=True,", "followed by a fully connected layer. Changes to the model", "float( chin + num_filters) * num_filters) layer = tf.keras.layers.Conv2D( filters=chout", "kernel_size), strides=(strides, strides), padding=padding, activation=None, use_bias=True, # not self.config.batch_norm, name=os.path.join(self.variable_scope,", "combining_weights_initializer=( self.config.combining_weights_initializer), spatial_rank=self.config.rank, normalize_weights=self.config.normalize_weights, input_dependent=config.input_dependent, share_row_combining_weights=self.config.share_row_combining_weights, share_col_combining_weights=self.config.share_col_combining_weights) else: raise ValueError('Can", "spatial_rank=self.config.rank, normalize_weights=self.config.normalize_weights, input_dependent=config.input_dependent, share_row_combining_weights=self.config.share_row_combining_weights, share_col_combining_weights=self.config.share_col_combining_weights) else: raise ValueError('Can not recognize", "0 for %s layer.' % layer_type) chout = num_filters layer", "law or agreed to in writing, software # distributed under", "copy.deepcopy(config) filters_list = self.config.num_filters_list depth = len(filters_list) self.pass_is_training_list = []", "\"\"\" from __future__ import absolute_import from __future__ import division from", "layer(net, training=is_training) if pass_is_training else layer(net) endpoints['layer%d' % i] =", "# Full locally connected layer. chout = num_filters layer =", "num_filters) layer = tf.keras.layers.Conv2D( filters=chout if i < (depth-1) else", "layer_type), kernel_initializer=self.config.kernel_initializer) elif layer_type == 'low_rank_locally_connected2d': if self.config.rank < 1:", "self.config.batch_norm, kernel_initializer=self.config.kernel_initializer, name=os.path.join(self.variable_scope, 'layer%d' %i, layer_type)) elif layer_type == 'wide_conv2d':", "in enumerate(zip( self.config.kernel_size_list, filters_list, self.config.strides_list, self.config.layer_types)): padding = 'valid' if", "else int(num_filters * self.config.rank), kernel_size=kernel_size, strides=(strides, strides), padding=padding, activation=None, use_bias=not", "may obtain a copy of the License at # #", "strides), padding=padding, activation=None, use_bias=True, # not self.config.batch_norm, name=os.path.join(self.variable_scope, 'layer%d' %i,", "= num_filters layer = tf.keras.layers.Conv2D( filters=chout, kernel_size=kernel_size, strides=(strides, strides), padding=padding,", "use_bias=not self.config.batch_norm, kernel_initializer=self.config.kernel_initializer, name=os.path.join(self.variable_scope, 'layer%d' %i, layer_type)) elif layer_type ==", "language governing permissions and # limitations under the License. \"\"\"Simple", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "activation=None, use_bias=True, name='logits')) self.pass_is_training_list.append(False) def __call__(self, images, is_training): endpoints =", "'low_rank_locally_connected2d': if self.config.rank < 1: raise ValueError('rank should be >", "locally connected. if self.config.rank < 1: raise ValueError('rank should be", "may not use this file except in compliance with the", "import copy import os import tensorflow.compat.v1 as tf from low_rank_local_connectivity", "os import tensorflow.compat.v1 as tf from low_rank_local_connectivity import layers from", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "locally connected layer. chout = num_filters layer = tf.keras.layers.LocallyConnected2D( filters=chout,", "= tf.keras.layers.BatchNormalization( trainable=True, momentum=MOMENTUM, epsilon=EPS) self.layers_list.append(layer) self.pass_is_training_list.append(True) layer = tf.keras.layers.ReLU()", "net tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, layer.updates) self.add_update(layer.updates) logits = net return logits, endpoints", "endpoints = {} if self.config.coord_conv: # Append position channels. net", "variable_scope self.config = copy.deepcopy(config) filters_list = self.config.num_filters_list depth = len(filters_list)", "this file except in compliance with the License. # You", "import absolute_import from __future__ import division from __future__ import print_function", "'valid' if layer_type == 'conv2d': chout = num_filters layer =", "connected layer. Changes to the model architecture can be made", "The model is multiple conv/locally_connected/wide_conv/low_rank_locally_connected layers followed by a fully", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "= layer(net, training=is_training) if pass_is_training else layer(net) endpoints['layer%d' % i]", "channels. input_channels = input_channels + 2 if len(self.config.layer_types) < depth:", "# # Licensed under the Apache License, Version 2.0 (the", "use_bias=True, # not self.config.batch_norm, name=os.path.join(self.variable_scope, 'layer%d' %i, layer_type), kernel_initializer=self.config.kernel_initializer) elif", "file except in compliance with the License. # You may", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "+ num_filters) * num_filters) layer = tf.keras.layers.Conv2D( filters=chout if i", "normalize_weights=self.config.normalize_weights, input_dependent=config.input_dependent, share_row_combining_weights=self.config.share_row_combining_weights, share_col_combining_weights=self.config.share_col_combining_weights) else: raise ValueError('Can not recognize layer", "strides), padding=padding, activation=None, use_bias=not self.config.batch_norm, kernel_initializer=self.config.kernel_initializer, name=os.path.join(self.variable_scope, 'layer%d' %i, layer_type))", "type.' % layer_type) chin = chout self.layers_list.append(layer) self.pass_is_training_list.append(False) if self.config.batch_norm:", "name=os.path.join(self.variable_scope, 'layer%d' %i, layer_type), kernel_initializer=self.config.kernel_initializer, combining_weights_initializer=( self.config.combining_weights_initializer), spatial_rank=self.config.rank, normalize_weights=self.config.normalize_weights, input_dependent=config.input_dependent,", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "import layers from low_rank_local_connectivity import utils MOMENTUM = 0.9 EPS", "tf.keras.layers.Conv2D( filters=chout, kernel_size=kernel_size, strides=(strides, strides), padding=padding, activation=None, use_bias=not self.config.batch_norm, kernel_initializer=self.config.kernel_initializer,", "should be > 0') input_channels = self.config.num_channels if self.config.coord_conv: #", "self.config.num_channels < 1: raise ValueError('num_channels should be > 0') input_channels", "self.config.batch_norm, name=os.path.join(self.variable_scope, 'layer%d' %i, layer_type), kernel_initializer=self.config.kernel_initializer, combining_weights_initializer=( self.config.combining_weights_initializer), spatial_rank=self.config.rank, normalize_weights=self.config.normalize_weights,", "layer_type) chin = chout self.layers_list.append(layer) self.pass_is_training_list.append(False) if self.config.batch_norm: layer =", "\"\"\"Simple model for image classification. The model is multiple conv/locally_connected/wide_conv/low_rank_locally_connected", "super(SimpleNetwork, self).__init__() self.variable_scope = variable_scope self.config = copy.deepcopy(config) filters_list =", "with equivalent params to low rank locally connected. if self.config.rank", "kernel_initializer=self.config.kernel_initializer, name=os.path.join(self.variable_scope, 'layer%d' %i, layer_type)) elif layer_type == 'wide_conv2d': #", "== 'wide_conv2d': # Conv. layer with equivalent params to low", "int((self.config.rank * chin + num_filters) / float( chin + num_filters)", "momentum=MOMENTUM, epsilon=EPS) self.layers_list.append(layer) self.pass_is_training_list.append(True) layer = tf.keras.layers.ReLU() self.layers_list.append(layer) self.pass_is_training_list.append(False) if", "self.layers_list = [] if self.config.num_channels < 1: raise ValueError('num_channels should", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "layer(net) endpoints['layer%d' % i] = net tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, layer.updates) self.add_update(layer.updates) logits", "input_channels = input_channels + 2 if len(self.config.layer_types) < depth: self.config.layer_types.extend(", "padding = 'valid' if layer_type == 'conv2d': chout = num_filters", "self.layers_list.append(layer) self.pass_is_training_list.append(True) layer = tf.keras.layers.ReLU() self.layers_list.append(layer) self.pass_is_training_list.append(False) if self.config.global_avg_pooling: self.layers_list.append(tf.keras.layers.GlobalAveragePooling2D())", "def __call__(self, images, is_training): endpoints = {} if self.config.coord_conv: #", "= chout self.layers_list.append(layer) self.pass_is_training_list.append(False) if self.config.batch_norm: layer = tf.keras.layers.BatchNormalization( trainable=True,", "self.layers_list.append(tf.keras.layers.Dense( units=self.config.num_classes, activation=None, use_bias=True, name='logits')) self.pass_is_training_list.append(False) def __call__(self, images, is_training):", "import print_function import copy import os import tensorflow.compat.v1 as tf", "or implied. # See the License for the specific language", "[] self.layers_list = [] if self.config.num_channels < 1: raise ValueError('num_channels", "share_row_combining_weights=self.config.share_row_combining_weights, share_col_combining_weights=self.config.share_col_combining_weights) else: raise ValueError('Can not recognize layer %s type.'", "params to low rank locally connected. if self.config.rank < 1:", "self.pass_is_training_list.append(False) if self.config.batch_norm: layer = tf.keras.layers.BatchNormalization( trainable=True, momentum=MOMENTUM, epsilon=EPS) self.layers_list.append(layer)", "self.pass_is_training_list.append(False) if self.config.global_avg_pooling: self.layers_list.append(tf.keras.layers.GlobalAveragePooling2D()) else: self.layers_list.append(tf.keras.layers.Flatten()) self.pass_is_training_list.append(False) self.layers_list.append(tf.keras.layers.Dense( units=self.config.num_classes, activation=None,", "KIND, either express or implied. # See the License for", "specific language governing permissions and # limitations under the License.", "chin = input_channels for i, (kernel_size, num_filters, strides, layer_type) in", "= tf.keras.layers.Conv2D( filters=chout, kernel_size=kernel_size, strides=(strides, strides), padding=padding, activation=None, use_bias=not self.config.batch_norm,", "layer = tf.keras.layers.BatchNormalization( trainable=True, momentum=MOMENTUM, epsilon=EPS) self.layers_list.append(layer) self.pass_is_training_list.append(True) layer =", "to low rank locally connected. if self.config.rank < 1: raise", "kernel_size=kernel_size, strides=(strides, strides), padding=padding, activation=None, use_bias=not self.config.batch_norm, kernel_initializer=self.config.kernel_initializer, name=os.path.join(self.variable_scope, 'layer%d'", "['conv2d'] * (depth - len(self.config.layer_types))) chin = input_channels for i,", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "utils.position_channels(images)], axis=3) else: net = images for i, (pass_is_training, layer)", "a fully connected layer. Changes to the model architecture can", "(the \"License\"); # you may not use this file except", "# you may not use this file except in compliance", "coding=utf-8 # Copyright 2022 The Google Research Authors. # #", "model architecture can be made by modifying simple_model_config.py file. \"\"\"", "self.layers_list.append(tf.keras.layers.Flatten()) self.pass_is_training_list.append(False) self.layers_list.append(tf.keras.layers.Dense( units=self.config.num_classes, activation=None, use_bias=True, name='logits')) self.pass_is_training_list.append(False) def __call__(self,", "tf.keras.layers.Conv2D( filters=chout if i < (depth-1) else int(num_filters * self.config.rank),", "padding=padding, activation=None, use_bias=not self.config.batch_norm, name=os.path.join(self.variable_scope, 'layer%d' %i, layer_type), kernel_initializer=self.config.kernel_initializer, combining_weights_initializer=(", "- len(self.config.layer_types))) chin = input_channels for i, (kernel_size, num_filters, strides,", "Network.\"\"\" def __init__(self, config, variable_scope='simple_network'): super(SimpleNetwork, self).__init__() self.variable_scope = variable_scope", "connected layer. chout = num_filters layer = tf.keras.layers.LocallyConnected2D( filters=chout, kernel_size=(kernel_size,", "modifying simple_model_config.py file. \"\"\" from __future__ import absolute_import from __future__", "if i < (depth-1) else int(num_filters * self.config.rank), kernel_size=kernel_size, strides=(strides,", "name=os.path.join(self.variable_scope, 'layer%d' %i, layer_type)) elif layer_type == 'locally_connected2d': # Full", "num_filters, strides, layer_type) in enumerate(zip( self.config.kernel_size_list, filters_list, self.config.strides_list, self.config.layer_types)): padding", "self.config.rank), kernel_size=kernel_size, strides=(strides, strides), padding=padding, activation=None, use_bias=not self.config.batch_norm, kernel_initializer=self.config.kernel_initializer, name=os.path.join(self.variable_scope,", "import division from __future__ import print_function import copy import os", "layers.LowRankLocallyConnected2D( filters=chout, kernel_size=(kernel_size, kernel_size), strides=(strides, strides), padding=padding, activation=None, use_bias=not self.config.batch_norm,", "'locally_connected2d': # Full locally connected layer. chout = num_filters layer", "# # Unless required by applicable law or agreed to", "training=is_training) if pass_is_training else layer(net) endpoints['layer%d' % i] = net", "1e-5 class SimpleNetwork(tf.keras.Model): \"\"\"Locally Connected Network.\"\"\" def __init__(self, config, variable_scope='simple_network'):", "input_channels + 2 if len(self.config.layer_types) < depth: self.config.layer_types.extend( ['conv2d'] *", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "if len(self.config.layer_types) < depth: self.config.layer_types.extend( ['conv2d'] * (depth - len(self.config.layer_types)))", "< 1: raise ValueError('num_channels should be > 0') input_channels =", "Version 2.0 (the \"License\"); # you may not use this", "input_dependent=config.input_dependent, share_row_combining_weights=self.config.share_row_combining_weights, share_col_combining_weights=self.config.share_col_combining_weights) else: raise ValueError('Can not recognize layer %s", "SimpleNetwork(tf.keras.Model): \"\"\"Locally Connected Network.\"\"\" def __init__(self, config, variable_scope='simple_network'): super(SimpleNetwork, self).__init__()", "(kernel_size, num_filters, strides, layer_type) in enumerate(zip( self.config.kernel_size_list, filters_list, self.config.strides_list, self.config.layer_types)):", "= num_filters layer = layers.LowRankLocallyConnected2D( filters=chout, kernel_size=(kernel_size, kernel_size), strides=(strides, strides),", "from low_rank_local_connectivity import layers from low_rank_local_connectivity import utils MOMENTUM =", "num_filters) * num_filters) layer = tf.keras.layers.Conv2D( filters=chout if i <", "self.variable_scope = variable_scope self.config = copy.deepcopy(config) filters_list = self.config.num_filters_list depth", "__future__ import absolute_import from __future__ import division from __future__ import", "= {} if self.config.coord_conv: # Append position channels. net =", "implied. # See the License for the specific language governing", "== 'low_rank_locally_connected2d': if self.config.rank < 1: raise ValueError('rank should be", "under the Apache License, Version 2.0 (the \"License\"); # you", "elif layer_type == 'wide_conv2d': # Conv. layer with equivalent params", "share_col_combining_weights=self.config.share_col_combining_weights) else: raise ValueError('Can not recognize layer %s type.' %", "* (depth - len(self.config.layer_types))) chin = input_channels for i, (kernel_size,", "print_function import copy import os import tensorflow.compat.v1 as tf from", "%i, layer_type)) elif layer_type == 'locally_connected2d': # Full locally connected", "self).__init__() self.variable_scope = variable_scope self.config = copy.deepcopy(config) filters_list = self.config.num_filters_list", "trainable=True, momentum=MOMENTUM, epsilon=EPS) self.layers_list.append(layer) self.pass_is_training_list.append(True) layer = tf.keras.layers.ReLU() self.layers_list.append(layer) self.pass_is_training_list.append(False)", "by applicable law or agreed to in writing, software #", "layer = tf.keras.layers.ReLU() self.layers_list.append(layer) self.pass_is_training_list.append(False) if self.config.global_avg_pooling: self.layers_list.append(tf.keras.layers.GlobalAveragePooling2D()) else: self.layers_list.append(tf.keras.layers.Flatten())", "Full locally connected layer. chout = num_filters layer = tf.keras.layers.LocallyConnected2D(", "num_filters) / float( chin + num_filters) * num_filters) layer =", "limitations under the License. \"\"\"Simple model for image classification. The", "chout = int((self.config.rank * chin + num_filters) / float( chin", "tf.keras.layers.BatchNormalization( trainable=True, momentum=MOMENTUM, epsilon=EPS) self.layers_list.append(layer) self.pass_is_training_list.append(True) layer = tf.keras.layers.ReLU() self.layers_list.append(layer)", "axis=3) else: net = images for i, (pass_is_training, layer) in", "2 if len(self.config.layer_types) < depth: self.config.layer_types.extend( ['conv2d'] * (depth -", "= 'valid' if layer_type == 'conv2d': chout = num_filters layer", "layer_type) chout = num_filters layer = layers.LowRankLocallyConnected2D( filters=chout, kernel_size=(kernel_size, kernel_size),", "strides), padding=padding, activation=None, use_bias=not self.config.batch_norm, name=os.path.join(self.variable_scope, 'layer%d' %i, layer_type), kernel_initializer=self.config.kernel_initializer,", "layer. Changes to the model architecture can be made by", "self.config = copy.deepcopy(config) filters_list = self.config.num_filters_list depth = len(filters_list) self.pass_is_training_list", "can be made by modifying simple_model_config.py file. \"\"\" from __future__", "else layer(net) endpoints['layer%d' % i] = net tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, layer.updates) self.add_update(layer.updates)", "for %s layer.' % layer_type) chout = int((self.config.rank * chin", "self.layers_list.append(layer) self.pass_is_training_list.append(False) if self.config.batch_norm: layer = tf.keras.layers.BatchNormalization( trainable=True, momentum=MOMENTUM, epsilon=EPS)", "layer_type == 'low_rank_locally_connected2d': if self.config.rank < 1: raise ValueError('rank should", "layers followed by a fully connected layer. Changes to the", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "import utils MOMENTUM = 0.9 EPS = 1e-5 class SimpleNetwork(tf.keras.Model):", "input_channels = self.config.num_channels if self.config.coord_conv: # Add two coordinate conv", "Unless required by applicable law or agreed to in writing,", "filters=chout if i < (depth-1) else int(num_filters * self.config.rank), kernel_size=kernel_size,", "filters=chout, kernel_size=(kernel_size, kernel_size), strides=(strides, strides), padding=padding, activation=None, use_bias=not self.config.batch_norm, name=os.path.join(self.variable_scope,", "layer = layers.LowRankLocallyConnected2D( filters=chout, kernel_size=(kernel_size, kernel_size), strides=(strides, strides), padding=padding, activation=None,", "__call__(self, images, is_training): endpoints = {} if self.config.coord_conv: # Append", "layer. chout = num_filters layer = tf.keras.layers.LocallyConnected2D( filters=chout, kernel_size=(kernel_size, kernel_size),", "the specific language governing permissions and # limitations under the", "{} if self.config.coord_conv: # Append position channels. net = tf.concat([images,", "applicable law or agreed to in writing, software # distributed", "strides=(strides, strides), padding=padding, activation=None, use_bias=True, # not self.config.batch_norm, name=os.path.join(self.variable_scope, 'layer%d'", "< (depth-1) else int(num_filters * self.config.rank), kernel_size=kernel_size, strides=(strides, strides), padding=padding,", "# coding=utf-8 # Copyright 2022 The Google Research Authors. #", "self.config.rank < 1: raise ValueError('rank should be > 0 for", "self.config.layer_types.extend( ['conv2d'] * (depth - len(self.config.layer_types))) chin = input_channels for", "layer_type), kernel_initializer=self.config.kernel_initializer, combining_weights_initializer=( self.config.combining_weights_initializer), spatial_rank=self.config.rank, normalize_weights=self.config.normalize_weights, input_dependent=config.input_dependent, share_row_combining_weights=self.config.share_row_combining_weights, share_col_combining_weights=self.config.share_col_combining_weights) else:", "num_filters layer = layers.LowRankLocallyConnected2D( filters=chout, kernel_size=(kernel_size, kernel_size), strides=(strides, strides), padding=padding,", "enumerate( zip(self.pass_is_training_list, self.layers_list)): net = layer(net, training=is_training) if pass_is_training else", "if self.config.num_channels < 1: raise ValueError('num_channels should be > 0')", "in writing, software # distributed under the License is distributed", "self.config.layer_types)): padding = 'valid' if layer_type == 'conv2d': chout =", "self.config.batch_norm: layer = tf.keras.layers.BatchNormalization( trainable=True, momentum=MOMENTUM, epsilon=EPS) self.layers_list.append(layer) self.pass_is_training_list.append(True) layer", "utils MOMENTUM = 0.9 EPS = 1e-5 class SimpleNetwork(tf.keras.Model): \"\"\"Locally", "ValueError('num_channels should be > 0') input_channels = self.config.num_channels if self.config.coord_conv:", "input_channels for i, (kernel_size, num_filters, strides, layer_type) in enumerate(zip( self.config.kernel_size_list,", "< 1: raise ValueError('rank should be > 0 for %s", "kernel_initializer=self.config.kernel_initializer, combining_weights_initializer=( self.config.combining_weights_initializer), spatial_rank=self.config.rank, normalize_weights=self.config.normalize_weights, input_dependent=config.input_dependent, share_row_combining_weights=self.config.share_row_combining_weights, share_col_combining_weights=self.config.share_col_combining_weights) else: raise", "+ num_filters) / float( chin + num_filters) * num_filters) layer", "pass_is_training else layer(net) endpoints['layer%d' % i] = net tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, layer.updates)", "Authors. # # Licensed under the Apache License, Version 2.0", "= [] if self.config.num_channels < 1: raise ValueError('num_channels should be", "for %s layer.' % layer_type) chout = num_filters layer =", "self.pass_is_training_list.append(True) layer = tf.keras.layers.ReLU() self.layers_list.append(layer) self.pass_is_training_list.append(False) if self.config.global_avg_pooling: self.layers_list.append(tf.keras.layers.GlobalAveragePooling2D()) else:", "tensorflow.compat.v1 as tf from low_rank_local_connectivity import layers from low_rank_local_connectivity import", "the model architecture can be made by modifying simple_model_config.py file.", "License is distributed on an \"AS IS\" BASIS, # WITHOUT", "Append position channels. net = tf.concat([images, utils.position_channels(images)], axis=3) else: net", "ValueError('rank should be > 0 for %s layer.' % layer_type)", "License, Version 2.0 (the \"License\"); # you may not use", "self.config.num_filters_list depth = len(filters_list) self.pass_is_training_list = [] self.layers_list = []", "self.config.global_avg_pooling: self.layers_list.append(tf.keras.layers.GlobalAveragePooling2D()) else: self.layers_list.append(tf.keras.layers.Flatten()) self.pass_is_training_list.append(False) self.layers_list.append(tf.keras.layers.Dense( units=self.config.num_classes, activation=None, use_bias=True, name='logits'))", "# You may obtain a copy of the License at", "tf from low_rank_local_connectivity import layers from low_rank_local_connectivity import utils MOMENTUM", "units=self.config.num_classes, activation=None, use_bias=True, name='logits')) self.pass_is_training_list.append(False) def __call__(self, images, is_training): endpoints", "\"\"\"Locally Connected Network.\"\"\" def __init__(self, config, variable_scope='simple_network'): super(SimpleNetwork, self).__init__() self.variable_scope", "net = tf.concat([images, utils.position_channels(images)], axis=3) else: net = images for", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "architecture can be made by modifying simple_model_config.py file. \"\"\" from", "under the License. \"\"\"Simple model for image classification. The model", "1: raise ValueError('num_channels should be > 0') input_channels = self.config.num_channels", "the License for the specific language governing permissions and #", "Apache License, Version 2.0 (the \"License\"); # you may not", "License. \"\"\"Simple model for image classification. The model is multiple", "either express or implied. # See the License for the", "import tensorflow.compat.v1 as tf from low_rank_local_connectivity import layers from low_rank_local_connectivity", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "* chin + num_filters) / float( chin + num_filters) *", "name='logits')) self.pass_is_training_list.append(False) def __call__(self, images, is_training): endpoints = {} if", "1: raise ValueError('rank should be > 0 for %s layer.'", "= tf.keras.layers.Conv2D( filters=chout if i < (depth-1) else int(num_filters *", "self.config.coord_conv: # Add two coordinate conv channels. input_channels = input_channels", "coordinate conv channels. input_channels = input_channels + 2 if len(self.config.layer_types)", "self.config.kernel_size_list, filters_list, self.config.strides_list, self.config.layer_types)): padding = 'valid' if layer_type ==", "ValueError('Can not recognize layer %s type.' % layer_type) chin =", "recognize layer %s type.' % layer_type) chin = chout self.layers_list.append(layer)", "self.pass_is_training_list.append(False) self.layers_list.append(tf.keras.layers.Dense( units=self.config.num_classes, activation=None, use_bias=True, name='logits')) self.pass_is_training_list.append(False) def __call__(self, images,", "if self.config.coord_conv: # Append position channels. net = tf.concat([images, utils.position_channels(images)],", "else: net = images for i, (pass_is_training, layer) in enumerate(", "activation=None, use_bias=not self.config.batch_norm, kernel_initializer=self.config.kernel_initializer, name=os.path.join(self.variable_scope, 'layer%d' %i, layer_type)) elif layer_type", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "len(filters_list) self.pass_is_training_list = [] self.layers_list = [] if self.config.num_channels <", "= int((self.config.rank * chin + num_filters) / float( chin +", "= input_channels for i, (kernel_size, num_filters, strides, layer_type) in enumerate(zip(", "chout self.layers_list.append(layer) self.pass_is_training_list.append(False) if self.config.batch_norm: layer = tf.keras.layers.BatchNormalization( trainable=True, momentum=MOMENTUM,", "low_rank_local_connectivity import utils MOMENTUM = 0.9 EPS = 1e-5 class", "raise ValueError('rank should be > 0 for %s layer.' %", "[] if self.config.num_channels < 1: raise ValueError('num_channels should be >", "layer = tf.keras.layers.Conv2D( filters=chout, kernel_size=kernel_size, strides=(strides, strides), padding=padding, activation=None, use_bias=not", "# not self.config.batch_norm, name=os.path.join(self.variable_scope, 'layer%d' %i, layer_type), kernel_initializer=self.config.kernel_initializer) elif layer_type", "absolute_import from __future__ import division from __future__ import print_function import", "fully connected layer. Changes to the model architecture can be", "%i, layer_type)) elif layer_type == 'wide_conv2d': # Conv. layer with", "== 'conv2d': chout = num_filters layer = tf.keras.layers.Conv2D( filters=chout, kernel_size=kernel_size,", "\"License\"); # you may not use this file except in", "layer with equivalent params to low rank locally connected. if", "'layer%d' %i, layer_type)) elif layer_type == 'locally_connected2d': # Full locally", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "filters=chout, kernel_size=kernel_size, strides=(strides, strides), padding=padding, activation=None, use_bias=not self.config.batch_norm, kernel_initializer=self.config.kernel_initializer, name=os.path.join(self.variable_scope,", "== 'locally_connected2d': # Full locally connected layer. chout = num_filters", "chout = num_filters layer = tf.keras.layers.LocallyConnected2D( filters=chout, kernel_size=(kernel_size, kernel_size), strides=(strides,", "# distributed under the License is distributed on an \"AS", "# Unless required by applicable law or agreed to in", "is_training): endpoints = {} if self.config.coord_conv: # Append position channels.", "= input_channels + 2 if len(self.config.layer_types) < depth: self.config.layer_types.extend( ['conv2d']", "layer.' % layer_type) chout = int((self.config.rank * chin + num_filters)", "The Google Research Authors. # # Licensed under the Apache", "# Copyright 2022 The Google Research Authors. # # Licensed", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "0 for %s layer.' % layer_type) chout = int((self.config.rank *", "tf.keras.layers.ReLU() self.layers_list.append(layer) self.pass_is_training_list.append(False) if self.config.global_avg_pooling: self.layers_list.append(tf.keras.layers.GlobalAveragePooling2D()) else: self.layers_list.append(tf.keras.layers.Flatten()) self.pass_is_training_list.append(False) self.layers_list.append(tf.keras.layers.Dense(", "layer) in enumerate( zip(self.pass_is_training_list, self.layers_list)): net = layer(net, training=is_training) if", "if self.config.rank < 1: raise ValueError('rank should be > 0", "You may obtain a copy of the License at #", "padding=padding, activation=None, use_bias=not self.config.batch_norm, kernel_initializer=self.config.kernel_initializer, name=os.path.join(self.variable_scope, 'layer%d' %i, layer_type)) elif", "'wide_conv2d': # Conv. layer with equivalent params to low rank", "= tf.keras.layers.ReLU() self.layers_list.append(layer) self.pass_is_training_list.append(False) if self.config.global_avg_pooling: self.layers_list.append(tf.keras.layers.GlobalAveragePooling2D()) else: self.layers_list.append(tf.keras.layers.Flatten()) self.pass_is_training_list.append(False)", "chout = num_filters layer = tf.keras.layers.Conv2D( filters=chout, kernel_size=kernel_size, strides=(strides, strides),", "= images for i, (pass_is_training, layer) in enumerate( zip(self.pass_is_training_list, self.layers_list)):", "< depth: self.config.layer_types.extend( ['conv2d'] * (depth - len(self.config.layer_types))) chin =", "%s layer.' % layer_type) chout = num_filters layer = layers.LowRankLocallyConnected2D(", "the Apache License, Version 2.0 (the \"License\"); # you may", "strides, layer_type) in enumerate(zip( self.config.kernel_size_list, filters_list, self.config.strides_list, self.config.layer_types)): padding =", "(depth - len(self.config.layer_types))) chin = input_channels for i, (kernel_size, num_filters,", "Research Authors. # # Licensed under the Apache License, Version", "for i, (pass_is_training, layer) in enumerate( zip(self.pass_is_training_list, self.layers_list)): net =" ]
[ "Adafruit Industries # SPDX-License-Identifier: MIT import time import board import", "time.sleep(2) for i in range(cycles): print(icm.gyro) icm.gyro_data_rate_divisor = 255 #", "# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries # SPDX-License-Identifier: MIT", "busio.I2C(board.SCL, board.SDA) icm = ICM20948(i2c) # Cycle between two data", "can see how # the data rate affects the resolution", "# Best viewed in the Mu serial plotter where you", "affects the resolution of the data while True: icm.gyro_data_rate_divisor =", "icm = ICM20948(i2c) # Cycle between two data rates #", "maximum print(\"Data Rate:\", icm.gyro_data_rate) time.sleep(2) for i in range(cycles): print(icm.gyro)", "serial plotter where you can see how # the data", "import board import busio from adafruit_icm20x import ICM20948 cycles =", "minimum print(\"Data Rate:\", icm.gyro_data_rate) time.sleep(2) for i in range(cycles): print(icm.gyro)", "the Mu serial plotter where you can see how #", "import busio from adafruit_icm20x import ICM20948 cycles = 200 i2c", "for Adafruit Industries # SPDX-License-Identifier: MIT import time import board", "see how # the data rate affects the resolution of", "while True: icm.gyro_data_rate_divisor = 0 # minimum print(\"Data Rate:\", icm.gyro_data_rate)", "viewed in the Mu serial plotter where you can see", "SPDX-License-Identifier: MIT import time import board import busio from adafruit_icm20x", "in range(cycles): print(icm.gyro) icm.gyro_data_rate_divisor = 255 # maximum print(\"Data Rate:\",", "Mu serial plotter where you can see how # the", "2021 ladyada for Adafruit Industries # SPDX-License-Identifier: MIT import time", "the data while True: icm.gyro_data_rate_divisor = 0 # minimum print(\"Data", "import ICM20948 cycles = 200 i2c = busio.I2C(board.SCL, board.SDA) icm", "plotter where you can see how # the data rate", "= 200 i2c = busio.I2C(board.SCL, board.SDA) icm = ICM20948(i2c) #", "from adafruit_icm20x import ICM20948 cycles = 200 i2c = busio.I2C(board.SCL,", "icm.gyro_data_rate_divisor = 255 # maximum print(\"Data Rate:\", icm.gyro_data_rate) time.sleep(2) for", "the data rate affects the resolution of the data while", "cycles = 200 i2c = busio.I2C(board.SCL, board.SDA) icm = ICM20948(i2c)", "<reponame>jacoblb64/pico_rgb_keypad_hid # SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries # SPDX-License-Identifier:", "rate affects the resolution of the data while True: icm.gyro_data_rate_divisor", "data rate affects the resolution of the data while True:", "range(cycles): print(icm.gyro) icm.gyro_data_rate_divisor = 255 # maximum print(\"Data Rate:\", icm.gyro_data_rate)", "icm.gyro_data_rate) time.sleep(2) for i in range(cycles): print(icm.gyro) icm.gyro_data_rate_divisor = 255", "= 0 # minimum print(\"Data Rate:\", icm.gyro_data_rate) time.sleep(2) for i", "Industries # SPDX-License-Identifier: MIT import time import board import busio", "SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries # SPDX-License-Identifier: MIT import", "ICM20948 cycles = 200 i2c = busio.I2C(board.SCL, board.SDA) icm =", "you can see how # the data rate affects the", "board import busio from adafruit_icm20x import ICM20948 cycles = 200", "of the data while True: icm.gyro_data_rate_divisor = 0 # minimum", "255 # maximum print(\"Data Rate:\", icm.gyro_data_rate) time.sleep(2) for i in", "Rate:\", icm.gyro_data_rate) time.sleep(2) for i in range(cycles): print(icm.gyro) icm.gyro_data_rate_divisor =", "where you can see how # the data rate affects", "two data rates # Best viewed in the Mu serial", "= 255 # maximum print(\"Data Rate:\", icm.gyro_data_rate) time.sleep(2) for i", "ICM20948(i2c) # Cycle between two data rates # Best viewed", "= busio.I2C(board.SCL, board.SDA) icm = ICM20948(i2c) # Cycle between two", "between two data rates # Best viewed in the Mu", "# maximum print(\"Data Rate:\", icm.gyro_data_rate) time.sleep(2) for i in range(cycles):", "for i in range(cycles): print(icm.gyro) icm.gyro_data_rate_divisor = 255 # maximum", "i2c = busio.I2C(board.SCL, board.SDA) icm = ICM20948(i2c) # Cycle between", "# minimum print(\"Data Rate:\", icm.gyro_data_rate) time.sleep(2) for i in range(cycles):", "print(\"Data Rate:\", icm.gyro_data_rate) time.sleep(2) for i in range(cycles): print(icm.gyro) icm.gyro_data_rate_divisor", "rates # Best viewed in the Mu serial plotter where", "data while True: icm.gyro_data_rate_divisor = 0 # minimum print(\"Data Rate:\",", "busio from adafruit_icm20x import ICM20948 cycles = 200 i2c =", "the resolution of the data while True: icm.gyro_data_rate_divisor = 0", "ladyada for Adafruit Industries # SPDX-License-Identifier: MIT import time import", "200 i2c = busio.I2C(board.SCL, board.SDA) icm = ICM20948(i2c) # Cycle", "# the data rate affects the resolution of the data", "= ICM20948(i2c) # Cycle between two data rates # Best", "i in range(cycles): print(icm.gyro) icm.gyro_data_rate_divisor = 255 # maximum print(\"Data", "how # the data rate affects the resolution of the", "True: icm.gyro_data_rate_divisor = 0 # minimum print(\"Data Rate:\", icm.gyro_data_rate) time.sleep(2)", "import time import board import busio from adafruit_icm20x import ICM20948", "data rates # Best viewed in the Mu serial plotter", "0 # minimum print(\"Data Rate:\", icm.gyro_data_rate) time.sleep(2) for i in", "adafruit_icm20x import ICM20948 cycles = 200 i2c = busio.I2C(board.SCL, board.SDA)", "Cycle between two data rates # Best viewed in the", "time import board import busio from adafruit_icm20x import ICM20948 cycles", "board.SDA) icm = ICM20948(i2c) # Cycle between two data rates", "icm.gyro_data_rate_divisor = 0 # minimum print(\"Data Rate:\", icm.gyro_data_rate) time.sleep(2) for", "# SPDX-License-Identifier: MIT import time import board import busio from", "resolution of the data while True: icm.gyro_data_rate_divisor = 0 #", "# Cycle between two data rates # Best viewed in", "MIT import time import board import busio from adafruit_icm20x import", "Best viewed in the Mu serial plotter where you can", "in the Mu serial plotter where you can see how", "print(icm.gyro) icm.gyro_data_rate_divisor = 255 # maximum print(\"Data Rate:\", icm.gyro_data_rate) time.sleep(2)" ]
[ "* (a-x-2) + '*' print(out.center(2*a-1)) print('*' * (2 * a", "* a - 1)) for x in range(a-1): out =", "* (2 * a - 1)) for x in range(a-1):", "in range(a-1): out = '*' + ' ' * x", "' ' * x + '*' + ' ' *", "'*' + ' ' * x + '*' print(out.center(2*a-1)) a", "1)) for x in range(a-1): out = '*' + '", "print(out.center(2*a-1)) print('*' * (2 * a - 1)) for x", "print('*' * (2 * a - 1)) for x in", "+ ' ' * (a-x-2) + '*' print(out.center(2*a-1)) print('*' *", "* (a-x-2) + '*' + ' ' * (a-x-2) +", "(a-x-2) + '*' + ' ' * (a-x-2) + '*'", "a: for x in range(a-1): out = '*' + '", "range(a-1): out = '*' + ' ' * x +", "<gh_stars>0 a = int(input()) while a: for x in range(a-1):", "' ' * x + '*' print(out.center(2*a-1)) a = int(input())", "+ '*' + ' ' * x + '*' print(out.center(2*a-1))", "for x in range(a-1): out = '*' + ' '", "a = int(input()) while a: for x in range(a-1): out", "' * (a-x-2) + '*' + ' ' * (a-x-2)", "range(a-1): out = '*' + ' ' * (a-x-2) +", "= '*' + ' ' * x + '*' +", "while a: for x in range(a-1): out = '*' +", "+ ' ' * x + '*' + ' '", "' * (a-x-2) + '*' print(out.center(2*a-1)) print('*' * (2 *", "(a-x-2) + '*' print(out.center(2*a-1)) print('*' * (2 * a -", "' ' * (a-x-2) + '*' + ' ' *", "- 1)) for x in range(a-1): out = '*' +", "a - 1)) for x in range(a-1): out = '*'", "'*' + ' ' * x + '*' + '", "in range(a-1): out = '*' + ' ' * (a-x-2)", "'*' + ' ' * (a-x-2) + '*' print(out.center(2*a-1)) print('*'", "= '*' + ' ' * (a-x-2) + '*' +", "' * x + '*' + ' ' * x", "out = '*' + ' ' * (a-x-2) + '*'", "out = '*' + ' ' * x + '*'", "* x + '*' + ' ' * x +", "x in range(a-1): out = '*' + ' ' *", "(2 * a - 1)) for x in range(a-1): out", "'*' print(out.center(2*a-1)) print('*' * (2 * a - 1)) for", "'*' + ' ' * (a-x-2) + '*' + '", "= int(input()) while a: for x in range(a-1): out =", "' ' * (a-x-2) + '*' print(out.center(2*a-1)) print('*' * (2", "int(input()) while a: for x in range(a-1): out = '*'", "+ ' ' * (a-x-2) + '*' + ' '", "+ ' ' * x + '*' print(out.center(2*a-1)) a =", "x + '*' + ' ' * x + '*'", "+ '*' print(out.center(2*a-1)) print('*' * (2 * a - 1))", "+ '*' + ' ' * (a-x-2) + '*' print(out.center(2*a-1))" ]
[ "raise ValueError( f\"expected to find 1 high_res_video_path from PathDetails; instead", "Optional[int] timestamp: datetime.datetime camera_name: str is_image: bool is_lowres: bool class", "low_res_video_paths[0] # in Go: # eventId := uuid.NewSHA1( # uuid.NameSpaceDNS,", "= relate_path_details(some_path_details=some_path_details, get_key_methods=get_key_methods) print(f\"got {len(related_path_details)} related paths\") print(\"building events...\") events", "they were {camera_ids}\" ) camera_names = list(set([x.camera_name for x in", "json_path: Path, parse_method: Callable, get_key_methods: List[Callable]): print(f\"getting sorted paths from", "were {event_ids}\" ) camera_ids = list(set([x.camera_id for x in some_path_details]))", "+= [some_path_details] return deduplicated_path_details def build_events_for_related_path_details( related_path_details: List[List[PathDetails]], path: Path", "in some_path_details_by_key.items() if len(v) == 4 } deduplicated_path_details = []", "x.is_lowres]) ) if len(low_res_image_paths) != 1: raise ValueError( f\"expected to", "in paths if x is not None] if y is", "event in sorted_events: event.timestamp = format_timestamp_for_go(timestamp=event.timestamp) return sorted_events def build_json_lines_from_events(events:", "len(high_res_image_paths) != 1: raise ValueError( f\"expected to find 1 high_res_image_path", "some_path_details in viable_some_path_details_by_key.values(): if some_path_details not in deduplicated_path_details: deduplicated_path_details +=", "find 1 low_res_video_path from PathDetails; instead found {low_res_video_paths}\" ) timestamp", "print(\"relating parsed paths...\") related_path_details = relate_path_details(some_path_details=some_path_details, get_key_methods=get_key_methods) print(f\"got {len(related_path_details)} related", "to have a common camera_name; instead they were {camera_names}\" )", "[] for some_path_details in viable_some_path_details_by_key.values(): if some_path_details not in deduplicated_path_details:", "x.high_res_image_path, \"low_res_image_path\": x.low_res_image_path, \"high_res_video_path\": x.high_res_video_path, \"low_res_video_path\": x.low_res_video_path, } ) for", "if len(camera_ids) != 1: raise ValueError( f\"expected all PathDetails to", "highResVideoPath, lowResVideoPath)), # ) event_id = uuid3( NAMESPACE_DNS, f\"{format_timestamp_for_go(timestamp)}, {high_res_image_path},", "some_path_details_by_key = {} for path_details in some_path_details: keys = [x(path_details)", "json lines...\") json_lines = build_json_lines_from_events(events=events) print(f\"built {len(json_lines)} bytes\") print(f\"writing to", "lowResVideoPath)), # ) event_id = uuid3( NAMESPACE_DNS, f\"{format_timestamp_for_go(timestamp)}, {high_res_image_path}, {low_res_image_path},", "] sorted_events = sorted(events, key=lambda x: x.timestamp) for event in", "event_ids = list(set([x.event_id for x in some_path_details])) if len(event_ids) !=", "x.is_image and not x.is_lowres]) ) if len(high_res_video_paths) != 1: raise", "in some_path_details if not x.is_image and not x.is_lowres]) ) if", "x.timestamp) for event in sorted_events: event.timestamp = format_timestamp_for_go(timestamp=event.timestamp) return sorted_events", "x in some_path_details if not x.is_image and not x.is_lowres]) )", "\"high_res_video_path\": x.high_res_video_path, \"low_res_video_path\": x.low_res_video_path, } ) for x in events", "sorted paths from {root_path}...\") sorted_paths = get_sorted_paths(path=root_path) print(f\"got {len(sorted_paths)} sorted", "instead found {high_res_video_paths}\" ) low_res_video_paths = list( set([x.path for x", "return timestamp.strftime(f\"%Y-%m-%dT%H:%M:%S.{us}00{tz}\") def parse_paths(paths: List[Path], tzinfo: datetime.tzinfo, parse_method: Callable) ->", "+ _IMAGE_SUFFIXES class PathDetails(NamedTuple): path: Path event_id: Optional[int] camera_id: Optional[int]", "not in deduplicated_path_details: deduplicated_path_details += [some_path_details] return deduplicated_path_details def build_events_for_related_path_details(", "# uuid.NameSpaceDNS, # []byte(fmt.Sprintf(\"%v, %v, %v, %v, %v\", timestamp, highResImagePath,", "have a common camera_id; instead they were {camera_ids}\" ) camera_names", "return deduplicated_path_details def build_events_for_related_path_details( related_path_details: List[List[PathDetails]], path: Path ) ->", "= get_sorted_paths(path=root_path) print(f\"got {len(sorted_paths)} sorted paths\") print(\"parsing sorted paths...\") some_path_details", "some_path_details])[0] high_res_image_path = high_res_image_paths[0] low_res_image_path = low_res_image_paths[0] high_res_video_path = high_res_video_paths[0]", "import Path from types import SimpleNamespace from typing import List", "= list(set([x.camera_name for x in some_path_details])) if len(camera_names) != 1:", "low_res_image_paths = list( set([x.path for x in some_path_details if x.is_image", "!= 1: raise ValueError( f\"expected to find 1 low_res_video_path from", "uuid3, NAMESPACE_DNS from dateutil.parser import parse _VIDEO_SUFFIXES = [\".mkv\", \".mp4\"]", "} ) for x in events ] ) def write_to_file(path:", "timestamp.strftime(\"%z\") tz = \"{}:{}\".format(tz_raw[0:3], tz_raw[3:]) return timestamp.strftime(f\"%Y-%m-%dT%H:%M:%S.{us}00{tz}\") def parse_paths(paths: List[Path],", "f\"expected all PathDetails to have a common camera_name; instead they", "class PathDetails(NamedTuple): path: Path event_id: Optional[int] camera_id: Optional[int] timestamp: datetime.datetime", "x in events ] ) def write_to_file(path: Path, data: str):", "paths\") print(\"relating parsed paths...\") related_path_details = relate_path_details(some_path_details=some_path_details, get_key_methods=get_key_methods) print(f\"got {len(related_path_details)}", "List[List[PathDetails]], path: Path ) -> List[Event]: events: List[Event] = []", "_VIDEO_SUFFIXES = [\".mkv\", \".mp4\"] _IMAGE_SUFFIXES = [\".jpg\"] _PERMITTED_EXTENSIONS = _VIDEO_SUFFIXES", "= [\".mkv\", \".mp4\"] _IMAGE_SUFFIXES = [\".jpg\"] _PERMITTED_EXTENSIONS = _VIDEO_SUFFIXES +", "in events ] ) def write_to_file(path: Path, data: str): with", "/ high_res_video_path), low_res_video_path=str(path / low_res_video_path), ) def relate_path_details( some_path_details: List[PathDetails],", "highResImagePath, lowResImagePath, highResVideoPath, lowResVideoPath)), # ) event_id = uuid3( NAMESPACE_DNS,", "= \"{}:{}\".format(tz_raw[0:3], tz_raw[3:]) return timestamp.strftime(f\"%Y-%m-%dT%H:%M:%S.{us}00{tz}\") def parse_paths(paths: List[Path], tzinfo: datetime.tzinfo,", "{high_res_image_paths}\" ) low_res_image_paths = list( set([x.path for x in some_path_details", "camera_name; instead they were {camera_names}\" ) high_res_image_paths = list( set([x.path", "is_lowres: bool class Event(SimpleNamespace): event_id: str timestamp: Union[datetime.datetime, str] camera_name:", "event_id: str timestamp: Union[datetime.datetime, str] camera_name: str high_res_image_path: str low_res_image_path:", "if len(camera_names) != 1: raise ValueError( f\"expected all PathDetails to", "List from typing import NamedTuple, Union, Optional, Callable from uuid", "in keys: some_path_details_by_key.setdefault(key, []) some_path_details_by_key[key] += [path_details] viable_some_path_details_by_key = {", ") timestamp = sorted([x.timestamp for x in some_path_details])[0] high_res_image_path =", "low_res_video_path from PathDetails; instead found {low_res_video_paths}\" ) timestamp = sorted([x.timestamp", ") print(f\"built {len(events)} events\") print(\"building json lines...\") json_lines = build_json_lines_from_events(events=events)", "find 1 low_res_image_path from PathDetails; instead found {low_res_image_paths}\" ) high_res_video_paths", "deduplicated_path_details def build_events_for_related_path_details( related_path_details: List[List[PathDetails]], path: Path ) -> List[Event]:", ":= uuid.NewSHA1( # uuid.NameSpaceDNS, # []byte(fmt.Sprintf(\"%v, %v, %v, %v, %v\",", "for x in events ] ) def write_to_file(path: Path, data:", "if len(high_res_image_paths) != 1: raise ValueError( f\"expected to find 1", "\"low_res_video_path\": x.low_res_video_path, } ) for x in events ] )", "raise ValueError( f\"expected all PathDetails to have a common event_id;", "for x in some_path_details])) if len(camera_names) != 1: raise ValueError(", "rebuild_event_store(root_path: Path, tzinfo: datetime.tzinfo, json_path: Path, parse_method: Callable, get_key_methods: List[Callable]):", "def get_sorted_paths(path: Path) -> List[Path]: return sorted(Path(path).iterdir(), key=os.path.getmtime) def format_timestamp_for_go(timestamp:", "not None ] def build_event_for_some_path_details(some_path_details: List[PathDetails], path: Path): if len(some_path_details)", "# eventId := uuid.NewSHA1( # uuid.NameSpaceDNS, # []byte(fmt.Sprintf(\"%v, %v, %v,", "camera_name=camera_names[0], high_res_image_path=str(path / high_res_image_path), low_res_image_path=str(path / low_res_image_path), high_res_video_path=str(path / high_res_video_path),", "import os from pathlib import Path from types import SimpleNamespace", "str low_res_image_path: str high_res_video_path: str low_res_video_path: str def get_sorted_paths(path: Path)", "timestamp: Union[datetime.datetime, str] camera_name: str high_res_image_path: str low_res_image_path: str high_res_video_path:", "Event( event_id=str(event_id), timestamp=timestamp, camera_name=camera_names[0], high_res_image_path=str(path / high_res_image_path), low_res_image_path=str(path / low_res_image_path),", "return sorted_events def build_json_lines_from_events(events: List[Event]) -> str: return \"\\n\".join( [", "len(high_res_video_paths) != 1: raise ValueError( f\"expected to find 1 high_res_video_path", "y is not None ] def build_event_for_some_path_details(some_path_details: List[PathDetails], path: Path):", "json_lines = build_json_lines_from_events(events=events) print(f\"built {len(json_lines)} bytes\") print(f\"writing to {json_path}\") write_to_file(path=json_path,", "in some_path_details if not x.is_image and x.is_lowres]) ) if len(low_res_video_paths)", ") -> List[List[PathDetails]]: some_path_details_by_key = {} for path_details in some_path_details:", "Path ) -> List[Event]: events: List[Event] = [] for some_path_details", "str): timestamp = parse(timestamp) us = timestamp.strftime(\"%f\") tz_raw = timestamp.strftime(\"%z\")", "high_res_video_path), low_res_video_path=str(path / low_res_video_path), ) def relate_path_details( some_path_details: List[PathDetails], get_key_methods:", "parse_paths(paths: List[Path], tzinfo: datetime.tzinfo, parse_method: Callable) -> List[PathDetails]: return [", "timestamp = sorted([x.timestamp for x in some_path_details])[0] high_res_image_path = high_res_image_paths[0]", "in sorted_events: event.timestamp = format_timestamp_for_go(timestamp=event.timestamp) return sorted_events def build_json_lines_from_events(events: List[Event])", "{len(some_path_details)} long\" ) event_ids = list(set([x.event_id for x in some_path_details]))", "in some_path_details if x.is_image and not x.is_lowres]) ) if len(high_res_image_paths)", "not x.is_lowres]) ) if len(high_res_video_paths) != 1: raise ValueError( f\"expected", "path: Path): if len(some_path_details) != 4: raise ValueError( f\"expected some_path_details", "not None] if y is not None ] def build_event_for_some_path_details(some_path_details:", "low_res_image_path: str high_res_video_path: str low_res_video_path: str def get_sorted_paths(path: Path) ->", "None] if y is not None ] def build_event_for_some_path_details(some_path_details: List[PathDetails],", "set([x.path for x in some_path_details if not x.is_image and x.is_lowres])", "# ) event_id = uuid3( NAMESPACE_DNS, f\"{format_timestamp_for_go(timestamp)}, {high_res_image_path}, {low_res_image_path}, {high_res_video_path},", "sorted_events: event.timestamp = format_timestamp_for_go(timestamp=event.timestamp) return sorted_events def build_json_lines_from_events(events: List[Event]) ->", "a common event_id; instead they were {event_ids}\" ) camera_ids =", "{root_path}...\") sorted_paths = get_sorted_paths(path=root_path) print(f\"got {len(sorted_paths)} sorted paths\") print(\"parsing sorted", "{len(some_path_details)} parsed paths\") print(\"relating parsed paths...\") related_path_details = relate_path_details(some_path_details=some_path_details, get_key_methods=get_key_methods)", "[\".mkv\", \".mp4\"] _IMAGE_SUFFIXES = [\".jpg\"] _PERMITTED_EXTENSIONS = _VIDEO_SUFFIXES + _IMAGE_SUFFIXES", "from pathlib import Path from types import SimpleNamespace from typing", "parsed paths\") print(\"relating parsed paths...\") related_path_details = relate_path_details(some_path_details=some_path_details, get_key_methods=get_key_methods) print(f\"got", "have a common camera_name; instead they were {camera_names}\" ) high_res_image_paths", "found {low_res_image_paths}\" ) high_res_video_paths = list( set([x.path for x in", "x in some_path_details])[0] high_res_image_path = high_res_image_paths[0] low_res_image_path = low_res_image_paths[0] high_res_video_path", "get_key_methods=get_key_methods) print(f\"got {len(related_path_details)} related paths\") print(\"building events...\") events = build_events_for_related_path_details(", "1: raise ValueError( f\"expected to find 1 high_res_video_path from PathDetails;", "x.is_image and x.is_lowres]) ) if len(low_res_video_paths) != 1: raise ValueError(", "in some_path_details: keys = [x(path_details) for x in get_key_methods] for", "format_timestamp_for_go(timestamp=event.timestamp) return sorted_events def build_json_lines_from_events(events: List[Event]) -> str: return \"\\n\".join(", ") event_id = uuid3( NAMESPACE_DNS, f\"{format_timestamp_for_go(timestamp)}, {high_res_image_path}, {low_res_image_path}, {high_res_video_path}, {low_res_video_path}\",", "list( set([x.path for x in some_path_details if not x.is_image and", "%v, %v\", timestamp, highResImagePath, lowResImagePath, highResVideoPath, lowResVideoPath)), # ) event_id", "x.camera_name, \"high_res_image_path\": x.high_res_image_path, \"low_res_image_path\": x.low_res_image_path, \"high_res_video_path\": x.high_res_video_path, \"low_res_video_path\": x.low_res_video_path, }", "str): with open(str(path), \"w\") as f: f.write(data) def rebuild_event_store(root_path: Path,", "parsed paths...\") related_path_details = relate_path_details(some_path_details=some_path_details, get_key_methods=get_key_methods) print(f\"got {len(related_path_details)} related paths\")", ") if len(low_res_image_paths) != 1: raise ValueError( f\"expected to find", "{low_res_image_paths}\" ) high_res_video_paths = list( set([x.path for x in some_path_details", "list(set([x.event_id for x in some_path_details])) if len(event_ids) != 1: raise", "x in some_path_details if not x.is_image and x.is_lowres]) ) if", "instead they were {event_ids}\" ) camera_ids = list(set([x.camera_id for x", "%v, %v, %v, %v\", timestamp, highResImagePath, lowResImagePath, highResVideoPath, lowResVideoPath)), #", "related_path_details = relate_path_details(some_path_details=some_path_details, get_key_methods=get_key_methods) print(f\"got {len(related_path_details)} related paths\") print(\"building events...\")", "Union[datetime.datetime, str]) -> str: if isinstance(timestamp, str): timestamp = parse(timestamp)", "{len(related_path_details)} related paths\") print(\"building events...\") events = build_events_for_related_path_details( related_path_details=related_path_details, path=root_path", "tzinfo=tzinfo, parse_method=parse_method) print(f\"got {len(some_path_details)} parsed paths\") print(\"relating parsed paths...\") related_path_details", "to find 1 low_res_video_path from PathDetails; instead found {low_res_video_paths}\" )", "Path) -> List[Path]: return sorted(Path(path).iterdir(), key=os.path.getmtime) def format_timestamp_for_go(timestamp: Union[datetime.datetime, str])", ") camera_names = list(set([x.camera_name for x in some_path_details])) if len(camera_names)", "from PathDetails; instead found {low_res_image_paths}\" ) high_res_video_paths = list( set([x.path", "viable_some_path_details_by_key = { k: v for k, v in some_path_details_by_key.items()", "in related_path_details: events += [ build_event_for_some_path_details( some_path_details=some_path_details, path=path ) ]", "for x in some_path_details])[0] high_res_image_path = high_res_image_paths[0] low_res_image_path = low_res_image_paths[0]", "len(low_res_video_paths) != 1: raise ValueError( f\"expected to find 1 low_res_video_path", "\"timestamp\": x.timestamp, \"camera_name\": x.camera_name, \"high_res_image_path\": x.high_res_image_path, \"low_res_image_path\": x.low_res_image_path, \"high_res_video_path\": x.high_res_video_path,", "List[PathDetails], get_key_methods: List[Callable] ) -> List[List[PathDetails]]: some_path_details_by_key = {} for", "4 long (and related); instead it was {len(some_path_details)} long\" )", "x.is_lowres]) ) if len(high_res_video_paths) != 1: raise ValueError( f\"expected to", "+= [ build_event_for_some_path_details( some_path_details=some_path_details, path=path ) ] sorted_events = sorted(events,", "Path from types import SimpleNamespace from typing import List from", "get_key_methods] for key in keys: some_path_details_by_key.setdefault(key, []) some_path_details_by_key[key] += [path_details]", "List[Path]: return sorted(Path(path).iterdir(), key=os.path.getmtime) def format_timestamp_for_go(timestamp: Union[datetime.datetime, str]) -> str:", "they were {camera_names}\" ) high_res_image_paths = list( set([x.path for x", "some_path_details if not x.is_image and not x.is_lowres]) ) if len(high_res_video_paths)", "instead it was {len(some_path_details)} long\" ) event_ids = list(set([x.event_id for", "if len(some_path_details) != 4: raise ValueError( f\"expected some_path_details to be", "timestamp = parse(timestamp) us = timestamp.strftime(\"%f\") tz_raw = timestamp.strftime(\"%z\") tz", "sorted paths...\") some_path_details = parse_paths(paths=sorted_paths, tzinfo=tzinfo, parse_method=parse_method) print(f\"got {len(some_path_details)} parsed", "List[Event]: events: List[Event] = [] for some_path_details in related_path_details: events", "lines...\") json_lines = build_json_lines_from_events(events=events) print(f\"built {len(json_lines)} bytes\") print(f\"writing to {json_path}\")", "str timestamp: Union[datetime.datetime, str] camera_name: str high_res_image_path: str low_res_image_path: str", "low_res_video_path: str def get_sorted_paths(path: Path) -> List[Path]: return sorted(Path(path).iterdir(), key=os.path.getmtime)", "!= 4: raise ValueError( f\"expected some_path_details to be 4 long", "List[PathDetails], path: Path): if len(some_path_details) != 4: raise ValueError( f\"expected", "for x in some_path_details if not x.is_image and x.is_lowres]) )", "[] for some_path_details in related_path_details: events += [ build_event_for_some_path_details( some_path_details=some_path_details,", "high_res_image_paths = list( set([x.path for x in some_path_details if x.is_image", "= sorted([x.timestamp for x in some_path_details])[0] high_res_image_path = high_res_image_paths[0] low_res_image_path", "\".mp4\"] _IMAGE_SUFFIXES = [\".jpg\"] _PERMITTED_EXTENSIONS = _VIDEO_SUFFIXES + _IMAGE_SUFFIXES class", "[some_path_details] return deduplicated_path_details def build_events_for_related_path_details( related_path_details: List[List[PathDetails]], path: Path )", "from PathDetails; instead found {high_res_video_paths}\" ) low_res_video_paths = list( set([x.path", "k, v in some_path_details_by_key.items() if len(v) == 4 } deduplicated_path_details", "y for y in [parse_method(path=x, tzinfo=tzinfo) for x in paths", "data: str): with open(str(path), \"w\") as f: f.write(data) def rebuild_event_store(root_path:", "in some_path_details])) if len(camera_names) != 1: raise ValueError( f\"expected all", ") def write_to_file(path: Path, data: str): with open(str(path), \"w\") as", ") high_res_video_paths = list( set([x.path for x in some_path_details if", "NAMESPACE_DNS from dateutil.parser import parse _VIDEO_SUFFIXES = [\".mkv\", \".mp4\"] _IMAGE_SUFFIXES", "from typing import List from typing import NamedTuple, Union, Optional,", "PathDetails(NamedTuple): path: Path event_id: Optional[int] camera_id: Optional[int] timestamp: datetime.datetime camera_name:", "sorted([x.timestamp for x in some_path_details])[0] high_res_image_path = high_res_image_paths[0] low_res_image_path =", "some_path_details_by_key.setdefault(key, []) some_path_details_by_key[key] += [path_details] viable_some_path_details_by_key = { k: v", "event_id = uuid3( NAMESPACE_DNS, f\"{format_timestamp_for_go(timestamp)}, {high_res_image_path}, {low_res_image_path}, {high_res_video_path}, {low_res_video_path}\", )", "ValueError( f\"expected to find 1 low_res_video_path from PathDetails; instead found", "it was {len(some_path_details)} long\" ) event_ids = list(set([x.event_id for x", "-> List[PathDetails]: return [ y for y in [parse_method(path=x, tzinfo=tzinfo)", "found {high_res_image_paths}\" ) low_res_image_paths = list( set([x.path for x in", "build_event_for_some_path_details(some_path_details: List[PathDetails], path: Path): if len(some_path_details) != 4: raise ValueError(", "if isinstance(timestamp, str): timestamp = parse(timestamp) us = timestamp.strftime(\"%f\") tz_raw", "long\" ) event_ids = list(set([x.event_id for x in some_path_details])) if", "list(set([x.camera_name for x in some_path_details])) if len(camera_names) != 1: raise", "4 } deduplicated_path_details = [] for some_path_details in viable_some_path_details_by_key.values(): if", "Path, tzinfo: datetime.tzinfo, json_path: Path, parse_method: Callable, get_key_methods: List[Callable]): print(f\"getting", "set([x.path for x in some_path_details if x.is_image and x.is_lowres]) )", "1: raise ValueError( f\"expected to find 1 low_res_image_path from PathDetails;", "low_res_video_path = low_res_video_paths[0] # in Go: # eventId := uuid.NewSHA1(", "high_res_video_path=str(path / high_res_video_path), low_res_video_path=str(path / low_res_video_path), ) def relate_path_details( some_path_details:", "related_path_details: List[List[PathDetails]], path: Path ) -> List[Event]: events: List[Event] =", "parse_method: Callable, get_key_methods: List[Callable]): print(f\"getting sorted paths from {root_path}...\") sorted_paths", "camera_name: str high_res_image_path: str low_res_image_path: str high_res_video_path: str low_res_video_path: str", "-> str: return \"\\n\".join( [ json.dumps( { \"event_id\": x.event_id, \"timestamp\":", "class Event(SimpleNamespace): event_id: str timestamp: Union[datetime.datetime, str] camera_name: str high_res_image_path:", "Optional, Callable from uuid import uuid3, NAMESPACE_DNS from dateutil.parser import", "List[PathDetails]: return [ y for y in [parse_method(path=x, tzinfo=tzinfo) for", "def build_json_lines_from_events(events: List[Event]) -> str: return \"\\n\".join( [ json.dumps( {", "all PathDetails to have a common event_id; instead they were", "Event(SimpleNamespace): event_id: str timestamp: Union[datetime.datetime, str] camera_name: str high_res_image_path: str", "_IMAGE_SUFFIXES = [\".jpg\"] _PERMITTED_EXTENSIONS = _VIDEO_SUFFIXES + _IMAGE_SUFFIXES class PathDetails(NamedTuple):", "events...\") events = build_events_for_related_path_details( related_path_details=related_path_details, path=root_path ) print(f\"built {len(events)} events\")", "key=lambda x: x.timestamp) for event in sorted_events: event.timestamp = format_timestamp_for_go(timestamp=event.timestamp)", "in some_path_details])) if len(camera_ids) != 1: raise ValueError( f\"expected all", "some_path_details: List[PathDetails], get_key_methods: List[Callable] ) -> List[List[PathDetails]]: some_path_details_by_key = {}", "for some_path_details in related_path_details: events += [ build_event_for_some_path_details( some_path_details=some_path_details, path=path", "# []byte(fmt.Sprintf(\"%v, %v, %v, %v, %v\", timestamp, highResImagePath, lowResImagePath, highResVideoPath,", "list(set([x.camera_id for x in some_path_details])) if len(camera_ids) != 1: raise", "datetime.tzinfo, json_path: Path, parse_method: Callable, get_key_methods: List[Callable]): print(f\"getting sorted paths", "if y is not None ] def build_event_for_some_path_details(some_path_details: List[PathDetails], path:", "get_sorted_paths(path=root_path) print(f\"got {len(sorted_paths)} sorted paths\") print(\"parsing sorted paths...\") some_path_details =", "to find 1 high_res_image_path from PathDetails; instead found {high_res_image_paths}\" )", "1: raise ValueError( f\"expected all PathDetails to have a common", "!= 1: raise ValueError( f\"expected to find 1 high_res_image_path from", "if not x.is_image and not x.is_lowres]) ) if len(high_res_video_paths) !=", "datetime import json import os from pathlib import Path from", ") if len(high_res_image_paths) != 1: raise ValueError( f\"expected to find", "datetime.tzinfo, parse_method: Callable) -> List[PathDetails]: return [ y for y", "= parse_paths(paths=sorted_paths, tzinfo=tzinfo, parse_method=parse_method) print(f\"got {len(some_path_details)} parsed paths\") print(\"relating parsed", "in some_path_details if x.is_image and x.is_lowres]) ) if len(low_res_image_paths) !=", "some_path_details=some_path_details, path=path ) ] sorted_events = sorted(events, key=lambda x: x.timestamp)", "= parse(timestamp) us = timestamp.strftime(\"%f\") tz_raw = timestamp.strftime(\"%z\") tz =", "{low_res_video_paths}\" ) timestamp = sorted([x.timestamp for x in some_path_details])[0] high_res_image_path", "typing import List from typing import NamedTuple, Union, Optional, Callable", "is not None ] def build_event_for_some_path_details(some_path_details: List[PathDetails], path: Path): if", "x.is_lowres]) ) if len(high_res_image_paths) != 1: raise ValueError( f\"expected to", "[]) some_path_details_by_key[key] += [path_details] viable_some_path_details_by_key = { k: v for", "print(f\"got {len(sorted_paths)} sorted paths\") print(\"parsing sorted paths...\") some_path_details = parse_paths(paths=sorted_paths,", "str high_res_image_path: str low_res_image_path: str high_res_video_path: str low_res_video_path: str def", "set([x.path for x in some_path_details if not x.is_image and not", "None ] def build_event_for_some_path_details(some_path_details: List[PathDetails], path: Path): if len(some_path_details) !=", "paths\") print(\"parsing sorted paths...\") some_path_details = parse_paths(paths=sorted_paths, tzinfo=tzinfo, parse_method=parse_method) print(f\"got", "high_res_image_path), low_res_image_path=str(path / low_res_image_path), high_res_video_path=str(path / high_res_video_path), low_res_video_path=str(path / low_res_video_path),", "def rebuild_event_store(root_path: Path, tzinfo: datetime.tzinfo, json_path: Path, parse_method: Callable, get_key_methods:", "x.is_image and x.is_lowres]) ) if len(low_res_image_paths) != 1: raise ValueError(", "for x in some_path_details if x.is_image and x.is_lowres]) ) if", "build_json_lines_from_events(events: List[Event]) -> str: return \"\\n\".join( [ json.dumps( { \"event_id\":", "build_events_for_related_path_details( related_path_details: List[List[PathDetails]], path: Path ) -> List[Event]: events: List[Event]", "return [ y for y in [parse_method(path=x, tzinfo=tzinfo) for x", "y in [parse_method(path=x, tzinfo=tzinfo) for x in paths if x", "in [parse_method(path=x, tzinfo=tzinfo) for x in paths if x is", "str def get_sorted_paths(path: Path) -> List[Path]: return sorted(Path(path).iterdir(), key=os.path.getmtime) def", "dateutil.parser import parse _VIDEO_SUFFIXES = [\".mkv\", \".mp4\"] _IMAGE_SUFFIXES = [\".jpg\"]", "in some_path_details])[0] high_res_image_path = high_res_image_paths[0] low_res_image_path = low_res_image_paths[0] high_res_video_path =", "x in get_key_methods] for key in keys: some_path_details_by_key.setdefault(key, []) some_path_details_by_key[key]", "low_res_video_path=str(path / low_res_video_path), ) def relate_path_details( some_path_details: List[PathDetails], get_key_methods: List[Callable]", "== 4 } deduplicated_path_details = [] for some_path_details in viable_some_path_details_by_key.values():", "from PathDetails; instead found {high_res_image_paths}\" ) low_res_image_paths = list( set([x.path", "and not x.is_lowres]) ) if len(high_res_image_paths) != 1: raise ValueError(", "raise ValueError( f\"expected to find 1 high_res_image_path from PathDetails; instead", "bool class Event(SimpleNamespace): event_id: str timestamp: Union[datetime.datetime, str] camera_name: str", "some_path_details if x.is_image and not x.is_lowres]) ) if len(high_res_image_paths) !=", "ValueError( f\"expected to find 1 high_res_video_path from PathDetails; instead found", "raise ValueError( f\"expected all PathDetails to have a common camera_name;", ") return Event( event_id=str(event_id), timestamp=timestamp, camera_name=camera_names[0], high_res_image_path=str(path / high_res_image_path), low_res_image_path=str(path", "for x in get_key_methods] for key in keys: some_path_details_by_key.setdefault(key, [])", "= timestamp.strftime(\"%f\") tz_raw = timestamp.strftime(\"%z\") tz = \"{}:{}\".format(tz_raw[0:3], tz_raw[3:]) return", "= build_events_for_related_path_details( related_path_details=related_path_details, path=root_path ) print(f\"built {len(events)} events\") print(\"building json", "def format_timestamp_for_go(timestamp: Union[datetime.datetime, str]) -> str: if isinstance(timestamp, str): timestamp", "instead found {high_res_image_paths}\" ) low_res_image_paths = list( set([x.path for x", "f\"expected to find 1 low_res_image_path from PathDetails; instead found {low_res_image_paths}\"", "[parse_method(path=x, tzinfo=tzinfo) for x in paths if x is not", "str] camera_name: str high_res_image_path: str low_res_image_path: str high_res_video_path: str low_res_video_path:", "high_res_image_path=str(path / high_res_image_path), low_res_image_path=str(path / low_res_image_path), high_res_video_path=str(path / high_res_video_path), low_res_video_path=str(path", "low_res_image_path), high_res_video_path=str(path / high_res_video_path), low_res_video_path=str(path / low_res_video_path), ) def relate_path_details(", "x is not None] if y is not None ]", "if not x.is_image and x.is_lowres]) ) if len(low_res_video_paths) != 1:", ") low_res_image_paths = list( set([x.path for x in some_path_details if", "parse_paths(paths=sorted_paths, tzinfo=tzinfo, parse_method=parse_method) print(f\"got {len(some_path_details)} parsed paths\") print(\"relating parsed paths...\")", "for some_path_details in viable_some_path_details_by_key.values(): if some_path_details not in deduplicated_path_details: deduplicated_path_details", "raise ValueError( f\"expected to find 1 low_res_video_path from PathDetails; instead", "4: raise ValueError( f\"expected some_path_details to be 4 long (and", "paths\") print(\"building events...\") events = build_events_for_related_path_details( related_path_details=related_path_details, path=root_path ) print(f\"built", "{high_res_video_path}, {low_res_video_path}\", ) return Event( event_id=str(event_id), timestamp=timestamp, camera_name=camera_names[0], high_res_image_path=str(path /", "if x.is_image and x.is_lowres]) ) if len(low_res_image_paths) != 1: raise", "= [x(path_details) for x in get_key_methods] for key in keys:", "[x(path_details) for x in get_key_methods] for key in keys: some_path_details_by_key.setdefault(key,", "related_path_details: events += [ build_event_for_some_path_details( some_path_details=some_path_details, path=path ) ] sorted_events", "for x in some_path_details if not x.is_image and not x.is_lowres])", "len(camera_names) != 1: raise ValueError( f\"expected all PathDetails to have", "\"w\") as f: f.write(data) def rebuild_event_store(root_path: Path, tzinfo: datetime.tzinfo, json_path:", "{len(events)} events\") print(\"building json lines...\") json_lines = build_json_lines_from_events(events=events) print(f\"built {len(json_lines)}", "str: if isinstance(timestamp, str): timestamp = parse(timestamp) us = timestamp.strftime(\"%f\")", ") camera_ids = list(set([x.camera_id for x in some_path_details])) if len(camera_ids)", "x in some_path_details])) if len(camera_ids) != 1: raise ValueError( f\"expected", "for event in sorted_events: event.timestamp = format_timestamp_for_go(timestamp=event.timestamp) return sorted_events def", "deduplicated_path_details: deduplicated_path_details += [some_path_details] return deduplicated_path_details def build_events_for_related_path_details( related_path_details: List[List[PathDetails]],", "for path_details in some_path_details: keys = [x(path_details) for x in", "PathDetails to have a common camera_id; instead they were {camera_ids}\"", "have a common event_id; instead they were {event_ids}\" ) camera_ids", "List[Event] = [] for some_path_details in related_path_details: events += [", "List[Callable]): print(f\"getting sorted paths from {root_path}...\") sorted_paths = get_sorted_paths(path=root_path) print(f\"got", "x.low_res_image_path, \"high_res_video_path\": x.high_res_video_path, \"low_res_video_path\": x.low_res_video_path, } ) for x in", "print(f\"got {len(some_path_details)} parsed paths\") print(\"relating parsed paths...\") related_path_details = relate_path_details(some_path_details=some_path_details,", "{event_ids}\" ) camera_ids = list(set([x.camera_id for x in some_path_details])) if", "camera_id; instead they were {camera_ids}\" ) camera_names = list(set([x.camera_name for", "def write_to_file(path: Path, data: str): with open(str(path), \"w\") as f:", "path=path ) ] sorted_events = sorted(events, key=lambda x: x.timestamp) for", "(and related); instead it was {len(some_path_details)} long\" ) event_ids =", "format_timestamp_for_go(timestamp: Union[datetime.datetime, str]) -> str: if isinstance(timestamp, str): timestamp =", "uuid3( NAMESPACE_DNS, f\"{format_timestamp_for_go(timestamp)}, {high_res_image_path}, {low_res_image_path}, {high_res_video_path}, {low_res_video_path}\", ) return Event(", "related paths\") print(\"building events...\") events = build_events_for_related_path_details( related_path_details=related_path_details, path=root_path )", "list( set([x.path for x in some_path_details if x.is_image and x.is_lowres])", "\"{}:{}\".format(tz_raw[0:3], tz_raw[3:]) return timestamp.strftime(f\"%Y-%m-%dT%H:%M:%S.{us}00{tz}\") def parse_paths(paths: List[Path], tzinfo: datetime.tzinfo, parse_method:", "PathDetails; instead found {high_res_image_paths}\" ) low_res_image_paths = list( set([x.path for", "path_details in some_path_details: keys = [x(path_details) for x in get_key_methods]", ") if len(high_res_video_paths) != 1: raise ValueError( f\"expected to find", "some_path_details to be 4 long (and related); instead it was", "find 1 high_res_video_path from PathDetails; instead found {high_res_video_paths}\" ) low_res_video_paths", "= [\".jpg\"] _PERMITTED_EXTENSIONS = _VIDEO_SUFFIXES + _IMAGE_SUFFIXES class PathDetails(NamedTuple): path:", "from PathDetails; instead found {low_res_video_paths}\" ) timestamp = sorted([x.timestamp for", "str: return \"\\n\".join( [ json.dumps( { \"event_id\": x.event_id, \"timestamp\": x.timestamp,", "if some_path_details not in deduplicated_path_details: deduplicated_path_details += [some_path_details] return deduplicated_path_details", "keys: some_path_details_by_key.setdefault(key, []) some_path_details_by_key[key] += [path_details] viable_some_path_details_by_key = { k:", "as f: f.write(data) def rebuild_event_store(root_path: Path, tzinfo: datetime.tzinfo, json_path: Path,", "not x.is_lowres]) ) if len(high_res_image_paths) != 1: raise ValueError( f\"expected", "ValueError( f\"expected to find 1 high_res_image_path from PathDetails; instead found", "common event_id; instead they were {event_ids}\" ) camera_ids = list(set([x.camera_id", "event_id: Optional[int] camera_id: Optional[int] timestamp: datetime.datetime camera_name: str is_image: bool", "some_path_details not in deduplicated_path_details: deduplicated_path_details += [some_path_details] return deduplicated_path_details def", "from uuid import uuid3, NAMESPACE_DNS from dateutil.parser import parse _VIDEO_SUFFIXES", "f\"expected to find 1 high_res_image_path from PathDetails; instead found {high_res_image_paths}\"", "some_path_details if x.is_image and x.is_lowres]) ) if len(low_res_image_paths) != 1:", "if len(event_ids) != 1: raise ValueError( f\"expected all PathDetails to", "from typing import NamedTuple, Union, Optional, Callable from uuid import", "event_id=str(event_id), timestamp=timestamp, camera_name=camera_names[0], high_res_image_path=str(path / high_res_image_path), low_res_image_path=str(path / low_res_image_path), high_res_video_path=str(path", "= low_res_video_paths[0] # in Go: # eventId := uuid.NewSHA1( #", "x.is_image and not x.is_lowres]) ) if len(high_res_image_paths) != 1: raise", "= high_res_image_paths[0] low_res_image_path = low_res_image_paths[0] high_res_video_path = high_res_video_paths[0] low_res_video_path =", "isinstance(timestamp, str): timestamp = parse(timestamp) us = timestamp.strftime(\"%f\") tz_raw =", "} deduplicated_path_details = [] for some_path_details in viable_some_path_details_by_key.values(): if some_path_details", "PathDetails; instead found {low_res_image_paths}\" ) high_res_video_paths = list( set([x.path for", "datetime.datetime camera_name: str is_image: bool is_lowres: bool class Event(SimpleNamespace): event_id:", "high_res_video_paths = list( set([x.path for x in some_path_details if not", "key=os.path.getmtime) def format_timestamp_for_go(timestamp: Union[datetime.datetime, str]) -> str: if isinstance(timestamp, str):", "to have a common camera_id; instead they were {camera_ids}\" )", "find 1 high_res_image_path from PathDetails; instead found {high_res_image_paths}\" ) low_res_image_paths", "some_path_details])) if len(camera_ids) != 1: raise ValueError( f\"expected all PathDetails", "List[Callable] ) -> List[List[PathDetails]]: some_path_details_by_key = {} for path_details in", "path=root_path ) print(f\"built {len(events)} events\") print(\"building json lines...\") json_lines =", "/ high_res_image_path), low_res_image_path=str(path / low_res_image_path), high_res_video_path=str(path / high_res_video_path), low_res_video_path=str(path /", "instead found {low_res_video_paths}\" ) timestamp = sorted([x.timestamp for x in", "tz = \"{}:{}\".format(tz_raw[0:3], tz_raw[3:]) return timestamp.strftime(f\"%Y-%m-%dT%H:%M:%S.{us}00{tz}\") def parse_paths(paths: List[Path], tzinfo:", "long (and related); instead it was {len(some_path_details)} long\" ) event_ids", "eventId := uuid.NewSHA1( # uuid.NameSpaceDNS, # []byte(fmt.Sprintf(\"%v, %v, %v, %v,", "v in some_path_details_by_key.items() if len(v) == 4 } deduplicated_path_details =", "common camera_id; instead they were {camera_ids}\" ) camera_names = list(set([x.camera_name", "build_events_for_related_path_details( related_path_details=related_path_details, path=root_path ) print(f\"built {len(events)} events\") print(\"building json lines...\")", "[\".jpg\"] _PERMITTED_EXTENSIONS = _VIDEO_SUFFIXES + _IMAGE_SUFFIXES class PathDetails(NamedTuple): path: Path", "sorted(Path(path).iterdir(), key=os.path.getmtime) def format_timestamp_for_go(timestamp: Union[datetime.datetime, str]) -> str: if isinstance(timestamp,", "-> List[Event]: events: List[Event] = [] for some_path_details in related_path_details:", "types import SimpleNamespace from typing import List from typing import", "1: raise ValueError( f\"expected to find 1 high_res_image_path from PathDetails;", "def relate_path_details( some_path_details: List[PathDetails], get_key_methods: List[Callable] ) -> List[List[PathDetails]]: some_path_details_by_key", "1 low_res_image_path from PathDetails; instead found {low_res_image_paths}\" ) high_res_video_paths =", "print(f\"getting sorted paths from {root_path}...\") sorted_paths = get_sorted_paths(path=root_path) print(f\"got {len(sorted_paths)}", "= {} for path_details in some_path_details: keys = [x(path_details) for", "event.timestamp = format_timestamp_for_go(timestamp=event.timestamp) return sorted_events def build_json_lines_from_events(events: List[Event]) -> str:", "timestamp, highResImagePath, lowResImagePath, highResVideoPath, lowResVideoPath)), # ) event_id = uuid3(", "set([x.path for x in some_path_details if x.is_image and not x.is_lowres])", "{camera_names}\" ) high_res_image_paths = list( set([x.path for x in some_path_details", "SimpleNamespace from typing import List from typing import NamedTuple, Union,", "import json import os from pathlib import Path from types", "uuid import uuid3, NAMESPACE_DNS from dateutil.parser import parse _VIDEO_SUFFIXES =", "] def build_event_for_some_path_details(some_path_details: List[PathDetails], path: Path): if len(some_path_details) != 4:", "high_res_video_path from PathDetails; instead found {high_res_video_paths}\" ) low_res_video_paths = list(", "instead they were {camera_ids}\" ) camera_names = list(set([x.camera_name for x", "were {camera_ids}\" ) camera_names = list(set([x.camera_name for x in some_path_details]))", "was {len(some_path_details)} long\" ) event_ids = list(set([x.event_id for x in", "from {root_path}...\") sorted_paths = get_sorted_paths(path=root_path) print(f\"got {len(sorted_paths)} sorted paths\") print(\"parsing", "!= 1: raise ValueError( f\"expected all PathDetails to have a", "some_path_details: keys = [x(path_details) for x in get_key_methods] for key", "str high_res_video_path: str low_res_video_path: str def get_sorted_paths(path: Path) -> List[Path]:", "str is_image: bool is_lowres: bool class Event(SimpleNamespace): event_id: str timestamp:", "some_path_details])) if len(camera_names) != 1: raise ValueError( f\"expected all PathDetails", "in Go: # eventId := uuid.NewSHA1( # uuid.NameSpaceDNS, # []byte(fmt.Sprintf(\"%v,", "return sorted(Path(path).iterdir(), key=os.path.getmtime) def format_timestamp_for_go(timestamp: Union[datetime.datetime, str]) -> str: if", "def parse_paths(paths: List[Path], tzinfo: datetime.tzinfo, parse_method: Callable) -> List[PathDetails]: return", "some_path_details_by_key.items() if len(v) == 4 } deduplicated_path_details = [] for", "NAMESPACE_DNS, f\"{format_timestamp_for_go(timestamp)}, {high_res_image_path}, {low_res_image_path}, {high_res_video_path}, {low_res_video_path}\", ) return Event( event_id=str(event_id),", "if x.is_image and not x.is_lowres]) ) if len(high_res_image_paths) != 1:", "List[Event]) -> str: return \"\\n\".join( [ json.dumps( { \"event_id\": x.event_id,", "json import os from pathlib import Path from types import", "some_path_details])) if len(event_ids) != 1: raise ValueError( f\"expected all PathDetails", "sorted(events, key=lambda x: x.timestamp) for event in sorted_events: event.timestamp =", "[ json.dumps( { \"event_id\": x.event_id, \"timestamp\": x.timestamp, \"camera_name\": x.camera_name, \"high_res_image_path\":", "import datetime import json import os from pathlib import Path", "= _VIDEO_SUFFIXES + _IMAGE_SUFFIXES class PathDetails(NamedTuple): path: Path event_id: Optional[int]", "PathDetails to have a common event_id; instead they were {event_ids}\"", "+= [path_details] viable_some_path_details_by_key = { k: v for k, v", "# in Go: # eventId := uuid.NewSHA1( # uuid.NameSpaceDNS, #", "relate_path_details(some_path_details=some_path_details, get_key_methods=get_key_methods) print(f\"got {len(related_path_details)} related paths\") print(\"building events...\") events =", "import NamedTuple, Union, Optional, Callable from uuid import uuid3, NAMESPACE_DNS", "if len(low_res_video_paths) != 1: raise ValueError( f\"expected to find 1", "os from pathlib import Path from types import SimpleNamespace from", "f\"expected all PathDetails to have a common camera_id; instead they", "high_res_image_paths[0] low_res_image_path = low_res_image_paths[0] high_res_video_path = high_res_video_paths[0] low_res_video_path = low_res_video_paths[0]", "path: Path event_id: Optional[int] camera_id: Optional[int] timestamp: datetime.datetime camera_name: str", ") if len(low_res_video_paths) != 1: raise ValueError( f\"expected to find", "v for k, v in some_path_details_by_key.items() if len(v) == 4", "they were {event_ids}\" ) camera_ids = list(set([x.camera_id for x in", "ValueError( f\"expected all PathDetails to have a common camera_name; instead", "= list( set([x.path for x in some_path_details if not x.is_image", "PathDetails; instead found {high_res_video_paths}\" ) low_res_video_paths = list( set([x.path for", "\"low_res_image_path\": x.low_res_image_path, \"high_res_video_path\": x.high_res_video_path, \"low_res_video_path\": x.low_res_video_path, } ) for x", "low_res_video_path), ) def relate_path_details( some_path_details: List[PathDetails], get_key_methods: List[Callable] ) ->", "bool is_lowres: bool class Event(SimpleNamespace): event_id: str timestamp: Union[datetime.datetime, str]", "= timestamp.strftime(\"%z\") tz = \"{}:{}\".format(tz_raw[0:3], tz_raw[3:]) return timestamp.strftime(f\"%Y-%m-%dT%H:%M:%S.{us}00{tz}\") def parse_paths(paths:", "ValueError( f\"expected to find 1 low_res_image_path from PathDetails; instead found", "to be 4 long (and related); instead it was {len(some_path_details)}", ") low_res_video_paths = list( set([x.path for x in some_path_details if", "= uuid3( NAMESPACE_DNS, f\"{format_timestamp_for_go(timestamp)}, {high_res_image_path}, {low_res_image_path}, {high_res_video_path}, {low_res_video_path}\", ) return", "related_path_details=related_path_details, path=root_path ) print(f\"built {len(events)} events\") print(\"building json lines...\") json_lines", "print(\"building json lines...\") json_lines = build_json_lines_from_events(events=events) print(f\"built {len(json_lines)} bytes\") print(f\"writing", "uuid.NewSHA1( # uuid.NameSpaceDNS, # []byte(fmt.Sprintf(\"%v, %v, %v, %v, %v\", timestamp,", "if x is not None] if y is not None", "related); instead it was {len(some_path_details)} long\" ) event_ids = list(set([x.event_id", "timestamp=timestamp, camera_name=camera_names[0], high_res_image_path=str(path / high_res_image_path), low_res_image_path=str(path / low_res_image_path), high_res_video_path=str(path /", "x in some_path_details if x.is_image and x.is_lowres]) ) if len(low_res_image_paths)", "k: v for k, v in some_path_details_by_key.items() if len(v) ==", "and not x.is_lowres]) ) if len(high_res_video_paths) != 1: raise ValueError(", "low_res_image_paths[0] high_res_video_path = high_res_video_paths[0] low_res_video_path = low_res_video_paths[0] # in Go:", ") event_ids = list(set([x.event_id for x in some_path_details])) if len(event_ids)", "to have a common event_id; instead they were {event_ids}\" )", "1 low_res_video_path from PathDetails; instead found {low_res_video_paths}\" ) timestamp =", "parse_method=parse_method) print(f\"got {len(some_path_details)} parsed paths\") print(\"relating parsed paths...\") related_path_details =", "instead found {low_res_image_paths}\" ) high_res_video_paths = list( set([x.path for x", "timestamp.strftime(f\"%Y-%m-%dT%H:%M:%S.{us}00{tz}\") def parse_paths(paths: List[Path], tzinfo: datetime.tzinfo, parse_method: Callable) -> List[PathDetails]:", "to find 1 low_res_image_path from PathDetails; instead found {low_res_image_paths}\" )", "keys = [x(path_details) for x in get_key_methods] for key in", "= sorted(events, key=lambda x: x.timestamp) for event in sorted_events: event.timestamp", "x: x.timestamp) for event in sorted_events: event.timestamp = format_timestamp_for_go(timestamp=event.timestamp) return", "-> List[List[PathDetails]]: some_path_details_by_key = {} for path_details in some_path_details: keys", "{ \"event_id\": x.event_id, \"timestamp\": x.timestamp, \"camera_name\": x.camera_name, \"high_res_image_path\": x.high_res_image_path, \"low_res_image_path\":", "len(event_ids) != 1: raise ValueError( f\"expected all PathDetails to have", "us = timestamp.strftime(\"%f\") tz_raw = timestamp.strftime(\"%z\") tz = \"{}:{}\".format(tz_raw[0:3], tz_raw[3:])", "print(\"building events...\") events = build_events_for_related_path_details( related_path_details=related_path_details, path=root_path ) print(f\"built {len(events)}", "%v, %v, %v\", timestamp, highResImagePath, lowResImagePath, highResVideoPath, lowResVideoPath)), # )", "for k, v in some_path_details_by_key.items() if len(v) == 4 }", "a common camera_id; instead they were {camera_ids}\" ) camera_names =", "json.dumps( { \"event_id\": x.event_id, \"timestamp\": x.timestamp, \"camera_name\": x.camera_name, \"high_res_image_path\": x.high_res_image_path,", "events = build_events_for_related_path_details( related_path_details=related_path_details, path=root_path ) print(f\"built {len(events)} events\") print(\"building", "\"event_id\": x.event_id, \"timestamp\": x.timestamp, \"camera_name\": x.camera_name, \"high_res_image_path\": x.high_res_image_path, \"low_res_image_path\": x.low_res_image_path,", ") def relate_path_details( some_path_details: List[PathDetails], get_key_methods: List[Callable] ) -> List[List[PathDetails]]:", "len(v) == 4 } deduplicated_path_details = [] for some_path_details in", "= low_res_image_paths[0] high_res_video_path = high_res_video_paths[0] low_res_video_path = low_res_video_paths[0] # in", "x in paths if x is not None] if y", "were {camera_names}\" ) high_res_image_paths = list( set([x.path for x in", "if len(low_res_image_paths) != 1: raise ValueError( f\"expected to find 1", "\"camera_name\": x.camera_name, \"high_res_image_path\": x.high_res_image_path, \"low_res_image_path\": x.low_res_image_path, \"high_res_video_path\": x.high_res_video_path, \"low_res_video_path\": x.low_res_video_path,", "_VIDEO_SUFFIXES + _IMAGE_SUFFIXES class PathDetails(NamedTuple): path: Path event_id: Optional[int] camera_id:", "and x.is_lowres]) ) if len(low_res_video_paths) != 1: raise ValueError( f\"expected", "x in some_path_details if x.is_image and not x.is_lowres]) ) if", "str]) -> str: if isinstance(timestamp, str): timestamp = parse(timestamp) us", "from types import SimpleNamespace from typing import List from typing", "{low_res_image_path}, {high_res_video_path}, {low_res_video_path}\", ) return Event( event_id=str(event_id), timestamp=timestamp, camera_name=camera_names[0], high_res_image_path=str(path", "some_path_details in related_path_details: events += [ build_event_for_some_path_details( some_path_details=some_path_details, path=path )", "get_key_methods: List[Callable]): print(f\"getting sorted paths from {root_path}...\") sorted_paths = get_sorted_paths(path=root_path)", "print(f\"got {len(related_path_details)} related paths\") print(\"building events...\") events = build_events_for_related_path_details( related_path_details=related_path_details,", "relate_path_details( some_path_details: List[PathDetails], get_key_methods: List[Callable] ) -> List[List[PathDetails]]: some_path_details_by_key =", "timestamp.strftime(\"%f\") tz_raw = timestamp.strftime(\"%z\") tz = \"{}:{}\".format(tz_raw[0:3], tz_raw[3:]) return timestamp.strftime(f\"%Y-%m-%dT%H:%M:%S.{us}00{tz}\")", "common camera_name; instead they were {camera_names}\" ) high_res_image_paths = list(", "PathDetails to have a common camera_name; instead they were {camera_names}\"", "Path, parse_method: Callable, get_key_methods: List[Callable]): print(f\"getting sorted paths from {root_path}...\")", "is_image: bool is_lowres: bool class Event(SimpleNamespace): event_id: str timestamp: Union[datetime.datetime,", "build_json_lines_from_events(events=events) print(f\"built {len(json_lines)} bytes\") print(f\"writing to {json_path}\") write_to_file(path=json_path, data=json_lines) print(\"done.\")", "camera_name: str is_image: bool is_lowres: bool class Event(SimpleNamespace): event_id: str", "1 high_res_image_path from PathDetails; instead found {high_res_image_paths}\" ) low_res_image_paths =", "uuid.NameSpaceDNS, # []byte(fmt.Sprintf(\"%v, %v, %v, %v, %v\", timestamp, highResImagePath, lowResImagePath,", "for x in paths if x is not None] if", "ValueError( f\"expected some_path_details to be 4 long (and related); instead", "= [] for some_path_details in related_path_details: events += [ build_event_for_some_path_details(", "Path): if len(some_path_details) != 4: raise ValueError( f\"expected some_path_details to", "Callable from uuid import uuid3, NAMESPACE_DNS from dateutil.parser import parse", "tz_raw = timestamp.strftime(\"%z\") tz = \"{}:{}\".format(tz_raw[0:3], tz_raw[3:]) return timestamp.strftime(f\"%Y-%m-%dT%H:%M:%S.{us}00{tz}\") def", "List[Path], tzinfo: datetime.tzinfo, parse_method: Callable) -> List[PathDetails]: return [ y", "import SimpleNamespace from typing import List from typing import NamedTuple,", "len(some_path_details) != 4: raise ValueError( f\"expected some_path_details to be 4", "\"\\n\".join( [ json.dumps( { \"event_id\": x.event_id, \"timestamp\": x.timestamp, \"camera_name\": x.camera_name,", "for x in some_path_details if x.is_image and not x.is_lowres]) )", "= [] for some_path_details in viable_some_path_details_by_key.values(): if some_path_details not in", "!= 1: raise ValueError( f\"expected to find 1 low_res_image_path from", "events ] ) def write_to_file(path: Path, data: str): with open(str(path),", "all PathDetails to have a common camera_id; instead they were", "= high_res_video_paths[0] low_res_video_path = low_res_video_paths[0] # in Go: # eventId", "open(str(path), \"w\") as f: f.write(data) def rebuild_event_store(root_path: Path, tzinfo: datetime.tzinfo,", "not x.is_image and x.is_lowres]) ) if len(low_res_video_paths) != 1: raise", "ValueError( f\"expected all PathDetails to have a common event_id; instead", "parse(timestamp) us = timestamp.strftime(\"%f\") tz_raw = timestamp.strftime(\"%z\") tz = \"{}:{}\".format(tz_raw[0:3],", "x.event_id, \"timestamp\": x.timestamp, \"camera_name\": x.camera_name, \"high_res_image_path\": x.high_res_image_path, \"low_res_image_path\": x.low_res_image_path, \"high_res_video_path\":", "-> List[Path]: return sorted(Path(path).iterdir(), key=os.path.getmtime) def format_timestamp_for_go(timestamp: Union[datetime.datetime, str]) ->", "if len(high_res_video_paths) != 1: raise ValueError( f\"expected to find 1", "{camera_ids}\" ) camera_names = list(set([x.camera_name for x in some_path_details])) if", "to find 1 high_res_video_path from PathDetails; instead found {high_res_video_paths}\" )", "print(\"parsing sorted paths...\") some_path_details = parse_paths(paths=sorted_paths, tzinfo=tzinfo, parse_method=parse_method) print(f\"got {len(some_path_details)}", "all PathDetails to have a common camera_name; instead they were", "list( set([x.path for x in some_path_details if x.is_image and not", "/ low_res_video_path), ) def relate_path_details( some_path_details: List[PathDetails], get_key_methods: List[Callable] )", "sorted_events = sorted(events, key=lambda x: x.timestamp) for event in sorted_events:", "{ k: v for k, v in some_path_details_by_key.items() if len(v)", "events += [ build_event_for_some_path_details( some_path_details=some_path_details, path=path ) ] sorted_events =", "[ y for y in [parse_method(path=x, tzinfo=tzinfo) for x in", "write_to_file(path: Path, data: str): with open(str(path), \"w\") as f: f.write(data)", "timestamp: datetime.datetime camera_name: str is_image: bool is_lowres: bool class Event(SimpleNamespace):", "build_event_for_some_path_details( some_path_details=some_path_details, path=path ) ] sorted_events = sorted(events, key=lambda x:", "sorted paths\") print(\"parsing sorted paths...\") some_path_details = parse_paths(paths=sorted_paths, tzinfo=tzinfo, parse_method=parse_method)", "_IMAGE_SUFFIXES class PathDetails(NamedTuple): path: Path event_id: Optional[int] camera_id: Optional[int] timestamp:", "raise ValueError( f\"expected to find 1 low_res_image_path from PathDetails; instead", "with open(str(path), \"w\") as f: f.write(data) def rebuild_event_store(root_path: Path, tzinfo:", "print(f\"built {len(events)} events\") print(\"building json lines...\") json_lines = build_json_lines_from_events(events=events) print(f\"built", "= build_json_lines_from_events(events=events) print(f\"built {len(json_lines)} bytes\") print(f\"writing to {json_path}\") write_to_file(path=json_path, data=json_lines)", "pathlib import Path from types import SimpleNamespace from typing import", "import uuid3, NAMESPACE_DNS from dateutil.parser import parse _VIDEO_SUFFIXES = [\".mkv\",", "be 4 long (and related); instead it was {len(some_path_details)} long\"", ") for x in events ] ) def write_to_file(path: Path,", "{len(sorted_paths)} sorted paths\") print(\"parsing sorted paths...\") some_path_details = parse_paths(paths=sorted_paths, tzinfo=tzinfo,", "1 high_res_video_path from PathDetails; instead found {high_res_video_paths}\" ) low_res_video_paths =", "low_res_image_path from PathDetails; instead found {low_res_image_paths}\" ) high_res_video_paths = list(", "f: f.write(data) def rebuild_event_store(root_path: Path, tzinfo: datetime.tzinfo, json_path: Path, parse_method:", "Union, Optional, Callable from uuid import uuid3, NAMESPACE_DNS from dateutil.parser", "Optional[int] camera_id: Optional[int] timestamp: datetime.datetime camera_name: str is_image: bool is_lowres:", "raise ValueError( f\"expected all PathDetails to have a common camera_id;", "key in keys: some_path_details_by_key.setdefault(key, []) some_path_details_by_key[key] += [path_details] viable_some_path_details_by_key =", "events\") print(\"building json lines...\") json_lines = build_json_lines_from_events(events=events) print(f\"built {len(json_lines)} bytes\")", "get_sorted_paths(path: Path) -> List[Path]: return sorted(Path(path).iterdir(), key=os.path.getmtime) def format_timestamp_for_go(timestamp: Union[datetime.datetime,", "= { k: v for k, v in some_path_details_by_key.items() if", "high_res_video_path = high_res_video_paths[0] low_res_video_path = low_res_video_paths[0] # in Go: #", "= list(set([x.camera_id for x in some_path_details])) if len(camera_ids) != 1:", "str low_res_video_path: str def get_sorted_paths(path: Path) -> List[Path]: return sorted(Path(path).iterdir(),", "high_res_video_paths[0] low_res_video_path = low_res_video_paths[0] # in Go: # eventId :=", "x.timestamp, \"camera_name\": x.camera_name, \"high_res_image_path\": x.high_res_image_path, \"low_res_image_path\": x.low_res_image_path, \"high_res_video_path\": x.high_res_video_path, \"low_res_video_path\":", "for key in keys: some_path_details_by_key.setdefault(key, []) some_path_details_by_key[key] += [path_details] viable_some_path_details_by_key", "low_res_image_path=str(path / low_res_image_path), high_res_video_path=str(path / high_res_video_path), low_res_video_path=str(path / low_res_video_path), )", "paths if x is not None] if y is not", "in deduplicated_path_details: deduplicated_path_details += [some_path_details] return deduplicated_path_details def build_events_for_related_path_details( related_path_details:", "high_res_image_path from PathDetails; instead found {high_res_image_paths}\" ) low_res_image_paths = list(", "found {high_res_video_paths}\" ) low_res_video_paths = list( set([x.path for x in", "= list(set([x.event_id for x in some_path_details])) if len(event_ids) != 1:", "!= 1: raise ValueError( f\"expected to find 1 high_res_video_path from", "[path_details] viable_some_path_details_by_key = { k: v for k, v in", "sorted_paths = get_sorted_paths(path=root_path) print(f\"got {len(sorted_paths)} sorted paths\") print(\"parsing sorted paths...\")", "raise ValueError( f\"expected some_path_details to be 4 long (and related);", "paths...\") some_path_details = parse_paths(paths=sorted_paths, tzinfo=tzinfo, parse_method=parse_method) print(f\"got {len(some_path_details)} parsed paths\")", "for x in some_path_details])) if len(camera_ids) != 1: raise ValueError(", "found {low_res_video_paths}\" ) timestamp = sorted([x.timestamp for x in some_path_details])[0]", "_PERMITTED_EXTENSIONS = _VIDEO_SUFFIXES + _IMAGE_SUFFIXES class PathDetails(NamedTuple): path: Path event_id:", "instead they were {camera_names}\" ) high_res_image_paths = list( set([x.path for", "low_res_image_path = low_res_image_paths[0] high_res_video_path = high_res_video_paths[0] low_res_video_path = low_res_video_paths[0] #", "f\"expected to find 1 low_res_video_path from PathDetails; instead found {low_res_video_paths}\"", "viable_some_path_details_by_key.values(): if some_path_details not in deduplicated_path_details: deduplicated_path_details += [some_path_details] return", "tzinfo=tzinfo) for x in paths if x is not None]", "not x.is_image and not x.is_lowres]) ) if len(high_res_video_paths) != 1:", "Callable, get_key_methods: List[Callable]): print(f\"getting sorted paths from {root_path}...\") sorted_paths =", "parse _VIDEO_SUFFIXES = [\".mkv\", \".mp4\"] _IMAGE_SUFFIXES = [\".jpg\"] _PERMITTED_EXTENSIONS =", "x.is_lowres]) ) if len(low_res_video_paths) != 1: raise ValueError( f\"expected to", "get_key_methods: List[Callable] ) -> List[List[PathDetails]]: some_path_details_by_key = {} for path_details", "some_path_details if not x.is_image and x.is_lowres]) ) if len(low_res_video_paths) !=", "x.high_res_video_path, \"low_res_video_path\": x.low_res_video_path, } ) for x in events ]", "x.low_res_video_path, } ) for x in events ] ) def", "some_path_details = parse_paths(paths=sorted_paths, tzinfo=tzinfo, parse_method=parse_method) print(f\"got {len(some_path_details)} parsed paths\") print(\"relating", "\"high_res_image_path\": x.high_res_image_path, \"low_res_image_path\": x.low_res_image_path, \"high_res_video_path\": x.high_res_video_path, \"low_res_video_path\": x.low_res_video_path, } )", "x in some_path_details])) if len(camera_names) != 1: raise ValueError( f\"expected", "camera_ids = list(set([x.camera_id for x in some_path_details])) if len(camera_ids) !=", "path: Path ) -> List[Event]: events: List[Event] = [] for", "f\"expected to find 1 high_res_video_path from PathDetails; instead found {high_res_video_paths}\"", "[ build_event_for_some_path_details( some_path_details=some_path_details, path=path ) ] sorted_events = sorted(events, key=lambda", "import List from typing import NamedTuple, Union, Optional, Callable from", ") high_res_image_paths = list( set([x.path for x in some_path_details if", "= list( set([x.path for x in some_path_details if x.is_image and", "Callable) -> List[PathDetails]: return [ y for y in [parse_method(path=x,", "{high_res_video_paths}\" ) low_res_video_paths = list( set([x.path for x in some_path_details", "deduplicated_path_details += [some_path_details] return deduplicated_path_details def build_events_for_related_path_details( related_path_details: List[List[PathDetails]], path:", "parse_method: Callable) -> List[PathDetails]: return [ y for y in", "import parse _VIDEO_SUFFIXES = [\".mkv\", \".mp4\"] _IMAGE_SUFFIXES = [\".jpg\"] _PERMITTED_EXTENSIONS", "a common camera_name; instead they were {camera_names}\" ) high_res_image_paths =", "camera_id: Optional[int] timestamp: datetime.datetime camera_name: str is_image: bool is_lowres: bool", "PathDetails; instead found {low_res_video_paths}\" ) timestamp = sorted([x.timestamp for x", "lowResImagePath, highResVideoPath, lowResVideoPath)), # ) event_id = uuid3( NAMESPACE_DNS, f\"{format_timestamp_for_go(timestamp)},", "1: raise ValueError( f\"expected to find 1 low_res_video_path from PathDetails;", "Path event_id: Optional[int] camera_id: Optional[int] timestamp: datetime.datetime camera_name: str is_image:", "[]byte(fmt.Sprintf(\"%v, %v, %v, %v, %v\", timestamp, highResImagePath, lowResImagePath, highResVideoPath, lowResVideoPath)),", "high_res_image_path = high_res_image_paths[0] low_res_image_path = low_res_image_paths[0] high_res_video_path = high_res_video_paths[0] low_res_video_path", "def build_event_for_some_path_details(some_path_details: List[PathDetails], path: Path): if len(some_path_details) != 4: raise", "tzinfo: datetime.tzinfo, parse_method: Callable) -> List[PathDetails]: return [ y for", "] ) def write_to_file(path: Path, data: str): with open(str(path), \"w\")", "return \"\\n\".join( [ json.dumps( { \"event_id\": x.event_id, \"timestamp\": x.timestamp, \"camera_name\":", "typing import NamedTuple, Union, Optional, Callable from uuid import uuid3,", "camera_names = list(set([x.camera_name for x in some_path_details])) if len(camera_names) !=", "high_res_image_path: str low_res_image_path: str high_res_video_path: str low_res_video_path: str def get_sorted_paths(path:", "{} for path_details in some_path_details: keys = [x(path_details) for x", "/ low_res_image_path), high_res_video_path=str(path / high_res_video_path), low_res_video_path=str(path / low_res_video_path), ) def", "deduplicated_path_details = [] for some_path_details in viable_some_path_details_by_key.values(): if some_path_details not", "NamedTuple, Union, Optional, Callable from uuid import uuid3, NAMESPACE_DNS from", ") ] sorted_events = sorted(events, key=lambda x: x.timestamp) for event", "len(low_res_image_paths) != 1: raise ValueError( f\"expected to find 1 low_res_image_path", "low_res_video_paths = list( set([x.path for x in some_path_details if not", "events: List[Event] = [] for some_path_details in related_path_details: events +=", "f\"{format_timestamp_for_go(timestamp)}, {high_res_image_path}, {low_res_image_path}, {high_res_video_path}, {low_res_video_path}\", ) return Event( event_id=str(event_id), timestamp=timestamp,", "Path, data: str): with open(str(path), \"w\") as f: f.write(data) def", "is not None] if y is not None ] def", "and x.is_lowres]) ) if len(low_res_image_paths) != 1: raise ValueError( f\"expected", "sorted_events def build_json_lines_from_events(events: List[Event]) -> str: return \"\\n\".join( [ json.dumps(", "tz_raw[3:]) return timestamp.strftime(f\"%Y-%m-%dT%H:%M:%S.{us}00{tz}\") def parse_paths(paths: List[Path], tzinfo: datetime.tzinfo, parse_method: Callable)", ") -> List[Event]: events: List[Event] = [] for some_path_details in", "high_res_video_path: str low_res_video_path: str def get_sorted_paths(path: Path) -> List[Path]: return", "for y in [parse_method(path=x, tzinfo=tzinfo) for x in paths if", "f.write(data) def rebuild_event_store(root_path: Path, tzinfo: datetime.tzinfo, json_path: Path, parse_method: Callable,", "def build_events_for_related_path_details( related_path_details: List[List[PathDetails]], path: Path ) -> List[Event]: events:", "in viable_some_path_details_by_key.values(): if some_path_details not in deduplicated_path_details: deduplicated_path_details += [some_path_details]", "event_id; instead they were {event_ids}\" ) camera_ids = list(set([x.camera_id for", "in some_path_details])) if len(event_ids) != 1: raise ValueError( f\"expected all", "ValueError( f\"expected all PathDetails to have a common camera_id; instead", "List[List[PathDetails]]: some_path_details_by_key = {} for path_details in some_path_details: keys =", "from dateutil.parser import parse _VIDEO_SUFFIXES = [\".mkv\", \".mp4\"] _IMAGE_SUFFIXES =", "paths...\") related_path_details = relate_path_details(some_path_details=some_path_details, get_key_methods=get_key_methods) print(f\"got {len(related_path_details)} related paths\") print(\"building", "x in some_path_details])) if len(event_ids) != 1: raise ValueError( f\"expected", "Union[datetime.datetime, str] camera_name: str high_res_image_path: str low_res_image_path: str high_res_video_path: str", "= format_timestamp_for_go(timestamp=event.timestamp) return sorted_events def build_json_lines_from_events(events: List[Event]) -> str: return", "tzinfo: datetime.tzinfo, json_path: Path, parse_method: Callable, get_key_methods: List[Callable]): print(f\"getting sorted", "{low_res_video_path}\", ) return Event( event_id=str(event_id), timestamp=timestamp, camera_name=camera_names[0], high_res_image_path=str(path / high_res_image_path),", "paths from {root_path}...\") sorted_paths = get_sorted_paths(path=root_path) print(f\"got {len(sorted_paths)} sorted paths\")", "in get_key_methods] for key in keys: some_path_details_by_key.setdefault(key, []) some_path_details_by_key[key] +=", "-> str: if isinstance(timestamp, str): timestamp = parse(timestamp) us =", "{high_res_image_path}, {low_res_image_path}, {high_res_video_path}, {low_res_video_path}\", ) return Event( event_id=str(event_id), timestamp=timestamp, camera_name=camera_names[0],", "f\"expected some_path_details to be 4 long (and related); instead it", "f\"expected all PathDetails to have a common event_id; instead they", "%v\", timestamp, highResImagePath, lowResImagePath, highResVideoPath, lowResVideoPath)), # ) event_id =", "return Event( event_id=str(event_id), timestamp=timestamp, camera_name=camera_names[0], high_res_image_path=str(path / high_res_image_path), low_res_image_path=str(path /", "some_path_details_by_key[key] += [path_details] viable_some_path_details_by_key = { k: v for k,", "for x in some_path_details])) if len(event_ids) != 1: raise ValueError(", "len(camera_ids) != 1: raise ValueError( f\"expected all PathDetails to have", "Go: # eventId := uuid.NewSHA1( # uuid.NameSpaceDNS, # []byte(fmt.Sprintf(\"%v, %v,", "if len(v) == 4 } deduplicated_path_details = [] for some_path_details" ]
[ "2019-09-27 14:23 from django.db import migrations, models class Migration(migrations.Migration): dependencies", "model_name='student_assessment', name='assessment_score', field=models.IntegerField(blank=True, null=True), ), migrations.AlterField( model_name='student_assessment', name='understanding_level', field=models.CharField(blank=True, max_length=150,", "Generated by Django 2.2.1 on 2019-09-27 14:23 from django.db import", "operations = [ migrations.AlterField( model_name='student_assessment', name='assessment_mark', field=models.IntegerField(blank=True, null=True), ), migrations.AlterField(", "14:23 from django.db import migrations, models class Migration(migrations.Migration): dependencies =", "name='assessment_score', field=models.IntegerField(blank=True, null=True), ), migrations.AlterField( model_name='student_assessment', name='understanding_level', field=models.CharField(blank=True, max_length=150, null=True),", "class Migration(migrations.Migration): dependencies = [ ('schoolio', '0004_auto_20190927_0405'), ] operations =", "migrations.AlterField( model_name='student_assessment', name='assessment_score', field=models.IntegerField(blank=True, null=True), ), migrations.AlterField( model_name='student_assessment', name='understanding_level', field=models.CharField(blank=True,", "import migrations, models class Migration(migrations.Migration): dependencies = [ ('schoolio', '0004_auto_20190927_0405'),", "dependencies = [ ('schoolio', '0004_auto_20190927_0405'), ] operations = [ migrations.AlterField(", "null=True), ), migrations.AlterField( model_name='student_assessment', name='assessment_score', field=models.IntegerField(blank=True, null=True), ), migrations.AlterField( model_name='student_assessment',", "= [ ('schoolio', '0004_auto_20190927_0405'), ] operations = [ migrations.AlterField( model_name='student_assessment',", "('schoolio', '0004_auto_20190927_0405'), ] operations = [ migrations.AlterField( model_name='student_assessment', name='assessment_mark', field=models.IntegerField(blank=True,", "= [ migrations.AlterField( model_name='student_assessment', name='assessment_mark', field=models.IntegerField(blank=True, null=True), ), migrations.AlterField( model_name='student_assessment',", "Django 2.2.1 on 2019-09-27 14:23 from django.db import migrations, models", "by Django 2.2.1 on 2019-09-27 14:23 from django.db import migrations,", "from django.db import migrations, models class Migration(migrations.Migration): dependencies = [", "), migrations.AlterField( model_name='student_assessment', name='assessment_score', field=models.IntegerField(blank=True, null=True), ), migrations.AlterField( model_name='student_assessment', name='understanding_level',", "migrations.AlterField( model_name='student_assessment', name='assessment_mark', field=models.IntegerField(blank=True, null=True), ), migrations.AlterField( model_name='student_assessment', name='assessment_score', field=models.IntegerField(blank=True,", "2.2.1 on 2019-09-27 14:23 from django.db import migrations, models class", "# Generated by Django 2.2.1 on 2019-09-27 14:23 from django.db", "Migration(migrations.Migration): dependencies = [ ('schoolio', '0004_auto_20190927_0405'), ] operations = [", "models class Migration(migrations.Migration): dependencies = [ ('schoolio', '0004_auto_20190927_0405'), ] operations", "null=True), ), migrations.AlterField( model_name='student_assessment', name='understanding_level', field=models.CharField(blank=True, max_length=150, null=True), ), ]", "'0004_auto_20190927_0405'), ] operations = [ migrations.AlterField( model_name='student_assessment', name='assessment_mark', field=models.IntegerField(blank=True, null=True),", "field=models.IntegerField(blank=True, null=True), ), migrations.AlterField( model_name='student_assessment', name='assessment_score', field=models.IntegerField(blank=True, null=True), ), migrations.AlterField(", "name='assessment_mark', field=models.IntegerField(blank=True, null=True), ), migrations.AlterField( model_name='student_assessment', name='assessment_score', field=models.IntegerField(blank=True, null=True), ),", "[ migrations.AlterField( model_name='student_assessment', name='assessment_mark', field=models.IntegerField(blank=True, null=True), ), migrations.AlterField( model_name='student_assessment', name='assessment_score',", "] operations = [ migrations.AlterField( model_name='student_assessment', name='assessment_mark', field=models.IntegerField(blank=True, null=True), ),", "model_name='student_assessment', name='assessment_mark', field=models.IntegerField(blank=True, null=True), ), migrations.AlterField( model_name='student_assessment', name='assessment_score', field=models.IntegerField(blank=True, null=True),", "field=models.IntegerField(blank=True, null=True), ), migrations.AlterField( model_name='student_assessment', name='understanding_level', field=models.CharField(blank=True, max_length=150, null=True), ),", "migrations, models class Migration(migrations.Migration): dependencies = [ ('schoolio', '0004_auto_20190927_0405'), ]", "on 2019-09-27 14:23 from django.db import migrations, models class Migration(migrations.Migration):", "[ ('schoolio', '0004_auto_20190927_0405'), ] operations = [ migrations.AlterField( model_name='student_assessment', name='assessment_mark',", "django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('schoolio'," ]
[ "self def __next__(self): if self._idx >= len(self._data): raise StopIteration else:", "self._data is None: raise Exception('Dataset is not loaded') def __iter__(self):", "None _label_col = 'label' def __init__(self): self._idx = 0 if", "else: return item[self._first_text_col], int(item[self._label_col]) def __getitem__(self, item): if isinstance(item, int):", "'text' _second_text_col = None _label_col = 'label' def __init__(self): self._idx", "= self._data.iloc[item] if self._second_text_col: return item[self._first_text_col], item[self._second_text_col], int(item[self._label_col]) else: return", "is not loaded') def __iter__(self): return self def __next__(self): if", "1 if self._second_text_col: return item[self._first_text_col], item[self._second_text_col], int(item[self._label_col]) else: return item[self._first_text_col],", "= 'text' _second_text_col = None _label_col = 'label' def __init__(self):", "if item.start else 0 stop = item.stop if item.stop else", "int(item[self._label_col]) elif isinstance(item, slice): start = item.start if item.start else", "item.stop if item.stop else len(self._data) step = item.step if item.step", "= None _first_text_col = 'text' _second_text_col = None _label_col =", "_first_text_col = 'text' _second_text_col = None _label_col = 'label' def", "step = item.step if item.step else 1 items = self._data.iloc[start:stop:step]", "item[self._first_text_col], item[self._second_text_col], int(item[self._label_col]) else: return item[self._first_text_col], int(item[self._label_col]) def __getitem__(self, item):", "__next__(self): if self._idx >= len(self._data): raise StopIteration else: item =", "= self._data.iloc[start:stop:step] if self._second_text_col: return [(item[self._first_text_col], item[self._second_text_col], int(item[self._label_col])) for _,", "isinstance(item, int): item = self._data.iloc[item] if self._second_text_col: return item[self._first_text_col], item[self._second_text_col],", "__getitem__(self, item): if isinstance(item, int): item = self._data.iloc[item] if self._second_text_col:", "is None: raise Exception('Dataset is not loaded') def __iter__(self): return", "def __next__(self): if self._idx >= len(self._data): raise StopIteration else: item", "if self._second_text_col: return [(item[self._first_text_col], item[self._second_text_col], int(item[self._label_col])) for _, item in", "= item.start if item.start else 0 stop = item.stop if", "items.iterrows()] else: return [(item[self._first_text_col], int(item[self._label_col])) for _, item in items.iterrows()]", "item[self._second_text_col], int(item[self._label_col]) else: return item[self._first_text_col], int(item[self._label_col]) def __getitem__(self, item): if", "self._data.iloc[self._idx] self._idx += 1 if self._second_text_col: return item[self._first_text_col], item[self._second_text_col], int(item[self._label_col])", "return item[self._first_text_col], int(item[self._label_col]) elif isinstance(item, slice): start = item.start if", "if item.step else 1 items = self._data.iloc[start:stop:step] if self._second_text_col: return", "= 0 if self._data is None: raise Exception('Dataset is not", "_, item in items.iterrows()] else: raise KeyError def __str__(self): return", "loaded') def __iter__(self): return self def __next__(self): if self._idx >=", "item = self._data.iloc[self._idx] self._idx += 1 if self._second_text_col: return item[self._first_text_col],", "return item[self._first_text_col], item[self._second_text_col], int(item[self._label_col]) else: return item[self._first_text_col], int(item[self._label_col]) elif isinstance(item,", "int(item[self._label_col])) for _, item in items.iterrows()] else: return [(item[self._first_text_col], int(item[self._label_col]))", "elif isinstance(item, slice): start = item.start if item.start else 0", "= item.stop if item.stop else len(self._data) step = item.step if", "else: item = self._data.iloc[self._idx] self._idx += 1 if self._second_text_col: return", "for _, item in items.iterrows()] else: raise KeyError def __str__(self):", "_data = None _first_text_col = 'text' _second_text_col = None _label_col", "<gh_stars>0 class Dataset: _data = None _first_text_col = 'text' _second_text_col", "0 if self._data is None: raise Exception('Dataset is not loaded')", "self._data.iloc[start:stop:step] if self._second_text_col: return [(item[self._first_text_col], item[self._second_text_col], int(item[self._label_col])) for _, item", "len(self._data): raise StopIteration else: item = self._data.iloc[self._idx] self._idx += 1", "item.step else 1 items = self._data.iloc[start:stop:step] if self._second_text_col: return [(item[self._first_text_col],", "start = item.start if item.start else 0 stop = item.stop", "item[self._second_text_col], int(item[self._label_col])) for _, item in items.iterrows()] else: return [(item[self._first_text_col],", "self._idx >= len(self._data): raise StopIteration else: item = self._data.iloc[self._idx] self._idx", "self._data.iloc[item] if self._second_text_col: return item[self._first_text_col], item[self._second_text_col], int(item[self._label_col]) else: return item[self._first_text_col],", "None _first_text_col = 'text' _second_text_col = None _label_col = 'label'", "isinstance(item, slice): start = item.start if item.start else 0 stop", "item.start else 0 stop = item.stop if item.stop else len(self._data)", "item = self._data.iloc[item] if self._second_text_col: return item[self._first_text_col], item[self._second_text_col], int(item[self._label_col]) else:", "None: raise Exception('Dataset is not loaded') def __iter__(self): return self", "= item.step if item.step else 1 items = self._data.iloc[start:stop:step] if", "item[self._first_text_col], item[self._second_text_col], int(item[self._label_col]) else: return item[self._first_text_col], int(item[self._label_col]) elif isinstance(item, slice):", "[(item[self._first_text_col], item[self._second_text_col], int(item[self._label_col])) for _, item in items.iterrows()] else: return", "item[self._second_text_col], int(item[self._label_col]) else: return item[self._first_text_col], int(item[self._label_col]) elif isinstance(item, slice): start", "int(item[self._label_col])) for _, item in items.iterrows()] else: raise KeyError def", "item[self._first_text_col], int(item[self._label_col]) def __getitem__(self, item): if isinstance(item, int): item =", "1 items = self._data.iloc[start:stop:step] if self._second_text_col: return [(item[self._first_text_col], item[self._second_text_col], int(item[self._label_col]))", "__init__(self): self._idx = 0 if self._data is None: raise Exception('Dataset", "= 'label' def __init__(self): self._idx = 0 if self._data is", "raise StopIteration else: item = self._data.iloc[self._idx] self._idx += 1 if", "item.start if item.start else 0 stop = item.stop if item.stop", "def __getitem__(self, item): if isinstance(item, int): item = self._data.iloc[item] if", "'label' def __init__(self): self._idx = 0 if self._data is None:", "Dataset: _data = None _first_text_col = 'text' _second_text_col = None", "stop = item.stop if item.stop else len(self._data) step = item.step", "item.stop else len(self._data) step = item.step if item.step else 1", "_label_col = 'label' def __init__(self): self._idx = 0 if self._data", "_second_text_col = None _label_col = 'label' def __init__(self): self._idx =", "slice): start = item.start if item.start else 0 stop =", "int(item[self._label_col]) def __getitem__(self, item): if isinstance(item, int): item = self._data.iloc[item]", "def __init__(self): self._idx = 0 if self._data is None: raise", "else 0 stop = item.stop if item.stop else len(self._data) step", "int): item = self._data.iloc[item] if self._second_text_col: return item[self._first_text_col], item[self._second_text_col], int(item[self._label_col])", "else: return [(item[self._first_text_col], int(item[self._label_col])) for _, item in items.iterrows()] else:", "StopIteration else: item = self._data.iloc[self._idx] self._idx += 1 if self._second_text_col:", "if self._idx >= len(self._data): raise StopIteration else: item = self._data.iloc[self._idx]", "self._second_text_col: return item[self._first_text_col], item[self._second_text_col], int(item[self._label_col]) else: return item[self._first_text_col], int(item[self._label_col]) elif", "else: return item[self._first_text_col], int(item[self._label_col]) elif isinstance(item, slice): start = item.start", "+= 1 if self._second_text_col: return item[self._first_text_col], item[self._second_text_col], int(item[self._label_col]) else: return", "item in items.iterrows()] else: return [(item[self._first_text_col], int(item[self._label_col])) for _, item", "if self._data is None: raise Exception('Dataset is not loaded') def", "_, item in items.iterrows()] else: return [(item[self._first_text_col], int(item[self._label_col])) for _,", "len(self._data) step = item.step if item.step else 1 items =", "self._idx += 1 if self._second_text_col: return item[self._first_text_col], item[self._second_text_col], int(item[self._label_col]) else:", "item.step if item.step else 1 items = self._data.iloc[start:stop:step] if self._second_text_col:", "for _, item in items.iterrows()] else: return [(item[self._first_text_col], int(item[self._label_col])) for", ">= len(self._data): raise StopIteration else: item = self._data.iloc[self._idx] self._idx +=", "else 1 items = self._data.iloc[start:stop:step] if self._second_text_col: return [(item[self._first_text_col], item[self._second_text_col],", "[(item[self._first_text_col], int(item[self._label_col])) for _, item in items.iterrows()] else: raise KeyError", "if item.stop else len(self._data) step = item.step if item.step else", "in items.iterrows()] else: return [(item[self._first_text_col], int(item[self._label_col])) for _, item in", "if self._second_text_col: return item[self._first_text_col], item[self._second_text_col], int(item[self._label_col]) else: return item[self._first_text_col], int(item[self._label_col])", "return [(item[self._first_text_col], int(item[self._label_col])) for _, item in items.iterrows()] else: raise", "class Dataset: _data = None _first_text_col = 'text' _second_text_col =", "self._idx = 0 if self._data is None: raise Exception('Dataset is", "Exception('Dataset is not loaded') def __iter__(self): return self def __next__(self):", "self._second_text_col: return item[self._first_text_col], item[self._second_text_col], int(item[self._label_col]) else: return item[self._first_text_col], int(item[self._label_col]) def", "__iter__(self): return self def __next__(self): if self._idx >= len(self._data): raise", "return [(item[self._first_text_col], item[self._second_text_col], int(item[self._label_col])) for _, item in items.iterrows()] else:", "def __iter__(self): return self def __next__(self): if self._idx >= len(self._data):", "return item[self._first_text_col], item[self._second_text_col], int(item[self._label_col]) else: return item[self._first_text_col], int(item[self._label_col]) def __getitem__(self,", "= self._data.iloc[self._idx] self._idx += 1 if self._second_text_col: return item[self._first_text_col], item[self._second_text_col],", "item in items.iterrows()] else: raise KeyError def __str__(self): return str(self._data)", "int(item[self._label_col]) else: return item[self._first_text_col], int(item[self._label_col]) elif isinstance(item, slice): start =", "items = self._data.iloc[start:stop:step] if self._second_text_col: return [(item[self._first_text_col], item[self._second_text_col], int(item[self._label_col])) for", "item): if isinstance(item, int): item = self._data.iloc[item] if self._second_text_col: return", "item[self._first_text_col], int(item[self._label_col]) elif isinstance(item, slice): start = item.start if item.start", "= None _label_col = 'label' def __init__(self): self._idx = 0", "return self def __next__(self): if self._idx >= len(self._data): raise StopIteration", "raise Exception('Dataset is not loaded') def __iter__(self): return self def", "0 stop = item.stop if item.stop else len(self._data) step =", "else len(self._data) step = item.step if item.step else 1 items", "if isinstance(item, int): item = self._data.iloc[item] if self._second_text_col: return item[self._first_text_col],", "return item[self._first_text_col], int(item[self._label_col]) def __getitem__(self, item): if isinstance(item, int): item", "int(item[self._label_col]) else: return item[self._first_text_col], int(item[self._label_col]) def __getitem__(self, item): if isinstance(item,", "not loaded') def __iter__(self): return self def __next__(self): if self._idx", "self._second_text_col: return [(item[self._first_text_col], item[self._second_text_col], int(item[self._label_col])) for _, item in items.iterrows()]" ]
[ "True/False \"\"\" try: # pass the hashed password req =", "req.reset_identity() # make a request now morphed_identity = req.get('http://ipecho.net/plain') #", "the tor service Parameters ---------- arg1 [OPTIONAL]| text: bool A", "import literal_eval from fp.fp import FreeProxy from torrequest import TorRequest", "from tqdm import tqdm from ast import literal_eval from fp.fp", "Use the os module to restart the tor service Parameters", "requests.get('http://ipecho.net/plain') # reset the identity using Tor req.reset_identity() # make", "make the query query = scholarly.search_pubs(title) # come out break", "dict return next(query) # function for assigning new IP address", "successful return True def get_articleInfo(title): \"\"\" Use the google scholar", "self.deque.maxlen == len(self.deque): cTime = time.time() if cTime - self.deque[0]", "# search for the query search_query = scholarly.search_pubs(title) # print", "import requests import subprocess import numpy as np import pandas", "morphed_identity != normal_identity: if text == True: # return the", "length of the file # write the results to a", "write the results to a file for i in tqdm(range(length_of_file)):", "iterate over the length of the file # write the", "the file # write the results to a file for", "file, You can obtain one at # https://github.com/akhilpandey95/scholarlyimpact/blob/master/LICENSE. import os", "False # function for obtaining the citations using the dimensions", "a tuple return (normal_identity.text, morphed_identity.text) else: return True else: #", "i in tqdm(range(length_of_file)): alt_info = open('paper_titles.txt', 'r+') cit_info = open('citations_gs.csv',", "scholarly.search_pubs(title) # print success print(\"Got the results of the query\")", "tor identity ips = assign_new_ip(text=True) # use the tor request", "restarting the system tor service def restart_tor_system_service(text=False): \"\"\" Use the", "# function for connecting tor to scholarly def scholarly_init_connection(): \"\"\"", "[OPTIONAL]| text: bool A boolean flag to return the IP", "time.time() if cTime - self.deque[0] > self.timeUnit: self.deque.append(cTime) return False", "------- Dictionary dict \"\"\" while True: try: # init the", "scholarly_init_connection() # search for the query search_query = scholarly.search_pubs(title) #", "stderr = tor_status.communicate() if len(stderr) > 0: # return False", "if self.deque.maxlen == len(self.deque): cTime = time.time() if cTime -", "the tor service tor_status = subprocess.Popen(['service', 'tor', 'status'], stdout=subprocess.PIPE, stderr=subprocess.PIPE,", "scholarly and tor scholarly_init_connection() # search for the query search_query", "the contents of the list into a file alt_list =", "= len(open('paper_titles.txt').readlines()) # place the contents of the list into", "of a scholarly article Parameters ---------- arg1 | title: str", "works if proxy_works: # come out break # print the", "\"\"\" try: # pass the hashed password req = TorRequest(password='<PASSWORD>')", "try: # init the connection with scholarly and tor scholarly_init_connection()", "query search_query = scholarly.search_pubs(title) # print success print(\"Got the results", "restart the system tor service restart_tor_system_service(text=False) # assign new connection", "pandas as pd from tqdm import tqdm from ast import", "assign_new_ip(text=False): \"\"\" Reset the identity using TorRequest Parameters ---------- arg1", "import os import csv import glob import json import requests", "\"\"\" Bind TorRequest to Scholarly service Parameters ---------- No arguments", "copy of the same was not distributed with this #", "break # return the response dict return next(query) # function", "putting a rate limit on the number of requests made", "print the ip address depending on the text argument if", "if cTime - self.deque[0] > self.timeUnit: self.deque.append(cTime) return False else:", "for restarting the tor service tor_status = subprocess.Popen(['service', 'tor', 'status'],", "limit on the number of requests made Parameters ---------- No", "tor scholarly_init_connection() # search for the query search_query = scholarly.search_pubs(title)", "assign new tor identity ips = assign_new_ip(text=True) # use the", "identity:\", ips[1]) # function for restarting the system tor service", "tor service tor_stop = subprocess.Popen(['service', 'tor', 'stop']) # subprocess command", "if __name__ == '__main__': # iterate over the length length_of_file", "open('paper_titles.txt').readlines() # iterate over the length of the file #", "while True: # assign new tor identity ips = assign_new_ip(text=True)", "= req.get('http://ipecho.net/plain') # return the status depending on the flag", "tor_stop = subprocess.Popen(['service', 'tor', 'stop']) # subprocess command for restarting", "allocate the proxy address to scholarly proxy_works = scholarly.use_proxy(http=proxy, https=proxy)", "try: # pass the hashed password req = TorRequest(password='<PASSWORD>') #", "come out of the loop, when successful break # print", "flag to return the status of the command Returns -------", "out the stdout, stderr for the subprocess stdout, stderr =", "error message print(\"Attempt Failed, patching new tor identity\") # restart", "made Parameters ---------- No arguments Returns ------- Nothing \"\"\" def", "tor_req: # come out of the loop, when successful break", "as e: # print error message print(\"Attempt Failed, patching new", "'a') cit_info.write(str(alt_list[i].strip( ).split('\\t')[0]) + ',' + str(get_articleInfo(alt_list[i].strip().split('\\t')[1]))) cit_info.write('\\n') cit_info.close() alt_info.seek(0)", "!= normal_identity: if text == True: # return the ip", "return the status of the command Returns ------- Boolean bool", "system tor service def restart_tor_system_service(text=False): \"\"\" Use the os module", "for putting a rate limit on the number of requests", "new connection again scholarly_init_connection() # obtain the bib entry of", "tor request for scholarly tor_req = scholarly.use_tor(tor_sock_port=9050, \\ tor_control_port=9051, \\", "print(output.strip()) # pipe out the stdout, stderr for the subprocess", "limiting class RateLimiter: \"\"\" Class object for putting a rate", "service Parameters ---------- arg1 [OPTIONAL]| text: bool A boolean flag", "True self.deque.append(time.time()) return False # function for obtaining the citations", "come out of the loop break except Exception as e:", "(normal_identity.text, morphed_identity.text) else: return True else: # return just the", "import pandas as pd from tqdm import tqdm from ast", ").split('\\t')[0]) + ',' + str(get_articleInfo(alt_list[i].strip().split('\\t')[1]))) cit_info.write('\\n') cit_info.close() alt_info.seek(0) alt_info.truncate() alt_info.writelines(alt_list[i+1:])", "# obtain the bib entry of the scholarly article pub", "subprocess.Popen(['service', 'tor', 'status'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) # if the label", "using FreeProxy Parameters ---------- arg1 [OPTIONAL]| text: bool A boolean", "definition for Rate limiting class RateLimiter: \"\"\" Class object for", "dict \"\"\" while True: try: # init the connection with", "open('citations_gs.csv', 'a') cit_info.write(str(alt_list[i].strip( ).split('\\t')[0]) + ',' + str(get_articleInfo(alt_list[i].strip().split('\\t')[1]))) cit_info.write('\\n') cit_info.close()", "tqdm from ast import literal_eval from fp.fp import FreeProxy from", "object scholarly.use_lum_proxy() # make the query query = scholarly.search_pubs(title) #", "again scholarly_init_connection() # obtain the bib entry of the scholarly", "a request now morphed_identity = req.get('http://ipecho.net/plain') # return the status", "on the number of requests made Parameters ---------- No arguments", "to obtain the citations for a given title of a", "normal_identity = requests.get('http://ipecho.net/plain') # reset the identity using Tor req.reset_identity()", "FreeProxy Parameters ---------- arg1 [OPTIONAL]| text: bool A boolean flag", "from fp.fp import FreeProxy from torrequest import TorRequest from scholarly", "if proxy_works: # come out break # print the ip", "depending on the text argument if text: # print the", "the text argument if text: # print the working ip", "stderr=subprocess.PIPE, universal_newlines=True) # if the label is set to true", "rate limit on the number of requests made Parameters ----------", "False # function for assigning a new proxy def set_new_proxy(text=True):", "the subprocess stdout, stderr = tor_status.communicate() if len(stderr) > 0:", "address depending on the text argument if text: # print", "for the subprocess stdout, stderr = tor_status.communicate() if len(stderr) >", "output if text: for output in tor_status.stdout.readlines(): print(output.strip()) # pipe", "of the MIT # License. If a copy of the", "of the list into a file alt_list = open('paper_titles.txt').readlines() #", "the results to a file for i in tqdm(range(length_of_file)): alt_info", "This Source Code Form is subject to the terms of", "FreeProxy from torrequest import TorRequest from scholarly import scholarly from", "the freeproxy object proxy = FreeProxy(rand=True, timeout=1).get() # allocate the", "subprocess import numpy as np import pandas as pd from", "scholarly_init_connection(): \"\"\" Bind TorRequest to Scholarly service Parameters ---------- No", "to restart the tor service Parameters ---------- arg1 [OPTIONAL]| text:", "entry of the scholarly article pub = next(search_query) # return", "the citations using the dimensions web url def get_gs_citations_web(title): \"\"\"", "# return the status depending on the flag if morphed_identity", "status of the command Returns ------- Boolean bool \"\"\" #", "tor to scholarly def scholarly_init_connection(): \"\"\" Bind TorRequest to Scholarly", "def restart_tor_system_service(text=False): \"\"\" Use the os module to restart the", "file # write the results to a file for i", "same was not distributed with this # file, You can", "the working ip print(\"Working proxy:\", proxy) # return the proxy", "OrderedDict from operator import attrgetter # class definition for Rate", "TorRequest(password='<PASSWORD>') # return the ip address normal_identity = requests.get('http://ipecho.net/plain') #", "return the response dict return next(query) # function for assigning", "len(stderr) > 0: # return False return False else: #", "Exception as e: # come out and try again break", "TorRequest Parameters ---------- arg1 [OPTIONAL]| text: bool A boolean flag", "to Scholarly service Parameters ---------- No arguments Returns ------- Nothing", "requests import subprocess import numpy as np import pandas as", "normal_identity: if text == True: # return the ip address", "obtain the citations for a given title of a scholarly", "break # print the tor identity print(\"Working Tor identity:\", ips[1])", "a new proxy def set_new_proxy(text=True): \"\"\" Reset the identity using", "service restart_tor_system_service(text=False) # assign new connection again scholarly_init_connection() # obtain", "the bib entry of the scholarly article pub = next(search_query)", "# pass the hashed password req = TorRequest(password='<PASSWORD>') # return", "IP address def assign_new_ip(text=False): \"\"\" Reset the identity using TorRequest", "into a file alt_list = open('paper_titles.txt').readlines() # iterate over the", "Returns ------- Nothing \"\"\" while True: # assign new tor", "return the IP address tuple (old, morphed) Returns ------- boolean", "pass the hashed password req = TorRequest(password='<PASSWORD>') # return the", "alt_list = open('paper_titles.txt').readlines() # iterate over the length of the", "RateLimiter: \"\"\" Class object for putting a rate limit on", "= assign_new_ip(text=True) # use the tor request for scholarly tor_req", "on the flag if morphed_identity != normal_identity: if text ==", "arg1 | title: str The title of a scholarly article", "self.deque.append(cTime) return False else: return True self.deque.append(time.time()) return False #", "for the query search_query = scholarly.search_pubs(title) # print success print(\"Got", "pub = next(search_query) # return the bib entry return pub", "from scholarly import scholarly from collections import Counter, OrderedDict from", "= scholarly.search_pubs(title) # print success print(\"Got the results of the", "# function for restarting the system tor service def restart_tor_system_service(text=False):", "scholarly article pub = next(search_query) # return the bib entry", "proxy details return proxy # function for connecting tor to", "while True: try: # call the lumproxy object scholarly.use_lum_proxy() #", "come out break # print the ip address depending on", "out and try again break # return the response dict", "address tuple (old, morphed) Returns ------- boolean True/False \"\"\" try:", "out of the loop break except Exception as e: #", "pub if __name__ == '__main__': # iterate over the length", "web URL and requests API to obtain the citations for", "python3 # This Source Code Form is subject to the", "Returns ------- Dictionary dict \"\"\" while True: try: # init", "the label is set to true then print the output", "\"\"\" Reset the identity using FreeProxy Parameters ---------- arg1 [OPTIONAL]|", "the query search_query = scholarly.search_pubs(title) # print success print(\"Got the", "success print(\"Got the results of the query\") # come out", "except Exception as e: # come out and try again", "true if successful return True def get_articleInfo(title): \"\"\" Use the", "return True self.deque.append(time.time()) return False # function for obtaining the", "function for assigning new IP address def assign_new_ip(text=False): \"\"\" Reset", "------- Nothing \"\"\" while True: # assign new tor identity", "len(open('paper_titles.txt').readlines()) # place the contents of the list into a", "tor_pw=\"<PASSWORD>\") if tor_req: # come out of the loop, when", "print the working ip print(\"Working proxy:\", proxy) # return the", "scholarly import scholarly from collections import Counter, OrderedDict from operator", "terms of the MIT # License. If a copy of", "timeout=1).get() # allocate the proxy address to scholarly proxy_works =", "def scholarly_init_connection(): \"\"\" Bind TorRequest to Scholarly service Parameters ----------", "the number of requests made Parameters ---------- No arguments Returns", "the tor identity print(\"Working Tor identity:\", ips[1]) # function for", "come out break except Exception as e: # come out", "message print(\"Attempt Failed, patching new tor identity\") # restart the", "to scholarly def scholarly_init_connection(): \"\"\" Bind TorRequest to Scholarly service", "the terms of the MIT # License. If a copy", "from torrequest import TorRequest from scholarly import scholarly from collections", "search for the query search_query = scholarly.search_pubs(title) # print success", "# print the ip address depending on the text argument", "cit_info = open('citations_gs.csv', 'a') cit_info.write(str(alt_list[i].strip( ).split('\\t')[0]) + ',' + str(get_articleInfo(alt_list[i].strip().split('\\t')[1])))", "arguments Returns ------- Nothing \"\"\" while True: # assign new", "alt_info = open('paper_titles.txt', 'r+') cit_info = open('citations_gs.csv', 'a') cit_info.write(str(alt_list[i].strip( ).split('\\t')[0])", "class RateLimiter: \"\"\" Class object for putting a rate limit", "------- Dictionary dict \"\"\" while True: try: # call the", "address tuple (old, morphed) Returns ------- Address fp.fp.FreeProxy \"\"\" while", "service Parameters ---------- No arguments Returns ------- Nothing \"\"\" while", "the ip address depending on the text argument if text:", "a rate limit on the number of requests made Parameters", "Reset the identity using TorRequest Parameters ---------- arg1 [OPTIONAL]| text:", "# iterate over the length of the file # write", "a file alt_list = open('paper_titles.txt').readlines() # iterate over the length", "= open('paper_titles.txt', 'r+') cit_info = open('citations_gs.csv', 'a') cit_info.write(str(alt_list[i].strip( ).split('\\t')[0]) +", "ip address works if proxy_works: # come out break #", "for restarting the tor service tor_restart = subprocess.Popen(['service', 'tor', 'restart'])", "of the scholarly article pub = next(search_query) # return the", "it the ip address works if proxy_works: # come out", "identity\") # restart the system tor service restart_tor_system_service(text=False) # assign", "for a given title of a scholarly article Parameters ----------", "successful break # print the tor identity print(\"Working Tor identity:\",", "identity using TorRequest Parameters ---------- arg1 [OPTIONAL]| text: bool A", "def set_new_proxy(text=True): \"\"\" Reset the identity using FreeProxy Parameters ----------", "fp.fp.FreeProxy \"\"\" while True: # call the freeproxy object proxy", "call the lumproxy object scholarly.use_lum_proxy() # make the query query", "import json import requests import subprocess import numpy as np", "proxy def set_new_proxy(text=True): \"\"\" Reset the identity using FreeProxy Parameters", "return True def get_articleInfo(title): \"\"\" Use the google scholar web", "= timeUnit self.deque = deque(maxlen=maxRate) def __call__(self): if self.deque.maxlen ==", "morphed_identity = req.get('http://ipecho.net/plain') # return the status depending on the", "= time.time() if cTime - self.deque[0] > self.timeUnit: self.deque.append(cTime) return", "import glob import json import requests import subprocess import numpy", "next(query) # function for assigning new IP address def assign_new_ip(text=False):", "morphed) Returns ------- boolean True/False \"\"\" try: # pass the", "in tqdm(range(length_of_file)): alt_info = open('paper_titles.txt', 'r+') cit_info = open('citations_gs.csv', 'a')", "'tor', 'stop']) # subprocess command for restarting the tor service", "query\") # come out of the loop break except Exception", "from operator import attrgetter # class definition for Rate limiting", "flag if morphed_identity != normal_identity: if text == True: #", "= FreeProxy(rand=True, timeout=1).get() # allocate the proxy address to scholarly", "dict \"\"\" while True: try: # call the lumproxy object", "import TorRequest from scholarly import scholarly from collections import Counter,", "the identity using FreeProxy Parameters ---------- arg1 [OPTIONAL]| text: bool", "+ ',' + str(get_articleInfo(alt_list[i].strip().split('\\t')[1]))) cit_info.write('\\n') cit_info.close() alt_info.seek(0) alt_info.truncate() alt_info.writelines(alt_list[i+1:]) alt_info.close()", "= requests.get('http://ipecho.net/plain') # reset the identity using Tor req.reset_identity() #", "the results of the query\") # come out of the", "return pub if __name__ == '__main__': # iterate over the", "the query\") # come out of the loop break except", "print the output if text: for output in tor_status.stdout.readlines(): print(output.strip())", "# return the proxy details return proxy # function for", "def assign_new_ip(text=False): \"\"\" Reset the identity using TorRequest Parameters ----------", "scholar web URL and requests API to obtain the citations", "boolean flag to return the IP address tuple (old, morphed)", "new IP address def assign_new_ip(text=False): \"\"\" Reset the identity using", "the ip address works if proxy_works: # come out break", "of the loop break except Exception as e: # print", "import csv import glob import json import requests import subprocess", "next(search_query) # return the bib entry return pub if __name__", "command for stopping the tor service tor_stop = subprocess.Popen(['service', 'tor',", "scholarly.use_proxy(http=proxy, https=proxy) # check it the ip address works if", "ips[1]) # function for restarting the system tor service def", "Exception as e: # print error message print(\"Attempt Failed, patching", "title: str The title of a scholarly article Returns -------", "details return proxy # function for connecting tor to scholarly", "# return the response dict return next(query) # function for", "command for restarting the tor service tor_status = subprocess.Popen(['service', 'tor',", "object proxy = FreeProxy(rand=True, timeout=1).get() # allocate the proxy address", "collections import Counter, OrderedDict from operator import attrgetter # class", "MIT # License. If a copy of the same was", "# function for obtaining the citations using the dimensions web", "service tor_restart = subprocess.Popen(['service', 'tor', 'restart']) # subprocess command for", "the output if text: for output in tor_status.stdout.readlines(): print(output.strip()) #", "# function for assigning new IP address def assign_new_ip(text=False): \"\"\"", "address works if proxy_works: # come out break # print", "loop, when successful break # print the tor identity print(\"Working", "deque(maxlen=maxRate) def __call__(self): if self.deque.maxlen == len(self.deque): cTime = time.time()", "# allocate the proxy address to scholarly proxy_works = scholarly.use_proxy(http=proxy,", "service def restart_tor_system_service(text=False): \"\"\" Use the os module to restart", "---------- No arguments Returns ------- Nothing \"\"\" def __init__(self, maxRate=5,", "citations using the dimensions web url def get_gs_citations_web(title): \"\"\" Use", "requests API to obtain the citations for a given title", "lumproxy object scholarly.use_lum_proxy() # make the query query = scholarly.search_pubs(title)", "with this # file, You can obtain one at #", "a scholarly article Returns ------- Dictionary dict \"\"\" while True:", "the identity using Tor req.reset_identity() # make a request now", "Bind TorRequest to Scholarly service Parameters ---------- No arguments Returns", "------- Address fp.fp.FreeProxy \"\"\" while True: # call the freeproxy", "self.timeUnit = timeUnit self.deque = deque(maxlen=maxRate) def __call__(self): if self.deque.maxlen", "boolean flag to return the status of the command Returns", "------- Boolean bool \"\"\" # subprocess command for stopping the", "scholarly from collections import Counter, OrderedDict from operator import attrgetter", "text: # print the working ip print(\"Working proxy:\", proxy) #", "with scholarly and tor scholarly_init_connection() # search for the query", "Tor req.reset_identity() # make a request now morphed_identity = req.get('http://ipecho.net/plain')", "new proxy def set_new_proxy(text=True): \"\"\" Reset the identity using FreeProxy", "ip address depending on the text argument if text: #", "a copy of the same was not distributed with this", "proxy:\", proxy) # return the proxy details return proxy #", "True: try: # call the lumproxy object scholarly.use_lum_proxy() # make", "#!/usr/bin/env python3 # This Source Code Form is subject to", "tor_req = scholarly.use_tor(tor_sock_port=9050, \\ tor_control_port=9051, \\ tor_pw=\"<PASSWORD>\") if tor_req: #", "A boolean flag to return the status of the command", "length length_of_file = len(open('paper_titles.txt').readlines()) # place the contents of the", "address def assign_new_ip(text=False): \"\"\" Reset the identity using TorRequest Parameters", "# return False return False else: # return true if", "return False else: return True self.deque.append(time.time()) return False # function", "query query = scholarly.search_pubs(title) # come out break except Exception", "working ip print(\"Working proxy:\", proxy) # return the proxy details", "as pd from tqdm import tqdm from ast import literal_eval", "of the command Returns ------- Boolean bool \"\"\" # subprocess", "A boolean flag to return the IP address tuple (old,", "pd from tqdm import tqdm from ast import literal_eval from", "fp.fp import FreeProxy from torrequest import TorRequest from scholarly import", "now morphed_identity = req.get('http://ipecho.net/plain') # return the status depending on", "# return the bib entry return pub if __name__ ==", "file for i in tqdm(range(length_of_file)): alt_info = open('paper_titles.txt', 'r+') cit_info", "the IP address tuple (old, morphed) Returns ------- boolean True/False", "# function for assigning a new proxy def set_new_proxy(text=True): \"\"\"", "Rate limiting class RateLimiter: \"\"\" Class object for putting a", "self.timeUnit: self.deque.append(cTime) return False else: return True self.deque.append(time.time()) return False", "is set to true then print the output if text:", "return False return False else: # return true if successful", "can obtain one at # https://github.com/akhilpandey95/scholarlyimpact/blob/master/LICENSE. import os import csv", "return (normal_identity.text, morphed_identity.text) else: return True else: # return just", "bool A boolean flag to return the IP address tuple", "the dimensions web url def get_gs_citations_web(title): \"\"\" Use the google", "def __init__(self, maxRate=5, timeUnit=1): self.timeUnit = timeUnit self.deque = deque(maxlen=maxRate)", "the citations for a given title of a scholarly article", "search_query = scholarly.search_pubs(title) # print success print(\"Got the results of", "in tor_status.stdout.readlines(): print(output.strip()) # pipe out the stdout, stderr for", "return True else: # return just the status return False", "# call the freeproxy object proxy = FreeProxy(rand=True, timeout=1).get() #", "== len(self.deque): cTime = time.time() if cTime - self.deque[0] >", "https=proxy) # check it the ip address works if proxy_works:", "# come out of the loop, when successful break #", "out of the loop, when successful break # print the", "------- boolean True/False \"\"\" try: # pass the hashed password", "# init the connection with scholarly and tor scholarly_init_connection() #", "bib entry return pub if __name__ == '__main__': # iterate", "assigning new IP address def assign_new_ip(text=False): \"\"\" Reset the identity", "subprocess command for restarting the tor service tor_restart = subprocess.Popen(['service',", "the system tor service restart_tor_system_service(text=False) # assign new connection again", "break # print the ip address depending on the text", "for obtaining the citations using the dimensions web url def", "as e: # come out and try again break #", "identity using Tor req.reset_identity() # make a request now morphed_identity", "torrequest import TorRequest from scholarly import scholarly from collections import", "patching new tor identity\") # restart the system tor service", "cit_info.write(str(alt_list[i].strip( ).split('\\t')[0]) + ',' + str(get_articleInfo(alt_list[i].strip().split('\\t')[1]))) cit_info.write('\\n') cit_info.close() alt_info.seek(0) alt_info.truncate()", "for i in tqdm(range(length_of_file)): alt_info = open('paper_titles.txt', 'r+') cit_info =", "os import csv import glob import json import requests import", "tor identity print(\"Working Tor identity:\", ips[1]) # function for restarting", "print(\"Working proxy:\", proxy) # return the proxy details return proxy", "= subprocess.Popen(['service', 'tor', 'status'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) # if the", "identity using FreeProxy Parameters ---------- arg1 [OPTIONAL]| text: bool A", "else: return True self.deque.append(time.time()) return False # function for obtaining", "# return the ip address pairs as a tuple return", "proxy = FreeProxy(rand=True, timeout=1).get() # allocate the proxy address to", "scholarly.use_tor(tor_sock_port=9050, \\ tor_control_port=9051, \\ tor_pw=\"<PASSWORD>\") if tor_req: # come out", "len(self.deque): cTime = time.time() if cTime - self.deque[0] > self.timeUnit:", "---------- No arguments Returns ------- Nothing \"\"\" while True: #", "tor service restart_tor_system_service(text=False) # assign new connection again scholarly_init_connection() #", "title of a scholarly article Parameters ---------- arg1 | title:", "the proxy details return proxy # function for connecting tor", "scholarly article Parameters ---------- arg1 | title: str The title", "new tor identity\") # restart the system tor service restart_tor_system_service(text=False)", "proxy_works = scholarly.use_proxy(http=proxy, https=proxy) # check it the ip address", "__init__(self, maxRate=5, timeUnit=1): self.timeUnit = timeUnit self.deque = deque(maxlen=maxRate) def", "TorRequest to Scholarly service Parameters ---------- No arguments Returns -------", "== True: # return the ip address pairs as a", "restarting the tor service tor_restart = subprocess.Popen(['service', 'tor', 'restart']) #", "the status of the command Returns ------- Boolean bool \"\"\"", "obtain one at # https://github.com/akhilpandey95/scholarlyimpact/blob/master/LICENSE. import os import csv import", "# come out break # print the ip address depending", "return False else: # return true if successful return True", "'r+') cit_info = open('citations_gs.csv', 'a') cit_info.write(str(alt_list[i].strip( ).split('\\t')[0]) + ',' +", "init the connection with scholarly and tor scholarly_init_connection() # search", "Reset the identity using FreeProxy Parameters ---------- arg1 [OPTIONAL]| text:", "restart the tor service Parameters ---------- arg1 [OPTIONAL]| text: bool", "the response dict return next(query) # function for assigning new", "from ast import literal_eval from fp.fp import FreeProxy from torrequest", "the flag if morphed_identity != normal_identity: if text == True:", "Tor identity:\", ips[1]) # function for restarting the system tor", "a given title of a scholarly article Parameters ---------- arg1", "assign new connection again scholarly_init_connection() # obtain the bib entry", "to scholarly proxy_works = scholarly.use_proxy(http=proxy, https=proxy) # check it the", "Form is subject to the terms of the MIT #", "if text == True: # return the ip address pairs", "scholarly def scholarly_init_connection(): \"\"\" Bind TorRequest to Scholarly service Parameters", "# return the ip address normal_identity = requests.get('http://ipecho.net/plain') # reset", "module to restart the tor service Parameters ---------- arg1 [OPTIONAL]|", "output in tor_status.stdout.readlines(): print(output.strip()) # pipe out the stdout, stderr", "= tor_status.communicate() if len(stderr) > 0: # return False return", "the bib entry return pub if __name__ == '__main__': #", "function for assigning a new proxy def set_new_proxy(text=True): \"\"\" Reset", "the loop break except Exception as e: # print error", "password req = TorRequest(password='<PASSWORD>') # return the ip address normal_identity", "of requests made Parameters ---------- No arguments Returns ------- Nothing", "tor service tor_status = subprocess.Popen(['service', 'tor', 'status'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)", "maxRate=5, timeUnit=1): self.timeUnit = timeUnit self.deque = deque(maxlen=maxRate) def __call__(self):", "True else: # return just the status return False except:", "on the text argument if text: # print the working", "this # file, You can obtain one at # https://github.com/akhilpandey95/scholarlyimpact/blob/master/LICENSE.", "https://github.com/akhilpandey95/scholarlyimpact/blob/master/LICENSE. import os import csv import glob import json import", "Returns ------- Nothing \"\"\" def __init__(self, maxRate=5, timeUnit=1): self.timeUnit =", "results to a file for i in tqdm(range(length_of_file)): alt_info =", "stopping the tor service tor_stop = subprocess.Popen(['service', 'tor', 'stop']) #", "Counter, OrderedDict from operator import attrgetter # class definition for", "article Returns ------- Dictionary dict \"\"\" while True: try: #", "proxy_works: # come out break # print the ip address", "return proxy # function for connecting tor to scholarly def", "tuple (old, morphed) Returns ------- Address fp.fp.FreeProxy \"\"\" while True:", "FreeProxy(rand=True, timeout=1).get() # allocate the proxy address to scholarly proxy_works", "If a copy of the same was not distributed with", "---------- arg1 [OPTIONAL]| text: bool A boolean flag to return", "restarting the tor service tor_status = subprocess.Popen(['service', 'tor', 'status'], stdout=subprocess.PIPE,", "the status depending on the flag if morphed_identity != normal_identity:", "the length of the file # write the results to", "try again break # return the response dict return next(query)", "scholarly.search_pubs(title) # come out break except Exception as e: #", "cTime = time.time() if cTime - self.deque[0] > self.timeUnit: self.deque.append(cTime)", "else: return True else: # return just the status return", "connection again scholarly_init_connection() # obtain the bib entry of the", "tor_control_port=9051, \\ tor_pw=\"<PASSWORD>\") if tor_req: # come out of the", "of the loop, when successful break # print the tor", "Code Form is subject to the terms of the MIT", "the MIT # License. If a copy of the same", "and requests API to obtain the citations for a given", "return the status depending on the flag if morphed_identity !=", "the list into a file alt_list = open('paper_titles.txt').readlines() # iterate", "morphed_identity.text) else: return True else: # return just the status", "= subprocess.Popen(['service', 'tor', 'stop']) # subprocess command for restarting the", "break except Exception as e: # print error message print(\"Attempt", "length_of_file = len(open('paper_titles.txt').readlines()) # place the contents of the list", "the hashed password req = TorRequest(password='<PASSWORD>') # return the ip", "glob import json import requests import subprocess import numpy as", "# reset the identity using Tor req.reset_identity() # make a", "given title of a scholarly article Parameters ---------- arg1 |", "Returns ------- boolean True/False \"\"\" try: # pass the hashed", "system tor service restart_tor_system_service(text=False) # assign new connection again scholarly_init_connection()", "= open('paper_titles.txt').readlines() # iterate over the length of the file", "Scholarly service Parameters ---------- No arguments Returns ------- Nothing \"\"\"", "arguments Returns ------- Nothing \"\"\" def __init__(self, maxRate=5, timeUnit=1): self.timeUnit", "# iterate over the length length_of_file = len(open('paper_titles.txt').readlines()) # place", "# subprocess command for restarting the tor service tor_status =", "for restarting the system tor service def restart_tor_system_service(text=False): \"\"\" Use", "the os module to restart the tor service Parameters ----------", "= next(search_query) # return the bib entry return pub if", "import FreeProxy from torrequest import TorRequest from scholarly import scholarly", "= scholarly.use_proxy(http=proxy, https=proxy) # check it the ip address works", "cTime - self.deque[0] > self.timeUnit: self.deque.append(cTime) return False else: return", "if text: for output in tor_status.stdout.readlines(): print(output.strip()) # pipe out", "query = scholarly.search_pubs(title) # come out break except Exception as", "make a request now morphed_identity = req.get('http://ipecho.net/plain') # return the", "e: # print error message print(\"Attempt Failed, patching new tor", "subprocess command for restarting the tor service tor_status = subprocess.Popen(['service',", "tuple return (normal_identity.text, morphed_identity.text) else: return True else: # return", "at # https://github.com/akhilpandey95/scholarlyimpact/blob/master/LICENSE. import os import csv import glob import", "# file, You can obtain one at # https://github.com/akhilpandey95/scholarlyimpact/blob/master/LICENSE. import", "function for connecting tor to scholarly def scholarly_init_connection(): \"\"\" Bind", "0: # return False return False else: # return true", "print(\"Working Tor identity:\", ips[1]) # function for restarting the system", "except: return False # function for assigning a new proxy", "object for putting a rate limit on the number of", "\"\"\" Use the os module to restart the tor service", "function for restarting the system tor service def restart_tor_system_service(text=False): \"\"\"", "when successful break # print the tor identity print(\"Working Tor", "using TorRequest Parameters ---------- arg1 [OPTIONAL]| text: bool A boolean", "of a scholarly article Returns ------- Dictionary dict \"\"\" while", "csv import glob import json import requests import subprocess import", "# come out break except Exception as e: # come", "the connection with scholarly and tor scholarly_init_connection() # search for", "iterate over the length length_of_file = len(open('paper_titles.txt').readlines()) # place the", "# License. If a copy of the same was not", "Failed, patching new tor identity\") # restart the system tor", "web url def get_gs_citations_web(title): \"\"\" Use the google scholar web", "file alt_list = open('paper_titles.txt').readlines() # iterate over the length of", "out break except Exception as e: # come out and", "request now morphed_identity = req.get('http://ipecho.net/plain') # return the status depending", "Returns ------- Address fp.fp.FreeProxy \"\"\" while True: # call the", "---------- arg1 | title: str The title of a scholarly", "if the label is set to true then print the", "Dictionary dict \"\"\" while True: try: # call the lumproxy", "a scholarly article Parameters ---------- arg1 | title: str The", "again break # return the response dict return next(query) #", "------- Nothing \"\"\" def __init__(self, maxRate=5, timeUnit=1): self.timeUnit = timeUnit", "# come out of the loop break except Exception as", "literal_eval from fp.fp import FreeProxy from torrequest import TorRequest from", "function for obtaining the citations using the dimensions web url", "if tor_req: # come out of the loop, when successful", "over the length length_of_file = len(open('paper_titles.txt').readlines()) # place the contents", "Parameters ---------- No arguments Returns ------- Nothing \"\"\" def __init__(self,", "= scholarly.search_pubs(title) # come out break except Exception as e:", "# class definition for Rate limiting class RateLimiter: \"\"\" Class", "self.deque = deque(maxlen=maxRate) def __call__(self): if self.deque.maxlen == len(self.deque): cTime", "pipe out the stdout, stderr for the subprocess stdout, stderr", "hashed password req = TorRequest(password='<PASSWORD>') # return the ip address", "== '__main__': # iterate over the length length_of_file = len(open('paper_titles.txt').readlines())", "tor identity\") # restart the system tor service restart_tor_system_service(text=False) #", "restart_tor_system_service(text=False): \"\"\" Use the os module to restart the tor", "and tor scholarly_init_connection() # search for the query search_query =", "return the IP address tuple (old, morphed) Returns ------- Address", "# This Source Code Form is subject to the terms", "stdout, stderr for the subprocess stdout, stderr = tor_status.communicate() if", "arg1 [OPTIONAL]| text: bool A boolean flag to return the", "No arguments Returns ------- Nothing \"\"\" def __init__(self, maxRate=5, timeUnit=1):", "true then print the output if text: for output in", "tuple (old, morphed) Returns ------- boolean True/False \"\"\" try: #", "\"\"\" Use the google scholar web URL and requests API", "scholarly_init_connection() # obtain the bib entry of the scholarly article", "= deque(maxlen=maxRate) def __call__(self): if self.deque.maxlen == len(self.deque): cTime =", "Nothing \"\"\" while True: # assign new tor identity ips", "universal_newlines=True) # if the label is set to true then", "> 0: # return False return False else: # return", "tqdm(range(length_of_file)): alt_info = open('paper_titles.txt', 'r+') cit_info = open('citations_gs.csv', 'a') cit_info.write(str(alt_list[i].strip(", "API to obtain the citations for a given title of", "the tor service tor_restart = subprocess.Popen(['service', 'tor', 'restart']) # subprocess", "if successful return True def get_articleInfo(title): \"\"\" Use the google", "check it the ip address works if proxy_works: # come", "the tor service tor_stop = subprocess.Popen(['service', 'tor', 'stop']) # subprocess", "the scholarly article pub = next(search_query) # return the bib", "ips = assign_new_ip(text=True) # use the tor request for scholarly", "print(\"Got the results of the query\") # come out of", "while True: # call the freeproxy object proxy = FreeProxy(rand=True,", "'stop']) # subprocess command for restarting the tor service tor_restart", "the length length_of_file = len(open('paper_titles.txt').readlines()) # place the contents of", "then print the output if text: for output in tor_status.stdout.readlines():", "the query query = scholarly.search_pubs(title) # come out break except", "proxy) # return the proxy details return proxy # function", "# print error message print(\"Attempt Failed, patching new tor identity\")", "tqdm import tqdm from ast import literal_eval from fp.fp import", "for assigning new IP address def assign_new_ip(text=False): \"\"\" Reset the", "def get_gs_citations_web(title): \"\"\" Use the google scholar web URL and", "Boolean bool \"\"\" # subprocess command for stopping the tor", "response dict return next(query) # function for assigning new IP", "subprocess command for stopping the tor service tor_stop = subprocess.Popen(['service',", "Parameters ---------- arg1 | title: str The title of a", "import Counter, OrderedDict from operator import attrgetter # class definition", "the system tor service def restart_tor_system_service(text=False): \"\"\" Use the os", "\"\"\" def __init__(self, maxRate=5, timeUnit=1): self.timeUnit = timeUnit self.deque =", "class definition for Rate limiting class RateLimiter: \"\"\" Class object", "return False # function for assigning a new proxy def", "article Parameters ---------- arg1 | title: str The title of", "using the dimensions web url def get_gs_citations_web(title): \"\"\" Use the", "# return just the status return False except: return False", "The title of a scholarly article Returns ------- Dictionary dict", "# subprocess command for restarting the tor service tor_restart =", "title of a scholarly article Returns ------- Dictionary dict \"\"\"", "True: # call the freeproxy object proxy = FreeProxy(rand=True, timeout=1).get()", "if text: # print the working ip print(\"Working proxy:\", proxy)", "bool \"\"\" # subprocess command for stopping the tor service", "Address fp.fp.FreeProxy \"\"\" while True: # call the freeproxy object", "import subprocess import numpy as np import pandas as pd", "# check it the ip address works if proxy_works: #", "tor_status.stdout.readlines(): print(output.strip()) # pipe out the stdout, stderr for the", "\"\"\" Class object for putting a rate limit on the", "No arguments Returns ------- Nothing \"\"\" while True: # assign", "True: try: # init the connection with scholarly and tor", "to a file for i in tqdm(range(length_of_file)): alt_info = open('paper_titles.txt',", "False except: return False # function for assigning a new", "requests made Parameters ---------- No arguments Returns ------- Nothing \"\"\"", "if len(stderr) > 0: # return False return False else:", "to the terms of the MIT # License. If a", "assign_new_ip(text=True) # use the tor request for scholarly tor_req =", "ip print(\"Working proxy:\", proxy) # return the proxy details return", "tor service def restart_tor_system_service(text=False): \"\"\" Use the os module to", "= subprocess.Popen(['service', 'tor', 'restart']) # subprocess command for restarting the", "scholarly.use_lum_proxy() # make the query query = scholarly.search_pubs(title) # come", "return False except: return False # function for assigning a", "is subject to the terms of the MIT # License.", "address to scholarly proxy_works = scholarly.use_proxy(http=proxy, https=proxy) # check it", "= open('citations_gs.csv', 'a') cit_info.write(str(alt_list[i].strip( ).split('\\t')[0]) + ',' + str(get_articleInfo(alt_list[i].strip().split('\\t')[1]))) cit_info.write('\\n')", "entry return pub if __name__ == '__main__': # iterate over", "# assign new connection again scholarly_init_connection() # obtain the bib", "text argument if text: # print the working ip print(\"Working", "one at # https://github.com/akhilpandey95/scholarlyimpact/blob/master/LICENSE. import os import csv import glob", "address pairs as a tuple return (normal_identity.text, morphed_identity.text) else: return", "Returns ------- Dictionary dict \"\"\" while True: try: # call", "stdout, stderr = tor_status.communicate() if len(stderr) > 0: # return", "as np import pandas as pd from tqdm import tqdm", "freeproxy object proxy = FreeProxy(rand=True, timeout=1).get() # allocate the proxy", "IP address tuple (old, morphed) Returns ------- boolean True/False \"\"\"", "IP address tuple (old, morphed) Returns ------- Address fp.fp.FreeProxy \"\"\"", "address normal_identity = requests.get('http://ipecho.net/plain') # reset the identity using Tor", "status depending on the flag if morphed_identity != normal_identity: if", "set_new_proxy(text=True): \"\"\" Reset the identity using FreeProxy Parameters ---------- arg1", "distributed with this # file, You can obtain one at", "results of the query\") # come out of the loop", "number of requests made Parameters ---------- No arguments Returns -------", "e: # come out and try again break # return", "# assign new tor identity ips = assign_new_ip(text=True) # use", "os module to restart the tor service Parameters ---------- arg1", "a file for i in tqdm(range(length_of_file)): alt_info = open('paper_titles.txt', 'r+')", "text: for output in tor_status.stdout.readlines(): print(output.strip()) # pipe out the", "numpy as np import pandas as pd from tqdm import", "True: # return the ip address pairs as a tuple", "'status'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) # if the label is set", "subprocess stdout, stderr = tor_status.communicate() if len(stderr) > 0: #", "False return False else: # return true if successful return", "get_articleInfo(title): \"\"\" Use the google scholar web URL and requests", "of the same was not distributed with this # file,", "json import requests import subprocess import numpy as np import", "status return False except: return False # function for assigning", "= scholarly.use_tor(tor_sock_port=9050, \\ tor_control_port=9051, \\ tor_pw=\"<PASSWORD>\") if tor_req: # come", "import numpy as np import pandas as pd from tqdm", "# make a request now morphed_identity = req.get('http://ipecho.net/plain') # return", "tor_restart = subprocess.Popen(['service', 'tor', 'restart']) # subprocess command for restarting", "# write the results to a file for i in", "[OPTIONAL]| text: bool A boolean flag to return the status", "# print success print(\"Got the results of the query\") #", "False else: # return true if successful return True def", "False else: return True self.deque.append(time.time()) return False # function for", "Parameters ---------- arg1 [OPTIONAL]| text: bool A boolean flag to", "boolean True/False \"\"\" try: # pass the hashed password req", "ip address pairs as a tuple return (normal_identity.text, morphed_identity.text) else:", "Dictionary dict \"\"\" while True: try: # init the connection", "identity ips = assign_new_ip(text=True) # use the tor request for", "# print the working ip print(\"Working proxy:\", proxy) # return", "for output in tor_status.stdout.readlines(): print(output.strip()) # pipe out the stdout,", "tor_status = subprocess.Popen(['service', 'tor', 'status'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) # if", "ip address normal_identity = requests.get('http://ipecho.net/plain') # reset the identity using", "if morphed_identity != normal_identity: if text == True: # return", "print success print(\"Got the results of the query\") # come", "tor service tor_restart = subprocess.Popen(['service', 'tor', 'restart']) # subprocess command", "scholarly proxy_works = scholarly.use_proxy(http=proxy, https=proxy) # check it the ip", "URL and requests API to obtain the citations for a", "bib entry of the scholarly article pub = next(search_query) #", "label is set to true then print the output if", "flag to return the IP address tuple (old, morphed) Returns", "argument if text: # print the working ip print(\"Working proxy:\",", "break except Exception as e: # come out and try", "True def get_articleInfo(title): \"\"\" Use the google scholar web URL", "req.get('http://ipecho.net/plain') # return the status depending on the flag if", "'restart']) # subprocess command for restarting the tor service tor_status", "self.deque.append(time.time()) return False # function for obtaining the citations using", "You can obtain one at # https://github.com/akhilpandey95/scholarlyimpact/blob/master/LICENSE. import os import", "call the freeproxy object proxy = FreeProxy(rand=True, timeout=1).get() # allocate", "over the length of the file # write the results", "# make the query query = scholarly.search_pubs(title) # come out", "# subprocess command for stopping the tor service tor_stop =", "<filename>scripts/extract_gs_citations.py #!/usr/bin/env python3 # This Source Code Form is subject", "import tqdm from ast import literal_eval from fp.fp import FreeProxy", "was not distributed with this # file, You can obtain", "timeUnit self.deque = deque(maxlen=maxRate) def __call__(self): if self.deque.maxlen == len(self.deque):", "citations for a given title of a scholarly article Parameters", "for Rate limiting class RateLimiter: \"\"\" Class object for putting", "assigning a new proxy def set_new_proxy(text=True): \"\"\" Reset the identity", "'tor', 'status'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) # if the label is", "the google scholar web URL and requests API to obtain", "stderr for the subprocess stdout, stderr = tor_status.communicate() if len(stderr)", "- self.deque[0] > self.timeUnit: self.deque.append(cTime) return False else: return True", "service tor_status = subprocess.Popen(['service', 'tor', 'status'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) #", "command Returns ------- Boolean bool \"\"\" # subprocess command for", "\\ tor_control_port=9051, \\ tor_pw=\"<PASSWORD>\") if tor_req: # come out of", "import scholarly from collections import Counter, OrderedDict from operator import", "Parameters ---------- No arguments Returns ------- Nothing \"\"\" while True:", "for scholarly tor_req = scholarly.use_tor(tor_sock_port=9050, \\ tor_control_port=9051, \\ tor_pw=\"<PASSWORD>\") if", "just the status return False except: return False # function", "url def get_gs_citations_web(title): \"\"\" Use the google scholar web URL", "\"\"\" while True: # assign new tor identity ips =", "# https://github.com/akhilpandey95/scholarlyimpact/blob/master/LICENSE. import os import csv import glob import json", "Use the google scholar web URL and requests API to", "and try again break # return the response dict return", "the lumproxy object scholarly.use_lum_proxy() # make the query query =", "connecting tor to scholarly def scholarly_init_connection(): \"\"\" Bind TorRequest to", "try: # call the lumproxy object scholarly.use_lum_proxy() # make the", "bool A boolean flag to return the status of the", "morphed) Returns ------- Address fp.fp.FreeProxy \"\"\" while True: # call", "(old, morphed) Returns ------- Address fp.fp.FreeProxy \"\"\" while True: #", "def get_articleInfo(title): \"\"\" Use the google scholar web URL and", "text == True: # return the ip address pairs as", "open('paper_titles.txt', 'r+') cit_info = open('citations_gs.csv', 'a') cit_info.write(str(alt_list[i].strip( ).split('\\t')[0]) + ','", "while True: try: # init the connection with scholarly and", "article pub = next(search_query) # return the bib entry return", "dimensions web url def get_gs_citations_web(title): \"\"\" Use the google scholar", "restart_tor_system_service(text=False) # assign new connection again scholarly_init_connection() # obtain the", "the same was not distributed with this # file, You", "for assigning a new proxy def set_new_proxy(text=True): \"\"\" Reset the", "# use the tor request for scholarly tor_req = scholarly.use_tor(tor_sock_port=9050,", "of the query\") # come out of the loop break", "the ip address normal_identity = requests.get('http://ipecho.net/plain') # reset the identity", "\"\"\" while True: try: # init the connection with scholarly", "the command Returns ------- Boolean bool \"\"\" # subprocess command", "return true if successful return True def get_articleInfo(title): \"\"\" Use", "# restart the system tor service restart_tor_system_service(text=False) # assign new", "request for scholarly tor_req = scholarly.use_tor(tor_sock_port=9050, \\ tor_control_port=9051, \\ tor_pw=\"<PASSWORD>\")", "command for restarting the tor service tor_restart = subprocess.Popen(['service', 'tor',", "| title: str The title of a scholarly article Returns", "the proxy address to scholarly proxy_works = scholarly.use_proxy(http=proxy, https=proxy) #", "google scholar web URL and requests API to obtain the", "print(\"Attempt Failed, patching new tor identity\") # restart the system", "return just the status return False except: return False #", "TorRequest from scholarly import scholarly from collections import Counter, OrderedDict", "return the proxy details return proxy # function for connecting", "attrgetter # class definition for Rate limiting class RateLimiter: \"\"\"", "place the contents of the list into a file alt_list", "return the ip address pairs as a tuple return (normal_identity.text,", "License. If a copy of the same was not distributed", "using Tor req.reset_identity() # make a request now morphed_identity =", "use the tor request for scholarly tor_req = scholarly.use_tor(tor_sock_port=9050, \\", "connection with scholarly and tor scholarly_init_connection() # search for the", "\"\"\" Reset the identity using TorRequest Parameters ---------- arg1 [OPTIONAL]|", "req = TorRequest(password='<PASSWORD>') # return the ip address normal_identity =", "\"\"\" # subprocess command for stopping the tor service tor_stop", "pairs as a tuple return (normal_identity.text, morphed_identity.text) else: return True", "# print the tor identity print(\"Working Tor identity:\", ips[1]) #", "to return the status of the command Returns ------- Boolean", "operator import attrgetter # class definition for Rate limiting class", "Nothing \"\"\" def __init__(self, maxRate=5, timeUnit=1): self.timeUnit = timeUnit self.deque", "timeUnit=1): self.timeUnit = timeUnit self.deque = deque(maxlen=maxRate) def __call__(self): if", "for stopping the tor service tor_stop = subprocess.Popen(['service', 'tor', 'stop'])", "obtaining the citations using the dimensions web url def get_gs_citations_web(title):", "Source Code Form is subject to the terms of the", "proxy # function for connecting tor to scholarly def scholarly_init_connection():", "for connecting tor to scholarly def scholarly_init_connection(): \"\"\" Bind TorRequest", "new tor identity ips = assign_new_ip(text=True) # use the tor", "# return true if successful return True def get_articleInfo(title): \"\"\"", "obtain the bib entry of the scholarly article pub =", "np import pandas as pd from tqdm import tqdm from", "the ip address pairs as a tuple return (normal_identity.text, morphed_identity.text)", "True: # assign new tor identity ips = assign_new_ip(text=True) #", "tor_status.communicate() if len(stderr) > 0: # return False return False", "not distributed with this # file, You can obtain one", "except Exception as e: # print error message print(\"Attempt Failed,", "# pipe out the stdout, stderr for the subprocess stdout,", "come out and try again break # return the response", "(old, morphed) Returns ------- boolean True/False \"\"\" try: # pass", "set to true then print the output if text: for", "the loop, when successful break # print the tor identity", "Returns ------- Boolean bool \"\"\" # subprocess command for stopping", "\"\"\" while True: try: # call the lumproxy object scholarly.use_lum_proxy()", "the IP address tuple (old, morphed) Returns ------- Address fp.fp.FreeProxy", "service tor_stop = subprocess.Popen(['service', 'tor', 'stop']) # subprocess command for", "self.deque[0] > self.timeUnit: self.deque.append(cTime) return False else: return True self.deque.append(time.time())", "# call the lumproxy object scholarly.use_lum_proxy() # make the query", "stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) # if the label is set to", "subprocess.Popen(['service', 'tor', 'restart']) # subprocess command for restarting the tor", "def __call__(self): if self.deque.maxlen == len(self.deque): cTime = time.time() if", "Class object for putting a rate limit on the number", "else: # return just the status return False except: return", "subprocess.Popen(['service', 'tor', 'stop']) # subprocess command for restarting the tor", "get_gs_citations_web(title): \"\"\" Use the google scholar web URL and requests", "# if the label is set to true then print", "return the ip address normal_identity = requests.get('http://ipecho.net/plain') # reset the", "to true then print the output if text: for output", "print the tor identity print(\"Working Tor identity:\", ips[1]) # function", "the stdout, stderr for the subprocess stdout, stderr = tor_status.communicate()", "'__main__': # iterate over the length length_of_file = len(open('paper_titles.txt').readlines()) #", "text: bool A boolean flag to return the status of", "the status return False except: return False # function for", "scholarly tor_req = scholarly.use_tor(tor_sock_port=9050, \\ tor_control_port=9051, \\ tor_pw=\"<PASSWORD>\") if tor_req:", "print error message print(\"Attempt Failed, patching new tor identity\") #", "identity print(\"Working Tor identity:\", ips[1]) # function for restarting the", "'tor', 'restart']) # subprocess command for restarting the tor service", "return False # function for obtaining the citations using the", "the identity using TorRequest Parameters ---------- arg1 [OPTIONAL]| text: bool", "return the bib entry return pub if __name__ == '__main__':", "> self.timeUnit: self.deque.append(cTime) return False else: return True self.deque.append(time.time()) return", "contents of the list into a file alt_list = open('paper_titles.txt').readlines()", "import attrgetter # class definition for Rate limiting class RateLimiter:", "tor service Parameters ---------- arg1 [OPTIONAL]| text: bool A boolean", "return next(query) # function for assigning new IP address def", "from collections import Counter, OrderedDict from operator import attrgetter #", "text: bool A boolean flag to return the IP address", "as a tuple return (normal_identity.text, morphed_identity.text) else: return True else:", "else: # return true if successful return True def get_articleInfo(title):", "list into a file alt_list = open('paper_titles.txt').readlines() # iterate over", "str The title of a scholarly article Returns ------- Dictionary", "proxy address to scholarly proxy_works = scholarly.use_proxy(http=proxy, https=proxy) # check", "ast import literal_eval from fp.fp import FreeProxy from torrequest import", "scholarly article Returns ------- Dictionary dict \"\"\" while True: try:", "\\ tor_pw=\"<PASSWORD>\") if tor_req: # come out of the loop,", "reset the identity using Tor req.reset_identity() # make a request", "the tor request for scholarly tor_req = scholarly.use_tor(tor_sock_port=9050, \\ tor_control_port=9051,", "loop break except Exception as e: # print error message", "\"\"\" while True: # call the freeproxy object proxy =", "# place the contents of the list into a file", "__name__ == '__main__': # iterate over the length length_of_file =", "__call__(self): if self.deque.maxlen == len(self.deque): cTime = time.time() if cTime", "of the file # write the results to a file", "depending on the flag if morphed_identity != normal_identity: if text", "subject to the terms of the MIT # License. If", "= TorRequest(password='<PASSWORD>') # return the ip address normal_identity = requests.get('http://ipecho.net/plain')", "# come out and try again break # return the", "to return the IP address tuple (old, morphed) Returns -------", "out break # print the ip address depending on the" ]
[ "c.endswith(' m') or c.endswith(' re'), 'path must start with a", "height): \"\"\"adds an ellipse to the path\"\"\" self._curves(pdfgeom.bezierArc(x, y, x", "not long, so we pack onto one line the code", "\"\"\" def __init__(self,code=None): self._code = (code,[])[code is None] self._code_append =", "an efficient way to draw paths on a Canvas. Do", "#top row self.curveTo(x1, y5, x0, y4, x0, y3) #top left", "fp_str(x,y)) def curveTo(self, x1, y1, x2, y2, x3, y3): self._code_append('%s", "add it back into the canvas with one of the", "y4 = y0 + height - t y5 = y0", "height, 0, 360)) def _curves(self,curves,initial='moveTo'): getattr(self,initial)(*curves[0][:2]) for curve in curves:", "expose Path operations ensures they are completed with no run-time", "#history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/pdfgen/pathobject.py __version__=''' $Id$ ''' __doc__=\"\"\" PDFPathObject is an efficient", "__version__=''' $Id$ ''' __doc__=\"\"\" PDFPathObject is an efficient way to", "28/7/99. Draw a partial ellipse inscribed within the rectangle x1,y1,x2,y2,", "self.ellipse(x1, y1, width, height) def roundRect(self, x, y, width, height,", "are completed with no run-time overhead. Ask the Canvas for", "object to expose Path operations ensures they are completed with", "are certain 'modes' to PDF drawing, and making a separate", "y1<y2. The algorithm is an elliptical generalization of the formulae", "roundRect(self, x, y, width, height, radius): \"\"\"Draws a rectangle with", "for the bezier approximation #to a circle. There are six", "operations ensures they are completed with no run-time overhead. Ask", "y axis. #sketch them and it should all make sense!", "radius x3 = x0 + width - radius x4 =", "radius x0 = x x1 = x0 + t x2", "at startAng degrees and covering extent degrees. Angles start with", "operators. Path objects are probably not long, so we pack", "overhead. Ask the Canvas for a PDFPath with getNewPathObject(); moveto/lineto/", "def curveTo(self, x1, y1, x2, y2, x3, y3): self._code_append('%s c'", "for a PDFPath with getNewPathObject(); moveto/lineto/ curveto wherever you want;", "self._code_append = self._init_code_append def _init_code_append(self,c): assert c.endswith(' m') or c.endswith('", "x3, y5) #top right self.lineTo(x2, y5) #top row self.curveTo(x1, y5,", "separate object to expose Path operations ensures they are completed", "self.lineTo(x3, y0) #bottom row self.curveTo(x4, y0, x5, y1, x5, y2)", "with no run-time overhead. Ask the Canvas for a PDFPath", "360)) def _curves(self,curves,initial='moveTo'): getattr(self,initial)(*curves[0][:2]) for curve in curves: self.curveTo(*curve[2:]) def", "y0 + height - t y5 = y0 + height", "self._code.append code_append('n') code_append(c) self._code_append = code_append def getCode(self): \"pack onto", "http://www.tinaja.com/bezarc1.pdf>.\"\"\" self._curves(pdfgeom.bezierArc(x1,y1, x2,y2, startAng, extent)) def arcTo(self, x1,y1, x2,y2, startAng=0,", "efficient way to draw paths on a Canvas. Do not", "PDF drawing, and making a separate object to expose Path", "a canvas to get the operatiosn appended directly so avoiding", "getCode \"\"\" def __init__(self,code=None): self._code = (code,[])[code is None] self._code_append", "extent=90): \"\"\"Contributed to piddlePDF by <NAME>, 28/7/99. Draw a partial", "x1,y1, x2,y2, startAng=0, extent=90): \"\"\"Contributed to piddlePDF by <NAME>, 28/7/99.", "re' % fp_str((x, y, width, height))) def ellipse(self, x, y,", "graphic path. There are certain 'modes' to PDF drawing, and", "self.moveTo(x2, y0) self.lineTo(x3, y0) #bottom row self.curveTo(x4, y0, x5, y1,", "Ltd. 2000-2012 #see license.txt for license details #history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/pdfgen/pathobject.py __version__='''", "moveto or rect' code_append = self._code.append code_append('n') code_append(c) self._code_append =", "None] self._code_append = self._init_code_append def _init_code_append(self,c): assert c.endswith(' m') or", "radius y3 = y0 + height - radius y4 =", "counter-clockwise. These should have x1<x2 and y1<y2. The algorithm is", "x2, y2, x3, y3)) def arc(self, x1,y1, x2,y2, startAng=0, extent=90):", "a rectangle to the path\"\"\" self._code_append('%s re' % fp_str((x, y,", "<filename>dist-packages/reportlab/pdfgen/pathobject.py #Copyright ReportLab Europe Ltd. 2000-2012 #see license.txt for license", "self._code_append('%s re' % fp_str((x, y, width, height))) def ellipse(self, x,", "way to draw paths on a Canvas. Do not instantiate", "rectangle to the path\"\"\" self._code_append('%s re' % fp_str((x, y, width,", "line; used internally\" return ' '.join(self._code) def moveTo(self, x, y):", "\"pack onto one line; used internally\" return ' '.join(self._code) def", "used internally\" return ' '.join(self._code) def moveTo(self, x, y): self._code_append('%s", "x1 = x0 + t x2 = x0 + radius", "y y1 = y0 + t y2 = y0 +", "Path objects are probably not long, so we pack onto", "= x_cen - r y1 = y_cen - r width", "startAng=0, extent=90): \"\"\"Like arc, but draws a line from the", "should all make sense! t = 0.4472 * radius x0", "from the current point to the start if the start", "details #history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/pdfgen/pathobject.py __version__=''' $Id$ ''' __doc__=\"\"\" PDFPathObject is an", "'.join(self._code) def moveTo(self, x, y): self._code_append('%s m' % fp_str(x,y)) def", "ellipse inscribed within the rectangle x1,y1,x2,y2, starting at startAng degrees", "t x5 = x0 + width y0 = y y1", "height - t y5 = y0 + height self.moveTo(x2, y0)", "from pdfgen.py \"\"\" from reportlab.pdfgen import pdfgeom from reportlab.lib.rl_accel import", "\"\"\"adds a circle to the path\"\"\" x1 = x_cen -", "There are certain 'modes' to PDF drawing, and making a", "line the code argument allows a canvas to get the", "- radius x4 = x0 + width - t x5", "#bottom left self.close() def close(self): \"draws a line back to", "six relevant points on the x axis and y axis.", "from the Canvas instead. Progress Reports: 8.83, 2000-01-13, gmcm: created", "self._code_append = code_append def getCode(self): \"pack onto one line; used", "+ height - t y5 = y0 + height self.moveTo(x2,", "canvas to get the operatiosn appended directly so avoiding the", "a line from the current point to the start if", "height): \"\"\"Adds a rectangle to the path\"\"\" self._code_append('%s re' %", "x1, y0, x2, y0) #bottom left self.close() def close(self): \"draws", "PDFPathObject is an efficient way to draw paths on a", "width, height) def roundRect(self, x, y, width, height, radius): \"\"\"Draws", "rounded corners. The corners are approximately quadrants of a circle,", "x, y, width, height): \"\"\"Adds a rectangle to the path\"\"\"", "y3 = y0 + height - radius y4 = y0", "m') or c.endswith(' re'), 'path must start with a moveto", "code_append def getCode(self): \"pack onto one line; used internally\" return", "http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/pdfgen/pathobject.py __version__=''' $Id$ ''' __doc__=\"\"\" PDFPathObject is an efficient way", "def close(self): \"draws a line back to where it started\"", "the start if the start is not the current point.\"\"\"", "x5, y1, x5, y2) #bottom right self.lineTo(x5, y3) #right edge", "path\"\"\" self._code_append('%s re' % fp_str((x, y, width, height))) def ellipse(self,", "x0 + radius x3 = x0 + width - radius", "#use a precomputed set of factors for the bezier approximation", "x0 + width - radius x4 = x0 + width", "must start with a moveto or rect' code_append = self._code.append", "self._curves(pdfgeom.bezierArc(x, y, x + width,y + height, 0, 360)) def", "path. There are certain 'modes' to PDF drawing, and making", "\"\"\" from reportlab.pdfgen import pdfgeom from reportlab.lib.rl_accel import fp_str class", "- r width = height = 2*r self.ellipse(x1, y1, width,", "- radius y4 = y0 + height - t y5", "width, height): \"\"\"adds an ellipse to the path\"\"\" self._curves(pdfgeom.bezierArc(x, y,", "y5) #top right self.lineTo(x2, y5) #top row self.curveTo(x1, y5, x0,", "in <NAME>'s TeX tutorial <URL: http://www.tinaja.com/bezarc1.pdf>.\"\"\" self._curves(pdfgeom.bezierArc(x1,y1, x2,y2, startAng, extent))", "left self.lineTo(x0, y2) #left edge self.curveTo(x0, y1, x1, y0, x2,", "sense! t = 0.4472 * radius x0 = x x1", "of a circle, with the given radius.\"\"\" #use a precomputed", "x axis and y axis. #sketch them and it should", "x3, y3): self._code_append('%s c' % fp_str(x1, y1, x2, y2, x3,", "arc(self, x1,y1, x2,y2, startAng=0, extent=90): \"\"\"Contributed to piddlePDF by <NAME>,", "y, width, height): \"\"\"Adds a rectangle to the path\"\"\" self._code_append('%s", "code_append = self._code.append code_append('n') code_append(c) self._code_append = code_append def getCode(self):", "allows a canvas to get the operatiosn appended directly so", "axis and y axis. #sketch them and it should all", "x5 = x0 + width y0 = y y1 =", "#top right self.lineTo(x2, y5) #top row self.curveTo(x1, y5, x0, y4,", "edge self.curveTo(x5, y4, x4, y5, x3, y5) #top right self.lineTo(x2,", "= y0 + height - t y5 = y0 +", "y2) #left edge self.curveTo(x0, y1, x1, y0, x2, y0) #bottom", "= x0 + t x2 = x0 + radius x3", "ensures they are completed with no run-time overhead. Ask the", "y1, x5, y2) #bottom right self.lineTo(x5, y3) #right edge self.curveTo(x5,", "to the path\"\"\" self._code_append('%s re' % fp_str((x, y, width, height)))", "make sense! t = 0.4472 * radius x0 = x", "width - radius x4 = x0 + width - t", "draws a line from the current point to the start", "shapes; and then add it back into the canvas with", "y1 = y0 + t y2 = y0 + radius", "degrees. Angles start with 0 to the right (+x) and", "license details #history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/pdfgen/pathobject.py __version__=''' $Id$ ''' __doc__=\"\"\" PDFPathObject is", "y0 = y y1 = y0 + t y2 =", "moveto/lineto/ curveto wherever you want; add whole shapes; and then", "x0, y3) #top left self.lineTo(x0, y2) #left edge self.curveTo(x0, y1,", "= x0 + width - t x5 = x0 +", "+ height self.moveTo(x2, y0) self.lineTo(x3, y0) #bottom row self.curveTo(x4, y0,", "directly, obtain one from the Canvas instead. Progress Reports: 8.83,", "close(self): \"draws a line back to where it started\" self._code_append('h')", "\"\"\"Represents a graphic path. There are certain 'modes' to PDF", "def __init__(self,code=None): self._code = (code,[])[code is None] self._code_append = self._init_code_append", "extent),'lineTo') def rect(self, x, y, width, height): \"\"\"Adds a rectangle", "appended directly so avoiding the final getCode \"\"\" def __init__(self,code=None):", "x4, y5, x3, y5) #top right self.lineTo(x2, y5) #top row", "the current point to the start if the start is", "y0) #bottom row self.curveTo(x4, y0, x5, y1, x5, y2) #bottom", "are probably not long, so we pack onto one line", "with getNewPathObject(); moveto/lineto/ curveto wherever you want; add whole shapes;", "if the start is not the current point.\"\"\" self._curves(pdfgeom.bezierArc(x1,y1, x2,y2,", "x x1 = x0 + t x2 = x0 +", "edge self.curveTo(x0, y1, x1, y0, x2, y0) #bottom left self.close()", "of the relevant operators. Path objects are probably not long,", "width, height): \"\"\"Adds a rectangle to the path\"\"\" self._code_append('%s re'", "y2 = y0 + radius y3 = y0 + height", "objects are probably not long, so we pack onto one", "startAng, extent),'lineTo') def rect(self, x, y, width, height): \"\"\"Adds a", "y1, x2, y2, x3, y3)) def arc(self, x1,y1, x2,y2, startAng=0,", "re'), 'path must start with a moveto or rect' code_append", "obtain one from the Canvas instead. Progress Reports: 8.83, 2000-01-13,", "getCode(self): \"pack onto one line; used internally\" return ' '.join(self._code)", "are approximately quadrants of a circle, with the given radius.\"\"\"", "x2,y2, startAng=0, extent=90): \"\"\"Like arc, but draws a line from", "Angles start with 0 to the right (+x) and increase", "for curve in curves: self.curveTo(*curve[2:]) def circle(self, x_cen, y_cen, r):", "t y2 = y0 + radius y3 = y0 +", "approximation #to a circle. There are six relevant points on", "on the x axis and y axis. #sketch them and", "y0) self.lineTo(x3, y0) #bottom row self.curveTo(x4, y0, x5, y1, x5,", "x1, y1, x2, y2, x3, y3): self._code_append('%s c' % fp_str(x1,", "code argument allows a canvas to get the operatiosn appended", "x2, y2, x3, y3): self._code_append('%s c' % fp_str(x1, y1, x2,", "paths on a Canvas. Do not instantiate directly, obtain one", "= y0 + height self.moveTo(x2, y0) self.lineTo(x3, y0) #bottom row", "class PDFPathObject: \"\"\"Represents a graphic path. There are certain 'modes'", "y0, x5, y1, x5, y2) #bottom right self.lineTo(x5, y3) #right", "def arc(self, x1,y1, x2,y2, startAng=0, extent=90): \"\"\"Contributed to piddlePDF by", "+ t x2 = x0 + radius x3 = x0", "within the rectangle x1,y1,x2,y2, starting at startAng degrees and covering", "and y1<y2. The algorithm is an elliptical generalization of the", "def arcTo(self, x1,y1, x2,y2, startAng=0, extent=90): \"\"\"Like arc, but draws", "\"\"\"Adds a rectangle to the path\"\"\" self._code_append('%s re' % fp_str((x,", "directly so avoiding the final getCode \"\"\" def __init__(self,code=None): self._code", "y0 + t y2 = y0 + radius y3 =", "y1, width, height) def roundRect(self, x, y, width, height, radius):", "an elliptical generalization of the formulae in <NAME>'s TeX tutorial", "t y5 = y0 + height self.moveTo(x2, y0) self.lineTo(x3, y0)", "to the path\"\"\" self._curves(pdfgeom.bezierArc(x, y, x + width,y + height,", "#bottom right self.lineTo(x5, y3) #right edge self.curveTo(x5, y4, x4, y5,", "+ radius x3 = x0 + width - radius x4", "formulae in <NAME>'s TeX tutorial <URL: http://www.tinaja.com/bezarc1.pdf>.\"\"\" self._curves(pdfgeom.bezierArc(x1,y1, x2,y2, startAng,", "radius): \"\"\"Draws a rectangle with rounded corners. The corners are", "There are six relevant points on the x axis and", "def ellipse(self, x, y, width, height): \"\"\"adds an ellipse to", "x2,y2, startAng=0, extent=90): \"\"\"Contributed to piddlePDF by <NAME>, 28/7/99. Draw", "line from the current point to the start if the", "self._curves(pdfgeom.bezierArc(x1,y1, x2,y2, startAng, extent)) def arcTo(self, x1,y1, x2,y2, startAng=0, extent=90):", "start is not the current point.\"\"\" self._curves(pdfgeom.bezierArc(x1,y1, x2,y2, startAng, extent),'lineTo')", "radius y4 = y0 + height - t y5 =", "code_append(c) self._code_append = code_append def getCode(self): \"pack onto one line;", "with one of the relevant operators. Path objects are probably", "it should all make sense! t = 0.4472 * radius", "from reportlab.pdfgen import pdfgeom from reportlab.lib.rl_accel import fp_str class PDFPathObject:", "to the path\"\"\" x1 = x_cen - r y1 =", "are six relevant points on the x axis and y", "wherever you want; add whole shapes; and then add it", "def getCode(self): \"pack onto one line; used internally\" return '", "the relevant operators. Path objects are probably not long, so", "c' % fp_str(x1, y1, x2, y2, x3, y3)) def arc(self,", "to the start if the start is not the current", "and y axis. #sketch them and it should all make", "+ width y0 = y y1 = y0 + t", "r width = height = 2*r self.ellipse(x1, y1, width, height)", "- t x5 = x0 + width y0 = y", "fp_str((x, y, width, height))) def ellipse(self, x, y, width, height):", "completed with no run-time overhead. Ask the Canvas for a", "pdfgeom from reportlab.lib.rl_accel import fp_str class PDFPathObject: \"\"\"Represents a graphic", "the path\"\"\" self._curves(pdfgeom.bezierArc(x, y, x + width,y + height, 0,", "def lineTo(self, x, y): self._code_append('%s l' % fp_str(x,y)) def curveTo(self,", "assert c.endswith(' m') or c.endswith(' re'), 'path must start with", "to piddlePDF by <NAME>, 28/7/99. Draw a partial ellipse inscribed", "the final getCode \"\"\" def __init__(self,code=None): self._code = (code,[])[code is", "height = 2*r self.ellipse(x1, y1, width, height) def roundRect(self, x,", "y5, x3, y5) #top right self.lineTo(x2, y5) #top row self.curveTo(x1,", "with a moveto or rect' code_append = self._code.append code_append('n') code_append(c)", "the x axis and y axis. #sketch them and it", "all make sense! t = 0.4472 * radius x0 =", "given radius.\"\"\" #use a precomputed set of factors for the", "self.curveTo(x4, y0, x5, y1, x5, y2) #bottom right self.lineTo(x5, y3)", "y4, x4, y5, x3, y5) #top right self.lineTo(x2, y5) #top", "ellipse to the path\"\"\" self._curves(pdfgeom.bezierArc(x, y, x + width,y +", "\"\"\"Draws a rectangle with rounded corners. The corners are approximately", "+ width - t x5 = x0 + width y0", "and then add it back into the canvas with one", "to PDF drawing, and making a separate object to expose", "start with a moveto or rect' code_append = self._code.append code_append('n')", "rect(self, x, y, width, height): \"\"\"Adds a rectangle to the", "\"\"\"Like arc, but draws a line from the current point", "- r y1 = y_cen - r width = height", "fp_str(x1, y1, x2, y2, x3, y3)) def arc(self, x1,y1, x2,y2,", "path\"\"\" self._curves(pdfgeom.bezierArc(x, y, x + width,y + height, 0, 360))", "from reportlab.lib.rl_accel import fp_str class PDFPathObject: \"\"\"Represents a graphic path.", "= self._init_code_append def _init_code_append(self,c): assert c.endswith(' m') or c.endswith(' re'),", "y2, x3, y3): self._code_append('%s c' % fp_str(x1, y1, x2, y2,", "corners. The corners are approximately quadrants of a circle, with", "approximately quadrants of a circle, with the given radius.\"\"\" #use", "#left edge self.curveTo(x0, y1, x1, y0, x2, y0) #bottom left", "x0, y4, x0, y3) #top left self.lineTo(x0, y2) #left edge", "= x0 + width y0 = y y1 = y0", "2000-01-13, gmcm: created from pdfgen.py \"\"\" from reportlab.pdfgen import pdfgeom", "getattr(self,initial)(*curves[0][:2]) for curve in curves: self.curveTo(*curve[2:]) def circle(self, x_cen, y_cen,", "point.\"\"\" self._curves(pdfgeom.bezierArc(x1,y1, x2,y2, startAng, extent),'lineTo') def rect(self, x, y, width,", "<URL: http://www.tinaja.com/bezarc1.pdf>.\"\"\" self._curves(pdfgeom.bezierArc(x1,y1, x2,y2, startAng, extent)) def arcTo(self, x1,y1, x2,y2,", "radius x4 = x0 + width - t x5 =", "PDFPath with getNewPathObject(); moveto/lineto/ curveto wherever you want; add whole", "circle. There are six relevant points on the x axis", "% fp_str(x,y)) def curveTo(self, x1, y1, x2, y2, x3, y3):", "#Copyright ReportLab Europe Ltd. 2000-2012 #see license.txt for license details", "row self.curveTo(x4, y0, x5, y1, x5, y2) #bottom right self.lineTo(x5,", "the formulae in <NAME>'s TeX tutorial <URL: http://www.tinaja.com/bezarc1.pdf>.\"\"\" self._curves(pdfgeom.bezierArc(x1,y1, x2,y2,", "extent)) def arcTo(self, x1,y1, x2,y2, startAng=0, extent=90): \"\"\"Like arc, but", "+ width,y + height, 0, 360)) def _curves(self,curves,initial='moveTo'): getattr(self,initial)(*curves[0][:2]) for", "right self.lineTo(x5, y3) #right edge self.curveTo(x5, y4, x4, y5, x3,", "one of the relevant operators. Path objects are probably not", "= y0 + height - radius y4 = y0 +", "+ height, 0, 360)) def _curves(self,curves,initial='moveTo'): getattr(self,initial)(*curves[0][:2]) for curve in", "return ' '.join(self._code) def moveTo(self, x, y): self._code_append('%s m' %", "x0 + width - t x5 = x0 + width", "y1 = y_cen - r width = height = 2*r", "starting at startAng degrees and covering extent degrees. Angles start", "import pdfgeom from reportlab.lib.rl_accel import fp_str class PDFPathObject: \"\"\"Represents a", "fp_str class PDFPathObject: \"\"\"Represents a graphic path. There are certain", "= y y1 = y0 + t y2 = y0", "a circle, with the given radius.\"\"\" #use a precomputed set", "0 to the right (+x) and increase counter-clockwise. These should", "y): self._code_append('%s m' % fp_str(x,y)) def lineTo(self, x, y): self._code_append('%s", "height - radius y4 = y0 + height - t", "a circle to the path\"\"\" x1 = x_cen - r", "inscribed within the rectangle x1,y1,x2,y2, starting at startAng degrees and", "Europe Ltd. 2000-2012 #see license.txt for license details #history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/pdfgen/pathobject.py", "probably not long, so we pack onto one line the", "the right (+x) and increase counter-clockwise. These should have x1<x2", "self.close() def close(self): \"draws a line back to where it", "lineTo(self, x, y): self._code_append('%s l' % fp_str(x,y)) def curveTo(self, x1,", "long, so we pack onto one line the code argument", "Ask the Canvas for a PDFPath with getNewPathObject(); moveto/lineto/ curveto", "self.curveTo(x0, y1, x1, y0, x2, y0) #bottom left self.close() def", "license.txt for license details #history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/pdfgen/pathobject.py __version__=''' $Id$ ''' __doc__=\"\"\"", "height self.moveTo(x2, y0) self.lineTo(x3, y0) #bottom row self.curveTo(x4, y0, x5,", "one line the code argument allows a canvas to get", "by <NAME>, 28/7/99. Draw a partial ellipse inscribed within the", "onto one line; used internally\" return ' '.join(self._code) def moveTo(self,", "curves: self.curveTo(*curve[2:]) def circle(self, x_cen, y_cen, r): \"\"\"adds a circle", "y5) #top row self.curveTo(x1, y5, x0, y4, x0, y3) #top", "x1,y1,x2,y2, starting at startAng degrees and covering extent degrees. Angles", "Do not instantiate directly, obtain one from the Canvas instead.", "gmcm: created from pdfgen.py \"\"\" from reportlab.pdfgen import pdfgeom from", "the code argument allows a canvas to get the operatiosn", "width, height, radius): \"\"\"Draws a rectangle with rounded corners. The", "reportlab.pdfgen import pdfgeom from reportlab.lib.rl_accel import fp_str class PDFPathObject: \"\"\"Represents", "of factors for the bezier approximation #to a circle. There", "The corners are approximately quadrants of a circle, with the", "for license details #history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/pdfgen/pathobject.py __version__=''' $Id$ ''' __doc__=\"\"\" PDFPathObject", "should have x1<x2 and y1<y2. The algorithm is an elliptical", "argument allows a canvas to get the operatiosn appended directly", "the path\"\"\" self._code_append('%s re' % fp_str((x, y, width, height))) def", "corners are approximately quadrants of a circle, with the given", "right self.lineTo(x2, y5) #top row self.curveTo(x1, y5, x0, y4, x0,", "startAng, extent)) def arcTo(self, x1,y1, x2,y2, startAng=0, extent=90): \"\"\"Like arc,", "y0 + height - radius y4 = y0 + height", "to the right (+x) and increase counter-clockwise. These should have", "x2, y0) #bottom left self.close() def close(self): \"draws a line", "% fp_str((x, y, width, height))) def ellipse(self, x, y, width,", "get the operatiosn appended directly so avoiding the final getCode", "pdfgen.py \"\"\" from reportlab.pdfgen import pdfgeom from reportlab.lib.rl_accel import fp_str", "x, y, width, height, radius): \"\"\"Draws a rectangle with rounded", "add whole shapes; and then add it back into the", "instead. Progress Reports: 8.83, 2000-01-13, gmcm: created from pdfgen.py \"\"\"", "to expose Path operations ensures they are completed with no", "2000-2012 #see license.txt for license details #history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/pdfgen/pathobject.py __version__=''' $Id$", "and covering extent degrees. Angles start with 0 to the", "and it should all make sense! t = 0.4472 *", "self.lineTo(x5, y3) #right edge self.curveTo(x5, y4, x4, y5, x3, y5)", "y3): self._code_append('%s c' % fp_str(x1, y1, x2, y2, x3, y3))", "one from the Canvas instead. Progress Reports: 8.83, 2000-01-13, gmcm:", "x2,y2, startAng, extent),'lineTo') def rect(self, x, y, width, height): \"\"\"Adds", "2*r self.ellipse(x1, y1, width, height) def roundRect(self, x, y, width,", "+ radius y3 = y0 + height - radius y4", "bezier approximation #to a circle. There are six relevant points", "code_append('n') code_append(c) self._code_append = code_append def getCode(self): \"pack onto one", "so we pack onto one line the code argument allows", "def _init_code_append(self,c): assert c.endswith(' m') or c.endswith(' re'), 'path must", "x3 = x0 + width - radius x4 = x0", "the Canvas for a PDFPath with getNewPathObject(); moveto/lineto/ curveto wherever", "import fp_str class PDFPathObject: \"\"\"Represents a graphic path. There are", "y, width, height))) def ellipse(self, x, y, width, height): \"\"\"adds", "the canvas with one of the relevant operators. Path objects", "instantiate directly, obtain one from the Canvas instead. Progress Reports:", "#to a circle. There are six relevant points on the", "reportlab.lib.rl_accel import fp_str class PDFPathObject: \"\"\"Represents a graphic path. There", "operatiosn appended directly so avoiding the final getCode \"\"\" def", "#bottom row self.curveTo(x4, y0, x5, y1, x5, y2) #bottom right", "rectangle with rounded corners. The corners are approximately quadrants of", "have x1<x2 and y1<y2. The algorithm is an elliptical generalization", "= x0 + radius x3 = x0 + width -", "on a Canvas. Do not instantiate directly, obtain one from", "def moveTo(self, x, y): self._code_append('%s m' % fp_str(x,y)) def lineTo(self,", "<NAME>'s TeX tutorial <URL: http://www.tinaja.com/bezarc1.pdf>.\"\"\" self._curves(pdfgeom.bezierArc(x1,y1, x2,y2, startAng, extent)) def", "piddlePDF by <NAME>, 28/7/99. Draw a partial ellipse inscribed within", "relevant points on the x axis and y axis. #sketch", "curve in curves: self.curveTo(*curve[2:]) def circle(self, x_cen, y_cen, r): \"\"\"adds", "x0 + t x2 = x0 + radius x3 =", "left self.close() def close(self): \"draws a line back to where", "x, y): self._code_append('%s l' % fp_str(x,y)) def curveTo(self, x1, y1,", "whole shapes; and then add it back into the canvas", "making a separate object to expose Path operations ensures they", "back into the canvas with one of the relevant operators.", "y0 + height self.moveTo(x2, y0) self.lineTo(x3, y0) #bottom row self.curveTo(x4,", "= code_append def getCode(self): \"pack onto one line; used internally\"", "= y0 + t y2 = y0 + radius y3", "0.4472 * radius x0 = x x1 = x0 +", "x5, y2) #bottom right self.lineTo(x5, y3) #right edge self.curveTo(x5, y4,", "y0, x2, y0) #bottom left self.close() def close(self): \"draws a", "= 2*r self.ellipse(x1, y1, width, height) def roundRect(self, x, y,", "def roundRect(self, x, y, width, height, radius): \"\"\"Draws a rectangle", "width y0 = y y1 = y0 + t y2", "width = height = 2*r self.ellipse(x1, y1, width, height) def", "a rectangle with rounded corners. The corners are approximately quadrants", "final getCode \"\"\" def __init__(self,code=None): self._code = (code,[])[code is None]", "x0 + width y0 = y y1 = y0 +", "y2, x3, y3)) def arc(self, x1,y1, x2,y2, startAng=0, extent=90): \"\"\"Contributed", "point to the start if the start is not the", "rect' code_append = self._code.append code_append('n') code_append(c) self._code_append = code_append def", "avoiding the final getCode \"\"\" def __init__(self,code=None): self._code = (code,[])[code", "moveTo(self, x, y): self._code_append('%s m' % fp_str(x,y)) def lineTo(self, x,", "startAng=0, extent=90): \"\"\"Contributed to piddlePDF by <NAME>, 28/7/99. Draw a", "the rectangle x1,y1,x2,y2, starting at startAng degrees and covering extent", "def circle(self, x_cen, y_cen, r): \"\"\"adds a circle to the", "t = 0.4472 * radius x0 = x x1 =", "circle to the path\"\"\" x1 = x_cen - r y1", "or rect' code_append = self._code.append code_append('n') code_append(c) self._code_append = code_append", "x, y): self._code_append('%s m' % fp_str(x,y)) def lineTo(self, x, y):", "increase counter-clockwise. These should have x1<x2 and y1<y2. The algorithm", "is not the current point.\"\"\" self._curves(pdfgeom.bezierArc(x1,y1, x2,y2, startAng, extent),'lineTo') def", "self.curveTo(x1, y5, x0, y4, x0, y3) #top left self.lineTo(x0, y2)", "width - t x5 = x0 + width y0 =", "+ width - radius x4 = x0 + width -", "arc, but draws a line from the current point to", "8.83, 2000-01-13, gmcm: created from pdfgen.py \"\"\" from reportlab.pdfgen import", "x2 = x0 + radius x3 = x0 + width", "and increase counter-clockwise. These should have x1<x2 and y1<y2. The", "l' % fp_str(x,y)) def curveTo(self, x1, y1, x2, y2, x3,", "circle, with the given radius.\"\"\" #use a precomputed set of", "__init__(self,code=None): self._code = (code,[])[code is None] self._code_append = self._init_code_append def", "tutorial <URL: http://www.tinaja.com/bezarc1.pdf>.\"\"\" self._curves(pdfgeom.bezierArc(x1,y1, x2,y2, startAng, extent)) def arcTo(self, x1,y1,", "current point to the start if the start is not", "y0 + radius y3 = y0 + height - radius", "\"\"\"adds an ellipse to the path\"\"\" self._curves(pdfgeom.bezierArc(x, y, x +", "axis. #sketch them and it should all make sense! t", "= x x1 = x0 + t x2 = x0", "x + width,y + height, 0, 360)) def _curves(self,curves,initial='moveTo'): getattr(self,initial)(*curves[0][:2])", "run-time overhead. Ask the Canvas for a PDFPath with getNewPathObject();", "elliptical generalization of the formulae in <NAME>'s TeX tutorial <URL:", "the given radius.\"\"\" #use a precomputed set of factors for", "right (+x) and increase counter-clockwise. These should have x1<x2 and", "height, radius): \"\"\"Draws a rectangle with rounded corners. The corners", "you want; add whole shapes; and then add it back", "extent=90): \"\"\"Like arc, but draws a line from the current", "with 0 to the right (+x) and increase counter-clockwise. These", "a partial ellipse inscribed within the rectangle x1,y1,x2,y2, starting at", "pack onto one line the code argument allows a canvas", "fp_str(x,y)) def lineTo(self, x, y): self._code_append('%s l' % fp_str(x,y)) def", "y3) #right edge self.curveTo(x5, y4, x4, y5, x3, y5) #top", "(code,[])[code is None] self._code_append = self._init_code_append def _init_code_append(self,c): assert c.endswith('", "= 0.4472 * radius x0 = x x1 = x0", "y1, x2, y2, x3, y3): self._code_append('%s c' % fp_str(x1, y1,", "circle(self, x_cen, y_cen, r): \"\"\"adds a circle to the path\"\"\"", "PDFPathObject: \"\"\"Represents a graphic path. There are certain 'modes' to", "Canvas for a PDFPath with getNewPathObject(); moveto/lineto/ curveto wherever you", "internally\" return ' '.join(self._code) def moveTo(self, x, y): self._code_append('%s m'", "generalization of the formulae in <NAME>'s TeX tutorial <URL: http://www.tinaja.com/bezarc1.pdf>.\"\"\"", "y): self._code_append('%s l' % fp_str(x,y)) def curveTo(self, x1, y1, x2,", "getNewPathObject(); moveto/lineto/ curveto wherever you want; add whole shapes; and", "<NAME>, 28/7/99. Draw a partial ellipse inscribed within the rectangle", "rectangle x1,y1,x2,y2, starting at startAng degrees and covering extent degrees.", "arcTo(self, x1,y1, x2,y2, startAng=0, extent=90): \"\"\"Like arc, but draws a", "#top left self.lineTo(x0, y2) #left edge self.curveTo(x0, y1, x1, y0,", "self.curveTo(*curve[2:]) def circle(self, x_cen, y_cen, r): \"\"\"adds a circle to", "into the canvas with one of the relevant operators. Path", "Canvas. Do not instantiate directly, obtain one from the Canvas", "one line; used internally\" return ' '.join(self._code) def moveTo(self, x,", "- t y5 = y0 + height self.moveTo(x2, y0) self.lineTo(x3,", "is an efficient way to draw paths on a Canvas.", "#right edge self.curveTo(x5, y4, x4, y5, x3, y5) #top right", "y, x + width,y + height, 0, 360)) def _curves(self,curves,initial='moveTo'):", "x_cen, y_cen, r): \"\"\"adds a circle to the path\"\"\" x1", "These should have x1<x2 and y1<y2. The algorithm is an", "Progress Reports: 8.83, 2000-01-13, gmcm: created from pdfgen.py \"\"\" from", "startAng degrees and covering extent degrees. Angles start with 0", "not instantiate directly, obtain one from the Canvas instead. Progress", "a circle. There are six relevant points on the x", "Draw a partial ellipse inscribed within the rectangle x1,y1,x2,y2, starting", "(+x) and increase counter-clockwise. These should have x1<x2 and y1<y2.", "+ height - radius y4 = y0 + height -", "the start is not the current point.\"\"\" self._curves(pdfgeom.bezierArc(x1,y1, x2,y2, startAng,", "def _curves(self,curves,initial='moveTo'): getattr(self,initial)(*curves[0][:2]) for curve in curves: self.curveTo(*curve[2:]) def circle(self,", "the bezier approximation #to a circle. There are six relevant", "no run-time overhead. Ask the Canvas for a PDFPath with", "is None] self._code_append = self._init_code_append def _init_code_append(self,c): assert c.endswith(' m')", "TeX tutorial <URL: http://www.tinaja.com/bezarc1.pdf>.\"\"\" self._curves(pdfgeom.bezierArc(x1,y1, x2,y2, startAng, extent)) def arcTo(self,", "precomputed set of factors for the bezier approximation #to a", "= x0 + width - radius x4 = x0 +", "self._code_append('%s c' % fp_str(x1, y1, x2, y2, x3, y3)) def", "y5, x0, y4, x0, y3) #top left self.lineTo(x0, y2) #left", "def rect(self, x, y, width, height): \"\"\"Adds a rectangle to", "height) def roundRect(self, x, y, width, height, radius): \"\"\"Draws a", "the Canvas instead. Progress Reports: 8.83, 2000-01-13, gmcm: created from", "a PDFPath with getNewPathObject(); moveto/lineto/ curveto wherever you want; add", "the operatiosn appended directly so avoiding the final getCode \"\"\"", "y_cen, r): \"\"\"adds a circle to the path\"\"\" x1 =", "radius.\"\"\" #use a precomputed set of factors for the bezier", "then add it back into the canvas with one of", "Reports: 8.83, 2000-01-13, gmcm: created from pdfgen.py \"\"\" from reportlab.pdfgen", "% fp_str(x,y)) def lineTo(self, x, y): self._code_append('%s l' % fp_str(x,y))", "width,y + height, 0, 360)) def _curves(self,curves,initial='moveTo'): getattr(self,initial)(*curves[0][:2]) for curve", "but draws a line from the current point to the", "factors for the bezier approximation #to a circle. There are", "points on the x axis and y axis. #sketch them", "self.curveTo(x5, y4, x4, y5, x3, y5) #top right self.lineTo(x2, y5)", "so avoiding the final getCode \"\"\" def __init__(self,code=None): self._code =", "self._code_append('%s l' % fp_str(x,y)) def curveTo(self, x1, y1, x2, y2,", "y4, x0, y3) #top left self.lineTo(x0, y2) #left edge self.curveTo(x0,", "y3) #top left self.lineTo(x0, y2) #left edge self.curveTo(x0, y1, x1,", "y_cen - r width = height = 2*r self.ellipse(x1, y1,", "self.lineTo(x0, y2) #left edge self.curveTo(x0, y1, x1, y0, x2, y0)", "the current point.\"\"\" self._curves(pdfgeom.bezierArc(x1,y1, x2,y2, startAng, extent),'lineTo') def rect(self, x,", "row self.curveTo(x1, y5, x0, y4, x0, y3) #top left self.lineTo(x0,", "it back into the canvas with one of the relevant", "__doc__=\"\"\" PDFPathObject is an efficient way to draw paths on", "to draw paths on a Canvas. Do not instantiate directly,", "= self._code.append code_append('n') code_append(c) self._code_append = code_append def getCode(self): \"pack", "partial ellipse inscribed within the rectangle x1,y1,x2,y2, starting at startAng", "= height = 2*r self.ellipse(x1, y1, width, height) def roundRect(self,", "Path operations ensures they are completed with no run-time overhead.", "start if the start is not the current point.\"\"\" self._curves(pdfgeom.bezierArc(x1,y1,", "= (code,[])[code is None] self._code_append = self._init_code_append def _init_code_append(self,c): assert", "_init_code_append(self,c): assert c.endswith(' m') or c.endswith(' re'), 'path must start", "created from pdfgen.py \"\"\" from reportlab.pdfgen import pdfgeom from reportlab.lib.rl_accel", "to get the operatiosn appended directly so avoiding the final", "start with 0 to the right (+x) and increase counter-clockwise.", "width, height))) def ellipse(self, x, y, width, height): \"\"\"adds an", "a separate object to expose Path operations ensures they are", "self._code = (code,[])[code is None] self._code_append = self._init_code_append def _init_code_append(self,c):", "curveTo(self, x1, y1, x2, y2, x3, y3): self._code_append('%s c' %", "of the formulae in <NAME>'s TeX tutorial <URL: http://www.tinaja.com/bezarc1.pdf>.\"\"\" self._curves(pdfgeom.bezierArc(x1,y1,", "_curves(self,curves,initial='moveTo'): getattr(self,initial)(*curves[0][:2]) for curve in curves: self.curveTo(*curve[2:]) def circle(self, x_cen,", "0, 360)) def _curves(self,curves,initial='moveTo'): getattr(self,initial)(*curves[0][:2]) for curve in curves: self.curveTo(*curve[2:])", "% fp_str(x1, y1, x2, y2, x3, y3)) def arc(self, x1,y1,", "or c.endswith(' re'), 'path must start with a moveto or", "ellipse(self, x, y, width, height): \"\"\"adds an ellipse to the", "x3, y3)) def arc(self, x1,y1, x2,y2, startAng=0, extent=90): \"\"\"Contributed to", "with the given radius.\"\"\" #use a precomputed set of factors", "certain 'modes' to PDF drawing, and making a separate object", "$Id$ ''' __doc__=\"\"\" PDFPathObject is an efficient way to draw", "x1<x2 and y1<y2. The algorithm is an elliptical generalization of", "r y1 = y_cen - r width = height =", "and making a separate object to expose Path operations ensures", "x_cen - r y1 = y_cen - r width =", "path\"\"\" x1 = x_cen - r y1 = y_cen -", "them and it should all make sense! t = 0.4472", "self._init_code_append def _init_code_append(self,c): assert c.endswith(' m') or c.endswith(' re'), 'path", "with rounded corners. The corners are approximately quadrants of a", "not the current point.\"\"\" self._curves(pdfgeom.bezierArc(x1,y1, x2,y2, startAng, extent),'lineTo') def rect(self,", "extent degrees. Angles start with 0 to the right (+x)", "a graphic path. There are certain 'modes' to PDF drawing,", "we pack onto one line the code argument allows a", "= y0 + radius y3 = y0 + height -", "a precomputed set of factors for the bezier approximation #to", "current point.\"\"\" self._curves(pdfgeom.bezierArc(x1,y1, x2,y2, startAng, extent),'lineTo') def rect(self, x, y,", "#see license.txt for license details #history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/pdfgen/pathobject.py __version__=''' $Id$ '''", "r): \"\"\"adds a circle to the path\"\"\" x1 = x_cen", "relevant operators. Path objects are probably not long, so we", "x0 = x x1 = x0 + t x2 =", "a Canvas. Do not instantiate directly, obtain one from the", "canvas with one of the relevant operators. Path objects are", "The algorithm is an elliptical generalization of the formulae in", "\"\"\"Contributed to piddlePDF by <NAME>, 28/7/99. Draw a partial ellipse", "set of factors for the bezier approximation #to a circle.", "ReportLab Europe Ltd. 2000-2012 #see license.txt for license details #history", "x2,y2, startAng, extent)) def arcTo(self, x1,y1, x2,y2, startAng=0, extent=90): \"\"\"Like", "height))) def ellipse(self, x, y, width, height): \"\"\"adds an ellipse", "y2) #bottom right self.lineTo(x5, y3) #right edge self.curveTo(x5, y4, x4,", "'path must start with a moveto or rect' code_append =", "drawing, and making a separate object to expose Path operations", "y, width, height): \"\"\"adds an ellipse to the path\"\"\" self._curves(pdfgeom.bezierArc(x,", "= y_cen - r width = height = 2*r self.ellipse(x1,", "degrees and covering extent degrees. Angles start with 0 to", "onto one line the code argument allows a canvas to", "c.endswith(' re'), 'path must start with a moveto or rect'", "self.lineTo(x2, y5) #top row self.curveTo(x1, y5, x0, y4, x0, y3)", "in curves: self.curveTo(*curve[2:]) def circle(self, x_cen, y_cen, r): \"\"\"adds a", "they are completed with no run-time overhead. Ask the Canvas", "a moveto or rect' code_append = self._code.append code_append('n') code_append(c) self._code_append", "curveto wherever you want; add whole shapes; and then add", "m' % fp_str(x,y)) def lineTo(self, x, y): self._code_append('%s l' %", "algorithm is an elliptical generalization of the formulae in <NAME>'s", "y, width, height, radius): \"\"\"Draws a rectangle with rounded corners.", "want; add whole shapes; and then add it back into", "self._curves(pdfgeom.bezierArc(x1,y1, x2,y2, startAng, extent),'lineTo') def rect(self, x, y, width, height):", "+ t y2 = y0 + radius y3 = y0", "quadrants of a circle, with the given radius.\"\"\" #use a", "y1, x1, y0, x2, y0) #bottom left self.close() def close(self):", "x, y, width, height): \"\"\"adds an ellipse to the path\"\"\"", "x1 = x_cen - r y1 = y_cen - r", "the path\"\"\" x1 = x_cen - r y1 = y_cen", "Canvas instead. Progress Reports: 8.83, 2000-01-13, gmcm: created from pdfgen.py", "''' __doc__=\"\"\" PDFPathObject is an efficient way to draw paths", "self._code_append('%s m' % fp_str(x,y)) def lineTo(self, x, y): self._code_append('%s l'", "covering extent degrees. Angles start with 0 to the right", "is an elliptical generalization of the formulae in <NAME>'s TeX", "an ellipse to the path\"\"\" self._curves(pdfgeom.bezierArc(x, y, x + width,y", "y0) #bottom left self.close() def close(self): \"draws a line back", "y5 = y0 + height self.moveTo(x2, y0) self.lineTo(x3, y0) #bottom", "draw paths on a Canvas. Do not instantiate directly, obtain", "y3)) def arc(self, x1,y1, x2,y2, startAng=0, extent=90): \"\"\"Contributed to piddlePDF", "x4 = x0 + width - t x5 = x0", "t x2 = x0 + radius x3 = x0 +", "'modes' to PDF drawing, and making a separate object to", "#sketch them and it should all make sense! t =", "x1,y1, x2,y2, startAng=0, extent=90): \"\"\"Like arc, but draws a line", "* radius x0 = x x1 = x0 + t", "' '.join(self._code) def moveTo(self, x, y): self._code_append('%s m' % fp_str(x,y))" ]
[ "wikipedia import re import TCPclient as client WORDS = [\"WIKIPEDIA\",\"SEARCH\",\"INFORMATION\"]", "as client WORDS = [\"WIKIPEDIA\",\"SEARCH\",\"INFORMATION\"] def handle(text,mic,profile): # SEARCH ON", "to search about\") #text = mic.activeListen() print \"entering wiki term\"", "= client.grab_input() while text.upper()==\"WIKIPEDIA\": print \"entering while\" text = client.grab_input()", "search about\") #text = mic.activeListen() print \"entering wiki term\" text", "text.upper()==\"WIKIPEDIA\": print \"entering while\" text = client.grab_input() print text answer", "while\" text = client.grab_input() print text answer = wikipedia.summary(text,sentences=3) answer", "handle(text,mic,profile): # SEARCH ON WIKIPEDIA # ny = wikipedia.summary(\"New York\",sentences=3);", "print \"entering wiki term\" text = client.grab_input() while text.upper()==\"WIKIPEDIA\": print", "\"entering wiki term\" text = client.grab_input() while text.upper()==\"WIKIPEDIA\": print \"entering", "= [\"WIKIPEDIA\",\"SEARCH\",\"INFORMATION\"] def handle(text,mic,profile): # SEARCH ON WIKIPEDIA # ny", "mic.activeListen() print \"entering wiki term\" text = client.grab_input() while text.upper()==\"WIKIPEDIA\":", "York\",sentences=3); # mic.say(\"%s\"% ny) #mic.say(\"What you want to search about\")", "# mic.say(\"%s\"% ny) #mic.say(\"What you want to search about\") #text", "def handle(text,mic,profile): # SEARCH ON WIKIPEDIA # ny = wikipedia.summary(\"New", "ON WIKIPEDIA # ny = wikipedia.summary(\"New York\",sentences=3); # mic.say(\"%s\"% ny)", "= wikipedia.summary(\"New York\",sentences=3); # mic.say(\"%s\"% ny) #mic.say(\"What you want to", "import TCPclient as client WORDS = [\"WIKIPEDIA\",\"SEARCH\",\"INFORMATION\"] def handle(text,mic,profile): #", "import wikipedia import re import TCPclient as client WORDS =", "# SEARCH ON WIKIPEDIA # ny = wikipedia.summary(\"New York\",sentences=3); #", "ny) #mic.say(\"What you want to search about\") #text = mic.activeListen()", "= wikipedia.summary(text,sentences=3) answer +=\"\\n\" print answer client.send_out(answer) #mic.say(answer) def isValid(text):", "about\") #text = mic.activeListen() print \"entering wiki term\" text =", "while text.upper()==\"WIKIPEDIA\": print \"entering while\" text = client.grab_input() print text", "WIKIPEDIA # ny = wikipedia.summary(\"New York\",sentences=3); # mic.say(\"%s\"% ny) #mic.say(\"What", "= client.grab_input() print text answer = wikipedia.summary(text,sentences=3) answer +=\"\\n\" print", "+=\"\\n\" print answer client.send_out(answer) #mic.say(answer) def isValid(text): return bool(re.search(r'\\bwikipedia\\b',text, re.IGNORECASE))", "wikipedia.summary(\"New York\",sentences=3); # mic.say(\"%s\"% ny) #mic.say(\"What you want to search", "SEARCH ON WIKIPEDIA # ny = wikipedia.summary(\"New York\",sentences=3); # mic.say(\"%s\"%", "client.grab_input() print text answer = wikipedia.summary(text,sentences=3) answer +=\"\\n\" print answer", "TCPclient as client WORDS = [\"WIKIPEDIA\",\"SEARCH\",\"INFORMATION\"] def handle(text,mic,profile): # SEARCH", "[\"WIKIPEDIA\",\"SEARCH\",\"INFORMATION\"] def handle(text,mic,profile): # SEARCH ON WIKIPEDIA # ny =", "text = client.grab_input() print text answer = wikipedia.summary(text,sentences=3) answer +=\"\\n\"", "client.grab_input() while text.upper()==\"WIKIPEDIA\": print \"entering while\" text = client.grab_input() print", "# ny = wikipedia.summary(\"New York\",sentences=3); # mic.say(\"%s\"% ny) #mic.say(\"What you", "wikipedia.summary(text,sentences=3) answer +=\"\\n\" print answer client.send_out(answer) #mic.say(answer) def isValid(text): return", "mic.say(\"%s\"% ny) #mic.say(\"What you want to search about\") #text =", "= mic.activeListen() print \"entering wiki term\" text = client.grab_input() while", "#mic.say(\"What you want to search about\") #text = mic.activeListen() print", "answer +=\"\\n\" print answer client.send_out(answer) #mic.say(answer) def isValid(text): return bool(re.search(r'\\bwikipedia\\b',text,", "term\" text = client.grab_input() while text.upper()==\"WIKIPEDIA\": print \"entering while\" text", "want to search about\") #text = mic.activeListen() print \"entering wiki", "#text = mic.activeListen() print \"entering wiki term\" text = client.grab_input()", "you want to search about\") #text = mic.activeListen() print \"entering", "import re import TCPclient as client WORDS = [\"WIKIPEDIA\",\"SEARCH\",\"INFORMATION\"] def", "print text answer = wikipedia.summary(text,sentences=3) answer +=\"\\n\" print answer client.send_out(answer)", "WORDS = [\"WIKIPEDIA\",\"SEARCH\",\"INFORMATION\"] def handle(text,mic,profile): # SEARCH ON WIKIPEDIA #", "wiki term\" text = client.grab_input() while text.upper()==\"WIKIPEDIA\": print \"entering while\"", "\"entering while\" text = client.grab_input() print text answer = wikipedia.summary(text,sentences=3)", "client WORDS = [\"WIKIPEDIA\",\"SEARCH\",\"INFORMATION\"] def handle(text,mic,profile): # SEARCH ON WIKIPEDIA", "answer = wikipedia.summary(text,sentences=3) answer +=\"\\n\" print answer client.send_out(answer) #mic.say(answer) def", "text = client.grab_input() while text.upper()==\"WIKIPEDIA\": print \"entering while\" text =", "print \"entering while\" text = client.grab_input() print text answer =", "ny = wikipedia.summary(\"New York\",sentences=3); # mic.say(\"%s\"% ny) #mic.say(\"What you want", "text answer = wikipedia.summary(text,sentences=3) answer +=\"\\n\" print answer client.send_out(answer) #mic.say(answer)", "re import TCPclient as client WORDS = [\"WIKIPEDIA\",\"SEARCH\",\"INFORMATION\"] def handle(text,mic,profile):" ]
[ "all of the saturated \" , random.choice(plural) , \" be", "in range(4): n = input(\"Enter noun : \") noun.append(n) plural", "school cafeteria.\") print(\"The lunch special, prepared by our \" ,", "be eliminated.\") print(\"He rated the cafeteria a \" + letter", "of either a \" , random.choice(noun) , \" salad or", "surprise visit to our \" , random.choice(adjective) , \" school", "eliminated.\") print(\"He rated the cafeteria a \" + letter +", "\" , random.choice(plural) , \" be eliminated.\") print(\"He rated the", "= [] for i in range(4): n = input(\"Enter noun", "overcooked and discovered a live \" , random.choice(noun) , \"", "Eat, Drink, And Be Sick\") noun = [] for i", "+ \" ache.\") print(\"In response, he threw up all over", ": \") noun.append(n) plural = [] for i in range(6):", "threw up all over his \" , random.choice(plural) , \".\")", "nutritious \" , random.choice(plural) , \" as well as low-calorie", "And Be Sick\") noun = [] for i in range(4):", "serve only nutritious \" , random.choice(plural) , \" as well", "that all of the saturated \" , random.choice(plural) , \"", "he threw up all over his \" , random.choice(plural) ,", "to our \" , random.choice(adjective) , \" school cafeteria.\") print(\"The", "\" to be overcooked and discovered a live \" ,", "\" , random.choice(plural) , \" as well as low-calorie \"", "the saturated \" , random.choice(plural) , \" be eliminated.\") print(\"He", "i in range(6): pn = input(\"Enter plural noun : \")", "= [] for i in range(6): pn = input(\"Enter plural", "\" school cafeteria.\") print(\"The lunch special, prepared by our \"", ": \") adjective.append(a) adverb = input(\"Enter adverb : \") letter", "\" + adverb + \" recommended that the school cafeteria", "to be overcooked and discovered a live \" , random.choice(noun)", "balls with a choice of either a \" , random.choice(noun)", "adverb = input(\"Enter adverb : \") letter = input(\"Enter any", "body part : \") print(\"An inspector from the Department of", "a live \" , random.choice(noun) , \" in the fries,causing", "found the meat-\" , random.choice(plural) , \" to be overcooked", "the fries,causing him to have a \" + body_part +", "body_part = input(\"Enter any body part : \") print(\"An inspector", ", random.choice(adjective) , \" school cafeteria.\") print(\"The lunch special, prepared", "random.choice(noun) , \" salad or French \" , random.choice(plural) ,", ", \" in the fries,causing him to have a \"", "inspector found the meat-\" , random.choice(plural) , \" to be", "\" balls with a choice of either a \" ,", "\") adjective.append(a) adverb = input(\"Enter adverb : \") letter =", "in range(6): pn = input(\"Enter plural noun : \") plural.append(pn)", "\" , random.choice(plural) , \".\") print(\"In his report, the inspector", "any body part : \") print(\"An inspector from the Department", "random.choice(noun) , \" Services paid a surprise visit to our", "= [] for i in range(2): a = input(\"Enter adjective", "pn = input(\"Enter plural noun : \") plural.append(pn) adjective =", ", random.choice(noun) , \" salad or French \" , random.choice(plural)", "Department of Health and \", random.choice(noun) , \" Services paid", "recommended that the school cafeteria serve only nutritious \" ,", "print(\"He rated the cafeteria a \" + letter + \"-minus.\")", "\".\") print(\"The inspector found the meat-\" , random.choice(plural) , \"", "the meat-\" , random.choice(plural) , \" to be overcooked and", "adverb : \") letter = input(\"Enter any letter : \")", "was spaghetti and \" , random.choice(noun) , \" balls with", "letter : \") body_part = input(\"Enter any body part :", "input(\"Enter adverb : \") letter = input(\"Enter any letter :", "school cafeteria serve only nutritious \" , random.choice(plural) , \"", "plural noun : \") plural.append(pn) adjective = [] for i", "and that all of the saturated \" , random.choice(plural) ,", "random.choice(plural) , \" to be overcooked and discovered a live", "\" Services paid a surprise visit to our \" ,", "= input(\"Enter plural noun : \") plural.append(pn) adjective = []", "Health and \", random.choice(noun) , \" Services paid a surprise", "a surprise visit to our \" , random.choice(adjective) , \"", "random.choice(plural) , \" as well as low-calorie \" , random.choice(plural)", "a choice of either a \" , random.choice(noun) , \"", "Be Sick\") noun = [] for i in range(4): n", "of Health and \", random.choice(noun) , \" Services paid a", "random.choice(noun) , \" balls with a choice of either a", "in the fries,causing him to have a \" + body_part", "French \" , random.choice(plural) , \".\") print(\"The inspector found the", "noun.append(n) plural = [] for i in range(6): pn =", "our \" , random.choice(adjective) , \"dietician, was spaghetti and \"", "\") print(\"An inspector from the Department of Health and \",", "print(\"Title : Eat, Drink, And Be Sick\") noun = []", "part : \") print(\"An inspector from the Department of Health", "prepared by our \" , random.choice(adjective) , \"dietician, was spaghetti", "\" , random.choice(adjective) , \" school cafeteria.\") print(\"The lunch special,", "= input(\"Enter any letter : \") body_part = input(\"Enter any", "inspector \" + adverb + \" recommended that the school", "well as low-calorie \" , random.choice(plural) , \" and that", ", \" balls with a choice of either a \"", "plural.append(pn) adjective = [] for i in range(2): a =", "spaghetti and \" , random.choice(noun) , \" balls with a", "print(\"In his report, the inspector \" + adverb + \"", "visit to our \" , random.choice(adjective) , \" school cafeteria.\")", "low-calorie \" , random.choice(plural) , \" and that all of", "= input(\"Enter any body part : \") print(\"An inspector from", "live \" , random.choice(noun) , \" in the fries,causing him", ", \".\") print(\"The inspector found the meat-\" , random.choice(plural) ,", "+ \" recommended that the school cafeteria serve only nutritious", "\" as well as low-calorie \" , random.choice(plural) , \"", "all over his \" , random.choice(plural) , \".\") print(\"In his", ", random.choice(plural) , \" and that all of the saturated", "\" , random.choice(adjective) , \"dietician, was spaghetti and \" ,", "from the Department of Health and \", random.choice(noun) , \"", "random.choice(plural) , \" and that all of the saturated \"", ", \" salad or French \" , random.choice(plural) , \".\")", "for i in range(4): n = input(\"Enter noun : \")", "+ adverb + \" recommended that the school cafeteria serve", "import random print(\"Title : Eat, Drink, And Be Sick\") noun", "any letter : \") body_part = input(\"Enter any body part", "and \" , random.choice(noun) , \" balls with a choice", ", \".\") print(\"In his report, the inspector \" + adverb", ": \") plural.append(pn) adjective = [] for i in range(2):", "\" salad or French \" , random.choice(plural) , \".\") print(\"The", "adverb + \" recommended that the school cafeteria serve only", "\" , random.choice(plural) , \".\") print(\"The inspector found the meat-\"", "Drink, And Be Sick\") noun = [] for i in", "random.choice(plural) , \".\") print(\"The inspector found the meat-\" , random.choice(plural)", "ache.\") print(\"In response, he threw up all over his \"", "print(\"In response, he threw up all over his \" ,", ": Eat, Drink, And Be Sick\") noun = [] for", "[] for i in range(6): pn = input(\"Enter plural noun", "as low-calorie \" , random.choice(plural) , \" and that all", ": \") print(\"An inspector from the Department of Health and", "\" , random.choice(noun) , \" in the fries,causing him to", "adjective = [] for i in range(2): a = input(\"Enter", "lunch special, prepared by our \" , random.choice(adjective) , \"dietician,", ", random.choice(noun) , \" balls with a choice of either", "of the saturated \" , random.choice(plural) , \" be eliminated.\")", "saturated \" , random.choice(plural) , \" be eliminated.\") print(\"He rated", "range(6): pn = input(\"Enter plural noun : \") plural.append(pn) adjective", ", random.choice(adjective) , \"dietician, was spaghetti and \" , random.choice(noun)", "[] for i in range(2): a = input(\"Enter adjective :", "random.choice(plural) , \" be eliminated.\") print(\"He rated the cafeteria a", "up all over his \" , random.choice(plural) , \".\") print(\"In", "adjective.append(a) adverb = input(\"Enter adverb : \") letter = input(\"Enter", "that the school cafeteria serve only nutritious \" , random.choice(plural)", "salad or French \" , random.choice(plural) , \".\") print(\"The inspector", "discovered a live \" , random.choice(noun) , \" in the", ", \" be eliminated.\") print(\"He rated the cafeteria a \"", "choice of either a \" , random.choice(noun) , \" salad", "noun = [] for i in range(4): n = input(\"Enter", "either a \" , random.choice(noun) , \" salad or French", "\") letter = input(\"Enter any letter : \") body_part =", "+ body_part + \" ache.\") print(\"In response, he threw up", ", random.choice(plural) , \" be eliminated.\") print(\"He rated the cafeteria", "Services paid a surprise visit to our \" , random.choice(adjective)", "to have a \" + body_part + \" ache.\") print(\"In", "\" + body_part + \" ache.\") print(\"In response, he threw", "his \" , random.choice(plural) , \".\") print(\"In his report, the", "be overcooked and discovered a live \" , random.choice(noun) ,", "input(\"Enter noun : \") noun.append(n) plural = [] for i", "input(\"Enter any body part : \") print(\"An inspector from the", "random.choice(adjective) , \"dietician, was spaghetti and \" , random.choice(noun) ,", "a \" , random.choice(noun) , \" salad or French \"", "\".\") print(\"In his report, the inspector \" + adverb +", ", \" and that all of the saturated \" ,", "i in range(4): n = input(\"Enter noun : \") noun.append(n)", "the Department of Health and \", random.choice(noun) , \" Services", ", random.choice(plural) , \".\") print(\"The inspector found the meat-\" ,", "meat-\" , random.choice(plural) , \" to be overcooked and discovered", ", random.choice(plural) , \" as well as low-calorie \" ,", "random.choice(noun) , \" in the fries,causing him to have a", "only nutritious \" , random.choice(plural) , \" as well as", "\" , random.choice(noun) , \" balls with a choice of", "range(2): a = input(\"Enter adjective : \") adjective.append(a) adverb =", "range(4): n = input(\"Enter noun : \") noun.append(n) plural =", "random.choice(adjective) , \" school cafeteria.\") print(\"The lunch special, prepared by", "the inspector \" + adverb + \" recommended that the", "for i in range(2): a = input(\"Enter adjective : \")", "adjective : \") adjective.append(a) adverb = input(\"Enter adverb : \")", ": \") body_part = input(\"Enter any body part : \")", "and discovered a live \" , random.choice(noun) , \" in", "print(\"The lunch special, prepared by our \" , random.choice(adjective) ,", ", \" Services paid a surprise visit to our \"", "\", random.choice(noun) , \" Services paid a surprise visit to", "special, prepared by our \" , random.choice(adjective) , \"dietician, was", "by our \" , random.choice(adjective) , \"dietician, was spaghetti and", "as well as low-calorie \" , random.choice(plural) , \" and", "fries,causing him to have a \" + body_part + \"", "cafeteria.\") print(\"The lunch special, prepared by our \" , random.choice(adjective)", "with a choice of either a \" , random.choice(noun) ,", "input(\"Enter plural noun : \") plural.append(pn) adjective = [] for", "\" in the fries,causing him to have a \" +", ", \" as well as low-calorie \" , random.choice(plural) ,", "= input(\"Enter noun : \") noun.append(n) plural = [] for", "or French \" , random.choice(plural) , \".\") print(\"The inspector found", ", \" to be overcooked and discovered a live \"", "plural = [] for i in range(6): pn = input(\"Enter", ", \" school cafeteria.\") print(\"The lunch special, prepared by our", "\" recommended that the school cafeteria serve only nutritious \"", "the school cafeteria serve only nutritious \" , random.choice(plural) ,", "\" , random.choice(noun) , \" salad or French \" ,", "our \" , random.choice(adjective) , \" school cafeteria.\") print(\"The lunch", "\") body_part = input(\"Enter any body part : \") print(\"An", "= input(\"Enter adjective : \") adjective.append(a) adverb = input(\"Enter adverb", "have a \" + body_part + \" ache.\") print(\"In response,", "and \", random.choice(noun) , \" Services paid a surprise visit", "\" and that all of the saturated \" , random.choice(plural)", ", \"dietician, was spaghetti and \" , random.choice(noun) , \"", "\"dietician, was spaghetti and \" , random.choice(noun) , \" balls", "report, the inspector \" + adverb + \" recommended that", "\" , random.choice(plural) , \" and that all of the", "= input(\"Enter adverb : \") letter = input(\"Enter any letter", "i in range(2): a = input(\"Enter adjective : \") adjective.append(a)", "body_part + \" ache.\") print(\"In response, he threw up all", "in range(2): a = input(\"Enter adjective : \") adjective.append(a) adverb", "print(\"An inspector from the Department of Health and \", random.choice(noun)", "input(\"Enter adjective : \") adjective.append(a) adverb = input(\"Enter adverb :", "Sick\") noun = [] for i in range(4): n =", "a = input(\"Enter adjective : \") adjective.append(a) adverb = input(\"Enter", ": \") letter = input(\"Enter any letter : \") body_part", "inspector from the Department of Health and \", random.choice(noun) ,", "over his \" , random.choice(plural) , \".\") print(\"In his report,", ", random.choice(plural) , \".\") print(\"In his report, the inspector \"", "[] for i in range(4): n = input(\"Enter noun :", "noun : \") noun.append(n) plural = [] for i in", "for i in range(6): pn = input(\"Enter plural noun :", "\" ache.\") print(\"In response, he threw up all over his", "input(\"Enter any letter : \") body_part = input(\"Enter any body", "random print(\"Title : Eat, Drink, And Be Sick\") noun =", "response, he threw up all over his \" , random.choice(plural)", "print(\"The inspector found the meat-\" , random.choice(plural) , \" to", "noun : \") plural.append(pn) adjective = [] for i in", "random.choice(plural) , \".\") print(\"In his report, the inspector \" +", ", random.choice(noun) , \" in the fries,causing him to have", "\") plural.append(pn) adjective = [] for i in range(2): a", "cafeteria serve only nutritious \" , random.choice(plural) , \" as", "\" be eliminated.\") print(\"He rated the cafeteria a \" +", "his report, the inspector \" + adverb + \" recommended", "paid a surprise visit to our \" , random.choice(adjective) ,", ", random.choice(plural) , \" to be overcooked and discovered a", "\") noun.append(n) plural = [] for i in range(6): pn", "n = input(\"Enter noun : \") noun.append(n) plural = []", "him to have a \" + body_part + \" ache.\")", "a \" + body_part + \" ache.\") print(\"In response, he", "letter = input(\"Enter any letter : \") body_part = input(\"Enter" ]
[ "numpy g = open('/home/srallaba/mgc/transposed/arctic_a0404.mgc','w') x = numpy.loadtxt('/home/srallaba/mgc_spaces/arctic_a0404.mgc') numpy.savetxt(g, numpy.transpose(x)) g.close()", "import numpy g = open('/home/srallaba/mgc/transposed/arctic_a0404.mgc','w') x = numpy.loadtxt('/home/srallaba/mgc_spaces/arctic_a0404.mgc') numpy.savetxt(g, numpy.transpose(x))" ]
[ "from zone_api.core.devices.motion_sensor import MotionSensor from zone_api.core.actions.turn_on_switch import TurnOnSwitch from zone_api_test.core.device_test", "8 INVALID_ITEM_NAME = 'invalid item name' class ZoneManagerTest(DeviceTest): \"\"\" Unit", "Zone from zone_api.core.zone_event import ZoneEvent from zone_api.core.devices.dimmer import Dimmer from", "[self.lightItem, self.motionSensorItem, self.illuminanceSensorItem, self.astroSensorItem, self.dimmerItem, self.fanItem] = items self.illuminanceSensor =", "= [pe.create_switch_item('TestLightName'), pe.create_switch_item('TestMotionSensorName'), pe.create_number_item('IlluminanceSensorName'), pe.create_string_item('AstroSensorName'), pe.create_dimmer_item('TestDimmerName'), pe.create_switch_item('TestFanName'), ] self.set_items(items) super(ZoneManagerTest,", "self.fanItem] = items self.illuminanceSensor = IlluminanceSensor(self.illuminanceSensorItem) self.light = Light(self.lightItem, 2,", "zone = Zone('ff', [self.light, self.motionSensor]) self.zm.add_zone(zone) self.assertTrue(self.zm.get_immutable_instance().on_switch_turned_off( pe.get_event_dispatcher(), self.light, self.light.get_item()))", "self.light, pe.create_string_item(INVALID_ITEM_NAME))) def testOnSwitchTurnedOn_withNonApplicableZone_returnsFalse(self): zone = Zone('ff', [self.light, self.motionSensor]) self.zm.add_zone(zone)", "= Fan(self.fanItem, 2) self.zm = ZoneManager() def tearDown(self): self.zm.stop_auto_report_watch_dog() self.fan._cancel_timer()", "ILLUMINANCE_THRESHOLD_IN_LUX) self.motionSensor = MotionSensor(self.motionSensorItem) self.dimmer = Dimmer(self.dimmerItem, 2, 100, \"0-23:59\")", "pe.get_event_dispatcher(), self.light, pe.create_string_item(INVALID_ITEM_NAME))) def testOnSwitchTurnedOn_withApplicableZone_returnsTrue(self): zone = Zone('ff', [self.light, self.motionSensor])", "pe.create_dimmer_item('TestDimmerName'), pe.create_switch_item('TestFanName'), ] self.set_items(items) super(ZoneManagerTest, self).setUp() [self.lightItem, self.motionSensorItem, self.illuminanceSensorItem, self.astroSensorItem,", "2, 100, \"0-23:59\") self.fan = Fan(self.fanItem, 2) self.zm = ZoneManager()", "Zone('ff', [self.light, self.motionSensor]) self.zm.add_zone(zone) self.assertFalse(self.zm.get_immutable_instance().on_switch_turned_on( pe.get_event_dispatcher(), self.light, pe.create_string_item(INVALID_ITEM_NAME))) def testOnSwitchTurnedOn_withApplicableZone_returnsTrue(self):", "= Dimmer(self.dimmerItem, 2, 100, \"0-23:59\") self.fan = Fan(self.fanItem, 2) self.zm", "testAddZone_validZone_zoneAdded(self): zone1 = Zone('ff') self.zm.add_zone(zone1) self.assertEqual(1, len(self.zm.get_zones())) zone2 = Zone('2f')", "Light, Switch from zone_api.core.devices.illuminance_sensor import IlluminanceSensor from zone_api.core.devices.motion_sensor import MotionSensor", "Unit tests for zone_manager.py. \"\"\" def setUp(self): items = [pe.create_switch_item('TestLightName'),", "self.zm.add_zone(zone2) self.assertEqual(zone1, self.zm.get_immutable_instance().get_containing_zone(self.light)) self.assertEqual(zone2, self.zm.get_immutable_instance().get_containing_zone(self.fan)) def testContainingZone_invalidDevice_returnsNone(self): zone1 = Zone('ff').add_device(self.light)", "= Zone('ff') self.zm.add_zone(zone1) self.assertEqual(1, len(self.zm.get_zones())) zone2 = Zone('2f') self.zm.add_zone(zone2) self.assertEqual(2,", "def testGetZoneById_validZoneId_returnValidZone(self): zone1 = Zone('ff') self.zm.add_zone(zone1) zone2 = Zone('2f') self.zm.add_zone(zone2)", "Zone('sf').add_device(self.fan) self.zm.add_zone(zone1) self.zm.add_zone(zone2) self.assertEqual(2, len(self.zm.get_zones())) self.assertEqual(1, len(self.zm.get_devices_by_type(Light))) self.assertEqual(2, len(self.zm.get_devices_by_type(Switch))) self.assertEqual(0,", "self.zm.get_zone_by_id(zone2.get_id()).get_name()) def testGetZoneById_invalidZoneId_returnNone(self): self.assertTrue(self.zm.get_zone_by_id('invalid zone id') is None) def testRemoveZone_validZone_zoneRemoved(self):", "self.zm.get_immutable_instance().get_containing_zone(self.light)) self.assertEqual(zone2, self.zm.get_immutable_instance().get_containing_zone(self.fan)) def testContainingZone_invalidDevice_returnsNone(self): zone1 = Zone('ff').add_device(self.light) self.zm.add_zone(zone1) self.assertEqual(None,", "def testOnSwitchTurnedOn_noZone_returnsFalse(self): self.assertFalse(self.zm.get_immutable_instance().on_switch_turned_on( pe.get_event_dispatcher(), self.light, pe.create_string_item(INVALID_ITEM_NAME))) def testOnSwitchTurnedOn_withNonApplicableZone_returnsFalse(self): zone =", "zone = Zone('ff', [self.light, self.motionSensor]) self.zm.add_zone(zone) self.assertFalse(self.zm.get_immutable_instance().dispatch_event( ZoneEvent.MOTION, pe.get_event_dispatcher(), self.motionSensor,", "import TurnOnSwitch from zone_api_test.core.device_test import DeviceTest ILLUMINANCE_THRESHOLD_IN_LUX = 8 INVALID_ITEM_NAME", "pe.create_number_item('IlluminanceSensorName'), pe.create_string_item('AstroSensorName'), pe.create_dimmer_item('TestDimmerName'), pe.create_switch_item('TestFanName'), ] self.set_items(items) super(ZoneManagerTest, self).setUp() [self.lightItem, self.motionSensorItem,", "zone1 = Zone('ff') self.zm.add_zone(zone1) zone2 = Zone('2f') self.zm.add_zone(zone2) self.assertEqual(2, len(self.zm.get_zones()))", "import Dimmer from zone_api.core.devices.switch import Fan, Light, Switch from zone_api.core.devices.illuminance_sensor", "ILLUMINANCE_THRESHOLD_IN_LUX - 1) zone = Zone('ff', [self.light, self.motionSensor, self.illuminanceSensor]) zone", "ZoneEvent.MOTION, pe.get_event_dispatcher(), self.motionSensor, self.motionSensor.get_item())) def testOnSwitchTurnedOn_noZone_returnsFalse(self): self.assertFalse(self.zm.get_immutable_instance().on_switch_turned_on( pe.get_event_dispatcher(), self.light, pe.create_string_item(INVALID_ITEM_NAME)))", "pe from zone_api.core.zone import Zone from zone_api.core.zone_event import ZoneEvent from", "self.dimmerItem, self.fanItem] = items self.illuminanceSensor = IlluminanceSensor(self.illuminanceSensorItem) self.light = Light(self.lightItem,", "Zone('2f') self.zm.add_zone(zone2) self.assertEqual(zone1.get_name(), self.zm.get_zone_by_id(zone1.get_id()).get_name()) self.assertEqual(zone2.get_name(), self.zm.get_zone_by_id(zone2.get_id()).get_name()) def testGetZoneById_invalidZoneId_returnNone(self): self.assertTrue(self.zm.get_zone_by_id('invalid zone", "zone = Zone('ff', [self.light, self.motionSensor]) self.zm.add_zone(zone) self.assertFalse(self.zm.get_immutable_instance().on_switch_turned_on( pe.get_event_dispatcher(), self.light, pe.create_string_item(INVALID_ITEM_NAME)))", "Dimmer from zone_api.core.devices.switch import Fan, Light, Switch from zone_api.core.devices.illuminance_sensor import", "items self.illuminanceSensor = IlluminanceSensor(self.illuminanceSensorItem) self.light = Light(self.lightItem, 2, ILLUMINANCE_THRESHOLD_IN_LUX) self.motionSensor", "testGetDevicesByType_variousScenarios_returnsCorrectList(self): zone1 = Zone('ff').add_device(self.light) zone2 = Zone('sf').add_device(self.fan) self.zm.add_zone(zone1) self.zm.add_zone(zone2) self.assertEqual(2,", "self.assertEqual(1, len(self.zm.get_devices_by_type(Light))) self.assertEqual(2, len(self.zm.get_devices_by_type(Switch))) self.assertEqual(0, len(self.zm.get_devices_by_type(Dimmer))) def testOnMotionSensorTurnedOn_noZone_returnsFalse(self): self.assertFalse(self.zm.get_immutable_instance().dispatch_event( ZoneEvent.MOTION,", "testOnSwitchTurnedOff_withNonApplicableZone_returnsFalse(self): zone = Zone('ff', [self.light, self.motionSensor]) self.zm.add_zone(zone) self.assertFalse(self.zm.get_immutable_instance().on_switch_turned_off( pe.get_event_dispatcher(), self.light,", "zone_api.core.devices.motion_sensor import MotionSensor from zone_api.core.actions.turn_on_switch import TurnOnSwitch from zone_api_test.core.device_test import", "zone = Zone('ff', [self.light, self.motionSensor, self.illuminanceSensor]) zone = zone.add_action(TurnOnSwitch()) self.zm.add_zone(zone)", "= 8 INVALID_ITEM_NAME = 'invalid item name' class ZoneManagerTest(DeviceTest): \"\"\"", "testOnSwitchTurnedOn_withApplicableZone_returnsTrue(self): zone = Zone('ff', [self.light, self.motionSensor]) self.zm.add_zone(zone) self.assertTrue(self.zm.get_immutable_instance().on_switch_turned_on( pe.get_event_dispatcher(), self.light,", "self.motionSensorItem, self.illuminanceSensorItem, self.astroSensorItem, self.dimmerItem, self.fanItem] = items self.illuminanceSensor = IlluminanceSensor(self.illuminanceSensorItem)", "setUp(self): items = [pe.create_switch_item('TestLightName'), pe.create_switch_item('TestMotionSensorName'), pe.create_number_item('IlluminanceSensorName'), pe.create_string_item('AstroSensorName'), pe.create_dimmer_item('TestDimmerName'), pe.create_switch_item('TestFanName'), ]", "zone2 = Zone('2f') self.zm.add_zone(zone2) self.assertEqual(zone1.get_name(), self.zm.get_zone_by_id(zone1.get_id()).get_name()) self.assertEqual(zone2.get_name(), self.zm.get_zone_by_id(zone2.get_id()).get_name()) def testGetZoneById_invalidZoneId_returnNone(self):", "IlluminanceSensor from zone_api.core.devices.motion_sensor import MotionSensor from zone_api.core.actions.turn_on_switch import TurnOnSwitch from", "zone = zone.add_action(TurnOnSwitch()) self.zm.add_zone(zone) self.assertTrue(self.zm.get_immutable_instance().dispatch_event( ZoneEvent.MOTION, pe.get_event_dispatcher(), self.motionSensor, self.motionSensor.get_item())) def", "def testOnMotionSensorTurnedOn_withNonApplicableZone_returnsFalse(self): zone = Zone('ff', [self.light, self.motionSensor]) self.zm.add_zone(zone) self.assertFalse(self.zm.get_immutable_instance().dispatch_event( ZoneEvent.MOTION,", "pe.create_switch_item('TestFanName'), ] self.set_items(items) super(ZoneManagerTest, self).setUp() [self.lightItem, self.motionSensorItem, self.illuminanceSensorItem, self.astroSensorItem, self.dimmerItem,", "Light(self.lightItem, 2, ILLUMINANCE_THRESHOLD_IN_LUX) self.motionSensor = MotionSensor(self.motionSensorItem) self.dimmer = Dimmer(self.dimmerItem, 2,", "from zone_api.core.devices.dimmer import Dimmer from zone_api.core.devices.switch import Fan, Light, Switch", "def testAddZone_validZone_zoneAdded(self): zone1 = Zone('ff') self.zm.add_zone(zone1) self.assertEqual(1, len(self.zm.get_zones())) zone2 =", "self.assertTrue(self.zm.get_immutable_instance().on_switch_turned_on( pe.get_event_dispatcher(), self.light, self.light.get_item())) def testOnSwitchTurnedOff_noZone_returnsFalse(self): self.assertFalse(self.zm.get_immutable_instance().on_switch_turned_off( pe.get_event_dispatcher(), self.light, pe.create_string_item(INVALID_ITEM_NAME)))", "pe.create_string_item(INVALID_ITEM_NAME))) def testOnSwitchTurnedOn_withNonApplicableZone_returnsFalse(self): zone = Zone('ff', [self.light, self.motionSensor]) self.zm.add_zone(zone) self.assertFalse(self.zm.get_immutable_instance().on_switch_turned_on(", "tearDown(self): self.zm.stop_auto_report_watch_dog() self.fan._cancel_timer() self.dimmer._cancel_timer() self.light._cancel_timer() super(ZoneManagerTest, self).tearDown() def testAddZone_validZone_zoneAdded(self): zone1", "self.light, pe.create_string_item(INVALID_ITEM_NAME))) def testOnSwitchTurnedOff_withApplicableZone_returnsTrue(self): zone = Zone('ff', [self.light, self.motionSensor]) self.zm.add_zone(zone)", "def testOnSwitchTurnedOn_withNonApplicableZone_returnsFalse(self): zone = Zone('ff', [self.light, self.motionSensor]) self.zm.add_zone(zone) self.assertFalse(self.zm.get_immutable_instance().on_switch_turned_on( pe.get_event_dispatcher(),", "= 'invalid item name' class ZoneManagerTest(DeviceTest): \"\"\" Unit tests for", "ZoneEvent.MOTION, pe.get_event_dispatcher(), self.motionSensor, pe.create_string_item(INVALID_ITEM_NAME))) def testOnMotionSensorTurnedOn_withNonApplicableZone_returnsFalse(self): zone = Zone('ff', [self.light,", "self.motionSensor]) self.zm.add_zone(zone) self.assertTrue(self.zm.get_immutable_instance().on_switch_turned_on( pe.get_event_dispatcher(), self.light, self.light.get_item())) def testOnSwitchTurnedOff_noZone_returnsFalse(self): self.assertFalse(self.zm.get_immutable_instance().on_switch_turned_off( pe.get_event_dispatcher(),", "tests for zone_manager.py. \"\"\" def setUp(self): items = [pe.create_switch_item('TestLightName'), pe.create_switch_item('TestMotionSensorName'),", "zone_manager.py. \"\"\" def setUp(self): items = [pe.create_switch_item('TestLightName'), pe.create_switch_item('TestMotionSensorName'), pe.create_number_item('IlluminanceSensorName'), pe.create_string_item('AstroSensorName'),", "self.assertEqual(0, len(self.zm.get_devices_by_type(Dimmer))) def testOnMotionSensorTurnedOn_noZone_returnsFalse(self): self.assertFalse(self.zm.get_immutable_instance().dispatch_event( ZoneEvent.MOTION, pe.get_event_dispatcher(), self.motionSensor, pe.create_string_item(INVALID_ITEM_NAME))) def", "[self.light, self.motionSensor, self.illuminanceSensor]) zone = zone.add_action(TurnOnSwitch()) self.zm.add_zone(zone) self.assertTrue(self.zm.get_immutable_instance().dispatch_event( ZoneEvent.MOTION, pe.get_event_dispatcher(),", "'invalid item name' class ZoneManagerTest(DeviceTest): \"\"\" Unit tests for zone_manager.py.", "self.assertEqual(2, len(self.zm.get_devices_by_type(Switch))) self.assertEqual(0, len(self.zm.get_devices_by_type(Dimmer))) def testOnMotionSensorTurnedOn_noZone_returnsFalse(self): self.assertFalse(self.zm.get_immutable_instance().dispatch_event( ZoneEvent.MOTION, pe.get_event_dispatcher(), self.motionSensor,", "self.dimmer = Dimmer(self.dimmerItem, 2, 100, \"0-23:59\") self.fan = Fan(self.fanItem, 2)", "self.zm.add_zone(zone1) self.zm.add_zone(zone2) self.assertEqual(zone1, self.zm.get_immutable_instance().get_containing_zone(self.light)) self.assertEqual(zone2, self.zm.get_immutable_instance().get_containing_zone(self.fan)) def testContainingZone_invalidDevice_returnsNone(self): zone1 =", "def testOnMotionSensorTurnedOn_noZone_returnsFalse(self): self.assertFalse(self.zm.get_immutable_instance().dispatch_event( ZoneEvent.MOTION, pe.get_event_dispatcher(), self.motionSensor, pe.create_string_item(INVALID_ITEM_NAME))) def testOnMotionSensorTurnedOn_withNonApplicableZone_returnsFalse(self): zone", "zone1 = Zone('ff').add_device(self.light) self.zm.add_zone(zone1) self.assertEqual(None, self.zm.get_immutable_instance().get_containing_zone(self.fan)) def testGetDevicesByType_variousScenarios_returnsCorrectList(self): zone1 =", "= Zone('ff') self.zm.add_zone(zone1) zone2 = Zone('2f') self.zm.add_zone(zone2) self.assertEqual(2, len(self.zm.get_zones())) self.zm.remove_zone(zone1)", "= IlluminanceSensor(self.illuminanceSensorItem) self.light = Light(self.lightItem, 2, ILLUMINANCE_THRESHOLD_IN_LUX) self.motionSensor = MotionSensor(self.motionSensorItem)", "zone id') is None) def testRemoveZone_validZone_zoneRemoved(self): zone1 = Zone('ff') self.zm.add_zone(zone1)", "self.zm.add_zone(zone) self.assertFalse(self.zm.get_immutable_instance().on_switch_turned_off( pe.get_event_dispatcher(), self.light, pe.create_string_item(INVALID_ITEM_NAME))) def testOnSwitchTurnedOff_withApplicableZone_returnsTrue(self): zone = Zone('ff',", "self.motionSensor = MotionSensor(self.motionSensorItem) self.dimmer = Dimmer(self.dimmerItem, 2, 100, \"0-23:59\") self.fan", "= Light(self.lightItem, 2, ILLUMINANCE_THRESHOLD_IN_LUX) self.motionSensor = MotionSensor(self.motionSensorItem) self.dimmer = Dimmer(self.dimmerItem,", "def setUp(self): items = [pe.create_switch_item('TestLightName'), pe.create_switch_item('TestMotionSensorName'), pe.create_number_item('IlluminanceSensorName'), pe.create_string_item('AstroSensorName'), pe.create_dimmer_item('TestDimmerName'), pe.create_switch_item('TestFanName'),", "is None) def testRemoveZone_validZone_zoneRemoved(self): zone1 = Zone('ff') self.zm.add_zone(zone1) zone2 =", "self.zm.add_zone(zone2) self.assertEqual(2, len(self.zm.get_zones())) self.zm.remove_zone(zone1) self.assertEqual(1, len(self.zm.get_zones())) self.zm.remove_zone(zone2) self.assertEqual(0, len(self.zm.get_zones())) def", "self.assertEqual(None, self.zm.get_immutable_instance().get_containing_zone(self.fan)) def testGetDevicesByType_variousScenarios_returnsCorrectList(self): zone1 = Zone('ff').add_device(self.light) zone2 = Zone('sf').add_device(self.fan)", "Zone('ff') self.zm.add_zone(zone1) self.assertEqual(1, len(self.zm.get_zones())) zone2 = Zone('2f') self.zm.add_zone(zone2) self.assertEqual(2, len(self.zm.get_zones()))", "= Zone('2f') self.zm.add_zone(zone2) self.assertEqual(zone1.get_name(), self.zm.get_zone_by_id(zone1.get_id()).get_name()) self.assertEqual(zone2.get_name(), self.zm.get_zone_by_id(zone2.get_id()).get_name()) def testGetZoneById_invalidZoneId_returnNone(self): self.assertTrue(self.zm.get_zone_by_id('invalid", "pe.get_event_dispatcher(), self.motionSensor, pe.create_string_item(INVALID_ITEM_NAME))) def testOnMotionSensorTurnedOn_withApplicableZone_returnsTrue(self): self.assertFalse(self.light.is_on()) pe.set_number_value(self.illuminanceSensorItem, ILLUMINANCE_THRESHOLD_IN_LUX - 1)", "name' class ZoneManagerTest(DeviceTest): \"\"\" Unit tests for zone_manager.py. \"\"\" def", "= Zone('sf').add_device(self.fan) self.zm.add_zone(zone1) self.zm.add_zone(zone2) self.assertEqual(zone1, self.zm.get_immutable_instance().get_containing_zone(self.light)) self.assertEqual(zone2, self.zm.get_immutable_instance().get_containing_zone(self.fan)) def testContainingZone_invalidDevice_returnsNone(self):", "= Zone('ff').add_device(self.light) zone2 = Zone('sf').add_device(self.fan) self.zm.add_zone(zone1) self.zm.add_zone(zone2) self.assertEqual(2, len(self.zm.get_zones())) self.assertEqual(1,", "self.set_items(items) super(ZoneManagerTest, self).setUp() [self.lightItem, self.motionSensorItem, self.illuminanceSensorItem, self.astroSensorItem, self.dimmerItem, self.fanItem] =", "pe.get_event_dispatcher(), self.motionSensor, self.motionSensor.get_item())) def testOnSwitchTurnedOn_noZone_returnsFalse(self): self.assertFalse(self.zm.get_immutable_instance().on_switch_turned_on( pe.get_event_dispatcher(), self.light, pe.create_string_item(INVALID_ITEM_NAME))) def", "= Zone('2f') self.zm.add_zone(zone2) self.assertEqual(2, len(self.zm.get_zones())) def testGetZoneById_validZoneId_returnValidZone(self): zone1 = Zone('ff')", "[self.light, self.motionSensor]) self.zm.add_zone(zone) self.assertFalse(self.zm.get_immutable_instance().on_switch_turned_on( pe.get_event_dispatcher(), self.light, pe.create_string_item(INVALID_ITEM_NAME))) def testOnSwitchTurnedOn_withApplicableZone_returnsTrue(self): zone", "pe.get_event_dispatcher(), self.light, pe.create_string_item(INVALID_ITEM_NAME))) def testOnSwitchTurnedOff_withApplicableZone_returnsTrue(self): zone = Zone('ff', [self.light, self.motionSensor])", "def testOnSwitchTurnedOff_withApplicableZone_returnsTrue(self): zone = Zone('ff', [self.light, self.motionSensor]) self.zm.add_zone(zone) self.assertTrue(self.zm.get_immutable_instance().on_switch_turned_off( pe.get_event_dispatcher(),", "2, ILLUMINANCE_THRESHOLD_IN_LUX) self.motionSensor = MotionSensor(self.motionSensorItem) self.dimmer = Dimmer(self.dimmerItem, 2, 100,", "Zone('ff') self.zm.add_zone(zone1) zone2 = Zone('2f') self.zm.add_zone(zone2) self.assertEqual(2, len(self.zm.get_zones())) self.zm.remove_zone(zone1) self.assertEqual(1,", "self.zm.remove_zone(zone2) self.assertEqual(0, len(self.zm.get_zones())) def testContainingZone_validDevice_returnsCorrectZone(self): zone1 = Zone('ff').add_device(self.light) zone2 =", "[self.light, self.motionSensor]) self.zm.add_zone(zone) self.assertFalse(self.zm.get_immutable_instance().dispatch_event( ZoneEvent.MOTION, pe.get_event_dispatcher(), self.motionSensor, pe.create_string_item(INVALID_ITEM_NAME))) def testOnMotionSensorTurnedOn_withApplicableZone_returnsTrue(self):", "self.zm.get_immutable_instance().get_containing_zone(self.fan)) def testGetDevicesByType_variousScenarios_returnsCorrectList(self): zone1 = Zone('ff').add_device(self.light) zone2 = Zone('sf').add_device(self.fan) self.zm.add_zone(zone1)", "from zone_api_test.core.device_test import DeviceTest ILLUMINANCE_THRESHOLD_IN_LUX = 8 INVALID_ITEM_NAME = 'invalid", "- 1) zone = Zone('ff', [self.light, self.motionSensor, self.illuminanceSensor]) zone =", "self.zm = ZoneManager() def tearDown(self): self.zm.stop_auto_report_watch_dog() self.fan._cancel_timer() self.dimmer._cancel_timer() self.light._cancel_timer() super(ZoneManagerTest,", "self.zm.add_zone(zone1) zone2 = Zone('2f') self.zm.add_zone(zone2) self.assertEqual(2, len(self.zm.get_zones())) self.zm.remove_zone(zone1) self.assertEqual(1, len(self.zm.get_zones()))", "self.motionSensor, pe.create_string_item(INVALID_ITEM_NAME))) def testOnMotionSensorTurnedOn_withApplicableZone_returnsTrue(self): self.assertFalse(self.light.is_on()) pe.set_number_value(self.illuminanceSensorItem, ILLUMINANCE_THRESHOLD_IN_LUX - 1) zone", "pe.get_event_dispatcher(), self.light, pe.create_string_item(INVALID_ITEM_NAME))) def testOnSwitchTurnedOn_withNonApplicableZone_returnsFalse(self): zone = Zone('ff', [self.light, self.motionSensor])", "<gh_stars>1-10 from zone_api.core.zone_manager import ZoneManager from zone_api import platform_encapsulator as", "zone = Zone('ff', [self.light, self.motionSensor]) self.zm.add_zone(zone) self.assertFalse(self.zm.get_immutable_instance().on_switch_turned_off( pe.get_event_dispatcher(), self.light, pe.create_string_item(INVALID_ITEM_NAME)))", "[pe.create_switch_item('TestLightName'), pe.create_switch_item('TestMotionSensorName'), pe.create_number_item('IlluminanceSensorName'), pe.create_string_item('AstroSensorName'), pe.create_dimmer_item('TestDimmerName'), pe.create_switch_item('TestFanName'), ] self.set_items(items) super(ZoneManagerTest, self).setUp()", "self.zm.add_zone(zone2) self.assertEqual(2, len(self.zm.get_zones())) def testGetZoneById_validZoneId_returnValidZone(self): zone1 = Zone('ff') self.zm.add_zone(zone1) zone2", "ILLUMINANCE_THRESHOLD_IN_LUX = 8 INVALID_ITEM_NAME = 'invalid item name' class ZoneManagerTest(DeviceTest):", "for zone_manager.py. \"\"\" def setUp(self): items = [pe.create_switch_item('TestLightName'), pe.create_switch_item('TestMotionSensorName'), pe.create_number_item('IlluminanceSensorName'),", "self.assertEqual(2, len(self.zm.get_zones())) self.zm.remove_zone(zone1) self.assertEqual(1, len(self.zm.get_zones())) self.zm.remove_zone(zone2) self.assertEqual(0, len(self.zm.get_zones())) def testContainingZone_validDevice_returnsCorrectZone(self):", "import MotionSensor from zone_api.core.actions.turn_on_switch import TurnOnSwitch from zone_api_test.core.device_test import DeviceTest", "INVALID_ITEM_NAME = 'invalid item name' class ZoneManagerTest(DeviceTest): \"\"\" Unit tests", "testContainingZone_validDevice_returnsCorrectZone(self): zone1 = Zone('ff').add_device(self.light) zone2 = Zone('sf').add_device(self.fan) self.zm.add_zone(zone1) self.zm.add_zone(zone2) self.assertEqual(zone1,", "testOnMotionSensorTurnedOn_noZone_returnsFalse(self): self.assertFalse(self.zm.get_immutable_instance().dispatch_event( ZoneEvent.MOTION, pe.get_event_dispatcher(), self.motionSensor, pe.create_string_item(INVALID_ITEM_NAME))) def testOnMotionSensorTurnedOn_withNonApplicableZone_returnsFalse(self): zone =", "pe.get_event_dispatcher(), self.light, self.light.get_item())) def testOnSwitchTurnedOff_noZone_returnsFalse(self): self.assertFalse(self.zm.get_immutable_instance().on_switch_turned_off( pe.get_event_dispatcher(), self.light, pe.create_string_item(INVALID_ITEM_NAME))) def", "self.zm.add_zone(zone1) self.assertEqual(1, len(self.zm.get_zones())) zone2 = Zone('2f') self.zm.add_zone(zone2) self.assertEqual(2, len(self.zm.get_zones())) def", "\"0-23:59\") self.fan = Fan(self.fanItem, 2) self.zm = ZoneManager() def tearDown(self):", "ZoneEvent from zone_api.core.devices.dimmer import Dimmer from zone_api.core.devices.switch import Fan, Light,", "zone1 = Zone('ff').add_device(self.light) zone2 = Zone('sf').add_device(self.fan) self.zm.add_zone(zone1) self.zm.add_zone(zone2) self.assertEqual(zone1, self.zm.get_immutable_instance().get_containing_zone(self.light))", "self.light, pe.create_string_item(INVALID_ITEM_NAME))) def testOnSwitchTurnedOn_withApplicableZone_returnsTrue(self): zone = Zone('ff', [self.light, self.motionSensor]) self.zm.add_zone(zone)", "def testOnSwitchTurnedOff_noZone_returnsFalse(self): self.assertFalse(self.zm.get_immutable_instance().on_switch_turned_off( pe.get_event_dispatcher(), self.light, pe.create_string_item(INVALID_ITEM_NAME))) def testOnSwitchTurnedOff_withNonApplicableZone_returnsFalse(self): zone =", "self.motionSensor, pe.create_string_item(INVALID_ITEM_NAME))) def testOnMotionSensorTurnedOn_withNonApplicableZone_returnsFalse(self): zone = Zone('ff', [self.light, self.motionSensor]) self.zm.add_zone(zone)", "len(self.zm.get_zones())) self.zm.remove_zone(zone2) self.assertEqual(0, len(self.zm.get_zones())) def testContainingZone_validDevice_returnsCorrectZone(self): zone1 = Zone('ff').add_device(self.light) zone2", "pe.create_string_item(INVALID_ITEM_NAME))) def testOnMotionSensorTurnedOn_withNonApplicableZone_returnsFalse(self): zone = Zone('ff', [self.light, self.motionSensor]) self.zm.add_zone(zone) self.assertFalse(self.zm.get_immutable_instance().dispatch_event(", "id') is None) def testRemoveZone_validZone_zoneRemoved(self): zone1 = Zone('ff') self.zm.add_zone(zone1) zone2", "zone_api.core.zone import Zone from zone_api.core.zone_event import ZoneEvent from zone_api.core.devices.dimmer import", "= Zone('ff', [self.light, self.motionSensor, self.illuminanceSensor]) zone = zone.add_action(TurnOnSwitch()) self.zm.add_zone(zone) self.assertTrue(self.zm.get_immutable_instance().dispatch_event(", "import ZoneManager from zone_api import platform_encapsulator as pe from zone_api.core.zone", "self.assertFalse(self.light.is_on()) pe.set_number_value(self.illuminanceSensorItem, ILLUMINANCE_THRESHOLD_IN_LUX - 1) zone = Zone('ff', [self.light, self.motionSensor,", "self).setUp() [self.lightItem, self.motionSensorItem, self.illuminanceSensorItem, self.astroSensorItem, self.dimmerItem, self.fanItem] = items self.illuminanceSensor", "\"\"\" Unit tests for zone_manager.py. \"\"\" def setUp(self): items =", "Zone('2f') self.zm.add_zone(zone2) self.assertEqual(2, len(self.zm.get_zones())) def testGetZoneById_validZoneId_returnValidZone(self): zone1 = Zone('ff') self.zm.add_zone(zone1)", "\"\"\" def setUp(self): items = [pe.create_switch_item('TestLightName'), pe.create_switch_item('TestMotionSensorName'), pe.create_number_item('IlluminanceSensorName'), pe.create_string_item('AstroSensorName'), pe.create_dimmer_item('TestDimmerName'),", "pe.get_event_dispatcher(), self.light, pe.create_string_item(INVALID_ITEM_NAME))) def testOnSwitchTurnedOff_withNonApplicableZone_returnsFalse(self): zone = Zone('ff', [self.light, self.motionSensor])", "zone_api.core.devices.switch import Fan, Light, Switch from zone_api.core.devices.illuminance_sensor import IlluminanceSensor from", "MotionSensor from zone_api.core.actions.turn_on_switch import TurnOnSwitch from zone_api_test.core.device_test import DeviceTest ILLUMINANCE_THRESHOLD_IN_LUX", "self).tearDown() def testAddZone_validZone_zoneAdded(self): zone1 = Zone('ff') self.zm.add_zone(zone1) self.assertEqual(1, len(self.zm.get_zones())) zone2", "self.motionSensor]) self.zm.add_zone(zone) self.assertFalse(self.zm.get_immutable_instance().on_switch_turned_on( pe.get_event_dispatcher(), self.light, pe.create_string_item(INVALID_ITEM_NAME))) def testOnSwitchTurnedOn_withApplicableZone_returnsTrue(self): zone =", "items = [pe.create_switch_item('TestLightName'), pe.create_switch_item('TestMotionSensorName'), pe.create_number_item('IlluminanceSensorName'), pe.create_string_item('AstroSensorName'), pe.create_dimmer_item('TestDimmerName'), pe.create_switch_item('TestFanName'), ] self.set_items(items)", "super(ZoneManagerTest, self).tearDown() def testAddZone_validZone_zoneAdded(self): zone1 = Zone('ff') self.zm.add_zone(zone1) self.assertEqual(1, len(self.zm.get_zones()))", "Zone('ff').add_device(self.light) self.zm.add_zone(zone1) self.assertEqual(None, self.zm.get_immutable_instance().get_containing_zone(self.fan)) def testGetDevicesByType_variousScenarios_returnsCorrectList(self): zone1 = Zone('ff').add_device(self.light) zone2", "zone2 = Zone('sf').add_device(self.fan) self.zm.add_zone(zone1) self.zm.add_zone(zone2) self.assertEqual(2, len(self.zm.get_zones())) self.assertEqual(1, len(self.zm.get_devices_by_type(Light))) self.assertEqual(2,", "zone1 = Zone('ff') self.zm.add_zone(zone1) self.assertEqual(1, len(self.zm.get_zones())) zone2 = Zone('2f') self.zm.add_zone(zone2)", "= MotionSensor(self.motionSensorItem) self.dimmer = Dimmer(self.dimmerItem, 2, 100, \"0-23:59\") self.fan =", "ZoneManager from zone_api import platform_encapsulator as pe from zone_api.core.zone import", "import Zone from zone_api.core.zone_event import ZoneEvent from zone_api.core.devices.dimmer import Dimmer", "Fan(self.fanItem, 2) self.zm = ZoneManager() def tearDown(self): self.zm.stop_auto_report_watch_dog() self.fan._cancel_timer() self.dimmer._cancel_timer()", "self.assertFalse(self.zm.get_immutable_instance().on_switch_turned_off( pe.get_event_dispatcher(), self.light, pe.create_string_item(INVALID_ITEM_NAME))) def testOnSwitchTurnedOff_withApplicableZone_returnsTrue(self): zone = Zone('ff', [self.light,", "def testContainingZone_invalidDevice_returnsNone(self): zone1 = Zone('ff').add_device(self.light) self.zm.add_zone(zone1) self.assertEqual(None, self.zm.get_immutable_instance().get_containing_zone(self.fan)) def testGetDevicesByType_variousScenarios_returnsCorrectList(self):", "from zone_api.core.zone_event import ZoneEvent from zone_api.core.devices.dimmer import Dimmer from zone_api.core.devices.switch", "None) def testRemoveZone_validZone_zoneRemoved(self): zone1 = Zone('ff') self.zm.add_zone(zone1) zone2 = Zone('2f')", "self.zm.stop_auto_report_watch_dog() self.fan._cancel_timer() self.dimmer._cancel_timer() self.light._cancel_timer() super(ZoneManagerTest, self).tearDown() def testAddZone_validZone_zoneAdded(self): zone1 =", "testOnSwitchTurnedOff_noZone_returnsFalse(self): self.assertFalse(self.zm.get_immutable_instance().on_switch_turned_off( pe.get_event_dispatcher(), self.light, pe.create_string_item(INVALID_ITEM_NAME))) def testOnSwitchTurnedOff_withNonApplicableZone_returnsFalse(self): zone = Zone('ff',", "self.assertEqual(2, len(self.zm.get_zones())) def testGetZoneById_validZoneId_returnValidZone(self): zone1 = Zone('ff') self.zm.add_zone(zone1) zone2 =", "Zone('ff').add_device(self.light) zone2 = Zone('sf').add_device(self.fan) self.zm.add_zone(zone1) self.zm.add_zone(zone2) self.assertEqual(zone1, self.zm.get_immutable_instance().get_containing_zone(self.light)) self.assertEqual(zone2, self.zm.get_immutable_instance().get_containing_zone(self.fan))", "from zone_api.core.devices.illuminance_sensor import IlluminanceSensor from zone_api.core.devices.motion_sensor import MotionSensor from zone_api.core.actions.turn_on_switch", "Zone('ff', [self.light, self.motionSensor]) self.zm.add_zone(zone) self.assertFalse(self.zm.get_immutable_instance().dispatch_event( ZoneEvent.MOTION, pe.get_event_dispatcher(), self.motionSensor, pe.create_string_item(INVALID_ITEM_NAME))) def", "self.motionSensor, self.motionSensor.get_item())) def testOnSwitchTurnedOn_noZone_returnsFalse(self): self.assertFalse(self.zm.get_immutable_instance().on_switch_turned_on( pe.get_event_dispatcher(), self.light, pe.create_string_item(INVALID_ITEM_NAME))) def testOnSwitchTurnedOn_withNonApplicableZone_returnsFalse(self):", "self.motionSensor, self.illuminanceSensor]) zone = zone.add_action(TurnOnSwitch()) self.zm.add_zone(zone) self.assertTrue(self.zm.get_immutable_instance().dispatch_event( ZoneEvent.MOTION, pe.get_event_dispatcher(), self.motionSensor,", "zone_api_test.core.device_test import DeviceTest ILLUMINANCE_THRESHOLD_IN_LUX = 8 INVALID_ITEM_NAME = 'invalid item", "Zone('ff', [self.light, self.motionSensor]) self.zm.add_zone(zone) self.assertTrue(self.zm.get_immutable_instance().on_switch_turned_on( pe.get_event_dispatcher(), self.light, self.light.get_item())) def testOnSwitchTurnedOff_noZone_returnsFalse(self):", "item name' class ZoneManagerTest(DeviceTest): \"\"\" Unit tests for zone_manager.py. \"\"\"", "ZoneManager() def tearDown(self): self.zm.stop_auto_report_watch_dog() self.fan._cancel_timer() self.dimmer._cancel_timer() self.light._cancel_timer() super(ZoneManagerTest, self).tearDown() def", "= Zone('ff', [self.light, self.motionSensor]) self.zm.add_zone(zone) self.assertFalse(self.zm.get_immutable_instance().on_switch_turned_off( pe.get_event_dispatcher(), self.light, pe.create_string_item(INVALID_ITEM_NAME))) def", "self.zm.remove_zone(zone1) self.assertEqual(1, len(self.zm.get_zones())) self.zm.remove_zone(zone2) self.assertEqual(0, len(self.zm.get_zones())) def testContainingZone_validDevice_returnsCorrectZone(self): zone1 =", "Zone('ff', [self.light, self.motionSensor]) self.zm.add_zone(zone) self.assertFalse(self.zm.get_immutable_instance().on_switch_turned_off( pe.get_event_dispatcher(), self.light, pe.create_string_item(INVALID_ITEM_NAME))) def testOnSwitchTurnedOff_withApplicableZone_returnsTrue(self):", "len(self.zm.get_zones())) self.zm.remove_zone(zone1) self.assertEqual(1, len(self.zm.get_zones())) self.zm.remove_zone(zone2) self.assertEqual(0, len(self.zm.get_zones())) def testContainingZone_validDevice_returnsCorrectZone(self): zone1", "self.assertEqual(zone1.get_name(), self.zm.get_zone_by_id(zone1.get_id()).get_name()) self.assertEqual(zone2.get_name(), self.zm.get_zone_by_id(zone2.get_id()).get_name()) def testGetZoneById_invalidZoneId_returnNone(self): self.assertTrue(self.zm.get_zone_by_id('invalid zone id') is", "self.assertEqual(1, len(self.zm.get_zones())) self.zm.remove_zone(zone2) self.assertEqual(0, len(self.zm.get_zones())) def testContainingZone_validDevice_returnsCorrectZone(self): zone1 = Zone('ff').add_device(self.light)", "testGetZoneById_validZoneId_returnValidZone(self): zone1 = Zone('ff') self.zm.add_zone(zone1) zone2 = Zone('2f') self.zm.add_zone(zone2) self.assertEqual(zone1.get_name(),", "pe.create_string_item(INVALID_ITEM_NAME))) def testOnSwitchTurnedOff_withApplicableZone_returnsTrue(self): zone = Zone('ff', [self.light, self.motionSensor]) self.zm.add_zone(zone) self.assertTrue(self.zm.get_immutable_instance().on_switch_turned_off(", "super(ZoneManagerTest, self).setUp() [self.lightItem, self.motionSensorItem, self.illuminanceSensorItem, self.astroSensorItem, self.dimmerItem, self.fanItem] = items", "100, \"0-23:59\") self.fan = Fan(self.fanItem, 2) self.zm = ZoneManager() def", "self.dimmer._cancel_timer() self.light._cancel_timer() super(ZoneManagerTest, self).tearDown() def testAddZone_validZone_zoneAdded(self): zone1 = Zone('ff') self.zm.add_zone(zone1)", "testOnMotionSensorTurnedOn_withNonApplicableZone_returnsFalse(self): zone = Zone('ff', [self.light, self.motionSensor]) self.zm.add_zone(zone) self.assertFalse(self.zm.get_immutable_instance().dispatch_event( ZoneEvent.MOTION, pe.get_event_dispatcher(),", "self.zm.add_zone(zone2) self.assertEqual(2, len(self.zm.get_zones())) self.assertEqual(1, len(self.zm.get_devices_by_type(Light))) self.assertEqual(2, len(self.zm.get_devices_by_type(Switch))) self.assertEqual(0, len(self.zm.get_devices_by_type(Dimmer))) def", "MotionSensor(self.motionSensorItem) self.dimmer = Dimmer(self.dimmerItem, 2, 100, \"0-23:59\") self.fan = Fan(self.fanItem,", "testGetZoneById_invalidZoneId_returnNone(self): self.assertTrue(self.zm.get_zone_by_id('invalid zone id') is None) def testRemoveZone_validZone_zoneRemoved(self): zone1 =", "Zone('ff', [self.light, self.motionSensor, self.illuminanceSensor]) zone = zone.add_action(TurnOnSwitch()) self.zm.add_zone(zone) self.assertTrue(self.zm.get_immutable_instance().dispatch_event( ZoneEvent.MOTION,", "def tearDown(self): self.zm.stop_auto_report_watch_dog() self.fan._cancel_timer() self.dimmer._cancel_timer() self.light._cancel_timer() super(ZoneManagerTest, self).tearDown() def testAddZone_validZone_zoneAdded(self):", "class ZoneManagerTest(DeviceTest): \"\"\" Unit tests for zone_manager.py. \"\"\" def setUp(self):", "= Zone('ff') self.zm.add_zone(zone1) zone2 = Zone('2f') self.zm.add_zone(zone2) self.assertEqual(zone1.get_name(), self.zm.get_zone_by_id(zone1.get_id()).get_name()) self.assertEqual(zone2.get_name(),", "len(self.zm.get_zones())) def testContainingZone_validDevice_returnsCorrectZone(self): zone1 = Zone('ff').add_device(self.light) zone2 = Zone('sf').add_device(self.fan) self.zm.add_zone(zone1)", "zone_api.core.actions.turn_on_switch import TurnOnSwitch from zone_api_test.core.device_test import DeviceTest ILLUMINANCE_THRESHOLD_IN_LUX = 8", "Switch from zone_api.core.devices.illuminance_sensor import IlluminanceSensor from zone_api.core.devices.motion_sensor import MotionSensor from", "zone1 = Zone('ff').add_device(self.light) zone2 = Zone('sf').add_device(self.fan) self.zm.add_zone(zone1) self.zm.add_zone(zone2) self.assertEqual(2, len(self.zm.get_zones()))", "= Zone('sf').add_device(self.fan) self.zm.add_zone(zone1) self.zm.add_zone(zone2) self.assertEqual(2, len(self.zm.get_zones())) self.assertEqual(1, len(self.zm.get_devices_by_type(Light))) self.assertEqual(2, len(self.zm.get_devices_by_type(Switch)))", "def testContainingZone_validDevice_returnsCorrectZone(self): zone1 = Zone('ff').add_device(self.light) zone2 = Zone('sf').add_device(self.fan) self.zm.add_zone(zone1) self.zm.add_zone(zone2)", "self.motionSensor.get_item())) def testOnSwitchTurnedOn_noZone_returnsFalse(self): self.assertFalse(self.zm.get_immutable_instance().on_switch_turned_on( pe.get_event_dispatcher(), self.light, pe.create_string_item(INVALID_ITEM_NAME))) def testOnSwitchTurnedOn_withNonApplicableZone_returnsFalse(self): zone", "Zone('ff').add_device(self.light) zone2 = Zone('sf').add_device(self.fan) self.zm.add_zone(zone1) self.zm.add_zone(zone2) self.assertEqual(2, len(self.zm.get_zones())) self.assertEqual(1, len(self.zm.get_devices_by_type(Light)))", "= Zone('ff', [self.light, self.motionSensor]) self.zm.add_zone(zone) self.assertTrue(self.zm.get_immutable_instance().on_switch_turned_on( pe.get_event_dispatcher(), self.light, self.light.get_item())) def", "[self.light, self.motionSensor]) self.zm.add_zone(zone) self.assertTrue(self.zm.get_immutable_instance().on_switch_turned_on( pe.get_event_dispatcher(), self.light, self.light.get_item())) def testOnSwitchTurnedOff_noZone_returnsFalse(self): self.assertFalse(self.zm.get_immutable_instance().on_switch_turned_off(", "pe.set_number_value(self.illuminanceSensorItem, ILLUMINANCE_THRESHOLD_IN_LUX - 1) zone = Zone('ff', [self.light, self.motionSensor, self.illuminanceSensor])", "= Zone('ff').add_device(self.light) zone2 = Zone('sf').add_device(self.fan) self.zm.add_zone(zone1) self.zm.add_zone(zone2) self.assertEqual(zone1, self.zm.get_immutable_instance().get_containing_zone(self.light)) self.assertEqual(zone2,", "self.zm.add_zone(zone2) self.assertEqual(zone1.get_name(), self.zm.get_zone_by_id(zone1.get_id()).get_name()) self.assertEqual(zone2.get_name(), self.zm.get_zone_by_id(zone2.get_id()).get_name()) def testGetZoneById_invalidZoneId_returnNone(self): self.assertTrue(self.zm.get_zone_by_id('invalid zone id')", "Zone('2f') self.zm.add_zone(zone2) self.assertEqual(2, len(self.zm.get_zones())) self.zm.remove_zone(zone1) self.assertEqual(1, len(self.zm.get_zones())) self.zm.remove_zone(zone2) self.assertEqual(0, len(self.zm.get_zones()))", "self.assertEqual(zone2, self.zm.get_immutable_instance().get_containing_zone(self.fan)) def testContainingZone_invalidDevice_returnsNone(self): zone1 = Zone('ff').add_device(self.light) self.zm.add_zone(zone1) self.assertEqual(None, self.zm.get_immutable_instance().get_containing_zone(self.fan))", "pe.create_string_item(INVALID_ITEM_NAME))) def testOnSwitchTurnedOff_withNonApplicableZone_returnsFalse(self): zone = Zone('ff', [self.light, self.motionSensor]) self.zm.add_zone(zone) self.assertFalse(self.zm.get_immutable_instance().on_switch_turned_off(", "def testOnSwitchTurnedOn_withApplicableZone_returnsTrue(self): zone = Zone('ff', [self.light, self.motionSensor]) self.zm.add_zone(zone) self.assertTrue(self.zm.get_immutable_instance().on_switch_turned_on( pe.get_event_dispatcher(),", "Dimmer(self.dimmerItem, 2, 100, \"0-23:59\") self.fan = Fan(self.fanItem, 2) self.zm =", "self.assertEqual(zone1, self.zm.get_immutable_instance().get_containing_zone(self.light)) self.assertEqual(zone2, self.zm.get_immutable_instance().get_containing_zone(self.fan)) def testContainingZone_invalidDevice_returnsNone(self): zone1 = Zone('ff').add_device(self.light) self.zm.add_zone(zone1)", "self.illuminanceSensorItem, self.astroSensorItem, self.dimmerItem, self.fanItem] = items self.illuminanceSensor = IlluminanceSensor(self.illuminanceSensorItem) self.light", "self.light._cancel_timer() super(ZoneManagerTest, self).tearDown() def testAddZone_validZone_zoneAdded(self): zone1 = Zone('ff') self.zm.add_zone(zone1) self.assertEqual(1,", "= ZoneManager() def tearDown(self): self.zm.stop_auto_report_watch_dog() self.fan._cancel_timer() self.dimmer._cancel_timer() self.light._cancel_timer() super(ZoneManagerTest, self).tearDown()", "zone2 = Zone('2f') self.zm.add_zone(zone2) self.assertEqual(2, len(self.zm.get_zones())) def testGetZoneById_validZoneId_returnValidZone(self): zone1 =", "pe.get_event_dispatcher(), self.motionSensor, pe.create_string_item(INVALID_ITEM_NAME))) def testOnMotionSensorTurnedOn_withNonApplicableZone_returnsFalse(self): zone = Zone('ff', [self.light, self.motionSensor])", "def testGetZoneById_invalidZoneId_returnNone(self): self.assertTrue(self.zm.get_zone_by_id('invalid zone id') is None) def testRemoveZone_validZone_zoneRemoved(self): zone1", "self.assertTrue(self.zm.get_zone_by_id('invalid zone id') is None) def testRemoveZone_validZone_zoneRemoved(self): zone1 = Zone('ff')", "testContainingZone_invalidDevice_returnsNone(self): zone1 = Zone('ff').add_device(self.light) self.zm.add_zone(zone1) self.assertEqual(None, self.zm.get_immutable_instance().get_containing_zone(self.fan)) def testGetDevicesByType_variousScenarios_returnsCorrectList(self): zone1", "self.fan._cancel_timer() self.dimmer._cancel_timer() self.light._cancel_timer() super(ZoneManagerTest, self).tearDown() def testAddZone_validZone_zoneAdded(self): zone1 = Zone('ff')", "len(self.zm.get_devices_by_type(Dimmer))) def testOnMotionSensorTurnedOn_noZone_returnsFalse(self): self.assertFalse(self.zm.get_immutable_instance().dispatch_event( ZoneEvent.MOTION, pe.get_event_dispatcher(), self.motionSensor, pe.create_string_item(INVALID_ITEM_NAME))) def testOnMotionSensorTurnedOn_withNonApplicableZone_returnsFalse(self):", "len(self.zm.get_devices_by_type(Switch))) self.assertEqual(0, len(self.zm.get_devices_by_type(Dimmer))) def testOnMotionSensorTurnedOn_noZone_returnsFalse(self): self.assertFalse(self.zm.get_immutable_instance().dispatch_event( ZoneEvent.MOTION, pe.get_event_dispatcher(), self.motionSensor, pe.create_string_item(INVALID_ITEM_NAME)))", "Zone('sf').add_device(self.fan) self.zm.add_zone(zone1) self.zm.add_zone(zone2) self.assertEqual(zone1, self.zm.get_immutable_instance().get_containing_zone(self.light)) self.assertEqual(zone2, self.zm.get_immutable_instance().get_containing_zone(self.fan)) def testContainingZone_invalidDevice_returnsNone(self): zone1", "pe.create_string_item(INVALID_ITEM_NAME))) def testOnSwitchTurnedOn_withApplicableZone_returnsTrue(self): zone = Zone('ff', [self.light, self.motionSensor]) self.zm.add_zone(zone) self.assertTrue(self.zm.get_immutable_instance().on_switch_turned_on(", "self.fan = Fan(self.fanItem, 2) self.zm = ZoneManager() def tearDown(self): self.zm.stop_auto_report_watch_dog()", "self.zm.add_zone(zone) self.assertTrue(self.zm.get_immutable_instance().on_switch_turned_on( pe.get_event_dispatcher(), self.light, self.light.get_item())) def testOnSwitchTurnedOff_noZone_returnsFalse(self): self.assertFalse(self.zm.get_immutable_instance().on_switch_turned_off( pe.get_event_dispatcher(), self.light,", "platform_encapsulator as pe from zone_api.core.zone import Zone from zone_api.core.zone_event import", "self.light = Light(self.lightItem, 2, ILLUMINANCE_THRESHOLD_IN_LUX) self.motionSensor = MotionSensor(self.motionSensorItem) self.dimmer =", "Zone('ff') self.zm.add_zone(zone1) zone2 = Zone('2f') self.zm.add_zone(zone2) self.assertEqual(zone1.get_name(), self.zm.get_zone_by_id(zone1.get_id()).get_name()) self.assertEqual(zone2.get_name(), self.zm.get_zone_by_id(zone2.get_id()).get_name())", "self.illuminanceSensor]) zone = zone.add_action(TurnOnSwitch()) self.zm.add_zone(zone) self.assertTrue(self.zm.get_immutable_instance().dispatch_event( ZoneEvent.MOTION, pe.get_event_dispatcher(), self.motionSensor, self.motionSensor.get_item()))", "DeviceTest ILLUMINANCE_THRESHOLD_IN_LUX = 8 INVALID_ITEM_NAME = 'invalid item name' class", "self.assertFalse(self.zm.get_immutable_instance().on_switch_turned_on( pe.get_event_dispatcher(), self.light, pe.create_string_item(INVALID_ITEM_NAME))) def testOnSwitchTurnedOn_withApplicableZone_returnsTrue(self): zone = Zone('ff', [self.light,", "= Zone('ff').add_device(self.light) self.zm.add_zone(zone1) self.assertEqual(None, self.zm.get_immutable_instance().get_containing_zone(self.fan)) def testGetDevicesByType_variousScenarios_returnsCorrectList(self): zone1 = Zone('ff').add_device(self.light)", "def testOnMotionSensorTurnedOn_withApplicableZone_returnsTrue(self): self.assertFalse(self.light.is_on()) pe.set_number_value(self.illuminanceSensorItem, ILLUMINANCE_THRESHOLD_IN_LUX - 1) zone = Zone('ff',", "self.astroSensorItem, self.dimmerItem, self.fanItem] = items self.illuminanceSensor = IlluminanceSensor(self.illuminanceSensorItem) self.light =", "zone = Zone('ff', [self.light, self.motionSensor]) self.zm.add_zone(zone) self.assertTrue(self.zm.get_immutable_instance().on_switch_turned_on( pe.get_event_dispatcher(), self.light, self.light.get_item()))", "self.zm.add_zone(zone1) zone2 = Zone('2f') self.zm.add_zone(zone2) self.assertEqual(zone1.get_name(), self.zm.get_zone_by_id(zone1.get_id()).get_name()) self.assertEqual(zone2.get_name(), self.zm.get_zone_by_id(zone2.get_id()).get_name()) def", "testOnSwitchTurnedOn_noZone_returnsFalse(self): self.assertFalse(self.zm.get_immutable_instance().on_switch_turned_on( pe.get_event_dispatcher(), self.light, pe.create_string_item(INVALID_ITEM_NAME))) def testOnSwitchTurnedOn_withNonApplicableZone_returnsFalse(self): zone = Zone('ff',", "self.assertFalse(self.zm.get_immutable_instance().dispatch_event( ZoneEvent.MOTION, pe.get_event_dispatcher(), self.motionSensor, pe.create_string_item(INVALID_ITEM_NAME))) def testOnMotionSensorTurnedOn_withNonApplicableZone_returnsFalse(self): zone = Zone('ff',", "zone_api import platform_encapsulator as pe from zone_api.core.zone import Zone from", "TurnOnSwitch from zone_api_test.core.device_test import DeviceTest ILLUMINANCE_THRESHOLD_IN_LUX = 8 INVALID_ITEM_NAME =", "= items self.illuminanceSensor = IlluminanceSensor(self.illuminanceSensorItem) self.light = Light(self.lightItem, 2, ILLUMINANCE_THRESHOLD_IN_LUX)", "= Zone('2f') self.zm.add_zone(zone2) self.assertEqual(2, len(self.zm.get_zones())) self.zm.remove_zone(zone1) self.assertEqual(1, len(self.zm.get_zones())) self.zm.remove_zone(zone2) self.assertEqual(0,", "len(self.zm.get_devices_by_type(Light))) self.assertEqual(2, len(self.zm.get_devices_by_type(Switch))) self.assertEqual(0, len(self.zm.get_devices_by_type(Dimmer))) def testOnMotionSensorTurnedOn_noZone_returnsFalse(self): self.assertFalse(self.zm.get_immutable_instance().dispatch_event( ZoneEvent.MOTION, pe.get_event_dispatcher(),", "zone_api.core.zone_event import ZoneEvent from zone_api.core.devices.dimmer import Dimmer from zone_api.core.devices.switch import", "self.zm.add_zone(zone) self.assertFalse(self.zm.get_immutable_instance().dispatch_event( ZoneEvent.MOTION, pe.get_event_dispatcher(), self.motionSensor, pe.create_string_item(INVALID_ITEM_NAME))) def testOnMotionSensorTurnedOn_withApplicableZone_returnsTrue(self): self.assertFalse(self.light.is_on()) pe.set_number_value(self.illuminanceSensorItem,", "self.assertEqual(2, len(self.zm.get_zones())) self.assertEqual(1, len(self.zm.get_devices_by_type(Light))) self.assertEqual(2, len(self.zm.get_devices_by_type(Switch))) self.assertEqual(0, len(self.zm.get_devices_by_type(Dimmer))) def testOnMotionSensorTurnedOn_noZone_returnsFalse(self):", "pe.create_string_item(INVALID_ITEM_NAME))) def testOnMotionSensorTurnedOn_withApplicableZone_returnsTrue(self): self.assertFalse(self.light.is_on()) pe.set_number_value(self.illuminanceSensorItem, ILLUMINANCE_THRESHOLD_IN_LUX - 1) zone =", "zone.add_action(TurnOnSwitch()) self.zm.add_zone(zone) self.assertTrue(self.zm.get_immutable_instance().dispatch_event( ZoneEvent.MOTION, pe.get_event_dispatcher(), self.motionSensor, self.motionSensor.get_item())) def testOnSwitchTurnedOn_noZone_returnsFalse(self): self.assertFalse(self.zm.get_immutable_instance().on_switch_turned_on(", "pe.create_switch_item('TestMotionSensorName'), pe.create_number_item('IlluminanceSensorName'), pe.create_string_item('AstroSensorName'), pe.create_dimmer_item('TestDimmerName'), pe.create_switch_item('TestFanName'), ] self.set_items(items) super(ZoneManagerTest, self).setUp() [self.lightItem,", "zone2 = Zone('sf').add_device(self.fan) self.zm.add_zone(zone1) self.zm.add_zone(zone2) self.assertEqual(zone1, self.zm.get_immutable_instance().get_containing_zone(self.light)) self.assertEqual(zone2, self.zm.get_immutable_instance().get_containing_zone(self.fan)) def", "[self.light, self.motionSensor]) self.zm.add_zone(zone) self.assertFalse(self.zm.get_immutable_instance().on_switch_turned_off( pe.get_event_dispatcher(), self.light, pe.create_string_item(INVALID_ITEM_NAME))) def testOnSwitchTurnedOff_withApplicableZone_returnsTrue(self): zone", "zone_api.core.zone_manager import ZoneManager from zone_api import platform_encapsulator as pe from", "= Zone('ff', [self.light, self.motionSensor]) self.zm.add_zone(zone) self.assertFalse(self.zm.get_immutable_instance().on_switch_turned_on( pe.get_event_dispatcher(), self.light, pe.create_string_item(INVALID_ITEM_NAME))) def", "def testGetDevicesByType_variousScenarios_returnsCorrectList(self): zone1 = Zone('ff').add_device(self.light) zone2 = Zone('sf').add_device(self.fan) self.zm.add_zone(zone1) self.zm.add_zone(zone2)", "import platform_encapsulator as pe from zone_api.core.zone import Zone from zone_api.core.zone_event", "testOnSwitchTurnedOff_withApplicableZone_returnsTrue(self): zone = Zone('ff', [self.light, self.motionSensor]) self.zm.add_zone(zone) self.assertTrue(self.zm.get_immutable_instance().on_switch_turned_off( pe.get_event_dispatcher(), self.light,", "from zone_api import platform_encapsulator as pe from zone_api.core.zone import Zone", "self.assertTrue(self.zm.get_immutable_instance().dispatch_event( ZoneEvent.MOTION, pe.get_event_dispatcher(), self.motionSensor, self.motionSensor.get_item())) def testOnSwitchTurnedOn_noZone_returnsFalse(self): self.assertFalse(self.zm.get_immutable_instance().on_switch_turned_on( pe.get_event_dispatcher(), self.light,", "self.illuminanceSensor = IlluminanceSensor(self.illuminanceSensorItem) self.light = Light(self.lightItem, 2, ILLUMINANCE_THRESHOLD_IN_LUX) self.motionSensor =", "self.assertFalse(self.zm.get_immutable_instance().on_switch_turned_off( pe.get_event_dispatcher(), self.light, pe.create_string_item(INVALID_ITEM_NAME))) def testOnSwitchTurnedOff_withNonApplicableZone_returnsFalse(self): zone = Zone('ff', [self.light,", "self.assertEqual(1, len(self.zm.get_zones())) zone2 = Zone('2f') self.zm.add_zone(zone2) self.assertEqual(2, len(self.zm.get_zones())) def testGetZoneById_validZoneId_returnValidZone(self):", "import Fan, Light, Switch from zone_api.core.devices.illuminance_sensor import IlluminanceSensor from zone_api.core.devices.motion_sensor", "= zone.add_action(TurnOnSwitch()) self.zm.add_zone(zone) self.assertTrue(self.zm.get_immutable_instance().dispatch_event( ZoneEvent.MOTION, pe.get_event_dispatcher(), self.motionSensor, self.motionSensor.get_item())) def testOnSwitchTurnedOn_noZone_returnsFalse(self):", "self.light.get_item())) def testOnSwitchTurnedOff_noZone_returnsFalse(self): self.assertFalse(self.zm.get_immutable_instance().on_switch_turned_off( pe.get_event_dispatcher(), self.light, pe.create_string_item(INVALID_ITEM_NAME))) def testOnSwitchTurnedOff_withNonApplicableZone_returnsFalse(self): zone", "from zone_api.core.actions.turn_on_switch import TurnOnSwitch from zone_api_test.core.device_test import DeviceTest ILLUMINANCE_THRESHOLD_IN_LUX =", "pe.create_string_item('AstroSensorName'), pe.create_dimmer_item('TestDimmerName'), pe.create_switch_item('TestFanName'), ] self.set_items(items) super(ZoneManagerTest, self).setUp() [self.lightItem, self.motionSensorItem, self.illuminanceSensorItem,", "as pe from zone_api.core.zone import Zone from zone_api.core.zone_event import ZoneEvent", "IlluminanceSensor(self.illuminanceSensorItem) self.light = Light(self.lightItem, 2, ILLUMINANCE_THRESHOLD_IN_LUX) self.motionSensor = MotionSensor(self.motionSensorItem) self.dimmer", "import ZoneEvent from zone_api.core.devices.dimmer import Dimmer from zone_api.core.devices.switch import Fan,", "zone1 = Zone('ff') self.zm.add_zone(zone1) zone2 = Zone('2f') self.zm.add_zone(zone2) self.assertEqual(zone1.get_name(), self.zm.get_zone_by_id(zone1.get_id()).get_name())", "import DeviceTest ILLUMINANCE_THRESHOLD_IN_LUX = 8 INVALID_ITEM_NAME = 'invalid item name'", "self.assertEqual(0, len(self.zm.get_zones())) def testContainingZone_validDevice_returnsCorrectZone(self): zone1 = Zone('ff').add_device(self.light) zone2 = Zone('sf').add_device(self.fan)", "self.zm.add_zone(zone1) self.assertEqual(None, self.zm.get_immutable_instance().get_containing_zone(self.fan)) def testGetDevicesByType_variousScenarios_returnsCorrectList(self): zone1 = Zone('ff').add_device(self.light) zone2 =", "zone_api.core.devices.dimmer import Dimmer from zone_api.core.devices.switch import Fan, Light, Switch from", "ZoneManagerTest(DeviceTest): \"\"\" Unit tests for zone_manager.py. \"\"\" def setUp(self): items", "self.motionSensor]) self.zm.add_zone(zone) self.assertFalse(self.zm.get_immutable_instance().dispatch_event( ZoneEvent.MOTION, pe.get_event_dispatcher(), self.motionSensor, pe.create_string_item(INVALID_ITEM_NAME))) def testOnMotionSensorTurnedOn_withApplicableZone_returnsTrue(self): self.assertFalse(self.light.is_on())", "testOnMotionSensorTurnedOn_withApplicableZone_returnsTrue(self): self.assertFalse(self.light.is_on()) pe.set_number_value(self.illuminanceSensorItem, ILLUMINANCE_THRESHOLD_IN_LUX - 1) zone = Zone('ff', [self.light,", "testRemoveZone_validZone_zoneRemoved(self): zone1 = Zone('ff') self.zm.add_zone(zone1) zone2 = Zone('2f') self.zm.add_zone(zone2) self.assertEqual(2,", "] self.set_items(items) super(ZoneManagerTest, self).setUp() [self.lightItem, self.motionSensorItem, self.illuminanceSensorItem, self.astroSensorItem, self.dimmerItem, self.fanItem]", "self.zm.add_zone(zone1) self.zm.add_zone(zone2) self.assertEqual(2, len(self.zm.get_zones())) self.assertEqual(1, len(self.zm.get_devices_by_type(Light))) self.assertEqual(2, len(self.zm.get_devices_by_type(Switch))) self.assertEqual(0, len(self.zm.get_devices_by_type(Dimmer)))", "len(self.zm.get_zones())) self.assertEqual(1, len(self.zm.get_devices_by_type(Light))) self.assertEqual(2, len(self.zm.get_devices_by_type(Switch))) self.assertEqual(0, len(self.zm.get_devices_by_type(Dimmer))) def testOnMotionSensorTurnedOn_noZone_returnsFalse(self): self.assertFalse(self.zm.get_immutable_instance().dispatch_event(", "self.assertFalse(self.zm.get_immutable_instance().on_switch_turned_on( pe.get_event_dispatcher(), self.light, pe.create_string_item(INVALID_ITEM_NAME))) def testOnSwitchTurnedOn_withNonApplicableZone_returnsFalse(self): zone = Zone('ff', [self.light,", "testOnSwitchTurnedOn_withNonApplicableZone_returnsFalse(self): zone = Zone('ff', [self.light, self.motionSensor]) self.zm.add_zone(zone) self.assertFalse(self.zm.get_immutable_instance().on_switch_turned_on( pe.get_event_dispatcher(), self.light,", "self.light, self.light.get_item())) def testOnSwitchTurnedOff_noZone_returnsFalse(self): self.assertFalse(self.zm.get_immutable_instance().on_switch_turned_off( pe.get_event_dispatcher(), self.light, pe.create_string_item(INVALID_ITEM_NAME))) def testOnSwitchTurnedOff_withNonApplicableZone_returnsFalse(self):", "1) zone = Zone('ff', [self.light, self.motionSensor, self.illuminanceSensor]) zone = zone.add_action(TurnOnSwitch())", "self.assertFalse(self.zm.get_immutable_instance().dispatch_event( ZoneEvent.MOTION, pe.get_event_dispatcher(), self.motionSensor, pe.create_string_item(INVALID_ITEM_NAME))) def testOnMotionSensorTurnedOn_withApplicableZone_returnsTrue(self): self.assertFalse(self.light.is_on()) pe.set_number_value(self.illuminanceSensorItem, ILLUMINANCE_THRESHOLD_IN_LUX", "from zone_api.core.devices.switch import Fan, Light, Switch from zone_api.core.devices.illuminance_sensor import IlluminanceSensor", "self.motionSensor]) self.zm.add_zone(zone) self.assertFalse(self.zm.get_immutable_instance().on_switch_turned_off( pe.get_event_dispatcher(), self.light, pe.create_string_item(INVALID_ITEM_NAME))) def testOnSwitchTurnedOff_withApplicableZone_returnsTrue(self): zone =", "zone_api.core.devices.illuminance_sensor import IlluminanceSensor from zone_api.core.devices.motion_sensor import MotionSensor from zone_api.core.actions.turn_on_switch import", "Fan, Light, Switch from zone_api.core.devices.illuminance_sensor import IlluminanceSensor from zone_api.core.devices.motion_sensor import", "import IlluminanceSensor from zone_api.core.devices.motion_sensor import MotionSensor from zone_api.core.actions.turn_on_switch import TurnOnSwitch", "def testRemoveZone_validZone_zoneRemoved(self): zone1 = Zone('ff') self.zm.add_zone(zone1) zone2 = Zone('2f') self.zm.add_zone(zone2)", "len(self.zm.get_zones())) def testGetZoneById_validZoneId_returnValidZone(self): zone1 = Zone('ff') self.zm.add_zone(zone1) zone2 = Zone('2f')", "self.assertEqual(zone2.get_name(), self.zm.get_zone_by_id(zone2.get_id()).get_name()) def testGetZoneById_invalidZoneId_returnNone(self): self.assertTrue(self.zm.get_zone_by_id('invalid zone id') is None) def", "zone2 = Zone('2f') self.zm.add_zone(zone2) self.assertEqual(2, len(self.zm.get_zones())) self.zm.remove_zone(zone1) self.assertEqual(1, len(self.zm.get_zones())) self.zm.remove_zone(zone2)", "from zone_api.core.zone_manager import ZoneManager from zone_api import platform_encapsulator as pe", "self.zm.get_immutable_instance().get_containing_zone(self.fan)) def testContainingZone_invalidDevice_returnsNone(self): zone1 = Zone('ff').add_device(self.light) self.zm.add_zone(zone1) self.assertEqual(None, self.zm.get_immutable_instance().get_containing_zone(self.fan)) def", "self.zm.get_zone_by_id(zone1.get_id()).get_name()) self.assertEqual(zone2.get_name(), self.zm.get_zone_by_id(zone2.get_id()).get_name()) def testGetZoneById_invalidZoneId_returnNone(self): self.assertTrue(self.zm.get_zone_by_id('invalid zone id') is None)", "from zone_api.core.zone import Zone from zone_api.core.zone_event import ZoneEvent from zone_api.core.devices.dimmer", "= Zone('ff', [self.light, self.motionSensor]) self.zm.add_zone(zone) self.assertFalse(self.zm.get_immutable_instance().dispatch_event( ZoneEvent.MOTION, pe.get_event_dispatcher(), self.motionSensor, pe.create_string_item(INVALID_ITEM_NAME)))", "ZoneEvent.MOTION, pe.get_event_dispatcher(), self.motionSensor, pe.create_string_item(INVALID_ITEM_NAME))) def testOnMotionSensorTurnedOn_withApplicableZone_returnsTrue(self): self.assertFalse(self.light.is_on()) pe.set_number_value(self.illuminanceSensorItem, ILLUMINANCE_THRESHOLD_IN_LUX -", "self.zm.add_zone(zone) self.assertFalse(self.zm.get_immutable_instance().on_switch_turned_on( pe.get_event_dispatcher(), self.light, pe.create_string_item(INVALID_ITEM_NAME))) def testOnSwitchTurnedOn_withApplicableZone_returnsTrue(self): zone = Zone('ff',", "len(self.zm.get_zones())) zone2 = Zone('2f') self.zm.add_zone(zone2) self.assertEqual(2, len(self.zm.get_zones())) def testGetZoneById_validZoneId_returnValidZone(self): zone1", "def testOnSwitchTurnedOff_withNonApplicableZone_returnsFalse(self): zone = Zone('ff', [self.light, self.motionSensor]) self.zm.add_zone(zone) self.assertFalse(self.zm.get_immutable_instance().on_switch_turned_off( pe.get_event_dispatcher(),", "self.zm.add_zone(zone) self.assertTrue(self.zm.get_immutable_instance().dispatch_event( ZoneEvent.MOTION, pe.get_event_dispatcher(), self.motionSensor, self.motionSensor.get_item())) def testOnSwitchTurnedOn_noZone_returnsFalse(self): self.assertFalse(self.zm.get_immutable_instance().on_switch_turned_on( pe.get_event_dispatcher(),", "2) self.zm = ZoneManager() def tearDown(self): self.zm.stop_auto_report_watch_dog() self.fan._cancel_timer() self.dimmer._cancel_timer() self.light._cancel_timer()", "self.light, pe.create_string_item(INVALID_ITEM_NAME))) def testOnSwitchTurnedOff_withNonApplicableZone_returnsFalse(self): zone = Zone('ff', [self.light, self.motionSensor]) self.zm.add_zone(zone)" ]
[ "conn = get_redis_connection('cart') # 获取hash数据sku_id ,count sku_id_count = conn.hgetall('cart_%s' %user.id)", "= self.kwargs['sku_id'] # 获取商品信息 orders = OrderGoods.objects.filter(sku_id=sku_id, is_commented = True)", "decimal import Decimal from rest_framework.generics import CreateAPIView,ListAPIView from rest_framework.mixins import", "import Decimal from rest_framework.generics import CreateAPIView,ListAPIView from rest_framework.mixins import ListModelMixin", "建立redis连接 conn = get_redis_connection('cart') # 获取hash数据sku_id ,count sku_id_count = conn.hgetall('cart_%s'", "sku_id_count.items(): cart[int(sku_id)] = int(count) # 获取集合数据 sku_ids = conn.smembers('cart_selected_%s' %user.id)", "from rest_framework.mixins import ListModelMixin from orders.serializers import OrderShowSerializer, OrderSaveSerializer, OrderListSerializer,", "OrderInfo,OrderGoods from orders.utils import PageNum from rest_framework.filters import OrderingFilter #", "= request.user # 建立redis连接 conn = get_redis_connection('cart') # 获取hash数据sku_id ,count", "评论-获取商品信息 class OrderComment(ListAPIView): serializer_class = CommentSerializers def get_queryset(self): order_id =", "class SaveSkuComment(CreateAPIView): serializer_class = CommentSaveSerializers # 商品详情中的评论展示 class ShowComment(ListAPIView): serializer_class", "get_redis_connection('cart') # 获取hash数据sku_id ,count sku_id_count = conn.hgetall('cart_%s' %user.id) # {10:1}", "= OrderSaveSerializer # 订单列表数据获取 class OrderListView(ListAPIView): pagination_class = PageNum serializer_class", "cart = {} for sku_id, count in sku_id_count.items(): cart[int(sku_id)] =", "skus}) return Response(ser.data) # 保存订单信息 class OrderSaveView(ListModelMixin, CreateAPIView): serializer_class =", "def get_queryset(self): order_id = self.kwargs['order_id'] skus = OrderGoods.objects.filter(order_id = order_id,", "get_redis_connection from goods.models import SKU from decimal import Decimal from", "order # 评论-获取商品信息 class OrderComment(ListAPIView): serializer_class = CommentSerializers def get_queryset(self):", "生成运费 freight = Decimal(10.00) # 序列化返回商品对象 ser = OrderShowSerializer({'freight': freight,", "= order_id, is_commented=False) return skus # 保存评论 class SaveSkuComment(CreateAPIView): serializer_class", "sku in skus: sku.count = cart[sku.id] # 生成运费 freight =", "order_id, is_commented=False) return skus # 保存评论 class SaveSkuComment(CreateAPIView): serializer_class =", "获取hash数据sku_id ,count sku_id_count = conn.hgetall('cart_%s' %user.id) # {10:1} # 将byte类型数据转为整形", "CreateAPIView,ListAPIView from rest_framework.mixins import ListModelMixin from orders.serializers import OrderShowSerializer, OrderSaveSerializer,", "freight, 'skus': skus}) return Response(ser.data) # 保存订单信息 class OrderSaveView(ListModelMixin, CreateAPIView):", "for sku_id, count in sku_id_count.items(): cart[int(sku_id)] = int(count) # 获取集合数据", "count in sku_id_count.items(): cart[int(sku_id)] = int(count) # 获取集合数据 sku_ids =", "CommentSaveSerializers # 商品详情中的评论展示 class ShowComment(ListAPIView): serializer_class = CommentShowSerializers def get_queryset(self):", "= OrderListSerializer def get_queryset(self): user = self.request.user order = OrderInfo.objects.filter(user", "{10:1} # 将byte类型数据转为整形 cart = {} for sku_id, count in", "= CommentSerializers def get_queryset(self): order_id = self.kwargs['order_id'] skus = OrderGoods.objects.filter(order_id", "\\ CommentSaveSerializers, CommentShowSerializers from users.models import User from orders.models import", "# 查询所有选中状态的数据对象 skus = SKU.objects.filter(id__in=sku_ids) # 商品对象添加count属性(sku表中没有count字段,要手动添加属性) for sku in", "from rest_framework.generics import CreateAPIView,ListAPIView from rest_framework.mixins import ListModelMixin from orders.serializers", "rest_framework.filters import OrderingFilter # 展示订单信息 class OrdersShowView(APIView): def get(self, request):", "return Response(ser.data) # 保存订单信息 class OrderSaveView(ListModelMixin, CreateAPIView): serializer_class = OrderSaveSerializer", "goods.models import SKU from decimal import Decimal from rest_framework.generics import", "OrdersShowView(APIView): def get(self, request): # 获取用户对象 user = request.user #", "orders.utils import PageNum from rest_framework.filters import OrderingFilter # 展示订单信息 class", "= cart[sku.id] # 生成运费 freight = Decimal(10.00) # 序列化返回商品对象 ser", "skus = OrderGoods.objects.filter(order_id = order_id, is_commented=False) return skus # 保存评论", "sku_id = self.kwargs['sku_id'] # 获取商品信息 orders = OrderGoods.objects.filter(sku_id=sku_id, is_commented =", "= User.objects.get(id = skuinfo.user_id) # 获取用户名,判断是否匿名 sku.username = user.username if", "skuinfo.user_id) # 获取用户名,判断是否匿名 sku.username = user.username if sku.is_anonymous == True:", "Response from rest_framework.views import APIView from django_redis import get_redis_connection from", "商品对象添加count属性(sku表中没有count字段,要手动添加属性) for sku in skus: sku.count = cart[sku.id] # 生成运费", "rest_framework.generics import CreateAPIView,ListAPIView from rest_framework.mixins import ListModelMixin from orders.serializers import", "orders.models import OrderInfo,OrderGoods from orders.utils import PageNum from rest_framework.filters import", "import CreateAPIView,ListAPIView from rest_framework.mixins import ListModelMixin from orders.serializers import OrderShowSerializer,", "request): # 获取用户对象 user = request.user # 建立redis连接 conn =", "= OrderGoods.objects.filter(sku_id=sku_id, is_commented = True) for sku in orders: skuinfo", "import OrderingFilter # 展示订单信息 class OrdersShowView(APIView): def get(self, request): #", "request.user # 建立redis连接 conn = get_redis_connection('cart') # 获取hash数据sku_id ,count sku_id_count", "序列化返回商品对象 ser = OrderShowSerializer({'freight': freight, 'skus': skus}) return Response(ser.data) #", "return skus # 保存评论 class SaveSkuComment(CreateAPIView): serializer_class = CommentSaveSerializers #", "获取用户名,判断是否匿名 sku.username = user.username if sku.is_anonymous == True: sku.username =", "OrderListSerializer def get_queryset(self): user = self.request.user order = OrderInfo.objects.filter(user =", "= PageNum serializer_class = OrderListSerializer def get_queryset(self): user = self.request.user", "from rest_framework.filters import OrderingFilter # 展示订单信息 class OrdersShowView(APIView): def get(self,", "is_commented = True) for sku in orders: skuinfo = OrderInfo.objects.get(order_id=sku.order_id)", "from rest_framework.views import APIView from django_redis import get_redis_connection from goods.models", "Decimal from rest_framework.generics import CreateAPIView,ListAPIView from rest_framework.mixins import ListModelMixin from", "Decimal(10.00) # 序列化返回商品对象 ser = OrderShowSerializer({'freight': freight, 'skus': skus}) return", "cart[sku.id] # 生成运费 freight = Decimal(10.00) # 序列化返回商品对象 ser =", "freight = Decimal(10.00) # 序列化返回商品对象 ser = OrderShowSerializer({'freight': freight, 'skus':", "get_queryset(self): # 从kwargs中获取sku_id sku_id = self.kwargs['sku_id'] # 获取商品信息 orders =", "= user) return order # 评论-获取商品信息 class OrderComment(ListAPIView): serializer_class =", "# {10:1} # 将byte类型数据转为整形 cart = {} for sku_id, count", "import APIView from django_redis import get_redis_connection from goods.models import SKU", "rest_framework.response import Response from rest_framework.views import APIView from django_redis import", "OrderComment(ListAPIView): serializer_class = CommentSerializers def get_queryset(self): order_id = self.kwargs['order_id'] skus", "OrderInfo.objects.get(order_id=sku.order_id) user = User.objects.get(id = skuinfo.user_id) # 获取用户名,判断是否匿名 sku.username =", "{} for sku_id, count in sku_id_count.items(): cart[int(sku_id)] = int(count) #", "self.kwargs['order_id'] skus = OrderGoods.objects.filter(order_id = order_id, is_commented=False) return skus #", "import SKU from decimal import Decimal from rest_framework.generics import CreateAPIView,ListAPIView", "conn.smembers('cart_selected_%s' %user.id) # 查询所有选中状态的数据对象 skus = SKU.objects.filter(id__in=sku_ids) # 商品对象添加count属性(sku表中没有count字段,要手动添加属性) for", "订单列表数据获取 class OrderListView(ListAPIView): pagination_class = PageNum serializer_class = OrderListSerializer def", "= CommentSaveSerializers # 商品详情中的评论展示 class ShowComment(ListAPIView): serializer_class = CommentShowSerializers def", "from goods.models import SKU from decimal import Decimal from rest_framework.generics", "OrderingFilter # 展示订单信息 class OrdersShowView(APIView): def get(self, request): # 获取用户对象", "展示订单信息 class OrdersShowView(APIView): def get(self, request): # 获取用户对象 user =", "# 将byte类型数据转为整形 cart = {} for sku_id, count in sku_id_count.items():", "pagination_class = PageNum serializer_class = OrderListSerializer def get_queryset(self): user =", "skus # 保存评论 class SaveSkuComment(CreateAPIView): serializer_class = CommentSaveSerializers # 商品详情中的评论展示", "from orders.utils import PageNum from rest_framework.filters import OrderingFilter # 展示订单信息", "class OrderSaveView(ListModelMixin, CreateAPIView): serializer_class = OrderSaveSerializer # 订单列表数据获取 class OrderListView(ListAPIView):", "OrderGoods.objects.filter(sku_id=sku_id, is_commented = True) for sku in orders: skuinfo =", "class OrdersShowView(APIView): def get(self, request): # 获取用户对象 user = request.user", "= {} for sku_id, count in sku_id_count.items(): cart[int(sku_id)] = int(count)", "OrderGoods.objects.filter(order_id = order_id, is_commented=False) return skus # 保存评论 class SaveSkuComment(CreateAPIView):", "User from orders.models import OrderInfo,OrderGoods from orders.utils import PageNum from", "ListModelMixin from orders.serializers import OrderShowSerializer, OrderSaveSerializer, OrderListSerializer, CommentSerializers, \\ CommentSaveSerializers,", "sku.username = user.username if sku.is_anonymous == True: sku.username = '****'", "order = OrderInfo.objects.filter(user = user) return order # 评论-获取商品信息 class", "serializer_class = CommentSaveSerializers # 商品详情中的评论展示 class ShowComment(ListAPIView): serializer_class = CommentShowSerializers", "import ListModelMixin from orders.serializers import OrderShowSerializer, OrderSaveSerializer, OrderListSerializer, CommentSerializers, \\", "in orders: skuinfo = OrderInfo.objects.get(order_id=sku.order_id) user = User.objects.get(id = skuinfo.user_id)", "skus: sku.count = cart[sku.id] # 生成运费 freight = Decimal(10.00) #", "OrderSaveSerializer, OrderListSerializer, CommentSerializers, \\ CommentSaveSerializers, CommentShowSerializers from users.models import User", "Response(ser.data) # 保存订单信息 class OrderSaveView(ListModelMixin, CreateAPIView): serializer_class = OrderSaveSerializer #", "is_commented=False) return skus # 保存评论 class SaveSkuComment(CreateAPIView): serializer_class = CommentSaveSerializers", "django_redis import get_redis_connection from goods.models import SKU from decimal import", "rest_framework.views import APIView from django_redis import get_redis_connection from goods.models import", "CommentSaveSerializers, CommentShowSerializers from users.models import User from orders.models import OrderInfo,OrderGoods", ",count sku_id_count = conn.hgetall('cart_%s' %user.id) # {10:1} # 将byte类型数据转为整形 cart", "# 评论-获取商品信息 class OrderComment(ListAPIView): serializer_class = CommentSerializers def get_queryset(self): order_id", "# 生成运费 freight = Decimal(10.00) # 序列化返回商品对象 ser = OrderShowSerializer({'freight':", "= user.username if sku.is_anonymous == True: sku.username = '****' return", "serializer_class = CommentSerializers def get_queryset(self): order_id = self.kwargs['order_id'] skus =", "for sku in orders: skuinfo = OrderInfo.objects.get(order_id=sku.order_id) user = User.objects.get(id", "in skus: sku.count = cart[sku.id] # 生成运费 freight = Decimal(10.00)", "sku_id_count = conn.hgetall('cart_%s' %user.id) # {10:1} # 将byte类型数据转为整形 cart =", "from django_redis import get_redis_connection from goods.models import SKU from decimal", "%user.id) # {10:1} # 将byte类型数据转为整形 cart = {} for sku_id,", "ShowComment(ListAPIView): serializer_class = CommentShowSerializers def get_queryset(self): # 从kwargs中获取sku_id sku_id =", "# 保存订单信息 class OrderSaveView(ListModelMixin, CreateAPIView): serializer_class = OrderSaveSerializer # 订单列表数据获取", "# 获取集合数据 sku_ids = conn.smembers('cart_selected_%s' %user.id) # 查询所有选中状态的数据对象 skus =", "CommentShowSerializers from users.models import User from orders.models import OrderInfo,OrderGoods from", "获取商品信息 orders = OrderGoods.objects.filter(sku_id=sku_id, is_commented = True) for sku in", "get(self, request): # 获取用户对象 user = request.user # 建立redis连接 conn", "from users.models import User from orders.models import OrderInfo,OrderGoods from orders.utils", "from orders.models import OrderInfo,OrderGoods from orders.utils import PageNum from rest_framework.filters", "import get_redis_connection from goods.models import SKU from decimal import Decimal", "CreateAPIView): serializer_class = OrderSaveSerializer # 订单列表数据获取 class OrderListView(ListAPIView): pagination_class =", "sku_ids = conn.smembers('cart_selected_%s' %user.id) # 查询所有选中状态的数据对象 skus = SKU.objects.filter(id__in=sku_ids) #", "= conn.hgetall('cart_%s' %user.id) # {10:1} # 将byte类型数据转为整形 cart = {}", "from rest_framework.response import Response from rest_framework.views import APIView from django_redis", "商品详情中的评论展示 class ShowComment(ListAPIView): serializer_class = CommentShowSerializers def get_queryset(self): # 从kwargs中获取sku_id", "class ShowComment(ListAPIView): serializer_class = CommentShowSerializers def get_queryset(self): # 从kwargs中获取sku_id sku_id", "import Response from rest_framework.views import APIView from django_redis import get_redis_connection", "import OrderShowSerializer, OrderSaveSerializer, OrderListSerializer, CommentSerializers, \\ CommentSaveSerializers, CommentShowSerializers from users.models", "保存订单信息 class OrderSaveView(ListModelMixin, CreateAPIView): serializer_class = OrderSaveSerializer # 订单列表数据获取 class", "将byte类型数据转为整形 cart = {} for sku_id, count in sku_id_count.items(): cart[int(sku_id)]", "ser = OrderShowSerializer({'freight': freight, 'skus': skus}) return Response(ser.data) # 保存订单信息", "get_queryset(self): order_id = self.kwargs['order_id'] skus = OrderGoods.objects.filter(order_id = order_id, is_commented=False)", "# 获取用户名,判断是否匿名 sku.username = user.username if sku.is_anonymous == True: sku.username", "user = User.objects.get(id = skuinfo.user_id) # 获取用户名,判断是否匿名 sku.username = user.username", "OrderListSerializer, CommentSerializers, \\ CommentSaveSerializers, CommentShowSerializers from users.models import User from", "from decimal import Decimal from rest_framework.generics import CreateAPIView,ListAPIView from rest_framework.mixins", "PageNum from rest_framework.filters import OrderingFilter # 展示订单信息 class OrdersShowView(APIView): def", "int(count) # 获取集合数据 sku_ids = conn.smembers('cart_selected_%s' %user.id) # 查询所有选中状态的数据对象 skus", "OrderSaveSerializer # 订单列表数据获取 class OrderListView(ListAPIView): pagination_class = PageNum serializer_class =", "users.models import User from orders.models import OrderInfo,OrderGoods from orders.utils import", "获取用户对象 user = request.user # 建立redis连接 conn = get_redis_connection('cart') #", "= get_redis_connection('cart') # 获取hash数据sku_id ,count sku_id_count = conn.hgetall('cart_%s' %user.id) #", "orders.serializers import OrderShowSerializer, OrderSaveSerializer, OrderListSerializer, CommentSerializers, \\ CommentSaveSerializers, CommentShowSerializers from", "import User from orders.models import OrderInfo,OrderGoods from orders.utils import PageNum", "cart[int(sku_id)] = int(count) # 获取集合数据 sku_ids = conn.smembers('cart_selected_%s' %user.id) #", "# 序列化返回商品对象 ser = OrderShowSerializer({'freight': freight, 'skus': skus}) return Response(ser.data)", "# 订单列表数据获取 class OrderListView(ListAPIView): pagination_class = PageNum serializer_class = OrderListSerializer", "orders: skuinfo = OrderInfo.objects.get(order_id=sku.order_id) user = User.objects.get(id = skuinfo.user_id) #", "user.username if sku.is_anonymous == True: sku.username = '****' return orders", "= self.request.user order = OrderInfo.objects.filter(user = user) return order #", "sku_id, count in sku_id_count.items(): cart[int(sku_id)] = int(count) # 获取集合数据 sku_ids", "= CommentShowSerializers def get_queryset(self): # 从kwargs中获取sku_id sku_id = self.kwargs['sku_id'] #", "CommentShowSerializers def get_queryset(self): # 从kwargs中获取sku_id sku_id = self.kwargs['sku_id'] # 获取商品信息", "# 商品对象添加count属性(sku表中没有count字段,要手动添加属性) for sku in skus: sku.count = cart[sku.id] #", "get_queryset(self): user = self.request.user order = OrderInfo.objects.filter(user = user) return", "True) for sku in orders: skuinfo = OrderInfo.objects.get(order_id=sku.order_id) user =", "sku in orders: skuinfo = OrderInfo.objects.get(order_id=sku.order_id) user = User.objects.get(id =", "'skus': skus}) return Response(ser.data) # 保存订单信息 class OrderSaveView(ListModelMixin, CreateAPIView): serializer_class", "获取集合数据 sku_ids = conn.smembers('cart_selected_%s' %user.id) # 查询所有选中状态的数据对象 skus = SKU.objects.filter(id__in=sku_ids)", "保存评论 class SaveSkuComment(CreateAPIView): serializer_class = CommentSaveSerializers # 商品详情中的评论展示 class ShowComment(ListAPIView):", "# 获取用户对象 user = request.user # 建立redis连接 conn = get_redis_connection('cart')", "# 展示订单信息 class OrdersShowView(APIView): def get(self, request): # 获取用户对象 user", "user) return order # 评论-获取商品信息 class OrderComment(ListAPIView): serializer_class = CommentSerializers", "return order # 评论-获取商品信息 class OrderComment(ListAPIView): serializer_class = CommentSerializers def", "= OrderGoods.objects.filter(order_id = order_id, is_commented=False) return skus # 保存评论 class", "# 获取商品信息 orders = OrderGoods.objects.filter(sku_id=sku_id, is_commented = True) for sku", "= OrderInfo.objects.filter(user = user) return order # 评论-获取商品信息 class OrderComment(ListAPIView):", "from orders.serializers import OrderShowSerializer, OrderSaveSerializer, OrderListSerializer, CommentSerializers, \\ CommentSaveSerializers, CommentShowSerializers", "for sku in skus: sku.count = cart[sku.id] # 生成运费 freight", "serializer_class = OrderSaveSerializer # 订单列表数据获取 class OrderListView(ListAPIView): pagination_class = PageNum", "# 商品详情中的评论展示 class ShowComment(ListAPIView): serializer_class = CommentShowSerializers def get_queryset(self): #", "OrderShowSerializer, OrderSaveSerializer, OrderListSerializer, CommentSerializers, \\ CommentSaveSerializers, CommentShowSerializers from users.models import", "rest_framework.mixins import ListModelMixin from orders.serializers import OrderShowSerializer, OrderSaveSerializer, OrderListSerializer, CommentSerializers,", "class OrderComment(ListAPIView): serializer_class = CommentSerializers def get_queryset(self): order_id = self.kwargs['order_id']", "conn.hgetall('cart_%s' %user.id) # {10:1} # 将byte类型数据转为整形 cart = {} for", "in sku_id_count.items(): cart[int(sku_id)] = int(count) # 获取集合数据 sku_ids = conn.smembers('cart_selected_%s'", "serializer_class = OrderListSerializer def get_queryset(self): user = self.request.user order =", "PageNum serializer_class = OrderListSerializer def get_queryset(self): user = self.request.user order", "skus = SKU.objects.filter(id__in=sku_ids) # 商品对象添加count属性(sku表中没有count字段,要手动添加属性) for sku in skus: sku.count", "self.kwargs['sku_id'] # 获取商品信息 orders = OrderGoods.objects.filter(sku_id=sku_id, is_commented = True) for", "def get_queryset(self): user = self.request.user order = OrderInfo.objects.filter(user = user)", "从kwargs中获取sku_id sku_id = self.kwargs['sku_id'] # 获取商品信息 orders = OrderGoods.objects.filter(sku_id=sku_id, is_commented", "OrderInfo.objects.filter(user = user) return order # 评论-获取商品信息 class OrderComment(ListAPIView): serializer_class", "# 保存评论 class SaveSkuComment(CreateAPIView): serializer_class = CommentSaveSerializers # 商品详情中的评论展示 class", "CommentSerializers, \\ CommentSaveSerializers, CommentShowSerializers from users.models import User from orders.models", "def get(self, request): # 获取用户对象 user = request.user # 建立redis连接", "self.request.user order = OrderInfo.objects.filter(user = user) return order # 评论-获取商品信息", "= skuinfo.user_id) # 获取用户名,判断是否匿名 sku.username = user.username if sku.is_anonymous ==", "= True) for sku in orders: skuinfo = OrderInfo.objects.get(order_id=sku.order_id) user", "# 从kwargs中获取sku_id sku_id = self.kwargs['sku_id'] # 获取商品信息 orders = OrderGoods.objects.filter(sku_id=sku_id,", "import OrderInfo,OrderGoods from orders.utils import PageNum from rest_framework.filters import OrderingFilter", "SKU.objects.filter(id__in=sku_ids) # 商品对象添加count属性(sku表中没有count字段,要手动添加属性) for sku in skus: sku.count = cart[sku.id]", "order_id = self.kwargs['order_id'] skus = OrderGoods.objects.filter(order_id = order_id, is_commented=False) return", "= OrderInfo.objects.get(order_id=sku.order_id) user = User.objects.get(id = skuinfo.user_id) # 获取用户名,判断是否匿名 sku.username", "user = self.request.user order = OrderInfo.objects.filter(user = user) return order", "OrderShowSerializer({'freight': freight, 'skus': skus}) return Response(ser.data) # 保存订单信息 class OrderSaveView(ListModelMixin,", "APIView from django_redis import get_redis_connection from goods.models import SKU from", "import PageNum from rest_framework.filters import OrderingFilter # 展示订单信息 class OrdersShowView(APIView):", "SaveSkuComment(CreateAPIView): serializer_class = CommentSaveSerializers # 商品详情中的评论展示 class ShowComment(ListAPIView): serializer_class =", "= self.kwargs['order_id'] skus = OrderGoods.objects.filter(order_id = order_id, is_commented=False) return skus", "User.objects.get(id = skuinfo.user_id) # 获取用户名,判断是否匿名 sku.username = user.username if sku.is_anonymous", "OrderListView(ListAPIView): pagination_class = PageNum serializer_class = OrderListSerializer def get_queryset(self): user", "查询所有选中状态的数据对象 skus = SKU.objects.filter(id__in=sku_ids) # 商品对象添加count属性(sku表中没有count字段,要手动添加属性) for sku in skus:", "serializer_class = CommentShowSerializers def get_queryset(self): # 从kwargs中获取sku_id sku_id = self.kwargs['sku_id']", "CommentSerializers def get_queryset(self): order_id = self.kwargs['order_id'] skus = OrderGoods.objects.filter(order_id =", "= conn.smembers('cart_selected_%s' %user.id) # 查询所有选中状态的数据对象 skus = SKU.objects.filter(id__in=sku_ids) # 商品对象添加count属性(sku表中没有count字段,要手动添加属性)", "SKU from decimal import Decimal from rest_framework.generics import CreateAPIView,ListAPIView from", "orders = OrderGoods.objects.filter(sku_id=sku_id, is_commented = True) for sku in orders:", "# 建立redis连接 conn = get_redis_connection('cart') # 获取hash数据sku_id ,count sku_id_count =", "skuinfo = OrderInfo.objects.get(order_id=sku.order_id) user = User.objects.get(id = skuinfo.user_id) # 获取用户名,判断是否匿名", "= int(count) # 获取集合数据 sku_ids = conn.smembers('cart_selected_%s' %user.id) # 查询所有选中状态的数据对象", "sku.count = cart[sku.id] # 生成运费 freight = Decimal(10.00) # 序列化返回商品对象", "= SKU.objects.filter(id__in=sku_ids) # 商品对象添加count属性(sku表中没有count字段,要手动添加属性) for sku in skus: sku.count =", "= OrderShowSerializer({'freight': freight, 'skus': skus}) return Response(ser.data) # 保存订单信息 class", "def get_queryset(self): # 从kwargs中获取sku_id sku_id = self.kwargs['sku_id'] # 获取商品信息 orders", "user = request.user # 建立redis连接 conn = get_redis_connection('cart') # 获取hash数据sku_id", "OrderSaveView(ListModelMixin, CreateAPIView): serializer_class = OrderSaveSerializer # 订单列表数据获取 class OrderListView(ListAPIView): pagination_class", "# 获取hash数据sku_id ,count sku_id_count = conn.hgetall('cart_%s' %user.id) # {10:1} #", "%user.id) # 查询所有选中状态的数据对象 skus = SKU.objects.filter(id__in=sku_ids) # 商品对象添加count属性(sku表中没有count字段,要手动添加属性) for sku", "class OrderListView(ListAPIView): pagination_class = PageNum serializer_class = OrderListSerializer def get_queryset(self):", "= Decimal(10.00) # 序列化返回商品对象 ser = OrderShowSerializer({'freight': freight, 'skus': skus})" ]
[ "other file output options.\") if args.output: if args.output == \"-\":", "+ \"[{name}][{levelname}] {message}\", datefmt=\"%H:%M:%S\" + (\".%f\" if level == \"trace\"", "= platform.platform() log.debug(f\"OS: {os_version}\") log.debug(f\"Python: {platform.python_version()}\") log.debug(f\"Streamlink: {streamlink_version}\") log.debug(f\"Requests({requests.__version__}), \"", "args.https_proxy: streamlink.set_option(\"https-proxy\", args.https_proxy) if args.http_cookie: streamlink.set_option(\"http-cookies\", dict(args.http_cookie)) if args.http_header: streamlink.set_option(\"http-headers\",", "== \"-\": out = FileOutput(fd=stdout) else: out = check_file_output(formatter.filename(args.output, args.fs_safe_rules),", "\"\"\"Continuously output the stream over HTTP.\"\"\" global output if not", "is DeprecatedPath: log.info(f\"Loaded plugins from deprecated path, see CLI docs", "action.option_strings[0] ) if action.option_strings else action.dest log.debug(f\" {name}={value if name", "} ) def check_file_output(filename, force): \"\"\"Checks if file already exists", "if this stream # uses a subprocess. if args.subprocess_cmdline: if", "streamlink.load_plugins(str(directory)) if success and type(directory) is DeprecatedPath: log.info(f\"Loaded plugins from", "\"-\": filename = LOG_DIR / f\"{datetime.now()}.log\" elif filename: filename =", "silent_log = any(getattr(args, attr) for attr in QUIET_OPTIONS) log_level =", "log_level, args.json) setup_signals() setup_streamlink() # load additional plugins setup_plugins(args.plugin_dirs) setup_plugin_args(streamlink,", "def log_current_versions(): \"\"\"Show current installed versions\"\"\" if not logger.root.isEnabledFor(logging.DEBUG): return", "% \" \".join(unknown)) # Force lowercase to allow case-insensitive lookup", "again once the plugin specific args have been added setup_args(parser)", "streams, stream_name): \"\"\"Decides what to do with the selected stream.", "if it should be overwritten if it does.\"\"\" log.debug(\"Checking file", "to read data from stream: {err}\") if not prebuffer: stream_fd.close()", "data.get(\"info\").get(\"version\") cache.set(\"latest_version\", latest_version, (60 * 60 * 24)) version_info_printed =", "**_kwargs) except OSError as err: console.exit(f\"Failed to create HTTP server:", "see CLI docs for how to migrate: {directory}\") elif showwarning:", "streamlink.set_option(\"ffmpeg-verbose\", args.ffmpeg_verbose) if args.ffmpeg_verbose_path: streamlink.set_option(\"ffmpeg-verbose-path\", args.ffmpeg_verbose_path) if args.ffmpeg_fout: streamlink.set_option(\"ffmpeg-fout\", args.ffmpeg_fout)", "if not streams: log.info(f\"Waiting for streams, retrying every {interval} second(s)\")", "args.stream and not args.json: args.stream = args.default_stream if args.stream: validstreams", "stdin pipe - A named pipe that the subprocess reads", "to get highest priority for config_file in map(lambda path: Path(path).expanduser(),", "if isinstance(stream, StreamProcess): try: cmdline = stream.cmdline() except StreamError as", "output, prebuffer, formatter: Formatter, chunk_size=8192): \"\"\"Reads data from stream and", "is not None: log.info(\"Player closed\") break try: output.write(data) except OSError", "DeprecatedPath: log.info(f\"Loaded config from deprecated path, see CLI docs for", "streamlink.set_option(\"https-proxy\", args.https_proxy) if args.http_cookie: streamlink.set_option(\"http-cookies\", dict(args.http_cookie)) if args.http_header: streamlink.set_option(\"http-headers\", dict(args.http_header))", "from gettext import gettext from itertools import chain from pathlib", "output_stream_http(plugin, streams, formatter, external=True, port=args.player_external_http_port) elif args.player_continuous_http and not file_output:", "if args.output == \"-\": out = FileOutput(fd=stdout) else: out =", "format=(\"[{asctime}]\" if level == \"trace\" else \"\") + \"[{name}][{levelname}] {message}\",", "None, ignore_unknown: bool = False): \"\"\"Parses arguments.\"\"\" global args arglist", "streamlink.set_option(\"http-timeout\", args.http_timeout) def setup_plugins(extra_plugin_dir=None): \"\"\"Loads any additional plugins.\"\"\" load_plugins(PLUGIN_DIRS, showwarning=False)", "of the stream elif args.json: console.msg_json( stream, metadata=plugin.get_metadata() ) elif", "\"getuid\"): if os.geteuid() == 0: log.info(\"streamlink is running as root!", "StreamProcess from streamlink.utils.named_pipe import NamedPipe from streamlink_cli.argparser import build_parser from", "args.http_disable_dh: streamlink.set_option(\"http-disable-dh\", True) if args.http_ssl_cert: streamlink.set_option(\"http-ssl-cert\", args.http_ssl_cert) if args.http_ssl_cert_crt_key: streamlink.set_option(\"http-ssl-cert\",", "log.debug(\"Arguments:\") for action in parser._actions: if not hasattr(args, action.dest): continue", "delimiter.join(validstreams) def handle_url(): \"\"\"The URL handler. Attempts to resolve the", "def create_output(formatter: Formatter): \"\"\"Decides where to write the stream. Depending", "selected output \"\"\" stream_name = resolve_stream_name(streams, stream_name) stream = streams[stream_name]", "not parg.is_global: group.add_argument(parg.argument_name(pname), **parg.options) defaults[parg.dest] = parg.default else: pargdest =", "need to check if the player process still exists when", "NoPluginError, PluginError, StreamError, Streamlink, __version__ as streamlink_version from streamlink.cache import", ") try: for data in stream_iterator: # We need to", "logger from streamlink import NoPluginError, PluginError, StreamError, Streamlink, __version__ as", "\"[{name}][{levelname}] {message}\", datefmt=\"%H:%M:%S\" + (\".%f\" if level == \"trace\" else", "{stream} ({err})\") if not success_open: console.exit(f\"Could not open stream {stream},", "ACCEPTABLE_ERRNO: log.info(\"HTTP connection closed\") else: console.exit(f\"Error when writing to output:", "= FileOutput(fd=stdout, record=record) else: http = namedpipe = record =", "plugins = getattr(action, \"plugins\", []) plugins.append(pname) setattr(action, \"plugins\", plugins) plugin.options", "config_files.append(config_file) break if streamlink and args.url: # Only load first", "is available!\") cache.set(\"version_info_printed\", True, (60 * 60 * 6)) elif", "streamlink.set_option(\"ringbuffer-size\", args.ringbuffer_size) if args.mux_subtitles: streamlink.set_option(\"mux-subtitles\", args.mux_subtitles) if args.hds_live_edge: streamlink.set_option(\"hds-live-edge\", args.hds_live_edge)", "\"\"\"Sets Streamlink options.\"\"\" if args.interface: streamlink.set_option(\"interface\", args.interface) if args.ipv4: streamlink.set_option(\"ipv4\",", "else args.url ) return out def create_http_server(*_args, **_kwargs): \"\"\"Creates a", "it is not empty. \"\"\" while not player or player.running:", "= res.json() latest_version = data.get(\"info\").get(\"version\") cache.set(\"latest_version\", latest_version, (60 * 60", "= fetch_streams(plugin) except PluginError as err: log.error(err) streams = None", "high port. \"\"\" try: http = HTTPServer() http.bind(*_args, **_kwargs) except", "streamlink.set_option(\"http-trust-env\", False) if args.http_no_ssl_verify: streamlink.set_option(\"http-ssl-verify\", False) if args.http_disable_dh: streamlink.set_option(\"http-disable-dh\", True)", "if args.hls_segment_threads: streamlink.set_option(\"hls-segment-threads\", args.hls_segment_threads) if args.hls_segment_timeout: streamlink.set_option(\"hls-segment-timeout\", args.hls_segment_timeout) if args.hls_timeout:", "and (sys.stdout.isatty() or args.force_progress) ) show_record_progress = ( hasattr(output, \"record\")", "Not windows QUIET_OPTIONS = (\"json\", \"stream_url\", \"subprocess_cmdline\", \"quiet\") args =", "sorting_excludes=args.stream_sorting_excludes) def fetch_streams_with_retry(plugin, interval, count): \"\"\"Attempts to fetch streams repeatedly", "streamlink.set_option(\"hls-segment-ignore-names\", args.hls_segment_ignore_names) if args.hls_segment_key_uri: streamlink.set_option(\"hls-segment-key-uri\", args.hls_segment_key_uri) if args.hls_audio_select: streamlink.set_option(\"hls-audio-select\", args.hls_audio_select)", "= isinstance(output, HTTPServer) is_fifo = is_player and output.namedpipe show_progress =", "import gettext from itertools import chain from pathlib import Path", "streamlink.set_option(\"rtmp-rtmpdump\", args.rtmpdump) if args.rtmp_proxy: streamlink.set_option(\"rtmp-proxy\", args.rtmp_proxy) # deprecated if args.hds_segment_attempts:", "= sys.argv[1:] # Load arguments from config files configs =", "in args.player_passthrough and not file_output: log.info(f\"Opening stream: {stream_name} ({stream_type})\") success", "socks_version from websocket import __version__ as websocket_version import streamlink.logger as", "= type(stream).shortname() if stream_type in args.player_passthrough and not file_output: log.info(f\"Opening", "the path to a player \" \"executable with --player.\") if", "args.retry_streams: retry_streams = args.retry_streams if args.retry_max: retry_max = args.retry_max streams", "False) if args.http_disable_dh: streamlink.set_option(\"http-disable-dh\", True) if args.http_ssl_cert: streamlink.set_option(\"http-ssl-cert\", args.http_ssl_cert) if", "while a player is running if it is not empty.", "= None if not args.player: console.exit(\"The default player (VLC) does", "config_files, ignore_unknown=ignore_unknown) def setup_signals(): # Handle SIGTERM just like SIGINT", "console.ask(prompt) ) def log_root_warning(): if hasattr(os, \"getuid\"): if os.geteuid() ==", "args.default_stream and not args.stream and not args.json: args.stream = args.default_stream", "args.subprocess_errorlog) streamlink.set_option(\"subprocess-errorlog-path\", args.subprocess_errorlog_path) streamlink.set_option(\"locale\", args.locale) def setup_plugin_args(session, parser): \"\"\"Sets Streamlink", "such as proxy and headers.\"\"\" if args.http_proxy: streamlink.set_option(\"http-proxy\", args.http_proxy) if", "config_file.with_name(f\"{config_file.name}.{plugin.module}\") if not config_file.is_file(): continue if type(config_file) is DeprecatedPath: log.info(f\"Loaded", "setup_options(): \"\"\"Sets Streamlink options.\"\"\" if args.interface: streamlink.set_option(\"interface\", args.interface) if args.ipv4:", "= stream_fd.read(8192) except OSError as err: stream_fd.close() raise StreamError(f\"Failed to", "if args.interface: streamlink.set_option(\"interface\", args.interface) if args.ipv4: streamlink.set_option(\"ipv4\", args.ipv4) if args.ipv6:", "current installed versions\"\"\" if not logger.root.isEnabledFor(logging.DEBUG): return # macOS if", "returned or limit hit.\"\"\" try: streams = fetch_streams(plugin) except PluginError", "pargdest != action.dest: continue defaults[pargdest] = action.default # add plugin", "specified last to get highest priority for config_file in map(lambda", "closed by the player. if is_win32 and is_fifo: output.player.poll() if", "StreamError as err: log.error(f\"Try {i + 1}/{args.retry_open}: Could not open", "'.join(args.stream)}' could not be found\" if args.json: console.msg_json( plugin=plugin.module, metadata=plugin.get_metadata(),", "stream_iterator, prefix=os.path.basename(output.record.filename) ) try: for data in stream_iterator: # We", "# pragma: no branch (option for option in action.option_strings if", "and headers.\"\"\" if args.http_proxy: streamlink.set_option(\"http-proxy\", args.http_proxy) if args.https_proxy: streamlink.set_option(\"https-proxy\", args.https_proxy)", "force and version_info_printed: return installed_version = StrictVersion(streamlink.version) latest_version = StrictVersion(latest_version)", "start player: {args.player} ({err})\") return False return True def open_stream(stream):", "try: streams = fetch_streams(plugin) except FatalPluginError: raise except PluginError as", "name = f\"{name} ({joined})\" validstreams.append(name) return delimiter.join(validstreams) def handle_url(): \"\"\"The", "stream over HTTP.\"\"\" global output if not external: if not", "or args.stdout) and (args.record or args.record_and_pipe): console.exit(\"Cannot use record options", "installed versions\"\"\" if not logger.root.isEnabledFor(logging.DEBUG): return # macOS if sys.platform", "record = check_file_output(formatter.filename(args.record, args.fs_safe_rules), args.force) log.info(f\"Starting player: {args.player}\") out =", ") if show_progress: stream_iterator = progress( stream_iterator, prefix=os.path.basename(output.filename) ) elif", "write the stream to output.\"\"\" global output success_open = False", "URL: {args.url}\") except PluginError as err: console.exit(err) if not streams:", "extra_plugin_dir]) def setup_streamlink(): \"\"\"Creates the Streamlink session.\"\"\" global streamlink streamlink", "if user specified a valid one, otherwise output list of", "gettext(\"unrecognized arguments: %s\") parser.error(msg % \" \".join(unknown)) # Force lowercase", "= data.get(\"info\").get(\"version\") cache.set(\"latest_version\", latest_version, (60 * 60 * 24)) version_info_printed", "if args.record: record = check_file_output(formatter.filename(args.record, args.fs_safe_rules), args.force) log.info(f\"Starting player: {args.player}\")", "return streams def resolve_stream_name(streams, stream_name): \"\"\"Returns the real stream name", "Find any streams with a '_alt' suffix and attempt #", "parser) if args.version_check or args.auto_version_check: with ignored(Exception): check_version(force=args.version_check) if args.plugins:", "len(synonyms) > 0: joined = delimiter.join(synonyms) name = f\"{name} ({joined})\"", "loaded.\"\"\" pluginlist = list(streamlink.get_plugins().keys()) pluginlist_formatted = \", \".join(sorted(pluginlist)) if args.json:", "yield server.open(timeout=2.5) except OSError: continue def output_stream_http(plugin, initial_streams, formatter: Formatter,", "delimiter = \", \" validstreams = [] for name, stream", "os_version = f\"macOS {platform.mac_ver()[0]}\" # Windows elif sys.platform == \"win32\":", "the stream over HTTP.\"\"\" global output if not external: if", "{i + 1}/{args.retry_open}: Could not open stream {stream} ({err})\") if", "or args.output == \"-\" or args.record_and_pipe: console_out = sys.stderr else:", "stream_fd: try: log.info(\"Closing currently open stream...\") stream_fd.close() except KeyboardInterrupt: error_code", "uses a subprocess. if args.subprocess_cmdline: if isinstance(stream, StreamProcess): try: cmdline", "streams, stream_name) return err = f\"The specified stream(s) '{', '.join(args.stream)}'", "setup_signals(): # Handle SIGTERM just like SIGINT signal.signal(signal.SIGTERM, signal.default_int_handler) def", "if args.http_proxy: streamlink.set_option(\"http-proxy\", args.http_proxy) if args.https_proxy: streamlink.set_option(\"https-proxy\", args.https_proxy) if args.http_cookie:", "args.verbose_player, title=formatter.title(args.title, defaults=DEFAULT_STREAM_METADATA) if args.title else args.url ) try: log.info(f\"Starting", "if answer.lower() != \"y\": sys.exit() else: log.error(f\"File {filename} already exists,", "if args.http_ssl_cert: streamlink.set_option(\"http-ssl-cert\", args.http_ssl_cert) if args.http_ssl_cert_crt_key: streamlink.set_option(\"http-ssl-cert\", tuple(args.http_ssl_cert_crt_key)) if args.http_timeout:", "create_output(formatter: Formatter): \"\"\"Decides where to write the stream. Depending on", "command-line. silent_log = any(getattr(args, attr) for attr in QUIET_OPTIONS) log_level", "to start player: {args.player} ({err})\") else: server = create_http_server(host=None, port=port)", "err: console.exit(f\"Failed to create pipe: {err}\") elif args.player_http: http =", "streams[stream_name] and name not in STREAM_SYNONYMS: return name return stream_name", "i in range(args.retry_open): try: stream_fd, prebuffer = open_stream(stream) success_open =", "in plugin.arguments: if parg.sensitive: sensitive.add(parg.argument_name(pname)) log.debug(\"Arguments:\") for action in parser._actions:", "call argument set up as early as possible to load", "and output.record.fd is not stdout and (sys.stdout.isatty() or args.force_progress) )", "from stream: {err}, exiting\") finally: stream.close() log.info(\"Stream ended\") def handle_stream(plugin,", "to see the available options or read the manual at", "None plugin: Plugin = None stream_fd: StreamIO = None streamlink:", "= is_player and output.namedpipe show_progress = ( isinstance(output, FileOutput) and", "stream(s) '{', '.join(args.stream)}' could not be found\" if args.json: console.msg_json(", "lambda: plugin.get_category(), \"game\": lambda: plugin.get_category(), \"title\": lambda: plugin.get_title(), \"time\": lambda:", "+ url) for req in iter_http_requests(server, player): user_agent = req.headers.get(\"User-Agent\")", "s in args.stream): if stream_name in streams: stream = streams[stream_name]", "OSError as err: if isinstance(output, PlayerOutput): console.exit(f\"Failed to start player:", "else args.url ) try: log.info(f\"Starting player: {args.player}\") if player: player.open()", "to selected output \"\"\" stream_name = resolve_stream_name(streams, stream_name) stream =", "not silent_log else \"none\" logger.root.setLevel(log_level) setup_http_session() log_root_warning() log_current_versions() log_current_arguments(streamlink, parser)", "the output. \"\"\" global stream_fd # Attempts to open the", "setup_args(parser, ignore_unknown=True) # call argument set up as early as", "as websocket_version import streamlink.logger as logger from streamlink import NoPluginError,", "except StreamError as err: raise StreamError(f\"Could not open stream: {err}\")", "resolve the URL to a plugin and then attempts to", "# macOS if sys.platform == \"darwin\": os_version = f\"macOS {platform.mac_ver()[0]}\"", "dt.strftime(fmt) } ) def check_file_output(filename, force): \"\"\"Checks if file already", "is not a directory!\") def setup_args(parser: argparse.ArgumentParser, config_files: List[Path] =", "{} group = plugin_args.add_argument_group(pname.capitalize()) for parg in plugin.arguments: if not", "output.player.returncode is not None: log.info(\"Player closed\") break try: output.write(data) except", "host is empty, listen on all available interfaces, and if", "is_http = isinstance(output, HTTPServer) is_fifo = is_player and output.namedpipe show_progress", "stdout and (sys.stdout.isatty() or args.force_progress) ) show_record_progress = ( hasattr(output,", "action.dest: continue defaults[pargdest] = action.default # add plugin to global", "arguments take precedence over deprecated stream-type arguments if args.stream_segment_attempts: streamlink.set_option(\"stream-segment-attempts\",", "streamlink.set_option(\"hls-live-edge\", args.hls_live_edge) if args.hls_playlist_reload_attempts: streamlink.set_option(\"hls-playlist-reload-attempts\", args.hls_playlist_reload_attempts) if args.hls_playlist_reload_time: streamlink.set_option(\"hls-playlist-reload-time\", args.hls_playlist_reload_time)", "server.close(True) player.close() server.close() def output_stream_passthrough(stream, formatter: Formatter): \"\"\"Prepares a filename", "data from stream: {err}\") if not prebuffer: stream_fd.close() raise StreamError(\"No", "path in extra_plugin_dir]) def setup_streamlink(): \"\"\"Creates the Streamlink session.\"\"\" global", "PlayerOutput( args.player, args=args.player_args, filename=filename, call=True, quiet=not args.verbose_player, title=formatter.title(args.title, defaults=DEFAULT_STREAM_METADATA) if", "isinstance(output, PlayerOutput) is_http = isinstance(output, HTTPServer) is_fifo = is_player and", "# Console output should be on stderr if we are", "we are outputting # a stream to stdout. if args.stdout", "plugin): \"\"\"Sets Streamlink plugin options.\"\"\" pname = plugin.module required =", "case the main stream is not usable. alt_streams = list(filter(lambda", "lambda: plugin.get_category(), \"title\": lambda: plugin.get_title(), \"time\": lambda: datetime.now() }, {", "{platform.release()}\" # Linux / other else: os_version = platform.platform() log.debug(f\"OS:", "- A regular file \"\"\" if (args.output or args.stdout) and", "else: console.exit(f\"Error when writing to output: {err}, exiting\") break except", "in map(lambda path: Path(path).expanduser(), reversed(args.config)): if config_file.is_file(): config_files.append(config_file) else: #", "def setup_http_session(): \"\"\"Sets the global HTTP settings, such as proxy", "if config_files: setup_args(parser, config_files, ignore_unknown=ignore_unknown) def setup_signals(): # Handle SIGTERM", "lambda dt, fmt: dt.strftime(fmt) } ) def check_file_output(filename, force): \"\"\"Checks", "or while a player is running if it is not", "= getattr(args, action.dest) if action.default != value: name = next(", "import sys from collections import OrderedDict from contextlib import closing", "= StrictVersion(streamlink.version) latest_version = StrictVersion(latest_version) if latest_version > installed_version: log.info(f\"A", "if args.hls_live_restart: streamlink.set_option(\"hls-live-restart\", args.hls_live_restart) if args.rtmp_rtmpdump: streamlink.set_option(\"rtmp-rtmpdump\", args.rtmp_rtmpdump) elif args.rtmpdump:", "log_file, log_level, args.json) setup_signals() setup_streamlink() # load additional plugins setup_plugins(args.plugin_dirs)", "--player.\") if args.player_fifo: try: namedpipe = NamedPipe() except OSError as", "check_file_output(filename, force): \"\"\"Checks if file already exists and ask the", "it does.\"\"\" log.debug(\"Checking file output\") if os.path.isfile(filename) and not force:", "one, otherwise output list of valid streams. \"\"\" try: plugin", "\"-\" or args.record_and_pipe: console_out = sys.stderr else: console_out = sys.stdout", "streams.keys())) if len(synonyms) > 0: joined = delimiter.join(synonyms) name =", "if args.ffmpeg_verbose_path: streamlink.set_option(\"ffmpeg-verbose-path\", args.ffmpeg_verbose_path) if args.ffmpeg_fout: streamlink.set_option(\"ffmpeg-fout\", args.ffmpeg_fout) if args.ffmpeg_video_transcode:", "{err}\") elif args.player_http: http = create_http_server() if args.record: record =", "We want the config specified last to get highest priority", "+ arglist) if unknown and not ignore_unknown: msg = gettext(\"unrecognized", "attempts >= count: break return streams def resolve_stream_name(streams, stream_name): \"\"\"Returns", "sorted(streams.items(), key=lambda stream: plugin.stream_weight(stream[0])): if name in STREAM_SYNONYMS: continue def", "if type(config_file) is DeprecatedPath: log.info(f\"Loaded plugin config from deprecated path,", "from streamlink.exceptions import FatalPluginError from streamlink.plugin import Plugin, PluginOptions from", "streamlink.set_option(\"hds-segment-threads\", args.hds_segment_threads) if args.hds_segment_timeout: streamlink.set_option(\"hds-segment-timeout\", args.hds_segment_timeout) if args.hds_timeout: streamlink.set_option(\"hds-timeout\", args.hds_timeout)", "filename: filename = Path(filename).expanduser().resolve() if filename: filename.parent.mkdir(parents=True, exist_ok=True) streamhandler =", "possible to load args from config files setup_config_args(parser, ignore_unknown=True) #", "\"executable with --player.\") server = create_http_server() player = output =", "Formatter, external=False, port=0): \"\"\"Continuously output the stream over HTTP.\"\"\" global", "\"\"\"Open stream, create output and finally write the stream to", "if args.hls_segment_timeout: streamlink.set_option(\"hls-segment-timeout\", args.hls_segment_timeout) if args.hls_timeout: streamlink.set_option(\"hls-timeout\", args.hls_timeout) if args.http_stream_timeout:", "from deprecated path, see CLI docs for how to migrate:", "Close output if output: output.close() console.msg(\"Interrupted! Exiting...\") error_code = 130", "def output_stream(stream, formatter: Formatter): \"\"\"Open stream, create output and finally", "force: if sys.stdin.isatty(): answer = console.ask(f\"File {filename} already exists! Overwrite", "pipe that the subprocess reads from - A regular file", "to overwrite it.\") sys.exit() return FileOutput(filename) def create_output(formatter: Formatter): \"\"\"Decides", "args.url and args.url_param: args.url = args.url_param def setup_config_args(parser, ignore_unknown=False): config_files", "streamlink.set_option(\"http-ssl-cert\", tuple(args.http_ssl_cert_crt_key)) if args.http_timeout: streamlink.set_option(\"http-timeout\", args.http_timeout) def setup_plugins(extra_plugin_dir=None): \"\"\"Loads any", "\"darwin\": os_version = f\"macOS {platform.mac_ver()[0]}\" # Windows elif sys.platform ==", "when reading from stream: {err}, exiting\") finally: stream.close() log.info(\"Stream ended\")", "up as early as possible to load args from config", "({installed_version}) is up to date!\") if force: sys.exit() def setup_logger_and_console(stream=sys.stdout,", "# Not windows QUIET_OPTIONS = (\"json\", \"stream_url\", \"subprocess_cmdline\", \"quiet\") args", "request from {user_agent}\") stream_fd = prebuffer = None while not", "streams: sleep(interval) try: streams = fetch_streams(plugin) except FatalPluginError: raise except", "sys.exit() else: log.error(f\"File {filename} already exists, use --force to overwrite", "stream and reads 8192 bytes from it. This is useful", "exiting\") output = create_output(formatter) try: output.open() except OSError as err:", "connection closed\") else: console.exit(f\"Error when writing to output: {err}, exiting\")", "open_stream(stream): \"\"\"Opens a stream and reads 8192 bytes from it.", "stream_fd, prebuffer def output_stream(stream, formatter: Formatter): \"\"\"Open stream, create output", "ignore_unknown: bool = False): \"\"\"Parses arguments.\"\"\" global args arglist =", "output_stream_passthrough(stream, formatter: Formatter): \"\"\"Prepares a filename to be passed to", "try: setup_options() handle_url() except KeyboardInterrupt: # Close output if output:", "import logging import os import platform import signal import sys", "args.player, args=args.player_args, quiet=not args.verbose_player, kill=not args.player_no_close, namedpipe=namedpipe, http=http, record=record, title=formatter.title(args.title,", "setup_options() handle_url() except KeyboardInterrupt: # Close output if output: output.close()", "closed\") else: console.exit(f\"Error when writing to output: {err}, exiting\") break", "lowercase to allow case-insensitive lookup if args.stream: args.stream = [stream.lower()", "except OSError as err: stream_fd.close() raise StreamError(f\"Failed to read data", "= None plugin: Plugin = None stream_fd: StreamIO = None", "parser._actions: if not hasattr(args, action.dest): continue value = getattr(args, action.dest)", "# Read 8192 bytes before proceeding to check for errors.", "translated to a command\") # Print JSON representation of the", "and args.url: # Only load first available plugin config with", "from streamlink import NoPluginError, PluginError, StreamError, Streamlink, __version__ as streamlink_version", "raise StreamError(\"No data returned from stream\") return stream_fd, prebuffer def", "specified a valid one, otherwise output list of valid streams.", "defaults[pargdest] = action.default # add plugin to global argument plugins", "path: path.is_file(), CONFIG_FILES): if type(config_file) is DeprecatedPath: log.info(f\"Loaded config from", "latest_version > installed_version: log.info(f\"A new version of Streamlink ({latest_version}) is", "delimiter.join(synonyms) name = f\"{name} ({joined})\" validstreams.append(name) return delimiter.join(validstreams) def handle_url():", "= None console: ConsoleOutput = None output: Output = None", "err: console.exit(f\"Error when reading from stream: {err}, exiting\") finally: stream.close()", "= set() for pname, plugin in session.plugins.items(): for parg in", "> 0: joined = delimiter.join(synonyms) name = f\"{name} ({joined})\" validstreams.append(name)", "= [f\"@{config_file}\" for config_file in config_files or []] args, unknown", "= action.default # add plugin to global argument plugins =", "req.headers.get(\"User-Agent\") or \"unknown player\" log.info(f\"Got HTTP request from {user_agent}\") stream_fd", "def setup_signals(): # Handle SIGTERM just like SIGINT signal.signal(signal.SIGTERM, signal.default_int_handler)", "args.url ) return out def create_http_server(*_args, **_kwargs): \"\"\"Creates a HTTP", "({err})\") return False return True def open_stream(stream): \"\"\"Opens a stream", "= f\"The specified stream(s) '{', '.join(args.stream)}' could not be found\"", "log.error(err) if count > 0: attempts += 1 if attempts", "= [] for name, stream in sorted(streams.items(), key=lambda stream: plugin.stream_weight(stream[0])):", "log.info(f\"Found matching plugin {plugin.module} for URL {args.url}\") if args.retry_max or", "streamlink.set_option(\"ipv6\", args.ipv6) if args.ringbuffer_size: streamlink.set_option(\"ringbuffer-size\", args.ringbuffer_size) if args.mux_subtitles: streamlink.set_option(\"mux-subtitles\", args.mux_subtitles)", "additional plugins.\"\"\" load_plugins(PLUGIN_DIRS, showwarning=False) if extra_plugin_dir: load_plugins([Path(path).expanduser() for path in", "\"\"\"Loads any additional plugins.\"\"\" load_plugins(PLUGIN_DIRS, showwarning=False) if extra_plugin_dir: load_plugins([Path(path).expanduser() for", "args.output or args.stdout formatter = get_formatter(plugin) for stream_name in [stream_name]", "macOS if sys.platform == \"darwin\": os_version = f\"macOS {platform.mac_ver()[0]}\" #", "in session.plugins.items(): for parg in plugin.arguments: if parg.sensitive: sensitive.add(parg.argument_name(pname)) log.debug(\"Arguments:\")", "\"title\": lambda: plugin.get_title(), \"time\": lambda: datetime.now() }, { \"time\": lambda", "port is 0, listen on a random high port. \"\"\"", "ignore_unknown=True) # Console output should be on stderr if we", "is not # automatically closed by the player. if is_win32", "list(filter(synonymfilter, streams.keys())) if len(synonyms) > 0: joined = delimiter.join(synonyms) name", "KeyboardInterrupt: error_code = 130 elif args.url: try: setup_options() handle_url() except", "= OrderedDict({}) for parg in plugin.arguments: if parg.options.get(\"help\") == argparse.SUPPRESS:", "usable. alt_streams = list(filter(lambda k: stream_name + \"_alt\" in k,", "= 0 parser = build_parser() setup_args(parser, ignore_unknown=True) # call argument", "args.url_param: args.url = args.url_param def setup_config_args(parser, ignore_unknown=False): config_files = []", "as root! Be careful!\") def log_current_versions(): \"\"\"Show current installed versions\"\"\"", "pathlib import Path from time import sleep from typing import", "in k, sorted(streams.keys()))) file_output = args.output or args.stdout formatter =", "stream: {stream_name} ({stream_type})\") success = output_stream_passthrough(stream, formatter) elif args.player_external_http: return", "args.hds_segment_threads) if args.hds_segment_timeout: streamlink.set_option(\"hds-segment-timeout\", args.hds_segment_timeout) if args.hds_timeout: streamlink.set_option(\"hds-timeout\", args.hds_timeout) if", "path: Path(path).expanduser(), reversed(args.config)): if config_file.is_file(): config_files.append(config_file) else: # Only load", "logger.root.setLevel(log_level) setup_http_session() log_root_warning() log_current_versions() log_current_arguments(streamlink, parser) if args.version_check or args.auto_version_check:", "a player \" \"executable with --player.\") if args.player_fifo: try: namedpipe", "in CONFIG_FILES: config_file = config_file.with_name(f\"{config_file.name}.{plugin.module}\") if not config_file.is_file(): continue if", "stream and then writes it to the output.\"\"\" is_player =", "if parg.required or value: try: for rparg in plugin.arguments.requires(parg.name): required[rparg.name]", "setup_plugins(args.plugin_dirs) setup_plugin_args(streamlink, parser) # call setup args again once the", "StreamError(f\"Failed to read data from stream: {err}\") if not prebuffer:", "reads from - A regular file \"\"\" if (args.output or", "log.error(err) if stream_fd and prebuffer: log.debug(\"Writing stream to player\") read_stream(stream_fd,", "if sys.stdin.isatty(): answer = console.ask(f\"File {filename} already exists! Overwrite it?", "error_code = 1 except KeyboardInterrupt: error_code = 130 elif args.can_handle_url_no_redirect:", "\"none\" logger.root.setLevel(log_level) setup_http_session() log_root_warning() log_current_versions() log_current_arguments(streamlink, parser) if args.version_check or", "FileOutput) and output.record.fd is not stdout and (sys.stdout.isatty() or args.force_progress)", "log.error(f\"Unable to fetch new streams: {err}\") continue try: log.info(f\"Opening stream:", "stream_name) return err = f\"The specified stream(s) '{', '.join(args.stream)}' could", "1}/{args.retry_open}: Could not open stream {stream} ({err})\") if not success_open:", "in args.stream] if not args.url and args.url_param: args.url = args.url_param", "{pluginlist_formatted}\") def load_plugins(dirs: List[Path], showwarning: bool = True): \"\"\"Attempts to", "open stream {stream} ({err})\") if not success_open: console.exit(f\"Could not open", "\" + url) for req in iter_http_requests(server, player): user_agent =", "except OSError as err: console.exit(f\"Failed to start player: {args.player} ({err})\")", "while not stream_fd and (not player or player.running): try: streams", "want log output when we are printing JSON or a", "if args.hls_playlist_reload_time: streamlink.set_option(\"hls-playlist-reload-time\", args.hls_playlist_reload_time) if args.hls_segment_ignore_names: streamlink.set_option(\"hls-segment-ignore-names\", args.hls_segment_ignore_names) if args.hls_segment_key_uri:", "return delimiter.join(validstreams) def handle_url(): \"\"\"The URL handler. Attempts to resolve", "= check_file_output(formatter.filename(args.record_and_pipe, args.fs_safe_rules), args.force) out = FileOutput(fd=stdout, record=record) else: http", "log.debug(f\" {name}={value if name not in sensitive else '*' *", "0 while not streams: sleep(interval) try: streams = fetch_streams(plugin) except", "parg.dest for action in parser._actions: # find matching global argument", "to global argument plugins = getattr(action, \"plugins\", []) plugins.append(pname) setattr(action,", "then attempts to fetch a list of available streams. Proceeds", "args.http_cookie: streamlink.set_option(\"http-cookies\", dict(args.http_cookie)) if args.http_header: streamlink.set_option(\"http-headers\", dict(args.http_header)) if args.http_query_param: streamlink.set_option(\"http-query-params\",", "# Output the stream else: # Find any streams with", "streamlink.resolve_url(args.can_handle_url) except NoPluginError: error_code = 1 except KeyboardInterrupt: error_code =", "server, access with one of:\") for url in server.urls: log.info(\"", "\" \"installed. You must specify the path to a player", "= streams[stream_name] stream_type = type(stream).shortname() if stream_type in args.player_passthrough and", "if unknown and not ignore_unknown: msg = gettext(\"unrecognized arguments: %s\")", "stream.open() except StreamError as err: raise StreamError(f\"Could not open stream:", "streams, formatter, external=True, port=args.player_external_http_port) elif args.player_continuous_http and not file_output: return", "player process still exists when # using named pipes on", "args.player_continuous_http and not file_output: return output_stream_http(plugin, streams, formatter) else: log.info(f\"Opening", "= getattr(args, parg.dest if parg.is_global else parg.namespace_dest(pname)) session.set_plugin_option(pname, parg.dest, value)", "requests from socks import __version__ as socks_version from websocket import", "elif args.can_handle_url_no_redirect: try: streamlink.resolve_url_no_redirect(args.can_handle_url_no_redirect) except NoPluginError: error_code = 1 except", "streamlink_cli.argparser import build_parser from streamlink_cli.compat import DeprecatedPath, is_win32, stdout from", "a '_alt' suffix and attempt # to use these in", "logger.basicConfig( stream=stream, filename=filename, level=level, style=\"{\", format=(\"[{asctime}]\" if level == \"trace\"", "stream_fd.close() raise StreamError(\"No data returned from stream\") return stream_fd, prebuffer", "streamlink.set_option(\"hds-segment-timeout\", args.hds_segment_timeout) if args.hds_timeout: streamlink.set_option(\"hds-timeout\", args.hds_timeout) if args.hls_segment_attempts: streamlink.set_option(\"hls-segment-attempts\", args.hls_segment_attempts)", "create_output(formatter) try: output.open() except OSError as err: if isinstance(output, PlayerOutput):", "command\") # Print JSON representation of the stream elif args.json:", "args.retry_max streams = fetch_streams_with_retry(plugin, retry_streams, retry_max) else: streams = fetch_streams(plugin)", "output when we are printing JSON or a command-line. silent_log", "name synonyms = list(filter(synonymfilter, streams.keys())) if len(synonyms) > 0: joined", "player.running): try: streams = initial_streams or fetch_streams(plugin) initial_streams = None", "streamlink.set_option(\"hls-start-offset\", args.hls_start_offset) if args.hls_duration: streamlink.set_option(\"hls-duration\", args.hls_duration) if args.hls_live_restart: streamlink.set_option(\"hls-live-restart\", args.hls_live_restart)", "is useful to check if a stream actually has data", "plugins from a list of directories.\"\"\" for directory in dirs:", "None setup_logger_and_console(console_out, log_file, log_level, args.json) setup_signals() setup_streamlink() # load additional", "if not args.player: console.exit(\"The default player (VLC) does not seem", "name, stream in sorted(streams.items(), key=lambda stream: plugin.stream_weight(stream[0])): if name in", "streamlink = Streamlink({\"user-input-requester\": ConsoleUserInputRequester(console)}) def setup_options(): \"\"\"Sets Streamlink options.\"\"\" if", "err: log.error(err) if stream_fd and prebuffer: log.debug(\"Writing stream to player\")", "except StreamError as err: log.error(f\"Try {i + 1}/{args.retry_open}: Could not", "- A subprocess' stdin pipe - A named pipe that", "output success_open = False for i in range(args.retry_open): try: stream_fd,", "typing import List import requests from socks import __version__ as", "the stream else: # Find any streams with a '_alt'", "continue if type(config_file) is DeprecatedPath: log.info(f\"Loaded plugin config from deprecated", "if args.ipv6: streamlink.set_option(\"ipv6\", args.ipv6) if args.ringbuffer_size: streamlink.set_option(\"ringbuffer-size\", args.ringbuffer_size) if args.mux_subtitles:", "{args.retry_open} times, exiting\") output = create_output(formatter) try: output.open() except OSError", "import sleep from typing import List import requests from socks", "prebuffer, formatter) return True def read_stream(stream, output, prebuffer, formatter: Formatter,", "careful!\") def log_current_versions(): \"\"\"Show current installed versions\"\"\" if not logger.root.isEnabledFor(logging.DEBUG):", "filename = LOG_DIR / f\"{datetime.now()}.log\" elif filename: filename = Path(filename).expanduser().resolve()", "errors. # This is to avoid opening the output unnecessarily.", "show_progress = ( isinstance(output, FileOutput) and output.fd is not stdout", "a stream to stdout. if args.stdout or args.output == \"-\"", "player: {args.player}\") output.open() except OSError as err: console.exit(f\"Failed to start", "streams using correct parameters.\"\"\" return plugin.streams(stream_types=args.stream_types, sorting_excludes=args.stream_sorting_excludes) def fetch_streams_with_retry(plugin, interval,", "# generic stream- arguments take precedence over deprecated stream-type arguments", "STREAM_SYNONYMS: continue def synonymfilter(n): return stream is streams[n] and n", "from config files setup_config_args(parser, ignore_unknown=True) # Console output should be", "= plugin.module required = OrderedDict({}) for parg in plugin.arguments: if", "error_code = 1 except KeyboardInterrupt: error_code = 130 elif args.url:", "Streams are sorted according to their quality (based on plugin.stream_weight).", "player: {args.player} ({err})\") return False return True def open_stream(stream): \"\"\"Opens", "args.output == \"-\": out = FileOutput(fd=stdout) else: out = check_file_output(formatter.filename(args.output,", "not args.url and args.url_param: args.url = args.url_param def setup_config_args(parser, ignore_unknown=False):", "streamlink.set_option(\"hls-live-restart\", args.hls_live_restart) if args.rtmp_rtmpdump: streamlink.set_option(\"rtmp-rtmpdump\", args.rtmp_rtmpdump) elif args.rtmpdump: streamlink.set_option(\"rtmp-rtmpdump\", args.rtmpdump)", "def main(): error_code = 0 parser = build_parser() setup_args(parser, ignore_unknown=True)", ") stream_iterator = chain( [prebuffer], iter(partial(stream.read, chunk_size), b\"\") ) if", "log.info(\"Player closed\") elif is_http and err.errno in ACCEPTABLE_ERRNO: log.info(\"HTTP connection", "not args.stream and not args.json: args.stream = args.default_stream if args.stream:", "prebuffer = stream_fd.read(8192) except OSError as err: stream_fd.close() raise StreamError(f\"Failed", "record=record) else: http = namedpipe = record = None if", "branch (option for option in action.option_strings if option.startswith(\"--\")), action.option_strings[0] )", "websocket import __version__ as websocket_version import streamlink.logger as logger from", "to fetch new streams: {err}\") continue try: log.info(f\"Opening stream: {stream_name}", "= FileOutput(fd=stdout) else: out = check_file_output(formatter.filename(args.output, args.fs_safe_rules), args.force) elif args.stdout:", "= cache.get(\"latest_version\") if force or not latest_version: res = requests.get(\"https://pypi.python.org/pypi/streamlink/json\")", "stream in streams.items(): if stream is streams[stream_name] and name not", "as err: log.error(f\"Unable to fetch new streams: {err}\") continue try:", "def setup_streamlink(): \"\"\"Creates the Streamlink session.\"\"\" global streamlink streamlink =", "streamlink.set_option(\"hls-playlist-reload-attempts\", args.hls_playlist_reload_attempts) if args.hls_playlist_reload_time: streamlink.set_option(\"hls-playlist-reload-time\", args.hls_playlist_reload_time) if args.hls_segment_ignore_names: streamlink.set_option(\"hls-segment-ignore-names\", args.hls_segment_ignore_names)", "them next to the stream they point to. Streams are", "the stream they point to. Streams are sorted according to", "the selected stream. Depending on arguments it can be one", "StreamProcess): try: cmdline = stream.cmdline() except StreamError as err: console.exit(err)", "import os import platform import signal import sys from collections", "if we are outputting # a stream to stdout. if", "console.exit(f\"Failed to create pipe: {err}\") elif args.player_http: http = create_http_server()", "for how to migrate: {config_file}\") config_files.append(config_file) break if config_files: setup_args(parser,", "streamlink.set_option(\"hls-playlist-reload-time\", args.hls_playlist_reload_time) if args.hls_segment_ignore_names: streamlink.set_option(\"hls-segment-ignore-names\", args.hls_segment_ignore_names) if args.hls_segment_key_uri: streamlink.set_option(\"hls-segment-key-uri\", args.hls_segment_key_uri)", "URL {args.url}\") if args.retry_max or args.retry_streams: retry_streams = 1 retry_max", "external=True, port=args.player_external_http_port) elif args.player_continuous_http and not file_output: return output_stream_http(plugin, streams,", "ConsoleUserInputRequester(console)}) def setup_options(): \"\"\"Sets Streamlink options.\"\"\" if args.interface: streamlink.set_option(\"interface\", args.interface)", "else console.ask(prompt) ) def log_root_warning(): if hasattr(os, \"getuid\"): if os.geteuid()", "not external: if not args.player: console.exit(\"The default player (VLC) does", "args.player: console.exit(\"The default player (VLC) does not seem to be", "\"record\") and isinstance(output.record, FileOutput) and output.record.fd is not stdout and", "plugins: {pluginlist_formatted}\") def load_plugins(dirs: List[Path], showwarning: bool = True): \"\"\"Attempts", "streams) for stream_name in args.stream: if stream_name in streams: log.info(f\"Available", "of these: - Output internal command-line - Output JSON represenation", "in streams: for name, stream in streams.items(): if stream is", "requests.get(\"https://pypi.python.org/pypi/streamlink/json\") data = res.json() latest_version = data.get(\"info\").get(\"version\") cache.set(\"latest_version\", latest_version, (60", "True def read_stream(stream, output, prebuffer, formatter: Formatter, chunk_size=8192): \"\"\"Reads data", "still exists when # using named pipes on Windows since", "{args.url}\") if args.retry_max or args.retry_streams: retry_streams = 1 retry_max =", "except PluginError as err: log.error(err) if count > 0: attempts", "of these: - The stdout pipe - A subprocess' stdin", "console.exit(\"Cannot use record options with other file output options.\") if", "check if the player process still exists when # using", "console.msg(cmdline) else: console.exit(\"The stream specified cannot be translated to a", "metadata=plugin.get_metadata(), streams=streams ) elif args.stream_url: try: console.msg(streams[list(streams)[-1]].to_manifest_url()) except TypeError: console.exit(\"The", "args.can_handle_url: try: streamlink.resolve_url(args.can_handle_url) except NoPluginError: error_code = 1 except KeyboardInterrupt:", "args from config files setup_config_args(parser, ignore_unknown=True) # Console output should", "config_files.append(config_file) break if config_files: setup_args(parser, config_files, ignore_unknown=ignore_unknown) def setup_signals(): #", "by the player. if is_win32 and is_fifo: output.player.poll() if output.player.returncode", "= None stream_fd: StreamIO = None streamlink: Streamlink = None", "streamlink.set_option(\"hds-segment-attempts\", args.hds_segment_attempts) if args.hds_segment_threads: streamlink.set_option(\"hds-segment-threads\", args.hds_segment_threads) if args.hds_segment_timeout: streamlink.set_option(\"hds-segment-timeout\", args.hds_segment_timeout)", "import Plugin, PluginOptions from streamlink.stream import StreamIO, StreamProcess from streamlink.utils.named_pipe", "= fetch_streams(plugin) except FatalPluginError: raise except PluginError as err: log.error(err)", "return stream_name def format_valid_streams(plugin, streams): \"\"\"Formats a dict of streams.", "args.logfile if log_level != \"none\" else None setup_logger_and_console(console_out, log_file, log_level,", "Plugin = None stream_fd: StreamIO = None streamlink: Streamlink =", "sys.exit() return FileOutput(filename) def create_output(formatter: Formatter): \"\"\"Decides where to write", "where to write the stream. Depending on arguments it can", "try: yield server.open(timeout=2.5) except OSError: continue def output_stream_http(plugin, initial_streams, formatter:", "err: log.error(f\"Try {i + 1}/{args.retry_open}: Could not open stream {stream}", "given host and port. If host is empty, listen on", "to open the stream try: stream_fd = stream.open() except StreamError", "log.info(f\"Available streams: {validstreams}\") handle_stream(plugin, streams, stream_name) return err = f\"The", "= None, ignore_unknown: bool = False): \"\"\"Parses arguments.\"\"\" global args", "session.get_plugin_option(pname, req.dest): prompt = f\"{req.prompt or f'Enter {pname} {req.name}'}: \"", "f\"{platform.system()} {platform.release()}\" # Linux / other else: os_version = platform.platform()", "can handle URL: {args.url}\") except PluginError as err: console.exit(err) if", "= format_valid_streams(plugin, streams) console.msg(f\"Available streams: {validstreams}\") def print_plugins(): \"\"\"Outputs a", "streamlink.set_option(\"subprocess-errorlog\", args.subprocess_errorlog) streamlink.set_option(\"subprocess-errorlog-path\", args.subprocess_errorlog_path) streamlink.set_option(\"locale\", args.locale) def setup_plugin_args(session, parser): \"\"\"Sets", "args.url, \"author\": lambda: plugin.get_author(), \"category\": lambda: plugin.get_category(), \"game\": lambda: plugin.get_category(),", "= parg # if the value is set, check to", "and not force: if sys.stdin.isatty(): answer = console.ask(f\"File {filename} already", "setup_http_session(): \"\"\"Sets the global HTTP settings, such as proxy and", "at https://streamlink.github.io\" ) sys.exit(error_code) def parser_helper(): session = Streamlink() parser", "args.hls_timeout) if args.http_stream_timeout: streamlink.set_option(\"http-stream-timeout\", args.http_stream_timeout) if args.rtmp_timeout: streamlink.set_option(\"rtmp-timeout\", args.rtmp_timeout) #", "{filename} already exists! Overwrite it? [y/N] \") if answer.lower() !=", "pluginlist_formatted = \", \".join(sorted(pluginlist)) if args.json: console.msg_json(pluginlist) else: console.msg(f\"Loaded plugins:", "except KeyboardInterrupt: error_code = 130 elif args.url: try: setup_options() handle_url()", "already exists, use --force to overwrite it.\") sys.exit() return FileOutput(filename)", "overwrite it.\") sys.exit() return FileOutput(filename) def create_output(formatter: Formatter): \"\"\"Decides where", "or args.auto_version_check: with ignored(Exception): check_version(force=args.version_check) if args.plugins: print_plugins() elif args.can_handle_url:", "the player process still exists when # using named pipes", "not force and version_info_printed: return installed_version = StrictVersion(streamlink.version) latest_version =", "if level == \"trace\" else \"\") ) console = ConsoleOutput(streamhandler.stream,", "otherwise output list of valid streams. \"\"\" try: plugin =", "if args.default_stream and not args.stream and not args.json: args.stream =", "do with the selected stream. Depending on arguments it can", "stream over HTTP - Output stream data to selected output", "return out def create_http_server(*_args, **_kwargs): \"\"\"Creates a HTTP server listening", "-h/--help to see the available options or read the manual", "None stream_fd: StreamIO = None streamlink: Streamlink = None log", "ConsoleOutput = None output: Output = None plugin: Plugin =", "player. if is_win32 and is_fifo: output.player.poll() if output.player.returncode is not", "ACCEPTABLE_ERRNO = (errno.EPIPE, errno.EINVAL, errno.ECONNRESET) try: ACCEPTABLE_ERRNO += (errno.WSAECONNABORTED,) except", "if args.http_cookie: streamlink.set_option(\"http-cookies\", dict(args.http_cookie)) if args.http_header: streamlink.set_option(\"http-headers\", dict(args.http_header)) if args.http_query_param:", "os import platform import signal import sys from collections import", "latest_version = data.get(\"info\").get(\"version\") cache.set(\"latest_version\", latest_version, (60 * 60 * 24))", "{streamlink_version}\") log.debug(f\"Requests({requests.__version__}), \" f\"Socks({socks_version}), \" f\"Websocket({websocket_version})\") def log_current_arguments(session, parser): global", "req.dest): prompt = f\"{req.prompt or f'Enter {pname} {req.name}'}: \" session.set_plugin_option(", "to migrate: {directory}\") elif showwarning: log.warning(f\"Plugin path {directory} does not", "def setup_args(parser: argparse.ArgumentParser, config_files: List[Path] = None, ignore_unknown: bool =", "extra_plugin_dir: load_plugins([Path(path).expanduser() for path in extra_plugin_dir]) def setup_streamlink(): \"\"\"Creates the", "\"\"\"Parses arguments.\"\"\" global args arglist = sys.argv[1:] # Load arguments", "streamlink.set_option(\"ffmpeg-fout\", args.ffmpeg_fout) if args.ffmpeg_video_transcode: streamlink.set_option(\"ffmpeg-video-transcode\", args.ffmpeg_video_transcode) if args.ffmpeg_audio_transcode: streamlink.set_option(\"ffmpeg-audio-transcode\", args.ffmpeg_audio_transcode)", "args.rtmp_rtmpdump) elif args.rtmpdump: streamlink.set_option(\"rtmp-rtmpdump\", args.rtmpdump) if args.rtmp_proxy: streamlink.set_option(\"rtmp-proxy\", args.rtmp_proxy) #", "in plugin.arguments: if parg.options.get(\"help\") == argparse.SUPPRESS: continue value = getattr(args,", "plugin has a configuration error and the arguments cannot be", "break if streamlink and args.url: # Only load first available", "logger.root.isEnabledFor(logging.DEBUG): return sensitive = set() for pname, plugin in session.plugins.items():", "level=\"info\", json=False): global console if filename == \"-\": filename =", "pragma: no branch (option for option in action.option_strings if option.startswith(\"--\")),", "plugin config with ignored(NoPluginError): plugin = streamlink.resolve_url(args.url) for config_file in", "\" \"executable with --player.\") if args.player_fifo: try: namedpipe = NamedPipe()", "err: console.exit(f\"Failed to start player: {args.player} ({err})\") return False return", "title=formatter.title(args.title, defaults=DEFAULT_STREAM_METADATA) if args.title else args.url ) return out def", "not parg.is_global: if parg.required: required[parg.name] = parg # if the", "a given host and port. If host is empty, listen", "prebuffer, formatter) server.close(True) player.close() server.close() def output_stream_passthrough(stream, formatter: Formatter): \"\"\"Prepares", "not logger.root.isEnabledFor(logging.DEBUG): return sensitive = set() for pname, plugin in", "args.url ) try: log.info(f\"Starting player: {args.player}\") if player: player.open() except", "configs = [f\"@{config_file}\" for config_file in config_files or []] args,", "automatically closed by the player. if is_win32 and is_fifo: output.player.poll()", "with a '_alt' suffix and attempt # to use these", "arguments it can be one of these: - The stdout", "in required.values(): if not session.get_plugin_option(pname, req.dest): prompt = f\"{req.prompt or", "= args.output or args.stdout formatter = get_formatter(plugin) for stream_name in", "return stream is streams[n] and n is not name synonyms", "initial_streams, formatter: Formatter, external=False, port=0): \"\"\"Continuously output the stream over", "stderr if we are outputting # a stream to stdout.", "stream_fd.read(8192) except OSError as err: stream_fd.close() raise StreamError(f\"Failed to read", "valid one, otherwise output list of valid streams. \"\"\" try:", "def iter_http_requests(server, player): \"\"\"Repeatedly accept HTTP connections on a server.", "cannot be translated to a URL\") else: validstreams = format_valid_streams(plugin,", "streamlink.utils.named_pipe import NamedPipe from streamlink_cli.argparser import build_parser from streamlink_cli.compat import", "the manual at https://streamlink.github.io\" ) sys.exit(error_code) def parser_helper(): session =", "import closing from distutils.version import StrictVersion from functools import partial", "elif args.url: try: setup_options() handle_url() except KeyboardInterrupt: # Close output", "path to a player \" \"executable with --player.\") if args.player_fifo:", "chunk_size=8192): \"\"\"Reads data from stream and then writes it to", "args.output == \"-\" or args.record_and_pipe: console_out = sys.stderr else: console_out", "parg.is_global: if parg.required: required[parg.name] = parg # if the value", "= \", \".join(sorted(pluginlist)) if args.json: console.msg_json(pluginlist) else: console.msg(f\"Loaded plugins: {pluginlist_formatted}\")", "check for errors. # This is to avoid opening the", "{req.name}'}: \" session.set_plugin_option( pname, req.dest, console.askpass(prompt) if req.sensitive else console.ask(prompt)", "formatter: Formatter): \"\"\"Prepares a filename to be passed to the", "= get_formatter(plugin) for stream_name in [stream_name] + alt_streams: stream =", "is DeprecatedPath: log.info(f\"Loaded config from deprecated path, see CLI docs", "args.rtmpdump: streamlink.set_option(\"rtmp-rtmpdump\", args.rtmpdump) if args.rtmp_proxy: streamlink.set_option(\"rtmp-proxy\", args.rtmp_proxy) # deprecated if", "as err: stream_fd.close() raise StreamError(f\"Failed to read data from stream:", "bytes\") prebuffer = stream_fd.read(8192) except OSError as err: stream_fd.close() raise", "early as possible to load args from config files setup_config_args(parser,", "over HTTP - Output stream data to selected output \"\"\"", "except OSError: continue def output_stream_http(plugin, initial_streams, formatter: Formatter, external=False, port=0):", "def open_stream(stream): \"\"\"Opens a stream and reads 8192 bytes from", "use --force to overwrite it.\") sys.exit() return FileOutput(filename) def create_output(formatter:", ") elif args.stream_url: try: console.msg(stream.to_url()) except TypeError: console.exit(\"The stream specified", "plugin in session.plugins.items(): defaults = {} group = plugin_args.add_argument_group(pname.capitalize()) for", "or fetch_streams(plugin) initial_streams = None for stream_name in (resolve_stream_name(streams, s)", "= stream.cmdline() except StreamError as err: console.exit(err) console.msg(cmdline) else: console.exit(\"The", "f'Enter {pname} {req.name}'}: \" session.set_plugin_option( pname, req.dest, console.askpass(prompt) if req.sensitive", "if not prebuffer: stream_fd.close() raise StreamError(\"No data returned from stream\")", "output options.\") if args.output: if args.output == \"-\": out =", "else \"none\" logger.root.setLevel(log_level) setup_http_session() log_root_warning() log_current_versions() log_current_arguments(streamlink, parser) if args.version_check", "prefix=os.path.basename(output.record.filename) ) try: for data in stream_iterator: # We need", "streamlink_cli.output import FileOutput, Output, PlayerOutput from streamlink_cli.utils import Formatter, HTTPServer,", "ConsoleOutput, ConsoleUserInputRequester from streamlink_cli.constants import CONFIG_FILES, DEFAULT_STREAM_METADATA, LOG_DIR, PLUGIN_DIRS, STREAM_SYNONYMS", "a command\") # Print JSON representation of the stream elif", "log.info(\"Player closed\") break try: output.write(data) except OSError as err: if", "are outputting # a stream to stdout. if args.stdout or", "\"\"\"Reads data from stream and then writes it to the", "= sys.stdout # We don't want log output when we", "is up to date!\") if force: sys.exit() def setup_logger_and_console(stream=sys.stdout, filename=None,", "= \", \" validstreams = [] for name, stream in", "to allow case-insensitive lookup if args.stream: args.stream = [stream.lower() for", "{directory} does not exist or is not a directory!\") def", "({err})\") else: server = create_http_server(host=None, port=port) player = None log.info(\"Starting", "args.hds_live_edge) if args.hls_live_edge: streamlink.set_option(\"hls-live-edge\", args.hls_live_edge) if args.hls_playlist_reload_attempts: streamlink.set_option(\"hls-playlist-reload-attempts\", args.hls_playlist_reload_attempts) if", "stream # uses a subprocess. if args.subprocess_cmdline: if isinstance(stream, StreamProcess):", "cache.set(\"latest_version\", latest_version, (60 * 60 * 24)) version_info_printed = cache.get(\"version_info_printed\")", "elif args.stream_url: try: console.msg(streams[list(streams)[-1]].to_manifest_url()) except TypeError: console.exit(\"The stream specified cannot", "stream_type in args.player_passthrough and not file_output: log.info(f\"Opening stream: {stream_name} ({stream_type})\")", "config for config_file in filter(lambda path: path.is_file(), CONFIG_FILES): if type(config_file)", "log.info(\" \" + url) for req in iter_http_requests(server, player): user_agent", "import __version__ as websocket_version import streamlink.logger as logger from streamlink", "{output.filename} ({err})\") with closing(output): log.debug(\"Writing stream to output\") read_stream(stream_fd, output,", "is_player and output.namedpipe show_progress = ( isinstance(output, FileOutput) and output.fd", "required[parg.name] = parg # if the value is set, check", "opening the output. \"\"\" global stream_fd # Attempts to open", "in iter_http_requests(server, player): user_agent = req.headers.get(\"User-Agent\") or \"unknown player\" log.info(f\"Got", "sleep(interval) try: streams = fetch_streams(plugin) except FatalPluginError: raise except PluginError", "HTTP request from {user_agent}\") stream_fd = prebuffer = None while", "\"-\": out = FileOutput(fd=stdout) else: out = check_file_output(formatter.filename(args.output, args.fs_safe_rules), args.force)", "and port. If host is empty, listen on all available", "console.exit(f\"No plugin can handle URL: {args.url}\") except PluginError as err:", "log.info(f\"Loaded plugin config from deprecated path, see CLI docs for", "list(filter(lambda k: stream_name + \"_alt\" in k, sorted(streams.keys()))) file_output =", "plugin = streamlink.resolve_url(args.url) setup_plugin_options(streamlink, plugin) log.info(f\"Found matching plugin {plugin.module} for", "\"\"\"Outputs a list of all plugins Streamlink has loaded.\"\"\" pluginlist", "to load args from config files setup_config_args(parser, ignore_unknown=True) # Console", "plugin=plugin.module, metadata=plugin.get_metadata(), streams=streams ) elif args.stream_url: try: console.msg(streams[list(streams)[-1]].to_manifest_url()) except TypeError:", "# Close output if output: output.close() console.msg(\"Interrupted! Exiting...\") error_code =", "if success and type(directory) is DeprecatedPath: log.info(f\"Loaded plugins from deprecated", "access with one of:\") for url in server.urls: log.info(\" \"", "if filename == \"-\": filename = LOG_DIR / f\"{datetime.now()}.log\" elif", "({type(stream).shortname()})\") stream_fd, prebuffer = open_stream(stream) except StreamError as err: log.error(err)", "Output internal command-line - Output JSON represenation - Continuously output", "range(args.retry_open): try: stream_fd, prebuffer = open_stream(stream) success_open = True break", "args.ffmpeg_copyts: streamlink.set_option(\"ffmpeg-copyts\", args.ffmpeg_copyts) if args.ffmpeg_start_at_zero: streamlink.set_option(\"ffmpeg-start-at-zero\", args.ffmpeg_start_at_zero) streamlink.set_option(\"subprocess-errorlog\", args.subprocess_errorlog) streamlink.set_option(\"subprocess-errorlog-path\",", "args.stdout or args.output == \"-\" or args.record_and_pipe: console_out = sys.stderr", "the logging level if changed by a plugin specific config", "to resolve the URL to a plugin and then attempts", "config_file = config_file.with_name(f\"{config_file.name}.{plugin.module}\") if not config_file.is_file(): continue if type(config_file) is", "want the config specified last to get highest priority for", "last to get highest priority for config_file in map(lambda path:", "setup_plugin_args(streamlink, parser) # call setup args again once the plugin", "\"\"\"Creates the Streamlink session.\"\"\" global streamlink streamlink = Streamlink({\"user-input-requester\": ConsoleUserInputRequester(console)})", "args again once the plugin specific args have been added", "arguments it can be one of these: - Output internal", "(errno.EPIPE, errno.EINVAL, errno.ECONNRESET) try: ACCEPTABLE_ERRNO += (errno.WSAECONNABORTED,) except AttributeError: pass", "args.player_passthrough and not file_output: log.info(f\"Opening stream: {stream_name} ({stream_type})\") success =", "OSError: continue def output_stream_http(plugin, initial_streams, formatter: Formatter, external=False, port=0): \"\"\"Continuously", "not open stream {stream}, tried {args.retry_open} times, exiting\") output =", "stream_fd and (not player or player.running): try: streams = initial_streams", "plugin=plugin.module, metadata=plugin.get_metadata(), streams=streams, error=err ) else: console.exit(f\"{err}.\\n Available streams: {validstreams}\")", "if args.hds_segment_attempts: streamlink.set_option(\"hds-segment-attempts\", args.hds_segment_attempts) if args.hds_segment_threads: streamlink.set_option(\"hds-segment-threads\", args.hds_segment_threads) if args.hds_segment_timeout:", "= ConsoleOutput(streamhandler.stream, json) def main(): error_code = 0 parser =", "streamlink.set_option(\"rtmp-rtmpdump\", args.rtmp_rtmpdump) elif args.rtmpdump: streamlink.set_option(\"rtmp-rtmpdump\", args.rtmpdump) if args.rtmp_proxy: streamlink.set_option(\"rtmp-proxy\", args.rtmp_proxy)", "args.player, args=args.player_args, filename=filename, call=True, quiet=not args.verbose_player, title=formatter.title(args.title, defaults=DEFAULT_STREAM_METADATA) if args.title", "arglist = sys.argv[1:] # Load arguments from config files configs", "setup_plugin_args(session, parser): \"\"\"Sets Streamlink plugin options.\"\"\" plugin_args = parser.add_argument_group(\"Plugin options\")", "plugin.arguments: if parg.options.get(\"help\") == argparse.SUPPRESS: continue value = getattr(args, parg.dest", "deprecated stream-type arguments if args.stream_segment_attempts: streamlink.set_option(\"stream-segment-attempts\", args.stream_segment_attempts) if args.stream_segment_threads: streamlink.set_option(\"stream-segment-threads\",", "answer.lower() != \"y\": sys.exit() else: log.error(f\"File {filename} already exists, use", "available!\") cache.set(\"version_info_printed\", True, (60 * 60 * 6)) elif force:", "\" session.set_plugin_option( pname, req.dest, console.askpass(prompt) if req.sensitive else console.ask(prompt) )", "value = getattr(args, parg.dest if parg.is_global else parg.namespace_dest(pname)) session.set_plugin_option(pname, parg.dest,", "return output_stream_http(plugin, streams, formatter) else: log.info(f\"Opening stream: {stream_name} ({stream_type})\") success", "= 130 elif args.help: parser.print_help() else: usage = parser.format_usage() console.msg(", "PluginError as err: log.error(err) if count > 0: attempts +=", "= check_file_output(formatter.filename(args.record, args.fs_safe_rules), args.force) log.info(f\"Starting player: {args.player}\") out = PlayerOutput(", "as proxy and headers.\"\"\" if args.http_proxy: streamlink.set_option(\"http-proxy\", args.http_proxy) if args.https_proxy:", "if not parg.is_global: if parg.required: required[parg.name] = parg # if", "set up as early as possible to load args from", "from streamlink.utils.named_pipe import NamedPipe from streamlink_cli.argparser import build_parser from streamlink_cli.compat", "List import requests from socks import __version__ as socks_version from", "is_fifo: output.player.poll() if output.player.returncode is not None: log.info(\"Player closed\") break", "args.stream = [stream.lower() for stream in args.stream] if not args.url", "10 sec\") sleep(10) continue except PluginError as err: log.error(f\"Unable to", "args.ffmpeg_start_at_zero) streamlink.set_option(\"subprocess-errorlog\", args.subprocess_errorlog) streamlink.set_option(\"subprocess-errorlog-path\", args.subprocess_errorlog_path) streamlink.set_option(\"locale\", args.locale) def setup_plugin_args(session, parser):", "err: console.exit(err) console.msg(cmdline) else: console.exit(\"The stream specified cannot be translated", "not ignore_unknown: msg = gettext(\"unrecognized arguments: %s\") parser.error(msg % \"", "= [] if args.config: # We want the config specified", "= fetch_streams(plugin) except NoPluginError: console.exit(f\"No plugin can handle URL: {args.url}\")", "fetch new streams: {err}\") continue try: log.info(f\"Opening stream: {stream_name} ({type(stream).shortname()})\")", "err: log.error(f\"Unable to fetch new streams: {err}\") continue try: log.info(f\"Opening", "({err})\") with closing(output): log.debug(\"Writing stream to output\") read_stream(stream_fd, output, prebuffer,", "for name, stream in sorted(streams.items(), key=lambda stream: plugin.stream_weight(stream[0])): if name", "error_code = 0 parser = build_parser() setup_args(parser, ignore_unknown=True) # call", "\"plugins\", []) plugins.append(pname) setattr(action, \"plugins\", plugins) plugin.options = PluginOptions(defaults) def", "times, exiting\") output = create_output(formatter) try: output.open() except OSError as", "to a URL\") # Output the stream else: # Find", "externally, or while a player is running if it is", "os_version = f\"{platform.system()} {platform.release()}\" # Linux / other else: os_version", "in streams: stream = streams[stream_name] break else: log.info(\"Stream not available,", "cannot be translated to a URL\") # Output the stream", "a list of available streams. Proceeds to handle stream if", "for attr in QUIET_OPTIONS) log_level = args.loglevel if not silent_log", "if stream_name in STREAM_SYNONYMS and stream_name in streams: for name,", "sys.exit(error_code) def parser_helper(): session = Streamlink() parser = build_parser() setup_plugin_args(session,", "def format_valid_streams(plugin, streams): \"\"\"Formats a dict of streams. Filters out", "or args.retry_streams: retry_streams = 1 retry_max = 0 if args.retry_streams:", "logging.getLogger(\"streamlink.cli\") def get_formatter(plugin: Plugin): return Formatter( { \"url\": lambda: args.url,", "\"_alt\" in k, sorted(streams.keys()))) file_output = args.output or args.stdout formatter", "migrate: {directory}\") elif showwarning: log.warning(f\"Plugin path {directory} does not exist", "for pname, plugin in session.plugins.items(): defaults = {} group =", "if is_player and err.errno in ACCEPTABLE_ERRNO: log.info(\"Player closed\") elif is_http", "if args.https_proxy: streamlink.set_option(\"https-proxy\", args.https_proxy) if args.http_cookie: streamlink.set_option(\"http-cookies\", dict(args.http_cookie)) if args.http_header:", "if pargdest != action.dest: continue defaults[pargdest] = action.default # add", "ConsoleUserInputRequester from streamlink_cli.constants import CONFIG_FILES, DEFAULT_STREAM_METADATA, LOG_DIR, PLUGIN_DIRS, STREAM_SYNONYMS from", "and not args.json: args.stream = args.default_stream if args.stream: validstreams =", "PlayerOutput( args.player, args=args.player_args, quiet=not args.verbose_player, kill=not args.player_no_close, namedpipe=namedpipe, http=http, record=record,", "the stream over HTTP - Output stream data to selected", "args.hls_duration: streamlink.set_option(\"hls-duration\", args.hls_duration) if args.hls_live_restart: streamlink.set_option(\"hls-live-restart\", args.hls_live_restart) if args.rtmp_rtmpdump: streamlink.set_option(\"rtmp-rtmpdump\",", "action.option_strings if option.startswith(\"--\")), action.option_strings[0] ) if action.option_strings else action.dest log.debug(f\"", "args.hds_timeout: streamlink.set_option(\"hds-timeout\", args.hds_timeout) if args.hls_segment_attempts: streamlink.set_option(\"hls-segment-attempts\", args.hls_segment_attempts) if args.hls_segment_threads: streamlink.set_option(\"hls-segment-threads\",", "import errno import logging import os import platform import signal", "= create_http_server(host=None, port=port) player = None log.info(\"Starting server, access with", "if not success_open: console.exit(f\"Could not open stream {stream}, tried {args.retry_open}", "if args.stream: validstreams = format_valid_streams(plugin, streams) for stream_name in args.stream:", "130 elif args.help: parser.print_help() else: usage = parser.format_usage() console.msg( f\"{usage}\\n\"", "args.hls_segment_attempts: streamlink.set_option(\"hls-segment-attempts\", args.hls_segment_attempts) if args.hls_segment_threads: streamlink.set_option(\"hls-segment-threads\", args.hls_segment_threads) if args.hls_segment_timeout: streamlink.set_option(\"hls-segment-timeout\",", "for rparg in plugin.arguments.requires(parg.name): required[rparg.name] = rparg except RuntimeError: log.error(f\"{pname}", "as err: raise StreamError(f\"Could not open stream: {err}\") # Read", "writes it to the output.\"\"\" is_player = isinstance(output, PlayerOutput) is_http", "streamlink.set_option(\"locale\", args.locale) def setup_plugin_args(session, parser): \"\"\"Sets Streamlink plugin options.\"\"\" plugin_args", "continue value = getattr(args, parg.dest if parg.is_global else parg.namespace_dest(pname)) session.set_plugin_option(pname,", "functools import partial from gettext import gettext from itertools import", "not be found\" if args.json: console.msg_json( plugin=plugin.module, metadata=plugin.get_metadata(), streams=streams, error=err", "load args from config files setup_config_args(parser, ignore_unknown=True) # Console output", "any additional plugins.\"\"\" load_plugins(PLUGIN_DIRS, showwarning=False) if extra_plugin_dir: load_plugins([Path(path).expanduser() for path", "closing(output): log.debug(\"Writing stream to output\") read_stream(stream_fd, output, prebuffer, formatter) return", "port=port) player = None log.info(\"Starting server, access with one of:\")", "args.hls_playlist_reload_attempts) if args.hls_playlist_reload_time: streamlink.set_option(\"hls-playlist-reload-time\", args.hls_playlist_reload_time) if args.hls_segment_ignore_names: streamlink.set_option(\"hls-segment-ignore-names\", args.hls_segment_ignore_names) if", "config_file in filter(lambda path: path.is_file(), CONFIG_FILES): if type(config_file) is DeprecatedPath:", "synonym.\"\"\" if stream_name in STREAM_SYNONYMS and stream_name in streams: for", "\"y\": sys.exit() else: log.error(f\"File {filename} already exists, use --force to", "dict(args.http_cookie)) if args.http_header: streamlink.set_option(\"http-headers\", dict(args.http_header)) if args.http_query_param: streamlink.set_option(\"http-query-params\", dict(args.http_query_param)) if", "required.values(): if not session.get_plugin_option(pname, req.dest): prompt = f\"{req.prompt or f'Enter", "as err: log.error(err) if stream_fd and prebuffer: log.debug(\"Writing stream to", "n is not name synonyms = list(filter(synonymfilter, streams.keys())) if len(synonyms)", "else: console.exit(f\"{err}.\\n Available streams: {validstreams}\") elif args.json: console.msg_json( plugin=plugin.module, metadata=plugin.get_metadata(),", "res = requests.get(\"https://pypi.python.org/pypi/streamlink/json\") data = res.json() latest_version = data.get(\"info\").get(\"version\") cache.set(\"latest_version\",", "additional plugins setup_plugins(args.plugin_dirs) setup_plugin_args(streamlink, parser) # call setup args again", "streams = fetch_streams_with_retry(plugin, retry_streams, retry_max) else: streams = fetch_streams(plugin) except", "try: output.open() except OSError as err: if isinstance(output, PlayerOutput): console.exit(f\"Failed", "output.record.fd is not stdout and (sys.stdout.isatty() or args.force_progress) ) stream_iterator", "handle URL: {args.url}\") except PluginError as err: console.exit(err) if not", "create_http_server() player = output = PlayerOutput( args.player, args=args.player_args, filename=server.url, quiet=not", "__version__ as streamlink_version from streamlink.cache import Cache from streamlink.exceptions import", "finally write the stream to output.\"\"\" global output success_open =", "subprocess' stdin pipe - A named pipe that the subprocess", "data to selected output \"\"\" stream_name = resolve_stream_name(streams, stream_name) stream", "in parser._actions: # find matching global argument if pargdest !=", "log.debug(\"Checking file output\") if os.path.isfile(filename) and not force: if sys.stdin.isatty():", "stream_fd, prebuffer = open_stream(stream) except StreamError as err: log.error(err) if", "for streams, retrying every {interval} second(s)\") attempts = 0 while", "parg # if the value is set, check to see", "{platform.python_version()}\") log.debug(f\"Streamlink: {streamlink_version}\") log.debug(f\"Requests({requests.__version__}), \" f\"Socks({socks_version}), \" f\"Websocket({websocket_version})\") def log_current_arguments(session,", "import ConsoleOutput, ConsoleUserInputRequester from streamlink_cli.constants import CONFIG_FILES, DEFAULT_STREAM_METADATA, LOG_DIR, PLUGIN_DIRS,", "streams def resolve_stream_name(streams, stream_name): \"\"\"Returns the real stream name of", "for parg in plugin.arguments: if parg.sensitive: sensitive.add(parg.argument_name(pname)) log.debug(\"Arguments:\") for action", "outputting # a stream to stdout. if args.stdout or args.output", "while not streams: sleep(interval) try: streams = fetch_streams(plugin) except FatalPluginError:", "return Formatter( { \"url\": lambda: args.url, \"author\": lambda: plugin.get_author(), \"category\":", "streamlink.set_option(\"hls-segment-timeout\", args.hls_segment_timeout) if args.hls_timeout: streamlink.set_option(\"hls-timeout\", args.hls_timeout) if args.http_stream_timeout: streamlink.set_option(\"http-stream-timeout\", args.http_stream_timeout)", "of a synonym.\"\"\" if stream_name in STREAM_SYNONYMS and stream_name in", "DEFAULT_STREAM_METADATA, LOG_DIR, PLUGIN_DIRS, STREAM_SYNONYMS from streamlink_cli.output import FileOutput, Output, PlayerOutput", "console.exit(f\"Failed to start player: {args.player} ({err})\") else: console.exit(f\"Failed to open", "new version of Streamlink ({latest_version}) is available!\") cache.set(\"version_info_printed\", True, (60", "force: log.info(f\"Your Streamlink version ({installed_version}) is up to date!\") if", "args.interface) if args.ipv4: streamlink.set_option(\"ipv4\", args.ipv4) if args.ipv6: streamlink.set_option(\"ipv6\", args.ipv6) if", "console.exit(f\"{err}.\\n Available streams: {validstreams}\") elif args.json: console.msg_json( plugin=plugin.module, metadata=plugin.get_metadata(), streams=streams", "stream_fd.close() except KeyboardInterrupt: error_code = 130 elif args.help: parser.print_help() else:", "except PluginError as err: log.error(f\"Unable to fetch new streams: {err}\")", "to their quality (based on plugin.stream_weight). \"\"\" delimiter = \",", "from streamlink.plugin import Plugin, PluginOptions from streamlink.stream import StreamIO, StreamProcess", "streams): \"\"\"Formats a dict of streams. Filters out synonyms and", "showwarning: bool = True): \"\"\"Attempts to load plugins from a", "for stream in args.stream] if not args.url and args.url_param: args.url", "= StrictVersion(latest_version) if latest_version > installed_version: log.info(f\"A new version of", "displays them next to the stream they point to. Streams", "configuration error and the arguments cannot be parsed\") break if", "Formatter): \"\"\"Prepares a filename to be passed to the player.\"\"\"", "player is running if it is not empty. \"\"\" while", "the player. if is_win32 and is_fifo: output.player.poll() if output.player.returncode is", "err: raise StreamError(f\"Could not open stream: {err}\") # Read 8192", "type(config_file) is DeprecatedPath: log.info(f\"Loaded plugin config from deprecated path, see", "dirs: if directory.is_dir(): success = streamlink.load_plugins(str(directory)) if success and type(directory)", "args.http_header: streamlink.set_option(\"http-headers\", dict(args.http_header)) if args.http_query_param: streamlink.set_option(\"http-query-params\", dict(args.http_query_param)) if args.http_ignore_env: streamlink.set_option(\"http-trust-env\",", "type(directory) is DeprecatedPath: log.info(f\"Loaded plugins from deprecated path, see CLI", "named pipe is not # automatically closed by the player.", "pname, plugin in session.plugins.items(): for parg in plugin.arguments: if parg.sensitive:", "as err: console.exit(f\"Failed to create HTTP server: {err}\") return http", "global output if not external: if not args.player: console.exit(\"The default", "as err: log.error(f\"Try {i + 1}/{args.retry_open}: Could not open stream", "try: log.info(f\"Starting player: {args.player}\") if player: player.open() except OSError as", "+ \"_alt\" in k, sorted(streams.keys()))) file_output = args.output or args.stdout", "if args.hls_segment_key_uri: streamlink.set_option(\"hls-segment-key-uri\", args.hls_segment_key_uri) if args.hls_audio_select: streamlink.set_option(\"hls-audio-select\", args.hls_audio_select) if args.hls_start_offset:", "session.plugins.items(): for parg in plugin.arguments: if parg.sensitive: sensitive.add(parg.argument_name(pname)) log.debug(\"Arguments:\") for", "try: stream_fd, prebuffer = open_stream(stream) success_open = True break except", "directory!\") def setup_args(parser: argparse.ArgumentParser, config_files: List[Path] = None, ignore_unknown: bool", "http=http, record=record, title=formatter.title(args.title, defaults=DEFAULT_STREAM_METADATA) if args.title else args.url ) return", "as err: log.error(err) streams = None if not streams: log.info(f\"Waiting", "on all available interfaces, and if port is 0, listen", "streamlink.set_option(\"mux-subtitles\", args.mux_subtitles) if args.hds_live_edge: streamlink.set_option(\"hds-live-edge\", args.hds_live_edge) if args.hls_live_edge: streamlink.set_option(\"hls-live-edge\", args.hls_live_edge)", "import NamedPipe from streamlink_cli.argparser import build_parser from streamlink_cli.compat import DeprecatedPath,", "if not logger.root.isEnabledFor(logging.DEBUG): return sensitive = set() for pname, plugin", "specified cannot be translated to a URL\") else: validstreams =", "load_plugins([Path(path).expanduser() for path in extra_plugin_dir]) def setup_streamlink(): \"\"\"Creates the Streamlink", "sys.stderr else: console_out = sys.stdout # We don't want log", "group = plugin_args.add_argument_group(pname.capitalize()) for parg in plugin.arguments: if not parg.is_global:", "deprecated path, see CLI docs for how to migrate: {config_file}\")", "break return streams def resolve_stream_name(streams, stream_name): \"\"\"Returns the real stream", "{ \"time\": lambda dt, fmt: dt.strftime(fmt) } ) def check_file_output(filename,", "FatalPluginError from streamlink.plugin import Plugin, PluginOptions from streamlink.stream import StreamIO,", "player \" \"executable with --player.\") if args.player_fifo: try: namedpipe =", "args.ffmpeg_verbose: streamlink.set_option(\"ffmpeg-verbose\", args.ffmpeg_verbose) if args.ffmpeg_verbose_path: streamlink.set_option(\"ffmpeg-verbose-path\", args.ffmpeg_verbose_path) if args.ffmpeg_fout: streamlink.set_option(\"ffmpeg-fout\",", "global args arglist = sys.argv[1:] # Load arguments from config", "import Path from time import sleep from typing import List", "pass # Not windows QUIET_OPTIONS = (\"json\", \"stream_url\", \"subprocess_cmdline\", \"quiet\")", "Streamlink plugin options.\"\"\" pname = plugin.module required = OrderedDict({}) for", "plugin config from deprecated path, see CLI docs for how", "the real stream name of a synonym.\"\"\" if stream_name in", "stream = streams[stream_name] # Print internal command-line if this stream", "streams = fetch_streams(plugin) except NoPluginError: console.exit(f\"No plugin can handle URL:", "False for i in range(args.retry_open): try: stream_fd, prebuffer = open_stream(stream)", "parser._actions: # find matching global argument if pargdest != action.dest:", "[stream.lower() for stream in args.stream] if not args.url and args.url_param:", "for url in server.urls: log.info(\" \" + url) for req", "NoPluginError: console.exit(f\"No plugin can handle URL: {args.url}\") except PluginError as", "for config_file in config_files or []] args, unknown = parser.parse_known_args(configs", "plugin.get_author(), \"category\": lambda: plugin.get_category(), \"game\": lambda: plugin.get_category(), \"title\": lambda: plugin.get_title(),", "args.http_timeout: streamlink.set_option(\"http-timeout\", args.http_timeout) def setup_plugins(extra_plugin_dir=None): \"\"\"Loads any additional plugins.\"\"\" load_plugins(PLUGIN_DIRS,", "(args.record or args.record_and_pipe): console.exit(\"Cannot use record options with other file", "quiet=not args.verbose_player, kill=not args.player_no_close, namedpipe=namedpipe, http=http, record=record, title=formatter.title(args.title, defaults=DEFAULT_STREAM_METADATA) if", "from stream: {err}\") if not prebuffer: stream_fd.close() raise StreamError(\"No data", "host and port. If host is empty, listen on all", "player: {args.player} ({err})\") else: console.exit(f\"Failed to open output: {output.filename} ({err})\")", "or value: try: for rparg in plugin.arguments.requires(parg.name): required[rparg.name] = rparg", "= None output: Output = None plugin: Plugin = None", "if force or not latest_version: res = requests.get(\"https://pypi.python.org/pypi/streamlink/json\") data =", "output: output.close() console.msg(\"Interrupted! Exiting...\") error_code = 130 finally: if stream_fd:", "+ alt_streams: stream = streams[stream_name] stream_type = type(stream).shortname() if stream_type", "+ 1}/{args.retry_open}: Could not open stream {stream} ({err})\") if not", "create_http_server(host=None, port=port) player = None log.info(\"Starting server, access with one", "exists when # using named pipes on Windows since the", "log_level != \"none\" else None setup_logger_and_console(console_out, log_file, log_level, args.json) setup_signals()", "the global HTTP settings, such as proxy and headers.\"\"\" if", "console.msg_json( plugin=plugin.module, metadata=plugin.get_metadata(), streams=streams, error=err ) else: console.exit(f\"{err}.\\n Available streams:", ") elif args.stream_url: try: console.msg(streams[list(streams)[-1]].to_manifest_url()) except TypeError: console.exit(\"The stream specified", "add plugin to global argument plugins = getattr(action, \"plugins\", [])", "open the stream try: stream_fd = stream.open() except StreamError as", "# Handle SIGTERM just like SIGINT signal.signal(signal.SIGTERM, signal.default_int_handler) def setup_http_session():", "to open output: {output.filename} ({err})\") with closing(output): log.debug(\"Writing stream to", "pname, req.dest, console.askpass(prompt) if req.sensitive else console.ask(prompt) ) def log_root_warning():", "on stderr if we are outputting # a stream to", "error_code = 130 elif args.help: parser.print_help() else: usage = parser.format_usage()", "\"\"\"Formats a dict of streams. Filters out synonyms and displays", "if args.http_disable_dh: streamlink.set_option(\"http-disable-dh\", True) if args.http_ssl_cert: streamlink.set_option(\"http-ssl-cert\", args.http_ssl_cert) if args.http_ssl_cert_crt_key:", "specified stream(s) '{', '.join(args.stream)}' could not be found\" if args.json:", "= logger.basicConfig( stream=stream, filename=filename, level=level, style=\"{\", format=(\"[{asctime}]\" if level ==", "the user if it should be overwritten if it does.\"\"\"", "streamlink.resolve_url(args.url) for config_file in CONFIG_FILES: config_file = config_file.with_name(f\"{config_file.name}.{plugin.module}\") if not", "\"\"\"Checks if file already exists and ask the user if", "not # automatically closed by the player. if is_win32 and", "elif sys.platform == \"win32\": os_version = f\"{platform.system()} {platform.release()}\" # Linux", "if args.output: if args.output == \"-\": out = FileOutput(fd=stdout) else:", "to start player: {args.player} ({err})\") else: console.exit(f\"Failed to open output:", "sys.argv[1:] # Load arguments from config files configs = [f\"@{config_file}\"", "streamlink.set_option(\"ffmpeg-verbose-path\", args.ffmpeg_verbose_path) if args.ffmpeg_fout: streamlink.set_option(\"ffmpeg-fout\", args.ffmpeg_fout) if args.ffmpeg_video_transcode: streamlink.set_option(\"ffmpeg-video-transcode\", args.ffmpeg_video_transcode)", "= f\"{platform.system()} {platform.release()}\" # Linux / other else: os_version =", "PluginOptions from streamlink.stream import StreamIO, StreamProcess from streamlink.utils.named_pipe import NamedPipe", "QUIET_OPTIONS) log_level = args.loglevel if not silent_log else \"none\" log_file", "cache.get(\"version_info_printed\") if not force and version_info_printed: return installed_version = StrictVersion(streamlink.version)", "config_files = [] if args.config: # We want the config", "if args.plugins: print_plugins() elif args.can_handle_url: try: streamlink.resolve_url(args.can_handle_url) except NoPluginError: error_code", "console.msg(f\"Available streams: {validstreams}\") def print_plugins(): \"\"\"Outputs a list of all", "\"\"\"Attempts to fetch streams repeatedly until some are returned or", "this URL: {args.url}\") if args.default_stream and not args.stream and not", "output the stream over HTTP.\"\"\" global output if not external:", "if parg.options.get(\"help\") == argparse.SUPPRESS: continue value = getattr(args, parg.dest if", "plugin specific config log_level = args.loglevel if not silent_log else", "log.debug(f\"Streamlink: {streamlink_version}\") log.debug(f\"Requests({requests.__version__}), \" f\"Socks({socks_version}), \" f\"Websocket({websocket_version})\") def log_current_arguments(session, parser):", "= sys.stderr else: console_out = sys.stdout # We don't want", "stream_name in (resolve_stream_name(streams, s) for s in args.stream): if stream_name", "streams found on this URL: {args.url}\") if args.default_stream and not", "a URL\") else: validstreams = format_valid_streams(plugin, streams) console.msg(f\"Available streams: {validstreams}\")", "stream_fd # Attempts to open the stream try: stream_fd =", "version_info_printed: return installed_version = StrictVersion(streamlink.version) latest_version = StrictVersion(latest_version) if latest_version", "open stream...\") stream_fd.close() except KeyboardInterrupt: error_code = 130 elif args.help:", "# automatically closed by the player. if is_win32 and is_fifo:", "validstreams = format_valid_streams(plugin, streams) console.msg(f\"Available streams: {validstreams}\") def print_plugins(): \"\"\"Outputs", "as err: console.exit(f\"Failed to start player: {args.player} ({err})\") else: server", "else: log.info(f\"Opening stream: {stream_name} ({stream_type})\") success = output_stream(stream, formatter) if", "answer = console.ask(f\"File {filename} already exists! Overwrite it? [y/N] \")", "args.http_timeout) def setup_plugins(extra_plugin_dir=None): \"\"\"Loads any additional plugins.\"\"\" load_plugins(PLUGIN_DIRS, showwarning=False) if", "args.ringbuffer_size: streamlink.set_option(\"ringbuffer-size\", args.ringbuffer_size) if args.mux_subtitles: streamlink.set_option(\"mux-subtitles\", args.mux_subtitles) if args.hds_live_edge: streamlink.set_option(\"hds-live-edge\",", "if stream_name in streams: stream = streams[stream_name] break else: log.info(\"Stream", "if count > 0: attempts += 1 if attempts >=", "args.hds_segment_attempts: streamlink.set_option(\"hds-segment-attempts\", args.hds_segment_attempts) if args.hds_segment_threads: streamlink.set_option(\"hds-segment-threads\", args.hds_segment_threads) if args.hds_segment_timeout: streamlink.set_option(\"hds-segment-timeout\",", "\"url\": lambda: args.url, \"author\": lambda: plugin.get_author(), \"category\": lambda: plugin.get_category(), \"game\":", "port. If host is empty, listen on all available interfaces,", "args.rtmp_timeout) # generic stream- arguments take precedence over deprecated stream-type", "out = FileOutput(fd=stdout) elif args.record_and_pipe: record = check_file_output(formatter.filename(args.record_and_pipe, args.fs_safe_rules), args.force)", "chain from pathlib import Path from time import sleep from", "start player: {args.player} ({err})\") else: server = create_http_server(host=None, port=port) player", "exiting\") break except OSError as err: console.exit(f\"Error when reading from", "and reads 8192 bytes from it. This is useful to", "streamlink.set_option(\"interface\", args.interface) if args.ipv4: streamlink.set_option(\"ipv4\", args.ipv4) if args.ipv6: streamlink.set_option(\"ipv6\", args.ipv6)", "60 * 6)) elif force: log.info(f\"Your Streamlink version ({installed_version}) is", "should be on stderr if we are outputting # a", "if hasattr(os, \"getuid\"): if os.geteuid() == 0: log.info(\"streamlink is running", "server = create_http_server(host=None, port=port) player = None log.info(\"Starting server, access", "import OrderedDict from contextlib import closing from distutils.version import StrictVersion", "stream_name in streams: stream = streams[stream_name] break else: log.info(\"Stream not", "output the stream over HTTP - Output stream data to", "OSError as err: console.exit(f\"Failed to start player: {args.player} ({err})\") return", "out def create_http_server(*_args, **_kwargs): \"\"\"Creates a HTTP server listening on", "False return True def open_stream(stream): \"\"\"Opens a stream and reads", "one of these: - Output internal command-line - Output JSON", "log = logging.getLogger(\"streamlink.cli\") def get_formatter(plugin: Plugin): return Formatter( { \"url\":", "as err: console.exit(err) if not streams: console.exit(f\"No playable streams found", "try: for rparg in plugin.arguments.requires(parg.name): required[rparg.name] = rparg except RuntimeError:", "config_file.is_file(): continue if type(config_file) is DeprecatedPath: log.info(f\"Loaded plugin config from", "streamlink.set_option(\"http-ssl-verify\", False) if args.http_disable_dh: streamlink.set_option(\"http-disable-dh\", True) if args.http_ssl_cert: streamlink.set_option(\"http-ssl-cert\", args.http_ssl_cert)", "parser.error(msg % \" \".join(unknown)) # Force lowercase to allow case-insensitive", "PlayerOutput): console.exit(f\"Failed to start player: {args.player} ({err})\") else: console.exit(f\"Failed to", "to a plugin and then attempts to fetch a list", "priority for config_file in map(lambda path: Path(path).expanduser(), reversed(args.config)): if config_file.is_file():", "0 parser = build_parser() setup_args(parser, ignore_unknown=True) # call argument set", "try: namedpipe = NamedPipe() except OSError as err: console.exit(f\"Failed to", "TypeError: console.exit(\"The stream specified cannot be translated to a URL\")", "closing from distutils.version import StrictVersion from functools import partial from", "{stream_name} ({stream_type})\") success = output_stream(stream, formatter) if success: break def", "streams: log.info(f\"Waiting for streams, retrying every {interval} second(s)\") attempts =", "if len(synonyms) > 0: joined = delimiter.join(synonyms) name = f\"{name}", "streamlink.set_option(\"hds-timeout\", args.hds_timeout) if args.hls_segment_attempts: streamlink.set_option(\"hls-segment-attempts\", args.hls_segment_attempts) if args.hls_segment_threads: streamlink.set_option(\"hls-segment-threads\", args.hls_segment_threads)", "plugin in session.plugins.items(): for parg in plugin.arguments: if parg.sensitive: sensitive.add(parg.argument_name(pname))", "as early as possible to load args from config files", "log.info(\"Starting server, access with one of:\") for url in server.urls:", "'*' * 8}\") def check_version(force=False): cache = Cache(filename=\"cli.json\") latest_version =", "False) if args.http_no_ssl_verify: streamlink.set_option(\"http-ssl-verify\", False) if args.http_disable_dh: streamlink.set_option(\"http-disable-dh\", True) if", "# Find any streams with a '_alt' suffix and attempt", "log_root_warning() log_current_versions() log_current_arguments(streamlink, parser) if args.version_check or args.auto_version_check: with ignored(Exception):", "1 retry_max = 0 if args.retry_streams: retry_streams = args.retry_streams if", "streamlink.set_option(\"stream-segment-threads\", args.stream_segment_threads) if args.stream_segment_timeout: streamlink.set_option(\"stream-segment-timeout\", args.stream_segment_timeout) if args.stream_timeout: streamlink.set_option(\"stream-timeout\", args.stream_timeout)", "= False for i in range(args.retry_open): try: stream_fd, prebuffer =", "found on this URL: {args.url}\") if args.default_stream and not args.stream", "console.msg_json( plugin=plugin.module, metadata=plugin.get_metadata(), streams=streams ) elif args.stream_url: try: console.msg(streams[list(streams)[-1]].to_manifest_url()) except", "http def iter_http_requests(server, player): \"\"\"Repeatedly accept HTTP connections on a", "log.info(f\"Opening stream: {stream_name} ({stream_type})\") success = output_stream(stream, formatter) if success:", "stream_name in [stream_name] + alt_streams: stream = streams[stream_name] stream_type =", "socks import __version__ as socks_version from websocket import __version__ as", "global output success_open = False for i in range(args.retry_open): try:", "\"\"\"Opens a stream and reads 8192 bytes from it. This", "= Streamlink({\"user-input-requester\": ConsoleUserInputRequester(console)}) def setup_options(): \"\"\"Sets Streamlink options.\"\"\" if args.interface:", "available streams. Proceeds to handle stream if user specified a", "with ignored(Exception): check_version(force=args.version_check) if args.plugins: print_plugins() elif args.can_handle_url: try: streamlink.resolve_url(args.can_handle_url)", "console.exit(\"The default player (VLC) does not seem to be \"", "Formatter, HTTPServer, datetime, ignored, progress, stream_to_url ACCEPTABLE_ERRNO = (errno.EPIPE, errno.EINVAL,", "start player: {args.player} ({err})\") else: console.exit(f\"Failed to open output: {output.filename}", "f\"{req.prompt or f'Enter {pname} {req.name}'}: \" session.set_plugin_option( pname, req.dest, console.askpass(prompt)", "one of these: - The stdout pipe - A subprocess'", "streamlink.set_option(\"http-headers\", dict(args.http_header)) if args.http_query_param: streamlink.set_option(\"http-query-params\", dict(args.http_query_param)) if args.http_ignore_env: streamlink.set_option(\"http-trust-env\", False)", "user if it should be overwritten if it does.\"\"\" log.debug(\"Checking", "args.auto_version_check: with ignored(Exception): check_version(force=args.version_check) if args.plugins: print_plugins() elif args.can_handle_url: try:", "retry_max = args.retry_max streams = fetch_streams_with_retry(plugin, retry_streams, retry_max) else: streams", "= PluginOptions(defaults) def setup_plugin_options(session, plugin): \"\"\"Sets Streamlink plugin options.\"\"\" pname", "setup_config_args(parser, ignore_unknown=True) # Console output should be on stderr if", "count > 0: attempts += 1 if attempts >= count:", "This is to avoid opening the output unnecessarily. try: log.debug(\"Pre-buffering", "streamlink.stream import StreamIO, StreamProcess from streamlink.utils.named_pipe import NamedPipe from streamlink_cli.argparser", "and stream_name in streams: for name, stream in streams.items(): if", ") if action.option_strings else action.dest log.debug(f\" {name}={value if name not", "parg.namespace_dest(pname)) session.set_plugin_option(pname, parg.dest, value) if not parg.is_global: if parg.required: required[parg.name]", "stream_iterator: # We need to check if the player process", "rparg in plugin.arguments.requires(parg.name): required[rparg.name] = rparg except RuntimeError: log.error(f\"{pname} plugin", "# update the logging level if changed by a plugin", "it? [y/N] \") if answer.lower() != \"y\": sys.exit() else: log.error(f\"File", "stream_fd = prebuffer = None while not stream_fd and (not", "not stdout and (sys.stdout.isatty() or args.force_progress) ) stream_iterator = chain(", "streams.items(): if stream is streams[stream_name] and name not in STREAM_SYNONYMS:", "\"category\": lambda: plugin.get_category(), \"game\": lambda: plugin.get_category(), \"title\": lambda: plugin.get_title(), \"time\":", "migrate: {config_file}\") config_files.append(config_file) break if config_files: setup_args(parser, config_files, ignore_unknown=ignore_unknown) def", "formatter: Formatter, chunk_size=8192): \"\"\"Reads data from stream and then writes", "hasattr(output, \"record\") and isinstance(output.record, FileOutput) and output.record.fd is not stdout", "0: joined = delimiter.join(synonyms) name = f\"{name} ({joined})\" validstreams.append(name) return", "except KeyboardInterrupt: error_code = 130 elif args.help: parser.print_help() else: usage", "success = output_stream_passthrough(stream, formatter) elif args.player_external_http: return output_stream_http(plugin, streams, formatter,", "= None while not stream_fd and (not player or player.running):", "args.stream_segment_timeout) if args.stream_timeout: streamlink.set_option(\"stream-timeout\", args.stream_timeout) if args.ffmpeg_ffmpeg: streamlink.set_option(\"ffmpeg-ffmpeg\", args.ffmpeg_ffmpeg) if", "files setup_config_args(parser, ignore_unknown=True) # Console output should be on stderr", "= parser.format_usage() console.msg( f\"{usage}\\n\" f\"Use -h/--help to see the available", "defaults[parg.dest] = parg.default else: pargdest = parg.dest for action in", "args.json: console.msg_json( plugin=plugin.module, metadata=plugin.get_metadata(), streams=streams ) elif args.stream_url: try: console.msg(streams[list(streams)[-1]].to_manifest_url())", "b\"\") ) if show_progress: stream_iterator = progress( stream_iterator, prefix=os.path.basename(output.filename) )", "all plugins Streamlink has loaded.\"\"\" pluginlist = list(streamlink.get_plugins().keys()) pluginlist_formatted =", "global streamlink streamlink = Streamlink({\"user-input-requester\": ConsoleUserInputRequester(console)}) def setup_options(): \"\"\"Sets Streamlink", "args.verbose_player, kill=not args.player_no_close, namedpipe=namedpipe, http=http, record=record, title=formatter.title(args.title, defaults=DEFAULT_STREAM_METADATA) if args.title", "6)) elif force: log.info(f\"Your Streamlink version ({installed_version}) is up to", "stream elif args.json: console.msg_json( stream, metadata=plugin.get_metadata() ) elif args.stream_url: try:", "PluginError as err: log.error(err) streams = None if not streams:", "from it. This is useful to check if a stream", "streams: {validstreams}\") elif args.json: console.msg_json( plugin=plugin.module, metadata=plugin.get_metadata(), streams=streams ) elif", "def load_plugins(dirs: List[Path], showwarning: bool = True): \"\"\"Attempts to load", "sys.stdout # We don't want log output when we are", "if not silent_log else \"none\" log_file = args.logfile if log_level", "ACCEPTABLE_ERRNO += (errno.WSAECONNABORTED,) except AttributeError: pass # Not windows QUIET_OPTIONS", "streams, retrying every {interval} second(s)\") attempts = 0 while not", "file \"\"\" if (args.output or args.stdout) and (args.record or args.record_and_pipe):", "output.open() except OSError as err: console.exit(f\"Failed to start player: {args.player}", "args.hds_segment_timeout: streamlink.set_option(\"hds-segment-timeout\", args.hds_segment_timeout) if args.hds_timeout: streamlink.set_option(\"hds-timeout\", args.hds_timeout) if args.hls_segment_attempts: streamlink.set_option(\"hls-segment-attempts\",", "PluginError as err: console.exit(err) if not streams: console.exit(f\"No playable streams", "elif args.help: parser.print_help() else: usage = parser.format_usage() console.msg( f\"{usage}\\n\" f\"Use", "\"executable with --player.\") if args.player_fifo: try: namedpipe = NamedPipe() except", "except StreamError as err: console.exit(err) console.msg(cmdline) else: console.exit(\"The stream specified", "group.add_argument(parg.argument_name(pname), **parg.options) defaults[parg.dest] = parg.default else: pargdest = parg.dest for", "except PluginError as err: console.exit(err) if not streams: console.exit(f\"No playable", "== \"darwin\": os_version = f\"macOS {platform.mac_ver()[0]}\" # Windows elif sys.platform", "player.running: try: yield server.open(timeout=2.5) except OSError: continue def output_stream_http(plugin, initial_streams,", "config_files: List[Path] = None, ignore_unknown: bool = False): \"\"\"Parses arguments.\"\"\"", "out = PlayerOutput( args.player, args=args.player_args, quiet=not args.verbose_player, kill=not args.player_no_close, namedpipe=namedpipe,", "cache.get(\"latest_version\") if force or not latest_version: res = requests.get(\"https://pypi.python.org/pypi/streamlink/json\") data", "already exists! Overwrite it? [y/N] \") if answer.lower() != \"y\":", "k: stream_name + \"_alt\" in k, sorted(streams.keys()))) file_output = args.output", "in filter(lambda path: path.is_file(), CONFIG_FILES): if type(config_file) is DeprecatedPath: log.info(f\"Loaded", "style=\"{\", format=(\"[{asctime}]\" if level == \"trace\" else \"\") + \"[{name}][{levelname}]", "usage = parser.format_usage() console.msg( f\"{usage}\\n\" f\"Use -h/--help to see the", "create_http_server(*_args, **_kwargs): \"\"\"Creates a HTTP server listening on a given", "stream_iterator = progress( stream_iterator, prefix=os.path.basename(output.filename) ) elif show_record_progress: stream_iterator =", "args.player_no_close, namedpipe=namedpipe, http=http, record=record, title=formatter.title(args.title, defaults=DEFAULT_STREAM_METADATA) if args.title else args.url", "from streamlink.stream import StreamIO, StreamProcess from streamlink.utils.named_pipe import NamedPipe from", "named pipes on Windows since the named pipe is not", "to write the stream. Depending on arguments it can be", "contextlib import closing from distutils.version import StrictVersion from functools import", "handle_url() except KeyboardInterrupt: # Close output if output: output.close() console.msg(\"Interrupted!", "and attempt # to use these in case the main", "args.hds_segment_threads: streamlink.set_option(\"hds-segment-threads\", args.hds_segment_threads) if args.hds_segment_timeout: streamlink.set_option(\"hds-segment-timeout\", args.hds_segment_timeout) if args.hds_timeout: streamlink.set_option(\"hds-timeout\",", "cache = Cache(filename=\"cli.json\") latest_version = cache.get(\"latest_version\") if force or not", "player = None log.info(\"Starting server, access with one of:\") for", "output = PlayerOutput( args.player, args=args.player_args, filename=server.url, quiet=not args.verbose_player, title=formatter.title(args.title, defaults=DEFAULT_STREAM_METADATA)", "the URL to a plugin and then attempts to fetch", "= None streamlink: Streamlink = None log = logging.getLogger(\"streamlink.cli\") def", "showwarning: log.warning(f\"Plugin path {directory} does not exist or is not", "not available, will re-fetch streams in 10 sec\") sleep(10) continue", "not stream_fd and (not player or player.running): try: streams =", "read the manual at https://streamlink.github.io\" ) sys.exit(error_code) def parser_helper(): session", "find matching global argument if pargdest != action.dest: continue defaults[pargdest]", "by a plugin specific config log_level = args.loglevel if not", "pipe: {err}\") elif args.player_http: http = create_http_server() if args.record: record", "global argument if pargdest != action.dest: continue defaults[pargdest] = action.default", "NamedPipe from streamlink_cli.argparser import build_parser from streamlink_cli.compat import DeprecatedPath, is_win32,", "see if any of the required arguments are not set", "available interfaces, and if port is 0, listen on a", "if args.version_check or args.auto_version_check: with ignored(Exception): check_version(force=args.version_check) if args.plugins: print_plugins()", "list(streamlink.get_plugins().keys()) pluginlist_formatted = \", \".join(sorted(pluginlist)) if args.json: console.msg_json(pluginlist) else: console.msg(f\"Loaded", "in args.stream): if stream_name in streams: stream = streams[stream_name] break", "log.info(f\"Loaded config from deprecated path, see CLI docs for how", "JSON representation of the stream elif args.json: console.msg_json( stream, metadata=plugin.get_metadata()", "KeyboardInterrupt: # Close output if output: output.close() console.msg(\"Interrupted! Exiting...\") error_code", "from itertools import chain from pathlib import Path from time", "= None for stream_name in (resolve_stream_name(streams, s) for s in", "not in STREAM_SYNONYMS: return name return stream_name def format_valid_streams(plugin, streams):", "pname, plugin in session.plugins.items(): defaults = {} group = plugin_args.add_argument_group(pname.capitalize())", "not seem to be \" \"installed. You must specify the", "= PlayerOutput( args.player, args=args.player_args, filename=server.url, quiet=not args.verbose_player, title=formatter.title(args.title, defaults=DEFAULT_STREAM_METADATA) if", "= parser.add_argument_group(\"Plugin options\") for pname, plugin in session.plugins.items(): defaults =", "it can be one of these: - The stdout pipe", "args.default_stream if args.stream: validstreams = format_valid_streams(plugin, streams) for stream_name in", "Streamlink session.\"\"\" global streamlink streamlink = Streamlink({\"user-input-requester\": ConsoleUserInputRequester(console)}) def setup_options():", "stream. Depending on arguments it can be one of these:", "lookup if args.stream: args.stream = [stream.lower() for stream in args.stream]", "args.stream_segment_timeout: streamlink.set_option(\"stream-segment-timeout\", args.stream_segment_timeout) if args.stream_timeout: streamlink.set_option(\"stream-timeout\", args.stream_timeout) if args.ffmpeg_ffmpeg: streamlink.set_option(\"ffmpeg-ffmpeg\",", "plugins.append(pname) setattr(action, \"plugins\", plugins) plugin.options = PluginOptions(defaults) def setup_plugin_options(session, plugin):", "1 except KeyboardInterrupt: error_code = 130 elif args.url: try: setup_options()", "Streamlink, __version__ as streamlink_version from streamlink.cache import Cache from streamlink.exceptions", "listening on a given host and port. If host is", "else '*' * 8}\") def check_version(force=False): cache = Cache(filename=\"cli.json\") latest_version", "if args.hds_segment_timeout: streamlink.set_option(\"hds-segment-timeout\", args.hds_segment_timeout) if args.hds_timeout: streamlink.set_option(\"hds-timeout\", args.hds_timeout) if args.hls_segment_attempts:", "= record = None if not args.player: console.exit(\"The default player", "gettext from itertools import chain from pathlib import Path from", "{args.player} ({err})\") return False return True def open_stream(stream): \"\"\"Opens a", "output.namedpipe show_progress = ( isinstance(output, FileOutput) and output.fd is not", "{args.player} ({err})\") else: server = create_http_server(host=None, port=port) player = None", "\"time\": lambda dt, fmt: dt.strftime(fmt) } ) def check_file_output(filename, force):", "ignore_unknown=True) # call argument set up as early as possible", "log.error(f\"Try {i + 1}/{args.retry_open}: Could not open stream {stream} ({err})\")", "if args.stream: args.stream = [stream.lower() for stream in args.stream] if", "count: break return streams def resolve_stream_name(streams, stream_name): \"\"\"Returns the real", "subprocess. if args.subprocess_cmdline: if isinstance(stream, StreamProcess): try: cmdline = stream.cmdline()", "res.json() latest_version = data.get(\"info\").get(\"version\") cache.set(\"latest_version\", latest_version, (60 * 60 *", "({stream_type})\") success = output_stream_passthrough(stream, formatter) elif args.player_external_http: return output_stream_http(plugin, streams,", "# Force lowercase to allow case-insensitive lookup if args.stream: args.stream", "not in sensitive else '*' * 8}\") def check_version(force=False): cache", "cannot be parsed\") break if required: for req in required.values():", "any(getattr(args, attr) for attr in QUIET_OPTIONS) log_level = args.loglevel if", "log_level = args.loglevel if not silent_log else \"none\" logger.root.setLevel(log_level) setup_http_session()", "return True def read_stream(stream, output, prebuffer, formatter: Formatter, chunk_size=8192): \"\"\"Reads", "DeprecatedPath: log.info(f\"Loaded plugins from deprecated path, see CLI docs for", "k, sorted(streams.keys()))) file_output = args.output or args.stdout formatter = get_formatter(plugin)", "success = streamlink.load_plugins(str(directory)) if success and type(directory) is DeprecatedPath: log.info(f\"Loaded", "handle_stream(plugin, streams, stream_name) return err = f\"The specified stream(s) '{',", "itertools import chain from pathlib import Path from time import", "create pipe: {err}\") elif args.player_http: http = create_http_server() if args.record:", "{args.url}\") if args.default_stream and not args.stream and not args.json: args.stream", "a command-line. silent_log = any(getattr(args, attr) for attr in QUIET_OPTIONS)", "= args.logfile if log_level != \"none\" else None setup_logger_and_console(console_out, log_file,", "\"\"\"Creates a HTTP server listening on a given host and", "output_stream(stream, formatter: Formatter): \"\"\"Open stream, create output and finally write", "is running if it is not empty. \"\"\" while not", "a random high port. \"\"\" try: http = HTTPServer() http.bind(*_args,", "= 1 except KeyboardInterrupt: error_code = 130 elif args.can_handle_url_no_redirect: try:", "QUIET_OPTIONS = (\"json\", \"stream_url\", \"subprocess_cmdline\", \"quiet\") args = None console:", "interfaces, and if port is 0, listen on a random", "is not empty. \"\"\" while not player or player.running: try:", "console.exit(f\"Error when reading from stream: {err}, exiting\") finally: stream.close() log.info(\"Stream", "Path(path).expanduser(), reversed(args.config)): if config_file.is_file(): config_files.append(config_file) else: # Only load first", "raise StreamError(f\"Failed to read data from stream: {err}\") if not", "plugin) log.info(f\"Found matching plugin {plugin.module} for URL {args.url}\") if args.retry_max", "with --player.\") server = create_http_server() player = output = PlayerOutput(", "passed to the player.\"\"\" global output filename = f'\"{stream_to_url(stream)}\"' output", "def read_stream(stream, output, prebuffer, formatter: Formatter, chunk_size=8192): \"\"\"Reads data from", "list of valid streams. \"\"\" try: plugin = streamlink.resolve_url(args.url) setup_plugin_options(streamlink,", "read_stream(stream, output, prebuffer, formatter: Formatter, chunk_size=8192): \"\"\"Reads data from stream", "\"\"\"Sets Streamlink plugin options.\"\"\" pname = plugin.module required = OrderedDict({})", "isinstance(output, FileOutput) and output.fd is not stdout and (sys.stdout.isatty() or", "plugin.arguments: if parg.sensitive: sensitive.add(parg.argument_name(pname)) log.debug(\"Arguments:\") for action in parser._actions: if", "args = None console: ConsoleOutput = None output: Output =", "{config_file}\") config_files.append(config_file) break if streamlink and args.url: # Only load", "A subprocess' stdin pipe - A named pipe that the", "is streams[n] and n is not name synonyms = list(filter(synonymfilter,", "in STREAM_SYNONYMS: continue def synonymfilter(n): return stream is streams[n] and", "return False return True def open_stream(stream): \"\"\"Opens a stream and", "streamlink.set_option(\"hls-segment-threads\", args.hls_segment_threads) if args.hls_segment_timeout: streamlink.set_option(\"hls-segment-timeout\", args.hls_segment_timeout) if args.hls_timeout: streamlink.set_option(\"hls-timeout\", args.hls_timeout)", "plugin to global argument plugins = getattr(action, \"plugins\", []) plugins.append(pname)", "CONFIG_FILES: config_file = config_file.with_name(f\"{config_file.name}.{plugin.module}\") if not config_file.is_file(): continue if type(config_file)", "log.info(f\"Waiting for streams, retrying every {interval} second(s)\") attempts = 0", "streams. Filters out synonyms and displays them next to the", "prebuffer = open_stream(stream) except StreamError as err: log.error(err) if stream_fd", "elif args.rtmpdump: streamlink.set_option(\"rtmp-rtmpdump\", args.rtmpdump) if args.rtmp_proxy: streamlink.set_option(\"rtmp-proxy\", args.rtmp_proxy) # deprecated", "dict(args.http_query_param)) if args.http_ignore_env: streamlink.set_option(\"http-trust-env\", False) if args.http_no_ssl_verify: streamlink.set_option(\"http-ssl-verify\", False) if", "it can be one of these: - Output internal command-line", "if args.retry_max: retry_max = args.retry_max streams = fetch_streams_with_retry(plugin, retry_streams, retry_max)", "args.url_param def setup_config_args(parser, ignore_unknown=False): config_files = [] if args.config: #", "= False): \"\"\"Parses arguments.\"\"\" global args arglist = sys.argv[1:] #", "> installed_version: log.info(f\"A new version of Streamlink ({latest_version}) is available!\")", "args.hds_live_edge: streamlink.set_option(\"hds-live-edge\", args.hds_live_edge) if args.hls_live_edge: streamlink.set_option(\"hls-live-edge\", args.hls_live_edge) if args.hls_playlist_reload_attempts: streamlink.set_option(\"hls-playlist-reload-attempts\",", "stream_iterator, prefix=os.path.basename(output.filename) ) elif show_record_progress: stream_iterator = progress( stream_iterator, prefix=os.path.basename(output.record.filename)", "if player: player.open() except OSError as err: console.exit(f\"Failed to start", "arguments if args.stream_segment_attempts: streamlink.set_option(\"stream-segment-attempts\", args.stream_segment_attempts) if args.stream_segment_threads: streamlink.set_option(\"stream-segment-threads\", args.stream_segment_threads) if", "[stream_name] + alt_streams: stream = streams[stream_name] stream_type = type(stream).shortname() if", "player (VLC) does not seem to be \" \"installed. You", "log.error(f\"{pname} plugin has a configuration error and the arguments cannot", "level == \"trace\" else \"\") ) console = ConsoleOutput(streamhandler.stream, json)", "read data from stream: {err}\") if not prebuffer: stream_fd.close() raise", "validstreams = [] for name, stream in sorted(streams.items(), key=lambda stream:", "def setup_plugins(extra_plugin_dir=None): \"\"\"Loads any additional plugins.\"\"\" load_plugins(PLUGIN_DIRS, showwarning=False) if extra_plugin_dir:", "args.record_and_pipe): console.exit(\"Cannot use record options with other file output options.\")", "continue def output_stream_http(plugin, initial_streams, formatter: Formatter, external=False, port=0): \"\"\"Continuously output", "import StreamIO, StreamProcess from streamlink.utils.named_pipe import NamedPipe from streamlink_cli.argparser import", "= isinstance(output, PlayerOutput) is_http = isinstance(output, HTTPServer) is_fifo = is_player", "deprecated if args.hds_segment_attempts: streamlink.set_option(\"hds-segment-attempts\", args.hds_segment_attempts) if args.hds_segment_threads: streamlink.set_option(\"hds-segment-threads\", args.hds_segment_threads) if", "as err: if isinstance(output, PlayerOutput): console.exit(f\"Failed to start player: {args.player}", "to a player \" \"executable with --player.\") if args.player_fifo: try:", "console.exit(\"The stream specified cannot be translated to a URL\") #", "dict of streams. Filters out synonyms and displays them next", "specific args have been added setup_args(parser) setup_config_args(parser) # update the", "os.path.isfile(filename) and not force: if sys.stdin.isatty(): answer = console.ask(f\"File {filename}", "player: {args.player}\") out = PlayerOutput( args.player, args=args.player_args, quiet=not args.verbose_player, kill=not", "out synonyms and displays them next to the stream they", "\"\"\"Prepares a filename to be passed to the player.\"\"\" global", "argument plugins = getattr(action, \"plugins\", []) plugins.append(pname) setattr(action, \"plugins\", plugins)", "\"unknown player\" log.info(f\"Got HTTP request from {user_agent}\") stream_fd = prebuffer", "None output: Output = None plugin: Plugin = None stream_fd:", "parg.sensitive: sensitive.add(parg.argument_name(pname)) log.debug(\"Arguments:\") for action in parser._actions: if not hasattr(args,", "be translated to a URL\") else: validstreams = format_valid_streams(plugin, streams)", "set, check to see if any of the required arguments", "streams. \"\"\" try: plugin = streamlink.resolve_url(args.url) setup_plugin_options(streamlink, plugin) log.info(f\"Found matching", "stream specified cannot be translated to a URL\") # Output", "args.ffmpeg_verbose_path: streamlink.set_option(\"ffmpeg-verbose-path\", args.ffmpeg_verbose_path) if args.ffmpeg_fout: streamlink.set_option(\"ffmpeg-fout\", args.ffmpeg_fout) if args.ffmpeg_video_transcode: streamlink.set_option(\"ffmpeg-video-transcode\",", "required: for req in required.values(): if not session.get_plugin_option(pname, req.dest): prompt", "= (errno.EPIPE, errno.EINVAL, errno.ECONNRESET) try: ACCEPTABLE_ERRNO += (errno.WSAECONNABORTED,) except AttributeError:", "main(): error_code = 0 parser = build_parser() setup_args(parser, ignore_unknown=True) #", "over HTTP.\"\"\" global output if not external: if not args.player:", "stream_iterator = chain( [prebuffer], iter(partial(stream.read, chunk_size), b\"\") ) if show_progress:", "player: {args.player} ({err})\") else: server = create_http_server(host=None, port=port) player =", "can be one of these: - Output internal command-line -", "# to use these in case the main stream is", "arguments: %s\") parser.error(msg % \" \".join(unknown)) # Force lowercase to", "def setup_config_args(parser, ignore_unknown=False): config_files = [] if args.config: # We", "# Only load first available default config for config_file in", "when # using named pipes on Windows since the named", "if os.geteuid() == 0: log.info(\"streamlink is running as root! Be", "external: if not args.player: console.exit(\"The default player (VLC) does not", "None log = logging.getLogger(\"streamlink.cli\") def get_formatter(plugin: Plugin): return Formatter( {", "output, prebuffer, formatter) return True def read_stream(stream, output, prebuffer, formatter:", "f\"The specified stream(s) '{', '.join(args.stream)}' could not be found\" if", "and args.url_param: args.url = args.url_param def setup_config_args(parser, ignore_unknown=False): config_files =", "any streams with a '_alt' suffix and attempt # to", "f\"macOS {platform.mac_ver()[0]}\" # Windows elif sys.platform == \"win32\": os_version =", "Linux / other else: os_version = platform.platform() log.debug(f\"OS: {os_version}\") log.debug(f\"Python:", "sleep from typing import List import requests from socks import", "internal command-line - Output JSON represenation - Continuously output the", "args.https_proxy) if args.http_cookie: streamlink.set_option(\"http-cookies\", dict(args.http_cookie)) if args.http_header: streamlink.set_option(\"http-headers\", dict(args.http_header)) if", "argument if pargdest != action.dest: continue defaults[pargdest] = action.default #", "!= action.dest: continue defaults[pargdest] = action.default # add plugin to", "import chain from pathlib import Path from time import sleep", "[]) plugins.append(pname) setattr(action, \"plugins\", plugins) plugin.options = PluginOptions(defaults) def setup_plugin_options(session,", "named pipe that the subprocess reads from - A regular", "output list of valid streams. \"\"\" try: plugin = streamlink.resolve_url(args.url)", "and the arguments cannot be parsed\") break if required: for", "= streams[stream_name] # Print internal command-line if this stream #", "iter(partial(stream.read, chunk_size), b\"\") ) if show_progress: stream_iterator = progress( stream_iterator,", "streamlink.set_option(\"subprocess-errorlog-path\", args.subprocess_errorlog_path) streamlink.set_option(\"locale\", args.locale) def setup_plugin_args(session, parser): \"\"\"Sets Streamlink plugin", "import CONFIG_FILES, DEFAULT_STREAM_METADATA, LOG_DIR, PLUGIN_DIRS, STREAM_SYNONYMS from streamlink_cli.output import FileOutput,", "required[rparg.name] = rparg except RuntimeError: log.error(f\"{pname} plugin has a configuration", "List[Path] = None, ignore_unknown: bool = False): \"\"\"Parses arguments.\"\"\" global", "else: console.exit(\"The stream specified cannot be translated to a command\")", "in action.option_strings if option.startswith(\"--\")), action.option_strings[0] ) if action.option_strings else action.dest", "in server.urls: log.info(\" \" + url) for req in iter_http_requests(server,", "datetime.now() }, { \"time\": lambda dt, fmt: dt.strftime(fmt) } )", "if args.hls_start_offset: streamlink.set_option(\"hls-start-offset\", args.hls_start_offset) if args.hls_duration: streamlink.set_option(\"hls-duration\", args.hls_duration) if args.hls_live_restart:", "args.hls_segment_timeout: streamlink.set_option(\"hls-segment-timeout\", args.hls_segment_timeout) if args.hls_timeout: streamlink.set_option(\"hls-timeout\", args.hls_timeout) if args.http_stream_timeout: streamlink.set_option(\"http-stream-timeout\",", "ignored(NoPluginError): plugin = streamlink.resolve_url(args.url) for config_file in CONFIG_FILES: config_file =", "# using named pipes on Windows since the named pipe", "errno.ECONNRESET) try: ACCEPTABLE_ERRNO += (errno.WSAECONNABORTED,) except AttributeError: pass # Not", "stream_fd = stream.open() except StreamError as err: raise StreamError(f\"Could not", "break except StreamError as err: log.error(f\"Try {i + 1}/{args.retry_open}: Could", "\"win32\": os_version = f\"{platform.system()} {platform.release()}\" # Linux / other else:", "DeprecatedPath, is_win32, stdout from streamlink_cli.console import ConsoleOutput, ConsoleUserInputRequester from streamlink_cli.constants", "format_valid_streams(plugin, streams) for stream_name in args.stream: if stream_name in streams:", "[] if args.config: # We want the config specified last", "signal.signal(signal.SIGTERM, signal.default_int_handler) def setup_http_session(): \"\"\"Sets the global HTTP settings, such", "s) for s in args.stream): if stream_name in streams: stream", "translated to a URL\") else: validstreams = format_valid_streams(plugin, streams) console.msg(f\"Available", "if stream_name in streams: log.info(f\"Available streams: {validstreams}\") handle_stream(plugin, streams, stream_name)", "stream-type arguments if args.stream_segment_attempts: streamlink.set_option(\"stream-segment-attempts\", args.stream_segment_attempts) if args.stream_segment_threads: streamlink.set_option(\"stream-segment-threads\", args.stream_segment_threads)", "else: validstreams = format_valid_streams(plugin, streams) console.msg(f\"Available streams: {validstreams}\") def print_plugins():", "if parg.required: required[parg.name] = parg # if the value is", "parg.default else: pargdest = parg.dest for action in parser._actions: #", "player: player.open() except OSError as err: console.exit(f\"Failed to start player:", "StreamError as err: raise StreamError(f\"Could not open stream: {err}\") #", "plugin and then attempts to fetch a list of available", "stream_fd, prebuffer = open_stream(stream) success_open = True break except StreamError", "fetch a list of available streams. Proceeds to handle stream", "options.\"\"\" plugin_args = parser.add_argument_group(\"Plugin options\") for pname, plugin in session.plugins.items():", "list of directories.\"\"\" for directory in dirs: if directory.is_dir(): success", "see CLI docs for how to migrate: {config_file}\") config_files.append(config_file) break", "streams: {err}\") continue try: log.info(f\"Opening stream: {stream_name} ({type(stream).shortname()})\") stream_fd, prebuffer", "args.stream = args.default_stream if args.stream: validstreams = format_valid_streams(plugin, streams) for", "in (resolve_stream_name(streams, s) for s in args.stream): if stream_name in", "it.\") sys.exit() return FileOutput(filename) def create_output(formatter: Formatter): \"\"\"Decides where to", "if args.json: console.msg_json(pluginlist) else: console.msg(f\"Loaded plugins: {pluginlist_formatted}\") def load_plugins(dirs: List[Path],", "JSON or a command-line. silent_log = any(getattr(args, attr) for attr", "and if port is 0, listen on a random high", "!= value: name = next( # pragma: no branch (option", "setup args again once the plugin specific args have been", "console.msg(f\"Loaded plugins: {pluginlist_formatted}\") def load_plugins(dirs: List[Path], showwarning: bool = True):", "action.option_strings else action.dest log.debug(f\" {name}={value if name not in sensitive", "for how to migrate: {directory}\") elif showwarning: log.warning(f\"Plugin path {directory}", "else: os_version = platform.platform() log.debug(f\"OS: {os_version}\") log.debug(f\"Python: {platform.python_version()}\") log.debug(f\"Streamlink: {streamlink_version}\")", "console.ask(f\"File {filename} already exists! Overwrite it? [y/N] \") if answer.lower()", "if args.stream_segment_attempts: streamlink.set_option(\"stream-segment-attempts\", args.stream_segment_attempts) if args.stream_segment_threads: streamlink.set_option(\"stream-segment-threads\", args.stream_segment_threads) if args.stream_segment_timeout:", "streams = fetch_streams(plugin) except FatalPluginError: raise except PluginError as err:", "formatter = get_formatter(plugin) for stream_name in [stream_name] + alt_streams: stream", "= f\"{req.prompt or f'Enter {pname} {req.name}'}: \" session.set_plugin_option( pname, req.dest,", "if args.stream_segment_timeout: streamlink.set_option(\"stream-segment-timeout\", args.stream_segment_timeout) if args.stream_timeout: streamlink.set_option(\"stream-timeout\", args.stream_timeout) if args.ffmpeg_ffmpeg:", "streamhandler = logger.basicConfig( stream=stream, filename=filename, level=level, style=\"{\", format=(\"[{asctime}]\" if level", "None console: ConsoleOutput = None output: Output = None plugin:", "= rparg except RuntimeError: log.error(f\"{pname} plugin has a configuration error", "stream if user specified a valid one, otherwise output list", "pluginlist = list(streamlink.get_plugins().keys()) pluginlist_formatted = \", \".join(sorted(pluginlist)) if args.json: console.msg_json(pluginlist)", "name not in STREAM_SYNONYMS: return name return stream_name def format_valid_streams(plugin,", "log.debug(f\"Python: {platform.python_version()}\") log.debug(f\"Streamlink: {streamlink_version}\") log.debug(f\"Requests({requests.__version__}), \" f\"Socks({socks_version}), \" f\"Websocket({websocket_version})\") def", "if show_progress: stream_iterator = progress( stream_iterator, prefix=os.path.basename(output.filename) ) elif show_record_progress:", "from streamlink_cli.output import FileOutput, Output, PlayerOutput from streamlink_cli.utils import Formatter,", "stream: {err}\") if not prebuffer: stream_fd.close() raise StreamError(\"No data returned", "output.close() console.msg(\"Interrupted! Exiting...\") error_code = 130 finally: if stream_fd: try:", "streams[stream_name] stream_type = type(stream).shortname() if stream_type in args.player_passthrough and not", "print_plugins() elif args.can_handle_url: try: streamlink.resolve_url(args.can_handle_url) except NoPluginError: error_code = 1", "as err: log.error(err) if count > 0: attempts += 1", "= namedpipe = record = None if not args.player: console.exit(\"The", "Streamlink({\"user-input-requester\": ConsoleUserInputRequester(console)}) def setup_options(): \"\"\"Sets Streamlink options.\"\"\" if args.interface: streamlink.set_option(\"interface\",", "err: if isinstance(output, PlayerOutput): console.exit(f\"Failed to start player: {args.player} ({err})\")", "to the player.\"\"\" global output filename = f'\"{stream_to_url(stream)}\"' output =", "log.info(\"Stream not available, will re-fetch streams in 10 sec\") sleep(10)", "args.retry_streams: retry_streams = 1 retry_max = 0 if args.retry_streams: retry_streams", "streamlink and args.url: # Only load first available plugin config", "plugin can handle URL: {args.url}\") except PluginError as err: console.exit(err)", "latest_version, (60 * 60 * 24)) version_info_printed = cache.get(\"version_info_printed\") if", "if args.ffmpeg_start_at_zero: streamlink.set_option(\"ffmpeg-start-at-zero\", args.ffmpeg_start_at_zero) streamlink.set_option(\"subprocess-errorlog\", args.subprocess_errorlog) streamlink.set_option(\"subprocess-errorlog-path\", args.subprocess_errorlog_path) streamlink.set_option(\"locale\", args.locale)", "from time import sleep from typing import List import requests", "fetch_streams_with_retry(plugin, interval, count): \"\"\"Attempts to fetch streams repeatedly until some", "stream in args.stream] if not args.url and args.url_param: args.url =", "they point to. Streams are sorted according to their quality", "deprecated path, see CLI docs for how to migrate: {directory}\")", "if any of the required arguments are not set if", "be \" \"installed. You must specify the path to a", "if args.config: # We want the config specified last to", "stream {stream}, tried {args.retry_open} times, exiting\") output = create_output(formatter) try:", "lambda: plugin.get_title(), \"time\": lambda: datetime.now() }, { \"time\": lambda dt,", "check_file_output(formatter.filename(args.record_and_pipe, args.fs_safe_rules), args.force) out = FileOutput(fd=stdout, record=record) else: http =", "\" \".join(unknown)) # Force lowercase to allow case-insensitive lookup if", "config_file in map(lambda path: Path(path).expanduser(), reversed(args.config)): if config_file.is_file(): config_files.append(config_file) else:", "if os.path.isfile(filename) and not force: if sys.stdin.isatty(): answer = console.ask(f\"File", "= parg.default else: pargdest = parg.dest for action in parser._actions:", "return name return stream_name def format_valid_streams(plugin, streams): \"\"\"Formats a dict", "streamlink.set_option(\"ffmpeg-video-transcode\", args.ffmpeg_video_transcode) if args.ffmpeg_audio_transcode: streamlink.set_option(\"ffmpeg-audio-transcode\", args.ffmpeg_audio_transcode) if args.ffmpeg_copyts: streamlink.set_option(\"ffmpeg-copyts\", args.ffmpeg_copyts)", "retry_streams, retry_max) else: streams = fetch_streams(plugin) except NoPluginError: console.exit(f\"No plugin", "plugins) plugin.options = PluginOptions(defaults) def setup_plugin_options(session, plugin): \"\"\"Sets Streamlink plugin", "from contextlib import closing from distutils.version import StrictVersion from functools", "date!\") if force: sys.exit() def setup_logger_and_console(stream=sys.stdout, filename=None, level=\"info\", json=False): global", "log_current_versions() log_current_arguments(streamlink, parser) if args.version_check or args.auto_version_check: with ignored(Exception): check_version(force=args.version_check)", "to check for errors. # This is to avoid opening", "stream to stdout. if args.stdout or args.output == \"-\" or", "args.stream: validstreams = format_valid_streams(plugin, streams) for stream_name in args.stream: if", "OSError as err: console.exit(f\"Failed to create pipe: {err}\") elif args.player_http:", "must specify the path to a player \" \"executable with", "elif args.stdout: out = FileOutput(fd=stdout) elif args.record_and_pipe: record = check_file_output(formatter.filename(args.record_and_pipe,", "path to a player \" \"executable with --player.\") server =", "the available options or read the manual at https://streamlink.github.io\" )", "seem to be \" \"installed. You must specify the path", "for name, stream in streams.items(): if stream is streams[stream_name] and", "to use these in case the main stream is not", "lambda: datetime.now() }, { \"time\": lambda dt, fmt: dt.strftime(fmt) }", "# find matching global argument if pargdest != action.dest: continue", "PlayerOutput from streamlink_cli.utils import Formatter, HTTPServer, datetime, ignored, progress, stream_to_url", "level if changed by a plugin specific config log_level =", "are printing JSON or a command-line. silent_log = any(getattr(args, attr)", "defaults = {} group = plugin_args.add_argument_group(pname.capitalize()) for parg in plugin.arguments:", "on a given host and port. If host is empty,", "= next( # pragma: no branch (option for option in", "from stream and then writes it to the output.\"\"\" is_player", "lambda: plugin.get_author(), \"category\": lambda: plugin.get_category(), \"game\": lambda: plugin.get_category(), \"title\": lambda:", "OSError as err: if is_player and err.errno in ACCEPTABLE_ERRNO: log.info(\"Player", "else action.dest log.debug(f\" {name}={value if name not in sensitive else", "to stdout. if args.stdout or args.output == \"-\" or args.record_and_pipe:", "OrderedDict from contextlib import closing from distutils.version import StrictVersion from", "list of available streams. Proceeds to handle stream if user", "metadata=plugin.get_metadata() ) elif args.stream_url: try: console.msg(stream.to_url()) except TypeError: console.exit(\"The stream", "args.ffmpeg_verbose) if args.ffmpeg_verbose_path: streamlink.set_option(\"ffmpeg-verbose-path\", args.ffmpeg_verbose_path) if args.ffmpeg_fout: streamlink.set_option(\"ffmpeg-fout\", args.ffmpeg_fout) if", "f\"{usage}\\n\" f\"Use -h/--help to see the available options or read", "with the selected stream. Depending on arguments it can be", "FileOutput(filename) def create_output(formatter: Formatter): \"\"\"Decides where to write the stream.", "if action.option_strings else action.dest log.debug(f\" {name}={value if name not in", "console: ConsoleOutput = None output: Output = None plugin: Plugin", "Windows elif sys.platform == \"win32\": os_version = f\"{platform.system()} {platform.release()}\" #", "option.startswith(\"--\")), action.option_strings[0] ) if action.option_strings else action.dest log.debug(f\" {name}={value if", "isinstance(output, PlayerOutput): console.exit(f\"Failed to start player: {args.player} ({err})\") else: console.exit(f\"Failed", "be found\" if args.json: console.msg_json( plugin=plugin.module, metadata=plugin.get_metadata(), streams=streams, error=err )", "streams=streams ) elif args.stream_url: try: console.msg(streams[list(streams)[-1]].to_manifest_url()) except TypeError: console.exit(\"The stream", "\"\"\"Fetches streams using correct parameters.\"\"\" return plugin.streams(stream_types=args.stream_types, sorting_excludes=args.stream_sorting_excludes) def fetch_streams_with_retry(plugin,", "and then writes it to the output.\"\"\" is_player = isinstance(output,", "{pname} {req.name}'}: \" session.set_plugin_option( pname, req.dest, console.askpass(prompt) if req.sensitive else", "( hasattr(output, \"record\") and isinstance(output.record, FileOutput) and output.record.fd is not", "name in STREAM_SYNONYMS: continue def synonymfilter(n): return stream is streams[n]", "def check_file_output(filename, force): \"\"\"Checks if file already exists and ask", "closed\") elif is_http and err.errno in ACCEPTABLE_ERRNO: log.info(\"HTTP connection closed\")", "Cache from streamlink.exceptions import FatalPluginError from streamlink.plugin import Plugin, PluginOptions", "try: streams = initial_streams or fetch_streams(plugin) initial_streams = None for", "filter(lambda path: path.is_file(), CONFIG_FILES): if type(config_file) is DeprecatedPath: log.info(f\"Loaded config", "config from deprecated path, see CLI docs for how to", "== \"-\" or args.record_and_pipe: console_out = sys.stderr else: console_out =", "plugin.get_title(), \"time\": lambda: datetime.now() }, { \"time\": lambda dt, fmt:", "formatter: Formatter, external=False, port=0): \"\"\"Continuously output the stream over HTTP.\"\"\"", "and not file_output: log.info(f\"Opening stream: {stream_name} ({stream_type})\") success = output_stream_passthrough(stream,", "and version_info_printed: return installed_version = StrictVersion(streamlink.version) latest_version = StrictVersion(latest_version) if", "that the subprocess reads from - A regular file \"\"\"", "err.errno in ACCEPTABLE_ERRNO: log.info(\"Player closed\") elif is_http and err.errno in", "if sys.platform == \"darwin\": os_version = f\"macOS {platform.mac_ver()[0]}\" # Windows", "log.debug(\"Writing stream to player\") read_stream(stream_fd, server, prebuffer, formatter) server.close(True) player.close()", "handler. Attempts to resolve the URL to a plugin and", "\"author\": lambda: plugin.get_author(), \"category\": lambda: plugin.get_category(), \"game\": lambda: plugin.get_category(), \"title\":", "else: log.error(f\"File {filename} already exists, use --force to overwrite it.\")", "= args.retry_streams if args.retry_max: retry_max = args.retry_max streams = fetch_streams_with_retry(plugin,", "StrictVersion from functools import partial from gettext import gettext from", "args.json: args.stream = args.default_stream if args.stream: validstreams = format_valid_streams(plugin, streams)", "fetch_streams(plugin) initial_streams = None for stream_name in (resolve_stream_name(streams, s) for", "sec\") sleep(10) continue except PluginError as err: log.error(f\"Unable to fetch", "[prebuffer], iter(partial(stream.read, chunk_size), b\"\") ) if show_progress: stream_iterator = progress(", "args.hls_live_edge: streamlink.set_option(\"hls-live-edge\", args.hls_live_edge) if args.hls_playlist_reload_attempts: streamlink.set_option(\"hls-playlist-reload-attempts\", args.hls_playlist_reload_attempts) if args.hls_playlist_reload_time: streamlink.set_option(\"hls-playlist-reload-time\",", "streamlink.set_option(\"ipv4\", args.ipv4) if args.ipv6: streamlink.set_option(\"ipv6\", args.ipv6) if args.ringbuffer_size: streamlink.set_option(\"ringbuffer-size\", args.ringbuffer_size)", "{plugin.module} for URL {args.url}\") if args.retry_max or args.retry_streams: retry_streams =", "if args.hls_playlist_reload_attempts: streamlink.set_option(\"hls-playlist-reload-attempts\", args.hls_playlist_reload_attempts) if args.hls_playlist_reload_time: streamlink.set_option(\"hls-playlist-reload-time\", args.hls_playlist_reload_time) if args.hls_segment_ignore_names:", "args.rtmp_proxy) # deprecated if args.hds_segment_attempts: streamlink.set_option(\"hds-segment-attempts\", args.hds_segment_attempts) if args.hds_segment_threads: streamlink.set_option(\"hds-segment-threads\",", "if not logger.root.isEnabledFor(logging.DEBUG): return # macOS if sys.platform == \"darwin\":", "point to. Streams are sorted according to their quality (based", "map(lambda path: Path(path).expanduser(), reversed(args.config)): if config_file.is_file(): config_files.append(config_file) else: # Only", "Attempts to open the stream try: stream_fd = stream.open() except", "stream, create output and finally write the stream to output.\"\"\"", "(VLC) does not seem to be \" \"installed. You must", "stream to output.\"\"\" global output success_open = False for i", "= HTTPServer() http.bind(*_args, **_kwargs) except OSError as err: console.exit(f\"Failed to", "Forever if the serving externally, or while a player is", "{stream_name} ({type(stream).shortname()})\") stream_fd, prebuffer = open_stream(stream) except StreamError as err:", "break def fetch_streams(plugin): \"\"\"Fetches streams using correct parameters.\"\"\" return plugin.streams(stream_types=args.stream_types,", "overwritten if it does.\"\"\" log.debug(\"Checking file output\") if os.path.isfile(filename) and", "log output when we are printing JSON or a command-line.", "a URL\") # Output the stream else: # Find any", "args have been added setup_args(parser) setup_config_args(parser) # update the logging", "args.stream_segment_attempts) if args.stream_segment_threads: streamlink.set_option(\"stream-segment-threads\", args.stream_segment_threads) if args.stream_segment_timeout: streamlink.set_option(\"stream-segment-timeout\", args.stream_segment_timeout) if", "bytes from it. This is useful to check if a", "to start player: {args.player} ({err})\") return False return True def", "argparse import errno import logging import os import platform import", "sys.platform == \"darwin\": os_version = f\"macOS {platform.mac_ver()[0]}\" # Windows elif", "and err.errno in ACCEPTABLE_ERRNO: log.info(\"Player closed\") elif is_http and err.errno", "if args.player_fifo: try: namedpipe = NamedPipe() except OSError as err:", "exists and ask the user if it should be overwritten", "attr in QUIET_OPTIONS) log_level = args.loglevel if not silent_log else", "specify the path to a player \" \"executable with --player.\")", "\".join(sorted(pluginlist)) if args.json: console.msg_json(pluginlist) else: console.msg(f\"Loaded plugins: {pluginlist_formatted}\") def load_plugins(dirs:", "from streamlink_cli.utils import Formatter, HTTPServer, datetime, ignored, progress, stream_to_url ACCEPTABLE_ERRNO", ") def check_file_output(filename, force): \"\"\"Checks if file already exists and", "stream in sorted(streams.items(), key=lambda stream: plugin.stream_weight(stream[0])): if name in STREAM_SYNONYMS:", "plugins from deprecated path, see CLI docs for how to", "type(stream).shortname() if stream_type in args.player_passthrough and not file_output: log.info(f\"Opening stream:", "args.stream_url: try: console.msg(streams[list(streams)[-1]].to_manifest_url()) except TypeError: console.exit(\"The stream specified cannot be", "action in parser._actions: # find matching global argument if pargdest", "0: log.info(\"streamlink is running as root! Be careful!\") def log_current_versions():", "Cache(filename=\"cli.json\") latest_version = cache.get(\"latest_version\") if force or not latest_version: res", "URL\") else: validstreams = format_valid_streams(plugin, streams) console.msg(f\"Available streams: {validstreams}\") def", "from socks import __version__ as socks_version from websocket import __version__", "Windows since the named pipe is not # automatically closed", "and is_fifo: output.player.poll() if output.player.returncode is not None: log.info(\"Player closed\")", "== \"trace\" else \"\") ) console = ConsoleOutput(streamhandler.stream, json) def", "# Windows elif sys.platform == \"win32\": os_version = f\"{platform.system()} {platform.release()}\"", "output: {err}, exiting\") break except OSError as err: console.exit(f\"Error when", "parser_helper(): session = Streamlink() parser = build_parser() setup_plugin_args(session, parser) return", "until some are returned or limit hit.\"\"\" try: streams =", "\"\"\" stream_name = resolve_stream_name(streams, stream_name) stream = streams[stream_name] # Print", "in extra_plugin_dir]) def setup_streamlink(): \"\"\"Creates the Streamlink session.\"\"\" global streamlink", "= streamlink.resolve_url(args.url) setup_plugin_options(streamlink, plugin) log.info(f\"Found matching plugin {plugin.module} for URL", "for stream_name in [stream_name] + alt_streams: stream = streams[stream_name] stream_type", "it. This is useful to check if a stream actually", "SIGTERM just like SIGINT signal.signal(signal.SIGTERM, signal.default_int_handler) def setup_http_session(): \"\"\"Sets the", "be translated to a command\") # Print JSON representation of", "if args.http_ignore_env: streamlink.set_option(\"http-trust-env\", False) if args.http_no_ssl_verify: streamlink.set_option(\"http-ssl-verify\", False) if args.http_disable_dh:", "sys.stdin.isatty(): answer = console.ask(f\"File {filename} already exists! Overwrite it? [y/N]", "# a stream to stdout. if args.stdout or args.output ==", "StreamError, Streamlink, __version__ as streamlink_version from streamlink.cache import Cache from", "try: log.info(f\"Starting player: {args.player}\") output.open() except OSError as err: console.exit(f\"Failed", "level == \"trace\" else \"\") + \"[{name}][{levelname}] {message}\", datefmt=\"%H:%M:%S\" +", "= console.ask(f\"File {filename} already exists! Overwrite it? [y/N] \") if", "FileOutput(fd=stdout, record=record) else: http = namedpipe = record = None", "tried {args.retry_open} times, exiting\") output = create_output(formatter) try: output.open() except", "file_output: return output_stream_http(plugin, streams, formatter) else: log.info(f\"Opening stream: {stream_name} ({stream_type})\")", "prebuffer = open_stream(stream) success_open = True break except StreamError as", "else: # Only load first available default config for config_file", "None while not stream_fd and (not player or player.running): try:", "HTTP server listening on a given host and port. If", "check to see if any of the required arguments are", "= create_http_server() player = output = PlayerOutput( args.player, args=args.player_args, filename=server.url,", "else parg.namespace_dest(pname)) session.set_plugin_option(pname, parg.dest, value) if not parg.is_global: if parg.required:", "if option.startswith(\"--\")), action.option_strings[0] ) if action.option_strings else action.dest log.debug(f\" {name}={value", "import List import requests from socks import __version__ as socks_version", "formatter) server.close(True) player.close() server.close() def output_stream_passthrough(stream, formatter: Formatter): \"\"\"Prepares a", "Streamlink ({latest_version}) is available!\") cache.set(\"version_info_printed\", True, (60 * 60 *", "output and finally write the stream to output.\"\"\" global output", "the output.\"\"\" is_player = isinstance(output, PlayerOutput) is_http = isinstance(output, HTTPServer)", "stream_name in streams: log.info(f\"Available streams: {validstreams}\") handle_stream(plugin, streams, stream_name) return", "setup_plugins(extra_plugin_dir=None): \"\"\"Loads any additional plugins.\"\"\" load_plugins(PLUGIN_DIRS, showwarning=False) if extra_plugin_dir: load_plugins([Path(path).expanduser()", "= prebuffer = None while not stream_fd and (not player", "return # macOS if sys.platform == \"darwin\": os_version = f\"macOS", "= output = PlayerOutput( args.player, args=args.player_args, filename=server.url, quiet=not args.verbose_player, title=formatter.title(args.title,", "record = None if not args.player: console.exit(\"The default player (VLC)", "except NoPluginError: error_code = 1 except KeyboardInterrupt: error_code = 130", "Path from time import sleep from typing import List import", "a filename to be passed to the player.\"\"\" global output", "or a command-line. silent_log = any(getattr(args, attr) for attr in", "for req in iter_http_requests(server, player): user_agent = req.headers.get(\"User-Agent\") or \"unknown", "console.exit(f\"Could not open stream {stream}, tried {args.retry_open} times, exiting\") output", "import build_parser from streamlink_cli.compat import DeprecatedPath, is_win32, stdout from streamlink_cli.console", "= FileOutput(fd=stdout) elif args.record_and_pipe: record = check_file_output(formatter.filename(args.record_and_pipe, args.fs_safe_rules), args.force) out", "command-line - Output JSON represenation - Continuously output the stream", "a synonym.\"\"\" if stream_name in STREAM_SYNONYMS and stream_name in streams:", "translated to a URL\") # Output the stream else: #", "fetch_streams(plugin) except PluginError as err: log.error(err) streams = None if", "fetch_streams_with_retry(plugin, retry_streams, retry_max) else: streams = fetch_streams(plugin) except NoPluginError: console.exit(f\"No", "import Formatter, HTTPServer, datetime, ignored, progress, stream_to_url ACCEPTABLE_ERRNO = (errno.EPIPE,", "Plugin): return Formatter( { \"url\": lambda: args.url, \"author\": lambda: plugin.get_author(),", "args.player, args=args.player_args, filename=server.url, quiet=not args.verbose_player, title=formatter.title(args.title, defaults=DEFAULT_STREAM_METADATA) if args.title else", "player.open() except OSError as err: console.exit(f\"Failed to start player: {args.player}", "try: plugin = streamlink.resolve_url(args.url) setup_plugin_options(streamlink, plugin) log.info(f\"Found matching plugin {plugin.module}", "sensitive = set() for pname, plugin in session.plugins.items(): for parg", "connections on a server. Forever if the serving externally, or", "data before opening the output. \"\"\" global stream_fd # Attempts", "in ACCEPTABLE_ERRNO: log.info(\"HTTP connection closed\") else: console.exit(f\"Error when writing to", "If host is empty, listen on all available interfaces, and", "platform import signal import sys from collections import OrderedDict from", "as socks_version from websocket import __version__ as websocket_version import streamlink.logger", "try: console.msg(streams[list(streams)[-1]].to_manifest_url()) except TypeError: console.exit(\"The stream specified cannot be translated", "streamlink.set_option(\"hls-segment-key-uri\", args.hls_segment_key_uri) if args.hls_audio_select: streamlink.set_option(\"hls-audio-select\", args.hls_audio_select) if args.hls_start_offset: streamlink.set_option(\"hls-start-offset\", args.hls_start_offset)", "if args.hds_segment_threads: streamlink.set_option(\"hds-segment-threads\", args.hds_segment_threads) if args.hds_segment_timeout: streamlink.set_option(\"hds-segment-timeout\", args.hds_segment_timeout) if args.hds_timeout:", "streamlink.logger as logger from streamlink import NoPluginError, PluginError, StreamError, Streamlink,", "stream.cmdline() except StreamError as err: console.exit(err) console.msg(cmdline) else: console.exit(\"The stream", "The stdout pipe - A subprocess' stdin pipe - A", "if the serving externally, or while a player is running", "according to their quality (based on plugin.stream_weight). \"\"\" delimiter =", "= cache.get(\"version_info_printed\") if not force and version_info_printed: return installed_version =", "argparse.ArgumentParser, config_files: List[Path] = None, ignore_unknown: bool = False): \"\"\"Parses", "arguments are not set if parg.required or value: try: for", "stream = streams[stream_name] break else: log.info(\"Stream not available, will re-fetch", "# call setup args again once the plugin specific args", "def fetch_streams(plugin): \"\"\"Fetches streams using correct parameters.\"\"\" return plugin.streams(stream_types=args.stream_types, sorting_excludes=args.stream_sorting_excludes)", "selected stream. Depending on arguments it can be one of", "console if filename == \"-\": filename = LOG_DIR / f\"{datetime.now()}.log\"", "args.hls_start_offset: streamlink.set_option(\"hls-start-offset\", args.hls_start_offset) if args.hls_duration: streamlink.set_option(\"hls-duration\", args.hls_duration) if args.hls_live_restart: streamlink.set_option(\"hls-live-restart\",", "if level == \"trace\" else \"\") + \"[{name}][{levelname}] {message}\", datefmt=\"%H:%M:%S\"", "is_win32, stdout from streamlink_cli.console import ConsoleOutput, ConsoleUserInputRequester from streamlink_cli.constants import", "(option for option in action.option_strings if option.startswith(\"--\")), action.option_strings[0] ) if", "all available interfaces, and if port is 0, listen on", "== \"-\": filename = LOG_DIR / f\"{datetime.now()}.log\" elif filename: filename", "def create_http_server(*_args, **_kwargs): \"\"\"Creates a HTTP server listening on a", "log.info(\"Stream ended\") def handle_stream(plugin, streams, stream_name): \"\"\"Decides what to do", "List[Path], showwarning: bool = True): \"\"\"Attempts to load plugins from", "in streams.items(): if stream is streams[stream_name] and name not in", "args.stdout) and (args.record or args.record_and_pipe): console.exit(\"Cannot use record options with", "file_output: log.info(f\"Opening stream: {stream_name} ({stream_type})\") success = output_stream_passthrough(stream, formatter) elif", "stream_name in args.stream: if stream_name in streams: log.info(f\"Available streams: {validstreams}\")", "parg in plugin.arguments: if parg.sensitive: sensitive.add(parg.argument_name(pname)) log.debug(\"Arguments:\") for action in", "else: console_out = sys.stdout # We don't want log output", "args.ffmpeg_fout: streamlink.set_option(\"ffmpeg-fout\", args.ffmpeg_fout) if args.ffmpeg_video_transcode: streamlink.set_option(\"ffmpeg-video-transcode\", args.ffmpeg_video_transcode) if args.ffmpeg_audio_transcode: streamlink.set_option(\"ffmpeg-audio-transcode\",", "output\") read_stream(stream_fd, output, prebuffer, formatter) return True def read_stream(stream, output,", "args.stream: args.stream = [stream.lower() for stream in args.stream] if not", "signal.default_int_handler) def setup_http_session(): \"\"\"Sets the global HTTP settings, such as", "args.output: if args.output == \"-\": out = FileOutput(fd=stdout) else: out", "if changed by a plugin specific config log_level = args.loglevel", "err.errno in ACCEPTABLE_ERRNO: log.info(\"HTTP connection closed\") else: console.exit(f\"Error when writing", "session = Streamlink() parser = build_parser() setup_plugin_args(session, parser) return parser", "output if not external: if not args.player: console.exit(\"The default player", "args.stream_segment_attempts: streamlink.set_option(\"stream-segment-attempts\", args.stream_segment_attempts) if args.stream_segment_threads: streamlink.set_option(\"stream-segment-threads\", args.stream_segment_threads) if args.stream_segment_timeout: streamlink.set_option(\"stream-segment-timeout\",", "and output.fd is not stdout and (sys.stdout.isatty() or args.force_progress) )", "output.fd is not stdout and (sys.stdout.isatty() or args.force_progress) ) show_record_progress", "plugins Streamlink has loaded.\"\"\" pluginlist = list(streamlink.get_plugins().keys()) pluginlist_formatted = \",", "= parser.parse_known_args(configs + arglist) if unknown and not ignore_unknown: msg", "config_file in CONFIG_FILES: config_file = config_file.with_name(f\"{config_file.name}.{plugin.module}\") if not config_file.is_file(): continue", "highest priority for config_file in map(lambda path: Path(path).expanduser(), reversed(args.config)): if", "from functools import partial from gettext import gettext from itertools", "elif showwarning: log.warning(f\"Plugin path {directory} does not exist or is", "plugin.options = PluginOptions(defaults) def setup_plugin_options(session, plugin): \"\"\"Sets Streamlink plugin options.\"\"\"", "set if parg.required or value: try: for rparg in plugin.arguments.requires(parg.name):", "f\"Use -h/--help to see the available options or read the", "running if it is not empty. \"\"\" while not player", "except NoPluginError: console.exit(f\"No plugin can handle URL: {args.url}\") except PluginError", "import signal import sys from collections import OrderedDict from contextlib", "args.rtmpdump) if args.rtmp_proxy: streamlink.set_option(\"rtmp-proxy\", args.rtmp_proxy) # deprecated if args.hds_segment_attempts: streamlink.set_option(\"hds-segment-attempts\",", "def handle_stream(plugin, streams, stream_name): \"\"\"Decides what to do with the", "sensitive else '*' * 8}\") def check_version(force=False): cache = Cache(filename=\"cli.json\")", "KeyboardInterrupt: error_code = 130 elif args.help: parser.print_help() else: usage =", "PlayerOutput) is_http = isinstance(output, HTTPServer) is_fifo = is_player and output.namedpipe", "key=lambda stream: plugin.stream_weight(stream[0])): if name in STREAM_SYNONYMS: continue def synonymfilter(n):", "else: console.exit(f\"Failed to open output: {output.filename} ({err})\") with closing(output): log.debug(\"Writing", "if it is not empty. \"\"\" while not player or", "new streams: {err}\") continue try: log.info(f\"Opening stream: {stream_name} ({type(stream).shortname()})\") stream_fd,", "it to the output.\"\"\" is_player = isinstance(output, PlayerOutput) is_http =", "24)) version_info_printed = cache.get(\"version_info_printed\") if not force and version_info_printed: return", "args.fs_safe_rules), args.force) elif args.stdout: out = FileOutput(fd=stdout) elif args.record_and_pipe: record", "Filters out synonyms and displays them next to the stream", "avoid opening the output unnecessarily. try: log.debug(\"Pre-buffering 8192 bytes\") prebuffer", "def print_plugins(): \"\"\"Outputs a list of all plugins Streamlink has", "from collections import OrderedDict from contextlib import closing from distutils.version", "and (sys.stdout.isatty() or args.force_progress) ) stream_iterator = chain( [prebuffer], iter(partial(stream.read,", "use record options with other file output options.\") if args.output:", "StreamError as err: log.error(err) if stream_fd and prebuffer: log.debug(\"Writing stream", "err: console.exit(f\"Failed to start player: {args.player} ({err})\") else: server =", ") return out def create_http_server(*_args, **_kwargs): \"\"\"Creates a HTTP server", "finally: stream.close() log.info(\"Stream ended\") def handle_stream(plugin, streams, stream_name): \"\"\"Decides what", "format_valid_streams(plugin, streams): \"\"\"Formats a dict of streams. Filters out synonyms", "if not session.get_plugin_option(pname, req.dest): prompt = f\"{req.prompt or f'Enter {pname}", "8}\") def check_version(force=False): cache = Cache(filename=\"cli.json\") latest_version = cache.get(\"latest_version\") if", "added setup_args(parser) setup_config_args(parser) # update the logging level if changed", "plugin_args = parser.add_argument_group(\"Plugin options\") for pname, plugin in session.plugins.items(): defaults", "log.info(f\"Your Streamlink version ({installed_version}) is up to date!\") if force:", "this stream # uses a subprocess. if args.subprocess_cmdline: if isinstance(stream,", "not player or player.running: try: yield server.open(timeout=2.5) except OSError: continue", "name not in sensitive else '*' * 8}\") def check_version(force=False):", "server listening on a given host and port. If host", "Output JSON represenation - Continuously output the stream over HTTP", "args.force) out = FileOutput(fd=stdout, record=record) else: http = namedpipe =", "\"\"\"Decides what to do with the selected stream. Depending on", "if stream is streams[stream_name] and name not in STREAM_SYNONYMS: return", "parser.format_usage() console.msg( f\"{usage}\\n\" f\"Use -h/--help to see the available options", "try: log.info(\"Closing currently open stream...\") stream_fd.close() except KeyboardInterrupt: error_code =", "specified cannot be translated to a command\") # Print JSON", "= args.loglevel if not silent_log else \"none\" log_file = args.logfile", "= NamedPipe() except OSError as err: console.exit(f\"Failed to create pipe:", "log.info(f\"Starting player: {args.player}\") if player: player.open() except OSError as err:", "= args.url_param def setup_config_args(parser, ignore_unknown=False): config_files = [] if args.config:", "try: streamlink.resolve_url_no_redirect(args.can_handle_url_no_redirect) except NoPluginError: error_code = 1 except KeyboardInterrupt: error_code", "to. Streams are sorted according to their quality (based on", "cannot be translated to a command\") # Print JSON representation", "continue def synonymfilter(n): return stream is streams[n] and n is", "elif is_http and err.errno in ACCEPTABLE_ERRNO: log.info(\"HTTP connection closed\") else:", "8192 bytes\") prebuffer = stream_fd.read(8192) except OSError as err: stream_fd.close()", "exiting\") finally: stream.close() log.info(\"Stream ended\") def handle_stream(plugin, streams, stream_name): \"\"\"Decides", "console.exit(\"The stream specified cannot be translated to a command\") #", "__version__ as socks_version from websocket import __version__ as websocket_version import", "these in case the main stream is not usable. alt_streams", "correct parameters.\"\"\" return plugin.streams(stream_types=args.stream_types, sorting_excludes=args.stream_sorting_excludes) def fetch_streams_with_retry(plugin, interval, count): \"\"\"Attempts", "exist or is not a directory!\") def setup_args(parser: argparse.ArgumentParser, config_files:", "of Streamlink ({latest_version}) is available!\") cache.set(\"version_info_printed\", True, (60 * 60", "output \"\"\" stream_name = resolve_stream_name(streams, stream_name) stream = streams[stream_name] #", ") sys.exit(error_code) def parser_helper(): session = Streamlink() parser = build_parser()", "validstreams = format_valid_streams(plugin, streams) for stream_name in args.stream: if stream_name", "Output, PlayerOutput from streamlink_cli.utils import Formatter, HTTPServer, datetime, ignored, progress,", "args, unknown = parser.parse_known_args(configs + arglist) if unknown and not", ") def log_root_warning(): if hasattr(os, \"getuid\"): if os.geteuid() == 0:", "for config_file in filter(lambda path: path.is_file(), CONFIG_FILES): if type(config_file) is", "namedpipe = NamedPipe() except OSError as err: console.exit(f\"Failed to create", "prebuffer, formatter: Formatter, chunk_size=8192): \"\"\"Reads data from stream and then", "CLI docs for how to migrate: {directory}\") elif showwarning: log.warning(f\"Plugin", "= f'\"{stream_to_url(stream)}\"' output = PlayerOutput( args.player, args=args.player_args, filename=filename, call=True, quiet=not", "args.stream] if not args.url and args.url_param: args.url = args.url_param def", "= logging.getLogger(\"streamlink.cli\") def get_formatter(plugin: Plugin): return Formatter( { \"url\": lambda:", "suffix and attempt # to use these in case the", "get highest priority for config_file in map(lambda path: Path(path).expanduser(), reversed(args.config)):", "proxy and headers.\"\"\" if args.http_proxy: streamlink.set_option(\"http-proxy\", args.http_proxy) if args.https_proxy: streamlink.set_option(\"https-proxy\",", "streamlink.set_option(\"stream-segment-attempts\", args.stream_segment_attempts) if args.stream_segment_threads: streamlink.set_option(\"stream-segment-threads\", args.stream_segment_threads) if args.stream_segment_timeout: streamlink.set_option(\"stream-segment-timeout\", args.stream_segment_timeout)", "parameters.\"\"\" return plugin.streams(stream_types=args.stream_types, sorting_excludes=args.stream_sorting_excludes) def fetch_streams_with_retry(plugin, interval, count): \"\"\"Attempts to", "{err}\") continue try: log.info(f\"Opening stream: {stream_name} ({type(stream).shortname()})\") stream_fd, prebuffer =", "load additional plugins setup_plugins(args.plugin_dirs) setup_plugin_args(streamlink, parser) # call setup args", "if type(config_file) is DeprecatedPath: log.info(f\"Loaded config from deprecated path, see", "signal import sys from collections import OrderedDict from contextlib import", "success and type(directory) is DeprecatedPath: log.info(f\"Loaded plugins from deprecated path,", "try: log.info(f\"Opening stream: {stream_name} ({type(stream).shortname()})\") stream_fd, prebuffer = open_stream(stream) except", "data from stream and then writes it to the output.\"\"\"", "stream = streams[stream_name] stream_type = type(stream).shortname() if stream_type in args.player_passthrough", "to a command\") # Print JSON representation of the stream", "available default config for config_file in filter(lambda path: path.is_file(), CONFIG_FILES):", "URL\") # Output the stream else: # Find any streams", "args.ipv6: streamlink.set_option(\"ipv6\", args.ipv6) if args.ringbuffer_size: streamlink.set_option(\"ringbuffer-size\", args.ringbuffer_size) if args.mux_subtitles: streamlink.set_option(\"mux-subtitles\",", "STREAM_SYNONYMS from streamlink_cli.output import FileOutput, Output, PlayerOutput from streamlink_cli.utils import", "to be \" \"installed. You must specify the path to", "stdout and (sys.stdout.isatty() or args.force_progress) ) stream_iterator = chain( [prebuffer],", "of:\") for url in server.urls: log.info(\" \" + url) for", "{args.url}\") except PluginError as err: console.exit(err) if not streams: console.exit(f\"No", "args=args.player_args, filename=server.url, quiet=not args.verbose_player, title=formatter.title(args.title, defaults=DEFAULT_STREAM_METADATA) if args.title else args.url", "from stream\") return stream_fd, prebuffer def output_stream(stream, formatter: Formatter): \"\"\"Open", "log.info(f\"Starting player: {args.player}\") out = PlayerOutput( args.player, args=args.player_args, quiet=not args.verbose_player,", "sys.exit() def setup_logger_and_console(stream=sys.stdout, filename=None, level=\"info\", json=False): global console if filename", "output. \"\"\" global stream_fd # Attempts to open the stream", "action.default # add plugin to global argument plugins = getattr(action,", "have been added setup_args(parser) setup_config_args(parser) # update the logging level", "open stream: {err}\") # Read 8192 bytes before proceeding to", "and isinstance(output.record, FileOutput) and output.record.fd is not stdout and (sys.stdout.isatty()", "not streams: log.info(f\"Waiting for streams, retrying every {interval} second(s)\") attempts", "value is set, check to see if any of the", "log.info(\"HTTP connection closed\") else: console.exit(f\"Error when writing to output: {err},", "stream_name in streams: for name, stream in streams.items(): if stream", "log.info(\"Closing currently open stream...\") stream_fd.close() except KeyboardInterrupt: error_code = 130", "player or player.running: try: yield server.open(timeout=2.5) except OSError: continue def", "to migrate: {config_file}\") config_files.append(config_file) break if config_files: setup_args(parser, config_files, ignore_unknown=ignore_unknown)", "the output unnecessarily. try: log.debug(\"Pre-buffering 8192 bytes\") prebuffer = stream_fd.read(8192)", "open stream {stream}, tried {args.retry_open} times, exiting\") output = create_output(formatter)", "plugin.stream_weight). \"\"\" delimiter = \", \" validstreams = [] for", "NoPluginError: error_code = 1 except KeyboardInterrupt: error_code = 130 elif", "{args.player}\") out = PlayerOutput( args.player, args=args.player_args, quiet=not args.verbose_player, kill=not args.player_no_close,", "{validstreams}\") handle_stream(plugin, streams, stream_name) return err = f\"The specified stream(s)", "out = FileOutput(fd=stdout, record=record) else: http = namedpipe = record", "config log_level = args.loglevel if not silent_log else \"none\" logger.root.setLevel(log_level)", "HTTPServer, datetime, ignored, progress, stream_to_url ACCEPTABLE_ERRNO = (errno.EPIPE, errno.EINVAL, errno.ECONNRESET)", "output unnecessarily. try: log.debug(\"Pre-buffering 8192 bytes\") prebuffer = stream_fd.read(8192) except", "= args.default_stream if args.stream: validstreams = format_valid_streams(plugin, streams) for stream_name", "streams[n] and n is not name synonyms = list(filter(synonymfilter, streams.keys()))", "as err: console.exit(f\"Failed to start player: {args.player} ({err})\") return False", "once the plugin specific args have been added setup_args(parser) setup_config_args(parser)", "if required: for req in required.values(): if not session.get_plugin_option(pname, req.dest):", "CONFIG_FILES, DEFAULT_STREAM_METADATA, LOG_DIR, PLUGIN_DIRS, STREAM_SYNONYMS from streamlink_cli.output import FileOutput, Output,", "formatter) if success: break def fetch_streams(plugin): \"\"\"Fetches streams using correct", "main stream is not usable. alt_streams = list(filter(lambda k: stream_name", "streamlink.set_option(\"ffmpeg-audio-transcode\", args.ffmpeg_audio_transcode) if args.ffmpeg_copyts: streamlink.set_option(\"ffmpeg-copyts\", args.ffmpeg_copyts) if args.ffmpeg_start_at_zero: streamlink.set_option(\"ffmpeg-start-at-zero\", args.ffmpeg_start_at_zero)", "the player.\"\"\" global output filename = f'\"{stream_to_url(stream)}\"' output = PlayerOutput(", "Streamlink has loaded.\"\"\" pluginlist = list(streamlink.get_plugins().keys()) pluginlist_formatted = \", \".join(sorted(pluginlist))", "version_info_printed = cache.get(\"version_info_printed\") if not force and version_info_printed: return installed_version", "log.error(err) streams = None if not streams: log.info(f\"Waiting for streams,", "allow case-insensitive lookup if args.stream: args.stream = [stream.lower() for stream", "= ( isinstance(output, FileOutput) and output.fd is not stdout and", "elif args.json: console.msg_json( stream, metadata=plugin.get_metadata() ) elif args.stream_url: try: console.msg(stream.to_url())", "don't want log output when we are printing JSON or", "and n is not name synonyms = list(filter(synonymfilter, streams.keys())) if", "\"\"\"Decides where to write the stream. Depending on arguments it", "}, { \"time\": lambda dt, fmt: dt.strftime(fmt) } ) def", "\"\"\" try: plugin = streamlink.resolve_url(args.url) setup_plugin_options(streamlink, plugin) log.info(f\"Found matching plugin", "iter_http_requests(server, player): \"\"\"Repeatedly accept HTTP connections on a server. Forever", "streamlink.set_option(\"rtmp-proxy\", args.rtmp_proxy) # deprecated if args.hds_segment_attempts: streamlink.set_option(\"hds-segment-attempts\", args.hds_segment_attempts) if args.hds_segment_threads:", "def fetch_streams_with_retry(plugin, interval, count): \"\"\"Attempts to fetch streams repeatedly until", "args.title else args.url ) try: log.info(f\"Starting player: {args.player}\") output.open() except", "name return stream_name def format_valid_streams(plugin, streams): \"\"\"Formats a dict of", "the stream. Depending on arguments it can be one of", "60 * 24)) version_info_printed = cache.get(\"version_info_printed\") if not force and", "console_out = sys.stderr else: console_out = sys.stdout # We don't", "args.hls_segment_threads: streamlink.set_option(\"hls-segment-threads\", args.hls_segment_threads) if args.hls_segment_timeout: streamlink.set_option(\"hls-segment-timeout\", args.hls_segment_timeout) if args.hls_timeout: streamlink.set_option(\"hls-timeout\",", "== argparse.SUPPRESS: continue value = getattr(args, parg.dest if parg.is_global else", "elif args.player_external_http: return output_stream_http(plugin, streams, formatter, external=True, port=args.player_external_http_port) elif args.player_continuous_http", "{args.player}\") if player: player.open() except OSError as err: console.exit(f\"Failed to", "err: log.error(err) streams = None if not streams: log.info(f\"Waiting for", "log_current_arguments(session, parser): global args if not logger.root.isEnabledFor(logging.DEBUG): return sensitive =", "not success_open: console.exit(f\"Could not open stream {stream}, tried {args.retry_open} times,", "args.http_stream_timeout: streamlink.set_option(\"http-stream-timeout\", args.http_stream_timeout) if args.rtmp_timeout: streamlink.set_option(\"rtmp-timeout\", args.rtmp_timeout) # generic stream-", "# This is to avoid opening the output unnecessarily. try:", "else: server = create_http_server(host=None, port=port) player = None log.info(\"Starting server,", "next to the stream they point to. Streams are sorted", "log_root_warning(): if hasattr(os, \"getuid\"): if os.geteuid() == 0: log.info(\"streamlink is", "in ACCEPTABLE_ERRNO: log.info(\"Player closed\") elif is_http and err.errno in ACCEPTABLE_ERRNO:", "os.geteuid() == 0: log.info(\"streamlink is running as root! Be careful!\")", "\"\"\" while not player or player.running: try: yield server.open(timeout=2.5) except", "streams. Proceeds to handle stream if user specified a valid", "args.ffmpeg_audio_transcode: streamlink.set_option(\"ffmpeg-audio-transcode\", args.ffmpeg_audio_transcode) if args.ffmpeg_copyts: streamlink.set_option(\"ffmpeg-copyts\", args.ffmpeg_copyts) if args.ffmpeg_start_at_zero: streamlink.set_option(\"ffmpeg-start-at-zero\",", "console.exit(\"The stream specified cannot be translated to a URL\") else:", "except RuntimeError: log.error(f\"{pname} plugin has a configuration error and the", "def resolve_stream_name(streams, stream_name): \"\"\"Returns the real stream name of a", "format_valid_streams(plugin, streams) console.msg(f\"Available streams: {validstreams}\") def print_plugins(): \"\"\"Outputs a list", "as err: console.exit(f\"Error when reading from stream: {err}, exiting\") finally:", "not streams: console.exit(f\"No playable streams found on this URL: {args.url}\")", "in plugin.arguments: if not parg.is_global: group.add_argument(parg.argument_name(pname), **parg.options) defaults[parg.dest] = parg.default", "value) if not parg.is_global: if parg.required: required[parg.name] = parg #", "Available streams: {validstreams}\") elif args.json: console.msg_json( plugin=plugin.module, metadata=plugin.get_metadata(), streams=streams )", "LOG_DIR, PLUGIN_DIRS, STREAM_SYNONYMS from streamlink_cli.output import FileOutput, Output, PlayerOutput from", "matching plugin {plugin.module} for URL {args.url}\") if args.retry_max or args.retry_streams:", "return True def open_stream(stream): \"\"\"Opens a stream and reads 8192", "stream {stream} ({err})\") if not success_open: console.exit(f\"Could not open stream", "every {interval} second(s)\") attempts = 0 while not streams: sleep(interval)", "for stream_name in args.stream: if stream_name in streams: log.info(f\"Available streams:", "{name}={value if name not in sensitive else '*' * 8}\")", "if args.ffmpeg_video_transcode: streamlink.set_option(\"ffmpeg-video-transcode\", args.ffmpeg_video_transcode) if args.ffmpeg_audio_transcode: streamlink.set_option(\"ffmpeg-audio-transcode\", args.ffmpeg_audio_transcode) if args.ffmpeg_copyts:", "Only load first available plugin config with ignored(NoPluginError): plugin =", "arguments.\"\"\" global args arglist = sys.argv[1:] # Load arguments from", "formatter, external=True, port=args.player_external_http_port) elif args.player_continuous_http and not file_output: return output_stream_http(plugin,", "or args.record_and_pipe): console.exit(\"Cannot use record options with other file output", "output if output: output.close() console.msg(\"Interrupted! Exiting...\") error_code = 130 finally:", "\" f\"Socks({socks_version}), \" f\"Websocket({websocket_version})\") def log_current_arguments(session, parser): global args if", "formatter) else: log.info(f\"Opening stream: {stream_name} ({stream_type})\") success = output_stream(stream, formatter)", "HTTP.\"\"\" global output if not external: if not args.player: console.exit(\"The", "args.json: console.msg_json(pluginlist) else: console.msg(f\"Loaded plugins: {pluginlist_formatted}\") def load_plugins(dirs: List[Path], showwarning:", "for s in args.stream): if stream_name in streams: stream =", "HTTP - Output stream data to selected output \"\"\" stream_name", "Only load first available default config for config_file in filter(lambda", "FileOutput) and output.fd is not stdout and (sys.stdout.isatty() or args.force_progress)", "streamlink.set_option(\"hds-live-edge\", args.hds_live_edge) if args.hls_live_edge: streamlink.set_option(\"hls-live-edge\", args.hls_live_edge) if args.hls_playlist_reload_attempts: streamlink.set_option(\"hls-playlist-reload-attempts\", args.hls_playlist_reload_attempts)", "name = next( # pragma: no branch (option for option", "= None log.info(\"Starting server, access with one of:\") for url", "subprocess reads from - A regular file \"\"\" if (args.output", "Load arguments from config files configs = [f\"@{config_file}\" for config_file", "A regular file \"\"\" if (args.output or args.stdout) and (args.record", "= check_file_output(formatter.filename(args.output, args.fs_safe_rules), args.force) elif args.stdout: out = FileOutput(fd=stdout) elif", "URL: {args.url}\") if args.default_stream and not args.stream and not args.json:", "to a player \" \"executable with --player.\") server = create_http_server()", "plugins.\"\"\" load_plugins(PLUGIN_DIRS, showwarning=False) if extra_plugin_dir: load_plugins([Path(path).expanduser() for path in extra_plugin_dir])", "when writing to output: {err}, exiting\") break except OSError as", "retry_streams = 1 retry_max = 0 if args.retry_streams: retry_streams =", "Continuously output the stream over HTTP - Output stream data", "for action in parser._actions: # find matching global argument if", "\"\"\"Sets the global HTTP settings, such as proxy and headers.\"\"\"", "if args.retry_max or args.retry_streams: retry_streams = 1 retry_max = 0", "player.\"\"\" global output filename = f'\"{stream_to_url(stream)}\"' output = PlayerOutput( args.player,", "= streamlink.load_plugins(str(directory)) if success and type(directory) is DeprecatedPath: log.info(f\"Loaded plugins", "logger.root.isEnabledFor(logging.DEBUG): return # macOS if sys.platform == \"darwin\": os_version =", "= any(getattr(args, attr) for attr in QUIET_OPTIONS) log_level = args.loglevel", "except OSError as err: console.exit(f\"Failed to create pipe: {err}\") elif", "setattr(action, \"plugins\", plugins) plugin.options = PluginOptions(defaults) def setup_plugin_options(session, plugin): \"\"\"Sets", "for how to migrate: {config_file}\") config_files.append(config_file) break if streamlink and", "filename=server.url, quiet=not args.verbose_player, title=formatter.title(args.title, defaults=DEFAULT_STREAM_METADATA) if args.title else args.url )", "streamlink.set_option(\"hls-segment-attempts\", args.hls_segment_attempts) if args.hls_segment_threads: streamlink.set_option(\"hls-segment-threads\", args.hls_segment_threads) if args.hls_segment_timeout: streamlink.set_option(\"hls-segment-timeout\", args.hls_segment_timeout)", "returned from stream\") return stream_fd, prebuffer def output_stream(stream, formatter: Formatter):", "streams = None if not streams: log.info(f\"Waiting for streams, retrying", "args.url ) try: log.info(f\"Starting player: {args.player}\") output.open() except OSError as", "if stream_type in args.player_passthrough and not file_output: log.info(f\"Opening stream: {stream_name}", "f\"Websocket({websocket_version})\") def log_current_arguments(session, parser): global args if not logger.root.isEnabledFor(logging.DEBUG): return", "default player (VLC) does not seem to be \" \"installed.", "PlayerOutput( args.player, args=args.player_args, filename=server.url, quiet=not args.verbose_player, title=formatter.title(args.title, defaults=DEFAULT_STREAM_METADATA) if args.title", "Force lowercase to allow case-insensitive lookup if args.stream: args.stream =", "output.\"\"\" is_player = isinstance(output, PlayerOutput) is_http = isinstance(output, HTTPServer) is_fifo", "file output\") if os.path.isfile(filename) and not force: if sys.stdin.isatty(): answer", "player\") read_stream(stream_fd, server, prebuffer, formatter) server.close(True) player.close() server.close() def output_stream_passthrough(stream,", "a directory!\") def setup_args(parser: argparse.ArgumentParser, config_files: List[Path] = None, ignore_unknown:", "if args.http_timeout: streamlink.set_option(\"http-timeout\", args.http_timeout) def setup_plugins(extra_plugin_dir=None): \"\"\"Loads any additional plugins.\"\"\"", "args.json: console.msg_json( stream, metadata=plugin.get_metadata() ) elif args.stream_url: try: console.msg(stream.to_url()) except", "console.exit(f\"Failed to start player: {args.player} ({err})\") return False return True", "args.http_query_param: streamlink.set_option(\"http-query-params\", dict(args.http_query_param)) if args.http_ignore_env: streamlink.set_option(\"http-trust-env\", False) if args.http_no_ssl_verify: streamlink.set_option(\"http-ssl-verify\",", "= plugin_args.add_argument_group(pname.capitalize()) for parg in plugin.arguments: if not parg.is_global: group.add_argument(parg.argument_name(pname),", "or is not a directory!\") def setup_args(parser: argparse.ArgumentParser, config_files: List[Path]", "args.hls_duration) if args.hls_live_restart: streamlink.set_option(\"hls-live-restart\", args.hls_live_restart) if args.rtmp_rtmpdump: streamlink.set_option(\"rtmp-rtmpdump\", args.rtmp_rtmpdump) elif", "= {} group = plugin_args.add_argument_group(pname.capitalize()) for parg in plugin.arguments: if", "HTTP server: {err}\") return http def iter_http_requests(server, player): \"\"\"Repeatedly accept", "success: break def fetch_streams(plugin): \"\"\"Fetches streams using correct parameters.\"\"\" return", "streams: log.info(f\"Available streams: {validstreams}\") handle_stream(plugin, streams, stream_name) return err =", "stream: {err}\") # Read 8192 bytes before proceeding to check", "if (args.output or args.stdout) and (args.record or args.record_and_pipe): console.exit(\"Cannot use", "elif args.json: console.msg_json( plugin=plugin.module, metadata=plugin.get_metadata(), streams=streams ) elif args.stream_url: try:", "8192 bytes from it. This is useful to check if", "filename.parent.mkdir(parents=True, exist_ok=True) streamhandler = logger.basicConfig( stream=stream, filename=filename, level=level, style=\"{\", format=(\"[{asctime}]\"", "no branch (option for option in action.option_strings if option.startswith(\"--\")), action.option_strings[0]", "streamlink_cli.console import ConsoleOutput, ConsoleUserInputRequester from streamlink_cli.constants import CONFIG_FILES, DEFAULT_STREAM_METADATA, LOG_DIR,", "synonyms and displays them next to the stream they point", "(sys.stdout.isatty() or args.force_progress) ) show_record_progress = ( hasattr(output, \"record\") and", "in case the main stream is not usable. alt_streams =", "args.ipv6) if args.ringbuffer_size: streamlink.set_option(\"ringbuffer-size\", args.ringbuffer_size) if args.mux_subtitles: streamlink.set_option(\"mux-subtitles\", args.mux_subtitles) if", "port=0): \"\"\"Continuously output the stream over HTTP.\"\"\" global output if", "in 10 sec\") sleep(10) continue except PluginError as err: log.error(f\"Unable", "def output_stream_http(plugin, initial_streams, formatter: Formatter, external=False, port=0): \"\"\"Continuously output the", "streamlink.set_option(\"http-stream-timeout\", args.http_stream_timeout) if args.rtmp_timeout: streamlink.set_option(\"rtmp-timeout\", args.rtmp_timeout) # generic stream- arguments", "plugins setup_plugins(args.plugin_dirs) setup_plugin_args(streamlink, parser) # call setup args again once", "\"time\": lambda: datetime.now() }, { \"time\": lambda dt, fmt: dt.strftime(fmt)", "args.ffmpeg_video_transcode) if args.ffmpeg_audio_transcode: streamlink.set_option(\"ffmpeg-audio-transcode\", args.ffmpeg_audio_transcode) if args.ffmpeg_copyts: streamlink.set_option(\"ffmpeg-copyts\", args.ffmpeg_copyts) if", "unknown and not ignore_unknown: msg = gettext(\"unrecognized arguments: %s\") parser.error(msg", "stream: {stream_name} ({type(stream).shortname()})\") stream_fd, prebuffer = open_stream(stream) except StreamError as", "def setup_plugin_options(session, plugin): \"\"\"Sets Streamlink plugin options.\"\"\" pname = plugin.module", "args.record_and_pipe: record = check_file_output(formatter.filename(args.record_and_pipe, args.fs_safe_rules), args.force) out = FileOutput(fd=stdout, record=record)", "for pname, plugin in session.plugins.items(): for parg in plugin.arguments: if", "\"\"\" if (args.output or args.stdout) and (args.record or args.record_and_pipe): console.exit(\"Cannot", "setup_args(parser) setup_config_args(parser) # update the logging level if changed by", "url in server.urls: log.info(\" \" + url) for req in", "streams: {validstreams}\") handle_stream(plugin, streams, stream_name) return err = f\"The specified", "( isinstance(output, FileOutput) and output.fd is not stdout and (sys.stdout.isatty()", "KeyboardInterrupt: error_code = 130 elif args.can_handle_url_no_redirect: try: streamlink.resolve_url_no_redirect(args.can_handle_url_no_redirect) except NoPluginError:", "call=True, quiet=not args.verbose_player, title=formatter.title(args.title, defaults=DEFAULT_STREAM_METADATA) if args.title else args.url )", "streams=streams, error=err ) else: console.exit(f\"{err}.\\n Available streams: {validstreams}\") elif args.json:", "or f'Enter {pname} {req.name}'}: \" session.set_plugin_option( pname, req.dest, console.askpass(prompt) if", "args.hls_segment_key_uri) if args.hls_audio_select: streamlink.set_option(\"hls-audio-select\", args.hls_audio_select) if args.hls_start_offset: streamlink.set_option(\"hls-start-offset\", args.hls_start_offset) if", "platform.platform() log.debug(f\"OS: {os_version}\") log.debug(f\"Python: {platform.python_version()}\") log.debug(f\"Streamlink: {streamlink_version}\") log.debug(f\"Requests({requests.__version__}), \" f\"Socks({socks_version}),", "as streamlink_version from streamlink.cache import Cache from streamlink.exceptions import FatalPluginError", "path {directory} does not exist or is not a directory!\")", "Could not open stream {stream} ({err})\") if not success_open: console.exit(f\"Could", "[f\"@{config_file}\" for config_file in config_files or []] args, unknown =", "- The stdout pipe - A subprocess' stdin pipe -", "else: streams = fetch_streams(plugin) except NoPluginError: console.exit(f\"No plugin can handle", "args.http_ssl_cert_crt_key: streamlink.set_option(\"http-ssl-cert\", tuple(args.http_ssl_cert_crt_key)) if args.http_timeout: streamlink.set_option(\"http-timeout\", args.http_timeout) def setup_plugins(extra_plugin_dir=None): \"\"\"Loads", "closed\") break try: output.write(data) except OSError as err: if is_player", "streams repeatedly until some are returned or limit hit.\"\"\" try:", "parg.dest if parg.is_global else parg.namespace_dest(pname)) session.set_plugin_option(pname, parg.dest, value) if not", "config files setup_config_args(parser, ignore_unknown=True) # Console output should be on", "to be passed to the player.\"\"\" global output filename =", "break else: log.info(\"Stream not available, will re-fetch streams in 10", "a list of all plugins Streamlink has loaded.\"\"\" pluginlist =", "config with ignored(NoPluginError): plugin = streamlink.resolve_url(args.url) for config_file in CONFIG_FILES:", "if args.hls_timeout: streamlink.set_option(\"hls-timeout\", args.hls_timeout) if args.http_stream_timeout: streamlink.set_option(\"http-stream-timeout\", args.http_stream_timeout) if args.rtmp_timeout:", "== 0: log.info(\"streamlink is running as root! Be careful!\") def", "\" validstreams = [] for name, stream in sorted(streams.items(), key=lambda", "def log_current_arguments(session, parser): global args if not logger.root.isEnabledFor(logging.DEBUG): return sensitive", "for stream_name in (resolve_stream_name(streams, s) for s in args.stream): if", "will re-fetch streams in 10 sec\") sleep(10) continue except PluginError", "\"subprocess_cmdline\", \"quiet\") args = None console: ConsoleOutput = None output:", "for directory in dirs: if directory.is_dir(): success = streamlink.load_plugins(str(directory)) if", "except OSError as err: console.exit(f\"Failed to create HTTP server: {err}\")", "continue except PluginError as err: log.error(f\"Unable to fetch new streams:", "parser = build_parser() setup_args(parser, ignore_unknown=True) # call argument set up", "output.player.poll() if output.player.returncode is not None: log.info(\"Player closed\") break try:", "cmdline = stream.cmdline() except StreamError as err: console.exit(err) console.msg(cmdline) else:", "from pathlib import Path from time import sleep from typing", "Console output should be on stderr if we are outputting", "collections import OrderedDict from contextlib import closing from distutils.version import", "args.ffmpeg_verbose_path) if args.ffmpeg_fout: streamlink.set_option(\"ffmpeg-fout\", args.ffmpeg_fout) if args.ffmpeg_video_transcode: streamlink.set_option(\"ffmpeg-video-transcode\", args.ffmpeg_video_transcode) if", "f\"{datetime.now()}.log\" elif filename: filename = Path(filename).expanduser().resolve() if filename: filename.parent.mkdir(parents=True, exist_ok=True)", "since the named pipe is not # automatically closed by", "else \"none\" log_file = args.logfile if log_level != \"none\" else", "distutils.version import StrictVersion from functools import partial from gettext import", "prompt = f\"{req.prompt or f'Enter {pname} {req.name}'}: \" session.set_plugin_option( pname,", "title=formatter.title(args.title, defaults=DEFAULT_STREAM_METADATA) if args.title else args.url ) try: log.info(f\"Starting player:", "import partial from gettext import gettext from itertools import chain", "data = res.json() latest_version = data.get(\"info\").get(\"version\") cache.set(\"latest_version\", latest_version, (60 *", "(60 * 60 * 6)) elif force: log.info(f\"Your Streamlink version", "args.ffmpeg_start_at_zero: streamlink.set_option(\"ffmpeg-start-at-zero\", args.ffmpeg_start_at_zero) streamlink.set_option(\"subprocess-errorlog\", args.subprocess_errorlog) streamlink.set_option(\"subprocess-errorlog-path\", args.subprocess_errorlog_path) streamlink.set_option(\"locale\", args.locale) def", "server: {err}\") return http def iter_http_requests(server, player): \"\"\"Repeatedly accept HTTP", "bytes before proceeding to check for errors. # This is", "command-line if this stream # uses a subprocess. if args.subprocess_cmdline:", "stream data to selected output \"\"\" stream_name = resolve_stream_name(streams, stream_name)", "to a URL\") else: validstreams = format_valid_streams(plugin, streams) console.msg(f\"Available streams:", "else: log.info(\"Stream not available, will re-fetch streams in 10 sec\")", "these: - The stdout pipe - A subprocess' stdin pipe", "streamlink.resolve_url_no_redirect(args.can_handle_url_no_redirect) except NoPluginError: error_code = 1 except KeyboardInterrupt: error_code =", "args.player_external_http: return output_stream_http(plugin, streams, formatter, external=True, port=args.player_external_http_port) elif args.player_continuous_http and", "streamlink.cache import Cache from streamlink.exceptions import FatalPluginError from streamlink.plugin import", "= None log = logging.getLogger(\"streamlink.cli\") def get_formatter(plugin: Plugin): return Formatter(", "Streamlink = None log = logging.getLogger(\"streamlink.cli\") def get_formatter(plugin: Plugin): return", "real stream name of a synonym.\"\"\" if stream_name in STREAM_SYNONYMS", "= f\"{name} ({joined})\" validstreams.append(name) return delimiter.join(validstreams) def handle_url(): \"\"\"The URL", "if args.retry_streams: retry_streams = args.retry_streams if args.retry_max: retry_max = args.retry_max", "logging level if changed by a plugin specific config log_level", "bool = True): \"\"\"Attempts to load plugins from a list", "a stream actually has data before opening the output. \"\"\"", "a valid one, otherwise output list of valid streams. \"\"\"", "= streams[stream_name] break else: log.info(\"Stream not available, will re-fetch streams", "= config_file.with_name(f\"{config_file.name}.{plugin.module}\") if not config_file.is_file(): continue if type(config_file) is DeprecatedPath:", "player or player.running): try: streams = initial_streams or fetch_streams(plugin) initial_streams", "actually has data before opening the output. \"\"\" global stream_fd", "and err.errno in ACCEPTABLE_ERRNO: log.info(\"HTTP connection closed\") else: console.exit(f\"Error when", "(sys.stdout.isatty() or args.force_progress) ) stream_iterator = chain( [prebuffer], iter(partial(stream.read, chunk_size),", "= 130 elif args.url: try: setup_options() handle_url() except KeyboardInterrupt: #", "8192 bytes before proceeding to check for errors. # This", "We need to check if the player process still exists", "migrate: {config_file}\") config_files.append(config_file) break if streamlink and args.url: # Only", "if streamlink and args.url: # Only load first available plugin", "file already exists and ask the user if it should", "as possible to load args from config files setup_config_args(parser, ignore_unknown=True)", "generic stream- arguments take precedence over deprecated stream-type arguments if", "settings, such as proxy and headers.\"\"\" if args.http_proxy: streamlink.set_option(\"http-proxy\", args.http_proxy)", "alt_streams: stream = streams[stream_name] stream_type = type(stream).shortname() if stream_type in", "getattr(args, action.dest) if action.default != value: name = next( #", "opening the output unnecessarily. try: log.debug(\"Pre-buffering 8192 bytes\") prebuffer =", "or not latest_version: res = requests.get(\"https://pypi.python.org/pypi/streamlink/json\") data = res.json() latest_version", "\"\"\"Show current installed versions\"\"\" if not logger.root.isEnabledFor(logging.DEBUG): return # macOS", "parser.parse_known_args(configs + arglist) if unknown and not ignore_unknown: msg =", "return plugin.streams(stream_types=args.stream_types, sorting_excludes=args.stream_sorting_excludes) def fetch_streams_with_retry(plugin, interval, count): \"\"\"Attempts to fetch", "stream_name + \"_alt\" in k, sorted(streams.keys()))) file_output = args.output or", "if stream_fd and prebuffer: log.debug(\"Writing stream to player\") read_stream(stream_fd, server,", "in sorted(streams.items(), key=lambda stream: plugin.stream_weight(stream[0])): if name in STREAM_SYNONYMS: continue", "initial_streams or fetch_streams(plugin) initial_streams = None for stream_name in (resolve_stream_name(streams,", "fetch_streams(plugin) except FatalPluginError: raise except PluginError as err: log.error(err) if", "as logger from streamlink import NoPluginError, PluginError, StreamError, Streamlink, __version__", "success = output_stream(stream, formatter) if success: break def fetch_streams(plugin): \"\"\"Fetches", "the Streamlink session.\"\"\" global streamlink streamlink = Streamlink({\"user-input-requester\": ConsoleUserInputRequester(console)}) def", "Formatter( { \"url\": lambda: args.url, \"author\": lambda: plugin.get_author(), \"category\": lambda:", "* 6)) elif force: log.info(f\"Your Streamlink version ({installed_version}) is up", "ignore_unknown=False): config_files = [] if args.config: # We want the", "in config_files or []] args, unknown = parser.parse_known_args(configs + arglist)", "or []] args, unknown = parser.parse_known_args(configs + arglist) if unknown", "if args.stream_segment_threads: streamlink.set_option(\"stream-segment-threads\", args.stream_segment_threads) if args.stream_segment_timeout: streamlink.set_option(\"stream-segment-timeout\", args.stream_segment_timeout) if args.stream_timeout:", "not hasattr(args, action.dest): continue value = getattr(args, action.dest) if action.default", "You must specify the path to a player \" \"executable", "to check if the player process still exists when #", "= None if not streams: log.info(f\"Waiting for streams, retrying every", "msg = gettext(\"unrecognized arguments: %s\") parser.error(msg % \" \".join(unknown)) #", "console.msg(stream.to_url()) except TypeError: console.exit(\"The stream specified cannot be translated to", "as err: if is_player and err.errno in ACCEPTABLE_ERRNO: log.info(\"Player closed\")", "valid streams. \"\"\" try: plugin = streamlink.resolve_url(args.url) setup_plugin_options(streamlink, plugin) log.info(f\"Found", "argument set up as early as possible to load args", "OSError as err: console.exit(f\"Failed to start player: {args.player} ({err})\") else:", "HTTPServer() http.bind(*_args, **_kwargs) except OSError as err: console.exit(f\"Failed to create", "> 0: attempts += 1 if attempts >= count: break", "{ \"url\": lambda: args.url, \"author\": lambda: plugin.get_author(), \"category\": lambda: plugin.get_category(),", "from distutils.version import StrictVersion from functools import partial from gettext", "args.stream_url: try: console.msg(stream.to_url()) except TypeError: console.exit(\"The stream specified cannot be", "Be careful!\") def log_current_versions(): \"\"\"Show current installed versions\"\"\" if not", "global output filename = f'\"{stream_to_url(stream)}\"' output = PlayerOutput( args.player, args=args.player_args,", "not file_output: return output_stream_http(plugin, streams, formatter) else: log.info(f\"Opening stream: {stream_name}", "parg in plugin.arguments: if not parg.is_global: group.add_argument(parg.argument_name(pname), **parg.options) defaults[parg.dest] =", "import Cache from streamlink.exceptions import FatalPluginError from streamlink.plugin import Plugin,", "= PlayerOutput( args.player, args=args.player_args, quiet=not args.verbose_player, kill=not args.player_no_close, namedpipe=namedpipe, http=http,", "with ignored(NoPluginError): plugin = streamlink.resolve_url(args.url) for config_file in CONFIG_FILES: config_file", "file output options.\") if args.output: if args.output == \"-\": out", "from streamlink_cli.console import ConsoleOutput, ConsoleUserInputRequester from streamlink_cli.constants import CONFIG_FILES, DEFAULT_STREAM_METADATA,", "errno.EINVAL, errno.ECONNRESET) try: ACCEPTABLE_ERRNO += (errno.WSAECONNABORTED,) except AttributeError: pass #", "player: {args.player}\") if player: player.open() except OSError as err: console.exit(f\"Failed", "JSON represenation - Continuously output the stream over HTTP -", "FileOutput(fd=stdout) elif args.record_and_pipe: record = check_file_output(formatter.filename(args.record_and_pipe, args.fs_safe_rules), args.force) out =", "for action in parser._actions: if not hasattr(args, action.dest): continue value", "of valid streams. \"\"\" try: plugin = streamlink.resolve_url(args.url) setup_plugin_options(streamlink, plugin)", "args.fs_safe_rules), args.force) out = FileOutput(fd=stdout, record=record) else: http = namedpipe", "= list(filter(synonymfilter, streams.keys())) if len(synonyms) > 0: joined = delimiter.join(synonyms)", "headers.\"\"\" if args.http_proxy: streamlink.set_option(\"http-proxy\", args.http_proxy) if args.https_proxy: streamlink.set_option(\"https-proxy\", args.https_proxy) if", "in args.stream: if stream_name in streams: log.info(f\"Available streams: {validstreams}\") handle_stream(plugin,", "the stream to output.\"\"\" global output success_open = False for", "streams = fetch_streams(plugin) except PluginError as err: log.error(err) streams =", "prebuffer def output_stream(stream, formatter: Formatter): \"\"\"Open stream, create output and", "showwarning=False) if extra_plugin_dir: load_plugins([Path(path).expanduser() for path in extra_plugin_dir]) def setup_streamlink():", "FileOutput(fd=stdout) else: out = check_file_output(formatter.filename(args.output, args.fs_safe_rules), args.force) elif args.stdout: out", "stream name of a synonym.\"\"\" if stream_name in STREAM_SYNONYMS and", "elif args.stream_url: try: console.msg(stream.to_url()) except TypeError: console.exit(\"The stream specified cannot", "- Output internal command-line - Output JSON represenation - Continuously", "player \" \"executable with --player.\") server = create_http_server() player =", "{args.player}\") output.open() except OSError as err: console.exit(f\"Failed to start player:", "path.is_file(), CONFIG_FILES): if type(config_file) is DeprecatedPath: log.info(f\"Loaded config from deprecated", "{platform.mac_ver()[0]}\" # Windows elif sys.platform == \"win32\": os_version = f\"{platform.system()}", "isinstance(output.record, FileOutput) and output.record.fd is not stdout and (sys.stdout.isatty() or", "hit.\"\"\" try: streams = fetch_streams(plugin) except PluginError as err: log.error(err)", "manual at https://streamlink.github.io\" ) sys.exit(error_code) def parser_helper(): session = Streamlink()", "global argument plugins = getattr(action, \"plugins\", []) plugins.append(pname) setattr(action, \"plugins\",", "http = HTTPServer() http.bind(*_args, **_kwargs) except OSError as err: console.exit(f\"Failed", "output.\"\"\" global output success_open = False for i in range(args.retry_open):", "error and the arguments cannot be parsed\") break if required:", "{validstreams}\") elif args.json: console.msg_json( plugin=plugin.module, metadata=plugin.get_metadata(), streams=streams ) elif args.stream_url:", "formatter) return True def read_stream(stream, output, prebuffer, formatter: Formatter, chunk_size=8192):", "if not external: if not args.player: console.exit(\"The default player (VLC)", "datefmt=\"%H:%M:%S\" + (\".%f\" if level == \"trace\" else \"\") )", "http = create_http_server() if args.record: record = check_file_output(formatter.filename(args.record, args.fs_safe_rules), args.force)", "and ask the user if it should be overwritten if", "latest_version = StrictVersion(latest_version) if latest_version > installed_version: log.info(f\"A new version", "= open_stream(stream) except StreamError as err: log.error(err) if stream_fd and", "errno import logging import os import platform import signal import", "if output.player.returncode is not None: log.info(\"Player closed\") break try: output.write(data)", "output_stream_http(plugin, initial_streams, formatter: Formatter, external=False, port=0): \"\"\"Continuously output the stream", "server.urls: log.info(\" \" + url) for req in iter_http_requests(server, player):", "be one of these: - The stdout pipe - A", "CONFIG_FILES): if type(config_file) is DeprecatedPath: log.info(f\"Loaded config from deprecated path,", "args.locale) def setup_plugin_args(session, parser): \"\"\"Sets Streamlink plugin options.\"\"\" plugin_args =", "to fetch streams repeatedly until some are returned or limit", "directories.\"\"\" for directory in dirs: if directory.is_dir(): success = streamlink.load_plugins(str(directory))", "from streamlink_cli.compat import DeprecatedPath, is_win32, stdout from streamlink_cli.console import ConsoleOutput,", "except TypeError: console.exit(\"The stream specified cannot be translated to a", "if args.hls_segment_attempts: streamlink.set_option(\"hls-segment-attempts\", args.hls_segment_attempts) if args.hls_segment_threads: streamlink.set_option(\"hls-segment-threads\", args.hls_segment_threads) if args.hls_segment_timeout:", "check_file_output(formatter.filename(args.output, args.fs_safe_rules), args.force) elif args.stdout: out = FileOutput(fd=stdout) elif args.record_and_pipe:", "what to do with the selected stream. Depending on arguments", "or limit hit.\"\"\" try: streams = fetch_streams(plugin) except PluginError as", "= format_valid_streams(plugin, streams) for stream_name in args.stream: if stream_name in", "({err})\") else: console.exit(f\"Failed to open output: {output.filename} ({err})\") with closing(output):", "stream_name = resolve_stream_name(streams, stream_name) stream = streams[stream_name] # Print internal", "setup_args(parser, config_files, ignore_unknown=ignore_unknown) def setup_signals(): # Handle SIGTERM just like", "global stream_fd # Attempts to open the stream try: stream_fd", "plugin_args.add_argument_group(pname.capitalize()) for parg in plugin.arguments: if not parg.is_global: group.add_argument(parg.argument_name(pname), **parg.options)", "listen on a random high port. \"\"\" try: http =", "json) def main(): error_code = 0 parser = build_parser() setup_args(parser,", "return output_stream_http(plugin, streams, formatter, external=True, port=args.player_external_http_port) elif args.player_continuous_http and not", "to output\") read_stream(stream_fd, output, prebuffer, formatter) return True def read_stream(stream,", "force): \"\"\"Checks if file already exists and ask the user", "\") if answer.lower() != \"y\": sys.exit() else: log.error(f\"File {filename} already", "NamedPipe() except OSError as err: console.exit(f\"Failed to create pipe: {err}\")", "output_stream(stream, formatter) if success: break def fetch_streams(plugin): \"\"\"Fetches streams using", "= list(streamlink.get_plugins().keys()) pluginlist_formatted = \", \".join(sorted(pluginlist)) if args.json: console.msg_json(pluginlist) else:", "if name not in sensitive else '*' * 8}\") def", "specific config log_level = args.loglevel if not silent_log else \"none\"", "or \"unknown player\" log.info(f\"Got HTTP request from {user_agent}\") stream_fd =", "if is_win32 and is_fifo: output.player.poll() if output.player.returncode is not None:", "for i in range(args.retry_open): try: stream_fd, prebuffer = open_stream(stream) success_open", "the required arguments are not set if parg.required or value:", "a configuration error and the arguments cannot be parsed\") break", "if file already exists and ask the user if it", "player): user_agent = req.headers.get(\"User-Agent\") or \"unknown player\" log.info(f\"Got HTTP request", "= getattr(action, \"plugins\", []) plugins.append(pname) setattr(action, \"plugins\", plugins) plugin.options =", "plugin.streams(stream_types=args.stream_types, sorting_excludes=args.stream_sorting_excludes) def fetch_streams_with_retry(plugin, interval, count): \"\"\"Attempts to fetch streams", "return sensitive = set() for pname, plugin in session.plugins.items(): for", "print_plugins(): \"\"\"Outputs a list of all plugins Streamlink has loaded.\"\"\"", "can be one of these: - The stdout pipe -", "path, see CLI docs for how to migrate: {config_file}\") config_files.append(config_file)", "installed_version: log.info(f\"A new version of Streamlink ({latest_version}) is available!\") cache.set(\"version_info_printed\",", "console.exit(f\"Error when writing to output: {err}, exiting\") break except OSError", "options with other file output options.\") if args.output: if args.output", "server, prebuffer, formatter) server.close(True) player.close() server.close() def output_stream_passthrough(stream, formatter: Formatter):", "= output_stream(stream, formatter) if success: break def fetch_streams(plugin): \"\"\"Fetches streams", "global args if not logger.root.isEnabledFor(logging.DEBUG): return sensitive = set() for", "next( # pragma: no branch (option for option in action.option_strings", "setup_config_args(parser) # update the logging level if changed by a", "= requests.get(\"https://pypi.python.org/pypi/streamlink/json\") data = res.json() latest_version = data.get(\"info\").get(\"version\") cache.set(\"latest_version\", latest_version,", "attr) for attr in QUIET_OPTIONS) log_level = args.loglevel if not", "args.ringbuffer_size) if args.mux_subtitles: streamlink.set_option(\"mux-subtitles\", args.mux_subtitles) if args.hds_live_edge: streamlink.set_option(\"hds-live-edge\", args.hds_live_edge) if", "not args.player: console.exit(\"The default player (VLC) does not seem to", "= initial_streams or fetch_streams(plugin) initial_streams = None for stream_name in", "\"\"\"Attempts to load plugins from a list of directories.\"\"\" for", "specified cannot be translated to a URL\") # Output the", "try: streamlink.resolve_url(args.can_handle_url) except NoPluginError: error_code = 1 except KeyboardInterrupt: error_code", "Handle SIGTERM just like SIGINT signal.signal(signal.SIGTERM, signal.default_int_handler) def setup_http_session(): \"\"\"Sets", "stream is not usable. alt_streams = list(filter(lambda k: stream_name +", "if not args.url and args.url_param: args.url = args.url_param def setup_config_args(parser,", "plugin.get_category(), \"title\": lambda: plugin.get_title(), \"time\": lambda: datetime.now() }, { \"time\":", "args.hds_timeout) if args.hls_segment_attempts: streamlink.set_option(\"hls-segment-attempts\", args.hls_segment_attempts) if args.hls_segment_threads: streamlink.set_option(\"hls-segment-threads\", args.hls_segment_threads) if", "args.json: console.msg_json( plugin=plugin.module, metadata=plugin.get_metadata(), streams=streams, error=err ) else: console.exit(f\"{err}.\\n Available", "if directory.is_dir(): success = streamlink.load_plugins(str(directory)) if success and type(directory) is", "stream\") return stream_fd, prebuffer def output_stream(stream, formatter: Formatter): \"\"\"Open stream,", "console.msg_json(pluginlist) else: console.msg(f\"Loaded plugins: {pluginlist_formatted}\") def load_plugins(dirs: List[Path], showwarning: bool", "log.warning(f\"Plugin path {directory} does not exist or is not a", "load first available plugin config with ignored(NoPluginError): plugin = streamlink.resolve_url(args.url)", "- A named pipe that the subprocess reads from -", "elif args.player_continuous_http and not file_output: return output_stream_http(plugin, streams, formatter) else:", "pname = plugin.module required = OrderedDict({}) for parg in plugin.arguments:", "args.http_stream_timeout) if args.rtmp_timeout: streamlink.set_option(\"rtmp-timeout\", args.rtmp_timeout) # generic stream- arguments take", "if args.ffmpeg_audio_transcode: streamlink.set_option(\"ffmpeg-audio-transcode\", args.ffmpeg_audio_transcode) if args.ffmpeg_copyts: streamlink.set_option(\"ffmpeg-copyts\", args.ffmpeg_copyts) if args.ffmpeg_start_at_zero:", "partial from gettext import gettext from itertools import chain from", "attempt # to use these in case the main stream", "stdout from streamlink_cli.console import ConsoleOutput, ConsoleUserInputRequester from streamlink_cli.constants import CONFIG_FILES,", "before proceeding to check for errors. # This is to", "console.exit(err) if not streams: console.exit(f\"No playable streams found on this", "args.config: # We want the config specified last to get", "matching global argument if pargdest != action.dest: continue defaults[pargdest] =", "log.info(f\"A new version of Streamlink ({latest_version}) is available!\") cache.set(\"version_info_printed\", True,", "StreamError(\"No data returned from stream\") return stream_fd, prebuffer def output_stream(stream,", "stream_name in STREAM_SYNONYMS and stream_name in streams: for name, stream", "to check if a stream actually has data before opening", "is not usable. alt_streams = list(filter(lambda k: stream_name + \"_alt\"", "filename = f'\"{stream_to_url(stream)}\"' output = PlayerOutput( args.player, args=args.player_args, filename=filename, call=True,", "empty, listen on all available interfaces, and if port is", "stream.close() log.info(\"Stream ended\") def handle_stream(plugin, streams, stream_name): \"\"\"Decides what to", "before opening the output. \"\"\" global stream_fd # Attempts to", "* 60 * 24)) version_info_printed = cache.get(\"version_info_printed\") if not force", "how to migrate: {config_file}\") config_files.append(config_file) break if config_files: setup_args(parser, config_files,", "should be overwritten if it does.\"\"\" log.debug(\"Checking file output\") if", "StreamIO = None streamlink: Streamlink = None log = logging.getLogger(\"streamlink.cli\")", "output: {output.filename} ({err})\") with closing(output): log.debug(\"Writing stream to output\") read_stream(stream_fd,", "= (\"json\", \"stream_url\", \"subprocess_cmdline\", \"quiet\") args = None console: ConsoleOutput", "req in iter_http_requests(server, player): user_agent = req.headers.get(\"User-Agent\") or \"unknown player\"", "plugin.stream_weight(stream[0])): if name in STREAM_SYNONYMS: continue def synonymfilter(n): return stream", "synonymfilter(n): return stream is streams[n] and n is not name", "parg.required or value: try: for rparg in plugin.arguments.requires(parg.name): required[rparg.name] =", "stream, metadata=plugin.get_metadata() ) elif args.stream_url: try: console.msg(stream.to_url()) except TypeError: console.exit(\"The", "player.close() server.close() def output_stream_passthrough(stream, formatter: Formatter): \"\"\"Prepares a filename to", "StreamIO, StreamProcess from streamlink.utils.named_pipe import NamedPipe from streamlink_cli.argparser import build_parser", "= list(filter(lambda k: stream_name + \"_alt\" in k, sorted(streams.keys()))) file_output", "args.rtmp_proxy: streamlink.set_option(\"rtmp-proxy\", args.rtmp_proxy) # deprecated if args.hds_segment_attempts: streamlink.set_option(\"hds-segment-attempts\", args.hds_segment_attempts) if", "required = OrderedDict({}) for parg in plugin.arguments: if parg.options.get(\"help\") ==", "STREAM_SYNONYMS: return name return stream_name def format_valid_streams(plugin, streams): \"\"\"Formats a", "plugin options.\"\"\" pname = plugin.module required = OrderedDict({}) for parg", "log.debug(\"Writing stream to output\") read_stream(stream_fd, output, prebuffer, formatter) return True", "StrictVersion(latest_version) if latest_version > installed_version: log.info(f\"A new version of Streamlink", "to see if any of the required arguments are not", "not args.json: args.stream = args.default_stream if args.stream: validstreams = format_valid_streams(plugin,", "config specified last to get highest priority for config_file in", "= True break except StreamError as err: log.error(f\"Try {i +", "return installed_version = StrictVersion(streamlink.version) latest_version = StrictVersion(latest_version) if latest_version >", "streamlink_cli.compat import DeprecatedPath, is_win32, stdout from streamlink_cli.console import ConsoleOutput, ConsoleUserInputRequester", "%s\") parser.error(msg % \" \".join(unknown)) # Force lowercase to allow", "args.stream_timeout) if args.ffmpeg_ffmpeg: streamlink.set_option(\"ffmpeg-ffmpeg\", args.ffmpeg_ffmpeg) if args.ffmpeg_verbose: streamlink.set_option(\"ffmpeg-verbose\", args.ffmpeg_verbose) if", "second(s)\") attempts = 0 while not streams: sleep(interval) try: streams", "args.title else args.url ) return out def create_http_server(*_args, **_kwargs): \"\"\"Creates", "stream_name): \"\"\"Returns the real stream name of a synonym.\"\"\" if", "action.dest): continue value = getattr(args, action.dest) if action.default != value:", "to migrate: {config_file}\") config_files.append(config_file) break if streamlink and args.url: #", "player\" log.info(f\"Got HTTP request from {user_agent}\") stream_fd = prebuffer =", "== \"win32\": os_version = f\"{platform.system()} {platform.release()}\" # Linux / other", "synonyms = list(filter(synonymfilter, streams.keys())) if len(synonyms) > 0: joined =", "== \"trace\" else \"\") + \"[{name}][{levelname}] {message}\", datefmt=\"%H:%M:%S\" + (\".%f\"", "not name synonyms = list(filter(synonymfilter, streams.keys())) if len(synonyms) > 0:", "be on stderr if we are outputting # a stream", "reversed(args.config)): if config_file.is_file(): config_files.append(config_file) else: # Only load first available", "on plugin.stream_weight). \"\"\" delimiter = \", \" validstreams = []", "the arguments cannot be parsed\") break if required: for req", "args.url: # Only load first available plugin config with ignored(NoPluginError):", "open_stream(stream) except StreamError as err: log.error(err) if stream_fd and prebuffer:", "= stream.open() except StreamError as err: raise StreamError(f\"Could not open", "req.dest, console.askpass(prompt) if req.sensitive else console.ask(prompt) ) def log_root_warning(): if", "args.url: try: setup_options() handle_url() except KeyboardInterrupt: # Close output if", "if args.hds_timeout: streamlink.set_option(\"hds-timeout\", args.hds_timeout) if args.hls_segment_attempts: streamlink.set_option(\"hls-segment-attempts\", args.hls_segment_attempts) if args.hls_segment_threads:", "args.ffmpeg_ffmpeg) if args.ffmpeg_verbose: streamlink.set_option(\"ffmpeg-verbose\", args.ffmpeg_verbose) if args.ffmpeg_verbose_path: streamlink.set_option(\"ffmpeg-verbose-path\", args.ffmpeg_verbose_path) if", "output = PlayerOutput( args.player, args=args.player_args, filename=filename, call=True, quiet=not args.verbose_player, title=formatter.title(args.title,", "for config_file in CONFIG_FILES: config_file = config_file.with_name(f\"{config_file.name}.{plugin.module}\") if not config_file.is_file():", "chain( [prebuffer], iter(partial(stream.read, chunk_size), b\"\") ) if show_progress: stream_iterator =", "\"trace\" else \"\") ) console = ConsoleOutput(streamhandler.stream, json) def main():", "= ( hasattr(output, \"record\") and isinstance(output.record, FileOutput) and output.record.fd is", "progress, stream_to_url ACCEPTABLE_ERRNO = (errno.EPIPE, errno.EINVAL, errno.ECONNRESET) try: ACCEPTABLE_ERRNO +=", "is streams[stream_name] and name not in STREAM_SYNONYMS: return name return", "stream actually has data before opening the output. \"\"\" global", "not stdout and (sys.stdout.isatty() or args.force_progress) ) show_record_progress = (", "parg.options.get(\"help\") == argparse.SUPPRESS: continue value = getattr(args, parg.dest if parg.is_global", "the value is set, check to see if any of", "if args.ringbuffer_size: streamlink.set_option(\"ringbuffer-size\", args.ringbuffer_size) if args.mux_subtitles: streamlink.set_option(\"mux-subtitles\", args.mux_subtitles) if args.hds_live_edge:", "or args.stdout formatter = get_formatter(plugin) for stream_name in [stream_name] +", "is to avoid opening the output unnecessarily. try: log.debug(\"Pre-buffering 8192", "are sorted according to their quality (based on plugin.stream_weight). \"\"\"", "options or read the manual at https://streamlink.github.io\" ) sys.exit(error_code) def", "found\" if args.json: console.msg_json( plugin=plugin.module, metadata=plugin.get_metadata(), streams=streams, error=err ) else:", "log_file = args.logfile if log_level != \"none\" else None setup_logger_and_console(console_out,", "sorted(streams.keys()))) file_output = args.output or args.stdout formatter = get_formatter(plugin) for", "out = check_file_output(formatter.filename(args.output, args.fs_safe_rules), args.force) elif args.stdout: out = FileOutput(fd=stdout)", "if args.json: console.msg_json( plugin=plugin.module, metadata=plugin.get_metadata(), streams=streams, error=err ) else: console.exit(f\"{err}.\\n", "except OSError as err: if is_player and err.errno in ACCEPTABLE_ERRNO:", "be overwritten if it does.\"\"\" log.debug(\"Checking file output\") if os.path.isfile(filename)", "one of:\") for url in server.urls: log.info(\" \" + url)", "user_agent = req.headers.get(\"User-Agent\") or \"unknown player\" log.info(f\"Got HTTP request from", "err: stream_fd.close() raise StreamError(f\"Failed to read data from stream: {err}\")", "dt, fmt: dt.strftime(fmt) } ) def check_file_output(filename, force): \"\"\"Checks if", "namedpipe = record = None if not args.player: console.exit(\"The default", "and finally write the stream to output.\"\"\" global output success_open", "= f\"macOS {platform.mac_ver()[0]}\" # Windows elif sys.platform == \"win32\": os_version", "args.hls_segment_threads) if args.hls_segment_timeout: streamlink.set_option(\"hls-segment-timeout\", args.hls_segment_timeout) if args.hls_timeout: streamlink.set_option(\"hls-timeout\", args.hls_timeout) if", "args.record: record = check_file_output(formatter.filename(args.record, args.fs_safe_rules), args.force) log.info(f\"Starting player: {args.player}\") out", "args.ffmpeg_video_transcode: streamlink.set_option(\"ffmpeg-video-transcode\", args.ffmpeg_video_transcode) if args.ffmpeg_audio_transcode: streamlink.set_option(\"ffmpeg-audio-transcode\", args.ffmpeg_audio_transcode) if args.ffmpeg_copyts: streamlink.set_option(\"ffmpeg-copyts\",", "setup_signals() setup_streamlink() # load additional plugins setup_plugins(args.plugin_dirs) setup_plugin_args(streamlink, parser) #", "= parg.dest for action in parser._actions: # find matching global", "using correct parameters.\"\"\" return plugin.streams(stream_types=args.stream_types, sorting_excludes=args.stream_sorting_excludes) def fetch_streams_with_retry(plugin, interval, count):", "if args.hds_live_edge: streamlink.set_option(\"hds-live-edge\", args.hds_live_edge) if args.hls_live_edge: streamlink.set_option(\"hls-live-edge\", args.hls_live_edge) if args.hls_playlist_reload_attempts:", "the path to a player \" \"executable with --player.\") server", "streamlink.set_option(\"stream-segment-timeout\", args.stream_segment_timeout) if args.stream_timeout: streamlink.set_option(\"stream-timeout\", args.stream_timeout) if args.ffmpeg_ffmpeg: streamlink.set_option(\"ffmpeg-ffmpeg\", args.ffmpeg_ffmpeg)", "streamlink.set_option(\"hls-timeout\", args.hls_timeout) if args.http_stream_timeout: streamlink.set_option(\"http-stream-timeout\", args.http_stream_timeout) if args.rtmp_timeout: streamlink.set_option(\"rtmp-timeout\", args.rtmp_timeout)", "from a list of directories.\"\"\" for directory in dirs: if", "streamlink.set_option(\"ffmpeg-copyts\", args.ffmpeg_copyts) if args.ffmpeg_start_at_zero: streamlink.set_option(\"ffmpeg-start-at-zero\", args.ffmpeg_start_at_zero) streamlink.set_option(\"subprocess-errorlog\", args.subprocess_errorlog) streamlink.set_option(\"subprocess-errorlog-path\", args.subprocess_errorlog_path)", "(args.output or args.stdout) and (args.record or args.record_and_pipe): console.exit(\"Cannot use record", "file_output = args.output or args.stdout formatter = get_formatter(plugin) for stream_name", "first available default config for config_file in filter(lambda path: path.is_file(),", "streamlink.exceptions import FatalPluginError from streamlink.plugin import Plugin, PluginOptions from streamlink.stream", "in [stream_name] + alt_streams: stream = streams[stream_name] stream_type = type(stream).shortname()", "if args.title else args.url ) try: log.info(f\"Starting player: {args.player}\") output.open()", "in range(args.retry_open): try: stream_fd, prebuffer = open_stream(stream) success_open = True", "Output = None plugin: Plugin = None stream_fd: StreamIO =", "# Print internal command-line if this stream # uses a", "log.info(f\"Opening stream: {stream_name} ({stream_type})\") success = output_stream_passthrough(stream, formatter) elif args.player_external_http:", "args.stream_timeout: streamlink.set_option(\"stream-timeout\", args.stream_timeout) if args.ffmpeg_ffmpeg: streamlink.set_option(\"ffmpeg-ffmpeg\", args.ffmpeg_ffmpeg) if args.ffmpeg_verbose: streamlink.set_option(\"ffmpeg-verbose\",", "update the logging level if changed by a plugin specific", "None if not args.player: console.exit(\"The default player (VLC) does not", "chunk_size), b\"\") ) if show_progress: stream_iterator = progress( stream_iterator, prefix=os.path.basename(output.filename)", "from config files configs = [f\"@{config_file}\" for config_file in config_files", "for config_file in map(lambda path: Path(path).expanduser(), reversed(args.config)): if config_file.is_file(): config_files.append(config_file)", "({latest_version}) is available!\") cache.set(\"version_info_printed\", True, (60 * 60 * 6))", "from streamlink_cli.constants import CONFIG_FILES, DEFAULT_STREAM_METADATA, LOG_DIR, PLUGIN_DIRS, STREAM_SYNONYMS from streamlink_cli.output", "fetch_streams(plugin): \"\"\"Fetches streams using correct parameters.\"\"\" return plugin.streams(stream_types=args.stream_types, sorting_excludes=args.stream_sorting_excludes) def", "import FileOutput, Output, PlayerOutput from streamlink_cli.utils import Formatter, HTTPServer, datetime,", "OrderedDict({}) for parg in plugin.arguments: if parg.options.get(\"help\") == argparse.SUPPRESS: continue", "break except OSError as err: console.exit(f\"Error when reading from stream:", "stream: plugin.stream_weight(stream[0])): if name in STREAM_SYNONYMS: continue def synonymfilter(n): return", "/ f\"{datetime.now()}.log\" elif filename: filename = Path(filename).expanduser().resolve() if filename: filename.parent.mkdir(parents=True,", "empty. \"\"\" while not player or player.running: try: yield server.open(timeout=2.5)", "regular file \"\"\" if (args.output or args.stdout) and (args.record or", "streamlink: Streamlink = None log = logging.getLogger(\"streamlink.cli\") def get_formatter(plugin: Plugin):", "try: output.write(data) except OSError as err: if is_player and err.errno", "for URL {args.url}\") if args.retry_max or args.retry_streams: retry_streams = 1", "config_files: setup_args(parser, config_files, ignore_unknown=ignore_unknown) def setup_signals(): # Handle SIGTERM just", "defaults=DEFAULT_STREAM_METADATA) if args.title else args.url ) try: log.info(f\"Starting player: {args.player}\")", "= Path(filename).expanduser().resolve() if filename: filename.parent.mkdir(parents=True, exist_ok=True) streamhandler = logger.basicConfig( stream=stream,", "the main stream is not usable. alt_streams = list(filter(lambda k:", "0: attempts += 1 if attempts >= count: break return", "in parser._actions: if not hasattr(args, action.dest): continue value = getattr(args,", "args.mux_subtitles) if args.hds_live_edge: streamlink.set_option(\"hds-live-edge\", args.hds_live_edge) if args.hls_live_edge: streamlink.set_option(\"hls-live-edge\", args.hls_live_edge) if", "defaults=DEFAULT_STREAM_METADATA) if args.title else args.url ) return out def create_http_server(*_args,", "\"\"\" delimiter = \", \" validstreams = [] for name,", "kill=not args.player_no_close, namedpipe=namedpipe, http=http, record=record, title=formatter.title(args.title, defaults=DEFAULT_STREAM_METADATA) if args.title else", "+= (errno.WSAECONNABORTED,) except AttributeError: pass # Not windows QUIET_OPTIONS =", "Attempts to resolve the URL to a plugin and then", "filename=filename, level=level, style=\"{\", format=(\"[{asctime}]\" if level == \"trace\" else \"\")", "\"\") + \"[{name}][{levelname}] {message}\", datefmt=\"%H:%M:%S\" + (\".%f\" if level ==", "is_fifo = is_player and output.namedpipe show_progress = ( isinstance(output, FileOutput)", "HTTP settings, such as proxy and headers.\"\"\" if args.http_proxy: streamlink.set_option(\"http-proxy\",", "global console if filename == \"-\": filename = LOG_DIR /", "Plugin, PluginOptions from streamlink.stream import StreamIO, StreamProcess from streamlink.utils.named_pipe import", "try: ACCEPTABLE_ERRNO += (errno.WSAECONNABORTED,) except AttributeError: pass # Not windows", "sys.platform == \"win32\": os_version = f\"{platform.system()} {platform.release()}\" # Linux /", "if action.default != value: name = next( # pragma: no", "None for stream_name in (resolve_stream_name(streams, s) for s in args.stream):", "not open stream: {err}\") # Read 8192 bytes before proceeding", "OSError as err: stream_fd.close() raise StreamError(f\"Failed to read data from", "'{', '.join(args.stream)}' could not be found\" if args.json: console.msg_json( plugin=plugin.module,", "= [stream.lower() for stream in args.stream] if not args.url and", "= create_output(formatter) try: output.open() except OSError as err: if isinstance(output,", "ignore_unknown: msg = gettext(\"unrecognized arguments: %s\") parser.error(msg % \" \".join(unknown))", "log.error(f\"File {filename} already exists, use --force to overwrite it.\") sys.exit()", "AttributeError: pass # Not windows QUIET_OPTIONS = (\"json\", \"stream_url\", \"subprocess_cmdline\",", "try: console.msg(stream.to_url()) except TypeError: console.exit(\"The stream specified cannot be translated", "args.hls_live_edge) if args.hls_playlist_reload_attempts: streamlink.set_option(\"hls-playlist-reload-attempts\", args.hls_playlist_reload_attempts) if args.hls_playlist_reload_time: streamlink.set_option(\"hls-playlist-reload-time\", args.hls_playlist_reload_time) if", "not None: log.info(\"Player closed\") break try: output.write(data) except OSError as", "if args.hls_live_edge: streamlink.set_option(\"hls-live-edge\", args.hls_live_edge) if args.hls_playlist_reload_attempts: streamlink.set_option(\"hls-playlist-reload-attempts\", args.hls_playlist_reload_attempts) if args.hls_playlist_reload_time:", "setup_plugin_options(streamlink, plugin) log.info(f\"Found matching plugin {plugin.module} for URL {args.url}\") if", "console.exit(err) console.msg(cmdline) else: console.exit(\"The stream specified cannot be translated to", "user specified a valid one, otherwise output list of valid", "the stream try: stream_fd = stream.open() except StreamError as err:", "stream_fd and prebuffer: log.debug(\"Writing stream to player\") read_stream(stream_fd, server, prebuffer,", "def synonymfilter(n): return stream is streams[n] and n is not", "or player.running): try: streams = initial_streams or fetch_streams(plugin) initial_streams =", "# if the value is set, check to see if", "see the available options or read the manual at https://streamlink.github.io\"", "with closing(output): log.debug(\"Writing stream to output\") read_stream(stream_fd, output, prebuffer, formatter)", "not empty. \"\"\" while not player or player.running: try: yield", "STREAM_SYNONYMS and stream_name in streams: for name, stream in streams.items():", "args.hls_start_offset) if args.hls_duration: streamlink.set_option(\"hls-duration\", args.hls_duration) if args.hls_live_restart: streamlink.set_option(\"hls-live-restart\", args.hls_live_restart) if", "args.hds_segment_attempts) if args.hds_segment_threads: streamlink.set_option(\"hds-segment-threads\", args.hds_segment_threads) if args.hds_segment_timeout: streamlink.set_option(\"hds-segment-timeout\", args.hds_segment_timeout) if", "args.stdout: out = FileOutput(fd=stdout) elif args.record_and_pipe: record = check_file_output(formatter.filename(args.record_and_pipe, args.fs_safe_rules),", "not force: if sys.stdin.isatty(): answer = console.ask(f\"File {filename} already exists!", "output: Output = None plugin: Plugin = None stream_fd: StreamIO", "Formatter, chunk_size=8192): \"\"\"Reads data from stream and then writes it", "Print internal command-line if this stream # uses a subprocess.", "stream: {stream_name} ({stream_type})\") success = output_stream(stream, formatter) if success: break", "0, listen on a random high port. \"\"\" try: http", "args=args.player_args, quiet=not args.verbose_player, kill=not args.player_no_close, namedpipe=namedpipe, http=http, record=record, title=formatter.title(args.title, defaults=DEFAULT_STREAM_METADATA)", "or args.record_and_pipe: console_out = sys.stderr else: console_out = sys.stdout #", "as err: console.exit(f\"Failed to create pipe: {err}\") elif args.player_http: http", "check if a stream actually has data before opening the", "args=args.player_args, filename=filename, call=True, quiet=not args.verbose_player, title=formatter.title(args.title, defaults=DEFAULT_STREAM_METADATA) if args.title else", "args.hls_playlist_reload_time: streamlink.set_option(\"hls-playlist-reload-time\", args.hls_playlist_reload_time) if args.hls_segment_ignore_names: streamlink.set_option(\"hls-segment-ignore-names\", args.hls_segment_ignore_names) if args.hls_segment_key_uri: streamlink.set_option(\"hls-segment-key-uri\",", "req.sensitive else console.ask(prompt) ) def log_root_warning(): if hasattr(os, \"getuid\"): if", "in sensitive else '*' * 8}\") def check_version(force=False): cache =", "We don't want log output when we are printing JSON", "args.json) setup_signals() setup_streamlink() # load additional plugins setup_plugins(args.plugin_dirs) setup_plugin_args(streamlink, parser)", "server.close() def output_stream_passthrough(stream, formatter: Formatter): \"\"\"Prepares a filename to be", "force: sys.exit() def setup_logger_and_console(stream=sys.stdout, filename=None, level=\"info\", json=False): global console if", "* 60 * 6)) elif force: log.info(f\"Your Streamlink version ({installed_version})", "if args.ffmpeg_fout: streamlink.set_option(\"ffmpeg-fout\", args.ffmpeg_fout) if args.ffmpeg_video_transcode: streamlink.set_option(\"ffmpeg-video-transcode\", args.ffmpeg_video_transcode) if args.ffmpeg_audio_transcode:", "[] for name, stream in sorted(streams.items(), key=lambda stream: plugin.stream_weight(stream[0])): if", "config_file.is_file(): config_files.append(config_file) else: # Only load first available default config", "player = output = PlayerOutput( args.player, args=args.player_args, filename=server.url, quiet=not args.verbose_player,", "if not parg.is_global: group.add_argument(parg.argument_name(pname), **parg.options) defaults[parg.dest] = parg.default else: pargdest", "with --player.\") if args.player_fifo: try: namedpipe = NamedPipe() except OSError", "attempts to fetch a list of available streams. Proceeds to", "and (not player or player.running): try: streams = initial_streams or", "success_open: console.exit(f\"Could not open stream {stream}, tried {args.retry_open} times, exiting\")", "like SIGINT signal.signal(signal.SIGTERM, signal.default_int_handler) def setup_http_session(): \"\"\"Sets the global HTTP", "as err: console.exit(err) console.msg(cmdline) else: console.exit(\"The stream specified cannot be", "files configs = [f\"@{config_file}\" for config_file in config_files or []]", "= gettext(\"unrecognized arguments: %s\") parser.error(msg % \" \".join(unknown)) # Force", "= build_parser() setup_args(parser, ignore_unknown=True) # call argument set up as", "{interval} second(s)\") attempts = 0 while not streams: sleep(interval) try:", "playable streams found on this URL: {args.url}\") if args.default_stream and", "to do with the selected stream. Depending on arguments it", "running as root! Be careful!\") def log_current_versions(): \"\"\"Show current installed", "create HTTP server: {err}\") return http def iter_http_requests(server, player): \"\"\"Repeatedly", "config files configs = [f\"@{config_file}\" for config_file in config_files or", "a subprocess. if args.subprocess_cmdline: if isinstance(stream, StreamProcess): try: cmdline =", "session.set_plugin_option( pname, req.dest, console.askpass(prompt) if req.sensitive else console.ask(prompt) ) def", "it should be overwritten if it does.\"\"\" log.debug(\"Checking file output\")", "streams[stream_name] # Print internal command-line if this stream # uses", "https://streamlink.github.io\" ) sys.exit(error_code) def parser_helper(): session = Streamlink() parser =", "docs for how to migrate: {config_file}\") config_files.append(config_file) break if config_files:", "except StreamError as err: log.error(err) if stream_fd and prebuffer: log.debug(\"Writing", "parsed\") break if required: for req in required.values(): if not", "docs for how to migrate: {directory}\") elif showwarning: log.warning(f\"Plugin path", "does not seem to be \" \"installed. You must specify", "for option in action.option_strings if option.startswith(\"--\")), action.option_strings[0] ) if action.option_strings", "def output_stream_passthrough(stream, formatter: Formatter): \"\"\"Prepares a filename to be passed", "not logger.root.isEnabledFor(logging.DEBUG): return # macOS if sys.platform == \"darwin\": os_version", "{message}\", datefmt=\"%H:%M:%S\" + (\".%f\" if level == \"trace\" else \"\")", "try: http = HTTPServer() http.bind(*_args, **_kwargs) except OSError as err:", "OSError as err: console.exit(f\"Failed to create HTTP server: {err}\") return", "prefix=os.path.basename(output.filename) ) elif show_record_progress: stream_iterator = progress( stream_iterator, prefix=os.path.basename(output.record.filename) )", "the plugin specific args have been added setup_args(parser) setup_config_args(parser) #", "how to migrate: {config_file}\") config_files.append(config_file) break if streamlink and args.url:", "console_out = sys.stdout # We don't want log output when", "stream...\") stream_fd.close() except KeyboardInterrupt: error_code = 130 elif args.help: parser.print_help()", ") else: console.exit(f\"{err}.\\n Available streams: {validstreams}\") elif args.json: console.msg_json( plugin=plugin.module,", "streams: console.exit(f\"No playable streams found on this URL: {args.url}\") if", "StrictVersion(streamlink.version) latest_version = StrictVersion(latest_version) if latest_version > installed_version: log.info(f\"A new", "raise except PluginError as err: log.error(err) if count > 0:", "plugin.module required = OrderedDict({}) for parg in plugin.arguments: if parg.options.get(\"help\")", "config_files or []] args, unknown = parser.parse_known_args(configs + arglist) if", "if config_file.is_file(): config_files.append(config_file) else: # Only load first available default", "- Output JSON represenation - Continuously output the stream over", "import platform import signal import sys from collections import OrderedDict", "http.bind(*_args, **_kwargs) except OSError as err: console.exit(f\"Failed to create HTTP", "a dict of streams. Filters out synonyms and displays them", "True) if args.http_ssl_cert: streamlink.set_option(\"http-ssl-cert\", args.http_ssl_cert) if args.http_ssl_cert_crt_key: streamlink.set_option(\"http-ssl-cert\", tuple(args.http_ssl_cert_crt_key)) if", "\"installed. You must specify the path to a player \"", "output_stream_passthrough(stream, formatter) elif args.player_external_http: return output_stream_http(plugin, streams, formatter, external=True, port=args.player_external_http_port)", "quiet=not args.verbose_player, title=formatter.title(args.title, defaults=DEFAULT_STREAM_METADATA) if args.title else args.url ) try:", "else \"\") ) console = ConsoleOutput(streamhandler.stream, json) def main(): error_code", "streamlink.set_option(\"stream-timeout\", args.stream_timeout) if args.ffmpeg_ffmpeg: streamlink.set_option(\"ffmpeg-ffmpeg\", args.ffmpeg_ffmpeg) if args.ffmpeg_verbose: streamlink.set_option(\"ffmpeg-verbose\", args.ffmpeg_verbose)", "bool = False): \"\"\"Parses arguments.\"\"\" global args arglist = sys.argv[1:]", "+ (\".%f\" if level == \"trace\" else \"\") ) console", "prebuffer = None while not stream_fd and (not player or", "setup_args(parser: argparse.ArgumentParser, config_files: List[Path] = None, ignore_unknown: bool = False):", "\"none\" log_file = args.logfile if log_level != \"none\" else None", "set() for pname, plugin in session.plugins.items(): for parg in plugin.arguments:", "LOG_DIR / f\"{datetime.now()}.log\" elif filename: filename = Path(filename).expanduser().resolve() if filename:", "streams in 10 sec\") sleep(10) continue except PluginError as err:", "(not player or player.running): try: streams = initial_streams or fetch_streams(plugin)", "ignored, progress, stream_to_url ACCEPTABLE_ERRNO = (errno.EPIPE, errno.EINVAL, errno.ECONNRESET) try: ACCEPTABLE_ERRNO", "server = create_http_server() player = output = PlayerOutput( args.player, args=args.player_args,", "with one of:\") for url in server.urls: log.info(\" \" +", "[]] args, unknown = parser.parse_known_args(configs + arglist) if unknown and", "args.ffmpeg_audio_transcode) if args.ffmpeg_copyts: streamlink.set_option(\"ffmpeg-copyts\", args.ffmpeg_copyts) if args.ffmpeg_start_at_zero: streamlink.set_option(\"ffmpeg-start-at-zero\", args.ffmpeg_start_at_zero) streamlink.set_option(\"subprocess-errorlog\",", "option in action.option_strings if option.startswith(\"--\")), action.option_strings[0] ) if action.option_strings else", "import requests from socks import __version__ as socks_version from websocket", "listen on all available interfaces, and if port is 0,", "if args.http_query_param: streamlink.set_option(\"http-query-params\", dict(args.http_query_param)) if args.http_ignore_env: streamlink.set_option(\"http-trust-env\", False) if args.http_no_ssl_verify:", "pargdest = parg.dest for action in parser._actions: # find matching", "= delimiter.join(synonyms) name = f\"{name} ({joined})\" validstreams.append(name) return delimiter.join(validstreams) def", "/ other else: os_version = platform.platform() log.debug(f\"OS: {os_version}\") log.debug(f\"Python: {platform.python_version()}\")", "error_code = 130 elif args.url: try: setup_options() handle_url() except KeyboardInterrupt:", "be translated to a URL\") # Output the stream else:", "StreamError(f\"Could not open stream: {err}\") # Read 8192 bytes before", "\"none\" else None setup_logger_and_console(console_out, log_file, log_level, args.json) setup_signals() setup_streamlink() #", "args.ffmpeg_copyts) if args.ffmpeg_start_at_zero: streamlink.set_option(\"ffmpeg-start-at-zero\", args.ffmpeg_start_at_zero) streamlink.set_option(\"subprocess-errorlog\", args.subprocess_errorlog) streamlink.set_option(\"subprocess-errorlog-path\", args.subprocess_errorlog_path) streamlink.set_option(\"locale\",", "directory.is_dir(): success = streamlink.load_plugins(str(directory)) if success and type(directory) is DeprecatedPath:", "other else: os_version = platform.platform() log.debug(f\"OS: {os_version}\") log.debug(f\"Python: {platform.python_version()}\") log.debug(f\"Streamlink:", "elif args.can_handle_url: try: streamlink.resolve_url(args.can_handle_url) except NoPluginError: error_code = 1 except", "their quality (based on plugin.stream_weight). \"\"\" delimiter = \", \"", "log.info(f\"Got HTTP request from {user_agent}\") stream_fd = prebuffer = None", "options\") for pname, plugin in session.plugins.items(): defaults = {} group", "represenation - Continuously output the stream over HTTP - Output", "hasattr(os, \"getuid\"): if os.geteuid() == 0: log.info(\"streamlink is running as", "of directories.\"\"\" for directory in dirs: if directory.is_dir(): success =", "Streamlink plugin options.\"\"\" plugin_args = parser.add_argument_group(\"Plugin options\") for pname, plugin", "args.subprocess_cmdline: if isinstance(stream, StreamProcess): try: cmdline = stream.cmdline() except StreamError", "sorted according to their quality (based on plugin.stream_weight). \"\"\" delimiter", "\", \".join(sorted(pluginlist)) if args.json: console.msg_json(pluginlist) else: console.msg(f\"Loaded plugins: {pluginlist_formatted}\") def", "parg.required: required[parg.name] = parg # if the value is set,", "if latest_version > installed_version: log.info(f\"A new version of Streamlink ({latest_version})", "to output.\"\"\" global output success_open = False for i in", "already exists and ask the user if it should be", "streamlink streamlink = Streamlink({\"user-input-requester\": ConsoleUserInputRequester(console)}) def setup_options(): \"\"\"Sets Streamlink options.\"\"\"", "in session.plugins.items(): defaults = {} group = plugin_args.add_argument_group(pname.capitalize()) for parg", "streamlink import NoPluginError, PluginError, StreamError, Streamlink, __version__ as streamlink_version from", "args.stream): if stream_name in streams: stream = streams[stream_name] break else:", "stream to player\") read_stream(stream_fd, server, prebuffer, formatter) server.close(True) player.close() server.close()", "create_http_server() if args.record: record = check_file_output(formatter.filename(args.record, args.fs_safe_rules), args.force) log.info(f\"Starting player:", "getattr(action, \"plugins\", []) plugins.append(pname) setattr(action, \"plugins\", plugins) plugin.options = PluginOptions(defaults)", "err: console.exit(err) if not streams: console.exit(f\"No playable streams found on", "(\".%f\" if level == \"trace\" else \"\") ) console =", "is empty, listen on all available interfaces, and if port", "not prebuffer: stream_fd.close() raise StreamError(\"No data returned from stream\") return", "import NoPluginError, PluginError, StreamError, Streamlink, __version__ as streamlink_version from streamlink.cache", "dict(args.http_header)) if args.http_query_param: streamlink.set_option(\"http-query-params\", dict(args.http_query_param)) if args.http_ignore_env: streamlink.set_option(\"http-trust-env\", False) if", "if args.ffmpeg_copyts: streamlink.set_option(\"ffmpeg-copyts\", args.ffmpeg_copyts) if args.ffmpeg_start_at_zero: streamlink.set_option(\"ffmpeg-start-at-zero\", args.ffmpeg_start_at_zero) streamlink.set_option(\"subprocess-errorlog\", args.subprocess_errorlog)", "!= \"none\" else None setup_logger_and_console(console_out, log_file, log_level, args.json) setup_signals() setup_streamlink()", "**_kwargs): \"\"\"Creates a HTTP server listening on a given host", "value: name = next( # pragma: no branch (option for", "({stream_type})\") success = output_stream(stream, formatter) if success: break def fetch_streams(plugin):", "log.info(f\"Loaded plugins from deprecated path, see CLI docs for how", "datetime, ignored, progress, stream_to_url ACCEPTABLE_ERRNO = (errno.EPIPE, errno.EINVAL, errno.ECONNRESET) try:", "# deprecated if args.hds_segment_attempts: streamlink.set_option(\"hds-segment-attempts\", args.hds_segment_attempts) if args.hds_segment_threads: streamlink.set_option(\"hds-segment-threads\", args.hds_segment_threads)", "\"\"\"Repeatedly accept HTTP connections on a server. Forever if the", "= resolve_stream_name(streams, stream_name) stream = streams[stream_name] # Print internal command-line", "streams with a '_alt' suffix and attempt # to use", "stream_fd.close() raise StreamError(f\"Failed to read data from stream: {err}\") if", "streams: for name, stream in streams.items(): if stream is streams[stream_name]", "validstreams.append(name) return delimiter.join(validstreams) def handle_url(): \"\"\"The URL handler. Attempts to", "\"\"\" global stream_fd # Attempts to open the stream try:", "# Attempts to open the stream try: stream_fd = stream.open()", "options.\"\"\" if args.interface: streamlink.set_option(\"interface\", args.interface) if args.ipv4: streamlink.set_option(\"ipv4\", args.ipv4) if", "getattr(args, parg.dest if parg.is_global else parg.namespace_dest(pname)) session.set_plugin_option(pname, parg.dest, value) if", "RuntimeError: log.error(f\"{pname} plugin has a configuration error and the arguments", "if not force and version_info_printed: return installed_version = StrictVersion(streamlink.version) latest_version", "err: log.error(err) if count > 0: attempts += 1 if", "port=args.player_external_http_port) elif args.player_continuous_http and not file_output: return output_stream_http(plugin, streams, formatter)", "# We don't want log output when we are printing", "if args.subprocess_cmdline: if isinstance(stream, StreamProcess): try: cmdline = stream.cmdline() except", "resolve_stream_name(streams, stream_name): \"\"\"Returns the real stream name of a synonym.\"\"\"", "isinstance(output, HTTPServer) is_fifo = is_player and output.namedpipe show_progress = (", "import DeprecatedPath, is_win32, stdout from streamlink_cli.console import ConsoleOutput, ConsoleUserInputRequester from", "import argparse import errno import logging import os import platform", "using named pipes on Windows since the named pipe is", "required arguments are not set if parg.required or value: try:", "logging import os import platform import signal import sys from", "resolve_stream_name(streams, stream_name) stream = streams[stream_name] # Print internal command-line if", "if parg.is_global else parg.namespace_dest(pname)) session.set_plugin_option(pname, parg.dest, value) if not parg.is_global:", "if args.mux_subtitles: streamlink.set_option(\"mux-subtitles\", args.mux_subtitles) if args.hds_live_edge: streamlink.set_option(\"hds-live-edge\", args.hds_live_edge) if args.hls_live_edge:", "streamlink_cli.constants import CONFIG_FILES, DEFAULT_STREAM_METADATA, LOG_DIR, PLUGIN_DIRS, STREAM_SYNONYMS from streamlink_cli.output import", "output.write(data) except OSError as err: if is_player and err.errno in", "args.retry_max or args.retry_streams: retry_streams = 1 retry_max = 0 if", "try: for data in stream_iterator: # We need to check", "in STREAM_SYNONYMS and stream_name in streams: for name, stream in", "= 130 elif args.can_handle_url_no_redirect: try: streamlink.resolve_url_no_redirect(args.can_handle_url_no_redirect) except NoPluginError: error_code =", "options.\"\"\" pname = plugin.module required = OrderedDict({}) for parg in", "args.http_ignore_env: streamlink.set_option(\"http-trust-env\", False) if args.http_no_ssl_verify: streamlink.set_option(\"http-ssl-verify\", False) if args.http_disable_dh: streamlink.set_option(\"http-disable-dh\",", "Streamlink options.\"\"\" if args.interface: streamlink.set_option(\"interface\", args.interface) if args.ipv4: streamlink.set_option(\"ipv4\", args.ipv4)", "def setup_logger_and_console(stream=sys.stdout, filename=None, level=\"info\", json=False): global console if filename ==", "if args.http_no_ssl_verify: streamlink.set_option(\"http-ssl-verify\", False) if args.http_disable_dh: streamlink.set_option(\"http-disable-dh\", True) if args.http_ssl_cert:", "args.ipv4) if args.ipv6: streamlink.set_option(\"ipv6\", args.ipv6) if args.ringbuffer_size: streamlink.set_option(\"ringbuffer-size\", args.ringbuffer_size) if", "json=False): global console if filename == \"-\": filename = LOG_DIR", "if log_level != \"none\" else None setup_logger_and_console(console_out, log_file, log_level, args.json)", "setup_http_session() log_root_warning() log_current_versions() log_current_arguments(streamlink, parser) if args.version_check or args.auto_version_check: with", "streamlink.resolve_url(args.url) setup_plugin_options(streamlink, plugin) log.info(f\"Found matching plugin {plugin.module} for URL {args.url}\")", "if args.http_stream_timeout: streamlink.set_option(\"http-stream-timeout\", args.http_stream_timeout) if args.rtmp_timeout: streamlink.set_option(\"rtmp-timeout\", args.rtmp_timeout) # generic", "action.dest log.debug(f\" {name}={value if name not in sensitive else '*'", "if extra_plugin_dir: load_plugins([Path(path).expanduser() for path in extra_plugin_dir]) def setup_streamlink(): \"\"\"Creates", "root! Be careful!\") def log_current_versions(): \"\"\"Show current installed versions\"\"\" if", "check_file_output(formatter.filename(args.record, args.fs_safe_rules), args.force) log.info(f\"Starting player: {args.player}\") out = PlayerOutput( args.player,", ") elif show_record_progress: stream_iterator = progress( stream_iterator, prefix=os.path.basename(output.record.filename) ) try:", "filename: filename.parent.mkdir(parents=True, exist_ok=True) streamhandler = logger.basicConfig( stream=stream, filename=filename, level=level, style=\"{\",", "progress( stream_iterator, prefix=os.path.basename(output.filename) ) elif show_record_progress: stream_iterator = progress( stream_iterator,", "not usable. alt_streams = list(filter(lambda k: stream_name + \"_alt\" in", "just like SIGINT signal.signal(signal.SIGTERM, signal.default_int_handler) def setup_http_session(): \"\"\"Sets the global", "def handle_url(): \"\"\"The URL handler. Attempts to resolve the URL", "- Continuously output the stream over HTTP - Output stream", "FileOutput, Output, PlayerOutput from streamlink_cli.utils import Formatter, HTTPServer, datetime, ignored,", "parser.add_argument_group(\"Plugin options\") for pname, plugin in session.plugins.items(): defaults = {}", "# uses a subprocess. if args.subprocess_cmdline: if isinstance(stream, StreamProcess): try:", "joined = delimiter.join(synonyms) name = f\"{name} ({joined})\" validstreams.append(name) return delimiter.join(validstreams)", "if attempts >= count: break return streams def resolve_stream_name(streams, stream_name):", "= progress( stream_iterator, prefix=os.path.basename(output.record.filename) ) try: for data in stream_iterator:", "is not name synonyms = list(filter(synonymfilter, streams.keys())) if len(synonyms) >", "when we are printing JSON or a command-line. silent_log =", "quality (based on plugin.stream_weight). \"\"\" delimiter = \", \" validstreams", "continue try: log.info(f\"Opening stream: {stream_name} ({type(stream).shortname()})\") stream_fd, prebuffer = open_stream(stream)", "{stream_name} ({stream_type})\") success = output_stream_passthrough(stream, formatter) elif args.player_external_http: return output_stream_http(plugin,", "{err}\") if not prebuffer: stream_fd.close() raise StreamError(\"No data returned from", "try: streams = fetch_streams(plugin) except PluginError as err: log.error(err) streams", "args.hls_live_restart: streamlink.set_option(\"hls-live-restart\", args.hls_live_restart) if args.rtmp_rtmpdump: streamlink.set_option(\"rtmp-rtmpdump\", args.rtmp_rtmpdump) elif args.rtmpdump: streamlink.set_option(\"rtmp-rtmpdump\",", "build_parser from streamlink_cli.compat import DeprecatedPath, is_win32, stdout from streamlink_cli.console import", "if not silent_log else \"none\" logger.root.setLevel(log_level) setup_http_session() log_root_warning() log_current_versions() log_current_arguments(streamlink,", "stream_name) stream = streams[stream_name] # Print internal command-line if this", "versions\"\"\" if not logger.root.isEnabledFor(logging.DEBUG): return # macOS if sys.platform ==", "0 if args.retry_streams: retry_streams = args.retry_streams if args.retry_max: retry_max =", "Formatter): \"\"\"Decides where to write the stream. Depending on arguments", "value = getattr(args, action.dest) if action.default != value: name =", ") try: log.info(f\"Starting player: {args.player}\") output.open() except OSError as err:", "plugin: Plugin = None stream_fd: StreamIO = None streamlink: Streamlink", "global HTTP settings, such as proxy and headers.\"\"\" if args.http_proxy:", "pipe - A subprocess' stdin pipe - A named pipe", "then writes it to the output.\"\"\" is_player = isinstance(output, PlayerOutput)", "if req.sensitive else console.ask(prompt) ) def log_root_warning(): if hasattr(os, \"getuid\"):", "in streams: log.info(f\"Available streams: {validstreams}\") handle_stream(plugin, streams, stream_name) return err", "stream try: stream_fd = stream.open() except StreamError as err: raise", "fetch streams repeatedly until some are returned or limit hit.\"\"\"", "def log_root_warning(): if hasattr(os, \"getuid\"): if os.geteuid() == 0: log.info(\"streamlink", "use these in case the main stream is not usable.", "argparse.SUPPRESS: continue value = getattr(args, parg.dest if parg.is_global else parg.namespace_dest(pname))", "not config_file.is_file(): continue if type(config_file) is DeprecatedPath: log.info(f\"Loaded plugin config", "args.hls_segment_ignore_names) if args.hls_segment_key_uri: streamlink.set_option(\"hls-segment-key-uri\", args.hls_segment_key_uri) if args.hls_audio_select: streamlink.set_option(\"hls-audio-select\", args.hls_audio_select) if", "has loaded.\"\"\" pluginlist = list(streamlink.get_plugins().keys()) pluginlist_formatted = \", \".join(sorted(pluginlist)) if", "console.msg( f\"{usage}\\n\" f\"Use -h/--help to see the available options or", "console.msg(streams[list(streams)[-1]].to_manifest_url()) except TypeError: console.exit(\"The stream specified cannot be translated to", "ConsoleOutput(streamhandler.stream, json) def main(): error_code = 0 parser = build_parser()", "get_formatter(plugin: Plugin): return Formatter( { \"url\": lambda: args.url, \"author\": lambda:", "URL handler. Attempts to resolve the URL to a plugin", "attempts += 1 if attempts >= count: break return streams", "docs for how to migrate: {config_file}\") config_files.append(config_file) break if streamlink", "stream_iterator = progress( stream_iterator, prefix=os.path.basename(output.record.filename) ) try: for data in", ") console = ConsoleOutput(streamhandler.stream, json) def main(): error_code = 0", "interval, count): \"\"\"Attempts to fetch streams repeatedly until some are", "args.hls_timeout: streamlink.set_option(\"hls-timeout\", args.hls_timeout) if args.http_stream_timeout: streamlink.set_option(\"http-stream-timeout\", args.http_stream_timeout) if args.rtmp_timeout: streamlink.set_option(\"rtmp-timeout\",", "output should be on stderr if we are outputting #", "def setup_options(): \"\"\"Sets Streamlink options.\"\"\" if args.interface: streamlink.set_option(\"interface\", args.interface) if", "= 130 finally: if stream_fd: try: log.info(\"Closing currently open stream...\")", "if isinstance(output, PlayerOutput): console.exit(f\"Failed to start player: {args.player} ({err})\") else:", "args.hls_playlist_reload_attempts: streamlink.set_option(\"hls-playlist-reload-attempts\", args.hls_playlist_reload_attempts) if args.hls_playlist_reload_time: streamlink.set_option(\"hls-playlist-reload-time\", args.hls_playlist_reload_time) if args.hls_segment_ignore_names: streamlink.set_option(\"hls-segment-ignore-names\",", "and prebuffer: log.debug(\"Writing stream to player\") read_stream(stream_fd, server, prebuffer, formatter)", "args.http_no_ssl_verify: streamlink.set_option(\"http-ssl-verify\", False) if args.http_disable_dh: streamlink.set_option(\"http-disable-dh\", True) if args.http_ssl_cert: streamlink.set_option(\"http-ssl-cert\",", "ignored(Exception): check_version(force=args.version_check) if args.plugins: print_plugins() elif args.can_handle_url: try: streamlink.resolve_url(args.can_handle_url) except", "console.askpass(prompt) if req.sensitive else console.ask(prompt) ) def log_root_warning(): if hasattr(os,", "Exiting...\") error_code = 130 finally: if stream_fd: try: log.info(\"Closing currently", "ignore_unknown=ignore_unknown) def setup_signals(): # Handle SIGTERM just like SIGINT signal.signal(signal.SIGTERM,", "args.rtmp_timeout: streamlink.set_option(\"rtmp-timeout\", args.rtmp_timeout) # generic stream- arguments take precedence over", "streams, formatter) else: log.info(f\"Opening stream: {stream_name} ({stream_type})\") success = output_stream(stream,", "err = f\"The specified stream(s) '{', '.join(args.stream)}' could not be", "the subprocess reads from - A regular file \"\"\" if", "reads 8192 bytes from it. This is useful to check", "if success: break def fetch_streams(plugin): \"\"\"Fetches streams using correct parameters.\"\"\"", "version of Streamlink ({latest_version}) is available!\") cache.set(\"version_info_printed\", True, (60 *", "check_version(force=args.version_check) if args.plugins: print_plugins() elif args.can_handle_url: try: streamlink.resolve_url(args.can_handle_url) except NoPluginError:", "silent_log else \"none\" log_file = args.logfile if log_level != \"none\"", "args.hls_segment_key_uri: streamlink.set_option(\"hls-segment-key-uri\", args.hls_segment_key_uri) if args.hls_audio_select: streamlink.set_option(\"hls-audio-select\", args.hls_audio_select) if args.hls_start_offset: streamlink.set_option(\"hls-start-offset\",", "130 elif args.can_handle_url_no_redirect: try: streamlink.resolve_url_no_redirect(args.can_handle_url_no_redirect) except NoPluginError: error_code = 1", "accept HTTP connections on a server. Forever if the serving", "to the stream they point to. Streams are sorted according", "\"trace\" else \"\") + \"[{name}][{levelname}] {message}\", datefmt=\"%H:%M:%S\" + (\".%f\" if", "error_code = 130 elif args.can_handle_url_no_redirect: try: streamlink.resolve_url_no_redirect(args.can_handle_url_no_redirect) except NoPluginError: error_code", "log_current_versions(): \"\"\"Show current installed versions\"\"\" if not logger.root.isEnabledFor(logging.DEBUG): return #", "elif force: log.info(f\"Your Streamlink version ({installed_version}) is up to date!\")", "a player is running if it is not empty. \"\"\"", "(based on plugin.stream_weight). \"\"\" delimiter = \", \" validstreams =", "if it does.\"\"\" log.debug(\"Checking file output\") if os.path.isfile(filename) and not", "args.ffmpeg_ffmpeg: streamlink.set_option(\"ffmpeg-ffmpeg\", args.ffmpeg_ffmpeg) if args.ffmpeg_verbose: streamlink.set_option(\"ffmpeg-verbose\", args.ffmpeg_verbose) if args.ffmpeg_verbose_path: streamlink.set_option(\"ffmpeg-verbose-path\",", "f\"{name} ({joined})\" validstreams.append(name) return delimiter.join(validstreams) def handle_url(): \"\"\"The URL handler.", "args.hls_audio_select) if args.hls_start_offset: streamlink.set_option(\"hls-start-offset\", args.hls_start_offset) if args.hls_duration: streamlink.set_option(\"hls-duration\", args.hls_duration) if", "is 0, listen on a random high port. \"\"\" try:", "if a stream actually has data before opening the output.", "({err})\") if not success_open: console.exit(f\"Could not open stream {stream}, tried", "of streams. Filters out synonyms and displays them next to", "cache.set(\"version_info_printed\", True, (60 * 60 * 6)) elif force: log.info(f\"Your", "sensitive.add(parg.argument_name(pname)) log.debug(\"Arguments:\") for action in parser._actions: if not hasattr(args, action.dest):", "hasattr(args, action.dest): continue value = getattr(args, action.dest) if action.default !=", "plugin.get_category(), \"game\": lambda: plugin.get_category(), \"title\": lambda: plugin.get_title(), \"time\": lambda: datetime.now()", "of available streams. Proceeds to handle stream if user specified", "parser) # call setup args again once the plugin specific", "try: log.debug(\"Pre-buffering 8192 bytes\") prebuffer = stream_fd.read(8192) except OSError as", "to create HTTP server: {err}\") return http def iter_http_requests(server, player):", "Print JSON representation of the stream elif args.json: console.msg_json( stream,", "fetch_streams(plugin) except NoPluginError: console.exit(f\"No plugin can handle URL: {args.url}\") except", "finally: if stream_fd: try: log.info(\"Closing currently open stream...\") stream_fd.close() except", "in plugin.arguments.requires(parg.name): required[rparg.name] = rparg except RuntimeError: log.error(f\"{pname} plugin has", "True, (60 * 60 * 6)) elif force: log.info(f\"Your Streamlink", "args.stdout formatter = get_formatter(plugin) for stream_name in [stream_name] + alt_streams:", "on a random high port. \"\"\" try: http = HTTPServer()", "return stream_fd, prebuffer def output_stream(stream, formatter: Formatter): \"\"\"Open stream, create", "URL to a plugin and then attempts to fetch a", "args.version_check or args.auto_version_check: with ignored(Exception): check_version(force=args.version_check) if args.plugins: print_plugins() elif", "!= \"y\": sys.exit() else: log.error(f\"File {filename} already exists, use --force", "call setup args again once the plugin specific args have", "Overwrite it? [y/N] \") if answer.lower() != \"y\": sys.exit() else:", "parg in plugin.arguments: if parg.options.get(\"help\") == argparse.SUPPRESS: continue value =", "f'\"{stream_to_url(stream)}\"' output = PlayerOutput( args.player, args=args.player_args, filename=filename, call=True, quiet=not args.verbose_player,", "for path in extra_plugin_dir]) def setup_streamlink(): \"\"\"Creates the Streamlink session.\"\"\"", "break try: output.write(data) except OSError as err: if is_player and", "from - A regular file \"\"\" if (args.output or args.stdout)", "or args.force_progress) ) stream_iterator = chain( [prebuffer], iter(partial(stream.read, chunk_size), b\"\")", "args.hls_segment_ignore_names: streamlink.set_option(\"hls-segment-ignore-names\", args.hls_segment_ignore_names) if args.hls_segment_key_uri: streamlink.set_option(\"hls-segment-key-uri\", args.hls_segment_key_uri) if args.hls_audio_select: streamlink.set_option(\"hls-audio-select\",", "show_record_progress: stream_iterator = progress( stream_iterator, prefix=os.path.basename(output.record.filename) ) try: for data", "None if not streams: log.info(f\"Waiting for streams, retrying every {interval}", "args.player_fifo: try: namedpipe = NamedPipe() except OSError as err: console.exit(f\"Failed", "streamlink_version from streamlink.cache import Cache from streamlink.exceptions import FatalPluginError from", "args.fs_safe_rules), args.force) log.info(f\"Starting player: {args.player}\") out = PlayerOutput( args.player, args=args.player_args,", "130 finally: if stream_fd: try: log.info(\"Closing currently open stream...\") stream_fd.close()", "Proceeds to handle stream if user specified a valid one,", "PLUGIN_DIRS, STREAM_SYNONYMS from streamlink_cli.output import FileOutput, Output, PlayerOutput from streamlink_cli.utils", "console.exit(f\"Failed to create HTTP server: {err}\") return http def iter_http_requests(server,", "PluginError as err: log.error(f\"Unable to fetch new streams: {err}\") continue", "except KeyboardInterrupt: # Close output if output: output.close() console.msg(\"Interrupted! Exiting...\")", "not streams: sleep(interval) try: streams = fetch_streams(plugin) except FatalPluginError: raise", "exists! Overwrite it? [y/N] \") if answer.lower() != \"y\": sys.exit()", "stream_fd: StreamIO = None streamlink: Streamlink = None log =", "get_formatter(plugin) for stream_name in [stream_name] + alt_streams: stream = streams[stream_name]", "data returned from stream\") return stream_fd, prebuffer def output_stream(stream, formatter:", "parser): global args if not logger.root.isEnabledFor(logging.DEBUG): return sensitive = set()", "args.plugins: print_plugins() elif args.can_handle_url: try: streamlink.resolve_url(args.can_handle_url) except NoPluginError: error_code =", "record options with other file output options.\") if args.output: if", "args.title else args.url ) try: log.info(f\"Starting player: {args.player}\") if player:", "if name in STREAM_SYNONYMS: continue def synonymfilter(n): return stream is", "if args.rtmp_rtmpdump: streamlink.set_option(\"rtmp-rtmpdump\", args.rtmp_rtmpdump) elif args.rtmpdump: streamlink.set_option(\"rtmp-rtmpdump\", args.rtmpdump) if args.rtmp_proxy:", "installed_version = StrictVersion(streamlink.version) latest_version = StrictVersion(latest_version) if latest_version > installed_version:", "setup_streamlink() # load additional plugins setup_plugins(args.plugin_dirs) setup_plugin_args(streamlink, parser) # call", "log_current_arguments(streamlink, parser) if args.version_check or args.auto_version_check: with ignored(Exception): check_version(force=args.version_check) if", "stream_name def format_valid_streams(plugin, streams): \"\"\"Formats a dict of streams. Filters", "\"game\": lambda: plugin.get_category(), \"title\": lambda: plugin.get_title(), \"time\": lambda: datetime.now() },", "if parg.sensitive: sensitive.add(parg.argument_name(pname)) log.debug(\"Arguments:\") for action in parser._actions: if not", "to the output.\"\"\" is_player = isinstance(output, PlayerOutput) is_http = isinstance(output,", "a player \" \"executable with --player.\") server = create_http_server() player", "None log.info(\"Starting server, access with one of:\") for url in", "action.default != value: name = next( # pragma: no branch", "\"stream_url\", \"subprocess_cmdline\", \"quiet\") args = None console: ConsoleOutput = None", "open_stream(stream) success_open = True break except StreamError as err: log.error(f\"Try", "available options or read the manual at https://streamlink.github.io\" ) sys.exit(error_code)", "error_code = 130 finally: if stream_fd: try: log.info(\"Closing currently open", "not latest_version: res = requests.get(\"https://pypi.python.org/pypi/streamlink/json\") data = res.json() latest_version =", "a stream and reads 8192 bytes from it. This is", "time import sleep from typing import List import requests from", "and displays them next to the stream they point to.", "stream else: # Find any streams with a '_alt' suffix", "handle_stream(plugin, streams, stream_name): \"\"\"Decides what to do with the selected", "{config_file}\") config_files.append(config_file) break if config_files: setup_args(parser, config_files, ignore_unknown=ignore_unknown) def setup_signals():", "streamlink.set_option(\"http-disable-dh\", True) if args.http_ssl_cert: streamlink.set_option(\"http-ssl-cert\", args.http_ssl_cert) if args.http_ssl_cert_crt_key: streamlink.set_option(\"http-ssl-cert\", tuple(args.http_ssl_cert_crt_key))", "f\"Socks({socks_version}), \" f\"Websocket({websocket_version})\") def log_current_arguments(session, parser): global args if not", "sleep(10) continue except PluginError as err: log.error(f\"Unable to fetch new", "silent_log else \"none\" logger.root.setLevel(log_level) setup_http_session() log_root_warning() log_current_versions() log_current_arguments(streamlink, parser) if", "setup_logger_and_console(stream=sys.stdout, filename=None, level=\"info\", json=False): global console if filename == \"-\":", "not file_output: log.info(f\"Opening stream: {stream_name} ({stream_type})\") success = output_stream_passthrough(stream, formatter)", "import streamlink.logger as logger from streamlink import NoPluginError, PluginError, StreamError,", "serving externally, or while a player is running if it", "console.msg(\"Interrupted! Exiting...\") error_code = 130 finally: if stream_fd: try: log.info(\"Closing", "({joined})\" validstreams.append(name) return delimiter.join(validstreams) def handle_url(): \"\"\"The URL handler. Attempts", "args.subprocess_errorlog_path) streamlink.set_option(\"locale\", args.locale) def setup_plugin_args(session, parser): \"\"\"Sets Streamlink plugin options.\"\"\"", "None: log.info(\"Player closed\") break try: output.write(data) except OSError as err:", "retry_max = 0 if args.retry_streams: retry_streams = args.retry_streams if args.retry_max:", "action.dest) if action.default != value: name = next( # pragma:", "on a server. Forever if the serving externally, or while", "plugin = streamlink.resolve_url(args.url) for config_file in CONFIG_FILES: config_file = config_file.with_name(f\"{config_file.name}.{plugin.module}\")", "not session.get_plugin_option(pname, req.dest): prompt = f\"{req.prompt or f'Enter {pname} {req.name}'}:", "server. Forever if the serving externally, or while a player", "in dirs: if directory.is_dir(): success = streamlink.load_plugins(str(directory)) if success and", "else: # Find any streams with a '_alt' suffix and", "\"\"\"The URL handler. Attempts to resolve the URL to a", "to fetch a list of available streams. Proceeds to handle", "sys from collections import OrderedDict from contextlib import closing from", "log.debug(f\"OS: {os_version}\") log.debug(f\"Python: {platform.python_version()}\") log.debug(f\"Streamlink: {streamlink_version}\") log.debug(f\"Requests({requests.__version__}), \" f\"Socks({socks_version}), \"", "(errno.WSAECONNABORTED,) except AttributeError: pass # Not windows QUIET_OPTIONS = (\"json\",", "= 0 while not streams: sleep(interval) try: streams = fetch_streams(plugin)", "metadata=plugin.get_metadata(), streams=streams, error=err ) else: console.exit(f\"{err}.\\n Available streams: {validstreams}\") elif", "args.force_progress) ) stream_iterator = chain( [prebuffer], iter(partial(stream.read, chunk_size), b\"\") )", "Read 8192 bytes before proceeding to check for errors. #", "formatter) elif args.player_external_http: return output_stream_http(plugin, streams, formatter, external=True, port=args.player_external_http_port) elif", "streams) console.msg(f\"Available streams: {validstreams}\") def print_plugins(): \"\"\"Outputs a list of", "log.info(\"streamlink is running as root! Be careful!\") def log_current_versions(): \"\"\"Show", "args if not logger.root.isEnabledFor(logging.DEBUG): return sensitive = set() for pname,", "\", \" validstreams = [] for name, stream in sorted(streams.items(),", "prebuffer: stream_fd.close() raise StreamError(\"No data returned from stream\") return stream_fd,", "attempts = 0 while not streams: sleep(interval) try: streams =", "iter_http_requests(server, player): user_agent = req.headers.get(\"User-Agent\") or \"unknown player\" log.info(f\"Got HTTP", "raise StreamError(f\"Could not open stream: {err}\") # Read 8192 bytes", "filename=filename, call=True, quiet=not args.verbose_player, title=formatter.title(args.title, defaults=DEFAULT_STREAM_METADATA) if args.title else args.url", "else args.url ) try: log.info(f\"Starting player: {args.player}\") output.open() except OSError", "= args.retry_max streams = fetch_streams_with_retry(plugin, retry_streams, retry_max) else: streams =", "log.debug(\"Pre-buffering 8192 bytes\") prebuffer = stream_fd.read(8192) except OSError as err:", "if output: output.close() console.msg(\"Interrupted! Exiting...\") error_code = 130 finally: if", "lambda: args.url, \"author\": lambda: plugin.get_author(), \"category\": lambda: plugin.get_category(), \"game\": lambda:", "version ({installed_version}) is up to date!\") if force: sys.exit() def", "{err}, exiting\") break except OSError as err: console.exit(f\"Error when reading", "is running as root! Be careful!\") def log_current_versions(): \"\"\"Show current", "args.hls_segment_attempts) if args.hls_segment_threads: streamlink.set_option(\"hls-segment-threads\", args.hls_segment_threads) if args.hls_segment_timeout: streamlink.set_option(\"hls-segment-timeout\", args.hls_segment_timeout) if", "return err = f\"The specified stream(s) '{', '.join(args.stream)}' could not", "args.retry_streams if args.retry_max: retry_max = args.retry_max streams = fetch_streams_with_retry(plugin, retry_streams,", "http = namedpipe = record = None if not args.player:", "try: cmdline = stream.cmdline() except StreamError as err: console.exit(err) console.msg(cmdline)", "build_parser() setup_args(parser, ignore_unknown=True) # call argument set up as early", "config_file in config_files or []] args, unknown = parser.parse_known_args(configs +", "= 1 retry_max = 0 if args.retry_streams: retry_streams = args.retry_streams", "if port is 0, listen on a random high port.", "streamlink.set_option(\"hls-audio-select\", args.hls_audio_select) if args.hls_start_offset: streamlink.set_option(\"hls-start-offset\", args.hls_start_offset) if args.hls_duration: streamlink.set_option(\"hls-duration\", args.hls_duration)", "continue value = getattr(args, action.dest) if action.default != value: name", "output_stream_http(plugin, streams, formatter) else: log.info(f\"Opening stream: {stream_name} ({stream_type})\") success =", "return FileOutput(filename) def create_output(formatter: Formatter): \"\"\"Decides where to write the", "\" \"executable with --player.\") server = create_http_server() player = output", "filename == \"-\": filename = LOG_DIR / f\"{datetime.now()}.log\" elif filename:", "load_plugins(dirs: List[Path], showwarning: bool = True): \"\"\"Attempts to load plugins", "# Load arguments from config files configs = [f\"@{config_file}\" for", "name of a synonym.\"\"\" if stream_name in STREAM_SYNONYMS and stream_name", "prebuffer: log.debug(\"Writing stream to player\") read_stream(stream_fd, server, prebuffer, formatter) server.close(True)", "args.interface: streamlink.set_option(\"interface\", args.interface) if args.ipv4: streamlink.set_option(\"ipv4\", args.ipv4) if args.ipv6: streamlink.set_option(\"ipv6\",", "we are printing JSON or a command-line. silent_log = any(getattr(args,", "except FatalPluginError: raise except PluginError as err: log.error(err) if count", "not silent_log else \"none\" log_file = args.logfile if log_level !=", "else: out = check_file_output(formatter.filename(args.output, args.fs_safe_rules), args.force) elif args.stdout: out =", "to player\") read_stream(stream_fd, server, prebuffer, formatter) server.close(True) player.close() server.close() def", "be passed to the player.\"\"\" global output filename = f'\"{stream_to_url(stream)}\"'", "for errors. # This is to avoid opening the output", "args.player_http: http = create_http_server() if args.record: record = check_file_output(formatter.filename(args.record, args.fs_safe_rules),", "streams = initial_streams or fetch_streams(plugin) initial_streams = None for stream_name", "args.stream_segment_threads) if args.stream_segment_timeout: streamlink.set_option(\"stream-segment-timeout\", args.stream_segment_timeout) if args.stream_timeout: streamlink.set_option(\"stream-timeout\", args.stream_timeout) if", "A named pipe that the subprocess reads from - A", "= 0 if args.retry_streams: retry_streams = args.retry_streams if args.retry_max: retry_max", "streamlink.set_option(\"http-proxy\", args.http_proxy) if args.https_proxy: streamlink.set_option(\"https-proxy\", args.https_proxy) if args.http_cookie: streamlink.set_option(\"http-cookies\", dict(args.http_cookie))", "rparg except RuntimeError: log.error(f\"{pname} plugin has a configuration error and", "def check_version(force=False): cache = Cache(filename=\"cli.json\") latest_version = cache.get(\"latest_version\") if force", "args.force_progress) ) show_record_progress = ( hasattr(output, \"record\") and isinstance(output.record, FileOutput)", "{directory}\") elif showwarning: log.warning(f\"Plugin path {directory} does not exist or", "force or not latest_version: res = requests.get(\"https://pypi.python.org/pypi/streamlink/json\") data = res.json()", "\"quiet\") args = None console: ConsoleOutput = None output: Output", "\"\"\"Returns the real stream name of a synonym.\"\"\" if stream_name", "**parg.options) defaults[parg.dest] = parg.default else: pargdest = parg.dest for action", "if args.rtmp_timeout: streamlink.set_option(\"rtmp-timeout\", args.rtmp_timeout) # generic stream- arguments take precedence", "show_progress: stream_iterator = progress( stream_iterator, prefix=os.path.basename(output.filename) ) elif show_record_progress: stream_iterator", "{stream}, tried {args.retry_open} times, exiting\") output = create_output(formatter) try: output.open()", "if stream_fd: try: log.info(\"Closing currently open stream...\") stream_fd.close() except KeyboardInterrupt:", "args.http_proxy: streamlink.set_option(\"http-proxy\", args.http_proxy) if args.https_proxy: streamlink.set_option(\"https-proxy\", args.https_proxy) if args.http_cookie: streamlink.set_option(\"http-cookies\",", "streams: {validstreams}\") def print_plugins(): \"\"\"Outputs a list of all plugins", "stream is streams[stream_name] and name not in STREAM_SYNONYMS: return name", "args.record_and_pipe: console_out = sys.stderr else: console_out = sys.stdout # We", "writing to output: {err}, exiting\") break except OSError as err:", "read_stream(stream_fd, server, prebuffer, formatter) server.close(True) player.close() server.close() def output_stream_passthrough(stream, formatter:", "else: console.msg(f\"Loaded plugins: {pluginlist_formatted}\") def load_plugins(dirs: List[Path], showwarning: bool =", "PluginError, StreamError, Streamlink, __version__ as streamlink_version from streamlink.cache import Cache", "is_player and err.errno in ACCEPTABLE_ERRNO: log.info(\"Player closed\") elif is_http and", "try: stream_fd = stream.open() except StreamError as err: raise StreamError(f\"Could", "log.info(f\"Opening stream: {stream_name} ({type(stream).shortname()})\") stream_fd, prebuffer = open_stream(stream) except StreamError", "session.plugins.items(): defaults = {} group = plugin_args.add_argument_group(pname.capitalize()) for parg in", "- Output stream data to selected output \"\"\" stream_name =", "case-insensitive lookup if args.stream: args.stream = [stream.lower() for stream in", "log.debug(f\"Requests({requests.__version__}), \" f\"Socks({socks_version}), \" f\"Websocket({websocket_version})\") def log_current_arguments(session, parser): global args", "if args.http_ssl_cert_crt_key: streamlink.set_option(\"http-ssl-cert\", tuple(args.http_ssl_cert_crt_key)) if args.http_timeout: streamlink.set_option(\"http-timeout\", args.http_timeout) def setup_plugins(extra_plugin_dir=None):", "{err}\") return http def iter_http_requests(server, player): \"\"\"Repeatedly accept HTTP connections", "error=err ) else: console.exit(f\"{err}.\\n Available streams: {validstreams}\") elif args.json: console.msg_json(", "args.loglevel if not silent_log else \"none\" log_file = args.logfile if", "pipe - A named pipe that the subprocess reads from", "# add plugin to global argument plugins = getattr(action, \"plugins\",", "not exist or is not a directory!\") def setup_args(parser: argparse.ArgumentParser,", "has data before opening the output. \"\"\" global stream_fd #", "Output the stream else: # Find any streams with a", "args.url = args.url_param def setup_config_args(parser, ignore_unknown=False): config_files = [] if", "to handle stream if user specified a valid one, otherwise", "on this URL: {args.url}\") if args.default_stream and not args.stream and", "* 24)) version_info_printed = cache.get(\"version_info_printed\") if not force and version_info_printed:", "True def open_stream(stream): \"\"\"Opens a stream and reads 8192 bytes", "def get_formatter(plugin: Plugin): return Formatter( { \"url\": lambda: args.url, \"author\":", "to create pipe: {err}\") elif args.player_http: http = create_http_server() if", "log_level = args.loglevel if not silent_log else \"none\" log_file =", "server.open(timeout=2.5) except OSError: continue def output_stream_http(plugin, initial_streams, formatter: Formatter, external=False,", "reading from stream: {err}, exiting\") finally: stream.close() log.info(\"Stream ended\") def", "DeprecatedPath: log.info(f\"Loaded plugin config from deprecated path, see CLI docs", "args.rtmp_rtmpdump: streamlink.set_option(\"rtmp-rtmpdump\", args.rtmp_rtmpdump) elif args.rtmpdump: streamlink.set_option(\"rtmp-rtmpdump\", args.rtmpdump) if args.rtmp_proxy: streamlink.set_option(\"rtmp-proxy\",", "--force to overwrite it.\") sys.exit() return FileOutput(filename) def create_output(formatter: Formatter):", "these: - Output internal command-line - Output JSON represenation -", "stream_type = type(stream).shortname() if stream_type in args.player_passthrough and not file_output:", "if args.hls_duration: streamlink.set_option(\"hls-duration\", args.hls_duration) if args.hls_live_restart: streamlink.set_option(\"hls-live-restart\", args.hls_live_restart) if args.rtmp_rtmpdump:", "write the stream. Depending on arguments it can be one", "(60 * 60 * 24)) version_info_printed = cache.get(\"version_info_printed\") if not", "err: if is_player and err.errno in ACCEPTABLE_ERRNO: log.info(\"Player closed\") elif", "[y/N] \") if answer.lower() != \"y\": sys.exit() else: log.error(f\"File {filename}", "internal command-line if this stream # uses a subprocess. if", "streamlink.set_option(\"ffmpeg-ffmpeg\", args.ffmpeg_ffmpeg) if args.ffmpeg_verbose: streamlink.set_option(\"ffmpeg-verbose\", args.ffmpeg_verbose) if args.ffmpeg_verbose_path: streamlink.set_option(\"ffmpeg-verbose-path\", args.ffmpeg_verbose_path)", "config_files.append(config_file) else: # Only load first available default config for", "player): \"\"\"Repeatedly accept HTTP connections on a server. Forever if", "be parsed\") break if required: for req in required.values(): if", "console = ConsoleOutput(streamhandler.stream, json) def main(): error_code = 0 parser", "break if required: for req in required.values(): if not session.get_plugin_option(pname,", "args.force) elif args.stdout: out = FileOutput(fd=stdout) elif args.record_and_pipe: record =", "success_open = True break except StreamError as err: log.error(f\"Try {i", "available plugin config with ignored(NoPluginError): plugin = streamlink.resolve_url(args.url) for config_file", "of the required arguments are not set if parg.required or", "windows QUIET_OPTIONS = (\"json\", \"stream_url\", \"subprocess_cmdline\", \"quiet\") args = None", "= PlayerOutput( args.player, args=args.player_args, filename=filename, call=True, quiet=not args.verbose_player, title=formatter.title(args.title, defaults=DEFAULT_STREAM_METADATA)", "arguments cannot be parsed\") break if required: for req in", "a HTTP server listening on a given host and port.", "streamlink_cli.utils import Formatter, HTTPServer, datetime, ignored, progress, stream_to_url ACCEPTABLE_ERRNO =", "on arguments it can be one of these: - Output", "parg.is_global: group.add_argument(parg.argument_name(pname), **parg.options) defaults[parg.dest] = parg.default else: pargdest = parg.dest", "req in required.values(): if not session.get_plugin_option(pname, req.dest): prompt = f\"{req.prompt", "args.hls_live_restart) if args.rtmp_rtmpdump: streamlink.set_option(\"rtmp-rtmpdump\", args.rtmp_rtmpdump) elif args.rtmpdump: streamlink.set_option(\"rtmp-rtmpdump\", args.rtmpdump) if", "setup_logger_and_console(console_out, log_file, log_level, args.json) setup_signals() setup_streamlink() # load additional plugins", "a plugin specific config log_level = args.loglevel if not silent_log", "if args.ipv4: streamlink.set_option(\"ipv4\", args.ipv4) if args.ipv6: streamlink.set_option(\"ipv6\", args.ipv6) if args.ringbuffer_size:", "args.mux_subtitles: streamlink.set_option(\"mux-subtitles\", args.mux_subtitles) if args.hds_live_edge: streamlink.set_option(\"hds-live-edge\", args.hds_live_edge) if args.hls_live_edge: streamlink.set_option(\"hls-live-edge\",", "tuple(args.http_ssl_cert_crt_key)) if args.http_timeout: streamlink.set_option(\"http-timeout\", args.http_timeout) def setup_plugins(extra_plugin_dir=None): \"\"\"Loads any additional", "out = FileOutput(fd=stdout) else: out = check_file_output(formatter.filename(args.output, args.fs_safe_rules), args.force) elif", "precedence over deprecated stream-type arguments if args.stream_segment_attempts: streamlink.set_option(\"stream-segment-attempts\", args.stream_segment_attempts) if", "\"\"\"Sets Streamlink plugin options.\"\"\" plugin_args = parser.add_argument_group(\"Plugin options\") for pname,", "except PluginError as err: log.error(err) streams = None if not", "over deprecated stream-type arguments if args.stream_segment_attempts: streamlink.set_option(\"stream-segment-attempts\", args.stream_segment_attempts) if args.stream_segment_threads:", "elif filename: filename = Path(filename).expanduser().resolve() if filename: filename.parent.mkdir(parents=True, exist_ok=True) streamhandler", "filename = Path(filename).expanduser().resolve() if filename: filename.parent.mkdir(parents=True, exist_ok=True) streamhandler = logger.basicConfig(", "+= 1 if attempts >= count: break return streams def", "while not player or player.running: try: yield server.open(timeout=2.5) except OSError:", "output\") if os.path.isfile(filename) and not force: if sys.stdin.isatty(): answer =", "and name not in STREAM_SYNONYMS: return name return stream_name def", "stream specified cannot be translated to a command\") # Print", "a server. Forever if the serving externally, or while a", ") show_record_progress = ( hasattr(output, \"record\") and isinstance(output.record, FileOutput) and", "# Linux / other else: os_version = platform.platform() log.debug(f\"OS: {os_version}\")", "and then attempts to fetch a list of available streams.", "break if config_files: setup_args(parser, config_files, ignore_unknown=ignore_unknown) def setup_signals(): # Handle", "parser.print_help() else: usage = parser.format_usage() console.msg( f\"{usage}\\n\" f\"Use -h/--help to", "= 1 except KeyboardInterrupt: error_code = 130 elif args.url: try:", "the serving externally, or while a player is running if", "load first available default config for config_file in filter(lambda path:", "for parg in plugin.arguments: if parg.options.get(\"help\") == argparse.SUPPRESS: continue value", "and type(directory) is DeprecatedPath: log.info(f\"Loaded plugins from deprecated path, see", "for parg in plugin.arguments: if not parg.is_global: group.add_argument(parg.argument_name(pname), **parg.options) defaults[parg.dest]", "130 elif args.url: try: setup_options() handle_url() except KeyboardInterrupt: # Close", "stream: {err}, exiting\") finally: stream.close() log.info(\"Stream ended\") def handle_stream(plugin, streams,", "if args.ffmpeg_ffmpeg: streamlink.set_option(\"ffmpeg-ffmpeg\", args.ffmpeg_ffmpeg) if args.ffmpeg_verbose: streamlink.set_option(\"ffmpeg-verbose\", args.ffmpeg_verbose) if args.ffmpeg_verbose_path:", "= progress( stream_iterator, prefix=os.path.basename(output.filename) ) elif show_record_progress: stream_iterator = progress(", "True): \"\"\"Attempts to load plugins from a list of directories.\"\"\"", "Path(filename).expanduser().resolve() if filename: filename.parent.mkdir(parents=True, exist_ok=True) streamhandler = logger.basicConfig( stream=stream, filename=filename,", "or args.force_progress) ) show_record_progress = ( hasattr(output, \"record\") and isinstance(output.record,", "if args.stdout or args.output == \"-\" or args.record_and_pipe: console_out =", "if the value is set, check to see if any", "in QUIET_OPTIONS) log_level = args.loglevel if not silent_log else \"none\"", "initial_streams = None for stream_name in (resolve_stream_name(streams, s) for s", "stream_name): \"\"\"Decides what to do with the selected stream. Depending", "directory in dirs: if directory.is_dir(): success = streamlink.load_plugins(str(directory)) if success", "level=level, style=\"{\", format=(\"[{asctime}]\" if level == \"trace\" else \"\") +", "\".join(unknown)) # Force lowercase to allow case-insensitive lookup if args.stream:", "from streamlink.cache import Cache from streamlink.exceptions import FatalPluginError from streamlink.plugin", "from websocket import __version__ as websocket_version import streamlink.logger as logger", "output = create_output(formatter) try: output.open() except OSError as err: if", "except OSError as err: if isinstance(output, PlayerOutput): console.exit(f\"Failed to start", "None streamlink: Streamlink = None log = logging.getLogger(\"streamlink.cli\") def get_formatter(plugin:", "pipe is not # automatically closed by the player. if", "count): \"\"\"Attempts to fetch streams repeatedly until some are returned", "OSError as err: console.exit(f\"Error when reading from stream: {err}, exiting\")", "import FatalPluginError from streamlink.plugin import Plugin, PluginOptions from streamlink.stream import", "url) for req in iter_http_requests(server, player): user_agent = req.headers.get(\"User-Agent\") or", "log.info(f\"Starting player: {args.player}\") output.open() except OSError as err: console.exit(f\"Failed to", "success_open = False for i in range(args.retry_open): try: stream_fd, prebuffer", "plugin specific args have been added setup_args(parser) setup_config_args(parser) # update", "# load additional plugins setup_plugins(args.plugin_dirs) setup_plugin_args(streamlink, parser) # call setup", "{filename} already exists, use --force to overwrite it.\") sys.exit() return", "and output.namedpipe show_progress = ( isinstance(output, FileOutput) and output.fd is", "handle_url(): \"\"\"The URL handler. Attempts to resolve the URL to", "namedpipe=namedpipe, http=http, record=record, title=formatter.title(args.title, defaults=DEFAULT_STREAM_METADATA) if args.title else args.url )", "on Windows since the named pipe is not # automatically", "if args.title else args.url ) try: log.info(f\"Starting player: {args.player}\") if", "options.\") if args.output: if args.output == \"-\": out = FileOutput(fd=stdout)", "unnecessarily. try: log.debug(\"Pre-buffering 8192 bytes\") prebuffer = stream_fd.read(8192) except OSError", "Formatter): \"\"\"Open stream, create output and finally write the stream", "latest_version = cache.get(\"latest_version\") if force or not latest_version: res =", "process still exists when # using named pipes on Windows", "def setup_plugin_args(session, parser): \"\"\"Sets Streamlink plugin options.\"\"\" plugin_args = parser.add_argument_group(\"Plugin", "args.loglevel if not silent_log else \"none\" logger.root.setLevel(log_level) setup_http_session() log_root_warning() log_current_versions()", "stdout. if args.stdout or args.output == \"-\" or args.record_and_pipe: console_out", "args.ffmpeg_fout) if args.ffmpeg_video_transcode: streamlink.set_option(\"ffmpeg-video-transcode\", args.ffmpeg_video_transcode) if args.ffmpeg_audio_transcode: streamlink.set_option(\"ffmpeg-audio-transcode\", args.ffmpeg_audio_transcode) if", "import StrictVersion from functools import partial from gettext import gettext", "output.open() except OSError as err: if isinstance(output, PlayerOutput): console.exit(f\"Failed to", "read_stream(stream_fd, output, prebuffer, formatter) return True def read_stream(stream, output, prebuffer,", "os_version = platform.platform() log.debug(f\"OS: {os_version}\") log.debug(f\"Python: {platform.python_version()}\") log.debug(f\"Streamlink: {streamlink_version}\") log.debug(f\"Requests({requests.__version__}),", "open output: {output.filename} ({err})\") with closing(output): log.debug(\"Writing stream to output\")", "CLI docs for how to migrate: {config_file}\") config_files.append(config_file) break if", "parg.dest, value) if not parg.is_global: if parg.required: required[parg.name] = parg", "stream- arguments take precedence over deprecated stream-type arguments if args.stream_segment_attempts:", "exist_ok=True) streamhandler = logger.basicConfig( stream=stream, filename=filename, level=level, style=\"{\", format=(\"[{asctime}]\" if", "create output and finally write the stream to output.\"\"\" global", "FatalPluginError: raise except PluginError as err: log.error(err) if count >", "from streamlink_cli.argparser import build_parser from streamlink_cli.compat import DeprecatedPath, is_win32, stdout", "= open_stream(stream) success_open = True break except StreamError as err:", "plugin options.\"\"\" plugin_args = parser.add_argument_group(\"Plugin options\") for pname, plugin in", "the stream elif args.json: console.msg_json( stream, metadata=plugin.get_metadata() ) elif args.stream_url:", "up to date!\") if force: sys.exit() def setup_logger_and_console(stream=sys.stdout, filename=None, level=\"info\",", "load_plugins(PLUGIN_DIRS, showwarning=False) if extra_plugin_dir: load_plugins([Path(path).expanduser() for path in extra_plugin_dir]) def", "args arglist = sys.argv[1:] # Load arguments from config files", "parg.is_global else parg.namespace_dest(pname)) session.set_plugin_option(pname, parg.dest, value) if not parg.is_global: if", "plugin.arguments: if not parg.is_global: group.add_argument(parg.argument_name(pname), **parg.options) defaults[parg.dest] = parg.default else:", "are not set if parg.required or value: try: for rparg", "from typing import List import requests from socks import __version__", "args.retry_max: retry_max = args.retry_max streams = fetch_streams_with_retry(plugin, retry_streams, retry_max) else:", "if args.rtmp_proxy: streamlink.set_option(\"rtmp-proxy\", args.rtmp_proxy) # deprecated if args.hds_segment_attempts: streamlink.set_option(\"hds-segment-attempts\", args.hds_segment_attempts)", "1 except KeyboardInterrupt: error_code = 130 elif args.can_handle_url_no_redirect: try: streamlink.resolve_url_no_redirect(args.can_handle_url_no_redirect)", "not a directory!\") def setup_args(parser: argparse.ArgumentParser, config_files: List[Path] = None,", "if not hasattr(args, action.dest): continue value = getattr(args, action.dest) if", "= req.headers.get(\"User-Agent\") or \"unknown player\" log.info(f\"Got HTTP request from {user_agent}\")", "stream to output\") read_stream(stream_fd, output, prebuffer, formatter) return True def", "__version__ as websocket_version import streamlink.logger as logger from streamlink import", "args.hls_audio_select: streamlink.set_option(\"hls-audio-select\", args.hls_audio_select) if args.hls_start_offset: streamlink.set_option(\"hls-start-offset\", args.hls_start_offset) if args.hls_duration: streamlink.set_option(\"hls-duration\",", "args.http_proxy) if args.https_proxy: streamlink.set_option(\"https-proxy\", args.https_proxy) if args.http_cookie: streamlink.set_option(\"http-cookies\", dict(args.http_cookie)) if", "# call argument set up as early as possible to", "changed by a plugin specific config log_level = args.loglevel if", "args.hls_playlist_reload_time) if args.hls_segment_ignore_names: streamlink.set_option(\"hls-segment-ignore-names\", args.hls_segment_ignore_names) if args.hls_segment_key_uri: streamlink.set_option(\"hls-segment-key-uri\", args.hls_segment_key_uri) if", "setup_streamlink(): \"\"\"Creates the Streamlink session.\"\"\" global streamlink streamlink = Streamlink({\"user-input-requester\":", "elif args.record_and_pipe: record = check_file_output(formatter.filename(args.record_and_pipe, args.fs_safe_rules), args.force) out = FileOutput(fd=stdout,", "except KeyboardInterrupt: error_code = 130 elif args.can_handle_url_no_redirect: try: streamlink.resolve_url_no_redirect(args.can_handle_url_no_redirect) except", "stream they point to. Streams are sorted according to their", "proceeding to check for errors. # This is to avoid", "streamlink.plugin import Plugin, PluginOptions from streamlink.stream import StreamIO, StreamProcess from", "re-fetch streams in 10 sec\") sleep(10) continue except PluginError as", "True break except StreamError as err: log.error(f\"Try {i + 1}/{args.retry_open}:", "streamlink.set_option(\"rtmp-timeout\", args.rtmp_timeout) # generic stream- arguments take precedence over deprecated", "HTTP connections on a server. Forever if the serving externally,", "(resolve_stream_name(streams, s) for s in args.stream): if stream_name in streams:", "ACCEPTABLE_ERRNO: log.info(\"Player closed\") elif is_http and err.errno in ACCEPTABLE_ERRNO: log.info(\"HTTP", "if args.ffmpeg_verbose: streamlink.set_option(\"ffmpeg-verbose\", args.ffmpeg_verbose) if args.ffmpeg_verbose_path: streamlink.set_option(\"ffmpeg-verbose-path\", args.ffmpeg_verbose_path) if args.ffmpeg_fout:", "port. \"\"\" try: http = HTTPServer() http.bind(*_args, **_kwargs) except OSError", "session.\"\"\" global streamlink streamlink = Streamlink({\"user-input-requester\": ConsoleUserInputRequester(console)}) def setup_options(): \"\"\"Sets", "= streamlink.resolve_url(args.url) for config_file in CONFIG_FILES: config_file = config_file.with_name(f\"{config_file.name}.{plugin.module}\") if", "args.ipv4: streamlink.set_option(\"ipv4\", args.ipv4) if args.ipv6: streamlink.set_option(\"ipv6\", args.ipv6) if args.ringbuffer_size: streamlink.set_option(\"ringbuffer-size\",", "PluginOptions(defaults) def setup_plugin_options(session, plugin): \"\"\"Sets Streamlink plugin options.\"\"\" pname =", "if args.title else args.url ) return out def create_http_server(*_args, **_kwargs):", "is set, check to see if any of the required", "has a configuration error and the arguments cannot be parsed\")", "the config specified last to get highest priority for config_file", "path, see CLI docs for how to migrate: {directory}\") elif", "plugin.arguments.requires(parg.name): required[rparg.name] = rparg except RuntimeError: log.error(f\"{pname} plugin has a", "action in parser._actions: if not hasattr(args, action.dest): continue value =", "does.\"\"\" log.debug(\"Checking file output\") if os.path.isfile(filename) and not force: if", "args.hls_segment_timeout) if args.hls_timeout: streamlink.set_option(\"hls-timeout\", args.hls_timeout) if args.http_stream_timeout: streamlink.set_option(\"http-stream-timeout\", args.http_stream_timeout) if", "latest_version: res = requests.get(\"https://pypi.python.org/pypi/streamlink/json\") data = res.json() latest_version = data.get(\"info\").get(\"version\")", "1 if attempts >= count: break return streams def resolve_stream_name(streams,", "= chain( [prebuffer], iter(partial(stream.read, chunk_size), b\"\") ) if show_progress: stream_iterator", "fmt: dt.strftime(fmt) } ) def check_file_output(filename, force): \"\"\"Checks if file", "{os_version}\") log.debug(f\"Python: {platform.python_version()}\") log.debug(f\"Streamlink: {streamlink_version}\") log.debug(f\"Requests({requests.__version__}), \" f\"Socks({socks_version}), \" f\"Websocket({websocket_version})\")", "args.force) log.info(f\"Starting player: {args.player}\") out = PlayerOutput( args.player, args=args.player_args, quiet=not", ") try: log.info(f\"Starting player: {args.player}\") if player: player.open() except OSError", "= create_http_server() if args.record: record = check_file_output(formatter.filename(args.record, args.fs_safe_rules), args.force) log.info(f\"Starting", "arguments from config files configs = [f\"@{config_file}\" for config_file in", "Streamlink version ({installed_version}) is up to date!\") if force: sys.exit()", "data in stream_iterator: # We need to check if the", "from {user_agent}\") stream_fd = prebuffer = None while not stream_fd", "is_player = isinstance(output, PlayerOutput) is_http = isinstance(output, HTTPServer) is_fifo =", "ask the user if it should be overwritten if it", "is not stdout and (sys.stdout.isatty() or args.force_progress) ) show_record_progress =", "filename=None, level=\"info\", json=False): global console if filename == \"-\": filename", "exists, use --force to overwrite it.\") sys.exit() return FileOutput(filename) def", "in STREAM_SYNONYMS: return name return stream_name def format_valid_streams(plugin, streams): \"\"\"Formats", "formatter: Formatter): \"\"\"Open stream, create output and finally write the", "retry_max) else: streams = fetch_streams(plugin) except NoPluginError: console.exit(f\"No plugin can", "args.stream: if stream_name in streams: log.info(f\"Available streams: {validstreams}\") handle_stream(plugin, streams,", "value: try: for rparg in plugin.arguments.requires(parg.name): required[rparg.name] = rparg except", "a plugin and then attempts to fetch a list of", "record=record, title=formatter.title(args.title, defaults=DEFAULT_STREAM_METADATA) if args.title else args.url ) return out", "args.http_ssl_cert: streamlink.set_option(\"http-ssl-cert\", args.http_ssl_cert) if args.http_ssl_cert_crt_key: streamlink.set_option(\"http-ssl-cert\", tuple(args.http_ssl_cert_crt_key)) if args.http_timeout: streamlink.set_option(\"http-timeout\",", "or read the manual at https://streamlink.github.io\" ) sys.exit(error_code) def parser_helper():", "streamlink.set_option(\"hls-duration\", args.hls_duration) if args.hls_live_restart: streamlink.set_option(\"hls-live-restart\", args.hls_live_restart) if args.rtmp_rtmpdump: streamlink.set_option(\"rtmp-rtmpdump\", args.rtmp_rtmpdump)", "how to migrate: {directory}\") elif showwarning: log.warning(f\"Plugin path {directory} does", "except OSError as err: console.exit(f\"Error when reading from stream: {err},", "isinstance(stream, StreamProcess): try: cmdline = stream.cmdline() except StreamError as err:", "= LOG_DIR / f\"{datetime.now()}.log\" elif filename: filename = Path(filename).expanduser().resolve() if", "# We need to check if the player process still", "setup_config_args(parser, ignore_unknown=False): config_files = [] if args.config: # We want", "and not file_output: return output_stream_http(plugin, streams, formatter) else: log.info(f\"Opening stream:", "--player.\") server = create_http_server() player = output = PlayerOutput( args.player,", "to avoid opening the output unnecessarily. try: log.debug(\"Pre-buffering 8192 bytes\")", "setup_plugin_options(session, plugin): \"\"\"Sets Streamlink plugin options.\"\"\" pname = plugin.module required", "else: http = namedpipe = record = None if not", "default config for config_file in filter(lambda path: path.is_file(), CONFIG_FILES): if", "is_win32 and is_fifo: output.player.poll() if output.player.returncode is not None: log.info(\"Player", "console.exit(f\"No playable streams found on this URL: {args.url}\") if args.default_stream", "streamlink.set_option(\"http-cookies\", dict(args.http_cookie)) if args.http_header: streamlink.set_option(\"http-headers\", dict(args.http_header)) if args.http_query_param: streamlink.set_option(\"http-query-params\", dict(args.http_query_param))", "except AttributeError: pass # Not windows QUIET_OPTIONS = (\"json\", \"stream_url\",", "is not stdout and (sys.stdout.isatty() or args.force_progress) ) stream_iterator =", "to output: {err}, exiting\") break except OSError as err: console.exit(f\"Error", "Output stream data to selected output \"\"\" stream_name = resolve_stream_name(streams,", "\" f\"Websocket({websocket_version})\") def log_current_arguments(session, parser): global args if not logger.root.isEnabledFor(logging.DEBUG):", "args.help: parser.print_help() else: usage = parser.format_usage() console.msg( f\"{usage}\\n\" f\"Use -h/--help", "streams[stream_name] break else: log.info(\"Stream not available, will re-fetch streams in", "random high port. \"\"\" try: http = HTTPServer() http.bind(*_args, **_kwargs)", "a list of directories.\"\"\" for directory in dirs: if directory.is_dir():", "{args.player} ({err})\") else: console.exit(f\"Failed to open output: {output.filename} ({err})\") with", "args.stream_segment_threads: streamlink.set_option(\"stream-segment-threads\", args.stream_segment_threads) if args.stream_segment_timeout: streamlink.set_option(\"stream-segment-timeout\", args.stream_segment_timeout) if args.stream_timeout: streamlink.set_option(\"stream-timeout\",", "the named pipe is not # automatically closed by the", "if not config_file.is_file(): continue if type(config_file) is DeprecatedPath: log.info(f\"Loaded plugin", "stream_to_url ACCEPTABLE_ERRNO = (errno.EPIPE, errno.EINVAL, errno.ECONNRESET) try: ACCEPTABLE_ERRNO += (errno.WSAECONNABORTED,)", ">= count: break return streams def resolve_stream_name(streams, stream_name): \"\"\"Returns the", "unknown = parser.parse_known_args(configs + arglist) if unknown and not ignore_unknown:", "pipes on Windows since the named pipe is not #", "or player.running: try: yield server.open(timeout=2.5) except OSError: continue def output_stream_http(plugin,", "on arguments it can be one of these: - The", "(\"json\", \"stream_url\", \"subprocess_cmdline\", \"quiet\") args = None console: ConsoleOutput =", "output filename = f'\"{stream_to_url(stream)}\"' output = PlayerOutput( args.player, args=args.player_args, filename=filename,", "some are returned or limit hit.\"\"\" try: streams = fetch_streams(plugin)", "alt_streams = list(filter(lambda k: stream_name + \"_alt\" in k, sorted(streams.keys())))", "\"plugins\", plugins) plugin.options = PluginOptions(defaults) def setup_plugin_options(session, plugin): \"\"\"Sets Streamlink", "check_version(force=False): cache = Cache(filename=\"cli.json\") latest_version = cache.get(\"latest_version\") if force or", "repeatedly until some are returned or limit hit.\"\"\" try: streams", "'_alt' suffix and attempt # to use these in case", "continue defaults[pargdest] = action.default # add plugin to global argument", "= output_stream_passthrough(stream, formatter) elif args.player_external_http: return output_stream_http(plugin, streams, formatter, external=True,", "{validstreams}\") def print_plugins(): \"\"\"Outputs a list of all plugins Streamlink", "stdout pipe - A subprocess' stdin pipe - A named", "StreamError as err: console.exit(err) console.msg(cmdline) else: console.exit(\"The stream specified cannot", "not set if parg.required or value: try: for rparg in", "else: usage = parser.format_usage() console.msg( f\"{usage}\\n\" f\"Use -h/--help to see", "console.exit(f\"Failed to open output: {output.filename} ({err})\") with closing(output): log.debug(\"Writing stream", "any of the required arguments are not set if parg.required", "be one of these: - Output internal command-line - Output", "type(config_file) is DeprecatedPath: log.info(f\"Loaded config from deprecated path, see CLI", "of all plugins Streamlink has loaded.\"\"\" pluginlist = list(streamlink.get_plugins().keys()) pluginlist_formatted", "filename to be passed to the player.\"\"\" global output filename", "# Only load first available plugin config with ignored(NoPluginError): plugin", "# We want the config specified last to get highest", "limit hit.\"\"\" try: streams = fetch_streams(plugin) except PluginError as err:", "representation of the stream elif args.json: console.msg_json( stream, metadata=plugin.get_metadata() )", "and not ignore_unknown: msg = gettext(\"unrecognized arguments: %s\") parser.error(msg %", "else: pargdest = parg.dest for action in parser._actions: # find", "ended\") def handle_stream(plugin, streams, stream_name): \"\"\"Decides what to do with", "= args.loglevel if not silent_log else \"none\" logger.root.setLevel(log_level) setup_http_session() log_root_warning()", "stream is streams[n] and n is not name synonyms =", "printing JSON or a command-line. silent_log = any(getattr(args, attr) for", "console.msg_json( stream, metadata=plugin.get_metadata() ) elif args.stream_url: try: console.msg(stream.to_url()) except TypeError:", "def parser_helper(): session = Streamlink() parser = build_parser() setup_plugin_args(session, parser)", "{err}, exiting\") finally: stream.close() log.info(\"Stream ended\") def handle_stream(plugin, streams, stream_name):", "to date!\") if force: sys.exit() def setup_logger_and_console(stream=sys.stdout, filename=None, level=\"info\", json=False):", "else \"\") + \"[{name}][{levelname}] {message}\", datefmt=\"%H:%M:%S\" + (\".%f\" if level", "and (args.record or args.record_and_pipe): console.exit(\"Cannot use record options with other", "load plugins from a list of directories.\"\"\" for directory in", "if args.stream_timeout: streamlink.set_option(\"stream-timeout\", args.stream_timeout) if args.ffmpeg_ffmpeg: streamlink.set_option(\"ffmpeg-ffmpeg\", args.ffmpeg_ffmpeg) if args.ffmpeg_verbose:", "elif show_record_progress: stream_iterator = progress( stream_iterator, prefix=os.path.basename(output.record.filename) ) try: for", "list of all plugins Streamlink has loaded.\"\"\" pluginlist = list(streamlink.get_plugins().keys())", "args.http_ssl_cert) if args.http_ssl_cert_crt_key: streamlink.set_option(\"http-ssl-cert\", tuple(args.http_ssl_cert_crt_key)) if args.http_timeout: streamlink.set_option(\"http-timeout\", args.http_timeout) def", "if args.hls_segment_ignore_names: streamlink.set_option(\"hls-segment-ignore-names\", args.hls_segment_ignore_names) if args.hls_segment_key_uri: streamlink.set_option(\"hls-segment-key-uri\", args.hls_segment_key_uri) if args.hls_audio_select:", "= Cache(filename=\"cli.json\") latest_version = cache.get(\"latest_version\") if force or not latest_version:", "available, will re-fetch streams in 10 sec\") sleep(10) continue except", "= fetch_streams_with_retry(plugin, retry_streams, retry_max) else: streams = fetch_streams(plugin) except NoPluginError:", "in stream_iterator: # We need to check if the player", "external=False, port=0): \"\"\"Continuously output the stream over HTTP.\"\"\" global output", "is DeprecatedPath: log.info(f\"Loaded plugin config from deprecated path, see CLI", "args.can_handle_url_no_redirect: try: streamlink.resolve_url_no_redirect(args.can_handle_url_no_redirect) except NoPluginError: error_code = 1 except KeyboardInterrupt:", "False): \"\"\"Parses arguments.\"\"\" global args arglist = sys.argv[1:] # Load", "to load plugins from a list of directories.\"\"\" for directory", "args.hds_segment_timeout) if args.hds_timeout: streamlink.set_option(\"hds-timeout\", args.hds_timeout) if args.hls_segment_attempts: streamlink.set_option(\"hls-segment-attempts\", args.hls_segment_attempts) if", "does not exist or is not a directory!\") def setup_args(parser:", "stream specified cannot be translated to a URL\") else: validstreams", "{user_agent}\") stream_fd = prebuffer = None while not stream_fd and", "with other file output options.\") if args.output: if args.output ==", "if args.http_header: streamlink.set_option(\"http-headers\", dict(args.http_header)) if args.http_query_param: streamlink.set_option(\"http-query-params\", dict(args.http_query_param)) if args.http_ignore_env:", "SIGINT signal.signal(signal.SIGTERM, signal.default_int_handler) def setup_http_session(): \"\"\"Sets the global HTTP settings,", "plugin {plugin.module} for URL {args.url}\") if args.retry_max or args.retry_streams: retry_streams", "elif args.player_http: http = create_http_server() if args.record: record = check_file_output(formatter.filename(args.record,", "show_record_progress = ( hasattr(output, \"record\") and isinstance(output.record, FileOutput) and output.record.fd", "Depending on arguments it can be one of these: -", "gettext import gettext from itertools import chain from pathlib import", "useful to check if a stream actually has data before", "name, stream in streams.items(): if stream is streams[stream_name] and name", "handle stream if user specified a valid one, otherwise output", "streamlink.set_option(\"ffmpeg-start-at-zero\", args.ffmpeg_start_at_zero) streamlink.set_option(\"subprocess-errorlog\", args.subprocess_errorlog) streamlink.set_option(\"subprocess-errorlog-path\", args.subprocess_errorlog_path) streamlink.set_option(\"locale\", args.locale) def setup_plugin_args(session,", "This is useful to check if a stream actually has", "could not be found\" if args.json: console.msg_json( plugin=plugin.module, metadata=plugin.get_metadata(), streams=streams,", "session.set_plugin_option(pname, parg.dest, value) if not parg.is_global: if parg.required: required[parg.name] =", "streams: stream = streams[stream_name] break else: log.info(\"Stream not available, will", "{err}\") # Read 8192 bytes before proceeding to check for", "and not args.stream and not args.json: args.stream = args.default_stream if", "parser): \"\"\"Sets Streamlink plugin options.\"\"\" plugin_args = parser.add_argument_group(\"Plugin options\") for", "for req in required.values(): if not session.get_plugin_option(pname, req.dest): prompt =", "if force: sys.exit() def setup_logger_and_console(stream=sys.stdout, filename=None, level=\"info\", json=False): global console", "record = check_file_output(formatter.filename(args.record_and_pipe, args.fs_safe_rules), args.force) out = FileOutput(fd=stdout, record=record) else:", "been added setup_args(parser) setup_config_args(parser) # update the logging level if", "if the player process still exists when # using named", "streamlink.set_option(\"http-query-params\", dict(args.http_query_param)) if args.http_ignore_env: streamlink.set_option(\"http-trust-env\", False) if args.http_no_ssl_verify: streamlink.set_option(\"http-ssl-verify\", False)", "stream=stream, filename=filename, level=level, style=\"{\", format=(\"[{asctime}]\" if level == \"trace\" else", "\"\"\" try: http = HTTPServer() http.bind(*_args, **_kwargs) except OSError as", "if not streams: console.exit(f\"No playable streams found on this URL:", "= True): \"\"\"Attempts to load plugins from a list of", "arglist) if unknown and not ignore_unknown: msg = gettext(\"unrecognized arguments:", "first available plugin config with ignored(NoPluginError): plugin = streamlink.resolve_url(args.url) for", "\"\") ) console = ConsoleOutput(streamhandler.stream, json) def main(): error_code =", "is_http and err.errno in ACCEPTABLE_ERRNO: log.info(\"HTTP connection closed\") else: console.exit(f\"Error", "if args.hls_audio_select: streamlink.set_option(\"hls-audio-select\", args.hls_audio_select) if args.hls_start_offset: streamlink.set_option(\"hls-start-offset\", args.hls_start_offset) if args.hls_duration:", "websocket_version import streamlink.logger as logger from streamlink import NoPluginError, PluginError,", "for data in stream_iterator: # We need to check if", "console.exit(f\"Failed to start player: {args.player} ({err})\") else: server = create_http_server(host=None,", "are returned or limit hit.\"\"\" try: streams = fetch_streams(plugin) except", "retry_streams = args.retry_streams if args.retry_max: retry_max = args.retry_max streams =", "import __version__ as socks_version from websocket import __version__ as websocket_version", "progress( stream_iterator, prefix=os.path.basename(output.record.filename) ) try: for data in stream_iterator: #", "HTTPServer) is_fifo = is_player and output.namedpipe show_progress = ( isinstance(output,", "if filename: filename.parent.mkdir(parents=True, exist_ok=True) streamhandler = logger.basicConfig( stream=stream, filename=filename, level=level,", "else None setup_logger_and_console(console_out, log_file, log_level, args.json) setup_signals() setup_streamlink() # load", "take precedence over deprecated stream-type arguments if args.stream_segment_attempts: streamlink.set_option(\"stream-segment-attempts\", args.stream_segment_attempts)", "return http def iter_http_requests(server, player): \"\"\"Repeatedly accept HTTP connections on", "retrying every {interval} second(s)\") attempts = 0 while not streams:", "currently open stream...\") stream_fd.close() except KeyboardInterrupt: error_code = 130 elif", "# Print JSON representation of the stream elif args.json: console.msg_json(", "streamlink.set_option(\"http-ssl-cert\", args.http_ssl_cert) if args.http_ssl_cert_crt_key: streamlink.set_option(\"http-ssl-cert\", tuple(args.http_ssl_cert_crt_key)) if args.http_timeout: streamlink.set_option(\"http-timeout\", args.http_timeout)", "* 8}\") def check_version(force=False): cache = Cache(filename=\"cli.json\") latest_version = cache.get(\"latest_version\")", "err: console.exit(f\"Failed to create HTTP server: {err}\") return http def", "not open stream {stream} ({err})\") if not success_open: console.exit(f\"Could not" ]
[ "\"Fortune Summit\": { \"id\": \"B2\", \"division\": { \"TMSC\": { \"id\":", "} } } } } } } } #Create and", "+\"-\" +str(end_date.month)+\"-\" + str(end_date.year) if(autoThrashed): end_date = scan_date if( not", "\"tmc-1\":{ \"id\":\"DEP1\", \"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\", \"3\":\"3\", \"4\":\"4\", \"5\":\"5\", \"6\":\"6\" }", "newDbref = DBRef(\"mydb.userInfo\",a[\"_id\"]) foundMails = mydb.mltable.find({\"otherdbref\":newDbref,\"status\":\"trash\"}) foundMailsList = list(mydb.mltable.find({\"otherdbref\":newDbref,\"status\":\"trash\"})) if(len(foundMailsList)", "elif(int(jsonData[\"cubicle\"])>50 and int(jsonData[\"cubicle\"])<=75): ilocation=3 else: ilocation=4 logger.debug(jsonData[\"building\"]) colorCode=jsonCode[\"building\"][jsonData[\"building\"]][\"id\"]+':'+jsonCode[\"building\"][jsonData[\"building\"]][\"division\"][jsonData[\"division\"]][\"id\"]+':'+dateTimeNow logger.debug(\"ColorCode -", "dall = {} item.pop(\"otherdbref\") dall.update(item) dall.update(newjson) print(dall) new_list_new.append(dall) new_list_new.append({\"totalsize\":totalsize}) logger.debug(new_list_new)", "logger.debug(jsonData) ilocation=1 today = datetime.datetime.now() date = str(today.day) time =", "\") logger.debug(jsonData) ilocation=1 today = datetime.datetime.now() date = str(today.day) time", "1) if(jsonData[\"action\"] == \"all\"): all_list = list(mydb.userMailInfo.find({\"userDeleted\":False},{'_id' : 0,'user_id':0})) all_list.reverse()", "logger.debug(jsonData[\"code\"]) logger.debug(jsonData[\"end_date\"]) foundmail = mydb.userMailInfo.find_one({\"code\":jsonData[\"code\"]},{\"_id\":1}) logger.debug(foundmail) foundMl = mydb.mltable.find_one({\"code\":jsonData[\"code\"]},{\"_id\":1}) logger.debug(foundMl)", "update_DB(jsonData): logger.debug(\"DBUMI::Update_db() entry\") logger.debug(jsonData[\"code\"]) logger.debug(jsonData[\"end_date\"]) foundmail = mydb.userMailInfo.find_one({\"code\":jsonData[\"code\"]},{\"_id\":1}) logger.debug(foundmail) foundMl", "\"id\":\"DEP4\", \"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\", \"3\":\"3\", \"4\":\"4\", \"5\":\"5\", \"6\":\"6\" } }", "= list(mydb.mltable.find({\"otherdbref\":newDbref,\"status\":\"trash\"})) if(len(foundMailsList) < 10): return False tagcount = 0", "x : x[\"name\"]) return json.dumps(new_list_new, default=json_util.default) else: all_list = list(mydb.userMailInfo.find({\"userDeleted\":False},{'_id'", "= all_list[skips:] all_list = all_list[:10] new_list_new = list() for item", "== \"today\"): all_list = list(mydb.userMailInfo.find({\"userDeleted\":False},{'_id' : 0,'user_id':0})) thrash_date = datetime.datetime.today()", "object logger=logging.getLogger() #Setting the threshold of logger to DEBUG logger.setLevel(logging.DEBUG)", "#img = qrcode.make(colorCode) #img.save(colorCode+\".png\") newjsonData = {\"name\":jsonData[\"name\"],\"code\":colorCode,\"email\":jsonData[\"email\"],\"division\":jsonData[\"division\"],\"department\":jsonData[\"department\"],\"floor\":jsonData[\"floor\"],\"cubicle\":jsonData[\"cubicle\"],\"building\":jsonData[\"building\"]} if(fromMFP): newjsonData[\"source\"] =", "foundMails: for tag in tags: if(tag in item[\"tags\"]): tagcount+=1 if(tagcount", "False def generateqrcode(jsonData,filenameJPG,tags,fromMFP): logger.debug(\"Received data for generating color code =", "dall.update(item) dall.update(newjson) print(dall) new_list_new.append(dall) new_list_new.append({\"totalsize\":totalsize}) logger.debug(new_list_new) #new_list_new.sort(key = lambda x", "= scan_date mydb.userMailInfo.insert({\"code\":jsonData[\"code\"],\"scan_date\":scan_date,\"end_date\":end_date,\"otherdbref\":newDbref,\"userDeleted\":False,\"user_id\":1,\"source\":jsonData[\"source\"]}) jsonData[\"autoThrashed\"] = autoThrashed return json.dumps(jsonData) def read_fromDB():", "logger.debug(\"DBUMI::delete_entry() entry\") logger.debug(jsonData[\"code\"]) mydb.userMailInfo.delete_one({\"code\":jsonData[\"code\"],\"user_id\":1}) return json.dumps({\"status\": \"Success\",\"statusreason\": \"updateSucess\"}) def clear_db():", "\"6\":\"6\" } }, \"TTEC-SL\":{ \"id\":\"DEP2\", \"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\", \"3\":\"3\", \"4\":\"4\",", "\"1\":\"1\", \"2\":\"2\", \"3\":\"3\", \"4\":\"4\", \"5\":\"5\", \"6\":\"6\" } }, \"TTEC-CI\":{ \"id\":\"DEP4\",", "continue db_date = datetime.datetime.strptime(item['end_date'],'%d-%m-%Y').date() if(db_date <= thrash_date): new_list.append(item) new_list.reverse() totalsize", "TRASH\"): continue db_date = datetime.datetime.strptime(item['end_date'],'%d-%m-%Y').date() if(db_date <= thrash_date): new_list.append(item) new_list.reverse()", "\"3\":\"3\", \"4\":\"4\", \"5\":\"5\", \"6\":\"6\" } }, \"RND\":{ \"id\":\"DEP2\", \"floor\":{\"0\":\"0\", \"1\":\"1\",", "\"+dateTimeNow) if(int(jsonData[\"cubicle\"])>25 and int(jsonData[\"cubicle\"])<=50): ilocation=2 elif(int(jsonData[\"cubicle\"])>50 and int(jsonData[\"cubicle\"])<=75): ilocation=3 else:", "= all_list[:10] new_list_new = list() for item in all_list: otherdbref", "scan_date = str(scan_date.day) +\"-\"+ str(scan_date.month)+\"-\" + str(scan_date.year) end_date = str(end_date.day)", "0 thrashcount = 0 for item in foundMails: for tag", "tags: if(tag in item[\"tags\"]): tagcount+=1 if(tagcount >= 3): thrashcount+=1 if(thrashcount", "= new_list[:10] new_list_new = list() for item in new_list: otherdbref", "x[\"name\"]) return json.dumps(new_list_new, default=json_util.default) else: all_list = list(mydb.userMailInfo.find({\"userDeleted\":False},{'_id' : 0,'user_id':0}))", "TRASH\"): mydb.mltable.update_many({\"_id\":foundMl[\"_id\"],\"user_id\":1},{\"$set\":{\"status\":\"trash\"}}) return json.dumps({\"status\": \"Success\",\"statusreason\": \"updateSucess\"}) #Clear DB only for", "def update_DB(jsonData): logger.debug(\"DBUMI::Update_db() entry\") logger.debug(jsonData[\"code\"]) logger.debug(jsonData[\"end_date\"]) foundmail = mydb.userMailInfo.find_one({\"code\":jsonData[\"code\"]},{\"_id\":1}) logger.debug(foundmail)", "json.dumps(new_list_new, default=json_util.default) elif(jsonData[\"action\"] == \"today\"): all_list = list(mydb.userMailInfo.find({\"userDeleted\":False},{'_id' : 0,'user_id':0}))", "mydb.mltable.insert({\"code\":jsonData[\"code\"],\"tags\": tags,\"status\":\"Keep\",\"user_id\":1,\"otherdbref\":newDbref})#Test code to be removed #end_date = scan_date mydb.userMailInfo.insert({\"code\":jsonData[\"code\"],\"scan_date\":scan_date,\"end_date\":end_date,\"otherdbref\":newDbref,\"userDeleted\":False,\"user_id\":1,\"source\":jsonData[\"source\"]})", "in all_list: otherdbref = item[\"otherdbref\"] newjson = mydb.userInfo.find_one({\"_id\":otherdbref.id},{\"_id\":0,\"user_id\":0}) dall =", "< 10): return False tagcount = 0 thrashcount = 0", "= datetime.datetime.strptime(item['scan_date'],'%d-%m-%Y').date() if(db_date == thrash_date): new_list.append(item) new_list.reverse() totalsize = len(new_list)", "of logger to DEBUG logger.setLevel(logging.DEBUG) import pymongo uri = \"mongodb://218ffa09-0ee0-4-231-b9ee:zTV4cwDG0vM49J2GFsw72JzwOD79Bv3dPU8fbVLb5pbh3p0CmTBYcvhrFKTjtl1s7hgYSfRbMOrsVve6hfvhag==@218ffa09-0ee0-4-231-b9ee.documents.azure.com:10255/?ssl=true&replicaSet=globaldb\"", "str(end_date.day) +\"-\" +str(end_date.month)+\"-\" + str(end_date.year) if(autoThrashed): end_date = scan_date if(", "int(jsonData[\"cubicle\"])<=50): ilocation=2 elif(int(jsonData[\"cubicle\"])>50 and int(jsonData[\"cubicle\"])<=75): ilocation=3 else: ilocation=4 logger.debug(jsonData[\"building\"]) colorCode=jsonCode[\"building\"][jsonData[\"building\"]][\"id\"]+':'+jsonCode[\"building\"][jsonData[\"building\"]][\"division\"][jsonData[\"division\"]][\"id\"]+':'+dateTimeNow", "num = int(jsonData['page']) skips = 10 * (num - 1)", "\"Imaging\":{ \"id\":\"DEP3\", \"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\", \"3\":\"3\", \"4\":\"4\", \"5\":\"5\", \"6\":\"6\" }", "{} item.pop(\"otherdbref\") dall.update(item) dall.update(newjson) print(dall) new_list_new.append(dall) new_list_new.append({\"totalsize\":totalsize}) logger.debug(new_list_new) return json.dumps(new_list_new,", "\"TTEC-DL\":{ \"id\":\"DEP3\", \"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\", \"3\":\"3\", \"4\":\"4\", \"5\":\"5\", \"6\":\"6\" }", "new_thrash_date = datetime.datetime.strptime(item[\"scan_date\"], '%d-%m-%Y').date() return new_thrash_date def checkIfAutoThrashed(jsonData,tags): if(len(tags) <", "\"6\":\"6\" } }, \"tmc-3\":{ \"id\":\"DEP3\", \"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\", \"3\":\"3\", \"4\":\"4\",", "0 for item in foundMails: for tag in tags: if(tag", "}, \"TTEC-CI\":{ \"id\":\"DEP4\", \"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\", \"3\":\"3\", \"4\":\"4\", \"5\":\"5\", \"6\":\"6\"", "and configure logger logging.basicConfig(filename=\"server.log\", format='%(asctime)s %(message)s', filemode='a') #Creating an object", "db_date = datetime.datetime.strptime(item['scan_date'],'%d-%m-%Y').date() if(db_date == thrash_date): new_list.append(item) new_list.reverse() totalsize =", "str(thrash_date.year) thrash_date = datetime.datetime.strptime(thrash_date, '%d-%m-%Y').date() new_list = list() for item", "%(message)s', filemode='a') #Creating an object logger=logging.getLogger() #Setting the threshold of", "datetime.datetime.strptime(item[\"scan_date\"], '%d-%m-%Y').date() return new_thrash_date def checkIfAutoThrashed(jsonData,tags): if(len(tags) < 3): return", "return new_thrash_date def checkIfAutoThrashed(jsonData,tags): if(len(tags) < 3): return False a", "mydb.userMailInfo.find_one({\"code\":jsonData[\"code\"]},{\"_id\":1}) logger.debug(foundmail) foundMl = mydb.mltable.find_one({\"code\":jsonData[\"code\"]},{\"_id\":1}) logger.debug(foundMl) mydb.userMailInfo.update_many({\"_id\":foundmail[\"_id\"],\"user_id\":1},{\"$set\":{'end_date':str(jsonData['end_date'])}}) if(not jsonData['end_date'] ==", "\"4\":\"4\", \"5\":\"5\", \"6\":\"6\" } } } } } }, \"Fortune", "\"DONT TRASH\"): continue db_date = datetime.datetime.strptime(item['end_date'],'%d-%m-%Y').date() if(db_date <= thrash_date): new_list.append(item)", "= list() for item in all_list: db_date = datetime.datetime.strptime(item['scan_date'],'%d-%m-%Y').date() if(db_date", "dall.update(newjson) print(dall) new_list_new.append(dall) new_list_new.append({\"totalsize\":totalsize}) logger.debug(new_list_new) #new_list_new.sort(key = lambda x :", "are %s\" % tags) import sendEmail as se se.execute(str(jsonData[\"email\"]),filenameJPG,str(colorCode),img,autoThrashed,fromMFP) #img", "#Create and configure logger logging.basicConfig(filename=\"server.log\", format='%(asctime)s %(message)s', filemode='a') #Creating an", "\"+dateTimeNow) dateTimeNow = str(today.day)+str(today.hour)+str(today.minute)+str(today.second)+(str(today.microsecond)[:2]) logger.debug(\"Unique Code - \"+dateTimeNow) if(int(jsonData[\"cubicle\"])>25 and", "- \"+dateTimeNow) dateTimeNow = str(today.day)+str(today.hour)+str(today.minute)+str(today.second)+(str(today.microsecond)[:2]) logger.debug(\"Unique Code - \"+dateTimeNow) if(int(jsonData[\"cubicle\"])>25", "\"5\":\"5\", \"6\":\"6\" } }, \"TTEC-SL\":{ \"id\":\"DEP2\", \"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\", \"3\":\"3\",", "} } } } #Create and configure logger logging.basicConfig(filename=\"server.log\", format='%(asctime)s", "Code mydb.mltable.insert({\"code\":jsonData[\"code\"],\"tags\": tags,\"status\":\"Keep\",\"user_id\":1,\"otherdbref\":newDbref})#Test code to be removed #end_date = scan_date", "logger.setLevel(logging.DEBUG) import pymongo uri = \"mongodb://218ffa09-0ee0-4-231-b9ee:zTV4cwDG0vM49J2GFsw72JzwOD79Bv3dPU8fbVLb5pbh3p0CmTBYcvhrFKTjtl1s7hgYSfRbMOrsVve6hfvhag==@218ffa09-0ee0-4-231-b9ee.documents.azure.com:10255/?ssl=true&replicaSet=globaldb\" client = pymongo.MongoClient(uri) print(\"Obtained", "code to be removed #end_date = scan_date mydb.userMailInfo.insert({\"code\":jsonData[\"code\"],\"scan_date\":scan_date,\"end_date\":end_date,\"otherdbref\":newDbref,\"userDeleted\":False,\"user_id\":1,\"source\":jsonData[\"source\"]}) jsonData[\"autoThrashed\"] =", "io import BytesIO from io import StringIO import json from", "\"2\":\"2\", \"3\":\"3\", \"4\":\"4\", \"5\":\"5\", \"6\":\"6\" } }, \"tmc-3\":{ \"id\":\"DEP3\", \"floor\":{\"0\":\"0\",", "entry\") logger.debug(jsonData[\"code\"]) mydb.userMailInfo.delete_one({\"code\":jsonData[\"code\"],\"user_id\":1}) return json.dumps({\"status\": \"Success\",\"statusreason\": \"updateSucess\"}) def clear_db(): mydb.userMailInfo.remove({})", "addEntry(newjsonData,tags,autoThrashed); def addEntry(jsonData,tags,autoThrashed): a = mydb.userInfo.find_one({\"name\":jsonData[\"name\"]}) newDbref = DBRef(\"mydb.userInfo\",a[\"_id\"]) scan_date", "tag in tags: if(tag in item[\"tags\"]): tagcount+=1 if(tagcount >= 3):", "else: newjsonData[\"source\"] = \"Mobile\" return addEntry(newjsonData,tags,autoThrashed); def addEntry(jsonData,tags,autoThrashed): a =", "def checkIfAutoThrashed(jsonData,tags): if(len(tags) < 3): return False a = mydb.userInfo.find_one({\"name\":jsonData[\"name\"]})", "return json.dumps({\"status\": \"Success\",\"statusreason\": \"updateSucess\"}) #Clear DB only for testing def", "\"D2\", \"dept\":{ \"TTEC-AL\":{ \"id\":\"DEP1\", \"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\", \"3\":\"3\", \"4\":\"4\", \"5\":\"5\",", "in tags: if(tag in item[\"tags\"]): tagcount+=1 if(tagcount >= 3): thrashcount+=1", "= item[\"otherdbref\"] newjson = mydb.userInfo.find_one({\"_id\":otherdbref.id},{\"_id\":0,\"user_id\":0}) dall = {} item.pop(\"otherdbref\") dall.update(item)", "= \") logger.debug(jsonData) ilocation=1 today = datetime.datetime.now() date = str(today.day)", "= datetime.datetime.now() date = str(today.day) time = str(today.hour) + \":\"", "DBRef(\"mydb.userInfo\",a[\"_id\"]) foundMails = mydb.mltable.find({\"otherdbref\":newDbref,\"status\":\"trash\"}) foundMailsList = list(mydb.mltable.find({\"otherdbref\":newDbref,\"status\":\"trash\"})) if(len(foundMailsList) < 10):", "} }, \"tmc-2\":{ \"id\":\"DEP2\", \"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\", \"3\":\"3\", \"4\":\"4\", \"5\":\"5\",", "\"all\"): all_list = list(mydb.userMailInfo.find({\"userDeleted\":False},{'_id' : 0,'user_id':0})) all_list.reverse() totalsize = len(all_list)", "\"division\": { \"TMSC\": { \"id\": \"D1\", \"dept\":{ \"Medical\":{ \"id\":\"DEP1\", \"floor\":{\"0\":\"0\",", "\"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\", \"3\":\"3\", \"4\":\"4\", \"5\":\"5\", \"6\":\"6\" } }, \"Imaging\":{", "totalsize = len(all_list) all_list = all_list[skips:] all_list = all_list[:10] new_list_new", "from bson import json_util import logging import base64 jsonCode ={", "for tag in tags: if(tag in item[\"tags\"]): tagcount+=1 if(tagcount >=", "json.dumps(new_list_new, default=json_util.default) else: all_list = list(mydb.userMailInfo.find({\"userDeleted\":False},{'_id' : 0,'user_id':0})) thrash_date =", "foundmail = mydb.userMailInfo.find_one({\"code\":jsonData[\"code\"]},{\"_id\":1}) logger.debug(foundmail) foundMl = mydb.mltable.find_one({\"code\":jsonData[\"code\"]},{\"_id\":1}) logger.debug(foundMl) mydb.userMailInfo.update_many({\"_id\":foundmail[\"_id\"],\"user_id\":1},{\"$set\":{'end_date':str(jsonData['end_date'])}}) if(not", "= mydb.userInfo.find_one({\"_id\":otherdbref.id},{\"_id\":0,\"user_id\":0}) dall = {} item.pop(\"otherdbref\") dall.update(item) dall.update(newjson) print(dall) new_list_new.append(dall)", "the client\") mydb = client.test def sortingReq(item): new_thrash_date = datetime.datetime.strptime(item[\"scan_date\"],", "dall.update(item) dall.update(newjson) print(dall) new_list_new.append(dall) new_list_new.append({\"totalsize\":totalsize}) logger.debug(new_list_new) return json.dumps(new_list_new, default=json_util.default) def", "new_list.reverse() totalsize = len(new_list) new_list = new_list[skips:] new_list = new_list[:10]", "\"5\":\"5\", \"6\":\"6\" } }, \"TTEC-DL\":{ \"id\":\"DEP3\", \"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\", \"3\":\"3\",", "mydb.userMailInfo.update_many({\"_id\":foundmail[\"_id\"],\"user_id\":1},{\"$set\":{'end_date':str(jsonData['end_date'])}}) if(not jsonData['end_date'] == \"DONT TRASH\"): mydb.mltable.update_many({\"_id\":foundMl[\"_id\"],\"user_id\":1},{\"$set\":{\"status\":\"trash\"}}) return json.dumps({\"status\": \"Success\",\"statusreason\":", "\"tmc\": { \"id\": \"D2\", \"dept\":{ \"tmc-1\":{ \"id\":\"DEP1\", \"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\",", "import pymongo uri = \"mongodb://218ffa09-0ee0-4-231-b9ee:zTV4cwDG0vM49J2GFsw72JzwOD79Bv3dPU8fbVLb5pbh3p0CmTBYcvhrFKTjtl1s7hgYSfRbMOrsVve6hfvhag==@218ffa09-0ee0-4-231-b9ee.documents.azure.com:10255/?ssl=true&replicaSet=globaldb\" client = pymongo.MongoClient(uri) print(\"Obtained the", "new_list_new.append({\"totalsize\":totalsize}) logger.debug(new_list_new) return json.dumps(new_list_new, default=json_util.default) def update_DB(jsonData): logger.debug(\"DBUMI::Update_db() entry\") logger.debug(jsonData[\"code\"])", "\"1\":\"1\", \"2\":\"2\", \"3\":\"3\", \"4\":\"4\", \"5\":\"5\", \"6\":\"6\" } }, \"tmc-3\":{ \"id\":\"DEP3\",", "= thrash_date + datetime.timedelta(hours=9) thrash_date = str(thrash_date.day) + \"-\" +str(thrash_date.month)+\"-\"", "\"5\":\"5\", \"6\":\"6\" } }, \"tmc-3\":{ \"id\":\"DEP3\", \"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\", \"3\":\"3\",", "json.dumps(new_list_new, default=json_util.default) def update_DB(jsonData): logger.debug(\"DBUMI::Update_db() entry\") logger.debug(jsonData[\"code\"]) logger.debug(jsonData[\"end_date\"]) foundmail =", "DEBUG logger.setLevel(logging.DEBUG) import pymongo uri = \"mongodb://218ffa09-0ee0-4-231-b9ee:zTV4cwDG0vM49J2GFsw72JzwOD79Bv3dPU8fbVLb5pbh3p0CmTBYcvhrFKTjtl1s7hgYSfRbMOrsVve6hfvhag==@218ffa09-0ee0-4-231-b9ee.documents.azure.com:10255/?ssl=true&replicaSet=globaldb\" client = pymongo.MongoClient(uri)", "= checkIfAutoThrashed(jsonData,tags) logger.debug(\"Auto thrashed value is %d\" % autoThrashed) logger.debug(\"Tags", "Solitaire\": { \"id\": \"B1\", \"division\": { \"SS\": { \"id\": \"D1\",", "all_list = all_list[skips:] all_list = all_list[:10] new_list_new = list() for", "+ str(end_date.year) if(autoThrashed): end_date = scan_date if( not autoThrashed and", "= autoThrashed return json.dumps(jsonData) def read_fromDB(): new_list = list() for", "date = str(today.day) time = str(today.hour) + \":\" + str(today.minute)", "as se se.execute(str(jsonData[\"email\"]),filenameJPG,str(colorCode),img,autoThrashed,fromMFP) #img = qrcode.make(colorCode) #img.save(colorCode+\".png\") newjsonData = {\"name\":jsonData[\"name\"],\"code\":colorCode,\"email\":jsonData[\"email\"],\"division\":jsonData[\"division\"],\"department\":jsonData[\"department\"],\"floor\":jsonData[\"floor\"],\"cubicle\":jsonData[\"cubicle\"],\"building\":jsonData[\"building\"]}", "DBRef import datetime from bson import json_util import logging import", "new_list = list() for item in all_list: db_date = datetime.datetime.strptime(item['scan_date'],'%d-%m-%Y').date()", "\"TTEC\": { \"id\": \"D2\", \"dept\":{ \"TTEC-AL\":{ \"id\":\"DEP1\", \"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\",", "10 * (num - 1) if(jsonData[\"action\"] == \"all\"): all_list =", "10): return False tagcount = 0 thrashcount = 0 for", "json.dumps(jsonData) def read_fromDB(): new_list = list() for item in mydb.userMailInfo.find({},{\"_id\":0,\"user_id\":0}):", "newDbref = DBRef(\"mydb.userInfo\",a[\"_id\"]) scan_date = datetime.datetime.today() scan_date = scan_date +", "= 0 for item in foundMails: for tag in tags:", "colorCode=jsonCode[\"building\"][jsonData[\"building\"]][\"id\"]+':'+jsonCode[\"building\"][jsonData[\"building\"]][\"division\"][jsonData[\"division\"]][\"id\"]+':'+dateTimeNow logger.debug(\"ColorCode - \"+colorCode) logger.debug(\"generateColorCode:: ColorCode value =\"+colorCode) import qrcode", "default=json_util.default) def update_DB(jsonData): logger.debug(\"DBUMI::Update_db() entry\") logger.debug(jsonData[\"code\"]) logger.debug(jsonData[\"end_date\"]) foundmail = mydb.userMailInfo.find_one({\"code\":jsonData[\"code\"]},{\"_id\":1})", "to be removed #end_date = scan_date mydb.userMailInfo.insert({\"code\":jsonData[\"code\"],\"scan_date\":scan_date,\"end_date\":end_date,\"otherdbref\":newDbref,\"userDeleted\":False,\"user_id\":1,\"source\":jsonData[\"source\"]}) jsonData[\"autoThrashed\"] = autoThrashed", "new_list: otherdbref = item[\"otherdbref\"] newjson = mydb.userInfo.find_one({\"_id\":otherdbref.id},{\"_id\":0,\"user_id\":0}) dall = {}", "item in all_list: otherdbref = item[\"otherdbref\"] newjson = mydb.userInfo.find_one({\"_id\":otherdbref.id},{\"_id\":0,\"user_id\":0}) dall", "data for generating color code = \") logger.debug(jsonData) ilocation=1 today", "scan_date if( not autoThrashed and len(tags) >= 3): #mydb.mltable.insert({\"code\":jsonData[\"code\"],\"tags\": tags,\"status\":\"Keep\",\"user_id\":1,\"otherdbref\":newDbref})", "be removed #end_date = scan_date mydb.userMailInfo.insert({\"code\":jsonData[\"code\"],\"scan_date\":scan_date,\"end_date\":end_date,\"otherdbref\":newDbref,\"userDeleted\":False,\"user_id\":1,\"source\":jsonData[\"source\"]}) jsonData[\"autoThrashed\"] = autoThrashed return", "def sortingReq(item): new_thrash_date = datetime.datetime.strptime(item[\"scan_date\"], '%d-%m-%Y').date() return new_thrash_date def checkIfAutoThrashed(jsonData,tags):", "end_date = scan_date + datetime.timedelta(days=10) scan_date = str(scan_date.day) +\"-\"+ str(scan_date.month)+\"-\"", "\"2\":\"2\", \"3\":\"3\", \"4\":\"4\", \"5\":\"5\", \"6\":\"6\" } }, \"TTEC-SL\":{ \"id\":\"DEP2\", \"floor\":{\"0\":\"0\",", "={ \"building\":{ \"Essae Vaishnavi Solitaire\": { \"id\": \"B1\", \"division\": {", "Code - \"+dateTimeNow) if(int(jsonData[\"cubicle\"])>25 and int(jsonData[\"cubicle\"])<=50): ilocation=2 elif(int(jsonData[\"cubicle\"])>50 and int(jsonData[\"cubicle\"])<=75):", "all_list: if(item['end_date'] == \"DONT TRASH\"): continue db_date = datetime.datetime.strptime(item['end_date'],'%d-%m-%Y').date() if(db_date", "logger.debug(\"generateColorCode:: ColorCode value =\"+colorCode) import qrcode img = qrcode.make(colorCode) logger.debug(type(img))", "from bson.dbref import DBRef import datetime from bson import json_util", "qrcode.make(colorCode) #img.save(colorCode+\".png\") newjsonData = {\"name\":jsonData[\"name\"],\"code\":colorCode,\"email\":jsonData[\"email\"],\"division\":jsonData[\"division\"],\"department\":jsonData[\"department\"],\"floor\":jsonData[\"floor\"],\"cubicle\":jsonData[\"cubicle\"],\"building\":jsonData[\"building\"]} if(fromMFP): newjsonData[\"source\"] = \"MFP\" else:", "mydb.userInfo.find_one({\"name\":jsonData[\"name\"]}) newDbref = DBRef(\"mydb.userInfo\",a[\"_id\"]) foundMails = mydb.mltable.find({\"otherdbref\":newDbref,\"status\":\"trash\"}) foundMailsList = list(mydb.mltable.find({\"otherdbref\":newDbref,\"status\":\"trash\"}))", "+ str(today.minute) + \":\" + str(today.second)+\":\"+str(today.microsecond) dateTimeNow = date+':'+time logger.debug(\"Current", "\"id\": \"B1\", \"division\": { \"SS\": { \"id\": \"D1\", \"dept\":{ \"Semicon\":{", "autoThrashed = checkIfAutoThrashed(jsonData,tags) logger.debug(\"Auto thrashed value is %d\" % autoThrashed)", "item in all_list: if(item['end_date'] == \"DONT TRASH\"): continue db_date =", "\"+colorCode) logger.debug(\"generateColorCode:: ColorCode value =\"+colorCode) import qrcode img = qrcode.make(colorCode)", "datetime.timedelta(hours=9) thrash_date = str(thrash_date.day) + \"-\" +str(thrash_date.month)+\"-\" + str(thrash_date.year) thrash_date", "ilocation=2 elif(int(jsonData[\"cubicle\"])>50 and int(jsonData[\"cubicle\"])<=75): ilocation=3 else: ilocation=4 logger.debug(jsonData[\"building\"]) colorCode=jsonCode[\"building\"][jsonData[\"building\"]][\"id\"]+':'+jsonCode[\"building\"][jsonData[\"building\"]][\"division\"][jsonData[\"division\"]][\"id\"]+':'+dateTimeNow logger.debug(\"ColorCode", "}, \"RND\":{ \"id\":\"DEP2\", \"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\", \"3\":\"3\", \"4\":\"4\", \"5\":\"5\", \"6\":\"6\"", "{ \"TMSC\": { \"id\": \"D1\", \"dept\":{ \"Medical\":{ \"id\":\"DEP1\", \"floor\":{\"0\":\"0\", \"1\":\"1\",", "a = mydb.userInfo.find_one({\"name\":jsonData[\"name\"]}) newDbref = DBRef(\"mydb.userInfo\",a[\"_id\"]) scan_date = datetime.datetime.today() scan_date", "for item in all_list: otherdbref = item[\"otherdbref\"] newjson = mydb.userInfo.find_one({\"_id\":otherdbref.id},{\"_id\":0,\"user_id\":0})", "list() for item in all_list: if(item['end_date'] == \"DONT TRASH\"): continue", "return json.dumps(new_list_new, default=json_util.default) def update_DB(jsonData): logger.debug(\"DBUMI::Update_db() entry\") logger.debug(jsonData[\"code\"]) logger.debug(jsonData[\"end_date\"]) foundmail", "= {} item.pop(\"otherdbref\") dall.update(item) dall.update(newjson) print(dall) new_list_new.append(dall) new_list_new.append({\"totalsize\":totalsize}) logger.debug(new_list_new) #new_list_new.sort(key", "str(thrash_date.day) + \"-\" +str(thrash_date.month)+\"-\" + str(thrash_date.year) thrash_date = datetime.datetime.strptime(thrash_date, '%d-%m-%Y').date()", "\"5\":\"5\", \"6\":\"6\" } } } } } } } }", "qrcode.make(colorCode) logger.debug(type(img)) autoThrashed = checkIfAutoThrashed(jsonData,tags) logger.debug(\"Auto thrashed value is %d\"", "+ str(today.second)+\":\"+str(today.microsecond) dateTimeNow = date+':'+time logger.debug(\"Current Datetime - \"+dateTimeNow) dateTimeNow", "se se.execute(str(jsonData[\"email\"]),filenameJPG,str(colorCode),img,autoThrashed,fromMFP) #img = qrcode.make(colorCode) #img.save(colorCode+\".png\") newjsonData = {\"name\":jsonData[\"name\"],\"code\":colorCode,\"email\":jsonData[\"email\"],\"division\":jsonData[\"division\"],\"department\":jsonData[\"department\"],\"floor\":jsonData[\"floor\"],\"cubicle\":jsonData[\"cubicle\"],\"building\":jsonData[\"building\"]} if(fromMFP):", "\"4\":\"4\", \"5\":\"5\", \"6\":\"6\" } }, \"RND\":{ \"id\":\"DEP2\", \"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\",", "def addEntry(jsonData,tags,autoThrashed): a = mydb.userInfo.find_one({\"name\":jsonData[\"name\"]}) newDbref = DBRef(\"mydb.userInfo\",a[\"_id\"]) scan_date =", "= mydb.userInfo.find_one({\"_id\":otherdbref.id},{\"_id\":0,\"user_id\":0}) dall = {} item.pop(\"otherdbref\") dall.update(item) dall.update(newjson) print(dall) new_list.append(dall)", "from io import BytesIO from io import StringIO import json", "{ \"SS\": { \"id\": \"D1\", \"dept\":{ \"Semicon\":{ \"id\":\"DEP1\", \"floor\":{\"0\":\"0\", \"1\":\"1\",", "return addEntry(newjsonData,tags,autoThrashed); def addEntry(jsonData,tags,autoThrashed): a = mydb.userInfo.find_one({\"name\":jsonData[\"name\"]}) newDbref = DBRef(\"mydb.userInfo\",a[\"_id\"])", "<= thrash_date): new_list.append(item) new_list.reverse() totalsize = len(new_list) new_list = new_list[skips:]", "\"5\":\"5\", \"6\":\"6\" } }, \"TTEC-CI\":{ \"id\":\"DEP4\", \"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\", \"3\":\"3\",", "+ \"-\" +str(thrash_date.month)+\"-\" + str(thrash_date.year) thrash_date = datetime.datetime.strptime(thrash_date, '%d-%m-%Y').date() new_list", "thrash_date = str(thrash_date.day) + \"-\" +str(thrash_date.month)+\"-\" + str(thrash_date.year) thrash_date =", "item[\"otherdbref\"] newjson = mydb.userInfo.find_one({\"_id\":otherdbref.id},{\"_id\":0,\"user_id\":0}) dall = {} item.pop(\"otherdbref\") dall.update(item) dall.update(newjson)", "= new_list[skips:] new_list = new_list[:10] new_list_new = list() for item", "= str(today.day)+str(today.hour)+str(today.minute)+str(today.second)+(str(today.microsecond)[:2]) logger.debug(\"Unique Code - \"+dateTimeNow) if(int(jsonData[\"cubicle\"])>25 and int(jsonData[\"cubicle\"])<=50): ilocation=2", "}, \"TTEC-DL\":{ \"id\":\"DEP3\", \"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\", \"3\":\"3\", \"4\":\"4\", \"5\":\"5\", \"6\":\"6\"", "= \"MFP\" else: newjsonData[\"source\"] = \"Mobile\" return addEntry(newjsonData,tags,autoThrashed); def addEntry(jsonData,tags,autoThrashed):", "in new_list: otherdbref = item[\"otherdbref\"] newjson = mydb.userInfo.find_one({\"_id\":otherdbref.id},{\"_id\":0,\"user_id\":0}) dall =", "= list(mydb.userMailInfo.find({\"userDeleted\":False},{'_id' : 0,'user_id':0})) thrash_date = datetime.datetime.today() thrash_date = thrash_date", "True return False def generateqrcode(jsonData,filenameJPG,tags,fromMFP): logger.debug(\"Received data for generating color", "for testing def delete_entry(jsonData): logger.debug(\"DBUMI::delete_entry() entry\") logger.debug(jsonData[\"code\"]) mydb.userMailInfo.delete_one({\"code\":jsonData[\"code\"],\"user_id\":1}) return json.dumps({\"status\":", "= mydb.userInfo.find_one({\"name\":jsonData[\"name\"]}) newDbref = DBRef(\"mydb.userInfo\",a[\"_id\"]) foundMails = mydb.mltable.find({\"otherdbref\":newDbref,\"status\":\"trash\"}) foundMailsList =", "\"4\":\"4\", \"5\":\"5\", \"6\":\"6\" } }, \"TTEC-SL\":{ \"id\":\"DEP2\", \"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\",", "logger to DEBUG logger.setLevel(logging.DEBUG) import pymongo uri = \"mongodb://218ffa09-0ee0-4-231-b9ee:zTV4cwDG0vM49J2GFsw72JzwOD79Bv3dPU8fbVLb5pbh3p0CmTBYcvhrFKTjtl1s7hgYSfRbMOrsVve6hfvhag==@218ffa09-0ee0-4-231-b9ee.documents.azure.com:10255/?ssl=true&replicaSet=globaldb\" client", "} } } } } } #Create and configure logger", "tagcount+=1 if(tagcount >= 3): thrashcount+=1 if(thrashcount >=10): return True return", "mydb.userMailInfo.find({},{\"_id\":0,\"user_id\":0}): print(item) otherdbref = item[\"otherdbref\"] newjson = mydb.userInfo.find_one({\"_id\":otherdbref.id},{\"_id\":0,\"user_id\":0}) dall =", "\"5\":\"5\", \"6\":\"6\" } } } }, \"tmc\": { \"id\": \"D2\",", "item.pop(\"otherdbref\") dall.update(item) dall.update(newjson) print(dall) new_list_new.append(dall) new_list_new.append({\"totalsize\":totalsize}) logger.debug(new_list_new) #new_list_new.sort(key = lambda", "+ datetime.timedelta(hours=9) end_date = scan_date + datetime.timedelta(days=10) scan_date = str(scan_date.day)", "#Clear DB only for testing def delete_entry(jsonData): logger.debug(\"DBUMI::delete_entry() entry\") logger.debug(jsonData[\"code\"])", "} }, \"Fortune Summit\": { \"id\": \"B2\", \"division\": { \"TMSC\":", "} } } } } #Create and configure logger logging.basicConfig(filename=\"server.log\",", "\"3\":\"3\", \"4\":\"4\", \"5\":\"5\", \"6\":\"6\" } }, \"tmc-3\":{ \"id\":\"DEP3\", \"floor\":{\"0\":\"0\", \"1\":\"1\",", "return False tagcount = 0 thrashcount = 0 for item", "\"TTEC-SL\":{ \"id\":\"DEP2\", \"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\", \"3\":\"3\", \"4\":\"4\", \"5\":\"5\", \"6\":\"6\" }", "\"SS\": { \"id\": \"D1\", \"dept\":{ \"Semicon\":{ \"id\":\"DEP1\", \"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\",", "for item in foundMails: for tag in tags: if(tag in", "and int(jsonData[\"cubicle\"])<=50): ilocation=2 elif(int(jsonData[\"cubicle\"])>50 and int(jsonData[\"cubicle\"])<=75): ilocation=3 else: ilocation=4 logger.debug(jsonData[\"building\"])", "logger.debug(jsonData[\"building\"]) colorCode=jsonCode[\"building\"][jsonData[\"building\"]][\"id\"]+':'+jsonCode[\"building\"][jsonData[\"building\"]][\"division\"][jsonData[\"division\"]][\"id\"]+':'+dateTimeNow logger.debug(\"ColorCode - \"+colorCode) logger.debug(\"generateColorCode:: ColorCode value =\"+colorCode) import", "%d\" % autoThrashed) logger.debug(\"Tags are %s\" % tags) import sendEmail", "\"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\", \"3\":\"3\", \"4\":\"4\", \"5\":\"5\", \"6\":\"6\" } }, \"tmc-3\":{", "json from bson.dbref import DBRef import datetime from bson import", "def read_fromDB(): new_list = list() for item in mydb.userMailInfo.find({},{\"_id\":0,\"user_id\":0}): print(item)", "thrash_date + datetime.timedelta(hours=9) thrash_date = str(thrash_date.day) + \"-\" +str(thrash_date.month)+\"-\" +", "Vaishnavi Solitaire\": { \"id\": \"B1\", \"division\": { \"SS\": { \"id\":", "= {} item.pop(\"otherdbref\") dall.update(item) dall.update(newjson) print(dall) new_list_new.append(dall) new_list_new.append({\"totalsize\":totalsize}) logger.debug(new_list_new) return", "\"6\":\"6\" } }, \"TTEC-DL\":{ \"id\":\"DEP3\", \"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\", \"3\":\"3\", \"4\":\"4\",", "in item[\"tags\"]): tagcount+=1 if(tagcount >= 3): thrashcount+=1 if(thrashcount >=10): return", ">= 3): #mydb.mltable.insert({\"code\":jsonData[\"code\"],\"tags\": tags,\"status\":\"Keep\",\"user_id\":1,\"otherdbref\":newDbref}) Actual Code mydb.mltable.insert({\"code\":jsonData[\"code\"],\"tags\": tags,\"status\":\"Keep\",\"user_id\":1,\"otherdbref\":newDbref})#Test code to", "}, \"Mobile\":{ \"id\":\"DEP3\", \"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\", \"3\":\"3\", \"4\":\"4\", \"5\":\"5\", \"6\":\"6\"", "== \"DONT TRASH\"): continue db_date = datetime.datetime.strptime(item['end_date'],'%d-%m-%Y').date() if(db_date <= thrash_date):", "DB only for testing def delete_entry(jsonData): logger.debug(\"DBUMI::delete_entry() entry\") logger.debug(jsonData[\"code\"]) mydb.userMailInfo.delete_one({\"code\":jsonData[\"code\"],\"user_id\":1})", "'%d-%m-%Y').date() new_list = list() for item in all_list: if(item['end_date'] ==", "generating color code = \") logger.debug(jsonData) ilocation=1 today = datetime.datetime.now()", "\"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\", \"3\":\"3\", \"4\":\"4\", \"5\":\"5\", \"6\":\"6\" } }, \"TTEC-CI\":{", "Datetime - \"+dateTimeNow) dateTimeNow = str(today.day)+str(today.hour)+str(today.minute)+str(today.second)+(str(today.microsecond)[:2]) logger.debug(\"Unique Code - \"+dateTimeNow)", "read_fromDB(): new_list = list() for item in mydb.userMailInfo.find({},{\"_id\":0,\"user_id\":0}): print(item) otherdbref", "= int(jsonData['page']) skips = 10 * (num - 1) if(jsonData[\"action\"]", "today = datetime.datetime.now() date = str(today.day) time = str(today.hour) +", "\"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\", \"3\":\"3\", \"4\":\"4\", \"5\":\"5\", \"6\":\"6\" } }, \"TTEC-SL\":{", "\"2\":\"2\", \"3\":\"3\", \"4\":\"4\", \"5\":\"5\", \"6\":\"6\" } }, \"TTEC-DL\":{ \"id\":\"DEP3\", \"floor\":{\"0\":\"0\",", "import sendEmail as se se.execute(str(jsonData[\"email\"]),filenameJPG,str(colorCode),img,autoThrashed,fromMFP) #img = qrcode.make(colorCode) #img.save(colorCode+\".png\") newjsonData", "item in all_list: db_date = datetime.datetime.strptime(item['scan_date'],'%d-%m-%Y').date() if(db_date == thrash_date): new_list.append(item)", "for item in all_list: db_date = datetime.datetime.strptime(item['scan_date'],'%d-%m-%Y').date() if(db_date == thrash_date):", "\"dept\":{ \"Medical\":{ \"id\":\"DEP1\", \"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\", \"3\":\"3\", \"4\":\"4\", \"5\":\"5\", \"6\":\"6\"", "list() for item in new_list: otherdbref = item[\"otherdbref\"] newjson =", "checkIfAutoThrashed(jsonData,tags): if(len(tags) < 3): return False a = mydb.userInfo.find_one({\"name\":jsonData[\"name\"]}) newDbref", "}, \"tmc\": { \"id\": \"D2\", \"dept\":{ \"tmc-1\":{ \"id\":\"DEP1\", \"floor\":{\"0\":\"0\", \"1\":\"1\",", "datetime.datetime.strptime(thrash_date, '%d-%m-%Y').date() new_list = list() for item in all_list: db_date", "logger.debug(\"Current Datetime - \"+dateTimeNow) dateTimeNow = str(today.day)+str(today.hour)+str(today.minute)+str(today.second)+(str(today.microsecond)[:2]) logger.debug(\"Unique Code -", "\"6\":\"6\" } }, \"TTEC-CI\":{ \"id\":\"DEP4\", \"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\", \"3\":\"3\", \"4\":\"4\",", "} }, \"tmc-3\":{ \"id\":\"DEP3\", \"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\", \"3\":\"3\", \"4\":\"4\", \"5\":\"5\",", "import qrcode img = qrcode.make(colorCode) logger.debug(type(img)) autoThrashed = checkIfAutoThrashed(jsonData,tags) logger.debug(\"Auto", "datetime.datetime.now() date = str(today.day) time = str(today.hour) + \":\" +", "\"2\":\"2\", \"3\":\"3\", \"4\":\"4\", \"5\":\"5\", \"6\":\"6\" } } } }, \"TTEC\":", "ColorCode value =\"+colorCode) import qrcode img = qrcode.make(colorCode) logger.debug(type(img)) autoThrashed", "threshold of logger to DEBUG logger.setLevel(logging.DEBUG) import pymongo uri =", "is %d\" % autoThrashed) logger.debug(\"Tags are %s\" % tags) import", "} } }, \"Fortune Summit\": { \"id\": \"B2\", \"division\": {", "\"id\":\"DEP3\", \"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\", \"3\":\"3\", \"4\":\"4\", \"5\":\"5\", \"6\":\"6\" } },", "lambda x : x[\"name\"]) return json.dumps(new_list_new, default=json_util.default) else: all_list =", "\"5\":\"5\", \"6\":\"6\" } } } } } }, \"Fortune Summit\":", "\":\" + str(today.minute) + \":\" + str(today.second)+\":\"+str(today.microsecond) dateTimeNow = date+':'+time", "str(scan_date.year) end_date = str(end_date.day) +\"-\" +str(end_date.month)+\"-\" + str(end_date.year) if(autoThrashed): end_date", "\"5\":\"5\", \"6\":\"6\" } }, \"Imaging\":{ \"id\":\"DEP3\", \"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\", \"3\":\"3\",", "= qrcode.make(colorCode) #img.save(colorCode+\".png\") newjsonData = {\"name\":jsonData[\"name\"],\"code\":colorCode,\"email\":jsonData[\"email\"],\"division\":jsonData[\"division\"],\"department\":jsonData[\"department\"],\"floor\":jsonData[\"floor\"],\"cubicle\":jsonData[\"cubicle\"],\"building\":jsonData[\"building\"]} if(fromMFP): newjsonData[\"source\"] = \"MFP\"", "{} item.pop(\"otherdbref\") dall.update(item) dall.update(newjson) print(dall) new_list_new.append(dall) new_list_new.append({\"totalsize\":totalsize}) logger.debug(new_list_new) #new_list_new.sort(key =", "= \"mongodb://218ffa09-0ee0-4-231-b9ee:zTV4cwDG0vM49J2GFsw72JzwOD79Bv3dPU8fbVLb5pbh3p0CmTBYcvhrFKTjtl1s7hgYSfRbMOrsVve6hfvhag==@218ffa09-0ee0-4-231-b9ee.documents.azure.com:10255/?ssl=true&replicaSet=globaldb\" client = pymongo.MongoClient(uri) print(\"Obtained the client\") mydb =", "a = mydb.userInfo.find_one({\"name\":jsonData[\"name\"]}) newDbref = DBRef(\"mydb.userInfo\",a[\"_id\"]) foundMails = mydb.mltable.find({\"otherdbref\":newDbref,\"status\":\"trash\"}) foundMailsList", "* (num - 1) if(jsonData[\"action\"] == \"all\"): all_list = list(mydb.userMailInfo.find({\"userDeleted\":False},{'_id'", "new_list = new_list[:10] new_list_new = list() for item in new_list:", "value =\"+colorCode) import qrcode img = qrcode.make(colorCode) logger.debug(type(img)) autoThrashed =", "new_list[skips:] new_list = new_list[:10] new_list_new = list() for item in", "str(today.day) time = str(today.hour) + \":\" + str(today.minute) + \":\"", "if(fromMFP): newjsonData[\"source\"] = \"MFP\" else: newjsonData[\"source\"] = \"Mobile\" return addEntry(newjsonData,tags,autoThrashed);", "else: all_list = list(mydb.userMailInfo.find({\"userDeleted\":False},{'_id' : 0,'user_id':0})) thrash_date = datetime.datetime.today() thrash_date", "=\"+colorCode) import qrcode img = qrcode.make(colorCode) logger.debug(type(img)) autoThrashed = checkIfAutoThrashed(jsonData,tags)", "\"2\":\"2\", \"3\":\"3\", \"4\":\"4\", \"5\":\"5\", \"6\":\"6\" } }, \"TTEC-CI\":{ \"id\":\"DEP4\", \"floor\":{\"0\":\"0\",", "\"4\":\"4\", \"5\":\"5\", \"6\":\"6\" } }, \"Imaging\":{ \"id\":\"DEP3\", \"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\",", "import StringIO import json from bson.dbref import DBRef import datetime", "mydb.mltable.find({\"otherdbref\":newDbref,\"status\":\"trash\"}) foundMailsList = list(mydb.mltable.find({\"otherdbref\":newDbref,\"status\":\"trash\"})) if(len(foundMailsList) < 10): return False tagcount", "False tagcount = 0 thrashcount = 0 for item in", "} } } } }, \"Fortune Summit\": { \"id\": \"B2\",", "json_util import logging import base64 jsonCode ={ \"building\":{ \"Essae Vaishnavi", "tags) import sendEmail as se se.execute(str(jsonData[\"email\"]),filenameJPG,str(colorCode),img,autoThrashed,fromMFP) #img = qrcode.make(colorCode) #img.save(colorCode+\".png\")", "% autoThrashed) logger.debug(\"Tags are %s\" % tags) import sendEmail as", "all_list.reverse() totalsize = len(all_list) all_list = all_list[skips:] all_list = all_list[:10]", "3): return False a = mydb.userInfo.find_one({\"name\":jsonData[\"name\"]}) newDbref = DBRef(\"mydb.userInfo\",a[\"_id\"]) foundMails", "= len(all_list) all_list = all_list[skips:] all_list = all_list[:10] new_list_new =", "\"3\":\"3\", \"4\":\"4\", \"5\":\"5\", \"6\":\"6\" } } } }, \"tmc\": {", "+ str(thrash_date.year) thrash_date = datetime.datetime.strptime(thrash_date, '%d-%m-%Y').date() new_list = list() for", "- 1) if(jsonData[\"action\"] == \"all\"): all_list = list(mydb.userMailInfo.find({\"userDeleted\":False},{'_id' : 0,'user_id':0}))", "if(db_date == thrash_date): new_list.append(item) new_list.reverse() totalsize = len(new_list) new_list =", "mydb = client.test def sortingReq(item): new_thrash_date = datetime.datetime.strptime(item[\"scan_date\"], '%d-%m-%Y').date() return", "} }, \"TTEC\": { \"id\": \"D2\", \"dept\":{ \"TTEC-AL\":{ \"id\":\"DEP1\", \"floor\":{\"0\":\"0\",", "all_list = all_list[:10] new_list_new = list() for item in all_list:", "\"TTEC-CI\":{ \"id\":\"DEP4\", \"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\", \"3\":\"3\", \"4\":\"4\", \"5\":\"5\", \"6\":\"6\" }", "all_list[skips:] all_list = all_list[:10] new_list_new = list() for item in", "\"6\":\"6\" } } } }, \"TTEC\": { \"id\": \"D2\", \"dept\":{", "} }, \"TTEC-CI\":{ \"id\":\"DEP4\", \"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\", \"3\":\"3\", \"4\":\"4\", \"5\":\"5\",", "} } #Create and configure logger logging.basicConfig(filename=\"server.log\", format='%(asctime)s %(message)s', filemode='a')", "\"Mobile\":{ \"id\":\"DEP3\", \"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\", \"3\":\"3\", \"4\":\"4\", \"5\":\"5\", \"6\":\"6\" }", "3): #mydb.mltable.insert({\"code\":jsonData[\"code\"],\"tags\": tags,\"status\":\"Keep\",\"user_id\":1,\"otherdbref\":newDbref}) Actual Code mydb.mltable.insert({\"code\":jsonData[\"code\"],\"tags\": tags,\"status\":\"Keep\",\"user_id\":1,\"otherdbref\":newDbref})#Test code to be", "print(\"Obtained the client\") mydb = client.test def sortingReq(item): new_thrash_date =", "'%d-%m-%Y').date() return new_thrash_date def checkIfAutoThrashed(jsonData,tags): if(len(tags) < 3): return False", "= qrcode.make(colorCode) logger.debug(type(img)) autoThrashed = checkIfAutoThrashed(jsonData,tags) logger.debug(\"Auto thrashed value is", "client = pymongo.MongoClient(uri) print(\"Obtained the client\") mydb = client.test def", "\"id\":\"DEP1\", \"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\", \"3\":\"3\", \"4\":\"4\", \"5\":\"5\", \"6\":\"6\" } },", "tags,\"status\":\"Keep\",\"user_id\":1,\"otherdbref\":newDbref}) Actual Code mydb.mltable.insert({\"code\":jsonData[\"code\"],\"tags\": tags,\"status\":\"Keep\",\"user_id\":1,\"otherdbref\":newDbref})#Test code to be removed #end_date", "logger.debug(new_list_new) return json.dumps(new_list_new, default=json_util.default) def update_DB(jsonData): logger.debug(\"DBUMI::Update_db() entry\") logger.debug(jsonData[\"code\"]) logger.debug(jsonData[\"end_date\"])", "= client.test def sortingReq(item): new_thrash_date = datetime.datetime.strptime(item[\"scan_date\"], '%d-%m-%Y').date() return new_thrash_date", "#mydb.mltable.insert({\"code\":jsonData[\"code\"],\"tags\": tags,\"status\":\"Keep\",\"user_id\":1,\"otherdbref\":newDbref}) Actual Code mydb.mltable.insert({\"code\":jsonData[\"code\"],\"tags\": tags,\"status\":\"Keep\",\"user_id\":1,\"otherdbref\":newDbref})#Test code to be removed", "}, \"TTEC-SL\":{ \"id\":\"DEP2\", \"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\", \"3\":\"3\", \"4\":\"4\", \"5\":\"5\", \"6\":\"6\"", "dall.update(item) dall.update(newjson) print(dall) new_list.append(dall) new_list.reverse() return json.dumps(new_list,default=json_util.default) def getspecificDate(jsonData): logger.debug(jsonData)", "} }, \"tmc\": { \"id\": \"D2\", \"dept\":{ \"tmc-1\":{ \"id\":\"DEP1\", \"floor\":{\"0\":\"0\",", "testing def delete_entry(jsonData): logger.debug(\"DBUMI::delete_entry() entry\") logger.debug(jsonData[\"code\"]) mydb.userMailInfo.delete_one({\"code\":jsonData[\"code\"],\"user_id\":1}) return json.dumps({\"status\": \"Success\",\"statusreason\":", "print(item) otherdbref = item[\"otherdbref\"] newjson = mydb.userInfo.find_one({\"_id\":otherdbref.id},{\"_id\":0,\"user_id\":0}) dall = {}", "= mydb.mltable.find_one({\"code\":jsonData[\"code\"]},{\"_id\":1}) logger.debug(foundMl) mydb.userMailInfo.update_many({\"_id\":foundmail[\"_id\"],\"user_id\":1},{\"$set\":{'end_date':str(jsonData['end_date'])}}) if(not jsonData['end_date'] == \"DONT TRASH\"): mydb.mltable.update_many({\"_id\":foundMl[\"_id\"],\"user_id\":1},{\"$set\":{\"status\":\"trash\"}})", "json.dumps({\"status\": \"Success\",\"statusreason\": \"updateSucess\"}) #Clear DB only for testing def delete_entry(jsonData):", "% tags) import sendEmail as se se.execute(str(jsonData[\"email\"]),filenameJPG,str(colorCode),img,autoThrashed,fromMFP) #img = qrcode.make(colorCode)", "autoThrashed and len(tags) >= 3): #mydb.mltable.insert({\"code\":jsonData[\"code\"],\"tags\": tags,\"status\":\"Keep\",\"user_id\":1,\"otherdbref\":newDbref}) Actual Code mydb.mltable.insert({\"code\":jsonData[\"code\"],\"tags\":", "only for testing def delete_entry(jsonData): logger.debug(\"DBUMI::delete_entry() entry\") logger.debug(jsonData[\"code\"]) mydb.userMailInfo.delete_one({\"code\":jsonData[\"code\"],\"user_id\":1}) return", "str(today.day)+str(today.hour)+str(today.minute)+str(today.second)+(str(today.microsecond)[:2]) logger.debug(\"Unique Code - \"+dateTimeNow) if(int(jsonData[\"cubicle\"])>25 and int(jsonData[\"cubicle\"])<=50): ilocation=2 elif(int(jsonData[\"cubicle\"])>50", "} #Create and configure logger logging.basicConfig(filename=\"server.log\", format='%(asctime)s %(message)s', filemode='a') #Creating", "= str(scan_date.day) +\"-\"+ str(scan_date.month)+\"-\" + str(scan_date.year) end_date = str(end_date.day) +\"-\"", "mydb.userInfo.find_one({\"name\":jsonData[\"name\"]}) newDbref = DBRef(\"mydb.userInfo\",a[\"_id\"]) scan_date = datetime.datetime.today() scan_date = scan_date", "+str(thrash_date.month)+\"-\" + str(thrash_date.year) thrash_date = datetime.datetime.strptime(thrash_date, '%d-%m-%Y').date() new_list = list()", "new_list_new = list() for item in new_list: otherdbref = item[\"otherdbref\"]", "len(all_list) all_list = all_list[skips:] all_list = all_list[:10] new_list_new = list()", "all_list = list(mydb.userMailInfo.find({\"userDeleted\":False},{'_id' : 0,'user_id':0})) thrash_date = datetime.datetime.today() thrash_date =", "\"6\":\"6\" } } } } } }, \"Fortune Summit\": {", "\"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\", \"3\":\"3\", \"4\":\"4\", \"5\":\"5\", \"6\":\"6\" } }, \"tmc-2\":{", "int(jsonData[\"cubicle\"])<=75): ilocation=3 else: ilocation=4 logger.debug(jsonData[\"building\"]) colorCode=jsonCode[\"building\"][jsonData[\"building\"]][\"id\"]+':'+jsonCode[\"building\"][jsonData[\"building\"]][\"division\"][jsonData[\"division\"]][\"id\"]+':'+dateTimeNow logger.debug(\"ColorCode - \"+colorCode) logger.debug(\"generateColorCode::", "= DBRef(\"mydb.userInfo\",a[\"_id\"]) foundMails = mydb.mltable.find({\"otherdbref\":newDbref,\"status\":\"trash\"}) foundMailsList = list(mydb.mltable.find({\"otherdbref\":newDbref,\"status\":\"trash\"})) if(len(foundMailsList) <", "False a = mydb.userInfo.find_one({\"name\":jsonData[\"name\"]}) newDbref = DBRef(\"mydb.userInfo\",a[\"_id\"]) foundMails = mydb.mltable.find({\"otherdbref\":newDbref,\"status\":\"trash\"})", "pymongo uri = \"mongodb://218ffa09-0ee0-4-231-b9ee:zTV4cwDG0vM49J2GFsw72JzwOD79Bv3dPU8fbVLb5pbh3p0CmTBYcvhrFKTjtl1s7hgYSfRbMOrsVve6hfvhag==@218ffa09-0ee0-4-231-b9ee.documents.azure.com:10255/?ssl=true&replicaSet=globaldb\" client = pymongo.MongoClient(uri) print(\"Obtained the client\")", "autoThrashed return json.dumps(jsonData) def read_fromDB(): new_list = list() for item", "jsonCode ={ \"building\":{ \"Essae Vaishnavi Solitaire\": { \"id\": \"B1\", \"division\":", "if(len(tags) < 3): return False a = mydb.userInfo.find_one({\"name\":jsonData[\"name\"]}) newDbref =", "ilocation=3 else: ilocation=4 logger.debug(jsonData[\"building\"]) colorCode=jsonCode[\"building\"][jsonData[\"building\"]][\"id\"]+':'+jsonCode[\"building\"][jsonData[\"building\"]][\"division\"][jsonData[\"division\"]][\"id\"]+':'+dateTimeNow logger.debug(\"ColorCode - \"+colorCode) logger.debug(\"generateColorCode:: ColorCode", "{ \"id\": \"B1\", \"division\": { \"SS\": { \"id\": \"D1\", \"dept\":{", "} }, \"Imaging\":{ \"id\":\"DEP3\", \"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\", \"3\":\"3\", \"4\":\"4\", \"5\":\"5\",", "format='%(asctime)s %(message)s', filemode='a') #Creating an object logger=logging.getLogger() #Setting the threshold", "\"B2\", \"division\": { \"TMSC\": { \"id\": \"D1\", \"dept\":{ \"Medical\":{ \"id\":\"DEP1\",", "and len(tags) >= 3): #mydb.mltable.insert({\"code\":jsonData[\"code\"],\"tags\": tags,\"status\":\"Keep\",\"user_id\":1,\"otherdbref\":newDbref}) Actual Code mydb.mltable.insert({\"code\":jsonData[\"code\"],\"tags\": tags,\"status\":\"Keep\",\"user_id\":1,\"otherdbref\":newDbref})#Test", "list() for item in all_list: otherdbref = item[\"otherdbref\"] newjson =", "0,'user_id':0})) all_list.reverse() totalsize = len(all_list) all_list = all_list[skips:] all_list =", "io import StringIO import json from bson.dbref import DBRef import", "if(len(foundMailsList) < 10): return False tagcount = 0 thrashcount =", "\"id\": \"D2\", \"dept\":{ \"TTEC-AL\":{ \"id\":\"DEP1\", \"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\", \"3\":\"3\", \"4\":\"4\",", "3): thrashcount+=1 if(thrashcount >=10): return True return False def generateqrcode(jsonData,filenameJPG,tags,fromMFP):", "\"3\":\"3\", \"4\":\"4\", \"5\":\"5\", \"6\":\"6\" } } } }, \"TTEC\": {", "return json.dumps(new_list,default=json_util.default) def getspecificDate(jsonData): logger.debug(jsonData) num = int(jsonData['page']) skips =", "= list() for item in all_list: otherdbref = item[\"otherdbref\"] newjson", "newjson = mydb.userInfo.find_one({\"_id\":otherdbref.id},{\"_id\":0,\"user_id\":0}) dall = {} item.pop(\"otherdbref\") dall.update(item) dall.update(newjson) print(dall)", "\"Medical\":{ \"id\":\"DEP1\", \"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\", \"3\":\"3\", \"4\":\"4\", \"5\":\"5\", \"6\":\"6\" }", "+ str(scan_date.year) end_date = str(end_date.day) +\"-\" +str(end_date.month)+\"-\" + str(end_date.year) if(autoThrashed):", "item.pop(\"otherdbref\") dall.update(item) dall.update(newjson) print(dall) new_list.append(dall) new_list.reverse() return json.dumps(new_list,default=json_util.default) def getspecificDate(jsonData):", "in mydb.userMailInfo.find({},{\"_id\":0,\"user_id\":0}): print(item) otherdbref = item[\"otherdbref\"] newjson = mydb.userInfo.find_one({\"_id\":otherdbref.id},{\"_id\":0,\"user_id\":0}) dall", "in all_list: if(item['end_date'] == \"DONT TRASH\"): continue db_date = datetime.datetime.strptime(item['end_date'],'%d-%m-%Y').date()", "'%d-%m-%Y').date() new_list = list() for item in all_list: db_date =", "scan_date mydb.userMailInfo.insert({\"code\":jsonData[\"code\"],\"scan_date\":scan_date,\"end_date\":end_date,\"otherdbref\":newDbref,\"userDeleted\":False,\"user_id\":1,\"source\":jsonData[\"source\"]}) jsonData[\"autoThrashed\"] = autoThrashed return json.dumps(jsonData) def read_fromDB(): new_list", "\"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\", \"3\":\"3\", \"4\":\"4\", \"5\":\"5\", \"6\":\"6\" } }, \"Mobile\":{", "img = qrcode.make(colorCode) logger.debug(type(img)) autoThrashed = checkIfAutoThrashed(jsonData,tags) logger.debug(\"Auto thrashed value", "json.dumps(new_list,default=json_util.default) def getspecificDate(jsonData): logger.debug(jsonData) num = int(jsonData['page']) skips = 10", "new_list[:10] new_list_new = list() for item in new_list: otherdbref =", "\"TTEC-AL\":{ \"id\":\"DEP1\", \"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\", \"3\":\"3\", \"4\":\"4\", \"5\":\"5\", \"6\":\"6\" }", "\"updateSucess\"}) #Clear DB only for testing def delete_entry(jsonData): logger.debug(\"DBUMI::delete_entry() entry\")", "0,'user_id':0})) thrash_date = datetime.datetime.today() thrash_date = thrash_date + datetime.timedelta(hours=9) thrash_date", "mydb.userMailInfo.insert({\"code\":jsonData[\"code\"],\"scan_date\":scan_date,\"end_date\":end_date,\"otherdbref\":newDbref,\"userDeleted\":False,\"user_id\":1,\"source\":jsonData[\"source\"]}) jsonData[\"autoThrashed\"] = autoThrashed return json.dumps(jsonData) def read_fromDB(): new_list =", "} } } }, \"Fortune Summit\": { \"id\": \"B2\", \"division\":", "thrash_date = datetime.datetime.strptime(thrash_date, '%d-%m-%Y').date() new_list = list() for item in", "\"3\":\"3\", \"4\":\"4\", \"5\":\"5\", \"6\":\"6\" } } } } } },", "str(today.second)+\":\"+str(today.microsecond) dateTimeNow = date+':'+time logger.debug(\"Current Datetime - \"+dateTimeNow) dateTimeNow =", "\"2\":\"2\", \"3\":\"3\", \"4\":\"4\", \"5\":\"5\", \"6\":\"6\" } }, \"Imaging\":{ \"id\":\"DEP3\", \"floor\":{\"0\":\"0\",", "logger.debug(jsonData) num = int(jsonData['page']) skips = 10 * (num -", "\"1\":\"1\", \"2\":\"2\", \"3\":\"3\", \"4\":\"4\", \"5\":\"5\", \"6\":\"6\" } }, \"Mobile\":{ \"id\":\"DEP3\",", "= str(thrash_date.day) + \"-\" +str(thrash_date.month)+\"-\" + str(thrash_date.year) thrash_date = datetime.datetime.strptime(thrash_date,", "\"1\":\"1\", \"2\":\"2\", \"3\":\"3\", \"4\":\"4\", \"5\":\"5\", \"6\":\"6\" } } } },", "= \"Mobile\" return addEntry(newjsonData,tags,autoThrashed); def addEntry(jsonData,tags,autoThrashed): a = mydb.userInfo.find_one({\"name\":jsonData[\"name\"]}) newDbref", "\"TMSC\": { \"id\": \"D1\", \"dept\":{ \"Medical\":{ \"id\":\"DEP1\", \"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\",", "print(dall) new_list_new.append(dall) new_list_new.append({\"totalsize\":totalsize}) logger.debug(new_list_new) return json.dumps(new_list_new, default=json_util.default) def update_DB(jsonData): logger.debug(\"DBUMI::Update_db()", "\"dept\":{ \"Semicon\":{ \"id\":\"DEP1\", \"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\", \"3\":\"3\", \"4\":\"4\", \"5\":\"5\", \"6\":\"6\"", "\"D1\", \"dept\":{ \"Semicon\":{ \"id\":\"DEP1\", \"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\", \"3\":\"3\", \"4\":\"4\", \"5\":\"5\",", "totalsize = len(new_list) new_list = new_list[skips:] new_list = new_list[:10] new_list_new", "list(mydb.mltable.find({\"otherdbref\":newDbref,\"status\":\"trash\"})) if(len(foundMailsList) < 10): return False tagcount = 0 thrashcount", "+\"-\"+ str(scan_date.month)+\"-\" + str(scan_date.year) end_date = str(end_date.day) +\"-\" +str(end_date.month)+\"-\" +", "import json from bson.dbref import DBRef import datetime from bson", ": x[\"name\"]) return json.dumps(new_list_new, default=json_util.default) elif(jsonData[\"action\"] == \"today\"): all_list =", "\"Success\",\"statusreason\": \"updateSucess\"}) #Clear DB only for testing def delete_entry(jsonData): logger.debug(\"DBUMI::delete_entry()", "\"building\":{ \"Essae Vaishnavi Solitaire\": { \"id\": \"B1\", \"division\": { \"SS\":", "sendEmail as se se.execute(str(jsonData[\"email\"]),filenameJPG,str(colorCode),img,autoThrashed,fromMFP) #img = qrcode.make(colorCode) #img.save(colorCode+\".png\") newjsonData =", "\"6\":\"6\" } }, \"Imaging\":{ \"id\":\"DEP3\", \"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\", \"3\":\"3\", \"4\":\"4\",", "datetime.datetime.today() thrash_date = thrash_date + datetime.timedelta(hours=9) thrash_date = str(thrash_date.day) +", "if(db_date <= thrash_date): new_list.append(item) new_list.reverse() totalsize = len(new_list) new_list =", "all_list: db_date = datetime.datetime.strptime(item['scan_date'],'%d-%m-%Y').date() if(db_date == thrash_date): new_list.append(item) new_list.reverse() totalsize", "all_list = list(mydb.userMailInfo.find({\"userDeleted\":False},{'_id' : 0,'user_id':0})) all_list.reverse() totalsize = len(all_list) all_list", "import datetime from bson import json_util import logging import base64", "x[\"name\"]) return json.dumps(new_list_new, default=json_util.default) elif(jsonData[\"action\"] == \"today\"): all_list = list(mydb.userMailInfo.find({\"userDeleted\":False},{'_id'", "= datetime.datetime.strptime(item['end_date'],'%d-%m-%Y').date() if(db_date <= thrash_date): new_list.append(item) new_list.reverse() totalsize = len(new_list)", "jsonData['end_date'] == \"DONT TRASH\"): mydb.mltable.update_many({\"_id\":foundMl[\"_id\"],\"user_id\":1},{\"$set\":{\"status\":\"trash\"}}) return json.dumps({\"status\": \"Success\",\"statusreason\": \"updateSucess\"}) #Clear", "\"D1\", \"dept\":{ \"Medical\":{ \"id\":\"DEP1\", \"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\", \"3\":\"3\", \"4\":\"4\", \"5\":\"5\",", "#Setting the threshold of logger to DEBUG logger.setLevel(logging.DEBUG) import pymongo", "\"4\":\"4\", \"5\":\"5\", \"6\":\"6\" } } } }, \"TTEC\": { \"id\":", "} } } #Create and configure logger logging.basicConfig(filename=\"server.log\", format='%(asctime)s %(message)s',", "}, \"tmc-3\":{ \"id\":\"DEP3\", \"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\", \"3\":\"3\", \"4\":\"4\", \"5\":\"5\", \"6\":\"6\"", "#end_date = scan_date mydb.userMailInfo.insert({\"code\":jsonData[\"code\"],\"scan_date\":scan_date,\"end_date\":end_date,\"otherdbref\":newDbref,\"userDeleted\":False,\"user_id\":1,\"source\":jsonData[\"source\"]}) jsonData[\"autoThrashed\"] = autoThrashed return json.dumps(jsonData) def", "newjsonData[\"source\"] = \"Mobile\" return addEntry(newjsonData,tags,autoThrashed); def addEntry(jsonData,tags,autoThrashed): a = mydb.userInfo.find_one({\"name\":jsonData[\"name\"]})", "jsonData[\"autoThrashed\"] = autoThrashed return json.dumps(jsonData) def read_fromDB(): new_list = list()", "thrashcount = 0 for item in foundMails: for tag in", "generateqrcode(jsonData,filenameJPG,tags,fromMFP): logger.debug(\"Received data for generating color code = \") logger.debug(jsonData)", "db_date = datetime.datetime.strptime(item['end_date'],'%d-%m-%Y').date() if(db_date <= thrash_date): new_list.append(item) new_list.reverse() totalsize =", "return False def generateqrcode(jsonData,filenameJPG,tags,fromMFP): logger.debug(\"Received data for generating color code", "str(end_date.year) if(autoThrashed): end_date = scan_date if( not autoThrashed and len(tags)", "{ \"id\": \"D1\", \"dept\":{ \"Semicon\":{ \"id\":\"DEP1\", \"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\", \"3\":\"3\",", "entry\") logger.debug(jsonData[\"code\"]) logger.debug(jsonData[\"end_date\"]) foundmail = mydb.userMailInfo.find_one({\"code\":jsonData[\"code\"]},{\"_id\":1}) logger.debug(foundmail) foundMl = mydb.mltable.find_one({\"code\":jsonData[\"code\"]},{\"_id\":1})", "newjsonData = {\"name\":jsonData[\"name\"],\"code\":colorCode,\"email\":jsonData[\"email\"],\"division\":jsonData[\"division\"],\"department\":jsonData[\"department\"],\"floor\":jsonData[\"floor\"],\"cubicle\":jsonData[\"cubicle\"],\"building\":jsonData[\"building\"]} if(fromMFP): newjsonData[\"source\"] = \"MFP\" else: newjsonData[\"source\"] =", "removed #end_date = scan_date mydb.userMailInfo.insert({\"code\":jsonData[\"code\"],\"scan_date\":scan_date,\"end_date\":end_date,\"otherdbref\":newDbref,\"userDeleted\":False,\"user_id\":1,\"source\":jsonData[\"source\"]}) jsonData[\"autoThrashed\"] = autoThrashed return json.dumps(jsonData)", "int(jsonData['page']) skips = 10 * (num - 1) if(jsonData[\"action\"] ==", "== \"DONT TRASH\"): mydb.mltable.update_many({\"_id\":foundMl[\"_id\"],\"user_id\":1},{\"$set\":{\"status\":\"trash\"}}) return json.dumps({\"status\": \"Success\",\"statusreason\": \"updateSucess\"}) #Clear DB", "} } } } } }, \"Fortune Summit\": { \"id\":", "print(dall) new_list_new.append(dall) new_list_new.append({\"totalsize\":totalsize}) logger.debug(new_list_new) #new_list_new.sort(key = lambda x : x[\"name\"])", "if(thrashcount >=10): return True return False def generateqrcode(jsonData,filenameJPG,tags,fromMFP): logger.debug(\"Received data", "thrashed value is %d\" % autoThrashed) logger.debug(\"Tags are %s\" %", "mydb.mltable.find_one({\"code\":jsonData[\"code\"]},{\"_id\":1}) logger.debug(foundMl) mydb.userMailInfo.update_many({\"_id\":foundmail[\"_id\"],\"user_id\":1},{\"$set\":{'end_date':str(jsonData['end_date'])}}) if(not jsonData['end_date'] == \"DONT TRASH\"): mydb.mltable.update_many({\"_id\":foundMl[\"_id\"],\"user_id\":1},{\"$set\":{\"status\":\"trash\"}}) return", "\"MFP\" else: newjsonData[\"source\"] = \"Mobile\" return addEntry(newjsonData,tags,autoThrashed); def addEntry(jsonData,tags,autoThrashed): a", "\"2\":\"2\", \"3\":\"3\", \"4\":\"4\", \"5\":\"5\", \"6\":\"6\" } }, \"RND\":{ \"id\":\"DEP2\", \"floor\":{\"0\":\"0\",", "dateTimeNow = str(today.day)+str(today.hour)+str(today.minute)+str(today.second)+(str(today.microsecond)[:2]) logger.debug(\"Unique Code - \"+dateTimeNow) if(int(jsonData[\"cubicle\"])>25 and int(jsonData[\"cubicle\"])<=50):", "se.execute(str(jsonData[\"email\"]),filenameJPG,str(colorCode),img,autoThrashed,fromMFP) #img = qrcode.make(colorCode) #img.save(colorCode+\".png\") newjsonData = {\"name\":jsonData[\"name\"],\"code\":colorCode,\"email\":jsonData[\"email\"],\"division\":jsonData[\"division\"],\"department\":jsonData[\"department\"],\"floor\":jsonData[\"floor\"],\"cubicle\":jsonData[\"cubicle\"],\"building\":jsonData[\"building\"]} if(fromMFP): newjsonData[\"source\"]", "\"id\": \"B2\", \"division\": { \"TMSC\": { \"id\": \"D1\", \"dept\":{ \"Medical\":{", "\"2\":\"2\", \"3\":\"3\", \"4\":\"4\", \"5\":\"5\", \"6\":\"6\" } } } }, \"tmc\":", "new_list.append(item) new_list.reverse() totalsize = len(new_list) new_list = new_list[skips:] new_list =", "== thrash_date): new_list.append(item) new_list.reverse() totalsize = len(new_list) new_list = new_list[skips:]", "base64 jsonCode ={ \"building\":{ \"Essae Vaishnavi Solitaire\": { \"id\": \"B1\",", "logger.debug(foundmail) foundMl = mydb.mltable.find_one({\"code\":jsonData[\"code\"]},{\"_id\":1}) logger.debug(foundMl) mydb.userMailInfo.update_many({\"_id\":foundmail[\"_id\"],\"user_id\":1},{\"$set\":{'end_date':str(jsonData['end_date'])}}) if(not jsonData['end_date'] == \"DONT", "#new_list_new.sort(key = lambda x : x[\"name\"]) return json.dumps(new_list_new, default=json_util.default) else:", "{ \"id\": \"D1\", \"dept\":{ \"Medical\":{ \"id\":\"DEP1\", \"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\", \"3\":\"3\",", "= datetime.datetime.strptime(item[\"scan_date\"], '%d-%m-%Y').date() return new_thrash_date def checkIfAutoThrashed(jsonData,tags): if(len(tags) < 3):", "}, \"TTEC\": { \"id\": \"D2\", \"dept\":{ \"TTEC-AL\":{ \"id\":\"DEP1\", \"floor\":{\"0\":\"0\", \"1\":\"1\",", "\"3\":\"3\", \"4\":\"4\", \"5\":\"5\", \"6\":\"6\" } }, \"Mobile\":{ \"id\":\"DEP3\", \"floor\":{\"0\":\"0\", \"1\":\"1\",", ">=10): return True return False def generateqrcode(jsonData,filenameJPG,tags,fromMFP): logger.debug(\"Received data for", "logging.basicConfig(filename=\"server.log\", format='%(asctime)s %(message)s', filemode='a') #Creating an object logger=logging.getLogger() #Setting the", "{ \"id\": \"B2\", \"division\": { \"TMSC\": { \"id\": \"D1\", \"dept\":{", "\"2\":\"2\", \"3\":\"3\", \"4\":\"4\", \"5\":\"5\", \"6\":\"6\" } }, \"tmc-2\":{ \"id\":\"DEP2\", \"floor\":{\"0\":\"0\",", "\"Essae Vaishnavi Solitaire\": { \"id\": \"B1\", \"division\": { \"SS\": {", "\"-\" +str(thrash_date.month)+\"-\" + str(thrash_date.year) thrash_date = datetime.datetime.strptime(thrash_date, '%d-%m-%Y').date() new_list =", "thrashcount+=1 if(thrashcount >=10): return True return False def generateqrcode(jsonData,filenameJPG,tags,fromMFP): logger.debug(\"Received", "\"5\":\"5\", \"6\":\"6\" } } } }, \"TTEC\": { \"id\": \"D2\",", "str(today.minute) + \":\" + str(today.second)+\":\"+str(today.microsecond) dateTimeNow = date+':'+time logger.debug(\"Current Datetime", "\"D2\", \"dept\":{ \"tmc-1\":{ \"id\":\"DEP1\", \"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\", \"3\":\"3\", \"4\":\"4\", \"5\":\"5\",", "dateTimeNow = date+':'+time logger.debug(\"Current Datetime - \"+dateTimeNow) dateTimeNow = str(today.day)+str(today.hour)+str(today.minute)+str(today.second)+(str(today.microsecond)[:2])", "thrash_date = datetime.datetime.today() thrash_date = thrash_date + datetime.timedelta(hours=9) thrash_date =", "date+':'+time logger.debug(\"Current Datetime - \"+dateTimeNow) dateTimeNow = str(today.day)+str(today.hour)+str(today.minute)+str(today.second)+(str(today.microsecond)[:2]) logger.debug(\"Unique Code", "= scan_date if( not autoThrashed and len(tags) >= 3): #mydb.mltable.insert({\"code\":jsonData[\"code\"],\"tags\":", "foundMails = mydb.mltable.find({\"otherdbref\":newDbref,\"status\":\"trash\"}) foundMailsList = list(mydb.mltable.find({\"otherdbref\":newDbref,\"status\":\"trash\"})) if(len(foundMailsList) < 10): return", "return json.dumps(jsonData) def read_fromDB(): new_list = list() for item in", "} }, \"Mobile\":{ \"id\":\"DEP3\", \"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\", \"3\":\"3\", \"4\":\"4\", \"5\":\"5\",", "sortingReq(item): new_thrash_date = datetime.datetime.strptime(item[\"scan_date\"], '%d-%m-%Y').date() return new_thrash_date def checkIfAutoThrashed(jsonData,tags): if(len(tags)", "for item in new_list: otherdbref = item[\"otherdbref\"] newjson = mydb.userInfo.find_one({\"_id\":otherdbref.id},{\"_id\":0,\"user_id\":0})", "\"4\":\"4\", \"5\":\"5\", \"6\":\"6\" } } } }, \"tmc\": { \"id\":", "\"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\", \"3\":\"3\", \"4\":\"4\", \"5\":\"5\", \"6\":\"6\" } }, \"TTEC-DL\":{", "otherdbref = item[\"otherdbref\"] newjson = mydb.userInfo.find_one({\"_id\":otherdbref.id},{\"_id\":0,\"user_id\":0}) dall = {} item.pop(\"otherdbref\")", "in foundMails: for tag in tags: if(tag in item[\"tags\"]): tagcount+=1", "= mydb.userInfo.find_one({\"name\":jsonData[\"name\"]}) newDbref = DBRef(\"mydb.userInfo\",a[\"_id\"]) scan_date = datetime.datetime.today() scan_date =", "pymongo.MongoClient(uri) print(\"Obtained the client\") mydb = client.test def sortingReq(item): new_thrash_date", "skips = 10 * (num - 1) if(jsonData[\"action\"] == \"all\"):", "\"6\":\"6\" } }, \"RND\":{ \"id\":\"DEP2\", \"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\", \"3\":\"3\", \"4\":\"4\",", "mydb.userInfo.find_one({\"_id\":otherdbref.id},{\"_id\":0,\"user_id\":0}) dall = {} item.pop(\"otherdbref\") dall.update(item) dall.update(newjson) print(dall) new_list.append(dall) new_list.reverse()", "all_list: otherdbref = item[\"otherdbref\"] newjson = mydb.userInfo.find_one({\"_id\":otherdbref.id},{\"_id\":0,\"user_id\":0}) dall = {}", "\"6\":\"6\" } }, \"Mobile\":{ \"id\":\"DEP3\", \"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\", \"3\":\"3\", \"4\":\"4\",", "item in new_list: otherdbref = item[\"otherdbref\"] newjson = mydb.userInfo.find_one({\"_id\":otherdbref.id},{\"_id\":0,\"user_id\":0}) dall", "new_list = list() for item in mydb.userMailInfo.find({},{\"_id\":0,\"user_id\":0}): print(item) otherdbref =", "= mydb.mltable.find({\"otherdbref\":newDbref,\"status\":\"trash\"}) foundMailsList = list(mydb.mltable.find({\"otherdbref\":newDbref,\"status\":\"trash\"})) if(len(foundMailsList) < 10): return False", "if(tag in item[\"tags\"]): tagcount+=1 if(tagcount >= 3): thrashcount+=1 if(thrashcount >=10):", "code = \") logger.debug(jsonData) ilocation=1 today = datetime.datetime.now() date =", "\"DONT TRASH\"): mydb.mltable.update_many({\"_id\":foundMl[\"_id\"],\"user_id\":1},{\"$set\":{\"status\":\"trash\"}}) return json.dumps({\"status\": \"Success\",\"statusreason\": \"updateSucess\"}) #Clear DB only", "\"5\":\"5\", \"6\":\"6\" } }, \"tmc-2\":{ \"id\":\"DEP2\", \"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\", \"3\":\"3\",", "= str(today.hour) + \":\" + str(today.minute) + \":\" + str(today.second)+\":\"+str(today.microsecond)", "{ \"id\": \"D2\", \"dept\":{ \"tmc-1\":{ \"id\":\"DEP1\", \"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\", \"3\":\"3\",", "thrash_date): new_list.append(item) new_list.reverse() totalsize = len(new_list) new_list = new_list[skips:] new_list", "bson.dbref import DBRef import datetime from bson import json_util import", "\"3\":\"3\", \"4\":\"4\", \"5\":\"5\", \"6\":\"6\" } } } } } }", "def generateqrcode(jsonData,filenameJPG,tags,fromMFP): logger.debug(\"Received data for generating color code = \")", "\"RND\":{ \"id\":\"DEP2\", \"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\", \"3\":\"3\", \"4\":\"4\", \"5\":\"5\", \"6\":\"6\" }", "= list() for item in all_list: if(item['end_date'] == \"DONT TRASH\"):", "Summit\": { \"id\": \"B2\", \"division\": { \"TMSC\": { \"id\": \"D1\",", "all_list[:10] new_list_new = list() for item in all_list: otherdbref =", "logger.debug(\"Tags are %s\" % tags) import sendEmail as se se.execute(str(jsonData[\"email\"]),filenameJPG,str(colorCode),img,autoThrashed,fromMFP)", "logger.debug(\"DBUMI::Update_db() entry\") logger.debug(jsonData[\"code\"]) logger.debug(jsonData[\"end_date\"]) foundmail = mydb.userMailInfo.find_one({\"code\":jsonData[\"code\"]},{\"_id\":1}) logger.debug(foundmail) foundMl =", "elif(jsonData[\"action\"] == \"today\"): all_list = list(mydb.userMailInfo.find({\"userDeleted\":False},{'_id' : 0,'user_id':0})) thrash_date =", "= datetime.datetime.today() thrash_date = thrash_date + datetime.timedelta(hours=9) thrash_date = str(thrash_date.day)", "\"3\":\"3\", \"4\":\"4\", \"5\":\"5\", \"6\":\"6\" } }, \"TTEC-SL\":{ \"id\":\"DEP2\", \"floor\":{\"0\":\"0\", \"1\":\"1\",", "\"id\": \"D2\", \"dept\":{ \"tmc-1\":{ \"id\":\"DEP1\", \"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\", \"3\":\"3\", \"4\":\"4\",", "new_list_new = list() for item in all_list: otherdbref = item[\"otherdbref\"]", "\"Mobile\" return addEntry(newjsonData,tags,autoThrashed); def addEntry(jsonData,tags,autoThrashed): a = mydb.userInfo.find_one({\"name\":jsonData[\"name\"]}) newDbref =", "list() for item in all_list: db_date = datetime.datetime.strptime(item['scan_date'],'%d-%m-%Y').date() if(db_date ==", "%s\" % tags) import sendEmail as se se.execute(str(jsonData[\"email\"]),filenameJPG,str(colorCode),img,autoThrashed,fromMFP) #img =", "list(mydb.userMailInfo.find({\"userDeleted\":False},{'_id' : 0,'user_id':0})) all_list.reverse() totalsize = len(all_list) all_list = all_list[skips:]", "\"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\", \"3\":\"3\", \"4\":\"4\", \"5\":\"5\", \"6\":\"6\" } }, \"RND\":{", "and int(jsonData[\"cubicle\"])<=75): ilocation=3 else: ilocation=4 logger.debug(jsonData[\"building\"]) colorCode=jsonCode[\"building\"][jsonData[\"building\"]][\"id\"]+':'+jsonCode[\"building\"][jsonData[\"building\"]][\"division\"][jsonData[\"division\"]][\"id\"]+':'+dateTimeNow logger.debug(\"ColorCode - \"+colorCode)", "list(mydb.userMailInfo.find({\"userDeleted\":False},{'_id' : 0,'user_id':0})) thrash_date = datetime.datetime.today() thrash_date = thrash_date +", "\"4\":\"4\", \"5\":\"5\", \"6\":\"6\" } }, \"TTEC-DL\":{ \"id\":\"DEP3\", \"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\",", "\"3\":\"3\", \"4\":\"4\", \"5\":\"5\", \"6\":\"6\" } }, \"tmc-2\":{ \"id\":\"DEP2\", \"floor\":{\"0\":\"0\", \"1\":\"1\",", "#new_list_new.sort(key = lambda x : x[\"name\"]) return json.dumps(new_list_new, default=json_util.default) elif(jsonData[\"action\"]", "\"1\":\"1\", \"2\":\"2\", \"3\":\"3\", \"4\":\"4\", \"5\":\"5\", \"6\":\"6\" } }, \"tmc-2\":{ \"id\":\"DEP2\",", "scan_date + datetime.timedelta(hours=9) end_date = scan_date + datetime.timedelta(days=10) scan_date =", "scan_date + datetime.timedelta(days=10) scan_date = str(scan_date.day) +\"-\"+ str(scan_date.month)+\"-\" + str(scan_date.year)", "new_list = list() for item in all_list: if(item['end_date'] == \"DONT", "} } }, \"TTEC\": { \"id\": \"D2\", \"dept\":{ \"TTEC-AL\":{ \"id\":\"DEP1\",", "end_date = scan_date if( not autoThrashed and len(tags) >= 3):", "x : x[\"name\"]) return json.dumps(new_list_new, default=json_util.default) elif(jsonData[\"action\"] == \"today\"): all_list", "return json.dumps(new_list_new, default=json_util.default) elif(jsonData[\"action\"] == \"today\"): all_list = list(mydb.userMailInfo.find({\"userDeleted\":False},{'_id' :", "= list() for item in mydb.userMailInfo.find({},{\"_id\":0,\"user_id\":0}): print(item) otherdbref = item[\"otherdbref\"]", "import json_util import logging import base64 jsonCode ={ \"building\":{ \"Essae", "for item in mydb.userMailInfo.find({},{\"_id\":0,\"user_id\":0}): print(item) otherdbref = item[\"otherdbref\"] newjson =", "= mydb.userMailInfo.find_one({\"code\":jsonData[\"code\"]},{\"_id\":1}) logger.debug(foundmail) foundMl = mydb.mltable.find_one({\"code\":jsonData[\"code\"]},{\"_id\":1}) logger.debug(foundMl) mydb.userMailInfo.update_many({\"_id\":foundmail[\"_id\"],\"user_id\":1},{\"$set\":{'end_date':str(jsonData['end_date'])}}) if(not jsonData['end_date']", "if(item['end_date'] == \"DONT TRASH\"): continue db_date = datetime.datetime.strptime(item['end_date'],'%d-%m-%Y').date() if(db_date <=", "= datetime.datetime.today() scan_date = scan_date + datetime.timedelta(hours=9) end_date = scan_date", "= date+':'+time logger.debug(\"Current Datetime - \"+dateTimeNow) dateTimeNow = str(today.day)+str(today.hour)+str(today.minute)+str(today.second)+(str(today.microsecond)[:2]) logger.debug(\"Unique", "} }, \"TTEC-SL\":{ \"id\":\"DEP2\", \"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\", \"3\":\"3\", \"4\":\"4\", \"5\":\"5\",", "delete_entry(jsonData): logger.debug(\"DBUMI::delete_entry() entry\") logger.debug(jsonData[\"code\"]) mydb.userMailInfo.delete_one({\"code\":jsonData[\"code\"],\"user_id\":1}) return json.dumps({\"status\": \"Success\",\"statusreason\": \"updateSucess\"}) def", "\"mongodb://218ffa09-0ee0-4-231-b9ee:zTV4cwDG0vM49J2GFsw72JzwOD79Bv3dPU8fbVLb5pbh3p0CmTBYcvhrFKTjtl1s7hgYSfRbMOrsVve6hfvhag==@218ffa09-0ee0-4-231-b9ee.documents.azure.com:10255/?ssl=true&replicaSet=globaldb\" client = pymongo.MongoClient(uri) print(\"Obtained the client\") mydb = client.test", "} }, \"RND\":{ \"id\":\"DEP2\", \"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\", \"3\":\"3\", \"4\":\"4\", \"5\":\"5\",", "== \"all\"): all_list = list(mydb.userMailInfo.find({\"userDeleted\":False},{'_id' : 0,'user_id':0})) all_list.reverse() totalsize =", "\"2\":\"2\", \"3\":\"3\", \"4\":\"4\", \"5\":\"5\", \"6\":\"6\" } }, \"Mobile\":{ \"id\":\"DEP3\", \"floor\":{\"0\":\"0\",", "client\") mydb = client.test def sortingReq(item): new_thrash_date = datetime.datetime.strptime(item[\"scan_date\"], '%d-%m-%Y').date()", "logger=logging.getLogger() #Setting the threshold of logger to DEBUG logger.setLevel(logging.DEBUG) import", "logger logging.basicConfig(filename=\"server.log\", format='%(asctime)s %(message)s', filemode='a') #Creating an object logger=logging.getLogger() #Setting", "new_list_new.append(dall) new_list_new.append({\"totalsize\":totalsize}) logger.debug(new_list_new) return json.dumps(new_list_new, default=json_util.default) def update_DB(jsonData): logger.debug(\"DBUMI::Update_db() entry\")", "\"3\":\"3\", \"4\":\"4\", \"5\":\"5\", \"6\":\"6\" } }, \"Imaging\":{ \"id\":\"DEP3\", \"floor\":{\"0\":\"0\", \"1\":\"1\",", "\"division\": { \"SS\": { \"id\": \"D1\", \"dept\":{ \"Semicon\":{ \"id\":\"DEP1\", \"floor\":{\"0\":\"0\",", "for generating color code = \") logger.debug(jsonData) ilocation=1 today =", "datetime.datetime.today() scan_date = scan_date + datetime.timedelta(hours=9) end_date = scan_date +", ": 0,'user_id':0})) thrash_date = datetime.datetime.today() thrash_date = thrash_date + datetime.timedelta(hours=9)", "= list() for item in new_list: otherdbref = item[\"otherdbref\"] newjson", "= 10 * (num - 1) if(jsonData[\"action\"] == \"all\"): all_list", "\"today\"): all_list = list(mydb.userMailInfo.find({\"userDeleted\":False},{'_id' : 0,'user_id':0})) thrash_date = datetime.datetime.today() thrash_date", "qrcode img = qrcode.make(colorCode) logger.debug(type(img)) autoThrashed = checkIfAutoThrashed(jsonData,tags) logger.debug(\"Auto thrashed", "if(autoThrashed): end_date = scan_date if( not autoThrashed and len(tags) >=", "if(tagcount >= 3): thrashcount+=1 if(thrashcount >=10): return True return False", "+str(end_date.month)+\"-\" + str(end_date.year) if(autoThrashed): end_date = scan_date if( not autoThrashed", "list() for item in mydb.userMailInfo.find({},{\"_id\":0,\"user_id\":0}): print(item) otherdbref = item[\"otherdbref\"] newjson", "if(int(jsonData[\"cubicle\"])>25 and int(jsonData[\"cubicle\"])<=50): ilocation=2 elif(int(jsonData[\"cubicle\"])>50 and int(jsonData[\"cubicle\"])<=75): ilocation=3 else: ilocation=4", "end_date = str(end_date.day) +\"-\" +str(end_date.month)+\"-\" + str(end_date.year) if(autoThrashed): end_date =", "= pymongo.MongoClient(uri) print(\"Obtained the client\") mydb = client.test def sortingReq(item):", "an object logger=logging.getLogger() #Setting the threshold of logger to DEBUG", "\"1\":\"1\", \"2\":\"2\", \"3\":\"3\", \"4\":\"4\", \"5\":\"5\", \"6\":\"6\" } }, \"RND\":{ \"id\":\"DEP2\",", "def delete_entry(jsonData): logger.debug(\"DBUMI::delete_entry() entry\") logger.debug(jsonData[\"code\"]) mydb.userMailInfo.delete_one({\"code\":jsonData[\"code\"],\"user_id\":1}) return json.dumps({\"status\": \"Success\",\"statusreason\": \"updateSucess\"})", "(num - 1) if(jsonData[\"action\"] == \"all\"): all_list = list(mydb.userMailInfo.find({\"userDeleted\":False},{'_id' :", "\"6\":\"6\" } } } } } } } } #Create", "\"Semicon\":{ \"id\":\"DEP1\", \"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\", \"3\":\"3\", \"4\":\"4\", \"5\":\"5\", \"6\":\"6\" }", "tagcount = 0 thrashcount = 0 for item in foundMails:", "= {\"name\":jsonData[\"name\"],\"code\":colorCode,\"email\":jsonData[\"email\"],\"division\":jsonData[\"division\"],\"department\":jsonData[\"department\"],\"floor\":jsonData[\"floor\"],\"cubicle\":jsonData[\"cubicle\"],\"building\":jsonData[\"building\"]} if(fromMFP): newjsonData[\"source\"] = \"MFP\" else: newjsonData[\"source\"] = \"Mobile\"", "str(scan_date.day) +\"-\"+ str(scan_date.month)+\"-\" + str(scan_date.year) end_date = str(end_date.day) +\"-\" +str(end_date.month)+\"-\"", "import BytesIO from io import StringIO import json from bson.dbref", "\":\" + str(today.second)+\":\"+str(today.microsecond) dateTimeNow = date+':'+time logger.debug(\"Current Datetime - \"+dateTimeNow)", "} } }, \"tmc\": { \"id\": \"D2\", \"dept\":{ \"tmc-1\":{ \"id\":\"DEP1\",", "logger.debug(\"Unique Code - \"+dateTimeNow) if(int(jsonData[\"cubicle\"])>25 and int(jsonData[\"cubicle\"])<=50): ilocation=2 elif(int(jsonData[\"cubicle\"])>50 and", "\"4\":\"4\", \"5\":\"5\", \"6\":\"6\" } }, \"TTEC-CI\":{ \"id\":\"DEP4\", \"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\",", "autoThrashed) logger.debug(\"Tags are %s\" % tags) import sendEmail as se", "= scan_date + datetime.timedelta(days=10) scan_date = str(scan_date.day) +\"-\"+ str(scan_date.month)+\"-\" +", "ilocation=4 logger.debug(jsonData[\"building\"]) colorCode=jsonCode[\"building\"][jsonData[\"building\"]][\"id\"]+':'+jsonCode[\"building\"][jsonData[\"building\"]][\"division\"][jsonData[\"division\"]][\"id\"]+':'+dateTimeNow logger.debug(\"ColorCode - \"+colorCode) logger.debug(\"generateColorCode:: ColorCode value =\"+colorCode)", "= lambda x : x[\"name\"]) return json.dumps(new_list_new, default=json_util.default) elif(jsonData[\"action\"] ==", "\"1\":\"1\", \"2\":\"2\", \"3\":\"3\", \"4\":\"4\", \"5\":\"5\", \"6\":\"6\" } }, \"TTEC-DL\":{ \"id\":\"DEP3\",", "scan_date = scan_date + datetime.timedelta(hours=9) end_date = scan_date + datetime.timedelta(days=10)", "return json.dumps(new_list_new, default=json_util.default) else: all_list = list(mydb.userMailInfo.find({\"userDeleted\":False},{'_id' : 0,'user_id':0})) thrash_date", "default=json_util.default) else: all_list = list(mydb.userMailInfo.find({\"userDeleted\":False},{'_id' : 0,'user_id':0})) thrash_date = datetime.datetime.today()", "if( not autoThrashed and len(tags) >= 3): #mydb.mltable.insert({\"code\":jsonData[\"code\"],\"tags\": tags,\"status\":\"Keep\",\"user_id\":1,\"otherdbref\":newDbref}) Actual", "= str(today.day) time = str(today.hour) + \":\" + str(today.minute) +", "foundMailsList = list(mydb.mltable.find({\"otherdbref\":newDbref,\"status\":\"trash\"})) if(len(foundMailsList) < 10): return False tagcount =", "value is %d\" % autoThrashed) logger.debug(\"Tags are %s\" % tags)", "\"dept\":{ \"TTEC-AL\":{ \"id\":\"DEP1\", \"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\", \"3\":\"3\", \"4\":\"4\", \"5\":\"5\", \"6\":\"6\"", "newjsonData[\"source\"] = \"MFP\" else: newjsonData[\"source\"] = \"Mobile\" return addEntry(newjsonData,tags,autoThrashed); def", "logger.debug(\"ColorCode - \"+colorCode) logger.debug(\"generateColorCode:: ColorCode value =\"+colorCode) import qrcode img", "color code = \") logger.debug(jsonData) ilocation=1 today = datetime.datetime.now() date", "= datetime.datetime.strptime(thrash_date, '%d-%m-%Y').date() new_list = list() for item in all_list:", "logger.debug(\"Received data for generating color code = \") logger.debug(jsonData) ilocation=1", "new_thrash_date def checkIfAutoThrashed(jsonData,tags): if(len(tags) < 3): return False a =", "dall.update(newjson) print(dall) new_list.append(dall) new_list.reverse() return json.dumps(new_list,default=json_util.default) def getspecificDate(jsonData): logger.debug(jsonData) num", "+ datetime.timedelta(hours=9) thrash_date = str(thrash_date.day) + \"-\" +str(thrash_date.month)+\"-\" + str(thrash_date.year)", "configure logger logging.basicConfig(filename=\"server.log\", format='%(asctime)s %(message)s', filemode='a') #Creating an object logger=logging.getLogger()", "str(today.hour) + \":\" + str(today.minute) + \":\" + str(today.second)+\":\"+str(today.microsecond) dateTimeNow", "datetime from bson import json_util import logging import base64 jsonCode", "tags,\"status\":\"Keep\",\"user_id\":1,\"otherdbref\":newDbref})#Test code to be removed #end_date = scan_date mydb.userMailInfo.insert({\"code\":jsonData[\"code\"],\"scan_date\":scan_date,\"end_date\":end_date,\"otherdbref\":newDbref,\"userDeleted\":False,\"user_id\":1,\"source\":jsonData[\"source\"]}) jsonData[\"autoThrashed\"]", "new_list_new.append(dall) new_list_new.append({\"totalsize\":totalsize}) logger.debug(new_list_new) #new_list_new.sort(key = lambda x : x[\"name\"]) return", "= str(end_date.day) +\"-\" +str(end_date.month)+\"-\" + str(end_date.year) if(autoThrashed): end_date = scan_date", "\"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\", \"3\":\"3\", \"4\":\"4\", \"5\":\"5\", \"6\":\"6\" } } }", "< 3): return False a = mydb.userInfo.find_one({\"name\":jsonData[\"name\"]}) newDbref = DBRef(\"mydb.userInfo\",a[\"_id\"])", "new_list.append(dall) new_list.reverse() return json.dumps(new_list,default=json_util.default) def getspecificDate(jsonData): logger.debug(jsonData) num = int(jsonData['page'])", "mydb.mltable.update_many({\"_id\":foundMl[\"_id\"],\"user_id\":1},{\"$set\":{\"status\":\"trash\"}}) return json.dumps({\"status\": \"Success\",\"statusreason\": \"updateSucess\"}) #Clear DB only for testing", "\"2\":\"2\", \"3\":\"3\", \"4\":\"4\", \"5\":\"5\", \"6\":\"6\" } } } } }", "\"id\":\"DEP2\", \"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\", \"3\":\"3\", \"4\":\"4\", \"5\":\"5\", \"6\":\"6\" } },", "logger.debug(jsonData[\"end_date\"]) foundmail = mydb.userMailInfo.find_one({\"code\":jsonData[\"code\"]},{\"_id\":1}) logger.debug(foundmail) foundMl = mydb.mltable.find_one({\"code\":jsonData[\"code\"]},{\"_id\":1}) logger.debug(foundMl) mydb.userMailInfo.update_many({\"_id\":foundmail[\"_id\"],\"user_id\":1},{\"$set\":{'end_date':str(jsonData['end_date'])}})", "\"id\": \"D1\", \"dept\":{ \"Medical\":{ \"id\":\"DEP1\", \"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\", \"3\":\"3\", \"4\":\"4\",", "\"4\":\"4\", \"5\":\"5\", \"6\":\"6\" } } } } } } }", "+ \":\" + str(today.minute) + \":\" + str(today.second)+\":\"+str(today.microsecond) dateTimeNow =", "checkIfAutoThrashed(jsonData,tags) logger.debug(\"Auto thrashed value is %d\" % autoThrashed) logger.debug(\"Tags are", "= 0 thrashcount = 0 for item in foundMails: for", "item in mydb.userMailInfo.find({},{\"_id\":0,\"user_id\":0}): print(item) otherdbref = item[\"otherdbref\"] newjson = mydb.userInfo.find_one({\"_id\":otherdbref.id},{\"_id\":0,\"user_id\":0})", ": 0,'user_id':0})) all_list.reverse() totalsize = len(all_list) all_list = all_list[skips:] all_list", "\"5\":\"5\", \"6\":\"6\" } }, \"Mobile\":{ \"id\":\"DEP3\", \"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\", \"3\":\"3\",", "\"dept\":{ \"tmc-1\":{ \"id\":\"DEP1\", \"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\", \"3\":\"3\", \"4\":\"4\", \"5\":\"5\", \"6\":\"6\"", "} } } } } } } #Create and configure", "- \"+colorCode) logger.debug(\"generateColorCode:: ColorCode value =\"+colorCode) import qrcode img =", "\"4\":\"4\", \"5\":\"5\", \"6\":\"6\" } }, \"tmc-2\":{ \"id\":\"DEP2\", \"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\",", "if(jsonData[\"action\"] == \"all\"): all_list = list(mydb.userMailInfo.find({\"userDeleted\":False},{'_id' : 0,'user_id':0})) all_list.reverse() totalsize", "} }, \"TTEC-DL\":{ \"id\":\"DEP3\", \"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\", \"3\":\"3\", \"4\":\"4\", \"5\":\"5\",", "addEntry(jsonData,tags,autoThrashed): a = mydb.userInfo.find_one({\"name\":jsonData[\"name\"]}) newDbref = DBRef(\"mydb.userInfo\",a[\"_id\"]) scan_date = datetime.datetime.today()", "import base64 jsonCode ={ \"building\":{ \"Essae Vaishnavi Solitaire\": { \"id\":", "new_list = new_list[skips:] new_list = new_list[:10] new_list_new = list() for", "datetime.datetime.strptime(thrash_date, '%d-%m-%Y').date() new_list = list() for item in all_list: if(item['end_date']", "\"6\":\"6\" } }, \"tmc-2\":{ \"id\":\"DEP2\", \"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\", \"3\":\"3\", \"4\":\"4\",", "foundMl = mydb.mltable.find_one({\"code\":jsonData[\"code\"]},{\"_id\":1}) logger.debug(foundMl) mydb.userMailInfo.update_many({\"_id\":foundmail[\"_id\"],\"user_id\":1},{\"$set\":{'end_date':str(jsonData['end_date'])}}) if(not jsonData['end_date'] == \"DONT TRASH\"):", "{ \"id\": \"D2\", \"dept\":{ \"TTEC-AL\":{ \"id\":\"DEP1\", \"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\", \"3\":\"3\",", "filemode='a') #Creating an object logger=logging.getLogger() #Setting the threshold of logger", "new_list.reverse() return json.dumps(new_list,default=json_util.default) def getspecificDate(jsonData): logger.debug(jsonData) num = int(jsonData['page']) skips", "StringIO import json from bson.dbref import DBRef import datetime from", "}, \"Fortune Summit\": { \"id\": \"B2\", \"division\": { \"TMSC\": {", "\"4\":\"4\", \"5\":\"5\", \"6\":\"6\" } }, \"tmc-3\":{ \"id\":\"DEP3\", \"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\",", "dall.update(newjson) print(dall) new_list_new.append(dall) new_list_new.append({\"totalsize\":totalsize}) logger.debug(new_list_new) return json.dumps(new_list_new, default=json_util.default) def update_DB(jsonData):", "\"1\":\"1\", \"2\":\"2\", \"3\":\"3\", \"4\":\"4\", \"5\":\"5\", \"6\":\"6\" } }, \"Imaging\":{ \"id\":\"DEP3\",", "\"id\":\"DEP3\", \"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\", \"3\":\"3\", \"4\":\"4\", \"5\":\"5\", \"6\":\"6\" } }", "new_list_new.append({\"totalsize\":totalsize}) logger.debug(new_list_new) #new_list_new.sort(key = lambda x : x[\"name\"]) return json.dumps(new_list_new,", "for item in all_list: if(item['end_date'] == \"DONT TRASH\"): continue db_date", "import logging import base64 jsonCode ={ \"building\":{ \"Essae Vaishnavi Solitaire\":", "to DEBUG logger.setLevel(logging.DEBUG) import pymongo uri = \"mongodb://218ffa09-0ee0-4-231-b9ee:zTV4cwDG0vM49J2GFsw72JzwOD79Bv3dPU8fbVLb5pbh3p0CmTBYcvhrFKTjtl1s7hgYSfRbMOrsVve6hfvhag==@218ffa09-0ee0-4-231-b9ee.documents.azure.com:10255/?ssl=true&replicaSet=globaldb\" client =", "logger.debug(\"Auto thrashed value is %d\" % autoThrashed) logger.debug(\"Tags are %s\"", "datetime.timedelta(hours=9) end_date = scan_date + datetime.timedelta(days=10) scan_date = str(scan_date.day) +\"-\"+", ": x[\"name\"]) return json.dumps(new_list_new, default=json_util.default) else: all_list = list(mydb.userMailInfo.find({\"userDeleted\":False},{'_id' :", "\"3\":\"3\", \"4\":\"4\", \"5\":\"5\", \"6\":\"6\" } }, \"TTEC-DL\":{ \"id\":\"DEP3\", \"floor\":{\"0\":\"0\", \"1\":\"1\",", "in all_list: db_date = datetime.datetime.strptime(item['scan_date'],'%d-%m-%Y').date() if(db_date == thrash_date): new_list.append(item) new_list.reverse()", "not autoThrashed and len(tags) >= 3): #mydb.mltable.insert({\"code\":jsonData[\"code\"],\"tags\": tags,\"status\":\"Keep\",\"user_id\":1,\"otherdbref\":newDbref}) Actual Code", "} } } }, \"TTEC\": { \"id\": \"D2\", \"dept\":{ \"TTEC-AL\":{", "Actual Code mydb.mltable.insert({\"code\":jsonData[\"code\"],\"tags\": tags,\"status\":\"Keep\",\"user_id\":1,\"otherdbref\":newDbref})#Test code to be removed #end_date =", "the threshold of logger to DEBUG logger.setLevel(logging.DEBUG) import pymongo uri", "return False a = mydb.userInfo.find_one({\"name\":jsonData[\"name\"]}) newDbref = DBRef(\"mydb.userInfo\",a[\"_id\"]) foundMails =", "\"tmc-3\":{ \"id\":\"DEP3\", \"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\", \"3\":\"3\", \"4\":\"4\", \"5\":\"5\", \"6\":\"6\" }", "= {} item.pop(\"otherdbref\") dall.update(item) dall.update(newjson) print(dall) new_list.append(dall) new_list.reverse() return json.dumps(new_list,default=json_util.default)", "+ datetime.timedelta(days=10) scan_date = str(scan_date.day) +\"-\"+ str(scan_date.month)+\"-\" + str(scan_date.year) end_date", "#Creating an object logger=logging.getLogger() #Setting the threshold of logger to", "logger.debug(type(img)) autoThrashed = checkIfAutoThrashed(jsonData,tags) logger.debug(\"Auto thrashed value is %d\" %", "{\"name\":jsonData[\"name\"],\"code\":colorCode,\"email\":jsonData[\"email\"],\"division\":jsonData[\"division\"],\"department\":jsonData[\"department\"],\"floor\":jsonData[\"floor\"],\"cubicle\":jsonData[\"cubicle\"],\"building\":jsonData[\"building\"]} if(fromMFP): newjsonData[\"source\"] = \"MFP\" else: newjsonData[\"source\"] = \"Mobile\" return", "}, \"tmc-2\":{ \"id\":\"DEP2\", \"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\", \"3\":\"3\", \"4\":\"4\", \"5\":\"5\", \"6\":\"6\"", "uri = \"mongodb://218ffa09-0ee0-4-231-b9ee:zTV4cwDG0vM49J2GFsw72JzwOD79Bv3dPU8fbVLb5pbh3p0CmTBYcvhrFKTjtl1s7hgYSfRbMOrsVve6hfvhag==@218ffa09-0ee0-4-231-b9ee.documents.azure.com:10255/?ssl=true&replicaSet=globaldb\" client = pymongo.MongoClient(uri) print(\"Obtained the client\") mydb", "dall = {} item.pop(\"otherdbref\") dall.update(item) dall.update(newjson) print(dall) new_list.append(dall) new_list.reverse() return", "import DBRef import datetime from bson import json_util import logging", "getspecificDate(jsonData): logger.debug(jsonData) num = int(jsonData['page']) skips = 10 * (num", "if(not jsonData['end_date'] == \"DONT TRASH\"): mydb.mltable.update_many({\"_id\":foundMl[\"_id\"],\"user_id\":1},{\"$set\":{\"status\":\"trash\"}}) return json.dumps({\"status\": \"Success\",\"statusreason\": \"updateSucess\"})", "datetime.timedelta(days=10) scan_date = str(scan_date.day) +\"-\"+ str(scan_date.month)+\"-\" + str(scan_date.year) end_date =", "+ \":\" + str(today.second)+\":\"+str(today.microsecond) dateTimeNow = date+':'+time logger.debug(\"Current Datetime -", "= lambda x : x[\"name\"]) return json.dumps(new_list_new, default=json_util.default) else: all_list", "logger.debug(foundMl) mydb.userMailInfo.update_many({\"_id\":foundmail[\"_id\"],\"user_id\":1},{\"$set\":{'end_date':str(jsonData['end_date'])}}) if(not jsonData['end_date'] == \"DONT TRASH\"): mydb.mltable.update_many({\"_id\":foundMl[\"_id\"],\"user_id\":1},{\"$set\":{\"status\":\"trash\"}}) return json.dumps({\"status\":", "\"1\":\"1\", \"2\":\"2\", \"3\":\"3\", \"4\":\"4\", \"5\":\"5\", \"6\":\"6\" } } } }", "\"3\":\"3\", \"4\":\"4\", \"5\":\"5\", \"6\":\"6\" } }, \"TTEC-CI\":{ \"id\":\"DEP4\", \"floor\":{\"0\":\"0\", \"1\":\"1\",", "ilocation=1 today = datetime.datetime.now() date = str(today.day) time = str(today.hour)", "str(scan_date.month)+\"-\" + str(scan_date.year) end_date = str(end_date.day) +\"-\" +str(end_date.month)+\"-\" + str(end_date.year)", "def getspecificDate(jsonData): logger.debug(jsonData) num = int(jsonData['page']) skips = 10 *", "logger.debug(new_list_new) #new_list_new.sort(key = lambda x : x[\"name\"]) return json.dumps(new_list_new, default=json_util.default)", "= DBRef(\"mydb.userInfo\",a[\"_id\"]) scan_date = datetime.datetime.today() scan_date = scan_date + datetime.timedelta(hours=9)", "return True return False def generateqrcode(jsonData,filenameJPG,tags,fromMFP): logger.debug(\"Received data for generating", "#img.save(colorCode+\".png\") newjsonData = {\"name\":jsonData[\"name\"],\"code\":colorCode,\"email\":jsonData[\"email\"],\"division\":jsonData[\"division\"],\"department\":jsonData[\"department\"],\"floor\":jsonData[\"floor\"],\"cubicle\":jsonData[\"cubicle\"],\"building\":jsonData[\"building\"]} if(fromMFP): newjsonData[\"source\"] = \"MFP\" else: newjsonData[\"source\"]", "\"id\": \"D1\", \"dept\":{ \"Semicon\":{ \"id\":\"DEP1\", \"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\", \"3\":\"3\", \"4\":\"4\",", "\"tmc-2\":{ \"id\":\"DEP2\", \"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\", \"3\":\"3\", \"4\":\"4\", \"5\":\"5\", \"6\":\"6\" }", "\"4\":\"4\", \"5\":\"5\", \"6\":\"6\" } }, \"Mobile\":{ \"id\":\"DEP3\", \"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\",", "DBRef(\"mydb.userInfo\",a[\"_id\"]) scan_date = datetime.datetime.today() scan_date = scan_date + datetime.timedelta(hours=9) end_date", "len(tags) >= 3): #mydb.mltable.insert({\"code\":jsonData[\"code\"],\"tags\": tags,\"status\":\"Keep\",\"user_id\":1,\"otherdbref\":newDbref}) Actual Code mydb.mltable.insert({\"code\":jsonData[\"code\"],\"tags\": tags,\"status\":\"Keep\",\"user_id\":1,\"otherdbref\":newDbref})#Test code", "logging import base64 jsonCode ={ \"building\":{ \"Essae Vaishnavi Solitaire\": {", "scan_date = datetime.datetime.today() scan_date = scan_date + datetime.timedelta(hours=9) end_date =", "= len(new_list) new_list = new_list[skips:] new_list = new_list[:10] new_list_new =", "len(new_list) new_list = new_list[skips:] new_list = new_list[:10] new_list_new = list()", "mydb.userInfo.find_one({\"_id\":otherdbref.id},{\"_id\":0,\"user_id\":0}) dall = {} item.pop(\"otherdbref\") dall.update(item) dall.update(newjson) print(dall) new_list_new.append(dall) new_list_new.append({\"totalsize\":totalsize})", "\"5\":\"5\", \"6\":\"6\" } }, \"RND\":{ \"id\":\"DEP2\", \"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\", \"3\":\"3\",", "{} item.pop(\"otherdbref\") dall.update(item) dall.update(newjson) print(dall) new_list.append(dall) new_list.reverse() return json.dumps(new_list,default=json_util.default) def", "datetime.datetime.strptime(item['scan_date'],'%d-%m-%Y').date() if(db_date == thrash_date): new_list.append(item) new_list.reverse() totalsize = len(new_list) new_list", "\"B1\", \"division\": { \"SS\": { \"id\": \"D1\", \"dept\":{ \"Semicon\":{ \"id\":\"DEP1\",", "= scan_date + datetime.timedelta(hours=9) end_date = scan_date + datetime.timedelta(days=10) scan_date", "bson import json_util import logging import base64 jsonCode ={ \"building\":{", "lambda x : x[\"name\"]) return json.dumps(new_list_new, default=json_util.default) elif(jsonData[\"action\"] == \"today\"):", "default=json_util.default) elif(jsonData[\"action\"] == \"today\"): all_list = list(mydb.userMailInfo.find({\"userDeleted\":False},{'_id' : 0,'user_id':0})) thrash_date", "print(dall) new_list.append(dall) new_list.reverse() return json.dumps(new_list,default=json_util.default) def getspecificDate(jsonData): logger.debug(jsonData) num =", "\"6\":\"6\" } } } }, \"tmc\": { \"id\": \"D2\", \"dept\":{", "} } } }, \"tmc\": { \"id\": \"D2\", \"dept\":{ \"tmc-1\":{", "datetime.datetime.strptime(item['end_date'],'%d-%m-%Y').date() if(db_date <= thrash_date): new_list.append(item) new_list.reverse() totalsize = len(new_list) new_list", "- \"+dateTimeNow) if(int(jsonData[\"cubicle\"])>25 and int(jsonData[\"cubicle\"])<=50): ilocation=2 elif(int(jsonData[\"cubicle\"])>50 and int(jsonData[\"cubicle\"])<=75): ilocation=3", "else: ilocation=4 logger.debug(jsonData[\"building\"]) colorCode=jsonCode[\"building\"][jsonData[\"building\"]][\"id\"]+':'+jsonCode[\"building\"][jsonData[\"building\"]][\"division\"][jsonData[\"division\"]][\"id\"]+':'+dateTimeNow logger.debug(\"ColorCode - \"+colorCode) logger.debug(\"generateColorCode:: ColorCode value", "item.pop(\"otherdbref\") dall.update(item) dall.update(newjson) print(dall) new_list_new.append(dall) new_list_new.append({\"totalsize\":totalsize}) logger.debug(new_list_new) return json.dumps(new_list_new, default=json_util.default)", "item[\"tags\"]): tagcount+=1 if(tagcount >= 3): thrashcount+=1 if(thrashcount >=10): return True", "from io import StringIO import json from bson.dbref import DBRef", "\"1\":\"1\", \"2\":\"2\", \"3\":\"3\", \"4\":\"4\", \"5\":\"5\", \"6\":\"6\" } }, \"TTEC-SL\":{ \"id\":\"DEP2\",", "time = str(today.hour) + \":\" + str(today.minute) + \":\" +", "client.test def sortingReq(item): new_thrash_date = datetime.datetime.strptime(item[\"scan_date\"], '%d-%m-%Y').date() return new_thrash_date def", ">= 3): thrashcount+=1 if(thrashcount >=10): return True return False def", "}, \"Imaging\":{ \"id\":\"DEP3\", \"floor\":{\"0\":\"0\", \"1\":\"1\", \"2\":\"2\", \"3\":\"3\", \"4\":\"4\", \"5\":\"5\", \"6\":\"6\"", "= list(mydb.userMailInfo.find({\"userDeleted\":False},{'_id' : 0,'user_id':0})) all_list.reverse() totalsize = len(all_list) all_list =", "thrash_date = thrash_date + datetime.timedelta(hours=9) thrash_date = str(thrash_date.day) + \"-\"", "BytesIO from io import StringIO import json from bson.dbref import", "item in foundMails: for tag in tags: if(tag in item[\"tags\"]):" ]
[ "[t.task_id for t in test_dag.tasks] self.assertListEqual(actual_task_ids, expected_task_ids) if __name__ ==", "mock.Mock() self.build_impersonated_client_mock.start() self.mock_variable = mock.patch.object( variable, 'Variable', autospec=True).start() # `side_effect`", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "import bigquery_hook from airflow.models import baseoperator from airflow.models import dag", "self.original_bigquery_hook_init = bigquery_hook.BigQueryHook.__init__ bigquery_hook.BigQueryHook.__init__ = mock.MagicMock() self.original_monitoring_hook = monitoring_hook.MonitoringHook monitoring_hook.MonitoringHook", "monitoring_hook.MonitoringHook = self.original_monitoring_hook def test_create_dag(self): \"\"\"Tests that returned DAG contains", "'bq_to_cm_task'] test_dag = bq_to_cm_dag.BigQueryToCMDag( AIRFLOW_VARIABLES['dag_name']).create_dag() self.assertIsInstance(test_dag, dag.DAG) self.assertEqual(len(test_dag.tasks), len(expected_task_ids)) for", "self.mock_variable = mock.patch.object( variable, 'Variable', autospec=True).start() # `side_effect` is assigned", "# # Licensed under the Apache License, Version 2.0 (the", "compliance with the License. # You may obtain a copy", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "2.0 (the \"License\"); # you may not use this file", "agreed to in writing, software # distributed under the License", "file except in compliance with the License. # You may", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "Unless required by applicable law or agreed to in writing,", "= bq_to_cm_dag._DAG_NAME AIRFLOW_VARIABLES = { 'dag_name': _DAG_NAME, f'{_DAG_NAME}_schedule': '@once', f'{_DAG_NAME}_retries':", "{ 'dag_name': _DAG_NAME, f'{_DAG_NAME}_schedule': '@once', f'{_DAG_NAME}_retries': 0, f'{_DAG_NAME}_retry_delay': 3, f'{_DAG_NAME}_is_retry':", "True, f'{_DAG_NAME}_is_run': True, f'{_DAG_NAME}_enable_run_report': False, f'{_DAG_NAME}_enable_monitoring': True, f'{_DAG_NAME}_enable_monitoring_cleanup': False, 'monitoring_data_days_to_live':", "called. self.mock_variable.get.side_effect = ( lambda key, value: AIRFLOW_VARIABLES[key]) self.original_bigquery_hook_init =", "for dags.bq_to_cm_dag.\"\"\" import unittest from airflow.contrib.hooks import bigquery_hook from airflow.models", "distributed under the License is distributed on an \"AS IS\"", "baseoperator from airflow.models import dag from airflow.models import variable import", "self.assertIsInstance(task, baseoperator.BaseOperator) actual_task_ids = [t.task_id for t in test_dag.tasks] self.assertListEqual(actual_task_ids,", "for task in test_dag.tasks: self.assertIsInstance(task, baseoperator.BaseOperator) actual_task_ids = [t.task_id for", "import unittest from airflow.contrib.hooks import bigquery_hook from airflow.models import baseoperator", "from dags import bq_to_cm_dag from plugins.pipeline_plugins.hooks import monitoring_hook _DAG_NAME =", "the specific language governing permissions and # limitations under the", "bq_to_cm_dag._DAG_NAME AIRFLOW_VARIABLES = { 'dag_name': _DAG_NAME, f'{_DAG_NAME}_schedule': '@once', f'{_DAG_NAME}_retries': 0,", "AIRFLOW_VARIABLES[key]) self.original_bigquery_hook_init = bigquery_hook.BigQueryHook.__init__ bigquery_hook.BigQueryHook.__init__ = mock.MagicMock() self.original_monitoring_hook = monitoring_hook.MonitoringHook", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "False, f'{_DAG_NAME}_enable_monitoring': True, f'{_DAG_NAME}_enable_monitoring_cleanup': False, 'monitoring_data_days_to_live': 50, 'monitoring_dataset': 'test_monitoring_dataset', 'monitoring_table':", "2020 Google LLC. # # Licensed under the Apache License,", "applicable law or agreed to in writing, software # distributed", "express or implied. # See the License for the specific", "f'{_DAG_NAME}_is_retry': True, f'{_DAG_NAME}_is_run': True, f'{_DAG_NAME}_enable_run_report': False, f'{_DAG_NAME}_enable_monitoring': True, f'{_DAG_NAME}_enable_monitoring_cleanup': False,", "except in compliance with the License. # You may obtain", "to dynamically return values # each time when self.mock_variable is", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "= self.original_monitoring_hook def test_create_dag(self): \"\"\"Tests that returned DAG contains correct", "bigquery_hook from airflow.models import baseoperator from airflow.models import dag from", "Licensed under the Apache License, Version 2.0 (the \"License\"); #", "'test_table', 'cm_profile_id': 'cm_profile_id', 'cm_service_account': 'cm_service_account' } class BQToCMDAGTest(unittest.TestCase): def setUp(self):", "tearDown(self): super().tearDown() bigquery_hook.BigQueryHook.__init__ = self.original_bigquery_hook_init monitoring_hook.MonitoringHook = self.original_monitoring_hook def test_create_dag(self):", "actual_task_ids = [t.task_id for t in test_dag.tasks] self.assertListEqual(actual_task_ids, expected_task_ids) if", "not use this file except in compliance with the License.", "import cloud_auth from dags import bq_to_cm_dag from plugins.pipeline_plugins.hooks import monitoring_hook", "AIRFLOW_VARIABLES = { 'dag_name': _DAG_NAME, f'{_DAG_NAME}_schedule': '@once', f'{_DAG_NAME}_retries': 0, f'{_DAG_NAME}_retry_delay':", "t in test_dag.tasks] self.assertListEqual(actual_task_ids, expected_task_ids) if __name__ == '__main__': unittest.main()", "\"\"\"Tests that returned DAG contains correct DAG and tasks.\"\"\" expected_task_ids", "= bigquery_hook.BigQueryHook.__init__ bigquery_hook.BigQueryHook.__init__ = mock.MagicMock() self.original_monitoring_hook = monitoring_hook.MonitoringHook monitoring_hook.MonitoringHook =", "unittest from airflow.contrib.hooks import bigquery_hook from airflow.models import baseoperator from", "monitoring_hook.MonitoringHook monitoring_hook.MonitoringHook = mock.MagicMock() def tearDown(self): super().tearDown() bigquery_hook.BigQueryHook.__init__ = self.original_bigquery_hook_init", "bq_to_cm_dag from plugins.pipeline_plugins.hooks import monitoring_hook _DAG_NAME = bq_to_cm_dag._DAG_NAME AIRFLOW_VARIABLES =", "'bq_table_id': 'test_table', 'cm_profile_id': 'cm_profile_id', 'cm_service_account': 'cm_service_account' } class BQToCMDAGTest(unittest.TestCase): def", "3, f'{_DAG_NAME}_is_retry': True, f'{_DAG_NAME}_is_run': True, f'{_DAG_NAME}_enable_run_report': False, f'{_DAG_NAME}_enable_monitoring': True, f'{_DAG_NAME}_enable_monitoring_cleanup':", "writing, software # distributed under the License is distributed on", "def test_create_dag(self): \"\"\"Tests that returned DAG contains correct DAG and", "import baseoperator from airflow.models import dag from airflow.models import variable", "in writing, software # distributed under the License is distributed", "'monitoring_bq_conn_id': 'test_monitoring_conn', 'bq_dataset_id': 'test_dataset', 'bq_table_id': 'test_table', 'cm_profile_id': 'cm_profile_id', 'cm_service_account': 'cm_service_account'", "autospec=True).start() # `side_effect` is assigned to `lambda` to dynamically return", "self.mock_variable is called. self.mock_variable.get.side_effect = ( lambda key, value: AIRFLOW_VARIABLES[key])", "is called. self.mock_variable.get.side_effect = ( lambda key, value: AIRFLOW_VARIABLES[key]) self.original_bigquery_hook_init", "you may not use this file except in compliance with", "self.mock_variable.get.side_effect = ( lambda key, value: AIRFLOW_VARIABLES[key]) self.original_bigquery_hook_init = bigquery_hook.BigQueryHook.__init__", "= ( lambda key, value: AIRFLOW_VARIABLES[key]) self.original_bigquery_hook_init = bigquery_hook.BigQueryHook.__init__ bigquery_hook.BigQueryHook.__init__", "setUp(self): super(BQToCMDAGTest, self).setUp() self.addCleanup(mock.patch.stopall) self.build_impersonated_client_mock = mock.patch.object( cloud_auth, 'build_impersonated_client', autospec=True)", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "mock from gps_building_blocks.cloud.utils import cloud_auth from dags import bq_to_cm_dag from", "test_create_dag(self): \"\"\"Tests that returned DAG contains correct DAG and tasks.\"\"\"", "['bq_to_cm_retry_task', 'bq_to_cm_task'] test_dag = bq_to_cm_dag.BigQueryToCMDag( AIRFLOW_VARIABLES['dag_name']).create_dag() self.assertIsInstance(test_dag, dag.DAG) self.assertEqual(len(test_dag.tasks), len(expected_task_ids))", "python3 # coding=utf-8 # Copyright 2020 Google LLC. # #", "dynamically return values # each time when self.mock_variable is called.", "from airflow.models import dag from airflow.models import variable import mock", "plugins.pipeline_plugins.hooks import monitoring_hook _DAG_NAME = bq_to_cm_dag._DAG_NAME AIRFLOW_VARIABLES = { 'dag_name':", "`lambda` to dynamically return values # each time when self.mock_variable", "= bq_to_cm_dag.BigQueryToCMDag( AIRFLOW_VARIABLES['dag_name']).create_dag() self.assertIsInstance(test_dag, dag.DAG) self.assertEqual(len(test_dag.tasks), len(expected_task_ids)) for task in", "= mock.patch.object( cloud_auth, 'build_impersonated_client', autospec=True) self.build_impersonated_client_mock.return_value = mock.Mock() self.build_impersonated_client_mock.start() self.mock_variable", "'monitoring_dataset': 'test_monitoring_dataset', 'monitoring_table': 'test_monitoring_table', 'monitoring_bq_conn_id': 'test_monitoring_conn', 'bq_dataset_id': 'test_dataset', 'bq_table_id': 'test_table',", "use this file except in compliance with the License. #", "import monitoring_hook _DAG_NAME = bq_to_cm_dag._DAG_NAME AIRFLOW_VARIABLES = { 'dag_name': _DAG_NAME,", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "f'{_DAG_NAME}_enable_run_report': False, f'{_DAG_NAME}_enable_monitoring': True, f'{_DAG_NAME}_enable_monitoring_cleanup': False, 'monitoring_data_days_to_live': 50, 'monitoring_dataset': 'test_monitoring_dataset',", "_DAG_NAME = bq_to_cm_dag._DAG_NAME AIRFLOW_VARIABLES = { 'dag_name': _DAG_NAME, f'{_DAG_NAME}_schedule': '@once',", "'cm_service_account': 'cm_service_account' } class BQToCMDAGTest(unittest.TestCase): def setUp(self): super(BQToCMDAGTest, self).setUp() self.addCleanup(mock.patch.stopall)", "f'{_DAG_NAME}_schedule': '@once', f'{_DAG_NAME}_retries': 0, f'{_DAG_NAME}_retry_delay': 3, f'{_DAG_NAME}_is_retry': True, f'{_DAG_NAME}_is_run': True,", "super(BQToCMDAGTest, self).setUp() self.addCleanup(mock.patch.stopall) self.build_impersonated_client_mock = mock.patch.object( cloud_auth, 'build_impersonated_client', autospec=True) self.build_impersonated_client_mock.return_value", "= mock.patch.object( variable, 'Variable', autospec=True).start() # `side_effect` is assigned to", "bigquery_hook.BigQueryHook.__init__ bigquery_hook.BigQueryHook.__init__ = mock.MagicMock() self.original_monitoring_hook = monitoring_hook.MonitoringHook monitoring_hook.MonitoringHook = mock.MagicMock()", "CONDITIONS OF ANY KIND, either express or implied. # See", "from airflow.contrib.hooks import bigquery_hook from airflow.models import baseoperator from airflow.models", "f'{_DAG_NAME}_is_run': True, f'{_DAG_NAME}_enable_run_report': False, f'{_DAG_NAME}_enable_monitoring': True, f'{_DAG_NAME}_enable_monitoring_cleanup': False, 'monitoring_data_days_to_live': 50,", "} class BQToCMDAGTest(unittest.TestCase): def setUp(self): super(BQToCMDAGTest, self).setUp() self.addCleanup(mock.patch.stopall) self.build_impersonated_client_mock =", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "variable, 'Variable', autospec=True).start() # `side_effect` is assigned to `lambda` to", "contains correct DAG and tasks.\"\"\" expected_task_ids = ['bq_to_cm_retry_task', 'bq_to_cm_task'] test_dag", "or implied. # See the License for the specific language", "License is distributed on an \"AS IS\" BASIS, # WITHOUT", "language governing permissions and # limitations under the License. \"\"\"Tests", "License. # You may obtain a copy of the License", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "License, Version 2.0 (the \"License\"); # you may not use", "'bq_dataset_id': 'test_dataset', 'bq_table_id': 'test_table', 'cm_profile_id': 'cm_profile_id', 'cm_service_account': 'cm_service_account' } class", "# You may obtain a copy of the License at", "KIND, either express or implied. # See the License for", "specific language governing permissions and # limitations under the License.", "assigned to `lambda` to dynamically return values # each time", "airflow.models import dag from airflow.models import variable import mock from", "under the License is distributed on an \"AS IS\" BASIS,", "dags import bq_to_cm_dag from plugins.pipeline_plugins.hooks import monitoring_hook _DAG_NAME = bq_to_cm_dag._DAG_NAME", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "0, f'{_DAG_NAME}_retry_delay': 3, f'{_DAG_NAME}_is_retry': True, f'{_DAG_NAME}_is_run': True, f'{_DAG_NAME}_enable_run_report': False, f'{_DAG_NAME}_enable_monitoring':", "key, value: AIRFLOW_VARIABLES[key]) self.original_bigquery_hook_init = bigquery_hook.BigQueryHook.__init__ bigquery_hook.BigQueryHook.__init__ = mock.MagicMock() self.original_monitoring_hook", "License for the specific language governing permissions and # limitations", "test_dag = bq_to_cm_dag.BigQueryToCMDag( AIRFLOW_VARIABLES['dag_name']).create_dag() self.assertIsInstance(test_dag, dag.DAG) self.assertEqual(len(test_dag.tasks), len(expected_task_ids)) for task", "correct DAG and tasks.\"\"\" expected_task_ids = ['bq_to_cm_retry_task', 'bq_to_cm_task'] test_dag =", "bq_to_cm_dag.BigQueryToCMDag( AIRFLOW_VARIABLES['dag_name']).create_dag() self.assertIsInstance(test_dag, dag.DAG) self.assertEqual(len(test_dag.tasks), len(expected_task_ids)) for task in test_dag.tasks:", "AIRFLOW_VARIABLES['dag_name']).create_dag() self.assertIsInstance(test_dag, dag.DAG) self.assertEqual(len(test_dag.tasks), len(expected_task_ids)) for task in test_dag.tasks: self.assertIsInstance(task,", "self.assertIsInstance(test_dag, dag.DAG) self.assertEqual(len(test_dag.tasks), len(expected_task_ids)) for task in test_dag.tasks: self.assertIsInstance(task, baseoperator.BaseOperator)", "def setUp(self): super(BQToCMDAGTest, self).setUp() self.addCleanup(mock.patch.stopall) self.build_impersonated_client_mock = mock.patch.object( cloud_auth, 'build_impersonated_client',", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "self.build_impersonated_client_mock = mock.patch.object( cloud_auth, 'build_impersonated_client', autospec=True) self.build_impersonated_client_mock.return_value = mock.Mock() self.build_impersonated_client_mock.start()", "self.addCleanup(mock.patch.stopall) self.build_impersonated_client_mock = mock.patch.object( cloud_auth, 'build_impersonated_client', autospec=True) self.build_impersonated_client_mock.return_value = mock.Mock()", "'cm_profile_id', 'cm_service_account': 'cm_service_account' } class BQToCMDAGTest(unittest.TestCase): def setUp(self): super(BQToCMDAGTest, self).setUp()", "value: AIRFLOW_VARIABLES[key]) self.original_bigquery_hook_init = bigquery_hook.BigQueryHook.__init__ bigquery_hook.BigQueryHook.__init__ = mock.MagicMock() self.original_monitoring_hook =", "each time when self.mock_variable is called. self.mock_variable.get.side_effect = ( lambda", "monitoring_hook _DAG_NAME = bq_to_cm_dag._DAG_NAME AIRFLOW_VARIABLES = { 'dag_name': _DAG_NAME, f'{_DAG_NAME}_schedule':", "self.build_impersonated_client_mock.start() self.mock_variable = mock.patch.object( variable, 'Variable', autospec=True).start() # `side_effect` is", "for t in test_dag.tasks] self.assertListEqual(actual_task_ids, expected_task_ids) if __name__ == '__main__':", "f'{_DAG_NAME}_retries': 0, f'{_DAG_NAME}_retry_delay': 3, f'{_DAG_NAME}_is_retry': True, f'{_DAG_NAME}_is_run': True, f'{_DAG_NAME}_enable_run_report': False,", "= [t.task_id for t in test_dag.tasks] self.assertListEqual(actual_task_ids, expected_task_ids) if __name__", "cloud_auth, 'build_impersonated_client', autospec=True) self.build_impersonated_client_mock.return_value = mock.Mock() self.build_impersonated_client_mock.start() self.mock_variable = mock.patch.object(", "BQToCMDAGTest(unittest.TestCase): def setUp(self): super(BQToCMDAGTest, self).setUp() self.addCleanup(mock.patch.stopall) self.build_impersonated_client_mock = mock.patch.object( cloud_auth,", "import bq_to_cm_dag from plugins.pipeline_plugins.hooks import monitoring_hook _DAG_NAME = bq_to_cm_dag._DAG_NAME AIRFLOW_VARIABLES", "the License for the specific language governing permissions and #", "= mock.MagicMock() def tearDown(self): super().tearDown() bigquery_hook.BigQueryHook.__init__ = self.original_bigquery_hook_init monitoring_hook.MonitoringHook =", "LLC. # # Licensed under the Apache License, Version 2.0", "(the \"License\"); # you may not use this file except", "governing permissions and # limitations under the License. \"\"\"Tests for", "Apache License, Version 2.0 (the \"License\"); # you may not", "airflow.models import baseoperator from airflow.models import dag from airflow.models import", "import dag from airflow.models import variable import mock from gps_building_blocks.cloud.utils", "# you may not use this file except in compliance", "= monitoring_hook.MonitoringHook monitoring_hook.MonitoringHook = mock.MagicMock() def tearDown(self): super().tearDown() bigquery_hook.BigQueryHook.__init__ =", "dag.DAG) self.assertEqual(len(test_dag.tasks), len(expected_task_ids)) for task in test_dag.tasks: self.assertIsInstance(task, baseoperator.BaseOperator) actual_task_ids", "either express or implied. # See the License for the", "from airflow.models import variable import mock from gps_building_blocks.cloud.utils import cloud_auth", "= self.original_bigquery_hook_init monitoring_hook.MonitoringHook = self.original_monitoring_hook def test_create_dag(self): \"\"\"Tests that returned", "class BQToCMDAGTest(unittest.TestCase): def setUp(self): super(BQToCMDAGTest, self).setUp() self.addCleanup(mock.patch.stopall) self.build_impersonated_client_mock = mock.patch.object(", "'build_impersonated_client', autospec=True) self.build_impersonated_client_mock.return_value = mock.Mock() self.build_impersonated_client_mock.start() self.mock_variable = mock.patch.object( variable,", "OR CONDITIONS OF ANY KIND, either express or implied. #", "coding=utf-8 # Copyright 2020 Google LLC. # # Licensed under", "mock.MagicMock() self.original_monitoring_hook = monitoring_hook.MonitoringHook monitoring_hook.MonitoringHook = mock.MagicMock() def tearDown(self): super().tearDown()", "from airflow.models import baseoperator from airflow.models import dag from airflow.models", "self.build_impersonated_client_mock.return_value = mock.Mock() self.build_impersonated_client_mock.start() self.mock_variable = mock.patch.object( variable, 'Variable', autospec=True).start()", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "True, f'{_DAG_NAME}_enable_run_report': False, f'{_DAG_NAME}_enable_monitoring': True, f'{_DAG_NAME}_enable_monitoring_cleanup': False, 'monitoring_data_days_to_live': 50, 'monitoring_dataset':", "# `side_effect` is assigned to `lambda` to dynamically return values", "the License is distributed on an \"AS IS\" BASIS, #", "import mock from gps_building_blocks.cloud.utils import cloud_auth from dags import bq_to_cm_dag", "in compliance with the License. # You may obtain a", "'Variable', autospec=True).start() # `side_effect` is assigned to `lambda` to dynamically", "= ['bq_to_cm_retry_task', 'bq_to_cm_task'] test_dag = bq_to_cm_dag.BigQueryToCMDag( AIRFLOW_VARIABLES['dag_name']).create_dag() self.assertIsInstance(test_dag, dag.DAG) self.assertEqual(len(test_dag.tasks),", "software # distributed under the License is distributed on an", "from gps_building_blocks.cloud.utils import cloud_auth from dags import bq_to_cm_dag from plugins.pipeline_plugins.hooks", "'cm_profile_id': 'cm_profile_id', 'cm_service_account': 'cm_service_account' } class BQToCMDAGTest(unittest.TestCase): def setUp(self): super(BQToCMDAGTest,", "# each time when self.mock_variable is called. self.mock_variable.get.side_effect = (", "'test_monitoring_conn', 'bq_dataset_id': 'test_dataset', 'bq_table_id': 'test_table', 'cm_profile_id': 'cm_profile_id', 'cm_service_account': 'cm_service_account' }", "dag from airflow.models import variable import mock from gps_building_blocks.cloud.utils import", "variable import mock from gps_building_blocks.cloud.utils import cloud_auth from dags import", "time when self.mock_variable is called. self.mock_variable.get.side_effect = ( lambda key,", "# # Unless required by applicable law or agreed to", "super().tearDown() bigquery_hook.BigQueryHook.__init__ = self.original_bigquery_hook_init monitoring_hook.MonitoringHook = self.original_monitoring_hook def test_create_dag(self): \"\"\"Tests", "self.assertEqual(len(test_dag.tasks), len(expected_task_ids)) for task in test_dag.tasks: self.assertIsInstance(task, baseoperator.BaseOperator) actual_task_ids =", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "mock.patch.object( cloud_auth, 'build_impersonated_client', autospec=True) self.build_impersonated_client_mock.return_value = mock.Mock() self.build_impersonated_client_mock.start() self.mock_variable =", "50, 'monitoring_dataset': 'test_monitoring_dataset', 'monitoring_table': 'test_monitoring_table', 'monitoring_bq_conn_id': 'test_monitoring_conn', 'bq_dataset_id': 'test_dataset', 'bq_table_id':", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "and tasks.\"\"\" expected_task_ids = ['bq_to_cm_retry_task', 'bq_to_cm_task'] test_dag = bq_to_cm_dag.BigQueryToCMDag( AIRFLOW_VARIABLES['dag_name']).create_dag()", "Version 2.0 (the \"License\"); # you may not use this", "to `lambda` to dynamically return values # each time when", "= mock.Mock() self.build_impersonated_client_mock.start() self.mock_variable = mock.patch.object( variable, 'Variable', autospec=True).start() #", "in test_dag.tasks: self.assertIsInstance(task, baseoperator.BaseOperator) actual_task_ids = [t.task_id for t in", "DAG and tasks.\"\"\" expected_task_ids = ['bq_to_cm_retry_task', 'bq_to_cm_task'] test_dag = bq_to_cm_dag.BigQueryToCMDag(", "mock.MagicMock() def tearDown(self): super().tearDown() bigquery_hook.BigQueryHook.__init__ = self.original_bigquery_hook_init monitoring_hook.MonitoringHook = self.original_monitoring_hook", "law or agreed to in writing, software # distributed under", "task in test_dag.tasks: self.assertIsInstance(task, baseoperator.BaseOperator) actual_task_ids = [t.task_id for t", "`side_effect` is assigned to `lambda` to dynamically return values #", "'test_monitoring_table', 'monitoring_bq_conn_id': 'test_monitoring_conn', 'bq_dataset_id': 'test_dataset', 'bq_table_id': 'test_table', 'cm_profile_id': 'cm_profile_id', 'cm_service_account':", "that returned DAG contains correct DAG and tasks.\"\"\" expected_task_ids =", "bigquery_hook.BigQueryHook.__init__ = mock.MagicMock() self.original_monitoring_hook = monitoring_hook.MonitoringHook monitoring_hook.MonitoringHook = mock.MagicMock() def", "= { 'dag_name': _DAG_NAME, f'{_DAG_NAME}_schedule': '@once', f'{_DAG_NAME}_retries': 0, f'{_DAG_NAME}_retry_delay': 3,", "self.original_bigquery_hook_init monitoring_hook.MonitoringHook = self.original_monitoring_hook def test_create_dag(self): \"\"\"Tests that returned DAG", "'@once', f'{_DAG_NAME}_retries': 0, f'{_DAG_NAME}_retry_delay': 3, f'{_DAG_NAME}_is_retry': True, f'{_DAG_NAME}_is_run': True, f'{_DAG_NAME}_enable_run_report':", "f'{_DAG_NAME}_enable_monitoring': True, f'{_DAG_NAME}_enable_monitoring_cleanup': False, 'monitoring_data_days_to_live': 50, 'monitoring_dataset': 'test_monitoring_dataset', 'monitoring_table': 'test_monitoring_table',", "implied. # See the License for the specific language governing", "under the Apache License, Version 2.0 (the \"License\"); # you", "'monitoring_data_days_to_live': 50, 'monitoring_dataset': 'test_monitoring_dataset', 'monitoring_table': 'test_monitoring_table', 'monitoring_bq_conn_id': 'test_monitoring_conn', 'bq_dataset_id': 'test_dataset',", "values # each time when self.mock_variable is called. self.mock_variable.get.side_effect =", "\"License\"); # you may not use this file except in", "returned DAG contains correct DAG and tasks.\"\"\" expected_task_ids = ['bq_to_cm_retry_task',", "Google LLC. # # Licensed under the Apache License, Version", "= mock.MagicMock() self.original_monitoring_hook = monitoring_hook.MonitoringHook monitoring_hook.MonitoringHook = mock.MagicMock() def tearDown(self):", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "_DAG_NAME, f'{_DAG_NAME}_schedule': '@once', f'{_DAG_NAME}_retries': 0, f'{_DAG_NAME}_retry_delay': 3, f'{_DAG_NAME}_is_retry': True, f'{_DAG_NAME}_is_run':", "tasks.\"\"\" expected_task_ids = ['bq_to_cm_retry_task', 'bq_to_cm_task'] test_dag = bq_to_cm_dag.BigQueryToCMDag( AIRFLOW_VARIABLES['dag_name']).create_dag() self.assertIsInstance(test_dag,", "def tearDown(self): super().tearDown() bigquery_hook.BigQueryHook.__init__ = self.original_bigquery_hook_init monitoring_hook.MonitoringHook = self.original_monitoring_hook def", "f'{_DAG_NAME}_enable_monitoring_cleanup': False, 'monitoring_data_days_to_live': 50, 'monitoring_dataset': 'test_monitoring_dataset', 'monitoring_table': 'test_monitoring_table', 'monitoring_bq_conn_id': 'test_monitoring_conn',", "# limitations under the License. \"\"\"Tests for dags.bq_to_cm_dag.\"\"\" import unittest", "'cm_service_account' } class BQToCMDAGTest(unittest.TestCase): def setUp(self): super(BQToCMDAGTest, self).setUp() self.addCleanup(mock.patch.stopall) self.build_impersonated_client_mock", "return values # each time when self.mock_variable is called. self.mock_variable.get.side_effect", "when self.mock_variable is called. self.mock_variable.get.side_effect = ( lambda key, value:", "by applicable law or agreed to in writing, software #", "# distributed under the License is distributed on an \"AS", "OF ANY KIND, either express or implied. # See the", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "the License. \"\"\"Tests for dags.bq_to_cm_dag.\"\"\" import unittest from airflow.contrib.hooks import", "airflow.contrib.hooks import bigquery_hook from airflow.models import baseoperator from airflow.models import", "may obtain a copy of the License at # #", "# Unless required by applicable law or agreed to in", "ANY KIND, either express or implied. # See the License", "See the License for the specific language governing permissions and", "self).setUp() self.addCleanup(mock.patch.stopall) self.build_impersonated_client_mock = mock.patch.object( cloud_auth, 'build_impersonated_client', autospec=True) self.build_impersonated_client_mock.return_value =", "from plugins.pipeline_plugins.hooks import monitoring_hook _DAG_NAME = bq_to_cm_dag._DAG_NAME AIRFLOW_VARIABLES = {", "cloud_auth from dags import bq_to_cm_dag from plugins.pipeline_plugins.hooks import monitoring_hook _DAG_NAME", "the License. # You may obtain a copy of the", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "for the specific language governing permissions and # limitations under", "'test_monitoring_dataset', 'monitoring_table': 'test_monitoring_table', 'monitoring_bq_conn_id': 'test_monitoring_conn', 'bq_dataset_id': 'test_dataset', 'bq_table_id': 'test_table', 'cm_profile_id':", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "test_dag.tasks: self.assertIsInstance(task, baseoperator.BaseOperator) actual_task_ids = [t.task_id for t in test_dag.tasks]", "to in writing, software # distributed under the License is", "'test_dataset', 'bq_table_id': 'test_table', 'cm_profile_id': 'cm_profile_id', 'cm_service_account': 'cm_service_account' } class BQToCMDAGTest(unittest.TestCase):", "DAG contains correct DAG and tasks.\"\"\" expected_task_ids = ['bq_to_cm_retry_task', 'bq_to_cm_task']", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "# Copyright 2020 Google LLC. # # Licensed under the", "# See the License for the specific language governing permissions", "'dag_name': _DAG_NAME, f'{_DAG_NAME}_schedule': '@once', f'{_DAG_NAME}_retries': 0, f'{_DAG_NAME}_retry_delay': 3, f'{_DAG_NAME}_is_retry': True,", "f'{_DAG_NAME}_retry_delay': 3, f'{_DAG_NAME}_is_retry': True, f'{_DAG_NAME}_is_run': True, f'{_DAG_NAME}_enable_run_report': False, f'{_DAG_NAME}_enable_monitoring': True,", "Copyright 2020 Google LLC. # # Licensed under the Apache", "import variable import mock from gps_building_blocks.cloud.utils import cloud_auth from dags", "gps_building_blocks.cloud.utils import cloud_auth from dags import bq_to_cm_dag from plugins.pipeline_plugins.hooks import", "You may obtain a copy of the License at #", "baseoperator.BaseOperator) actual_task_ids = [t.task_id for t in test_dag.tasks] self.assertListEqual(actual_task_ids, expected_task_ids)", "'monitoring_table': 'test_monitoring_table', 'monitoring_bq_conn_id': 'test_monitoring_conn', 'bq_dataset_id': 'test_dataset', 'bq_table_id': 'test_table', 'cm_profile_id': 'cm_profile_id',", "dags.bq_to_cm_dag.\"\"\" import unittest from airflow.contrib.hooks import bigquery_hook from airflow.models import", "autospec=True) self.build_impersonated_client_mock.return_value = mock.Mock() self.build_impersonated_client_mock.start() self.mock_variable = mock.patch.object( variable, 'Variable',", "True, f'{_DAG_NAME}_enable_monitoring_cleanup': False, 'monitoring_data_days_to_live': 50, 'monitoring_dataset': 'test_monitoring_dataset', 'monitoring_table': 'test_monitoring_table', 'monitoring_bq_conn_id':", "may not use this file except in compliance with the", "or agreed to in writing, software # distributed under the", "is assigned to `lambda` to dynamically return values # each", "required by applicable law or agreed to in writing, software", "bigquery_hook.BigQueryHook.__init__ = self.original_bigquery_hook_init monitoring_hook.MonitoringHook = self.original_monitoring_hook def test_create_dag(self): \"\"\"Tests that", "False, 'monitoring_data_days_to_live': 50, 'monitoring_dataset': 'test_monitoring_dataset', 'monitoring_table': 'test_monitoring_table', 'monitoring_bq_conn_id': 'test_monitoring_conn', 'bq_dataset_id':", "len(expected_task_ids)) for task in test_dag.tasks: self.assertIsInstance(task, baseoperator.BaseOperator) actual_task_ids = [t.task_id", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "self.original_monitoring_hook = monitoring_hook.MonitoringHook monitoring_hook.MonitoringHook = mock.MagicMock() def tearDown(self): super().tearDown() bigquery_hook.BigQueryHook.__init__", "# python3 # coding=utf-8 # Copyright 2020 Google LLC. #", "with the License. # You may obtain a copy of", "permissions and # limitations under the License. \"\"\"Tests for dags.bq_to_cm_dag.\"\"\"", "this file except in compliance with the License. # You", "monitoring_hook.MonitoringHook = mock.MagicMock() def tearDown(self): super().tearDown() bigquery_hook.BigQueryHook.__init__ = self.original_bigquery_hook_init monitoring_hook.MonitoringHook", "lambda key, value: AIRFLOW_VARIABLES[key]) self.original_bigquery_hook_init = bigquery_hook.BigQueryHook.__init__ bigquery_hook.BigQueryHook.__init__ = mock.MagicMock()", "expected_task_ids = ['bq_to_cm_retry_task', 'bq_to_cm_task'] test_dag = bq_to_cm_dag.BigQueryToCMDag( AIRFLOW_VARIABLES['dag_name']).create_dag() self.assertIsInstance(test_dag, dag.DAG)", "airflow.models import variable import mock from gps_building_blocks.cloud.utils import cloud_auth from", "the Apache License, Version 2.0 (the \"License\"); # you may", "under the License. \"\"\"Tests for dags.bq_to_cm_dag.\"\"\" import unittest from airflow.contrib.hooks", "self.original_monitoring_hook def test_create_dag(self): \"\"\"Tests that returned DAG contains correct DAG", "limitations under the License. \"\"\"Tests for dags.bq_to_cm_dag.\"\"\" import unittest from", "# coding=utf-8 # Copyright 2020 Google LLC. # # Licensed", "mock.patch.object( variable, 'Variable', autospec=True).start() # `side_effect` is assigned to `lambda`", "( lambda key, value: AIRFLOW_VARIABLES[key]) self.original_bigquery_hook_init = bigquery_hook.BigQueryHook.__init__ bigquery_hook.BigQueryHook.__init__ =", "\"\"\"Tests for dags.bq_to_cm_dag.\"\"\" import unittest from airflow.contrib.hooks import bigquery_hook from", "License. \"\"\"Tests for dags.bq_to_cm_dag.\"\"\" import unittest from airflow.contrib.hooks import bigquery_hook", "and # limitations under the License. \"\"\"Tests for dags.bq_to_cm_dag.\"\"\" import" ]
[ "Regional code setting is done automatically by DOS Webservices, so", "\"differential_rate\", \"BIDPOSTS:BT_REST_RELAXATION_POINT_TEXT\": strip_extra_spaces(\"rest_relaxation_point\"), \"BIDPOSTS:BT_DANGER_PAY_NUM\": \"danger_pay\", \"BIDPOSTS:BT_CONSUMABLE_ALLOWANCE_FLG\": parse_boolean(\"has_consumable_allowance\"), \"BIDPOSTS:BT_SERVICE_NEEDS_DIFF_FLG\": parse_boolean(\"has_service_needs_differential\"), }", "\"POSITIONS:POS_LANG_REQ_1_CODE\": \"_language_req_1_code\", \"POSITIONS:POS_LANG_REQ_2_CODE\": \"_language_req_2_code\", \"POSITIONS:POS_SPEAK_PROFICIENCY_1_CODE\": \"_language_1_spoken_proficiency_code\", \"POSITIONS:POS_READ_PROFICIENCY_1_CODE\": \"_language_1_reading_proficiency_code\", \"POSITIONS:POS_SPEAK_PROFICIENCY_2_CODE\": \"_language_2_spoken_proficiency_code\",", "\"BIDPOSTS:BT_SERVICE_NEEDS_DIFF_FLG\": parse_boolean(\"has_service_needs_differential\"), } def post_load_function(new_ids, updated_ids): for loc in Post.objects.filter(id__in=new_ids", "} # Update relationships def post_load_function(new_ids, updated_ids): for org in", "'tours_of_duty': mode_tour_of_duty, 'posts': mode_post, 'countries': mode_country, 'locations': mode_location, 'capsule_descriptions': mode_capsule_description,", "= { \"id\": \"_id\", \"name\": strip_extra_spaces(\"name\"), \"skill\": get_nested_tag(\"_skill_codes\", \"code\"), }", "mode_country(): model = Country instance_tag = \"DATA_RECORD\" collision_field = \"code\"", "\"_staff_ptrn_skill_code\", \"POSITIONS:POS_OVERSEAS_IND\": parse_boolean(\"is_overseas\", ['O']), \"POSITIONS:POS_PAY_PLAN_CODE\": \"_pay_plan_code\", \"POSITIONS:POS_STATUS_CODE\": \"_status_code\", \"POSITIONS:POS_SERVICE_TYPE_CODE\": \"_service_type_code\",", "\"description\" } return (model, instance_tag, tag_map, collision_field, None) def mode_grades():", "codes regional_codes = [ \"110000\", \"120000\", \"130000\", \"140000\", \"146000\", \"150000\",", "instance_tag = \"BIDPOSTS:BIDDING_TOOL\" collision_field = \"_location_code\" tag_map = { \"BIDPOSTS:DSC_CD\":", "\"_bureau_code\", \"POSITIONS:POS_SKILL_CODE\": \"_skill_code\", \"POSITIONS:POS_STAFF_PTRN_SKILL_CODE\": \"_staff_ptrn_skill_code\", \"POSITIONS:POS_OVERSEAS_IND\": parse_boolean(\"is_overseas\", ['O']), \"POSITIONS:POS_PAY_PLAN_CODE\": \"_pay_plan_code\",", "Location, Country class Command(BaseCommand): help = 'Loads an XML into", "\"POSITIONS:POS_PAY_PLAN_CODE\": \"_pay_plan_code\", \"POSITIONS:POS_STATUS_CODE\": \"_status_code\", \"POSITIONS:POS_SERVICE_TYPE_CODE\": \"_service_type_code\", \"POSITIONS:POS_GRADE_CODE\": \"_grade_code\", \"POSITIONS:POS_POST_CODE\": \"_post_code\",", "collision_field = \"code\" tag_map = { \"LANGUAGE_PROFICIENCY:LP_CODE\": \"code\", \"LANGUAGE_PROFICIENCY:LP_DESC\": \"description\"", "**kwargs) self.modes = { 'languages': mode_languages, 'proficiencies': mode_proficiencies, 'grades': mode_grades,", "\"POSITIONS:POS_SKILL_CODE\": \"_skill_code\", \"POSITIONS:POS_STAFF_PTRN_SKILL_CODE\": \"_staff_ptrn_skill_code\", \"POSITIONS:POS_OVERSEAS_IND\": parse_boolean(\"is_overseas\", ['O']), \"POSITIONS:POS_PAY_PLAN_CODE\": \"_pay_plan_code\", \"POSITIONS:POS_STATUS_CODE\":", "parse_boolean(\"has_service_needs_differential\"), } def post_load_function(new_ids, updated_ids): for loc in Post.objects.filter(id__in=new_ids +", "\"code\", \"ORG_SHORT_DESC\": \"short_description\", \"ORG_LONG_DESC\": strip_extra_spaces(\"long_description\"), \"ORG_PARENT_ORG_CODE\": \"_parent_organization_code\", \"ORG_BUREAU_ORG_CODE\": \"_parent_bureau_code\", \"ORG_LOCATION_CODE\":", "post_load_function(new_ids, updated_ids): for pos in Position.objects.filter(id__in=new_ids + updated_ids): pos.update_relationships() return", "+ updated_ids): org.update_relationships() # Regional code setting is done automatically", "\"140000\", \"146000\", \"150000\", \"160000\" ] if org.code in regional_codes: org.is_regional", "{len(updated_ids)}\\t\\t\") def mode_languages(): model = Language instance_tag = \"LANGUAGES:LANGUAGE\" collision_field", "instance_tag, tag_map, collision_field, post_load_function) def mode_positions(): model = Position instance_tag", "\"_update_id\", \"POSITIONS:POS_UPDATE_DATE\": parse_date(\"update_date\"), \"POSITIONS:POS_EFFECTIVE_DATE\": parse_date(\"effective_date\"), \"POSITIONS:POS_JOBCODE_CODE\": \"_jobcode_code\", \"POSITIONS:POS_OCC_SERIES_CODE\": \"_occ_series_code\", }", "] if org.code in regional_codes: org.is_regional = True else: org.is_regional", "True else: org.is_regional = False if org.code == org._parent_bureau_code: org.is_bureau", "Grade.objects.filter(id__in=new_ids + updated_ids): pos.update_relationships() return (model, instance_tag, tag_map, collision_field, post_load_function)", "None) def mode_organizations(): model = Organization instance_tag = \"DATA_RECORD\" collision_field", "parse_boolean, parse_date, get_nested_tag from talentmap_api.language.models import Language, Proficiency from talentmap_api.position.models", "None) def mode_grades(): model = Grade instance_tag = \"GRADES:GRADE\" collision_field", "\"146000\", \"150000\", \"160000\" ] if org.code in regional_codes: org.is_regional =", "collision_field = \"_pos_seq_num\" tag_map = { \"POS_SEQ_NUM\": \"_pos_seq_num\", \"capsuleDescription\": \"content\",", "\"months\" } return (model, instance_tag, tag_map, collision_field, None) def mode_post():", "our sample XML files # Array of regional codes regional_codes", "'&', item.text).strip()), \"TOUR_OF_DUTIES:TOD_MONTHS_NUM\": \"months\" } return (model, instance_tag, tag_map, collision_field,", "tag_map = { \"COUNTRY_CODE\": \"code\", \"FULL_NAME\": \"name\", \"SHORT_NAME\": \"short_name\", \"COUNTRY_CODE_2\":", "= \"LANGUAGES:LANGUAGE\" collision_field = \"code\" tag_map = { \"LANGUAGES:LANG_CODE\": \"code\",", "= \"LANGUAGE_PROFICIENCY:LANGUAGE_PROFICIENCY\" collision_field = \"code\" tag_map = { \"LANGUAGE_PROFICIENCY:LP_CODE\": \"code\",", "tag_map = { \"SKILLS:SKILL_CODE\": \"code\", \"SKILLS:SKILL_DESCRIPTION\": \"description\" } return (model,", "\"_title_code\", \"POSITIONS:POS_TITLE_DESC\": \"title\", \"POSITIONS:POS_ORG_CODE\": \"_org_code\", \"POSITIONS:POS_BUREAU_CODE\": \"_bureau_code\", \"POSITIONS:POS_SKILL_CODE\": \"_skill_code\", \"POSITIONS:POS_STAFF_PTRN_SKILL_CODE\":", "nargs=1, type=str, choices=self.modes.keys(), help=\"The type of data in the XML\")", "\"description\" } return (model, instance_tag, tag_map, collision_field, None) def mode_organizations():", "updated_ids): pos.update_relationships() return (model, instance_tag, tag_map, collision_field, post_load_function) def mode_skills():", "behavior collision_behavior = None if options['delete']: collision_behavior = \"delete\" elif", "None) def mode_proficiencies(): model = Proficiency instance_tag = \"LANGUAGE_PROFICIENCY:LANGUAGE_PROFICIENCY\" collision_field", "XMLloader(model, instance_tag, tag_map, collision_behavior, collision_field) new_ids, updated_ids = loader.create_models_from_xml(options['file'][0]) #", "item: setattr(instance, \"long_description\", re.sub('&amp;', '&', item.text).strip()), \"TOUR_OF_DUTIES:TOD_MONTHS_NUM\": \"months\" } return", "tag_map = { \"POS_SEQ_NUM\": \"_pos_seq_num\", \"capsuleDescription\": \"content\", } return (model,", "collision_field, post_load_function) def mode_tour_of_duty(): model = TourOfDuty instance_tag = \"TOUR_OF_DUTIES:TOUR_OF_DUTY\"", "Array of regional codes regional_codes = [ \"110000\", \"120000\", \"130000\",", "mode_skill_cone } def add_arguments(self, parser): parser.add_argument('file', nargs=1, type=str, help=\"The XML", "\"_language_1_spoken_proficiency_code\", \"POSITIONS:POS_READ_PROFICIENCY_1_CODE\": \"_language_1_reading_proficiency_code\", \"POSITIONS:POS_SPEAK_PROFICIENCY_2_CODE\": \"_language_2_spoken_proficiency_code\", \"POSITIONS:POS_READ_PROFICIENCY_2_CODE\": \"_language_2_reading_proficiency_code\", \"POSITIONS:POS_CREATE_ID\": \"_create_id\", \"POSITIONS:POS_CREATE_DATE\":", "mode_positions, 'tours_of_duty': mode_tour_of_duty, 'posts': mode_post, 'countries': mode_country, 'locations': mode_location, 'capsule_descriptions':", "\"ORG_LONG_DESC\": strip_extra_spaces(\"long_description\"), \"ORG_PARENT_ORG_CODE\": \"_parent_organization_code\", \"ORG_BUREAU_ORG_CODE\": \"_parent_bureau_code\", \"ORG_LOCATION_CODE\": \"_location_code\" } #", "posts for loc in Location.objects.filter(id__in=new_ids + updated_ids): Post.objects.filter(_location_code=loc.code).update(location=loc) return (model,", "return (model, instance_tag, tag_map, collision_field, post_load_function) def mode_tour_of_duty(): model =", "we now only need this logic when loading from our", "tag_map = { \"id\": \"_id\", \"name\": strip_extra_spaces(\"name\"), \"skill\": get_nested_tag(\"_skill_codes\", \"code\"),", "\"POSITIONS:POS_TITLE_CODE\": \"_title_code\", \"POSITIONS:POS_TITLE_DESC\": \"title\", \"POSITIONS:POS_ORG_CODE\": \"_org_code\", \"POSITIONS:POS_BUREAU_CODE\": \"_bureau_code\", \"POSITIONS:POS_SKILL_CODE\": \"_skill_code\",", "strip_extra_spaces(\"state\"), \"country\": \"_country\" } def post_load_function(new_ids, updated_ids): # Connect new", "file' logger = logging.getLogger(__name__) def __init__(self, *args, **kwargs): super(Command, self).__init__(*args,", "def handle(self, *args, **options): model, instance_tag, tag_map, collision_field, post_load_function =", "**options): model, instance_tag, tag_map, collision_field, post_load_function = self.modes[options['type'][0]]() # Set", "loading from our sample XML files # Array of regional", "item.text).strip()), \"TOUR_OF_DUTIES:TOD_MONTHS_NUM\": \"months\" } return (model, instance_tag, tag_map, collision_field, None)", "instance_tag = \"jobCategorySkill\" collision_field = None tag_map = { \"id\":", "\"code\", \"SKILLS:SKILL_DESCRIPTION\": \"description\" } return (model, instance_tag, tag_map, collision_field, None)", "\"_service_type_code\", \"POSITIONS:POS_GRADE_CODE\": \"_grade_code\", \"POSITIONS:POS_POST_CODE\": \"_post_code\", \"POSITIONS:POS_LANGUAGE_1_CODE\": \"_language_1_code\", \"POSITIONS:POS_LANGUAGE_2_CODE\": \"_language_2_code\", \"POSITIONS:POS_LOCATION_CODE\":", "\"code\" tag_map = { \"GRADES:GRD_GRADE_CODE\": \"code\" } def post_load_function(new_ids, updated_ids):", "org.is_bureau = True org.save() return (model, instance_tag, tag_map, collision_field, post_load_function)", "mode_post, 'countries': mode_country, 'locations': mode_location, 'capsule_descriptions': mode_capsule_description, 'skill_cone': mode_skill_cone }", "self.modes[options['type'][0]]() # Set / update the collision behavior collision_behavior =", "= TourOfDuty instance_tag = \"TOUR_OF_DUTIES:TOUR_OF_DUTY\" collision_field = \"code\" tag_map =", "in the XML\") parser.add_argument('--delete', dest='delete', action='store_true', help='Delete collisions') parser.add_argument('--update', dest='update',", "applicable posts for loc in Location.objects.filter(id__in=new_ids + updated_ids): Post.objects.filter(_location_code=loc.code).update(location=loc) return", "parser.add_argument('--update', dest='update', action='store_true', help='Update collisions') parser.add_argument('--skippost', dest='skip_post', action='store_true', help='Skip post", "# Run the post load function, if it exists if", "Language, Proficiency from talentmap_api.position.models import Grade, Skill, Position, CapsuleDescription, SkillCone", "import Language, Proficiency from talentmap_api.position.models import Grade, Skill, Position, CapsuleDescription,", "model = Post instance_tag = \"BIDPOSTS:BIDDING_TOOL\" collision_field = \"_location_code\" tag_map", "= True org.save() return (model, instance_tag, tag_map, collision_field, post_load_function) def", "loc in Post.objects.filter(id__in=new_ids + updated_ids): loc.update_relationships() return (model, instance_tag, tag_map,", "\"COUNTRY_CODE_2\": \"short_code\", \"LOCATION_PREFIX\": \"location_prefix\" } return (model, instance_tag, tag_map, collision_field,", "\"LOCATION_PREFIX\": \"location_prefix\" } return (model, instance_tag, tag_map, collision_field, None) def", "model = Skill instance_tag = \"SKILLS:SKILL\" collision_field = \"code\" tag_map", "\"LANGUAGES:LANG_LONG_DESC\": \"long_description\", \"LANGUAGES:LANG_SHORT_DESC\": \"short_description\", \"LANGUAGES:LANG_EFFECTIVE_DATE\": parse_date(\"effective_date\") } return (model, instance_tag,", "\"short_name\", \"COUNTRY_CODE_2\": \"short_code\", \"LOCATION_PREFIX\": \"location_prefix\" } return (model, instance_tag, tag_map,", "None) def mode_post(): model = Post instance_tag = \"BIDPOSTS:BIDDING_TOOL\" collision_field", "instance_tag = \"SKILLS:SKILL\" collision_field = \"code\" tag_map = { \"SKILLS:SKILL_CODE\":", "model = CapsuleDescription instance_tag = \"position\" collision_field = \"_pos_seq_num\" tag_map", "\"LANGUAGES:LANG_SHORT_DESC\": \"short_description\", \"LANGUAGES:LANG_EFFECTIVE_DATE\": parse_date(\"effective_date\") } return (model, instance_tag, tag_map, collision_field,", "collision_field = \"code\" tag_map = { \"SKILLS:SKILL_CODE\": \"code\", \"SKILLS:SKILL_DESCRIPTION\": \"description\"", "Position, CapsuleDescription, SkillCone from talentmap_api.organization.models import Organization, Post, TourOfDuty, Location,", "def post_load_function(new_ids, updated_ids): for org in Organization.objects.filter(id__in=new_ids + updated_ids): org.update_relationships()", "\"DATA_RECORD\" collision_field = \"code\" tag_map = { \"COUNTRY_CODE\": \"code\", \"FULL_NAME\":", "(model, instance_tag, tag_map, collision_field, None) def mode_post(): model = Post", "= \"code\" tag_map = { \"ORG_CODE\": \"code\", \"ORG_SHORT_DESC\": \"short_description\", \"ORG_LONG_DESC\":", "mode_languages, 'proficiencies': mode_proficiencies, 'grades': mode_grades, 'skills': mode_skills, 'organizations': mode_organizations, 'positions':", "'countries': mode_country, 'locations': mode_location, 'capsule_descriptions': mode_capsule_description, 'skill_cone': mode_skill_cone } def", "= { \"LANGUAGE_PROFICIENCY:LP_CODE\": \"code\", \"LANGUAGE_PROFICIENCY:LP_DESC\": \"description\" } return (model, instance_tag,", "} return (model, instance_tag, tag_map, collision_field, None) def mode_skill_cone(): model", "{ \"SKILLS:SKILL_CODE\": \"code\", \"SKILLS:SKILL_DESCRIPTION\": \"description\" } return (model, instance_tag, tag_map,", "\"_language_1_code\", \"POSITIONS:POS_LANGUAGE_2_CODE\": \"_language_2_code\", \"POSITIONS:POS_LOCATION_CODE\": \"_location_code\", \"POSITIONS:POS_LANG_REQ_1_CODE\": \"_language_req_1_code\", \"POSITIONS:POS_LANG_REQ_2_CODE\": \"_language_req_2_code\", \"POSITIONS:POS_SPEAK_PROFICIENCY_1_CODE\":", "return (model, instance_tag, tag_map, collision_field, None) def mode_skill_cone(): model =", "\"code\" tag_map = { \"code\": \"code\", \"city\": strip_extra_spaces(\"city\"), \"state\": strip_extra_spaces(\"state\"),", "regional_codes: org.is_regional = True else: org.is_regional = False if org.code", "import logging import re from talentmap_api.common.xml_helpers import XMLloader, strip_extra_spaces, parse_boolean,", "= { \"ORG_CODE\": \"code\", \"ORG_SHORT_DESC\": \"short_description\", \"ORG_LONG_DESC\": strip_extra_spaces(\"long_description\"), \"ORG_PARENT_ORG_CODE\": \"_parent_organization_code\",", "\"POSITIONS:POS_LANGUAGE_1_CODE\": \"_language_1_code\", \"POSITIONS:POS_LANGUAGE_2_CODE\": \"_language_2_code\", \"POSITIONS:POS_LOCATION_CODE\": \"_location_code\", \"POSITIONS:POS_LANG_REQ_1_CODE\": \"_language_req_1_code\", \"POSITIONS:POS_LANG_REQ_2_CODE\": \"_language_req_2_code\",", "\"_occ_series_code\", } def post_load_function(new_ids, updated_ids): for pos in Position.objects.filter(id__in=new_ids +", "code setting is done automatically by DOS Webservices, so #", "{ \"ORG_CODE\": \"code\", \"ORG_SHORT_DESC\": \"short_description\", \"ORG_LONG_DESC\": strip_extra_spaces(\"long_description\"), \"ORG_PARENT_ORG_CODE\": \"_parent_organization_code\", \"ORG_BUREAU_ORG_CODE\":", "\"_language_2_reading_proficiency_code\", \"POSITIONS:POS_CREATE_ID\": \"_create_id\", \"POSITIONS:POS_CREATE_DATE\": parse_date(\"create_date\"), \"POSITIONS:POS_UPDATE_ID\": \"_update_id\", \"POSITIONS:POS_UPDATE_DATE\": parse_date(\"update_date\"), \"POSITIONS:POS_EFFECTIVE_DATE\":", "def mode_tour_of_duty(): model = TourOfDuty instance_tag = \"TOUR_OF_DUTIES:TOUR_OF_DUTY\" collision_field =", "= \"jobCategorySkill\" collision_field = None tag_map = { \"id\": \"_id\",", "loc.update_relationships() return (model, instance_tag, tag_map, collision_field, post_load_function) def mode_country(): model", "\"jobCategorySkill\" collision_field = None tag_map = { \"id\": \"_id\", \"name\":", "talentmap_api.language.models import Language, Proficiency from talentmap_api.position.models import Grade, Skill, Position,", "= \"code\" tag_map = { \"TOUR_OF_DUTIES:TOD_CODE\": \"code\", \"TOUR_OF_DUTIES:TOD_SHORT_DESC\": \"short_description\", \"TOUR_OF_DUTIES:TOD_DESC_TEXT\":", "from django.core.management.base import BaseCommand import logging import re from talentmap_api.common.xml_helpers", "tag_map = { \"ORG_CODE\": \"code\", \"ORG_SHORT_DESC\": \"short_description\", \"ORG_LONG_DESC\": strip_extra_spaces(\"long_description\"), \"ORG_PARENT_ORG_CODE\":", "= Country instance_tag = \"DATA_RECORD\" collision_field = \"code\" tag_map =", "{ \"id\": \"_id\", \"name\": strip_extra_spaces(\"name\"), \"skill\": get_nested_tag(\"_skill_codes\", \"code\"), } return", "Location instance_tag = \"location\" collision_field = \"code\" tag_map = {", "collisions') parser.add_argument('--skippost', dest='skip_post', action='store_true', help='Skip post load functions') def handle(self,", "post_load_function) def mode_positions(): model = Position instance_tag = \"POSITIONS:POSITION\" collision_field", "\"position_number\", \"POSITIONS:POS_TITLE_CODE\": \"_title_code\", \"POSITIONS:POS_TITLE_DESC\": \"title\", \"POSITIONS:POS_ORG_CODE\": \"_org_code\", \"POSITIONS:POS_BUREAU_CODE\": \"_bureau_code\", \"POSITIONS:POS_SKILL_CODE\":", "mode_proficiencies(): model = Proficiency instance_tag = \"LANGUAGE_PROFICIENCY:LANGUAGE_PROFICIENCY\" collision_field = \"code\"", "{ \"LANGUAGES:LANG_CODE\": \"code\", \"LANGUAGES:LANG_LONG_DESC\": \"long_description\", \"LANGUAGES:LANG_SHORT_DESC\": \"short_description\", \"LANGUAGES:LANG_EFFECTIVE_DATE\": parse_date(\"effective_date\") }", "\"BIDPOSTS:BT_REST_RELAXATION_POINT_TEXT\": strip_extra_spaces(\"rest_relaxation_point\"), \"BIDPOSTS:BT_DANGER_PAY_NUM\": \"danger_pay\", \"BIDPOSTS:BT_CONSUMABLE_ALLOWANCE_FLG\": parse_boolean(\"has_consumable_allowance\"), \"BIDPOSTS:BT_SERVICE_NEEDS_DIFF_FLG\": parse_boolean(\"has_service_needs_differential\"), } def", "mode_location(): model = Location instance_tag = \"location\" collision_field = \"code\"", "\"120000\", \"130000\", \"140000\", \"146000\", \"150000\", \"160000\" ] if org.code in", "updated_ids) self.logger.info(f\"XML Load Report\\n\\tNew: {len(new_ids)}\\n\\tUpdated: {len(updated_ids)}\\t\\t\") def mode_languages(): model =", "= logging.getLogger(__name__) def __init__(self, *args, **kwargs): super(Command, self).__init__(*args, **kwargs) self.modes", "talentmap_api.position.models import Grade, Skill, Position, CapsuleDescription, SkillCone from talentmap_api.organization.models import", "= Organization instance_tag = \"DATA_RECORD\" collision_field = \"code\" tag_map =", "org.update_relationships() # Regional code setting is done automatically by DOS", "= \"POSITIONS:POSITION\" collision_field = \"_seq_num\" tag_map = { \"POSITIONS:POS_SEQ_NUM\": \"_seq_num\",", "new locations to applicable posts for loc in Location.objects.filter(id__in=new_ids +", "collision_behavior = \"delete\" elif options['update']: collision_behavior = \"update\" else: collision_behavior", "# Regional code setting is done automatically by DOS Webservices,", "import XMLloader, strip_extra_spaces, parse_boolean, parse_date, get_nested_tag from talentmap_api.language.models import Language,", "parse_date(\"update_date\"), \"POSITIONS:POS_EFFECTIVE_DATE\": parse_date(\"effective_date\"), \"POSITIONS:POS_JOBCODE_CODE\": \"_jobcode_code\", \"POSITIONS:POS_OCC_SERIES_CODE\": \"_occ_series_code\", } def post_load_function(new_ids,", "in Grade.objects.filter(id__in=new_ids + updated_ids): pos.update_relationships() return (model, instance_tag, tag_map, collision_field,", "\"_location_code\", \"POSITIONS:POS_LANG_REQ_1_CODE\": \"_language_req_1_code\", \"POSITIONS:POS_LANG_REQ_2_CODE\": \"_language_req_2_code\", \"POSITIONS:POS_SPEAK_PROFICIENCY_1_CODE\": \"_language_1_spoken_proficiency_code\", \"POSITIONS:POS_READ_PROFICIENCY_1_CODE\": \"_language_1_reading_proficiency_code\", \"POSITIONS:POS_SPEAK_PROFICIENCY_2_CODE\":", "\"ORG_SHORT_DESC\": \"short_description\", \"ORG_LONG_DESC\": strip_extra_spaces(\"long_description\"), \"ORG_PARENT_ORG_CODE\": \"_parent_organization_code\", \"ORG_BUREAU_ORG_CODE\": \"_parent_bureau_code\", \"ORG_LOCATION_CODE\": \"_location_code\"", "mode_post(): model = Post instance_tag = \"BIDPOSTS:BIDDING_TOOL\" collision_field = \"_location_code\"", "mode_skill_cone(): model = SkillCone instance_tag = \"jobCategorySkill\" collision_field = None", "collisions') parser.add_argument('--update', dest='update', action='store_true', help='Update collisions') parser.add_argument('--skippost', dest='skip_post', action='store_true', help='Skip", "\"POSITIONS:POS_SPEAK_PROFICIENCY_1_CODE\": \"_language_1_spoken_proficiency_code\", \"POSITIONS:POS_READ_PROFICIENCY_1_CODE\": \"_language_1_reading_proficiency_code\", \"POSITIONS:POS_SPEAK_PROFICIENCY_2_CODE\": \"_language_2_spoken_proficiency_code\", \"POSITIONS:POS_READ_PROFICIENCY_2_CODE\": \"_language_2_reading_proficiency_code\", \"POSITIONS:POS_CREATE_ID\": \"_create_id\",", "\"LANGUAGES:LANG_CODE\": \"code\", \"LANGUAGES:LANG_LONG_DESC\": \"long_description\", \"LANGUAGES:LANG_SHORT_DESC\": \"short_description\", \"LANGUAGES:LANG_EFFECTIVE_DATE\": parse_date(\"effective_date\") } return", "if callable(post_load_function) and not options['skip_post']: post_load_function(new_ids, updated_ids) self.logger.info(f\"XML Load Report\\n\\tNew:", "model = Proficiency instance_tag = \"LANGUAGE_PROFICIENCY:LANGUAGE_PROFICIENCY\" collision_field = \"code\" tag_map", "\"LANGUAGE_PROFICIENCY:LP_CODE\": \"code\", \"LANGUAGE_PROFICIENCY:LP_DESC\": \"description\" } return (model, instance_tag, tag_map, collision_field,", "\"_pay_plan_code\", \"POSITIONS:POS_STATUS_CODE\": \"_status_code\", \"POSITIONS:POS_SERVICE_TYPE_CODE\": \"_service_type_code\", \"POSITIONS:POS_GRADE_CODE\": \"_grade_code\", \"POSITIONS:POS_POST_CODE\": \"_post_code\", \"POSITIONS:POS_LANGUAGE_1_CODE\":", "\"COUNTRY_CODE\": \"code\", \"FULL_NAME\": \"name\", \"SHORT_NAME\": \"short_name\", \"COUNTRY_CODE_2\": \"short_code\", \"LOCATION_PREFIX\": \"location_prefix\"", "collision_field, post_load_function) def mode_capsule_description(): model = CapsuleDescription instance_tag = \"position\"", "*args, **kwargs): super(Command, self).__init__(*args, **kwargs) self.modes = { 'languages': mode_languages,", "\"_language_2_code\", \"POSITIONS:POS_LOCATION_CODE\": \"_location_code\", \"POSITIONS:POS_LANG_REQ_1_CODE\": \"_language_req_1_code\", \"POSITIONS:POS_LANG_REQ_2_CODE\": \"_language_req_2_code\", \"POSITIONS:POS_SPEAK_PROFICIENCY_1_CODE\": \"_language_1_spoken_proficiency_code\", \"POSITIONS:POS_READ_PROFICIENCY_1_CODE\":", "org._parent_bureau_code: org.is_bureau = True org.save() return (model, instance_tag, tag_map, collision_field,", "\"TOUR_OF_DUTIES:TOD_DESC_TEXT\": lambda instance, item: setattr(instance, \"long_description\", re.sub('&amp;', '&', item.text).strip()), \"TOUR_OF_DUTIES:TOD_MONTHS_NUM\":", "XML file to load\") parser.add_argument('type', nargs=1, type=str, choices=self.modes.keys(), help=\"The type", "def post_load_function(new_ids, updated_ids): for loc in Post.objects.filter(id__in=new_ids + updated_ids): loc.update_relationships()", "updated_ids): Post.objects.filter(_location_code=loc.code).update(location=loc) return (model, instance_tag, tag_map, collision_field, post_load_function) def mode_capsule_description():", "sample XML files # Array of regional codes regional_codes =", "model = SkillCone instance_tag = \"jobCategorySkill\" collision_field = None tag_map", "\"SKILLS:SKILL\" collision_field = \"code\" tag_map = { \"SKILLS:SKILL_CODE\": \"code\", \"SKILLS:SKILL_DESCRIPTION\":", "mode_skills, 'organizations': mode_organizations, 'positions': mode_positions, 'tours_of_duty': mode_tour_of_duty, 'posts': mode_post, 'countries':", "post_load_function(new_ids, updated_ids): for loc in Post.objects.filter(id__in=new_ids + updated_ids): loc.update_relationships() return", "mode_capsule_description(): model = CapsuleDescription instance_tag = \"position\" collision_field = \"_pos_seq_num\"", "\"code\", \"LANGUAGES:LANG_LONG_DESC\": \"long_description\", \"LANGUAGES:LANG_SHORT_DESC\": \"short_description\", \"LANGUAGES:LANG_EFFECTIVE_DATE\": parse_date(\"effective_date\") } return (model,", "def mode_post(): model = Post instance_tag = \"BIDPOSTS:BIDDING_TOOL\" collision_field =", "\"BIDPOSTS:TOD_CODE\": \"_tod_code\", \"BIDPOSTS:BT_COST_OF_LIVING_ADJUST_NUM\": \"cost_of_living_adjustment\", \"BIDPOSTS:BT_DIFFERENTIAL_RATE_NUM\": \"differential_rate\", \"BIDPOSTS:BT_REST_RELAXATION_POINT_TEXT\": strip_extra_spaces(\"rest_relaxation_point\"), \"BIDPOSTS:BT_DANGER_PAY_NUM\": \"danger_pay\",", "relationships def post_load_function(new_ids, updated_ids): for org in Organization.objects.filter(id__in=new_ids + updated_ids):", "post_load_function(new_ids, updated_ids): for pos in Grade.objects.filter(id__in=new_ids + updated_ids): pos.update_relationships() return", "+ updated_ids): pos.update_relationships() return (model, instance_tag, tag_map, collision_field, post_load_function) def", "for loc in Location.objects.filter(id__in=new_ids + updated_ids): Post.objects.filter(_location_code=loc.code).update(location=loc) return (model, instance_tag,", "(model, instance_tag, tag_map, collision_field, post_load_function) def mode_capsule_description(): model = CapsuleDescription", "re.sub('&amp;', '&', item.text).strip()), \"TOUR_OF_DUTIES:TOD_MONTHS_NUM\": \"months\" } return (model, instance_tag, tag_map,", "post load function, if it exists if callable(post_load_function) and not", "instance_tag, tag_map, collision_field, post_load_function) def mode_skills(): model = Skill instance_tag", "(model, instance_tag, tag_map, collision_field, None) def mode_organizations(): model = Organization", "\"POSITIONS:POS_TITLE_DESC\": \"title\", \"POSITIONS:POS_ORG_CODE\": \"_org_code\", \"POSITIONS:POS_BUREAU_CODE\": \"_bureau_code\", \"POSITIONS:POS_SKILL_CODE\": \"_skill_code\", \"POSITIONS:POS_STAFF_PTRN_SKILL_CODE\": \"_staff_ptrn_skill_code\",", "\"location\" collision_field = \"code\" tag_map = { \"code\": \"code\", \"city\":", "tag_map = { \"TOUR_OF_DUTIES:TOD_CODE\": \"code\", \"TOUR_OF_DUTIES:TOD_SHORT_DESC\": \"short_description\", \"TOUR_OF_DUTIES:TOD_DESC_TEXT\": lambda instance,", "= CapsuleDescription instance_tag = \"position\" collision_field = \"_pos_seq_num\" tag_map =", "load function, if it exists if callable(post_load_function) and not options['skip_post']:", "\"150000\", \"160000\" ] if org.code in regional_codes: org.is_regional = True", "from talentmap_api.language.models import Language, Proficiency from talentmap_api.position.models import Grade, Skill,", "the post load function, if it exists if callable(post_load_function) and", "if it exists if callable(post_load_function) and not options['skip_post']: post_load_function(new_ids, updated_ids)", "functions') def handle(self, *args, **options): model, instance_tag, tag_map, collision_field, post_load_function", "into a supported file' logger = logging.getLogger(__name__) def __init__(self, *args,", "def __init__(self, *args, **kwargs): super(Command, self).__init__(*args, **kwargs) self.modes = {", "= { \"POSITIONS:POS_SEQ_NUM\": \"_seq_num\", \"POSITIONS:POS_NUM_TEXT\": \"position_number\", \"POSITIONS:POS_TITLE_CODE\": \"_title_code\", \"POSITIONS:POS_TITLE_DESC\": \"title\",", "def post_load_function(new_ids, updated_ids): # Connect new locations to applicable posts", "instance_tag = \"TOUR_OF_DUTIES:TOUR_OF_DUTY\" collision_field = \"code\" tag_map = { \"TOUR_OF_DUTIES:TOD_CODE\":", "{ \"TOUR_OF_DUTIES:TOD_CODE\": \"code\", \"TOUR_OF_DUTIES:TOD_SHORT_DESC\": \"short_description\", \"TOUR_OF_DUTIES:TOD_DESC_TEXT\": lambda instance, item: setattr(instance,", "Language instance_tag = \"LANGUAGES:LANGUAGE\" collision_field = \"code\" tag_map = {", "parser.add_argument('--delete', dest='delete', action='store_true', help='Delete collisions') parser.add_argument('--update', dest='update', action='store_true', help='Update collisions')", "collision_field, None) def mode_post(): model = Post instance_tag = \"BIDPOSTS:BIDDING_TOOL\"", "= None tag_map = { \"id\": \"_id\", \"name\": strip_extra_spaces(\"name\"), \"skill\":", "logic when loading from our sample XML files # Array", "\"LANGUAGE_PROFICIENCY:LANGUAGE_PROFICIENCY\" collision_field = \"code\" tag_map = { \"LANGUAGE_PROFICIENCY:LP_CODE\": \"code\", \"LANGUAGE_PROFICIENCY:LP_DESC\":", "\"160000\" ] if org.code in regional_codes: org.is_regional = True else:", "help='Skip post load functions') def handle(self, *args, **options): model, instance_tag,", "== org._parent_bureau_code: org.is_bureau = True org.save() return (model, instance_tag, tag_map,", "None) def mode_skill_cone(): model = SkillCone instance_tag = \"jobCategorySkill\" collision_field", "def mode_skill_cone(): model = SkillCone instance_tag = \"jobCategorySkill\" collision_field =", "a supported file' logger = logging.getLogger(__name__) def __init__(self, *args, **kwargs):", "type=str, help=\"The XML file to load\") parser.add_argument('type', nargs=1, type=str, choices=self.modes.keys(),", "type=str, choices=self.modes.keys(), help=\"The type of data in the XML\") parser.add_argument('--delete',", "collision_behavior, collision_field) new_ids, updated_ids = loader.create_models_from_xml(options['file'][0]) # Run the post", "\"country\": \"_country\" } def post_load_function(new_ids, updated_ids): # Connect new locations", "= { \"LANGUAGES:LANG_CODE\": \"code\", \"LANGUAGES:LANG_LONG_DESC\": \"long_description\", \"LANGUAGES:LANG_SHORT_DESC\": \"short_description\", \"LANGUAGES:LANG_EFFECTIVE_DATE\": parse_date(\"effective_date\")", "new_ids, updated_ids = loader.create_models_from_xml(options['file'][0]) # Run the post load function,", "{ \"POSITIONS:POS_SEQ_NUM\": \"_seq_num\", \"POSITIONS:POS_NUM_TEXT\": \"position_number\", \"POSITIONS:POS_TITLE_CODE\": \"_title_code\", \"POSITIONS:POS_TITLE_DESC\": \"title\", \"POSITIONS:POS_ORG_CODE\":", "\"GRADES:GRD_GRADE_CODE\": \"code\" } def post_load_function(new_ids, updated_ids): for pos in Grade.objects.filter(id__in=new_ids", "org.code in regional_codes: org.is_regional = True else: org.is_regional = False", "True org.save() return (model, instance_tag, tag_map, collision_field, post_load_function) def mode_positions():", "Country class Command(BaseCommand): help = 'Loads an XML into a", "(model, instance_tag, tag_map, collision_field, post_load_function) def mode_skills(): model = Skill", "\"_location_code\", \"BIDPOSTS:TOD_CODE\": \"_tod_code\", \"BIDPOSTS:BT_COST_OF_LIVING_ADJUST_NUM\": \"cost_of_living_adjustment\", \"BIDPOSTS:BT_DIFFERENTIAL_RATE_NUM\": \"differential_rate\", \"BIDPOSTS:BT_REST_RELAXATION_POINT_TEXT\": strip_extra_spaces(\"rest_relaxation_point\"), \"BIDPOSTS:BT_DANGER_PAY_NUM\":", "\"code\", \"LANGUAGE_PROFICIENCY:LP_DESC\": \"description\" } return (model, instance_tag, tag_map, collision_field, None)", "instance_tag, tag_map, collision_field, post_load_function) def mode_capsule_description(): model = CapsuleDescription instance_tag", "mode_capsule_description, 'skill_cone': mode_skill_cone } def add_arguments(self, parser): parser.add_argument('file', nargs=1, type=str,", "Organization.objects.filter(id__in=new_ids + updated_ids): org.update_relationships() # Regional code setting is done", "= loader.create_models_from_xml(options['file'][0]) # Run the post load function, if it", "mode_positions(): model = Position instance_tag = \"POSITIONS:POSITION\" collision_field = \"_seq_num\"", "parse_date, get_nested_tag from talentmap_api.language.models import Language, Proficiency from talentmap_api.position.models import", "\"_language_req_1_code\", \"POSITIONS:POS_LANG_REQ_2_CODE\": \"_language_req_2_code\", \"POSITIONS:POS_SPEAK_PROFICIENCY_1_CODE\": \"_language_1_spoken_proficiency_code\", \"POSITIONS:POS_READ_PROFICIENCY_1_CODE\": \"_language_1_reading_proficiency_code\", \"POSITIONS:POS_SPEAK_PROFICIENCY_2_CODE\": \"_language_2_spoken_proficiency_code\", \"POSITIONS:POS_READ_PROFICIENCY_2_CODE\":", "in Location.objects.filter(id__in=new_ids + updated_ids): Post.objects.filter(_location_code=loc.code).update(location=loc) return (model, instance_tag, tag_map, collision_field,", "def add_arguments(self, parser): parser.add_argument('file', nargs=1, type=str, help=\"The XML file to", "= \"update\" else: collision_behavior = \"skip\" loader = XMLloader(model, instance_tag,", "\"SKILLS:SKILL_DESCRIPTION\": \"description\" } return (model, instance_tag, tag_map, collision_field, None) def", "from our sample XML files # Array of regional codes", "\"_parent_organization_code\", \"ORG_BUREAU_ORG_CODE\": \"_parent_bureau_code\", \"ORG_LOCATION_CODE\": \"_location_code\" } # Update relationships def", "\"content\", } return (model, instance_tag, tag_map, collision_field, None) def mode_skill_cone():", "\"code\", \"TOUR_OF_DUTIES:TOD_SHORT_DESC\": \"short_description\", \"TOUR_OF_DUTIES:TOD_DESC_TEXT\": lambda instance, item: setattr(instance, \"long_description\", re.sub('&amp;',", "\"LANGUAGES:LANGUAGE\" collision_field = \"code\" tag_map = { \"LANGUAGES:LANG_CODE\": \"code\", \"LANGUAGES:LANG_LONG_DESC\":", "\"POSITIONS:POS_SPEAK_PROFICIENCY_2_CODE\": \"_language_2_spoken_proficiency_code\", \"POSITIONS:POS_READ_PROFICIENCY_2_CODE\": \"_language_2_reading_proficiency_code\", \"POSITIONS:POS_CREATE_ID\": \"_create_id\", \"POSITIONS:POS_CREATE_DATE\": parse_date(\"create_date\"), \"POSITIONS:POS_UPDATE_ID\": \"_update_id\",", "pos in Position.objects.filter(id__in=new_ids + updated_ids): pos.update_relationships() return (model, instance_tag, tag_map,", "when loading from our sample XML files # Array of", "options['delete']: collision_behavior = \"delete\" elif options['update']: collision_behavior = \"update\" else:", "Proficiency instance_tag = \"LANGUAGE_PROFICIENCY:LANGUAGE_PROFICIENCY\" collision_field = \"code\" tag_map = {", "instance_tag = \"DATA_RECORD\" collision_field = \"code\" tag_map = { \"COUNTRY_CODE\":", "post_load_function) def mode_skills(): model = Skill instance_tag = \"SKILLS:SKILL\" collision_field", "= \"code\" tag_map = { \"LANGUAGE_PROFICIENCY:LP_CODE\": \"code\", \"LANGUAGE_PROFICIENCY:LP_DESC\": \"description\" }", "else: collision_behavior = \"skip\" loader = XMLloader(model, instance_tag, tag_map, collision_behavior,", "setattr(instance, \"long_description\", re.sub('&amp;', '&', item.text).strip()), \"TOUR_OF_DUTIES:TOD_MONTHS_NUM\": \"months\" } return (model,", "\"title\", \"POSITIONS:POS_ORG_CODE\": \"_org_code\", \"POSITIONS:POS_BUREAU_CODE\": \"_bureau_code\", \"POSITIONS:POS_SKILL_CODE\": \"_skill_code\", \"POSITIONS:POS_STAFF_PTRN_SKILL_CODE\": \"_staff_ptrn_skill_code\", \"POSITIONS:POS_OVERSEAS_IND\":", "collision_field, None) def mode_grades(): model = Grade instance_tag = \"GRADES:GRADE\"", "it exists if callable(post_load_function) and not options['skip_post']: post_load_function(new_ids, updated_ids) self.logger.info(f\"XML", "post_load_function) def mode_country(): model = Country instance_tag = \"DATA_RECORD\" collision_field", "CapsuleDescription, SkillCone from talentmap_api.organization.models import Organization, Post, TourOfDuty, Location, Country", "class Command(BaseCommand): help = 'Loads an XML into a supported", "= \"_location_code\" tag_map = { \"BIDPOSTS:DSC_CD\": \"_location_code\", \"BIDPOSTS:TOD_CODE\": \"_tod_code\", \"BIDPOSTS:BT_COST_OF_LIVING_ADJUST_NUM\":", "None tag_map = { \"id\": \"_id\", \"name\": strip_extra_spaces(\"name\"), \"skill\": get_nested_tag(\"_skill_codes\",", "= \"code\" tag_map = { \"COUNTRY_CODE\": \"code\", \"FULL_NAME\": \"name\", \"SHORT_NAME\":", "parser.add_argument('file', nargs=1, type=str, help=\"The XML file to load\") parser.add_argument('type', nargs=1,", "\"ORG_CODE\": \"code\", \"ORG_SHORT_DESC\": \"short_description\", \"ORG_LONG_DESC\": strip_extra_spaces(\"long_description\"), \"ORG_PARENT_ORG_CODE\": \"_parent_organization_code\", \"ORG_BUREAU_ORG_CODE\": \"_parent_bureau_code\",", "} return (model, instance_tag, tag_map, collision_field, None) def mode_post(): model", "\"update\" else: collision_behavior = \"skip\" loader = XMLloader(model, instance_tag, tag_map,", "collision_field, None) def mode_organizations(): model = Organization instance_tag = \"DATA_RECORD\"", "= \"delete\" elif options['update']: collision_behavior = \"update\" else: collision_behavior =", "def mode_grades(): model = Grade instance_tag = \"GRADES:GRADE\" collision_field =", "tag_map, collision_field, post_load_function) def mode_country(): model = Country instance_tag =", "\"_pos_seq_num\", \"capsuleDescription\": \"content\", } return (model, instance_tag, tag_map, collision_field, None)", "mode_tour_of_duty, 'posts': mode_post, 'countries': mode_country, 'locations': mode_location, 'capsule_descriptions': mode_capsule_description, 'skill_cone':", "(model, instance_tag, tag_map, collision_field, None) def mode_skill_cone(): model = SkillCone", "post_load_function = self.modes[options['type'][0]]() # Set / update the collision behavior", "to applicable posts for loc in Location.objects.filter(id__in=new_ids + updated_ids): Post.objects.filter(_location_code=loc.code).update(location=loc)", "+ updated_ids): loc.update_relationships() return (model, instance_tag, tag_map, collision_field, post_load_function) def", "# Connect new locations to applicable posts for loc in", "tag_map, collision_field, None) def mode_grades(): model = Grade instance_tag =", "of data in the XML\") parser.add_argument('--delete', dest='delete', action='store_true', help='Delete collisions')", "{ \"LANGUAGE_PROFICIENCY:LP_CODE\": \"code\", \"LANGUAGE_PROFICIENCY:LP_DESC\": \"description\" } return (model, instance_tag, tag_map,", "action='store_true', help='Skip post load functions') def handle(self, *args, **options): model,", "choices=self.modes.keys(), help=\"The type of data in the XML\") parser.add_argument('--delete', dest='delete',", "\"_language_1_reading_proficiency_code\", \"POSITIONS:POS_SPEAK_PROFICIENCY_2_CODE\": \"_language_2_spoken_proficiency_code\", \"POSITIONS:POS_READ_PROFICIENCY_2_CODE\": \"_language_2_reading_proficiency_code\", \"POSITIONS:POS_CREATE_ID\": \"_create_id\", \"POSITIONS:POS_CREATE_DATE\": parse_date(\"create_date\"), \"POSITIONS:POS_UPDATE_ID\":", "\"_language_req_2_code\", \"POSITIONS:POS_SPEAK_PROFICIENCY_1_CODE\": \"_language_1_spoken_proficiency_code\", \"POSITIONS:POS_READ_PROFICIENCY_1_CODE\": \"_language_1_reading_proficiency_code\", \"POSITIONS:POS_SPEAK_PROFICIENCY_2_CODE\": \"_language_2_spoken_proficiency_code\", \"POSITIONS:POS_READ_PROFICIENCY_2_CODE\": \"_language_2_reading_proficiency_code\", \"POSITIONS:POS_CREATE_ID\":", "\"_seq_num\", \"POSITIONS:POS_NUM_TEXT\": \"position_number\", \"POSITIONS:POS_TITLE_CODE\": \"_title_code\", \"POSITIONS:POS_TITLE_DESC\": \"title\", \"POSITIONS:POS_ORG_CODE\": \"_org_code\", \"POSITIONS:POS_BUREAU_CODE\":", "strip_extra_spaces(\"long_description\"), \"ORG_PARENT_ORG_CODE\": \"_parent_organization_code\", \"ORG_BUREAU_ORG_CODE\": \"_parent_bureau_code\", \"ORG_LOCATION_CODE\": \"_location_code\" } # Update", "= Proficiency instance_tag = \"LANGUAGE_PROFICIENCY:LANGUAGE_PROFICIENCY\" collision_field = \"code\" tag_map =", "self).__init__(*args, **kwargs) self.modes = { 'languages': mode_languages, 'proficiencies': mode_proficiencies, 'grades':", "instance_tag = \"LANGUAGES:LANGUAGE\" collision_field = \"code\" tag_map = { \"LANGUAGES:LANG_CODE\":", "\"POSITIONS:POS_LANGUAGE_2_CODE\": \"_language_2_code\", \"POSITIONS:POS_LOCATION_CODE\": \"_location_code\", \"POSITIONS:POS_LANG_REQ_1_CODE\": \"_language_req_1_code\", \"POSITIONS:POS_LANG_REQ_2_CODE\": \"_language_req_2_code\", \"POSITIONS:POS_SPEAK_PROFICIENCY_1_CODE\": \"_language_1_spoken_proficiency_code\",", "for loc in Post.objects.filter(id__in=new_ids + updated_ids): loc.update_relationships() return (model, instance_tag,", "from talentmap_api.common.xml_helpers import XMLloader, strip_extra_spaces, parse_boolean, parse_date, get_nested_tag from talentmap_api.language.models", "Skill instance_tag = \"SKILLS:SKILL\" collision_field = \"code\" tag_map = {", "updated_ids): org.update_relationships() # Regional code setting is done automatically by", "\"DATA_RECORD\" collision_field = \"code\" tag_map = { \"ORG_CODE\": \"code\", \"ORG_SHORT_DESC\":", "return (model, instance_tag, tag_map, collision_field, None) def mode_grades(): model =", "tag_map, collision_field, post_load_function) def mode_skills(): model = Skill instance_tag =", "Grade instance_tag = \"GRADES:GRADE\" collision_field = \"code\" tag_map = {", "} def post_load_function(new_ids, updated_ids): for loc in Post.objects.filter(id__in=new_ids + updated_ids):", "updated_ids): for org in Organization.objects.filter(id__in=new_ids + updated_ids): org.update_relationships() # Regional", "talentmap_api.common.xml_helpers import XMLloader, strip_extra_spaces, parse_boolean, parse_date, get_nested_tag from talentmap_api.language.models import", "mode_languages(): model = Language instance_tag = \"LANGUAGES:LANGUAGE\" collision_field = \"code\"", "in Position.objects.filter(id__in=new_ids + updated_ids): pos.update_relationships() return (model, instance_tag, tag_map, collision_field,", "Post, TourOfDuty, Location, Country class Command(BaseCommand): help = 'Loads an", "\"POSITIONS:POS_LANG_REQ_2_CODE\": \"_language_req_2_code\", \"POSITIONS:POS_SPEAK_PROFICIENCY_1_CODE\": \"_language_1_spoken_proficiency_code\", \"POSITIONS:POS_READ_PROFICIENCY_1_CODE\": \"_language_1_reading_proficiency_code\", \"POSITIONS:POS_SPEAK_PROFICIENCY_2_CODE\": \"_language_2_spoken_proficiency_code\", \"POSITIONS:POS_READ_PROFICIENCY_2_CODE\": \"_language_2_reading_proficiency_code\",", "\"TOUR_OF_DUTIES:TOD_CODE\": \"code\", \"TOUR_OF_DUTIES:TOD_SHORT_DESC\": \"short_description\", \"TOUR_OF_DUTIES:TOD_DESC_TEXT\": lambda instance, item: setattr(instance, \"long_description\",", "\"POSITIONS:POS_GRADE_CODE\": \"_grade_code\", \"POSITIONS:POS_POST_CODE\": \"_post_code\", \"POSITIONS:POS_LANGUAGE_1_CODE\": \"_language_1_code\", \"POSITIONS:POS_LANGUAGE_2_CODE\": \"_language_2_code\", \"POSITIONS:POS_LOCATION_CODE\": \"_location_code\",", "strip_extra_spaces(\"rest_relaxation_point\"), \"BIDPOSTS:BT_DANGER_PAY_NUM\": \"danger_pay\", \"BIDPOSTS:BT_CONSUMABLE_ALLOWANCE_FLG\": parse_boolean(\"has_consumable_allowance\"), \"BIDPOSTS:BT_SERVICE_NEEDS_DIFF_FLG\": parse_boolean(\"has_service_needs_differential\"), } def post_load_function(new_ids,", "\"ORG_BUREAU_ORG_CODE\": \"_parent_bureau_code\", \"ORG_LOCATION_CODE\": \"_location_code\" } # Update relationships def post_load_function(new_ids,", "= Position instance_tag = \"POSITIONS:POSITION\" collision_field = \"_seq_num\" tag_map =", "\"BIDPOSTS:BT_CONSUMABLE_ALLOWANCE_FLG\": parse_boolean(\"has_consumable_allowance\"), \"BIDPOSTS:BT_SERVICE_NEEDS_DIFF_FLG\": parse_boolean(\"has_service_needs_differential\"), } def post_load_function(new_ids, updated_ids): for loc", "\"name\", \"SHORT_NAME\": \"short_name\", \"COUNTRY_CODE_2\": \"short_code\", \"LOCATION_PREFIX\": \"location_prefix\" } return (model,", "post_load_function) def mode_tour_of_duty(): model = TourOfDuty instance_tag = \"TOUR_OF_DUTIES:TOUR_OF_DUTY\" collision_field", "\"code\" tag_map = { \"ORG_CODE\": \"code\", \"ORG_SHORT_DESC\": \"short_description\", \"ORG_LONG_DESC\": strip_extra_spaces(\"long_description\"),", "return (model, instance_tag, tag_map, collision_field, post_load_function) def mode_country(): model =", "None if options['delete']: collision_behavior = \"delete\" elif options['update']: collision_behavior =", "\"_tod_code\", \"BIDPOSTS:BT_COST_OF_LIVING_ADJUST_NUM\": \"cost_of_living_adjustment\", \"BIDPOSTS:BT_DIFFERENTIAL_RATE_NUM\": \"differential_rate\", \"BIDPOSTS:BT_REST_RELAXATION_POINT_TEXT\": strip_extra_spaces(\"rest_relaxation_point\"), \"BIDPOSTS:BT_DANGER_PAY_NUM\": \"danger_pay\", \"BIDPOSTS:BT_CONSUMABLE_ALLOWANCE_FLG\":", "return (model, instance_tag, tag_map, collision_field, None) def mode_proficiencies(): model =", "\"_pos_seq_num\" tag_map = { \"POS_SEQ_NUM\": \"_pos_seq_num\", \"capsuleDescription\": \"content\", } return", "\"POSITIONS:POS_SERVICE_TYPE_CODE\": \"_service_type_code\", \"POSITIONS:POS_GRADE_CODE\": \"_grade_code\", \"POSITIONS:POS_POST_CODE\": \"_post_code\", \"POSITIONS:POS_LANGUAGE_1_CODE\": \"_language_1_code\", \"POSITIONS:POS_LANGUAGE_2_CODE\": \"_language_2_code\",", "instance_tag = \"position\" collision_field = \"_pos_seq_num\" tag_map = { \"POS_SEQ_NUM\":", "logging.getLogger(__name__) def __init__(self, *args, **kwargs): super(Command, self).__init__(*args, **kwargs) self.modes =", "} def add_arguments(self, parser): parser.add_argument('file', nargs=1, type=str, help=\"The XML file", "model = Country instance_tag = \"DATA_RECORD\" collision_field = \"code\" tag_map", "talentmap_api.organization.models import Organization, Post, TourOfDuty, Location, Country class Command(BaseCommand): help", "now only need this logic when loading from our sample", "collision_field, None) def mode_location(): model = Location instance_tag = \"location\"", "options['update']: collision_behavior = \"update\" else: collision_behavior = \"skip\" loader =", "return (model, instance_tag, tag_map, collision_field, None) def mode_post(): model =", "import re from talentmap_api.common.xml_helpers import XMLloader, strip_extra_spaces, parse_boolean, parse_date, get_nested_tag", "XML\") parser.add_argument('--delete', dest='delete', action='store_true', help='Delete collisions') parser.add_argument('--update', dest='update', action='store_true', help='Update", "instance_tag, tag_map, collision_field, None) def mode_location(): model = Location instance_tag", "\"_id\", \"name\": strip_extra_spaces(\"name\"), \"skill\": get_nested_tag(\"_skill_codes\", \"code\"), } return (model, instance_tag,", "\"code\" } def post_load_function(new_ids, updated_ids): for pos in Grade.objects.filter(id__in=new_ids +", "tag_map, collision_field, post_load_function) def mode_positions(): model = Position instance_tag =", "\"_post_code\", \"POSITIONS:POS_LANGUAGE_1_CODE\": \"_language_1_code\", \"POSITIONS:POS_LANGUAGE_2_CODE\": \"_language_2_code\", \"POSITIONS:POS_LOCATION_CODE\": \"_location_code\", \"POSITIONS:POS_LANG_REQ_1_CODE\": \"_language_req_1_code\", \"POSITIONS:POS_LANG_REQ_2_CODE\":", "help='Update collisions') parser.add_argument('--skippost', dest='skip_post', action='store_true', help='Skip post load functions') def", "= \"location\" collision_field = \"code\" tag_map = { \"code\": \"code\",", "dest='delete', action='store_true', help='Delete collisions') parser.add_argument('--update', dest='update', action='store_true', help='Update collisions') parser.add_argument('--skippost',", "this logic when loading from our sample XML files #", "pos.update_relationships() return (model, instance_tag, tag_map, collision_field, post_load_function) def mode_tour_of_duty(): model", "action='store_true', help='Delete collisions') parser.add_argument('--update', dest='update', action='store_true', help='Update collisions') parser.add_argument('--skippost', dest='skip_post',", "for org in Organization.objects.filter(id__in=new_ids + updated_ids): org.update_relationships() # Regional code", "model = Location instance_tag = \"location\" collision_field = \"code\" tag_map", "tag_map, collision_field, None) def mode_organizations(): model = Organization instance_tag =", "\"POSITIONS:POS_LOCATION_CODE\": \"_location_code\", \"POSITIONS:POS_LANG_REQ_1_CODE\": \"_language_req_1_code\", \"POSITIONS:POS_LANG_REQ_2_CODE\": \"_language_req_2_code\", \"POSITIONS:POS_SPEAK_PROFICIENCY_1_CODE\": \"_language_1_spoken_proficiency_code\", \"POSITIONS:POS_READ_PROFICIENCY_1_CODE\": \"_language_1_reading_proficiency_code\",", "'grades': mode_grades, 'skills': mode_skills, 'organizations': mode_organizations, 'positions': mode_positions, 'tours_of_duty': mode_tour_of_duty,", "parse_date(\"effective_date\") } return (model, instance_tag, tag_map, collision_field, None) def mode_proficiencies():", "False if org.code == org._parent_bureau_code: org.is_bureau = True org.save() return", "\"BIDPOSTS:BIDDING_TOOL\" collision_field = \"_location_code\" tag_map = { \"BIDPOSTS:DSC_CD\": \"_location_code\", \"BIDPOSTS:TOD_CODE\":", "Update relationships def post_load_function(new_ids, updated_ids): for org in Organization.objects.filter(id__in=new_ids +", "Connect new locations to applicable posts for loc in Location.objects.filter(id__in=new_ids", "instance_tag, tag_map, collision_behavior, collision_field) new_ids, updated_ids = loader.create_models_from_xml(options['file'][0]) # Run", "setting is done automatically by DOS Webservices, so # we", "\"ORG_PARENT_ORG_CODE\": \"_parent_organization_code\", \"ORG_BUREAU_ORG_CODE\": \"_parent_bureau_code\", \"ORG_LOCATION_CODE\": \"_location_code\" } # Update relationships", "'positions': mode_positions, 'tours_of_duty': mode_tour_of_duty, 'posts': mode_post, 'countries': mode_country, 'locations': mode_location,", "(model, instance_tag, tag_map, collision_field, post_load_function) def mode_tour_of_duty(): model = TourOfDuty", "\"_country\" } def post_load_function(new_ids, updated_ids): # Connect new locations to", "def mode_capsule_description(): model = CapsuleDescription instance_tag = \"position\" collision_field =", "model = Grade instance_tag = \"GRADES:GRADE\" collision_field = \"code\" tag_map", "instance_tag, tag_map, collision_field, None) def mode_grades(): model = Grade instance_tag", "+ updated_ids): Post.objects.filter(_location_code=loc.code).update(location=loc) return (model, instance_tag, tag_map, collision_field, post_load_function) def", "elif options['update']: collision_behavior = \"update\" else: collision_behavior = \"skip\" loader", "so # we now only need this logic when loading", "\"_org_code\", \"POSITIONS:POS_BUREAU_CODE\": \"_bureau_code\", \"POSITIONS:POS_SKILL_CODE\": \"_skill_code\", \"POSITIONS:POS_STAFF_PTRN_SKILL_CODE\": \"_staff_ptrn_skill_code\", \"POSITIONS:POS_OVERSEAS_IND\": parse_boolean(\"is_overseas\", ['O']),", "CapsuleDescription instance_tag = \"position\" collision_field = \"_pos_seq_num\" tag_map = {", "= \"SKILLS:SKILL\" collision_field = \"code\" tag_map = { \"SKILLS:SKILL_CODE\": \"code\",", "\"short_code\", \"LOCATION_PREFIX\": \"location_prefix\" } return (model, instance_tag, tag_map, collision_field, None)", "/ update the collision behavior collision_behavior = None if options['delete']:", "\"_location_code\" tag_map = { \"BIDPOSTS:DSC_CD\": \"_location_code\", \"BIDPOSTS:TOD_CODE\": \"_tod_code\", \"BIDPOSTS:BT_COST_OF_LIVING_ADJUST_NUM\": \"cost_of_living_adjustment\",", "instance_tag = \"GRADES:GRADE\" collision_field = \"code\" tag_map = { \"GRADES:GRD_GRADE_CODE\":", "collision_behavior = None if options['delete']: collision_behavior = \"delete\" elif options['update']:", "org.is_regional = True else: org.is_regional = False if org.code ==", "tag_map, collision_behavior, collision_field) new_ids, updated_ids = loader.create_models_from_xml(options['file'][0]) # Run the", "= \"_pos_seq_num\" tag_map = { \"POS_SEQ_NUM\": \"_pos_seq_num\", \"capsuleDescription\": \"content\", }", "\"TOUR_OF_DUTIES:TOD_MONTHS_NUM\": \"months\" } return (model, instance_tag, tag_map, collision_field, None) def", "[ \"110000\", \"120000\", \"130000\", \"140000\", \"146000\", \"150000\", \"160000\" ] if", "help='Delete collisions') parser.add_argument('--update', dest='update', action='store_true', help='Update collisions') parser.add_argument('--skippost', dest='skip_post', action='store_true',", "= Skill instance_tag = \"SKILLS:SKILL\" collision_field = \"code\" tag_map =", "= Location instance_tag = \"location\" collision_field = \"code\" tag_map =", "\"long_description\", re.sub('&amp;', '&', item.text).strip()), \"TOUR_OF_DUTIES:TOD_MONTHS_NUM\": \"months\" } return (model, instance_tag,", "collision_behavior = \"update\" else: collision_behavior = \"skip\" loader = XMLloader(model,", "collision_field = \"_seq_num\" tag_map = { \"POSITIONS:POS_SEQ_NUM\": \"_seq_num\", \"POSITIONS:POS_NUM_TEXT\": \"position_number\",", "model = TourOfDuty instance_tag = \"TOUR_OF_DUTIES:TOUR_OF_DUTY\" collision_field = \"code\" tag_map", "updated_ids): for pos in Position.objects.filter(id__in=new_ids + updated_ids): pos.update_relationships() return (model,", "return (model, instance_tag, tag_map, collision_field, None) def mode_location(): model =", "def post_load_function(new_ids, updated_ids): for pos in Position.objects.filter(id__in=new_ids + updated_ids): pos.update_relationships()", "Report\\n\\tNew: {len(new_ids)}\\n\\tUpdated: {len(updated_ids)}\\t\\t\") def mode_languages(): model = Language instance_tag =", "\"FULL_NAME\": \"name\", \"SHORT_NAME\": \"short_name\", \"COUNTRY_CODE_2\": \"short_code\", \"LOCATION_PREFIX\": \"location_prefix\" } return", "the XML\") parser.add_argument('--delete', dest='delete', action='store_true', help='Delete collisions') parser.add_argument('--update', dest='update', action='store_true',", "if options['delete']: collision_behavior = \"delete\" elif options['update']: collision_behavior = \"update\"", "\"short_description\", \"ORG_LONG_DESC\": strip_extra_spaces(\"long_description\"), \"ORG_PARENT_ORG_CODE\": \"_parent_organization_code\", \"ORG_BUREAU_ORG_CODE\": \"_parent_bureau_code\", \"ORG_LOCATION_CODE\": \"_location_code\" }", "logging import re from talentmap_api.common.xml_helpers import XMLloader, strip_extra_spaces, parse_boolean, parse_date,", "Proficiency from talentmap_api.position.models import Grade, Skill, Position, CapsuleDescription, SkillCone from", "= None if options['delete']: collision_behavior = \"delete\" elif options['update']: collision_behavior", "Position instance_tag = \"POSITIONS:POSITION\" collision_field = \"_seq_num\" tag_map = {", "loader = XMLloader(model, instance_tag, tag_map, collision_behavior, collision_field) new_ids, updated_ids =", "action='store_true', help='Update collisions') parser.add_argument('--skippost', dest='skip_post', action='store_true', help='Skip post load functions')", "**kwargs): super(Command, self).__init__(*args, **kwargs) self.modes = { 'languages': mode_languages, 'proficiencies':", "= { 'languages': mode_languages, 'proficiencies': mode_proficiencies, 'grades': mode_grades, 'skills': mode_skills,", "collision_field, post_load_function) def mode_positions(): model = Position instance_tag = \"POSITIONS:POSITION\"", "\"name\": strip_extra_spaces(\"name\"), \"skill\": get_nested_tag(\"_skill_codes\", \"code\"), } return (model, instance_tag, tag_map,", "updated_ids): for pos in Grade.objects.filter(id__in=new_ids + updated_ids): pos.update_relationships() return (model,", "\"danger_pay\", \"BIDPOSTS:BT_CONSUMABLE_ALLOWANCE_FLG\": parse_boolean(\"has_consumable_allowance\"), \"BIDPOSTS:BT_SERVICE_NEEDS_DIFF_FLG\": parse_boolean(\"has_service_needs_differential\"), } def post_load_function(new_ids, updated_ids): for", "tag_map = { \"LANGUAGE_PROFICIENCY:LP_CODE\": \"code\", \"LANGUAGE_PROFICIENCY:LP_DESC\": \"description\" } return (model,", "{ 'languages': mode_languages, 'proficiencies': mode_proficiencies, 'grades': mode_grades, 'skills': mode_skills, 'organizations':", "= [ \"110000\", \"120000\", \"130000\", \"140000\", \"146000\", \"150000\", \"160000\" ]", "loc in Location.objects.filter(id__in=new_ids + updated_ids): Post.objects.filter(_location_code=loc.code).update(location=loc) return (model, instance_tag, tag_map,", "Grade, Skill, Position, CapsuleDescription, SkillCone from talentmap_api.organization.models import Organization, Post,", "= True else: org.is_regional = False if org.code == org._parent_bureau_code:", "def mode_country(): model = Country instance_tag = \"DATA_RECORD\" collision_field =", "*args, **options): model, instance_tag, tag_map, collision_field, post_load_function = self.modes[options['type'][0]]() #", "\"code\" tag_map = { \"SKILLS:SKILL_CODE\": \"code\", \"SKILLS:SKILL_DESCRIPTION\": \"description\" } return", "\"POSITIONS:POS_STAFF_PTRN_SKILL_CODE\": \"_staff_ptrn_skill_code\", \"POSITIONS:POS_OVERSEAS_IND\": parse_boolean(\"is_overseas\", ['O']), \"POSITIONS:POS_PAY_PLAN_CODE\": \"_pay_plan_code\", \"POSITIONS:POS_STATUS_CODE\": \"_status_code\", \"POSITIONS:POS_SERVICE_TYPE_CODE\":", "\"short_description\", \"LANGUAGES:LANG_EFFECTIVE_DATE\": parse_date(\"effective_date\") } return (model, instance_tag, tag_map, collision_field, None)", "import BaseCommand import logging import re from talentmap_api.common.xml_helpers import XMLloader,", "'skills': mode_skills, 'organizations': mode_organizations, 'positions': mode_positions, 'tours_of_duty': mode_tour_of_duty, 'posts': mode_post,", "\"state\": strip_extra_spaces(\"state\"), \"country\": \"_country\" } def post_load_function(new_ids, updated_ids): # Connect", "collision_field, None) def mode_skill_cone(): model = SkillCone instance_tag = \"jobCategorySkill\"", "'skill_cone': mode_skill_cone } def add_arguments(self, parser): parser.add_argument('file', nargs=1, type=str, help=\"The", "parser.add_argument('type', nargs=1, type=str, choices=self.modes.keys(), help=\"The type of data in the", "= Grade instance_tag = \"GRADES:GRADE\" collision_field = \"code\" tag_map =", "tag_map = { \"LANGUAGES:LANG_CODE\": \"code\", \"LANGUAGES:LANG_LONG_DESC\": \"long_description\", \"LANGUAGES:LANG_SHORT_DESC\": \"short_description\", \"LANGUAGES:LANG_EFFECTIVE_DATE\":", "tag_map = { \"BIDPOSTS:DSC_CD\": \"_location_code\", \"BIDPOSTS:TOD_CODE\": \"_tod_code\", \"BIDPOSTS:BT_COST_OF_LIVING_ADJUST_NUM\": \"cost_of_living_adjustment\", \"BIDPOSTS:BT_DIFFERENTIAL_RATE_NUM\":", "mode_proficiencies, 'grades': mode_grades, 'skills': mode_skills, 'organizations': mode_organizations, 'positions': mode_positions, 'tours_of_duty':", "\"POSITIONS:POS_READ_PROFICIENCY_1_CODE\": \"_language_1_reading_proficiency_code\", \"POSITIONS:POS_SPEAK_PROFICIENCY_2_CODE\": \"_language_2_spoken_proficiency_code\", \"POSITIONS:POS_READ_PROFICIENCY_2_CODE\": \"_language_2_reading_proficiency_code\", \"POSITIONS:POS_CREATE_ID\": \"_create_id\", \"POSITIONS:POS_CREATE_DATE\": parse_date(\"create_date\"),", "tag_map = { \"GRADES:GRD_GRADE_CODE\": \"code\" } def post_load_function(new_ids, updated_ids): for", "updated_ids): loc.update_relationships() return (model, instance_tag, tag_map, collision_field, post_load_function) def mode_country():", "self.modes = { 'languages': mode_languages, 'proficiencies': mode_proficiencies, 'grades': mode_grades, 'skills':", "in Organization.objects.filter(id__in=new_ids + updated_ids): org.update_relationships() # Regional code setting is", "collision_field, post_load_function) def mode_country(): model = Country instance_tag = \"DATA_RECORD\"", "\"city\": strip_extra_spaces(\"city\"), \"state\": strip_extra_spaces(\"state\"), \"country\": \"_country\" } def post_load_function(new_ids, updated_ids):", "def mode_organizations(): model = Organization instance_tag = \"DATA_RECORD\" collision_field =", "\"POSITIONS:POS_READ_PROFICIENCY_2_CODE\": \"_language_2_reading_proficiency_code\", \"POSITIONS:POS_CREATE_ID\": \"_create_id\", \"POSITIONS:POS_CREATE_DATE\": parse_date(\"create_date\"), \"POSITIONS:POS_UPDATE_ID\": \"_update_id\", \"POSITIONS:POS_UPDATE_DATE\": parse_date(\"update_date\"),", "Post.objects.filter(_location_code=loc.code).update(location=loc) return (model, instance_tag, tag_map, collision_field, post_load_function) def mode_capsule_description(): model", "mode_grades, 'skills': mode_skills, 'organizations': mode_organizations, 'positions': mode_positions, 'tours_of_duty': mode_tour_of_duty, 'posts':", "= \"position\" collision_field = \"_pos_seq_num\" tag_map = { \"POS_SEQ_NUM\": \"_pos_seq_num\",", "= { \"code\": \"code\", \"city\": strip_extra_spaces(\"city\"), \"state\": strip_extra_spaces(\"state\"), \"country\": \"_country\"", "\"TOUR_OF_DUTIES:TOUR_OF_DUTY\" collision_field = \"code\" tag_map = { \"TOUR_OF_DUTIES:TOD_CODE\": \"code\", \"TOUR_OF_DUTIES:TOD_SHORT_DESC\":", "{ \"GRADES:GRD_GRADE_CODE\": \"code\" } def post_load_function(new_ids, updated_ids): for pos in", "\"_grade_code\", \"POSITIONS:POS_POST_CODE\": \"_post_code\", \"POSITIONS:POS_LANGUAGE_1_CODE\": \"_language_1_code\", \"POSITIONS:POS_LANGUAGE_2_CODE\": \"_language_2_code\", \"POSITIONS:POS_LOCATION_CODE\": \"_location_code\", \"POSITIONS:POS_LANG_REQ_1_CODE\":", "= \"code\" tag_map = { \"GRADES:GRD_GRADE_CODE\": \"code\" } def post_load_function(new_ids,", "\"POSITIONS:POS_OVERSEAS_IND\": parse_boolean(\"is_overseas\", ['O']), \"POSITIONS:POS_PAY_PLAN_CODE\": \"_pay_plan_code\", \"POSITIONS:POS_STATUS_CODE\": \"_status_code\", \"POSITIONS:POS_SERVICE_TYPE_CODE\": \"_service_type_code\", \"POSITIONS:POS_GRADE_CODE\":", "tag_map, collision_field, None) def mode_skill_cone(): model = SkillCone instance_tag =", "locations to applicable posts for loc in Location.objects.filter(id__in=new_ids + updated_ids):", "['O']), \"POSITIONS:POS_PAY_PLAN_CODE\": \"_pay_plan_code\", \"POSITIONS:POS_STATUS_CODE\": \"_status_code\", \"POSITIONS:POS_SERVICE_TYPE_CODE\": \"_service_type_code\", \"POSITIONS:POS_GRADE_CODE\": \"_grade_code\", \"POSITIONS:POS_POST_CODE\":", "dest='update', action='store_true', help='Update collisions') parser.add_argument('--skippost', dest='skip_post', action='store_true', help='Skip post load", "collision_field) new_ids, updated_ids = loader.create_models_from_xml(options['file'][0]) # Run the post load", "Webservices, so # we now only need this logic when", "\"_jobcode_code\", \"POSITIONS:POS_OCC_SERIES_CODE\": \"_occ_series_code\", } def post_load_function(new_ids, updated_ids): for pos in", "type of data in the XML\") parser.add_argument('--delete', dest='delete', action='store_true', help='Delete", "data in the XML\") parser.add_argument('--delete', dest='delete', action='store_true', help='Delete collisions') parser.add_argument('--update',", "strip_extra_spaces, parse_boolean, parse_date, get_nested_tag from talentmap_api.language.models import Language, Proficiency from", "\"GRADES:GRADE\" collision_field = \"code\" tag_map = { \"GRADES:GRD_GRADE_CODE\": \"code\" }", "mode_skills(): model = Skill instance_tag = \"SKILLS:SKILL\" collision_field = \"code\"", "collision_field, post_load_function) def mode_skills(): model = Skill instance_tag = \"SKILLS:SKILL\"", "load\") parser.add_argument('type', nargs=1, type=str, choices=self.modes.keys(), help=\"The type of data in", "{ \"BIDPOSTS:DSC_CD\": \"_location_code\", \"BIDPOSTS:TOD_CODE\": \"_tod_code\", \"BIDPOSTS:BT_COST_OF_LIVING_ADJUST_NUM\": \"cost_of_living_adjustment\", \"BIDPOSTS:BT_DIFFERENTIAL_RATE_NUM\": \"differential_rate\", \"BIDPOSTS:BT_REST_RELAXATION_POINT_TEXT\":", "collision_field = \"code\" tag_map = { \"code\": \"code\", \"city\": strip_extra_spaces(\"city\"),", "strip_extra_spaces(\"city\"), \"state\": strip_extra_spaces(\"state\"), \"country\": \"_country\" } def post_load_function(new_ids, updated_ids): #", "\"code\", \"FULL_NAME\": \"name\", \"SHORT_NAME\": \"short_name\", \"COUNTRY_CODE_2\": \"short_code\", \"LOCATION_PREFIX\": \"location_prefix\" }", "= XMLloader(model, instance_tag, tag_map, collision_behavior, collision_field) new_ids, updated_ids = loader.create_models_from_xml(options['file'][0])", "instance_tag = \"LANGUAGE_PROFICIENCY:LANGUAGE_PROFICIENCY\" collision_field = \"code\" tag_map = { \"LANGUAGE_PROFICIENCY:LP_CODE\":", "for pos in Position.objects.filter(id__in=new_ids + updated_ids): pos.update_relationships() return (model, instance_tag,", "callable(post_load_function) and not options['skip_post']: post_load_function(new_ids, updated_ids) self.logger.info(f\"XML Load Report\\n\\tNew: {len(new_ids)}\\n\\tUpdated:", "def mode_proficiencies(): model = Proficiency instance_tag = \"LANGUAGE_PROFICIENCY:LANGUAGE_PROFICIENCY\" collision_field =", "tag_map = { \"code\": \"code\", \"city\": strip_extra_spaces(\"city\"), \"state\": strip_extra_spaces(\"state\"), \"country\":", "= \"code\" tag_map = { \"SKILLS:SKILL_CODE\": \"code\", \"SKILLS:SKILL_DESCRIPTION\": \"description\" }", "(model, instance_tag, tag_map, collision_field, post_load_function) def mode_positions(): model = Position", "post_load_function(new_ids, updated_ids): for org in Organization.objects.filter(id__in=new_ids + updated_ids): org.update_relationships() #", "\"code\" tag_map = { \"LANGUAGES:LANG_CODE\": \"code\", \"LANGUAGES:LANG_LONG_DESC\": \"long_description\", \"LANGUAGES:LANG_SHORT_DESC\": \"short_description\",", "def mode_languages(): model = Language instance_tag = \"LANGUAGES:LANGUAGE\" collision_field =", "import Organization, Post, TourOfDuty, Location, Country class Command(BaseCommand): help =", "= \"skip\" loader = XMLloader(model, instance_tag, tag_map, collision_behavior, collision_field) new_ids,", "(model, instance_tag, tag_map, collision_field, None) def mode_proficiencies(): model = Proficiency", "} return (model, instance_tag, tag_map, collision_field, None) def mode_organizations(): model", "exists if callable(post_load_function) and not options['skip_post']: post_load_function(new_ids, updated_ids) self.logger.info(f\"XML Load", "\"ORG_LOCATION_CODE\": \"_location_code\" } # Update relationships def post_load_function(new_ids, updated_ids): for", "\"_language_2_spoken_proficiency_code\", \"POSITIONS:POS_READ_PROFICIENCY_2_CODE\": \"_language_2_reading_proficiency_code\", \"POSITIONS:POS_CREATE_ID\": \"_create_id\", \"POSITIONS:POS_CREATE_DATE\": parse_date(\"create_date\"), \"POSITIONS:POS_UPDATE_ID\": \"_update_id\", \"POSITIONS:POS_UPDATE_DATE\":", "the collision behavior collision_behavior = None if options['delete']: collision_behavior =", "TourOfDuty instance_tag = \"TOUR_OF_DUTIES:TOUR_OF_DUTY\" collision_field = \"code\" tag_map = {", "\"BIDPOSTS:BT_DANGER_PAY_NUM\": \"danger_pay\", \"BIDPOSTS:BT_CONSUMABLE_ALLOWANCE_FLG\": parse_boolean(\"has_consumable_allowance\"), \"BIDPOSTS:BT_SERVICE_NEEDS_DIFF_FLG\": parse_boolean(\"has_service_needs_differential\"), } def post_load_function(new_ids, updated_ids):", "\"POSITIONS:POS_POST_CODE\": \"_post_code\", \"POSITIONS:POS_LANGUAGE_1_CODE\": \"_language_1_code\", \"POSITIONS:POS_LANGUAGE_2_CODE\": \"_language_2_code\", \"POSITIONS:POS_LOCATION_CODE\": \"_location_code\", \"POSITIONS:POS_LANG_REQ_1_CODE\": \"_language_req_1_code\",", "'locations': mode_location, 'capsule_descriptions': mode_capsule_description, 'skill_cone': mode_skill_cone } def add_arguments(self, parser):", "'Loads an XML into a supported file' logger = logging.getLogger(__name__)", "updated_ids): for loc in Post.objects.filter(id__in=new_ids + updated_ids): loc.update_relationships() return (model,", "parse_date(\"effective_date\"), \"POSITIONS:POS_JOBCODE_CODE\": \"_jobcode_code\", \"POSITIONS:POS_OCC_SERIES_CODE\": \"_occ_series_code\", } def post_load_function(new_ids, updated_ids): for", "= \"TOUR_OF_DUTIES:TOUR_OF_DUTY\" collision_field = \"code\" tag_map = { \"TOUR_OF_DUTIES:TOD_CODE\": \"code\",", "instance_tag, tag_map, collision_field, None) def mode_skill_cone(): model = SkillCone instance_tag", "updated_ids = loader.create_models_from_xml(options['file'][0]) # Run the post load function, if", "\"POSITIONS:POS_CREATE_ID\": \"_create_id\", \"POSITIONS:POS_CREATE_DATE\": parse_date(\"create_date\"), \"POSITIONS:POS_UPDATE_ID\": \"_update_id\", \"POSITIONS:POS_UPDATE_DATE\": parse_date(\"update_date\"), \"POSITIONS:POS_EFFECTIVE_DATE\": parse_date(\"effective_date\"),", "collision_field = \"code\" tag_map = { \"COUNTRY_CODE\": \"code\", \"FULL_NAME\": \"name\",", "post load functions') def handle(self, *args, **options): model, instance_tag, tag_map,", "{ \"COUNTRY_CODE\": \"code\", \"FULL_NAME\": \"name\", \"SHORT_NAME\": \"short_name\", \"COUNTRY_CODE_2\": \"short_code\", \"LOCATION_PREFIX\":", "= { \"GRADES:GRD_GRADE_CODE\": \"code\" } def post_load_function(new_ids, updated_ids): for pos", "for pos in Grade.objects.filter(id__in=new_ids + updated_ids): pos.update_relationships() return (model, instance_tag,", "def mode_skills(): model = Skill instance_tag = \"SKILLS:SKILL\" collision_field =", "\"code\": \"code\", \"city\": strip_extra_spaces(\"city\"), \"state\": strip_extra_spaces(\"state\"), \"country\": \"_country\" } def", "\"POSITIONS:POS_UPDATE_DATE\": parse_date(\"update_date\"), \"POSITIONS:POS_EFFECTIVE_DATE\": parse_date(\"effective_date\"), \"POSITIONS:POS_JOBCODE_CODE\": \"_jobcode_code\", \"POSITIONS:POS_OCC_SERIES_CODE\": \"_occ_series_code\", } def", "in Post.objects.filter(id__in=new_ids + updated_ids): loc.update_relationships() return (model, instance_tag, tag_map, collision_field,", "function, if it exists if callable(post_load_function) and not options['skip_post']: post_load_function(new_ids,", "\"position\" collision_field = \"_pos_seq_num\" tag_map = { \"POS_SEQ_NUM\": \"_pos_seq_num\", \"capsuleDescription\":", "from talentmap_api.organization.models import Organization, Post, TourOfDuty, Location, Country class Command(BaseCommand):", "file to load\") parser.add_argument('type', nargs=1, type=str, choices=self.modes.keys(), help=\"The type of", "in regional_codes: org.is_regional = True else: org.is_regional = False if", "org.is_regional = False if org.code == org._parent_bureau_code: org.is_bureau = True", "} return (model, instance_tag, tag_map, collision_field, None) def mode_grades(): model", "regional codes regional_codes = [ \"110000\", \"120000\", \"130000\", \"140000\", \"146000\",", "of regional codes regional_codes = [ \"110000\", \"120000\", \"130000\", \"140000\",", "\"SHORT_NAME\": \"short_name\", \"COUNTRY_CODE_2\": \"short_code\", \"LOCATION_PREFIX\": \"location_prefix\" } return (model, instance_tag,", "\"BIDPOSTS:BT_DIFFERENTIAL_RATE_NUM\": \"differential_rate\", \"BIDPOSTS:BT_REST_RELAXATION_POINT_TEXT\": strip_extra_spaces(\"rest_relaxation_point\"), \"BIDPOSTS:BT_DANGER_PAY_NUM\": \"danger_pay\", \"BIDPOSTS:BT_CONSUMABLE_ALLOWANCE_FLG\": parse_boolean(\"has_consumable_allowance\"), \"BIDPOSTS:BT_SERVICE_NEEDS_DIFF_FLG\": parse_boolean(\"has_service_needs_differential\"),", "updated_ids): # Connect new locations to applicable posts for loc", "\"_create_id\", \"POSITIONS:POS_CREATE_DATE\": parse_date(\"create_date\"), \"POSITIONS:POS_UPDATE_ID\": \"_update_id\", \"POSITIONS:POS_UPDATE_DATE\": parse_date(\"update_date\"), \"POSITIONS:POS_EFFECTIVE_DATE\": parse_date(\"effective_date\"), \"POSITIONS:POS_JOBCODE_CODE\":", "= 'Loads an XML into a supported file' logger =", "dest='skip_post', action='store_true', help='Skip post load functions') def handle(self, *args, **options):", "TourOfDuty, Location, Country class Command(BaseCommand): help = 'Loads an XML", "= \"_seq_num\" tag_map = { \"POSITIONS:POS_SEQ_NUM\": \"_seq_num\", \"POSITIONS:POS_NUM_TEXT\": \"position_number\", \"POSITIONS:POS_TITLE_CODE\":", "done automatically by DOS Webservices, so # we now only", "model = Language instance_tag = \"LANGUAGES:LANGUAGE\" collision_field = \"code\" tag_map", "django.core.management.base import BaseCommand import logging import re from talentmap_api.common.xml_helpers import", "load functions') def handle(self, *args, **options): model, instance_tag, tag_map, collision_field,", "tag_map, collision_field, post_load_function) def mode_capsule_description(): model = CapsuleDescription instance_tag =", "collision_field, None) def mode_proficiencies(): model = Proficiency instance_tag = \"LANGUAGE_PROFICIENCY:LANGUAGE_PROFICIENCY\"", "= \"BIDPOSTS:BIDDING_TOOL\" collision_field = \"_location_code\" tag_map = { \"BIDPOSTS:DSC_CD\": \"_location_code\",", "'posts': mode_post, 'countries': mode_country, 'locations': mode_location, 'capsule_descriptions': mode_capsule_description, 'skill_cone': mode_skill_cone", "\"POSITIONS:POS_UPDATE_ID\": \"_update_id\", \"POSITIONS:POS_UPDATE_DATE\": parse_date(\"update_date\"), \"POSITIONS:POS_EFFECTIVE_DATE\": parse_date(\"effective_date\"), \"POSITIONS:POS_JOBCODE_CODE\": \"_jobcode_code\", \"POSITIONS:POS_OCC_SERIES_CODE\": \"_occ_series_code\",", "\"cost_of_living_adjustment\", \"BIDPOSTS:BT_DIFFERENTIAL_RATE_NUM\": \"differential_rate\", \"BIDPOSTS:BT_REST_RELAXATION_POINT_TEXT\": strip_extra_spaces(\"rest_relaxation_point\"), \"BIDPOSTS:BT_DANGER_PAY_NUM\": \"danger_pay\", \"BIDPOSTS:BT_CONSUMABLE_ALLOWANCE_FLG\": parse_boolean(\"has_consumable_allowance\"), \"BIDPOSTS:BT_SERVICE_NEEDS_DIFF_FLG\":", "'languages': mode_languages, 'proficiencies': mode_proficiencies, 'grades': mode_grades, 'skills': mode_skills, 'organizations': mode_organizations,", "\"POSITIONS:POS_BUREAU_CODE\": \"_bureau_code\", \"POSITIONS:POS_SKILL_CODE\": \"_skill_code\", \"POSITIONS:POS_STAFF_PTRN_SKILL_CODE\": \"_staff_ptrn_skill_code\", \"POSITIONS:POS_OVERSEAS_IND\": parse_boolean(\"is_overseas\", ['O']), \"POSITIONS:POS_PAY_PLAN_CODE\":", "(model, instance_tag, tag_map, collision_field, None) def mode_location(): model = Location", "\"skill\": get_nested_tag(\"_skill_codes\", \"code\"), } return (model, instance_tag, tag_map, collision_field, None)", "} return (model, instance_tag, tag_map, collision_field, None) def mode_location(): model", "self.logger.info(f\"XML Load Report\\n\\tNew: {len(new_ids)}\\n\\tUpdated: {len(updated_ids)}\\t\\t\") def mode_languages(): model = Language", "re from talentmap_api.common.xml_helpers import XMLloader, strip_extra_spaces, parse_boolean, parse_date, get_nested_tag from", "collision_field = \"code\" tag_map = { \"ORG_CODE\": \"code\", \"ORG_SHORT_DESC\": \"short_description\",", "return (model, instance_tag, tag_map, collision_field, None) def mode_organizations(): model =", "collision_field = \"code\" tag_map = { \"TOUR_OF_DUTIES:TOD_CODE\": \"code\", \"TOUR_OF_DUTIES:TOD_SHORT_DESC\": \"short_description\",", "\"code\" tag_map = { \"LANGUAGE_PROFICIENCY:LP_CODE\": \"code\", \"LANGUAGE_PROFICIENCY:LP_DESC\": \"description\" } return", "\"capsuleDescription\": \"content\", } return (model, instance_tag, tag_map, collision_field, None) def", "regional_codes = [ \"110000\", \"120000\", \"130000\", \"140000\", \"146000\", \"150000\", \"160000\"", "need this logic when loading from our sample XML files", "'organizations': mode_organizations, 'positions': mode_positions, 'tours_of_duty': mode_tour_of_duty, 'posts': mode_post, 'countries': mode_country,", "\"SKILLS:SKILL_CODE\": \"code\", \"SKILLS:SKILL_DESCRIPTION\": \"description\" } return (model, instance_tag, tag_map, collision_field,", "return (model, instance_tag, tag_map, collision_field, post_load_function) def mode_capsule_description(): model =", "= \"DATA_RECORD\" collision_field = \"code\" tag_map = { \"COUNTRY_CODE\": \"code\",", "mode_organizations, 'positions': mode_positions, 'tours_of_duty': mode_tour_of_duty, 'posts': mode_post, 'countries': mode_country, 'locations':", "else: org.is_regional = False if org.code == org._parent_bureau_code: org.is_bureau =", "\"POSITIONS:POS_EFFECTIVE_DATE\": parse_date(\"effective_date\"), \"POSITIONS:POS_JOBCODE_CODE\": \"_jobcode_code\", \"POSITIONS:POS_OCC_SERIES_CODE\": \"_occ_series_code\", } def post_load_function(new_ids, updated_ids):", "org.save() return (model, instance_tag, tag_map, collision_field, post_load_function) def mode_positions(): model", "\"TOUR_OF_DUTIES:TOD_SHORT_DESC\": \"short_description\", \"TOUR_OF_DUTIES:TOD_DESC_TEXT\": lambda instance, item: setattr(instance, \"long_description\", re.sub('&amp;', '&',", "\"POSITIONS:POS_OCC_SERIES_CODE\": \"_occ_series_code\", } def post_load_function(new_ids, updated_ids): for pos in Position.objects.filter(id__in=new_ids", "Command(BaseCommand): help = 'Loads an XML into a supported file'", "mode_organizations(): model = Organization instance_tag = \"DATA_RECORD\" collision_field = \"code\"", "\"POS_SEQ_NUM\": \"_pos_seq_num\", \"capsuleDescription\": \"content\", } return (model, instance_tag, tag_map, collision_field,", "{len(new_ids)}\\n\\tUpdated: {len(updated_ids)}\\t\\t\") def mode_languages(): model = Language instance_tag = \"LANGUAGES:LANGUAGE\"", "def mode_location(): model = Location instance_tag = \"location\" collision_field =", "collision_field = None tag_map = { \"id\": \"_id\", \"name\": strip_extra_spaces(\"name\"),", "to load\") parser.add_argument('type', nargs=1, type=str, choices=self.modes.keys(), help=\"The type of data", "help = 'Loads an XML into a supported file' logger", "tag_map = { \"POSITIONS:POS_SEQ_NUM\": \"_seq_num\", \"POSITIONS:POS_NUM_TEXT\": \"position_number\", \"POSITIONS:POS_TITLE_CODE\": \"_title_code\", \"POSITIONS:POS_TITLE_DESC\":", "super(Command, self).__init__(*args, **kwargs) self.modes = { 'languages': mode_languages, 'proficiencies': mode_proficiencies,", "= { \"COUNTRY_CODE\": \"code\", \"FULL_NAME\": \"name\", \"SHORT_NAME\": \"short_name\", \"COUNTRY_CODE_2\": \"short_code\",", "= \"code\" tag_map = { \"code\": \"code\", \"city\": strip_extra_spaces(\"city\"), \"state\":", "post_load_function(new_ids, updated_ids) self.logger.info(f\"XML Load Report\\n\\tNew: {len(new_ids)}\\n\\tUpdated: {len(updated_ids)}\\t\\t\") def mode_languages(): model", "= SkillCone instance_tag = \"jobCategorySkill\" collision_field = None tag_map =", "help=\"The type of data in the XML\") parser.add_argument('--delete', dest='delete', action='store_true',", "mode_country, 'locations': mode_location, 'capsule_descriptions': mode_capsule_description, 'skill_cone': mode_skill_cone } def add_arguments(self,", "collision behavior collision_behavior = None if options['delete']: collision_behavior = \"delete\"", "add_arguments(self, parser): parser.add_argument('file', nargs=1, type=str, help=\"The XML file to load\")", "# we now only need this logic when loading from", "nargs=1, type=str, help=\"The XML file to load\") parser.add_argument('type', nargs=1, type=str,", "if org.code in regional_codes: org.is_regional = True else: org.is_regional =", "mode_tour_of_duty(): model = TourOfDuty instance_tag = \"TOUR_OF_DUTIES:TOUR_OF_DUTY\" collision_field = \"code\"", "def post_load_function(new_ids, updated_ids): for pos in Grade.objects.filter(id__in=new_ids + updated_ids): pos.update_relationships()", "updated_ids): pos.update_relationships() return (model, instance_tag, tag_map, collision_field, post_load_function) def mode_tour_of_duty():", "\"long_description\", \"LANGUAGES:LANG_SHORT_DESC\": \"short_description\", \"LANGUAGES:LANG_EFFECTIVE_DATE\": parse_date(\"effective_date\") } return (model, instance_tag, tag_map,", "strip_extra_spaces(\"name\"), \"skill\": get_nested_tag(\"_skill_codes\", \"code\"), } return (model, instance_tag, tag_map, collision_field,", "} def post_load_function(new_ids, updated_ids): for pos in Position.objects.filter(id__in=new_ids + updated_ids):", "DOS Webservices, so # we now only need this logic", "\"id\": \"_id\", \"name\": strip_extra_spaces(\"name\"), \"skill\": get_nested_tag(\"_skill_codes\", \"code\"), } return (model,", "__init__(self, *args, **kwargs): super(Command, self).__init__(*args, **kwargs) self.modes = { 'languages':", "tag_map, collision_field, None) def mode_location(): model = Location instance_tag =", "loader.create_models_from_xml(options['file'][0]) # Run the post load function, if it exists", "lambda instance, item: setattr(instance, \"long_description\", re.sub('&amp;', '&', item.text).strip()), \"TOUR_OF_DUTIES:TOD_MONTHS_NUM\": \"months\"", "XML files # Array of regional codes regional_codes = [", "tag_map, collision_field, post_load_function = self.modes[options['type'][0]]() # Set / update the", "instance_tag = \"location\" collision_field = \"code\" tag_map = { \"code\":", "# Update relationships def post_load_function(new_ids, updated_ids): for org in Organization.objects.filter(id__in=new_ids", "model = Organization instance_tag = \"DATA_RECORD\" collision_field = \"code\" tag_map", "Load Report\\n\\tNew: {len(new_ids)}\\n\\tUpdated: {len(updated_ids)}\\t\\t\") def mode_languages(): model = Language instance_tag", "Set / update the collision behavior collision_behavior = None if", "Post instance_tag = \"BIDPOSTS:BIDDING_TOOL\" collision_field = \"_location_code\" tag_map = {", "instance_tag = \"DATA_RECORD\" collision_field = \"code\" tag_map = { \"ORG_CODE\":", "XMLloader, strip_extra_spaces, parse_boolean, parse_date, get_nested_tag from talentmap_api.language.models import Language, Proficiency", "instance_tag, tag_map, collision_field, None) def mode_post(): model = Post instance_tag", "\"_location_code\" } # Update relationships def post_load_function(new_ids, updated_ids): for org", "files # Array of regional codes regional_codes = [ \"110000\",", "\"_status_code\", \"POSITIONS:POS_SERVICE_TYPE_CODE\": \"_service_type_code\", \"POSITIONS:POS_GRADE_CODE\": \"_grade_code\", \"POSITIONS:POS_POST_CODE\": \"_post_code\", \"POSITIONS:POS_LANGUAGE_1_CODE\": \"_language_1_code\", \"POSITIONS:POS_LANGUAGE_2_CODE\":", "parse_boolean(\"has_consumable_allowance\"), \"BIDPOSTS:BT_SERVICE_NEEDS_DIFF_FLG\": parse_boolean(\"has_service_needs_differential\"), } def post_load_function(new_ids, updated_ids): for loc in", "mode_grades(): model = Grade instance_tag = \"GRADES:GRADE\" collision_field = \"code\"", "Organization instance_tag = \"DATA_RECORD\" collision_field = \"code\" tag_map = {", "instance_tag, tag_map, collision_field, None) def mode_organizations(): model = Organization instance_tag", "collision_behavior = \"skip\" loader = XMLloader(model, instance_tag, tag_map, collision_behavior, collision_field)", "post_load_function) def mode_capsule_description(): model = CapsuleDescription instance_tag = \"position\" collision_field", "} def post_load_function(new_ids, updated_ids): for pos in Grade.objects.filter(id__in=new_ids + updated_ids):", "instance_tag, tag_map, collision_field, post_load_function = self.modes[options['type'][0]]() # Set / update", "= self.modes[options['type'][0]]() # Set / update the collision behavior collision_behavior", "\"POSITIONS:POSITION\" collision_field = \"_seq_num\" tag_map = { \"POSITIONS:POS_SEQ_NUM\": \"_seq_num\", \"POSITIONS:POS_NUM_TEXT\":", "org in Organization.objects.filter(id__in=new_ids + updated_ids): org.update_relationships() # Regional code setting", "tag_map, collision_field, None) def mode_proficiencies(): model = Proficiency instance_tag =", "\"_seq_num\" tag_map = { \"POSITIONS:POS_SEQ_NUM\": \"_seq_num\", \"POSITIONS:POS_NUM_TEXT\": \"position_number\", \"POSITIONS:POS_TITLE_CODE\": \"_title_code\",", "if org.code == org._parent_bureau_code: org.is_bureau = True org.save() return (model,", "automatically by DOS Webservices, so # we now only need", "model, instance_tag, tag_map, collision_field, post_load_function = self.modes[options['type'][0]]() # Set /", "collision_field = \"code\" tag_map = { \"GRADES:GRD_GRADE_CODE\": \"code\" } def", "= { \"POS_SEQ_NUM\": \"_pos_seq_num\", \"capsuleDescription\": \"content\", } return (model, instance_tag,", "SkillCone instance_tag = \"jobCategorySkill\" collision_field = None tag_map = {", "SkillCone from talentmap_api.organization.models import Organization, Post, TourOfDuty, Location, Country class", "\"BIDPOSTS:DSC_CD\": \"_location_code\", \"BIDPOSTS:TOD_CODE\": \"_tod_code\", \"BIDPOSTS:BT_COST_OF_LIVING_ADJUST_NUM\": \"cost_of_living_adjustment\", \"BIDPOSTS:BT_DIFFERENTIAL_RATE_NUM\": \"differential_rate\", \"BIDPOSTS:BT_REST_RELAXATION_POINT_TEXT\": strip_extra_spaces(\"rest_relaxation_point\"),", "\"skip\" loader = XMLloader(model, instance_tag, tag_map, collision_behavior, collision_field) new_ids, updated_ids", "\"POSITIONS:POS_ORG_CODE\": \"_org_code\", \"POSITIONS:POS_BUREAU_CODE\": \"_bureau_code\", \"POSITIONS:POS_SKILL_CODE\": \"_skill_code\", \"POSITIONS:POS_STAFF_PTRN_SKILL_CODE\": \"_staff_ptrn_skill_code\", \"POSITIONS:POS_OVERSEAS_IND\": parse_boolean(\"is_overseas\",", "instance, item: setattr(instance, \"long_description\", re.sub('&amp;', '&', item.text).strip()), \"TOUR_OF_DUTIES:TOD_MONTHS_NUM\": \"months\" }", "Post.objects.filter(id__in=new_ids + updated_ids): loc.update_relationships() return (model, instance_tag, tag_map, collision_field, post_load_function)", "Country instance_tag = \"DATA_RECORD\" collision_field = \"code\" tag_map = {", "{ \"code\": \"code\", \"city\": strip_extra_spaces(\"city\"), \"state\": strip_extra_spaces(\"state\"), \"country\": \"_country\" }", "post_load_function(new_ids, updated_ids): # Connect new locations to applicable posts for", "not options['skip_post']: post_load_function(new_ids, updated_ids) self.logger.info(f\"XML Load Report\\n\\tNew: {len(new_ids)}\\n\\tUpdated: {len(updated_ids)}\\t\\t\") def", "Location.objects.filter(id__in=new_ids + updated_ids): Post.objects.filter(_location_code=loc.code).update(location=loc) return (model, instance_tag, tag_map, collision_field, post_load_function)", "instance_tag, tag_map, collision_field, None) def mode_proficiencies(): model = Proficiency instance_tag", "\"POSITIONS:POS_NUM_TEXT\": \"position_number\", \"POSITIONS:POS_TITLE_CODE\": \"_title_code\", \"POSITIONS:POS_TITLE_DESC\": \"title\", \"POSITIONS:POS_ORG_CODE\": \"_org_code\", \"POSITIONS:POS_BUREAU_CODE\": \"_bureau_code\",", "instance_tag, tag_map, collision_field, post_load_function) def mode_tour_of_duty(): model = TourOfDuty instance_tag", "'proficiencies': mode_proficiencies, 'grades': mode_grades, 'skills': mode_skills, 'organizations': mode_organizations, 'positions': mode_positions,", "instance_tag = \"POSITIONS:POSITION\" collision_field = \"_seq_num\" tag_map = { \"POSITIONS:POS_SEQ_NUM\":", "= False if org.code == org._parent_bureau_code: org.is_bureau = True org.save()", "\"_skill_code\", \"POSITIONS:POS_STAFF_PTRN_SKILL_CODE\": \"_staff_ptrn_skill_code\", \"POSITIONS:POS_OVERSEAS_IND\": parse_boolean(\"is_overseas\", ['O']), \"POSITIONS:POS_PAY_PLAN_CODE\": \"_pay_plan_code\", \"POSITIONS:POS_STATUS_CODE\": \"_status_code\",", "\"code\" tag_map = { \"TOUR_OF_DUTIES:TOD_CODE\": \"code\", \"TOUR_OF_DUTIES:TOD_SHORT_DESC\": \"short_description\", \"TOUR_OF_DUTIES:TOD_DESC_TEXT\": lambda", "(model, instance_tag, tag_map, collision_field, post_load_function) def mode_country(): model = Country", "= Language instance_tag = \"LANGUAGES:LANGUAGE\" collision_field = \"code\" tag_map =", "is done automatically by DOS Webservices, so # we now", "collision_field = \"code\" tag_map = { \"LANGUAGES:LANG_CODE\": \"code\", \"LANGUAGES:LANG_LONG_DESC\": \"long_description\",", "= \"DATA_RECORD\" collision_field = \"code\" tag_map = { \"ORG_CODE\": \"code\",", "tag_map, collision_field, post_load_function) def mode_tour_of_duty(): model = TourOfDuty instance_tag =", "and not options['skip_post']: post_load_function(new_ids, updated_ids) self.logger.info(f\"XML Load Report\\n\\tNew: {len(new_ids)}\\n\\tUpdated: {len(updated_ids)}\\t\\t\")", "= Post instance_tag = \"BIDPOSTS:BIDDING_TOOL\" collision_field = \"_location_code\" tag_map =", "logger = logging.getLogger(__name__) def __init__(self, *args, **kwargs): super(Command, self).__init__(*args, **kwargs)", "collision_field, post_load_function = self.modes[options['type'][0]]() # Set / update the collision", "Position.objects.filter(id__in=new_ids + updated_ids): pos.update_relationships() return (model, instance_tag, tag_map, collision_field, post_load_function)", "\"LANGUAGES:LANG_EFFECTIVE_DATE\": parse_date(\"effective_date\") } return (model, instance_tag, tag_map, collision_field, None) def", "\"_parent_bureau_code\", \"ORG_LOCATION_CODE\": \"_location_code\" } # Update relationships def post_load_function(new_ids, updated_ids):", "def mode_positions(): model = Position instance_tag = \"POSITIONS:POSITION\" collision_field =", "parse_boolean(\"is_overseas\", ['O']), \"POSITIONS:POS_PAY_PLAN_CODE\": \"_pay_plan_code\", \"POSITIONS:POS_STATUS_CODE\": \"_status_code\", \"POSITIONS:POS_SERVICE_TYPE_CODE\": \"_service_type_code\", \"POSITIONS:POS_GRADE_CODE\": \"_grade_code\",", "= \"code\" tag_map = { \"LANGUAGES:LANG_CODE\": \"code\", \"LANGUAGES:LANG_LONG_DESC\": \"long_description\", \"LANGUAGES:LANG_SHORT_DESC\":", "= { \"SKILLS:SKILL_CODE\": \"code\", \"SKILLS:SKILL_DESCRIPTION\": \"description\" } return (model, instance_tag,", "model = Position instance_tag = \"POSITIONS:POSITION\" collision_field = \"_seq_num\" tag_map", "\"130000\", \"140000\", \"146000\", \"150000\", \"160000\" ] if org.code in regional_codes:", "instance_tag, tag_map, collision_field, post_load_function) def mode_country(): model = Country instance_tag", "\"POSITIONS:POS_SEQ_NUM\": \"_seq_num\", \"POSITIONS:POS_NUM_TEXT\": \"position_number\", \"POSITIONS:POS_TITLE_CODE\": \"_title_code\", \"POSITIONS:POS_TITLE_DESC\": \"title\", \"POSITIONS:POS_ORG_CODE\": \"_org_code\",", "XML into a supported file' logger = logging.getLogger(__name__) def __init__(self,", "handle(self, *args, **options): model, instance_tag, tag_map, collision_field, post_load_function = self.modes[options['type'][0]]()", "\"POSITIONS:POS_JOBCODE_CODE\": \"_jobcode_code\", \"POSITIONS:POS_OCC_SERIES_CODE\": \"_occ_series_code\", } def post_load_function(new_ids, updated_ids): for pos", "\"POSITIONS:POS_STATUS_CODE\": \"_status_code\", \"POSITIONS:POS_SERVICE_TYPE_CODE\": \"_service_type_code\", \"POSITIONS:POS_GRADE_CODE\": \"_grade_code\", \"POSITIONS:POS_POST_CODE\": \"_post_code\", \"POSITIONS:POS_LANGUAGE_1_CODE\": \"_language_1_code\",", "mode_location, 'capsule_descriptions': mode_capsule_description, 'skill_cone': mode_skill_cone } def add_arguments(self, parser): parser.add_argument('file',", "\"LANGUAGE_PROFICIENCY:LP_DESC\": \"description\" } return (model, instance_tag, tag_map, collision_field, None) def", "} return (model, instance_tag, tag_map, collision_field, None) def mode_proficiencies(): model", "= { \"BIDPOSTS:DSC_CD\": \"_location_code\", \"BIDPOSTS:TOD_CODE\": \"_tod_code\", \"BIDPOSTS:BT_COST_OF_LIVING_ADJUST_NUM\": \"cost_of_living_adjustment\", \"BIDPOSTS:BT_DIFFERENTIAL_RATE_NUM\": \"differential_rate\",", "\"delete\" elif options['update']: collision_behavior = \"update\" else: collision_behavior = \"skip\"", "return (model, instance_tag, tag_map, collision_field, post_load_function) def mode_skills(): model =", "\"BIDPOSTS:BT_COST_OF_LIVING_ADJUST_NUM\": \"cost_of_living_adjustment\", \"BIDPOSTS:BT_DIFFERENTIAL_RATE_NUM\": \"differential_rate\", \"BIDPOSTS:BT_REST_RELAXATION_POINT_TEXT\": strip_extra_spaces(\"rest_relaxation_point\"), \"BIDPOSTS:BT_DANGER_PAY_NUM\": \"danger_pay\", \"BIDPOSTS:BT_CONSUMABLE_ALLOWANCE_FLG\": parse_boolean(\"has_consumable_allowance\"),", "only need this logic when loading from our sample XML", "an XML into a supported file' logger = logging.getLogger(__name__) def", "} def post_load_function(new_ids, updated_ids): # Connect new locations to applicable", "= { \"TOUR_OF_DUTIES:TOD_CODE\": \"code\", \"TOUR_OF_DUTIES:TOD_SHORT_DESC\": \"short_description\", \"TOUR_OF_DUTIES:TOD_DESC_TEXT\": lambda instance, item:", "\"location_prefix\" } return (model, instance_tag, tag_map, collision_field, None) def mode_location():", "get_nested_tag from talentmap_api.language.models import Language, Proficiency from talentmap_api.position.models import Grade,", "pos.update_relationships() return (model, instance_tag, tag_map, collision_field, post_load_function) def mode_skills(): model", "pos in Grade.objects.filter(id__in=new_ids + updated_ids): pos.update_relationships() return (model, instance_tag, tag_map,", "# Array of regional codes regional_codes = [ \"110000\", \"120000\",", "\"110000\", \"120000\", \"130000\", \"140000\", \"146000\", \"150000\", \"160000\" ] if org.code", "None) def mode_location(): model = Location instance_tag = \"location\" collision_field", "BaseCommand import logging import re from talentmap_api.common.xml_helpers import XMLloader, strip_extra_spaces,", "Run the post load function, if it exists if callable(post_load_function)", "import Grade, Skill, Position, CapsuleDescription, SkillCone from talentmap_api.organization.models import Organization,", "\"code\" tag_map = { \"COUNTRY_CODE\": \"code\", \"FULL_NAME\": \"name\", \"SHORT_NAME\": \"short_name\",", "help=\"The XML file to load\") parser.add_argument('type', nargs=1, type=str, choices=self.modes.keys(), help=\"The", "supported file' logger = logging.getLogger(__name__) def __init__(self, *args, **kwargs): super(Command,", "(model, instance_tag, tag_map, collision_field, None) def mode_grades(): model = Grade", "options['skip_post']: post_load_function(new_ids, updated_ids) self.logger.info(f\"XML Load Report\\n\\tNew: {len(new_ids)}\\n\\tUpdated: {len(updated_ids)}\\t\\t\") def mode_languages():", "from talentmap_api.position.models import Grade, Skill, Position, CapsuleDescription, SkillCone from talentmap_api.organization.models", "parser.add_argument('--skippost', dest='skip_post', action='store_true', help='Skip post load functions') def handle(self, *args,", "by DOS Webservices, so # we now only need this", "\"POSITIONS:POS_CREATE_DATE\": parse_date(\"create_date\"), \"POSITIONS:POS_UPDATE_ID\": \"_update_id\", \"POSITIONS:POS_UPDATE_DATE\": parse_date(\"update_date\"), \"POSITIONS:POS_EFFECTIVE_DATE\": parse_date(\"effective_date\"), \"POSITIONS:POS_JOBCODE_CODE\": \"_jobcode_code\",", "'capsule_descriptions': mode_capsule_description, 'skill_cone': mode_skill_cone } def add_arguments(self, parser): parser.add_argument('file', nargs=1,", "parse_date(\"create_date\"), \"POSITIONS:POS_UPDATE_ID\": \"_update_id\", \"POSITIONS:POS_UPDATE_DATE\": parse_date(\"update_date\"), \"POSITIONS:POS_EFFECTIVE_DATE\": parse_date(\"effective_date\"), \"POSITIONS:POS_JOBCODE_CODE\": \"_jobcode_code\", \"POSITIONS:POS_OCC_SERIES_CODE\":", "parser): parser.add_argument('file', nargs=1, type=str, help=\"The XML file to load\") parser.add_argument('type',", "collision_field = \"_location_code\" tag_map = { \"BIDPOSTS:DSC_CD\": \"_location_code\", \"BIDPOSTS:TOD_CODE\": \"_tod_code\",", "Organization, Post, TourOfDuty, Location, Country class Command(BaseCommand): help = 'Loads", "{ \"POS_SEQ_NUM\": \"_pos_seq_num\", \"capsuleDescription\": \"content\", } return (model, instance_tag, tag_map,", "tag_map, collision_field, None) def mode_post(): model = Post instance_tag =", "# Set / update the collision behavior collision_behavior = None", "org.code == org._parent_bureau_code: org.is_bureau = True org.save() return (model, instance_tag,", "return (model, instance_tag, tag_map, collision_field, post_load_function) def mode_positions(): model =", "\"short_description\", \"TOUR_OF_DUTIES:TOD_DESC_TEXT\": lambda instance, item: setattr(instance, \"long_description\", re.sub('&amp;', '&', item.text).strip()),", "update the collision behavior collision_behavior = None if options['delete']: collision_behavior", "\"code\", \"city\": strip_extra_spaces(\"city\"), \"state\": strip_extra_spaces(\"state\"), \"country\": \"_country\" } def post_load_function(new_ids,", "= \"GRADES:GRADE\" collision_field = \"code\" tag_map = { \"GRADES:GRD_GRADE_CODE\": \"code\"", "Skill, Position, CapsuleDescription, SkillCone from talentmap_api.organization.models import Organization, Post, TourOfDuty," ]
[ "str(uuid.uuid4()) + '.test') with recfile.open(filename, \"w\") as g: g.write(teststring) self.assertEqual(recfile.open(filename,", "teststring = 'test%s' % k filename = os.path.join('tests', str(uuid.uuid4()), str(uuid.uuid4())", "% k filename = os.path.join('tests', str(uuid.uuid4()), str(uuid.uuid4()) + '.test') with", "uuid from .fix_path import fix_sys_path fix_sys_path(__file__) from gluon import recfile", "open(filename, 'w') as g: g.write('this file exists') self.assertTrue(recfile.exists(filename)) self.assertTrue(hasattr(recfile.open(filename, \"r\"),", "is_there = recfile.exists(filename, path='tests') self.assertTrue(is_there) recfile.remove(filename, path='tests') is_there = recfile.exists(filename,", "g.write(teststring) self.assertEqual(recfile.open(filename, \"r\").read(), teststring) is_there = recfile.exists(filename) self.assertTrue(is_there) recfile.remove(filename) is_there", "recfile.exists(filename, path='tests') self.assertTrue(is_there) recfile.remove(filename, path='tests') is_there = recfile.exists(filename, path='tests') self.assertFalse(is_there)", "fix_sys_path fix_sys_path(__file__) from gluon import recfile class TestRecfile(unittest.TestCase): def setUp(self):", "'.test' with recfile.open(filename, \"w\", path='tests') as g: g.write(teststring) self.assertEqual(recfile.open(filename, \"r\",", "\"w\", path='tests') as g: g.write(teststring) self.assertEqual(recfile.open(filename, \"r\", path='tests').read(), teststring) is_there", "filename = os.path.join('tests', str(uuid.uuid4()), str(uuid.uuid4()) + '.test') with recfile.open(filename, \"w\")", "recfile.exists(filename) self.assertTrue(is_there) recfile.remove(filename) is_there = recfile.exists(filename) self.assertFalse(is_there) for k in", "gluon.recfile \"\"\" import unittest import os import shutil import uuid", "fix_sys_path(__file__) from gluon import recfile class TestRecfile(unittest.TestCase): def setUp(self): os.mkdir('tests')", "% k filename = os.path.join('tests', str(uuid.uuid4()) + '.test') with recfile.open(filename,", "with recfile.open(filename, \"w\", path='tests') as g: g.write(teststring) self.assertEqual(recfile.open(filename, \"r\", path='tests').read(),", "os.path.join('tests', str(uuid.uuid4()) + '.test') with open(filename, 'w') as g: g.write('this", "filename = str(uuid.uuid4()) + '.test' with recfile.open(filename, \"w\", path='tests') as", "+ '.test') with open(filename, 'w') as g: g.write('this file exists')", "str(uuid.uuid4()), str(uuid.uuid4()) + '.test') with recfile.open(filename, \"w\") as g: g.write(teststring)", "def test_existing(self): filename = os.path.join('tests', str(uuid.uuid4()) + '.test') with open(filename,", "\"r\", path='tests').read(), teststring) is_there = recfile.exists(filename, path='tests') self.assertTrue(is_there) recfile.remove(filename, path='tests')", "filename) self.assertRaises(IOError, recfile.open, filename, \"r\") if __name__ == '__main__': unittest.main()", "def tearDown(self): shutil.rmtree('tests') def test_generation(self): for k in range(10): teststring", "self.assertEqual(recfile.open(filename, \"r\", path='tests').read(), teststring) is_there = recfile.exists(filename, path='tests') self.assertTrue(is_there) recfile.remove(filename,", "import shutil import uuid from .fix_path import fix_sys_path fix_sys_path(__file__) from", "recfile.open(filename, \"w\") as g: g.write(teststring) self.assertEqual(recfile.open(filename, \"r\").read(), teststring) is_there =", "path='tests') self.assertTrue(is_there) recfile.remove(filename, path='tests') is_there = recfile.exists(filename, path='tests') self.assertFalse(is_there) for", "recfile.remove(filename, path='tests') is_there = recfile.exists(filename, path='tests') self.assertFalse(is_there) for k in", "path='tests') as g: g.write(teststring) self.assertEqual(recfile.open(filename, \"r\", path='tests').read(), teststring) is_there =", "g: g.write('this file exists') self.assertTrue(recfile.exists(filename)) self.assertTrue(hasattr(recfile.open(filename, \"r\"), 'read')) recfile.remove(filename, path='tests')", "'read')) recfile.remove(filename, path='tests') self.assertFalse(recfile.exists(filename)) self.assertRaises(IOError, recfile.remove, filename) self.assertRaises(IOError, recfile.open, filename,", "for gluon.recfile \"\"\" import unittest import os import shutil import", "unittest import os import shutil import uuid from .fix_path import", "# -*- coding: utf-8 -*- \"\"\" Unit tests for gluon.recfile", "exists') self.assertTrue(recfile.exists(filename)) self.assertTrue(hasattr(recfile.open(filename, \"r\"), 'read')) recfile.remove(filename, path='tests') self.assertFalse(recfile.exists(filename)) self.assertRaises(IOError, recfile.remove,", "= recfile.exists(filename) self.assertTrue(is_there) recfile.remove(filename) is_there = recfile.exists(filename) self.assertFalse(is_there) def test_existing(self):", "shutil.rmtree('tests') def test_generation(self): for k in range(10): teststring = 'test%s'", "k in range(10): teststring = 'test%s' % k filename =", "+ '.test' with recfile.open(filename, \"w\", path='tests') as g: g.write(teststring) self.assertEqual(recfile.open(filename,", "'.test') with open(filename, 'w') as g: g.write('this file exists') self.assertTrue(recfile.exists(filename))", "g: g.write(teststring) self.assertEqual(recfile.open(filename, \"r\", path='tests').read(), teststring) is_there = recfile.exists(filename, path='tests')", "= recfile.exists(filename, path='tests') self.assertTrue(is_there) recfile.remove(filename, path='tests') is_there = recfile.exists(filename, path='tests')", "from .fix_path import fix_sys_path fix_sys_path(__file__) from gluon import recfile class", "range(10): teststring = 'test%s' % k filename = os.path.join('tests', str(uuid.uuid4())", "= 'test%s' % k filename = os.path.join('tests', str(uuid.uuid4()), str(uuid.uuid4()) +", "as g: g.write(teststring) self.assertEqual(recfile.open(filename, \"r\").read(), teststring) is_there = recfile.exists(filename) self.assertTrue(is_there)", "self.assertTrue(hasattr(recfile.open(filename, \"r\"), 'read')) recfile.remove(filename, path='tests') self.assertFalse(recfile.exists(filename)) self.assertRaises(IOError, recfile.remove, filename) self.assertRaises(IOError,", "recfile.remove(filename) is_there = recfile.exists(filename) self.assertFalse(is_there) def test_existing(self): filename = os.path.join('tests',", "'w') as g: g.write('this file exists') self.assertTrue(recfile.exists(filename)) self.assertTrue(hasattr(recfile.open(filename, \"r\"), 'read'))", "recfile.remove(filename, path='tests') self.assertFalse(recfile.exists(filename)) self.assertRaises(IOError, recfile.remove, filename) self.assertRaises(IOError, recfile.open, filename, \"r\")", ".fix_path import fix_sys_path fix_sys_path(__file__) from gluon import recfile class TestRecfile(unittest.TestCase):", "setUp(self): os.mkdir('tests') def tearDown(self): shutil.rmtree('tests') def test_generation(self): for k in", "with recfile.open(filename, \"w\") as g: g.write(teststring) self.assertEqual(recfile.open(filename, \"r\").read(), teststring) is_there", "= recfile.exists(filename) self.assertFalse(is_there) def test_existing(self): filename = os.path.join('tests', str(uuid.uuid4()) +", "teststring = 'test%s' % k filename = os.path.join('tests', str(uuid.uuid4()) +", "'test%s' % k filename = os.path.join('tests', str(uuid.uuid4()) + '.test') with", "= str(uuid.uuid4()) + '.test' with recfile.open(filename, \"w\", path='tests') as g:", "str(uuid.uuid4()) + '.test') with open(filename, 'w') as g: g.write('this file", "class TestRecfile(unittest.TestCase): def setUp(self): os.mkdir('tests') def tearDown(self): shutil.rmtree('tests') def test_generation(self):", "is_there = recfile.exists(filename) self.assertFalse(is_there) for k in range(10): teststring =", "os.path.join('tests', str(uuid.uuid4()) + '.test') with recfile.open(filename, \"w\") as g: g.write(teststring)", "gluon import recfile class TestRecfile(unittest.TestCase): def setUp(self): os.mkdir('tests') def tearDown(self):", "filename = os.path.join('tests', str(uuid.uuid4()) + '.test') with recfile.open(filename, \"w\") as", "recfile.open(filename, \"w\", path='tests') as g: g.write(teststring) self.assertEqual(recfile.open(filename, \"r\", path='tests').read(), teststring)", "Unit tests for gluon.recfile \"\"\" import unittest import os import", "import os import shutil import uuid from .fix_path import fix_sys_path", "tearDown(self): shutil.rmtree('tests') def test_generation(self): for k in range(10): teststring =", "range(10): teststring = 'test%s' % k filename = str(uuid.uuid4()) +", "import uuid from .fix_path import fix_sys_path fix_sys_path(__file__) from gluon import", "recfile.exists(filename, path='tests') self.assertFalse(is_there) for k in range(10): teststring = 'test%s'", "= os.path.join('tests', str(uuid.uuid4()), str(uuid.uuid4()) + '.test') with recfile.open(filename, \"w\") as", "self.assertRaises(IOError, recfile.remove, filename) self.assertRaises(IOError, recfile.open, filename, \"r\") if __name__ ==", "g: g.write(teststring) self.assertEqual(recfile.open(filename, \"r\").read(), teststring) is_there = recfile.exists(filename) self.assertTrue(is_there) recfile.remove(filename)", "path='tests').read(), teststring) is_there = recfile.exists(filename, path='tests') self.assertTrue(is_there) recfile.remove(filename, path='tests') is_there", "= os.path.join('tests', str(uuid.uuid4()) + '.test') with recfile.open(filename, \"w\") as g:", "recfile.exists(filename) self.assertFalse(is_there) for k in range(10): teststring = 'test%s' %", "def setUp(self): os.mkdir('tests') def tearDown(self): shutil.rmtree('tests') def test_generation(self): for k", "range(10): teststring = 'test%s' % k filename = os.path.join('tests', str(uuid.uuid4()),", "\"\"\" Unit tests for gluon.recfile \"\"\" import unittest import os", "= os.path.join('tests', str(uuid.uuid4()) + '.test') with open(filename, 'w') as g:", "recfile class TestRecfile(unittest.TestCase): def setUp(self): os.mkdir('tests') def tearDown(self): shutil.rmtree('tests') def", "k filename = os.path.join('tests', str(uuid.uuid4()) + '.test') with recfile.open(filename, \"w\")", "in range(10): teststring = 'test%s' % k filename = str(uuid.uuid4())", "shutil import uuid from .fix_path import fix_sys_path fix_sys_path(__file__) from gluon", "self.assertFalse(is_there) for k in range(10): teststring = 'test%s' % k", "is_there = recfile.exists(filename, path='tests') self.assertFalse(is_there) for k in range(10): teststring", "\"r\").read(), teststring) is_there = recfile.exists(filename) self.assertTrue(is_there) recfile.remove(filename) is_there = recfile.exists(filename)", "\"\"\" import unittest import os import shutil import uuid from", "python # -*- coding: utf-8 -*- \"\"\" Unit tests for", "recfile.exists(filename) self.assertTrue(is_there) recfile.remove(filename) is_there = recfile.exists(filename) self.assertFalse(is_there) def test_existing(self): filename", "'test%s' % k filename = str(uuid.uuid4()) + '.test' with recfile.open(filename,", "is_there = recfile.exists(filename) self.assertTrue(is_there) recfile.remove(filename) is_there = recfile.exists(filename) self.assertFalse(is_there) def", "coding: utf-8 -*- \"\"\" Unit tests for gluon.recfile \"\"\" import", "import recfile class TestRecfile(unittest.TestCase): def setUp(self): os.mkdir('tests') def tearDown(self): shutil.rmtree('tests')", "is_there = recfile.exists(filename) self.assertFalse(is_there) def test_existing(self): filename = os.path.join('tests', str(uuid.uuid4())", "test_generation(self): for k in range(10): teststring = 'test%s' % k", "tests for gluon.recfile \"\"\" import unittest import os import shutil", "self.assertTrue(is_there) recfile.remove(filename, path='tests') is_there = recfile.exists(filename, path='tests') self.assertFalse(is_there) for k", "path='tests') is_there = recfile.exists(filename, path='tests') self.assertFalse(is_there) for k in range(10):", "= 'test%s' % k filename = os.path.join('tests', str(uuid.uuid4()) + '.test')", "% k filename = str(uuid.uuid4()) + '.test' with recfile.open(filename, \"w\",", "self.assertEqual(recfile.open(filename, \"r\").read(), teststring) is_there = recfile.exists(filename) self.assertTrue(is_there) recfile.remove(filename) is_there =", "path='tests') self.assertFalse(is_there) for k in range(10): teststring = 'test%s' %", "test_existing(self): filename = os.path.join('tests', str(uuid.uuid4()) + '.test') with open(filename, 'w')", "teststring) is_there = recfile.exists(filename, path='tests') self.assertTrue(is_there) recfile.remove(filename, path='tests') is_there =", "-*- coding: utf-8 -*- \"\"\" Unit tests for gluon.recfile \"\"\"", "\"r\"), 'read')) recfile.remove(filename, path='tests') self.assertFalse(recfile.exists(filename)) self.assertRaises(IOError, recfile.remove, filename) self.assertRaises(IOError, recfile.open,", "self.assertTrue(is_there) recfile.remove(filename) is_there = recfile.exists(filename) self.assertFalse(is_there) def test_existing(self): filename =", "as g: g.write(teststring) self.assertEqual(recfile.open(filename, \"r\", path='tests').read(), teststring) is_there = recfile.exists(filename,", "#!/usr/bin/env python # -*- coding: utf-8 -*- \"\"\" Unit tests", "'test%s' % k filename = os.path.join('tests', str(uuid.uuid4()), str(uuid.uuid4()) + '.test')", "'.test') with recfile.open(filename, \"w\") as g: g.write(teststring) self.assertEqual(recfile.open(filename, \"r\").read(), teststring)", "def test_generation(self): for k in range(10): teststring = 'test%s' %", "\"w\") as g: g.write(teststring) self.assertEqual(recfile.open(filename, \"r\").read(), teststring) is_there = recfile.exists(filename)", "from gluon import recfile class TestRecfile(unittest.TestCase): def setUp(self): os.mkdir('tests') def", "self.assertTrue(is_there) recfile.remove(filename) is_there = recfile.exists(filename) self.assertFalse(is_there) for k in range(10):", "+ '.test') with recfile.open(filename, \"w\") as g: g.write(teststring) self.assertEqual(recfile.open(filename, \"r\").read(),", "is_there = recfile.exists(filename) self.assertTrue(is_there) recfile.remove(filename) is_there = recfile.exists(filename) self.assertFalse(is_there) for", "self.assertFalse(is_there) def test_existing(self): filename = os.path.join('tests', str(uuid.uuid4()) + '.test') with", "in range(10): teststring = 'test%s' % k filename = os.path.join('tests',", "g.write('this file exists') self.assertTrue(recfile.exists(filename)) self.assertTrue(hasattr(recfile.open(filename, \"r\"), 'read')) recfile.remove(filename, path='tests') self.assertFalse(recfile.exists(filename))", "str(uuid.uuid4()) + '.test' with recfile.open(filename, \"w\", path='tests') as g: g.write(teststring)", "k filename = str(uuid.uuid4()) + '.test' with recfile.open(filename, \"w\", path='tests')", "os.path.join('tests', str(uuid.uuid4()), str(uuid.uuid4()) + '.test') with recfile.open(filename, \"w\") as g:", "path='tests') self.assertFalse(recfile.exists(filename)) self.assertRaises(IOError, recfile.remove, filename) self.assertRaises(IOError, recfile.open, filename, \"r\") if", "import fix_sys_path fix_sys_path(__file__) from gluon import recfile class TestRecfile(unittest.TestCase): def", "recfile.remove, filename) self.assertRaises(IOError, recfile.open, filename, \"r\") if __name__ == '__main__':", "filename = os.path.join('tests', str(uuid.uuid4()) + '.test') with open(filename, 'w') as", "os import shutil import uuid from .fix_path import fix_sys_path fix_sys_path(__file__)", "file exists') self.assertTrue(recfile.exists(filename)) self.assertTrue(hasattr(recfile.open(filename, \"r\"), 'read')) recfile.remove(filename, path='tests') self.assertFalse(recfile.exists(filename)) self.assertRaises(IOError,", "utf-8 -*- \"\"\" Unit tests for gluon.recfile \"\"\" import unittest", "os.mkdir('tests') def tearDown(self): shutil.rmtree('tests') def test_generation(self): for k in range(10):", "self.assertFalse(recfile.exists(filename)) self.assertRaises(IOError, recfile.remove, filename) self.assertRaises(IOError, recfile.open, filename, \"r\") if __name__", "= 'test%s' % k filename = str(uuid.uuid4()) + '.test' with", "for k in range(10): teststring = 'test%s' % k filename", "-*- \"\"\" Unit tests for gluon.recfile \"\"\" import unittest import", "with open(filename, 'w') as g: g.write('this file exists') self.assertTrue(recfile.exists(filename)) self.assertTrue(hasattr(recfile.open(filename,", "k filename = os.path.join('tests', str(uuid.uuid4()), str(uuid.uuid4()) + '.test') with recfile.open(filename,", "recfile.remove(filename) is_there = recfile.exists(filename) self.assertFalse(is_there) for k in range(10): teststring", "TestRecfile(unittest.TestCase): def setUp(self): os.mkdir('tests') def tearDown(self): shutil.rmtree('tests') def test_generation(self): for", "self.assertTrue(recfile.exists(filename)) self.assertTrue(hasattr(recfile.open(filename, \"r\"), 'read')) recfile.remove(filename, path='tests') self.assertFalse(recfile.exists(filename)) self.assertRaises(IOError, recfile.remove, filename)", "as g: g.write('this file exists') self.assertTrue(recfile.exists(filename)) self.assertTrue(hasattr(recfile.open(filename, \"r\"), 'read')) recfile.remove(filename,", "= recfile.exists(filename) self.assertTrue(is_there) recfile.remove(filename) is_there = recfile.exists(filename) self.assertFalse(is_there) for k", "recfile.exists(filename) self.assertFalse(is_there) def test_existing(self): filename = os.path.join('tests', str(uuid.uuid4()) + '.test')", "teststring) is_there = recfile.exists(filename) self.assertTrue(is_there) recfile.remove(filename) is_there = recfile.exists(filename) self.assertFalse(is_there)", "g.write(teststring) self.assertEqual(recfile.open(filename, \"r\", path='tests').read(), teststring) is_there = recfile.exists(filename, path='tests') self.assertTrue(is_there)", "= recfile.exists(filename, path='tests') self.assertFalse(is_there) for k in range(10): teststring =", "teststring = 'test%s' % k filename = str(uuid.uuid4()) + '.test'", "import unittest import os import shutil import uuid from .fix_path", "= recfile.exists(filename) self.assertFalse(is_there) for k in range(10): teststring = 'test%s'" ]
[ "dotenv import load_dotenv from subprocess import check_output, Popen, PIPE load_dotenv()", "BUCKET_NAME = os.environ.get('BUCKET_NAME') def get_lambda_functions(): function_dict = {} res =", "lambda_functions: function_name = lambda_function['FunctionName'] subprocess.run([ \"aws\", \"lambda\", \"update-function-configuration\", \"--function-name\", f\"{function_name}\",", "# Accessing variables. CLIENT_ID = os.environ.get('CLIENT_ID') CLIENT_SECRET = os.environ.get('CLIENT_SECRET') USERNAME", "subprocess.Popen( [\"aws\", \"lambda\", \"list-functions\"], stdout=subprocess.PIPE ) output = res.communicate() function_dict.update(json.loads(output[0]))", "= os.environ.get('USERNAME') BUCKET_NAME = os.environ.get('BUCKET_NAME') def get_lambda_functions(): function_dict = {}", "os.environ.get('USERNAME') BUCKET_NAME = os.environ.get('BUCKET_NAME') def get_lambda_functions(): function_dict = {} res", "import check_output, Popen, PIPE load_dotenv() # Accessing variables. CLIENT_ID =", "lambda_function in lambda_functions: function_name = lambda_function['FunctionName'] subprocess.run([ \"aws\", \"lambda\", \"update-function-configuration\",", "subprocess from dotenv import load_dotenv from subprocess import check_output, Popen,", "= os.environ.get('CLIENT_SECRET') USERNAME = os.environ.get('USERNAME') BUCKET_NAME = os.environ.get('BUCKET_NAME') def get_lambda_functions():", "res.communicate() function_dict.update(json.loads(output[0])) return function_dict['Functions'] lambda_functions = get_lambda_functions() for lambda_function in", "\"list-functions\"], stdout=subprocess.PIPE ) output = res.communicate() function_dict.update(json.loads(output[0])) return function_dict['Functions'] lambda_functions", "os.environ.get('BUCKET_NAME') def get_lambda_functions(): function_dict = {} res = subprocess.Popen( [\"aws\",", "{} res = subprocess.Popen( [\"aws\", \"lambda\", \"list-functions\"], stdout=subprocess.PIPE ) output", "= subprocess.Popen( [\"aws\", \"lambda\", \"list-functions\"], stdout=subprocess.PIPE ) output = res.communicate()", "= lambda_function['FunctionName'] subprocess.run([ \"aws\", \"lambda\", \"update-function-configuration\", \"--function-name\", f\"{function_name}\", \"--environment\", f\"Variables={{CLIENT_ID={CLIENT_ID},CLIENT_SECRET={CLIENT_SECRET},USERNAME={USERNAME},BUCKET_NAME={BUCKET_NAME}}}\"", "os.environ.get('CLIENT_ID') CLIENT_SECRET = os.environ.get('CLIENT_SECRET') USERNAME = os.environ.get('USERNAME') BUCKET_NAME = os.environ.get('BUCKET_NAME')", "\"lambda\", \"list-functions\"], stdout=subprocess.PIPE ) output = res.communicate() function_dict.update(json.loads(output[0])) return function_dict['Functions']", ") output = res.communicate() function_dict.update(json.loads(output[0])) return function_dict['Functions'] lambda_functions = get_lambda_functions()", "PIPE load_dotenv() # Accessing variables. CLIENT_ID = os.environ.get('CLIENT_ID') CLIENT_SECRET =", "json import os import subprocess from dotenv import load_dotenv from", "stdout=subprocess.PIPE ) output = res.communicate() function_dict.update(json.loads(output[0])) return function_dict['Functions'] lambda_functions =", "Popen, PIPE load_dotenv() # Accessing variables. CLIENT_ID = os.environ.get('CLIENT_ID') CLIENT_SECRET", "function_dict = {} res = subprocess.Popen( [\"aws\", \"lambda\", \"list-functions\"], stdout=subprocess.PIPE", "subprocess import check_output, Popen, PIPE load_dotenv() # Accessing variables. CLIENT_ID", "os.environ.get('CLIENT_SECRET') USERNAME = os.environ.get('USERNAME') BUCKET_NAME = os.environ.get('BUCKET_NAME') def get_lambda_functions(): function_dict", "return function_dict['Functions'] lambda_functions = get_lambda_functions() for lambda_function in lambda_functions: function_name", "= res.communicate() function_dict.update(json.loads(output[0])) return function_dict['Functions'] lambda_functions = get_lambda_functions() for lambda_function", "lambda_function['FunctionName'] subprocess.run([ \"aws\", \"lambda\", \"update-function-configuration\", \"--function-name\", f\"{function_name}\", \"--environment\", f\"Variables={{CLIENT_ID={CLIENT_ID},CLIENT_SECRET={CLIENT_SECRET},USERNAME={USERNAME},BUCKET_NAME={BUCKET_NAME}}}\" ])", "import os import subprocess from dotenv import load_dotenv from subprocess", "= get_lambda_functions() for lambda_function in lambda_functions: function_name = lambda_function['FunctionName'] subprocess.run([", "res = subprocess.Popen( [\"aws\", \"lambda\", \"list-functions\"], stdout=subprocess.PIPE ) output =", "import subprocess from dotenv import load_dotenv from subprocess import check_output,", "CLIENT_ID = os.environ.get('CLIENT_ID') CLIENT_SECRET = os.environ.get('CLIENT_SECRET') USERNAME = os.environ.get('USERNAME') BUCKET_NAME", "from dotenv import load_dotenv from subprocess import check_output, Popen, PIPE", "CLIENT_SECRET = os.environ.get('CLIENT_SECRET') USERNAME = os.environ.get('USERNAME') BUCKET_NAME = os.environ.get('BUCKET_NAME') def", "function_name = lambda_function['FunctionName'] subprocess.run([ \"aws\", \"lambda\", \"update-function-configuration\", \"--function-name\", f\"{function_name}\", \"--environment\",", "load_dotenv() # Accessing variables. CLIENT_ID = os.environ.get('CLIENT_ID') CLIENT_SECRET = os.environ.get('CLIENT_SECRET')", "<filename>configLambdas.py import json import os import subprocess from dotenv import", "variables. CLIENT_ID = os.environ.get('CLIENT_ID') CLIENT_SECRET = os.environ.get('CLIENT_SECRET') USERNAME = os.environ.get('USERNAME')", "output = res.communicate() function_dict.update(json.loads(output[0])) return function_dict['Functions'] lambda_functions = get_lambda_functions() for", "function_dict.update(json.loads(output[0])) return function_dict['Functions'] lambda_functions = get_lambda_functions() for lambda_function in lambda_functions:", "def get_lambda_functions(): function_dict = {} res = subprocess.Popen( [\"aws\", \"lambda\",", "load_dotenv from subprocess import check_output, Popen, PIPE load_dotenv() # Accessing", "os import subprocess from dotenv import load_dotenv from subprocess import", "function_dict['Functions'] lambda_functions = get_lambda_functions() for lambda_function in lambda_functions: function_name =", "from subprocess import check_output, Popen, PIPE load_dotenv() # Accessing variables.", "USERNAME = os.environ.get('USERNAME') BUCKET_NAME = os.environ.get('BUCKET_NAME') def get_lambda_functions(): function_dict =", "[\"aws\", \"lambda\", \"list-functions\"], stdout=subprocess.PIPE ) output = res.communicate() function_dict.update(json.loads(output[0])) return", "for lambda_function in lambda_functions: function_name = lambda_function['FunctionName'] subprocess.run([ \"aws\", \"lambda\",", "import json import os import subprocess from dotenv import load_dotenv", "get_lambda_functions(): function_dict = {} res = subprocess.Popen( [\"aws\", \"lambda\", \"list-functions\"],", "lambda_functions = get_lambda_functions() for lambda_function in lambda_functions: function_name = lambda_function['FunctionName']", "= os.environ.get('CLIENT_ID') CLIENT_SECRET = os.environ.get('CLIENT_SECRET') USERNAME = os.environ.get('USERNAME') BUCKET_NAME =", "import load_dotenv from subprocess import check_output, Popen, PIPE load_dotenv() #", "= {} res = subprocess.Popen( [\"aws\", \"lambda\", \"list-functions\"], stdout=subprocess.PIPE )", "get_lambda_functions() for lambda_function in lambda_functions: function_name = lambda_function['FunctionName'] subprocess.run([ \"aws\",", "Accessing variables. CLIENT_ID = os.environ.get('CLIENT_ID') CLIENT_SECRET = os.environ.get('CLIENT_SECRET') USERNAME =", "= os.environ.get('BUCKET_NAME') def get_lambda_functions(): function_dict = {} res = subprocess.Popen(", "check_output, Popen, PIPE load_dotenv() # Accessing variables. CLIENT_ID = os.environ.get('CLIENT_ID')", "in lambda_functions: function_name = lambda_function['FunctionName'] subprocess.run([ \"aws\", \"lambda\", \"update-function-configuration\", \"--function-name\"," ]
[ "0 ) ) gbSizer1.Add( self.m_button20, wx.GBPosition( 2, 0 ), wx.GBSpan(", "self, event ): event.Skip() def onButton41Click( self, event ): event.Skip()", "1 ), wx.ALL, 5 ) self.m_button01 = wx.Button( self, wx.ID_ANY,", "wx.Size( 50,50 ), 0 ) self.m_button11.SetBackgroundColour( wx.Colour( 255, 0, 0", "gbSizer1.Add( self.m_button14, wx.GBPosition( 1, 4 ), wx.GBSpan( 1, 1 ),", "), wx.ALL, 5 ) self.m_button22 = wx.Button( self, wx.ID_ANY, wx.EmptyString,", "wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button33.SetBackgroundColour( wx.Colour( 255,", "self.onButton03Click ) self.m_button04.Bind( wx.EVT_BUTTON, self.onButton04Click ) self.m_button10.Bind( wx.EVT_BUTTON, self.onButton10Click )", "1, 1 ), wx.ALL, 5 ) self.m_button13 = wx.Button( self,", "0 ), wx.GBSpan( 1, 1 ), wx.ALL, 5 ) self.m_button31", "self, event ): event.Skip() def onButton22Click( self, event ): event.Skip()", "self.m_button14.SetBackgroundColour( wx.Colour( 255, 0, 0 ) ) gbSizer1.Add( self.m_button14, wx.GBPosition(", "0, 0 ) ) gbSizer1.Add( self.m_button41, wx.GBPosition( 4, 1 ),", "self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button22.SetBackgroundColour(", "Python code generated with wxFormBuilder (version Aug 8 2018) ##", "1 ), wx.ALL, 5 ) self.m_button14 = wx.Button( self, wx.ID_ANY,", "), wx.GBSpan( 1, 1 ), wx.ALL, 5 ) self.m_button23 =", "event.Skip() def onButton40Click( self, event ): event.Skip() def onButton41Click( self,", "), 0 ) self.m_button44.SetBackgroundColour( wx.Colour( 255, 0, 0 ) )", "self.m_button13.Bind( wx.EVT_BUTTON, self.onButton13Click ) self.m_button14.Bind( wx.EVT_BUTTON, self.onButton14Click ) self.m_button20.Bind( wx.EVT_BUTTON,", "self.m_button12.Bind( wx.EVT_BUTTON, self.onButton12Click ) self.m_button13.Bind( wx.EVT_BUTTON, self.onButton13Click ) self.m_button14.Bind( wx.EVT_BUTTON,", ") ) gbSizer1.Add( self.m_button10, wx.GBPosition( 1, 0 ), wx.GBSpan( 1,", "2, 0 ), wx.GBSpan( 1, 1 ), wx.ALL, 5 )", ") self.m_button13.Bind( wx.EVT_BUTTON, self.onButton13Click ) self.m_button14.Bind( wx.EVT_BUTTON, self.onButton14Click ) self.m_button20.Bind(", "wx.BOTH ) # Connect Events self.m_button00.Bind( wx.EVT_BUTTON, self.onButton00Click ) self.m_button01.Bind(", "wx.Size( 50,50 ), 0 ) self.m_button31.SetBackgroundColour( wx.Colour( 255, 0, 0", "), wx.GBSpan( 1, 1 ), wx.ALL, 5 ) self.SetSizer( gbSizer1", "self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button00.SetBackgroundColour(", ") gbSizer1.Add( self.m_button00, wx.GBPosition( 0, 0 ), wx.GBSpan( 1, 1", "event.Skip() def onButton22Click( self, event ): event.Skip() def onButton23Click( self,", "0, 0 ) ) gbSizer1.Add( self.m_button22, wx.GBPosition( 2, 2 ),", "self.m_menuItem3.GetId() ) self.Bind( wx.EVT_MENU, self.OnMenuSaveSelect, id = self.m_menuItem1.GetId() ) self.Bind(", ") self.m_menu1 = wx.Menu() self.m_menuItem3 = wx.MenuItem( self.m_menu1, wx.ID_ANY, u\"Open\",", "= wx.ID_ANY, title = wx.EmptyString, pos = wx.Point( 0,0 ),", "event ): event.Skip() def onButton22Click( self, event ): event.Skip() def", "wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button22.SetBackgroundColour( wx.Colour( 255,", ") self.Bind( wx.EVT_MENU, self.OnMenuQuitSelect, id = self.m_menuItem2.GetId() ) self.Bind( wx.EVT_MENU,", "wxFormBuilder (version Aug 8 2018) ## http://www.wxformbuilder.org/ ## ## PLEASE", "wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button04.SetBackgroundColour( wx.Colour( 255,", "wx.GBSpan( 1, 1 ), wx.ALL, 5 ) self.m_button23 = wx.Button(", ") ) gbSizer1.Add( self.m_button04, wx.GBPosition( 0, 4 ), wx.GBSpan( 1,", "wx.GBPosition( 2, 4 ), wx.GBSpan( 1, 1 ), wx.ALL, 5", "wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button43.SetBackgroundColour( wx.Colour( 255,", "255, 0, 0 ) ) gbSizer1.Add( self.m_button30, wx.GBPosition( 3, 0", "self.m_button40, wx.GBPosition( 4, 0 ), wx.GBSpan( 1, 1 ), wx.ALL,", "self.Bind( wx.EVT_MENU, self.OnExportPythonSelect, id = self.m_menuItem4.GetId() ) def __del__( self", "): event.Skip() def onButton42Click( self, event ): event.Skip() def onButton43Click(", "id = wx.ID_ANY, title = wx.EmptyString, pos = wx.Point( 0,0", ") self.m_button11 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50", "onButton14Click( self, event ): event.Skip() def onButton20Click( self, event ):", "MyFrame1 ( wx.Frame ): def __init__( self, parent ): wx.Frame.__init__", "4 ), wx.GBSpan( 1, 1 ), wx.ALL, 5 ) self.m_button30", "wx.ALL, 5 ) self.m_button41 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition,", "50,50 ), 0 ) self.m_button13.SetBackgroundColour( wx.Colour( 255, 0, 0 )", "0, 0 ) ) gbSizer1.Add( self.m_button24, wx.GBPosition( 2, 4 ),", "wx.Colour( 255, 0, 0 ) ) gbSizer1.Add( self.m_button41, wx.GBPosition( 4,", "0, 0 ) ) gbSizer1.Add( self.m_button20, wx.GBPosition( 2, 0 ),", "wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button23.SetBackgroundColour( wx.Colour( 255, 0,", "self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button24.SetBackgroundColour(", "onButton00Click( self, event ): event.Skip() def onButton01Click( self, event ):", "self.m_button00.SetBackgroundColour( wx.Colour( 255, 0, 0 ) ) gbSizer1.Add( self.m_button00, wx.GBPosition(", "0 ) self.m_button40.SetBackgroundColour( wx.Colour( 255, 0, 0 ) ) gbSizer1.Add(", "0 ) self.m_button01.SetBackgroundColour( wx.Colour( 255, 0, 0 ) ) gbSizer1.Add(", "self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button34.SetBackgroundColour(", "255, 0, 0 ) ) gbSizer1.Add( self.m_button14, wx.GBPosition( 1, 4", "wx.Colour( 255, 0, 0 ) ) gbSizer1.Add( self.m_button10, wx.GBPosition( 1,", "0, 0 ) ) gbSizer1.Add( self.m_button01, wx.GBPosition( 0, 1 ),", "onButton10Click( self, event ): event.Skip() def onButton11Click( self, event ):", "self.m_menubar1.Append( self.m_menu2, u\"export\" ) self.SetMenuBar( self.m_menubar1 ) self.Centre( wx.BOTH )", "onButton11Click( self, event ): event.Skip() def onButton12Click( self, event ):", ") self.m_button33.SetBackgroundColour( wx.Colour( 255, 0, 0 ) ) gbSizer1.Add( self.m_button33,", "id = self.m_menuItem2.GetId() ) self.Bind( wx.EVT_MENU, self.OnExportPythonSelect, id = self.m_menuItem4.GetId()", "def __del__( self ): pass # Virtual event handlers, overide", ") self.m_button11.SetBackgroundColour( wx.Colour( 255, 0, 0 ) ) gbSizer1.Add( self.m_button11,", "): event.Skip() def onButton13Click( self, event ): event.Skip() def onButton14Click(", "wx.GBSpan( 1, 1 ), wx.ALL, 5 ) self.m_button12 = wx.Button(", "wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button31.SetBackgroundColour( wx.Colour( 255, 0,", "self.m_button14.Bind( wx.EVT_BUTTON, self.onButton14Click ) self.m_button20.Bind( wx.EVT_BUTTON, self.onButton20Click ) self.m_button21.Bind( wx.EVT_BUTTON,", "self.m_button12 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ),", "self.OnMenuQuitSelect, id = self.m_menuItem2.GetId() ) self.Bind( wx.EVT_MENU, self.OnExportPythonSelect, id =", "wx.DEFAULT_FRAME_STYLE|wx.TAB_TRAVERSAL ) self.SetSizeHints( wx.DefaultSize, wx.DefaultSize ) gbSizer1 = wx.GridBagSizer( 0,", "0 ) self.m_button30.SetBackgroundColour( wx.Colour( 255, 0, 0 ) ) gbSizer1.Add(", "2 ), wx.GBSpan( 1, 1 ), wx.ALL, 5 ) self.m_button33", "), wx.ALL, 5 ) self.m_button42 = wx.Button( self, wx.ID_ANY, wx.EmptyString,", "wx.ALL, 5 ) self.m_button22 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition,", "wx.Size( 50,50 ), 0 ) self.m_button42.SetBackgroundColour( wx.Colour( 255, 0, 0", "self.onButton43Click ) self.m_button44.Bind( wx.EVT_BUTTON, self.onButton44Click ) self.Bind( wx.EVT_MENU, self.OnMenuOpenSelect, id", "0 ) self.m_button02.SetBackgroundColour( wx.Colour( 255, 0, 0 ) ) gbSizer1.Add(", "wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ), 0 )", "wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button32.SetBackgroundColour( wx.Colour( 255,", "5 ) self.m_button04 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size(", "0 ) ) gbSizer1.Add( self.m_button30, wx.GBPosition( 3, 0 ), wx.GBSpan(", ") ) gbSizer1.Add( self.m_button33, wx.GBPosition( 3, 3 ), wx.GBSpan( 1,", "self.m_button34.Bind( wx.EVT_BUTTON, self.onButton34Click ) self.m_button40.Bind( wx.EVT_BUTTON, self.onButton40Click ) self.m_button41.Bind( wx.EVT_BUTTON,", "self.m_button02.SetBackgroundColour( wx.Colour( 255, 0, 0 ) ) gbSizer1.Add( self.m_button02, wx.GBPosition(", "self.onButton12Click ) self.m_button13.Bind( wx.EVT_BUTTON, self.onButton13Click ) self.m_button14.Bind( wx.EVT_BUTTON, self.onButton14Click )", "), 0 ) self.m_button03.SetBackgroundColour( wx.Colour( 255, 0, 0 ) )", "): event.Skip() def OnMenuSaveSelect( self, event ): event.Skip() def OnMenuQuitSelect(", "wx.Size( 50,50 ), 0 ) self.m_button34.SetBackgroundColour( wx.Colour( 255, 0, 0", "http://www.wxformbuilder.org/ ## ## PLEASE DO *NOT* EDIT THIS FILE! ###########################################################################", "wx.GBSpan( 1, 1 ), wx.ALL, 5 ) self.m_button44 = wx.Button(", "wx.EVT_BUTTON, self.onButton04Click ) self.m_button10.Bind( wx.EVT_BUTTON, self.onButton10Click ) self.m_button11.Bind( wx.EVT_BUTTON, self.onButton11Click", "gbSizer1.Add( self.m_button40, wx.GBPosition( 4, 0 ), wx.GBSpan( 1, 1 ),", "self.m_button23 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ),", "wx.EVT_BUTTON, self.onButton33Click ) self.m_button34.Bind( wx.EVT_BUTTON, self.onButton34Click ) self.m_button40.Bind( wx.EVT_BUTTON, self.onButton40Click", ") self.m_button40.Bind( wx.EVT_BUTTON, self.onButton40Click ) self.m_button41.Bind( wx.EVT_BUTTON, self.onButton41Click ) self.m_button42.Bind(", "self.m_button40.SetBackgroundColour( wx.Colour( 255, 0, 0 ) ) gbSizer1.Add( self.m_button40, wx.GBPosition(", ") self.m_button42.SetBackgroundColour( wx.Colour( 255, 0, 0 ) ) gbSizer1.Add( self.m_button42,", "wx.ID_ANY, u\"Open\", wx.EmptyString, wx.ITEM_NORMAL ) self.m_menu1.Append( self.m_menuItem3 ) self.m_menuItem1 =", "self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button32.SetBackgroundColour(", "event.Skip() def onButton43Click( self, event ): event.Skip() def onButton44Click( self,", "event.Skip() def onButton41Click( self, event ): event.Skip() def onButton42Click( self,", "3 ), wx.GBSpan( 1, 1 ), wx.ALL, 5 ) self.m_button04", "self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button30.SetBackgroundColour(", "def onButton23Click( self, event ): event.Skip() def onButton24Click( self, event", "event ): event.Skip() def onButton10Click( self, event ): event.Skip() def", "5 ) self.m_button14 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size(", "self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button31.SetBackgroundColour(", "50,50 ), 0 ) self.m_button21.SetBackgroundColour( wx.Colour( 255, 0, 0 )", "event handlers, overide them in your derived class def onButton00Click(", "def onButton04Click( self, event ): event.Skip() def onButton10Click( self, event", "wx.GBSpan( 1, 1 ), wx.ALL, 5 ) self.m_button03 = wx.Button(", "), 0 ) self.m_button21.SetBackgroundColour( wx.Colour( 255, 0, 0 ) )", "self.m_button33 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ),", "wx.GBPosition( 0, 4 ), wx.GBSpan( 1, 1 ), wx.ALL, 5", "u\"Open\", wx.EmptyString, wx.ITEM_NORMAL ) self.m_menu1.Append( self.m_menuItem3 ) self.m_menuItem1 = wx.MenuItem(", "code generated with wxFormBuilder (version Aug 8 2018) ## http://www.wxformbuilder.org/", "), wx.GBSpan( 1, 1 ), wx.ALL, 5 ) self.m_button12 =", "1 ), wx.GBSpan( 1, 1 ), wx.ALL, 5 ) self.m_button12", "0, 0 ) ) gbSizer1.Add( self.m_button30, wx.GBPosition( 3, 0 ),", "# Connect Events self.m_button00.Bind( wx.EVT_BUTTON, self.onButton00Click ) self.m_button01.Bind( wx.EVT_BUTTON, self.onButton01Click", "255, 0, 0 ) ) gbSizer1.Add( self.m_button43, wx.GBPosition( 4, 3", "5 ) self.m_button02 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size(", ") self.Bind( wx.EVT_MENU, self.OnExportPythonSelect, id = self.m_menuItem4.GetId() ) def __del__(", "onButton22Click( self, event ): event.Skip() def onButton23Click( self, event ):", "event ): event.Skip() def OnMenuSaveSelect( self, event ): event.Skip() def", "), 0 ) self.m_button10.SetBackgroundColour( wx.Colour( 255, 0, 0 ) )", "self.m_button01.Bind( wx.EVT_BUTTON, self.onButton01Click ) self.m_button02.Bind( wx.EVT_BUTTON, self.onButton02Click ) self.m_button03.Bind( wx.EVT_BUTTON,", "0, 0 ) ) gbSizer1.Add( self.m_button12, wx.GBPosition( 1, 2 ),", "), style = wx.DEFAULT_FRAME_STYLE|wx.TAB_TRAVERSAL ) self.SetSizeHints( wx.DefaultSize, wx.DefaultSize ) gbSizer1", "self.Bind( wx.EVT_MENU, self.OnMenuOpenSelect, id = self.m_menuItem3.GetId() ) self.Bind( wx.EVT_MENU, self.OnMenuSaveSelect,", "## http://www.wxformbuilder.org/ ## ## PLEASE DO *NOT* EDIT THIS FILE!", "gbSizer1.Add( self.m_button23, wx.GBPosition( 2, 3 ), wx.GBSpan( 1, 1 ),", "self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button14.SetBackgroundColour(", "gbSizer1.Add( self.m_button44, wx.GBPosition( 4, 4 ), wx.GBSpan( 1, 1 ),", "5 ) self.m_button10 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size(", "self.m_button12.SetBackgroundColour( wx.Colour( 255, 0, 0 ) ) gbSizer1.Add( self.m_button12, wx.GBPosition(", "wx.GBPosition( 3, 1 ), wx.GBSpan( 1, 1 ), wx.ALL, 5", "0, 0 ) ) gbSizer1.Add( self.m_button13, wx.GBPosition( 1, 3 ),", "## ## PLEASE DO *NOT* EDIT THIS FILE! ########################################################################### import", ") gbSizer1.Add( self.m_button01, wx.GBPosition( 0, 1 ), wx.GBSpan( 1, 1", ") self.Centre( wx.BOTH ) # Connect Events self.m_button00.Bind( wx.EVT_BUTTON, self.onButton00Click", "0 ) gbSizer1.SetFlexibleDirection( wx.BOTH ) gbSizer1.SetNonFlexibleGrowMode( wx.FLEX_GROWMODE_SPECIFIED ) self.m_button00 =", "class MyFrame1 ( wx.Frame ): def __init__( self, parent ):", "wx.GBPosition( 1, 1 ), wx.GBSpan( 1, 1 ), wx.ALL, 5", "), wx.ALL, 5 ) self.m_button21 = wx.Button( self, wx.ID_ANY, wx.EmptyString,", "self.m_menuItem3 = wx.MenuItem( self.m_menu1, wx.ID_ANY, u\"Open\", wx.EmptyString, wx.ITEM_NORMAL ) self.m_menu1.Append(", "): event.Skip() def onButton12Click( self, event ): event.Skip() def onButton13Click(", "0 ), wx.GBSpan( 1, 1 ), wx.ALL, 5 ) self.m_button11", "wx.ALL, 5 ) self.m_button11 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition,", "wx.GBPosition( 1, 0 ), wx.GBSpan( 1, 1 ), wx.ALL, 5", "5 ) self.m_button42 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size(", "self.onButton30Click ) self.m_button31.Bind( wx.EVT_BUTTON, self.onButton31Click ) self.m_button32.Bind( wx.EVT_BUTTON, self.onButton32Click )", "1, 1 ), wx.ALL, 5 ) self.m_button34 = wx.Button( self,", "derived class def onButton00Click( self, event ): event.Skip() def onButton01Click(", "def onButton12Click( self, event ): event.Skip() def onButton13Click( self, event", "gbSizer1.Add( self.m_button21, wx.GBPosition( 2, 1 ), wx.GBSpan( 1, 1 ),", "u\"File\" ) self.m_menu2 = wx.Menu() self.m_menuItem4 = wx.MenuItem( self.m_menu2, wx.ID_ANY,", "), 0 ) self.m_button34.SetBackgroundColour( wx.Colour( 255, 0, 0 ) )", "########################################################################### import wx import wx.xrc ########################################################################### ## Class MyFrame1 ###########################################################################", "1, 1 ), wx.ALL, 5 ) self.m_button04 = wx.Button( self,", "self.m_menu1, wx.ID_ANY, u\"quit\", wx.EmptyString, wx.ITEM_NORMAL ) self.m_menu1.Append( self.m_menuItem2 ) self.m_menubar1.Append(", "<reponame>SaitoYutaka/microbitAnim<filename>microbitAnim.py # -*- coding: utf-8 -*- ########################################################################### ## Python code", "1, 1 ), wx.ALL, 5 ) self.m_button01 = wx.Button( self,", "self.m_button22, wx.GBPosition( 2, 2 ), wx.GBSpan( 1, 1 ), wx.ALL,", "1, 1 ), wx.ALL, 5 ) self.m_button42 = wx.Button( self,", "event ): event.Skip() def onButton14Click( self, event ): event.Skip() def", ") gbSizer1.Add( self.m_button10, wx.GBPosition( 1, 0 ), wx.GBSpan( 1, 1", ") self.m_button34.SetBackgroundColour( wx.Colour( 255, 0, 0 ) ) gbSizer1.Add( self.m_button34,", "255, 0, 0 ) ) gbSizer1.Add( self.m_button10, wx.GBPosition( 1, 0", "255, 0, 0 ) ) gbSizer1.Add( self.m_button42, wx.GBPosition( 4, 2", "), wx.GBSpan( 1, 1 ), wx.ALL, 5 ) self.m_button10 =", "self.SetSizeHints( wx.DefaultSize, wx.DefaultSize ) gbSizer1 = wx.GridBagSizer( 0, 0 )", "0 ) ) gbSizer1.Add( self.m_button10, wx.GBPosition( 1, 0 ), wx.GBSpan(", "utf-8 -*- ########################################################################### ## Python code generated with wxFormBuilder (version", "self.m_button01, wx.GBPosition( 0, 1 ), wx.GBSpan( 1, 1 ), wx.ALL,", "event ): event.Skip() def onButton43Click( self, event ): event.Skip() def", "wx.Colour( 255, 0, 0 ) ) gbSizer1.Add( self.m_button40, wx.GBPosition( 4,", ") gbSizer1.Add( self.m_button21, wx.GBPosition( 2, 1 ), wx.GBSpan( 1, 1", "1, 1 ), wx.ALL, 5 ) self.m_button22 = wx.Button( self,", "DO *NOT* EDIT THIS FILE! ########################################################################### import wx import wx.xrc", "), 0 ) self.m_button43.SetBackgroundColour( wx.Colour( 255, 0, 0 ) )", ") self.m_button34.Bind( wx.EVT_BUTTON, self.onButton34Click ) self.m_button40.Bind( wx.EVT_BUTTON, self.onButton40Click ) self.m_button41.Bind(", "self.m_button44 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ),", "self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button44.SetBackgroundColour(", "): event.Skip() def onButton22Click( self, event ): event.Skip() def onButton23Click(", "4, 2 ), wx.GBSpan( 1, 1 ), wx.ALL, 5 )", "self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button01.SetBackgroundColour(", "self, event ): event.Skip() def OnMenuOpenSelect( self, event ): event.Skip()", "def onButton11Click( self, event ): event.Skip() def onButton12Click( self, event", "), 0 ) self.m_button04.SetBackgroundColour( wx.Colour( 255, 0, 0 ) )", "767,507 ), style = wx.DEFAULT_FRAME_STYLE|wx.TAB_TRAVERSAL ) self.SetSizeHints( wx.DefaultSize, wx.DefaultSize )", "wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button03.SetBackgroundColour( wx.Colour(", "1 ), wx.ALL, 5 ) self.m_button30 = wx.Button( self, wx.ID_ANY,", "self.m_button30.SetBackgroundColour( wx.Colour( 255, 0, 0 ) ) gbSizer1.Add( self.m_button30, wx.GBPosition(", "= wx.MenuItem( self.m_menu1, wx.ID_ANY, u\"quit\", wx.EmptyString, wx.ITEM_NORMAL ) self.m_menu1.Append( self.m_menuItem2", "1, 1 ), wx.ALL, 5 ) self.m_button32 = wx.Button( self,", "self.onButton20Click ) self.m_button21.Bind( wx.EVT_BUTTON, self.onButton21Click ) self.m_button22.Bind( wx.EVT_BUTTON, self.onButton22Click )", "__del__( self ): pass # Virtual event handlers, overide them", "0, 0 ) ) gbSizer1.Add( self.m_button42, wx.GBPosition( 4, 2 ),", "wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button10.SetBackgroundColour( wx.Colour(", "), wx.ALL, 5 ) self.m_button12 = wx.Button( self, wx.ID_ANY, wx.EmptyString,", "wx.EmptyString, pos = wx.Point( 0,0 ), size = wx.Size( 767,507", "with wxFormBuilder (version Aug 8 2018) ## http://www.wxformbuilder.org/ ## ##", "wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button42.SetBackgroundColour( wx.Colour( 255, 0,", "wx.ALL, 5 ) self.m_button31 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition,", "self.m_button43 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ),", "1 ), wx.ALL, 5 ) self.m_button44 = wx.Button( self, wx.ID_ANY,", "= wx.Menu() self.m_menuItem4 = wx.MenuItem( self.m_menu2, wx.ID_ANY, u\"python\", wx.EmptyString, wx.ITEM_NORMAL", "wx.ID_ANY, u\"python\", wx.EmptyString, wx.ITEM_NORMAL ) self.m_menu2.Append( self.m_menuItem4 ) self.m_menubar1.Append( self.m_menu2,", "event.Skip() def onButton02Click( self, event ): event.Skip() def onButton03Click( self,", "def onButton21Click( self, event ): event.Skip() def onButton22Click( self, event", "): event.Skip() def onButton44Click( self, event ): event.Skip() def OnMenuOpenSelect(", "255, 0, 0 ) ) gbSizer1.Add( self.m_button04, wx.GBPosition( 0, 4", "wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button30.SetBackgroundColour( wx.Colour(", "4 ), wx.GBSpan( 1, 1 ), wx.ALL, 5 ) self.m_button40", "), wx.GBSpan( 1, 1 ), wx.ALL, 5 ) self.m_button31 =", "wx.Size( 50,50 ), 0 ) self.m_button30.SetBackgroundColour( wx.Colour( 255, 0, 0", "self.m_button30.Bind( wx.EVT_BUTTON, self.onButton30Click ) self.m_button31.Bind( wx.EVT_BUTTON, self.onButton31Click ) self.m_button32.Bind( wx.EVT_BUTTON,", "0 ) ) gbSizer1.Add( self.m_button34, wx.GBPosition( 3, 4 ), wx.GBSpan(", "self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button02.SetBackgroundColour(", "wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button20.SetBackgroundColour( wx.Colour(", "5 ) self.m_button43 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size(", "self.m_button23.Bind( wx.EVT_BUTTON, self.onButton23Click ) self.m_button24.Bind( wx.EVT_BUTTON, self.onButton24Click ) self.m_button30.Bind( wx.EVT_BUTTON,", "overide them in your derived class def onButton00Click( self, event", "self.m_button11, wx.GBPosition( 1, 1 ), wx.GBSpan( 1, 1 ), wx.ALL,", "wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button44.SetBackgroundColour( wx.Colour(", ") self.m_menu1.Append( self.m_menuItem2 ) self.m_menubar1.Append( self.m_menu1, u\"File\" ) self.m_menu2 =", "wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button20.SetBackgroundColour( wx.Colour( 255,", "0 ) self.m_button44.SetBackgroundColour( wx.Colour( 255, 0, 0 ) ) gbSizer1.Add(", "class def onButton00Click( self, event ): event.Skip() def onButton01Click( self,", ") self.m_button21.SetBackgroundColour( wx.Colour( 255, 0, 0 ) ) gbSizer1.Add( self.m_button21,", "), 0 ) self.m_button40.SetBackgroundColour( wx.Colour( 255, 0, 0 ) )", "wx.Colour( 255, 0, 0 ) ) gbSizer1.Add( self.m_button01, wx.GBPosition( 0,", "5 ) self.m_button31 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size(", "self.m_button13 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ),", "gbSizer1.Add( self.m_button33, wx.GBPosition( 3, 3 ), wx.GBSpan( 1, 1 ),", "wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button44.SetBackgroundColour( wx.Colour( 255, 0,", ") gbSizer1.Add( self.m_button34, wx.GBPosition( 3, 4 ), wx.GBSpan( 1, 1", "5 ) self.m_button23 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size(", "self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button20.SetBackgroundColour(", "gbSizer1.Add( self.m_button42, wx.GBPosition( 4, 2 ), wx.GBSpan( 1, 1 ),", "self, event ): event.Skip() def onButton13Click( self, event ): event.Skip()", "wx.ALL, 5 ) self.m_button42 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition,", ") ) gbSizer1.Add( self.m_button20, wx.GBPosition( 2, 0 ), wx.GBSpan( 1,", "wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button44.SetBackgroundColour( wx.Colour( 255,", "0 ) self.m_button42.SetBackgroundColour( wx.Colour( 255, 0, 0 ) ) gbSizer1.Add(", "wx.ALL, 5 ) self.m_button32 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition,", "wx.GBSpan( 1, 1 ), wx.ALL, 5 ) self.m_button31 = wx.Button(", "), wx.ALL, 5 ) self.m_button02 = wx.Button( self, wx.ID_ANY, wx.EmptyString,", ") self.m_button21.Bind( wx.EVT_BUTTON, self.onButton21Click ) self.m_button22.Bind( wx.EVT_BUTTON, self.onButton22Click ) self.m_button23.Bind(", "wx.ID_ANY, u\"Save\", wx.EmptyString, wx.ITEM_NORMAL ) self.m_menu1.Append( self.m_menuItem1 ) self.m_menuItem2 =", "self.m_menuItem1 = wx.MenuItem( self.m_menu1, wx.ID_ANY, u\"Save\", wx.EmptyString, wx.ITEM_NORMAL ) self.m_menu1.Append(", "1 ), wx.ALL, 5 ) self.m_button02 = wx.Button( self, wx.ID_ANY,", "parent, id = wx.ID_ANY, title = wx.EmptyString, pos = wx.Point(", "parent ): wx.Frame.__init__ ( self, parent, id = wx.ID_ANY, title", "2, 4 ), wx.GBSpan( 1, 1 ), wx.ALL, 5 )", ") self.m_button14.SetBackgroundColour( wx.Colour( 255, 0, 0 ) ) gbSizer1.Add( self.m_button14,", "0,0 ), size = wx.Size( 767,507 ), style = wx.DEFAULT_FRAME_STYLE|wx.TAB_TRAVERSAL", "0 ) ) gbSizer1.Add( self.m_button01, wx.GBPosition( 0, 1 ), wx.GBSpan(", "0, 0 ) ) gbSizer1.Add( self.m_button32, wx.GBPosition( 3, 2 ),", "wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button41.SetBackgroundColour( wx.Colour( 255,", "0 ) self.m_button13.SetBackgroundColour( wx.Colour( 255, 0, 0 ) ) gbSizer1.Add(", "wx import wx.xrc ########################################################################### ## Class MyFrame1 ########################################################################### class MyFrame1", "1, 1 ), wx.ALL, 5 ) self.m_button43 = wx.Button( self,", ") self.Layout() self.m_menubar1 = wx.MenuBar( 0 ) self.m_menu1 = wx.Menu()", "self.onButton10Click ) self.m_button11.Bind( wx.EVT_BUTTON, self.onButton11Click ) self.m_button12.Bind( wx.EVT_BUTTON, self.onButton12Click )", "self.m_button21.Bind( wx.EVT_BUTTON, self.onButton21Click ) self.m_button22.Bind( wx.EVT_BUTTON, self.onButton22Click ) self.m_button23.Bind( wx.EVT_BUTTON,", "255, 0, 0 ) ) gbSizer1.Add( self.m_button02, wx.GBPosition( 0, 2", "wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button40.SetBackgroundColour( wx.Colour(", "gbSizer1.Add( self.m_button10, wx.GBPosition( 1, 0 ), wx.GBSpan( 1, 1 ),", "wx.Size( 50,50 ), 0 ) self.m_button43.SetBackgroundColour( wx.Colour( 255, 0, 0", ") self.m_button00 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50", "event ): event.Skip() def onButton31Click( self, event ): event.Skip() def", ") self.m_button30.SetBackgroundColour( wx.Colour( 255, 0, 0 ) ) gbSizer1.Add( self.m_button30,", "gbSizer1.Add( self.m_button03, wx.GBPosition( 0, 3 ), wx.GBSpan( 1, 1 ),", "style = wx.DEFAULT_FRAME_STYLE|wx.TAB_TRAVERSAL ) self.SetSizeHints( wx.DefaultSize, wx.DefaultSize ) gbSizer1 =", ") self.m_menuItem1 = wx.MenuItem( self.m_menu1, wx.ID_ANY, u\"Save\", wx.EmptyString, wx.ITEM_NORMAL )", "import wx import wx.xrc ########################################################################### ## Class MyFrame1 ########################################################################### class", "0 ) ) gbSizer1.Add( self.m_button13, wx.GBPosition( 1, 3 ), wx.GBSpan(", "0 ) ) gbSizer1.Add( self.m_button32, wx.GBPosition( 3, 2 ), wx.GBSpan(", "wx.GBPosition( 4, 1 ), wx.GBSpan( 1, 1 ), wx.ALL, 5", "wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button31.SetBackgroundColour( wx.Colour(", "4, 3 ), wx.GBSpan( 1, 1 ), wx.ALL, 5 )", "self.onButton40Click ) self.m_button41.Bind( wx.EVT_BUTTON, self.onButton41Click ) self.m_button42.Bind( wx.EVT_BUTTON, self.onButton42Click )", "def __init__( self, parent ): wx.Frame.__init__ ( self, parent, id", "event ): event.Skip() def onButton33Click( self, event ): event.Skip() def", "wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button10.SetBackgroundColour( wx.Colour( 255, 0,", "MyFrame1 ########################################################################### class MyFrame1 ( wx.Frame ): def __init__( self,", "0, 4 ), wx.GBSpan( 1, 1 ), wx.ALL, 5 )", ") self.m_button44.Bind( wx.EVT_BUTTON, self.onButton44Click ) self.Bind( wx.EVT_MENU, self.OnMenuOpenSelect, id =", "self.m_button40.Bind( wx.EVT_BUTTON, self.onButton40Click ) self.m_button41.Bind( wx.EVT_BUTTON, self.onButton41Click ) self.m_button42.Bind( wx.EVT_BUTTON,", "self, event ): event.Skip() def onButton11Click( self, event ): event.Skip()", "wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button00.SetBackgroundColour( wx.Colour( 255, 0,", "self.m_button21 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ),", "= wx.Size( 767,507 ), style = wx.DEFAULT_FRAME_STYLE|wx.TAB_TRAVERSAL ) self.SetSizeHints( wx.DefaultSize,", "self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button33.SetBackgroundColour(", "50,50 ), 0 ) self.m_button03.SetBackgroundColour( wx.Colour( 255, 0, 0 )", "50,50 ), 0 ) self.m_button22.SetBackgroundColour( wx.Colour( 255, 0, 0 )", "0, 0 ) ) gbSizer1.Add( self.m_button44, wx.GBPosition( 4, 4 ),", "= wx.MenuItem( self.m_menu1, wx.ID_ANY, u\"Open\", wx.EmptyString, wx.ITEM_NORMAL ) self.m_menu1.Append( self.m_menuItem3", "onButton21Click( self, event ): event.Skip() def onButton22Click( self, event ):", "onButton30Click( self, event ): event.Skip() def onButton31Click( self, event ):", "wx.ALL, 5 ) self.m_button02 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition,", "1, 0 ), wx.GBSpan( 1, 1 ), wx.ALL, 5 )", "wx.GridBagSizer( 0, 0 ) gbSizer1.SetFlexibleDirection( wx.BOTH ) gbSizer1.SetNonFlexibleGrowMode( wx.FLEX_GROWMODE_SPECIFIED )", "self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button21.SetBackgroundColour(", "1, 1 ), wx.ALL, 5 ) self.m_button44 = wx.Button( self,", ") ) gbSizer1.Add( self.m_button32, wx.GBPosition( 3, 2 ), wx.GBSpan( 1,", "wx.Size( 50,50 ), 0 ) self.m_button03.SetBackgroundColour( wx.Colour( 255, 0, 0", "wx.EVT_BUTTON, self.onButton44Click ) self.Bind( wx.EVT_MENU, self.OnMenuOpenSelect, id = self.m_menuItem3.GetId() )", "): event.Skip() def OnMenuOpenSelect( self, event ): event.Skip() def OnMenuSaveSelect(", "= wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ), 0", "wx.Colour( 255, 0, 0 ) ) gbSizer1.Add( self.m_button31, wx.GBPosition( 3,", ") gbSizer1.Add( self.m_button23, wx.GBPosition( 2, 3 ), wx.GBSpan( 1, 1", "event ): event.Skip() def onButton40Click( self, event ): event.Skip() def", "1, 1 ), wx.ALL, 5 ) self.m_button14 = wx.Button( self,", "event.Skip() def OnMenuSaveSelect( self, event ): event.Skip() def OnMenuQuitSelect( self,", "1 ), wx.ALL, 5 ) self.m_button13 = wx.Button( self, wx.ID_ANY,", ") self.m_button32.SetBackgroundColour( wx.Colour( 255, 0, 0 ) ) gbSizer1.Add( self.m_button32,", "Aug 8 2018) ## http://www.wxformbuilder.org/ ## ## PLEASE DO *NOT*", ") gbSizer1.SetFlexibleDirection( wx.BOTH ) gbSizer1.SetNonFlexibleGrowMode( wx.FLEX_GROWMODE_SPECIFIED ) self.m_button00 = wx.Button(", "gbSizer1.Add( self.m_button34, wx.GBPosition( 3, 4 ), wx.GBSpan( 1, 1 ),", "50,50 ), 0 ) self.m_button11.SetBackgroundColour( wx.Colour( 255, 0, 0 )", "): event.Skip() def onButton01Click( self, event ): event.Skip() def onButton02Click(", "event.Skip() def onButton21Click( self, event ): event.Skip() def onButton22Click( self,", ") self.m_button23 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50", "5 ) self.m_button33 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size(", "), wx.ALL, 5 ) self.m_button20 = wx.Button( self, wx.ID_ANY, wx.EmptyString,", "1, 1 ), wx.ALL, 5 ) self.m_button12 = wx.Button( self,", "wx.GBSpan( 1, 1 ), wx.ALL, 5 ) self.m_button14 = wx.Button(", "gbSizer1.SetFlexibleDirection( wx.BOTH ) gbSizer1.SetNonFlexibleGrowMode( wx.FLEX_GROWMODE_SPECIFIED ) self.m_button00 = wx.Button( self,", "## PLEASE DO *NOT* EDIT THIS FILE! ########################################################################### import wx", "0, 0 ) ) gbSizer1.Add( self.m_button34, wx.GBPosition( 3, 4 ),", "self.m_menuItem1.GetId() ) self.Bind( wx.EVT_MENU, self.OnMenuQuitSelect, id = self.m_menuItem2.GetId() ) self.Bind(", "255, 0, 0 ) ) gbSizer1.Add( self.m_button01, wx.GBPosition( 0, 1", "1 ), wx.ALL, 5 ) self.m_button41 = wx.Button( self, wx.ID_ANY,", "), wx.ALL, 5 ) self.m_button13 = wx.Button( self, wx.ID_ANY, wx.EmptyString,", "), wx.GBSpan( 1, 1 ), wx.ALL, 5 ) self.m_button34 =", "wx.EVT_BUTTON, self.onButton22Click ) self.m_button23.Bind( wx.EVT_BUTTON, self.onButton23Click ) self.m_button24.Bind( wx.EVT_BUTTON, self.onButton24Click", "self.m_menubar1.Append( self.m_menu1, u\"File\" ) self.m_menu2 = wx.Menu() self.m_menuItem4 = wx.MenuItem(", "50,50 ), 0 ) self.m_button02.SetBackgroundColour( wx.Colour( 255, 0, 0 )", "0 ) self.m_button10.SetBackgroundColour( wx.Colour( 255, 0, 0 ) ) gbSizer1.Add(", "gbSizer1.Add( self.m_button43, wx.GBPosition( 4, 3 ), wx.GBSpan( 1, 1 ),", "wx.ALL, 5 ) self.m_button34 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition,", ") self.m_button20 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50", "), wx.ALL, 5 ) self.m_button33 = wx.Button( self, wx.ID_ANY, wx.EmptyString,", "event.Skip() def onButton03Click( self, event ): event.Skip() def onButton04Click( self,", ") gbSizer1.Add( self.m_button24, wx.GBPosition( 2, 4 ), wx.GBSpan( 1, 1", "self.m_menu1, wx.ID_ANY, u\"Save\", wx.EmptyString, wx.ITEM_NORMAL ) self.m_menu1.Append( self.m_menuItem1 ) self.m_menuItem2", "255, 0, 0 ) ) gbSizer1.Add( self.m_button23, wx.GBPosition( 2, 3", "50,50 ), 0 ) self.m_button43.SetBackgroundColour( wx.Colour( 255, 0, 0 )", "wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button24.SetBackgroundColour( wx.Colour(", "), wx.GBSpan( 1, 1 ), wx.ALL, 5 ) self.m_button02 =", "5 ) self.m_button40 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size(", ") self.m_button41.SetBackgroundColour( wx.Colour( 255, 0, 0 ) ) gbSizer1.Add( self.m_button41,", "50,50 ), 0 ) self.m_button44.SetBackgroundColour( wx.Colour( 255, 0, 0 )", ") self.m_menubar1.Append( self.m_menu1, u\"File\" ) self.m_menu2 = wx.Menu() self.m_menuItem4 =", "4 ), wx.GBSpan( 1, 1 ), wx.ALL, 5 ) self.SetSizer(", "Events self.m_button00.Bind( wx.EVT_BUTTON, self.onButton00Click ) self.m_button01.Bind( wx.EVT_BUTTON, self.onButton01Click ) self.m_button02.Bind(", ") self.m_button10 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50", "): event.Skip() def OnMenuQuitSelect( self, event ): event.Skip() def OnExportPythonSelect(", "wx.ALL, 5 ) self.m_button03 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition,", "self, event ): event.Skip() def onButton23Click( self, event ): event.Skip()", "wx.GBSpan( 1, 1 ), wx.ALL, 5 ) self.m_button21 = wx.Button(", "= wx.EmptyString, pos = wx.Point( 0,0 ), size = wx.Size(", "wx.Colour( 255, 0, 0 ) ) gbSizer1.Add( self.m_button03, wx.GBPosition( 0,", "wx.GBPosition( 0, 0 ), wx.GBSpan( 1, 1 ), wx.ALL, 5", "wx.ALL, 5 ) self.m_button10 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition,", "1, 1 ), wx.ALL, 5 ) self.m_button23 = wx.Button( self,", "onButton12Click( self, event ): event.Skip() def onButton13Click( self, event ):", "), wx.GBSpan( 1, 1 ), wx.ALL, 5 ) self.m_button43 =", "0, 2 ), wx.GBSpan( 1, 1 ), wx.ALL, 5 )", "self.m_button11.Bind( wx.EVT_BUTTON, self.onButton11Click ) self.m_button12.Bind( wx.EVT_BUTTON, self.onButton12Click ) self.m_button13.Bind( wx.EVT_BUTTON,", "wx.EVT_BUTTON, self.onButton34Click ) self.m_button40.Bind( wx.EVT_BUTTON, self.onButton40Click ) self.m_button41.Bind( wx.EVT_BUTTON, self.onButton41Click", "self.m_button32 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ),", "OnMenuOpenSelect( self, event ): event.Skip() def OnMenuSaveSelect( self, event ):", "), wx.ALL, 5 ) self.m_button03 = wx.Button( self, wx.ID_ANY, wx.EmptyString,", "wx.ALL, 5 ) self.m_button33 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition,", "wx.ID_ANY, u\"quit\", wx.EmptyString, wx.ITEM_NORMAL ) self.m_menu1.Append( self.m_menuItem2 ) self.m_menubar1.Append( self.m_menu1,", ") self.m_button30 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50", "50,50 ), 0 ) self.m_button40.SetBackgroundColour( wx.Colour( 255, 0, 0 )", "wx.ALL, 5 ) self.m_button12 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition,", "5 ) self.m_button22 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size(", "wx.Colour( 255, 0, 0 ) ) gbSizer1.Add( self.m_button23, wx.GBPosition( 2,", "50,50 ), 0 ) self.m_button24.SetBackgroundColour( wx.Colour( 255, 0, 0 )", "gbSizer1.Add( self.m_button31, wx.GBPosition( 3, 1 ), wx.GBSpan( 1, 1 ),", "wx.ITEM_NORMAL ) self.m_menu2.Append( self.m_menuItem4 ) self.m_menubar1.Append( self.m_menu2, u\"export\" ) self.SetMenuBar(", "): event.Skip() def onButton41Click( self, event ): event.Skip() def onButton42Click(", "wx.Colour( 255, 0, 0 ) ) gbSizer1.Add( self.m_button44, wx.GBPosition( 4,", "self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button04.SetBackgroundColour(", "wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button30.SetBackgroundColour( wx.Colour( 255,", "self, event ): event.Skip() def onButton34Click( self, event ): event.Skip()", "event.Skip() def onButton10Click( self, event ): event.Skip() def onButton11Click( self,", ") gbSizer1.Add( self.m_button14, wx.GBPosition( 1, 4 ), wx.GBSpan( 1, 1", "self.onButton41Click ) self.m_button42.Bind( wx.EVT_BUTTON, self.onButton42Click ) self.m_button43.Bind( wx.EVT_BUTTON, self.onButton43Click )", "## Class MyFrame1 ########################################################################### class MyFrame1 ( wx.Frame ): def", "# -*- coding: utf-8 -*- ########################################################################### ## Python code generated", "255, 0, 0 ) ) gbSizer1.Add( self.m_button03, wx.GBPosition( 0, 3", "0 ) self.m_button04.SetBackgroundColour( wx.Colour( 255, 0, 0 ) ) gbSizer1.Add(", "1 ), wx.ALL, 5 ) self.m_button04 = wx.Button( self, wx.ID_ANY,", "wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button10.SetBackgroundColour( wx.Colour( 255,", "50,50 ), 0 ) self.m_button23.SetBackgroundColour( wx.Colour( 255, 0, 0 )", "onButton31Click( self, event ): event.Skip() def onButton32Click( self, event ):", "1, 4 ), wx.GBSpan( 1, 1 ), wx.ALL, 5 )", "1, 1 ), wx.ALL, 5 ) self.m_button11 = wx.Button( self,", "self.m_button43.Bind( wx.EVT_BUTTON, self.onButton43Click ) self.m_button44.Bind( wx.EVT_BUTTON, self.onButton44Click ) self.Bind( wx.EVT_MENU,", "1, 2 ), wx.GBSpan( 1, 1 ), wx.ALL, 5 )", "self.m_menuItem2.GetId() ) self.Bind( wx.EVT_MENU, self.OnExportPythonSelect, id = self.m_menuItem4.GetId() ) def", "self.m_button12, wx.GBPosition( 1, 2 ), wx.GBSpan( 1, 1 ), wx.ALL,", "255, 0, 0 ) ) gbSizer1.Add( self.m_button22, wx.GBPosition( 2, 2", "1 ), wx.ALL, 5 ) self.m_button22 = wx.Button( self, wx.ID_ANY,", "1 ), wx.ALL, 5 ) self.m_button34 = wx.Button( self, wx.ID_ANY,", "), wx.ALL, 5 ) self.m_button04 = wx.Button( self, wx.ID_ANY, wx.EmptyString,", "), 0 ) self.m_button32.SetBackgroundColour( wx.Colour( 255, 0, 0 ) )", "0 ) self.m_button32.SetBackgroundColour( wx.Colour( 255, 0, 0 ) ) gbSizer1.Add(", ") ) gbSizer1.Add( self.m_button44, wx.GBPosition( 4, 4 ), wx.GBSpan( 1,", ") self.m_button01.Bind( wx.EVT_BUTTON, self.onButton01Click ) self.m_button02.Bind( wx.EVT_BUTTON, self.onButton02Click ) self.m_button03.Bind(", ") self.m_button23.Bind( wx.EVT_BUTTON, self.onButton23Click ) self.m_button24.Bind( wx.EVT_BUTTON, self.onButton24Click ) self.m_button30.Bind(", "), wx.GBSpan( 1, 1 ), wx.ALL, 5 ) self.m_button42 =", "wx.GBPosition( 0, 2 ), wx.GBSpan( 1, 1 ), wx.ALL, 5", "# Virtual event handlers, overide them in your derived class", "title = wx.EmptyString, pos = wx.Point( 0,0 ), size =", ") ) gbSizer1.Add( self.m_button01, wx.GBPosition( 0, 1 ), wx.GBSpan( 1,", "), wx.ALL, 5 ) self.m_button34 = wx.Button( self, wx.ID_ANY, wx.EmptyString,", "event ): event.Skip() def onButton42Click( self, event ): event.Skip() def", "onButton44Click( self, event ): event.Skip() def OnMenuOpenSelect( self, event ):", "def onButton20Click( self, event ): event.Skip() def onButton21Click( self, event", "wx.EVT_BUTTON, self.onButton24Click ) self.m_button30.Bind( wx.EVT_BUTTON, self.onButton30Click ) self.m_button31.Bind( wx.EVT_BUTTON, self.onButton31Click", "wx.DefaultSize, wx.DefaultSize ) gbSizer1 = wx.GridBagSizer( 0, 0 ) gbSizer1.SetFlexibleDirection(", "self.m_button02 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ),", ") ) gbSizer1.Add( self.m_button22, wx.GBPosition( 2, 2 ), wx.GBSpan( 1,", "wx.GBPosition( 2, 3 ), wx.GBSpan( 1, 1 ), wx.ALL, 5", "event.Skip() def onButton44Click( self, event ): event.Skip() def OnMenuOpenSelect( self,", "wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button40.SetBackgroundColour( wx.Colour( 255,", "FILE! ########################################################################### import wx import wx.xrc ########################################################################### ## Class MyFrame1", "wx.GBPosition( 0, 1 ), wx.GBSpan( 1, 1 ), wx.ALL, 5", "), wx.ALL, 5 ) self.m_button24 = wx.Button( self, wx.ID_ANY, wx.EmptyString,", ") ) gbSizer1.Add( self.m_button11, wx.GBPosition( 1, 1 ), wx.GBSpan( 1,", "50,50 ), 0 ) self.m_button04.SetBackgroundColour( wx.Colour( 255, 0, 0 )", "wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button12.SetBackgroundColour( wx.Colour(", ") ) gbSizer1.Add( self.m_button02, wx.GBPosition( 0, 2 ), wx.GBSpan( 1,", ") ) gbSizer1.Add( self.m_button21, wx.GBPosition( 2, 1 ), wx.GBSpan( 1,", "), wx.GBSpan( 1, 1 ), wx.ALL, 5 ) self.m_button33 =", "3 ), wx.GBSpan( 1, 1 ), wx.ALL, 5 ) self.m_button14", "wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button21.SetBackgroundColour( wx.Colour( 255, 0,", "self, event ): event.Skip() def onButton42Click( self, event ): event.Skip()", "wx.EVT_BUTTON, self.onButton32Click ) self.m_button33.Bind( wx.EVT_BUTTON, self.onButton33Click ) self.m_button34.Bind( wx.EVT_BUTTON, self.onButton34Click", "1 ), wx.ALL, 5 ) self.m_button11 = wx.Button( self, wx.ID_ANY,", ") gbSizer1.Add( self.m_button12, wx.GBPosition( 1, 2 ), wx.GBSpan( 1, 1", "wx.ALL, 5 ) self.m_button14 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition,", "self.m_button21.SetBackgroundColour( wx.Colour( 255, 0, 0 ) ) gbSizer1.Add( self.m_button21, wx.GBPosition(", "0, 0 ) ) gbSizer1.Add( self.m_button10, wx.GBPosition( 1, 0 ),", "-*- ########################################################################### ## Python code generated with wxFormBuilder (version Aug", "0, 0 ) ) gbSizer1.Add( self.m_button14, wx.GBPosition( 1, 4 ),", "wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button11.SetBackgroundColour( wx.Colour(", "self.m_menuItem3 ) self.m_menuItem1 = wx.MenuItem( self.m_menu1, wx.ID_ANY, u\"Save\", wx.EmptyString, wx.ITEM_NORMAL", "self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button23.SetBackgroundColour(", "wx.GBPosition( 3, 2 ), wx.GBSpan( 1, 1 ), wx.ALL, 5", "event.Skip() def OnMenuQuitSelect( self, event ): event.Skip() def OnExportPythonSelect( self,", ") self.Bind( wx.EVT_MENU, self.OnMenuSaveSelect, id = self.m_menuItem1.GetId() ) self.Bind( wx.EVT_MENU,", "Class MyFrame1 ########################################################################### class MyFrame1 ( wx.Frame ): def __init__(", "self.m_button22 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ),", "1, 1 ), wx.ALL, 5 ) self.m_button21 = wx.Button( self,", "wx.ALL, 5 ) self.m_button20 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition,", ") self.m_button32.Bind( wx.EVT_BUTTON, self.onButton32Click ) self.m_button33.Bind( wx.EVT_BUTTON, self.onButton33Click ) self.m_button34.Bind(", "wx.EVT_BUTTON, self.onButton43Click ) self.m_button44.Bind( wx.EVT_BUTTON, self.onButton44Click ) self.Bind( wx.EVT_MENU, self.OnMenuOpenSelect,", "gbSizer1.Add( self.m_button13, wx.GBPosition( 1, 3 ), wx.GBSpan( 1, 1 ),", "wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button32.SetBackgroundColour( wx.Colour(", "wx.ID_ANY, title = wx.EmptyString, pos = wx.Point( 0,0 ), size", "50,50 ), 0 ) self.m_button10.SetBackgroundColour( wx.Colour( 255, 0, 0 )", "50,50 ), 0 ) self.m_button12.SetBackgroundColour( wx.Colour( 255, 0, 0 )", "255, 0, 0 ) ) gbSizer1.Add( self.m_button32, wx.GBPosition( 3, 2", "): event.Skip() def onButton03Click( self, event ): event.Skip() def onButton04Click(", "self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button41.SetBackgroundColour(", "1 ), wx.ALL, 5 ) self.SetSizer( gbSizer1 ) self.Layout() self.m_menubar1", "onButton41Click( self, event ): event.Skip() def onButton42Click( self, event ):", "wx.Colour( 255, 0, 0 ) ) gbSizer1.Add( self.m_button11, wx.GBPosition( 1,", "0 ) self.m_button34.SetBackgroundColour( wx.Colour( 255, 0, 0 ) ) gbSizer1.Add(", ") ) gbSizer1.Add( self.m_button31, wx.GBPosition( 3, 1 ), wx.GBSpan( 1,", "self.onButton34Click ) self.m_button40.Bind( wx.EVT_BUTTON, self.onButton40Click ) self.m_button41.Bind( wx.EVT_BUTTON, self.onButton41Click )", "5 ) self.m_button24 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size(", "self.onButton04Click ) self.m_button10.Bind( wx.EVT_BUTTON, self.onButton10Click ) self.m_button11.Bind( wx.EVT_BUTTON, self.onButton11Click )", "onButton03Click( self, event ): event.Skip() def onButton04Click( self, event ):", "event ): event.Skip() def OnMenuQuitSelect( self, event ): event.Skip() def", "wx.GBPosition( 3, 0 ), wx.GBSpan( 1, 1 ), wx.ALL, 5", ") self.m_button12.Bind( wx.EVT_BUTTON, self.onButton12Click ) self.m_button13.Bind( wx.EVT_BUTTON, self.onButton13Click ) self.m_button14.Bind(", "self.m_button10.SetBackgroundColour( wx.Colour( 255, 0, 0 ) ) gbSizer1.Add( self.m_button10, wx.GBPosition(", "wx.ALL, 5 ) self.m_button21 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition,", "wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button31.SetBackgroundColour( wx.Colour( 255,", "event ): event.Skip() def onButton44Click( self, event ): event.Skip() def", "self.m_menu1, u\"File\" ) self.m_menu2 = wx.Menu() self.m_menuItem4 = wx.MenuItem( self.m_menu2,", "wx.Colour( 255, 0, 0 ) ) gbSizer1.Add( self.m_button33, wx.GBPosition( 3,", "1, 1 ), wx.ALL, 5 ) self.m_button10 = wx.Button( self,", "= wx.Menu() self.m_menuItem3 = wx.MenuItem( self.m_menu1, wx.ID_ANY, u\"Open\", wx.EmptyString, wx.ITEM_NORMAL", "0 ) ) gbSizer1.Add( self.m_button23, wx.GBPosition( 2, 3 ), wx.GBSpan(", "( self, parent, id = wx.ID_ANY, title = wx.EmptyString, pos", "4, 4 ), wx.GBSpan( 1, 1 ), wx.ALL, 5 )", "onButton40Click( self, event ): event.Skip() def onButton41Click( self, event ):", "self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button40.SetBackgroundColour(", "self.m_button34 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ),", "self, event ): event.Skip() def onButton21Click( self, event ): event.Skip()", ") self.m_button31.SetBackgroundColour( wx.Colour( 255, 0, 0 ) ) gbSizer1.Add( self.m_button31,", "wx.BOTH ) gbSizer1.SetNonFlexibleGrowMode( wx.FLEX_GROWMODE_SPECIFIED ) self.m_button00 = wx.Button( self, wx.ID_ANY,", "self, parent, id = wx.ID_ANY, title = wx.EmptyString, pos =", "self.SetMenuBar( self.m_menubar1 ) self.Centre( wx.BOTH ) # Connect Events self.m_button00.Bind(", ") self.m_button30.Bind( wx.EVT_BUTTON, self.onButton30Click ) self.m_button31.Bind( wx.EVT_BUTTON, self.onButton31Click ) self.m_button32.Bind(", "0 ) ) gbSizer1.Add( self.m_button03, wx.GBPosition( 0, 3 ), wx.GBSpan(", "), wx.GBSpan( 1, 1 ), wx.ALL, 5 ) self.m_button03 =", "50,50 ), 0 ) self.m_button32.SetBackgroundColour( wx.Colour( 255, 0, 0 )", "wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button11.SetBackgroundColour( wx.Colour( 255, 0,", "self.onButton21Click ) self.m_button22.Bind( wx.EVT_BUTTON, self.onButton22Click ) self.m_button23.Bind( wx.EVT_BUTTON, self.onButton23Click )", "self.m_menu2.Append( self.m_menuItem4 ) self.m_menubar1.Append( self.m_menu2, u\"export\" ) self.SetMenuBar( self.m_menubar1 )", "0 ) ) gbSizer1.Add( self.m_button43, wx.GBPosition( 4, 3 ), wx.GBSpan(", "5 ) self.SetSizer( gbSizer1 ) self.Layout() self.m_menubar1 = wx.MenuBar( 0", "Connect Events self.m_button00.Bind( wx.EVT_BUTTON, self.onButton00Click ) self.m_button01.Bind( wx.EVT_BUTTON, self.onButton01Click )", ") gbSizer1.Add( self.m_button22, wx.GBPosition( 2, 2 ), wx.GBSpan( 1, 1", "self.onButton14Click ) self.m_button20.Bind( wx.EVT_BUTTON, self.onButton20Click ) self.m_button21.Bind( wx.EVT_BUTTON, self.onButton21Click )", "onButton01Click( self, event ): event.Skip() def onButton02Click( self, event ):", "wx.GBSpan( 1, 1 ), wx.ALL, 5 ) self.m_button32 = wx.Button(", ") self.m_button10.SetBackgroundColour( wx.Colour( 255, 0, 0 ) ) gbSizer1.Add( self.m_button10,", "), 0 ) self.m_button20.SetBackgroundColour( wx.Colour( 255, 0, 0 ) )", ") gbSizer1.Add( self.m_button31, wx.GBPosition( 3, 1 ), wx.GBSpan( 1, 1", "wx.Size( 50,50 ), 0 ) self.m_button22.SetBackgroundColour( wx.Colour( 255, 0, 0", "), wx.GBSpan( 1, 1 ), wx.ALL, 5 ) self.m_button32 =", "wx.GBSpan( 1, 1 ), wx.ALL, 5 ) self.m_button04 = wx.Button(", ") gbSizer1.Add( self.m_button44, wx.GBPosition( 4, 4 ), wx.GBSpan( 1, 1", "def onButton24Click( self, event ): event.Skip() def onButton30Click( self, event", "): pass # Virtual event handlers, overide them in your", "5 ) self.m_button13 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size(", "0 ) ) gbSizer1.Add( self.m_button42, wx.GBPosition( 4, 2 ), wx.GBSpan(", ") self.m_button24.Bind( wx.EVT_BUTTON, self.onButton24Click ) self.m_button30.Bind( wx.EVT_BUTTON, self.onButton30Click ) self.m_button31.Bind(", "event ): event.Skip() def onButton41Click( self, event ): event.Skip() def", "(version Aug 8 2018) ## http://www.wxformbuilder.org/ ## ## PLEASE DO", "self.Bind( wx.EVT_MENU, self.OnMenuSaveSelect, id = self.m_menuItem1.GetId() ) self.Bind( wx.EVT_MENU, self.OnMenuQuitSelect,", "wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button13.SetBackgroundColour( wx.Colour( 255, 0,", "wx.Point( 0,0 ), size = wx.Size( 767,507 ), style =", "wx.MenuItem( self.m_menu1, wx.ID_ANY, u\"quit\", wx.EmptyString, wx.ITEM_NORMAL ) self.m_menu1.Append( self.m_menuItem2 )", ") gbSizer1.Add( self.m_button40, wx.GBPosition( 4, 0 ), wx.GBSpan( 1, 1", "wx.Size( 50,50 ), 0 ) self.m_button10.SetBackgroundColour( wx.Colour( 255, 0, 0", "), 0 ) self.m_button13.SetBackgroundColour( wx.Colour( 255, 0, 0 ) )", "50,50 ), 0 ) self.m_button14.SetBackgroundColour( wx.Colour( 255, 0, 0 )", "wx.Size( 50,50 ), 0 ) self.m_button24.SetBackgroundColour( wx.Colour( 255, 0, 0", "), 0 ) self.m_button30.SetBackgroundColour( wx.Colour( 255, 0, 0 ) )", "0 ) ) gbSizer1.Add( self.m_button21, wx.GBPosition( 2, 1 ), wx.GBSpan(", "wx.ITEM_NORMAL ) self.m_menu1.Append( self.m_menuItem3 ) self.m_menuItem1 = wx.MenuItem( self.m_menu1, wx.ID_ANY,", "wx.Colour( 255, 0, 0 ) ) gbSizer1.Add( self.m_button12, wx.GBPosition( 1,", "wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button22.SetBackgroundColour( wx.Colour( 255, 0,", "self.m_button31.SetBackgroundColour( wx.Colour( 255, 0, 0 ) ) gbSizer1.Add( self.m_button31, wx.GBPosition(", ") gbSizer1.SetNonFlexibleGrowMode( wx.FLEX_GROWMODE_SPECIFIED ) self.m_button00 = wx.Button( self, wx.ID_ANY, wx.EmptyString,", "self, event ): event.Skip() def onButton30Click( self, event ): event.Skip()", "255, 0, 0 ) ) gbSizer1.Add( self.m_button13, wx.GBPosition( 1, 3", "), wx.ALL, 5 ) self.m_button10 = wx.Button( self, wx.ID_ANY, wx.EmptyString,", "( wx.Frame ): def __init__( self, parent ): wx.Frame.__init__ (", "self.m_button04.SetBackgroundColour( wx.Colour( 255, 0, 0 ) ) gbSizer1.Add( self.m_button04, wx.GBPosition(", "5 ) self.m_button11 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size(", "event ): event.Skip() def onButton30Click( self, event ): event.Skip() def", "): event.Skip() def onButton34Click( self, event ): event.Skip() def onButton40Click(", "event.Skip() def onButton30Click( self, event ): event.Skip() def onButton31Click( self,", "0 ) ) gbSizer1.Add( self.m_button41, wx.GBPosition( 4, 1 ), wx.GBSpan(", ") self.m_button31 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50", ") ) gbSizer1.Add( self.m_button03, wx.GBPosition( 0, 3 ), wx.GBSpan( 1,", "wx.EVT_BUTTON, self.onButton00Click ) self.m_button01.Bind( wx.EVT_BUTTON, self.onButton01Click ) self.m_button02.Bind( wx.EVT_BUTTON, self.onButton02Click", "self.onButton13Click ) self.m_button14.Bind( wx.EVT_BUTTON, self.onButton14Click ) self.m_button20.Bind( wx.EVT_BUTTON, self.onButton20Click )", ") self.m_button22.Bind( wx.EVT_BUTTON, self.onButton22Click ) self.m_button23.Bind( wx.EVT_BUTTON, self.onButton23Click ) self.m_button24.Bind(", "): event.Skip() def onButton43Click( self, event ): event.Skip() def onButton44Click(", "3, 0 ), wx.GBSpan( 1, 1 ), wx.ALL, 5 )", "wx.Colour( 255, 0, 0 ) ) gbSizer1.Add( self.m_button20, wx.GBPosition( 2,", "0 ) self.m_button43.SetBackgroundColour( wx.Colour( 255, 0, 0 ) ) gbSizer1.Add(", "), wx.GBSpan( 1, 1 ), wx.ALL, 5 ) self.m_button40 =", "gbSizer1.Add( self.m_button12, wx.GBPosition( 1, 2 ), wx.GBSpan( 1, 1 ),", ") self.m_button13.SetBackgroundColour( wx.Colour( 255, 0, 0 ) ) gbSizer1.Add( self.m_button13,", "0, 0 ) ) gbSizer1.Add( self.m_button23, wx.GBPosition( 2, 3 ),", "wx.ITEM_NORMAL ) self.m_menu1.Append( self.m_menuItem1 ) self.m_menuItem2 = wx.MenuItem( self.m_menu1, wx.ID_ANY,", "wx.EVT_BUTTON, self.onButton20Click ) self.m_button21.Bind( wx.EVT_BUTTON, self.onButton21Click ) self.m_button22.Bind( wx.EVT_BUTTON, self.onButton22Click", "def OnMenuQuitSelect( self, event ): event.Skip() def OnExportPythonSelect( self, event", ") self.m_button20.Bind( wx.EVT_BUTTON, self.onButton20Click ) self.m_button21.Bind( wx.EVT_BUTTON, self.onButton21Click ) self.m_button22.Bind(", "self.Layout() self.m_menubar1 = wx.MenuBar( 0 ) self.m_menu1 = wx.Menu() self.m_menuItem3", ") self.m_button33.Bind( wx.EVT_BUTTON, self.onButton33Click ) self.m_button34.Bind( wx.EVT_BUTTON, self.onButton34Click ) self.m_button40.Bind(", "wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button33.SetBackgroundColour( wx.Colour( 255, 0,", ") self.m_menu1.Append( self.m_menuItem1 ) self.m_menuItem2 = wx.MenuItem( self.m_menu1, wx.ID_ANY, u\"quit\",", "self, event ): event.Skip() def onButton03Click( self, event ): event.Skip()", "1, 1 ), wx.ALL, 5 ) self.m_button30 = wx.Button( self,", "wx.Colour( 255, 0, 0 ) ) gbSizer1.Add( self.m_button24, wx.GBPosition( 2,", "1 ), wx.ALL, 5 ) self.m_button43 = wx.Button( self, wx.ID_ANY,", ") self.m_button23.SetBackgroundColour( wx.Colour( 255, 0, 0 ) ) gbSizer1.Add( self.m_button23,", ") self.m_button00.SetBackgroundColour( wx.Colour( 255, 0, 0 ) ) gbSizer1.Add( self.m_button00,", "self.m_menu1.Append( self.m_menuItem1 ) self.m_menuItem2 = wx.MenuItem( self.m_menu1, wx.ID_ANY, u\"quit\", wx.EmptyString,", "wx.EVT_MENU, self.OnMenuOpenSelect, id = self.m_menuItem3.GetId() ) self.Bind( wx.EVT_MENU, self.OnMenuSaveSelect, id", "self.Bind( wx.EVT_MENU, self.OnMenuQuitSelect, id = self.m_menuItem2.GetId() ) self.Bind( wx.EVT_MENU, self.OnExportPythonSelect,", "wx.GBPosition( 3, 3 ), wx.GBSpan( 1, 1 ), wx.ALL, 5", "0, 0 ) gbSizer1.SetFlexibleDirection( wx.BOTH ) gbSizer1.SetNonFlexibleGrowMode( wx.FLEX_GROWMODE_SPECIFIED ) self.m_button00", "gbSizer1.SetNonFlexibleGrowMode( wx.FLEX_GROWMODE_SPECIFIED ) self.m_button00 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition,", ") gbSizer1 = wx.GridBagSizer( 0, 0 ) gbSizer1.SetFlexibleDirection( wx.BOTH )", ") self.m_button24.SetBackgroundColour( wx.Colour( 255, 0, 0 ) ) gbSizer1.Add( self.m_button24,", ") gbSizer1.Add( self.m_button03, wx.GBPosition( 0, 3 ), wx.GBSpan( 1, 1", "self.m_menuItem2 ) self.m_menubar1.Append( self.m_menu1, u\"File\" ) self.m_menu2 = wx.Menu() self.m_menuItem4", "self.m_menu1.Append( self.m_menuItem2 ) self.m_menubar1.Append( self.m_menu1, u\"File\" ) self.m_menu2 = wx.Menu()", "wx.EVT_BUTTON, self.onButton01Click ) self.m_button02.Bind( wx.EVT_BUTTON, self.onButton02Click ) self.m_button03.Bind( wx.EVT_BUTTON, self.onButton03Click", "onButton13Click( self, event ): event.Skip() def onButton14Click( self, event ):", "self, event ): event.Skip() def onButton44Click( self, event ): event.Skip()", "wx.Colour( 255, 0, 0 ) ) gbSizer1.Add( self.m_button43, wx.GBPosition( 4,", "onButton20Click( self, event ): event.Skip() def onButton21Click( self, event ):", "wx.EVT_MENU, self.OnMenuSaveSelect, id = self.m_menuItem1.GetId() ) self.Bind( wx.EVT_MENU, self.OnMenuQuitSelect, id", "0, 0 ) ) gbSizer1.Add( self.m_button21, wx.GBPosition( 2, 1 ),", "wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button02.SetBackgroundColour( wx.Colour(", "0 ), wx.GBSpan( 1, 1 ), wx.ALL, 5 ) self.m_button21", "########################################################################### ## Class MyFrame1 ########################################################################### class MyFrame1 ( wx.Frame ):", "event.Skip() def onButton42Click( self, event ): event.Skip() def onButton43Click( self,", "1 ), wx.GBSpan( 1, 1 ), wx.ALL, 5 ) self.m_button42", "1 ), wx.GBSpan( 1, 1 ), wx.ALL, 5 ) self.m_button32", "def onButton22Click( self, event ): event.Skip() def onButton23Click( self, event", ") self.m_button31.Bind( wx.EVT_BUTTON, self.onButton31Click ) self.m_button32.Bind( wx.EVT_BUTTON, self.onButton32Click ) self.m_button33.Bind(", "wx.Colour( 255, 0, 0 ) ) gbSizer1.Add( self.m_button42, wx.GBPosition( 4,", ") self.SetSizer( gbSizer1 ) self.Layout() self.m_menubar1 = wx.MenuBar( 0 )", "def onButton34Click( self, event ): event.Skip() def onButton40Click( self, event", "wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button42.SetBackgroundColour( wx.Colour(", "wx.Size( 50,50 ), 0 ) self.m_button40.SetBackgroundColour( wx.Colour( 255, 0, 0", "wx.EVT_BUTTON, self.onButton11Click ) self.m_button12.Bind( wx.EVT_BUTTON, self.onButton12Click ) self.m_button13.Bind( wx.EVT_BUTTON, self.onButton13Click", "event ): event.Skip() def onButton23Click( self, event ): event.Skip() def", ") self.SetSizeHints( wx.DefaultSize, wx.DefaultSize ) gbSizer1 = wx.GridBagSizer( 0, 0", "0 ) self.m_button11.SetBackgroundColour( wx.Colour( 255, 0, 0 ) ) gbSizer1.Add(", "1 ), wx.GBSpan( 1, 1 ), wx.ALL, 5 ) self.m_button22", "event ): event.Skip() def onButton20Click( self, event ): event.Skip() def", "= wx.MenuItem( self.m_menu2, wx.ID_ANY, u\"python\", wx.EmptyString, wx.ITEM_NORMAL ) self.m_menu2.Append( self.m_menuItem4", "event ): event.Skip() def onButton01Click( self, event ): event.Skip() def", "onButton43Click( self, event ): event.Skip() def onButton44Click( self, event ):", "wx.GBSpan( 1, 1 ), wx.ALL, 5 ) self.m_button30 = wx.Button(", "your derived class def onButton00Click( self, event ): event.Skip() def", ") ) gbSizer1.Add( self.m_button30, wx.GBPosition( 3, 0 ), wx.GBSpan( 1,", "), wx.ALL, 5 ) self.m_button30 = wx.Button( self, wx.ID_ANY, wx.EmptyString,", ") self.m_button01 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50", "wx.Size( 50,50 ), 0 ) self.m_button33.SetBackgroundColour( wx.Colour( 255, 0, 0", "Virtual event handlers, overide them in your derived class def", "self, event ): event.Skip() def onButton01Click( self, event ): event.Skip()", "), wx.ALL, 5 ) self.m_button41 = wx.Button( self, wx.ID_ANY, wx.EmptyString,", "wx.Size( 50,50 ), 0 ) self.m_button41.SetBackgroundColour( wx.Colour( 255, 0, 0", "id = self.m_menuItem3.GetId() ) self.Bind( wx.EVT_MENU, self.OnMenuSaveSelect, id = self.m_menuItem1.GetId()", "size = wx.Size( 767,507 ), style = wx.DEFAULT_FRAME_STYLE|wx.TAB_TRAVERSAL ) self.SetSizeHints(", "= wx.GridBagSizer( 0, 0 ) gbSizer1.SetFlexibleDirection( wx.BOTH ) gbSizer1.SetNonFlexibleGrowMode( wx.FLEX_GROWMODE_SPECIFIED", "self, event ): event.Skip() def onButton24Click( self, event ): event.Skip()", "gbSizer1.Add( self.m_button01, wx.GBPosition( 0, 1 ), wx.GBSpan( 1, 1 ),", ") self.m_button11.Bind( wx.EVT_BUTTON, self.onButton11Click ) self.m_button12.Bind( wx.EVT_BUTTON, self.onButton12Click ) self.m_button13.Bind(", "0, 0 ) ) gbSizer1.Add( self.m_button04, wx.GBPosition( 0, 4 ),", "wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button14.SetBackgroundColour( wx.Colour(", "wx.EVT_BUTTON, self.onButton21Click ) self.m_button22.Bind( wx.EVT_BUTTON, self.onButton22Click ) self.m_button23.Bind( wx.EVT_BUTTON, self.onButton23Click", "5 ) self.m_button21 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size(", "__init__( self, parent ): wx.Frame.__init__ ( self, parent, id =", "1 ), wx.ALL, 5 ) self.m_button24 = wx.Button( self, wx.ID_ANY,", "= wx.Point( 0,0 ), size = wx.Size( 767,507 ), style", ") self.m_button41.Bind( wx.EVT_BUTTON, self.onButton41Click ) self.m_button42.Bind( wx.EVT_BUTTON, self.onButton42Click ) self.m_button43.Bind(", "event ): event.Skip() def onButton13Click( self, event ): event.Skip() def", "wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button33.SetBackgroundColour( wx.Colour(", "self.m_button33.SetBackgroundColour( wx.Colour( 255, 0, 0 ) ) gbSizer1.Add( self.m_button33, wx.GBPosition(", "0 ) self.m_button24.SetBackgroundColour( wx.Colour( 255, 0, 0 ) ) gbSizer1.Add(", "2 ), wx.GBSpan( 1, 1 ), wx.ALL, 5 ) self.m_button03", ") gbSizer1.Add( self.m_button11, wx.GBPosition( 1, 1 ), wx.GBSpan( 1, 1", "): event.Skip() def onButton14Click( self, event ): event.Skip() def onButton20Click(", "wx.MenuItem( self.m_menu2, wx.ID_ANY, u\"python\", wx.EmptyString, wx.ITEM_NORMAL ) self.m_menu2.Append( self.m_menuItem4 )", "def onButton01Click( self, event ): event.Skip() def onButton02Click( self, event", "self, event ): event.Skip() def onButton43Click( self, event ): event.Skip()", "2 ), wx.GBSpan( 1, 1 ), wx.ALL, 5 ) self.m_button13", "wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button01.SetBackgroundColour( wx.Colour(", "self.m_button30, wx.GBPosition( 3, 0 ), wx.GBSpan( 1, 1 ), wx.ALL,", "wx.GBSpan( 1, 1 ), wx.ALL, 5 ) self.SetSizer( gbSizer1 )", "self.m_menubar1 = wx.MenuBar( 0 ) self.m_menu1 = wx.Menu() self.m_menuItem3 =", "): event.Skip() def onButton04Click( self, event ): event.Skip() def onButton10Click(", "self.m_button21, wx.GBPosition( 2, 1 ), wx.GBSpan( 1, 1 ), wx.ALL,", "self, event ): event.Skip() def onButton40Click( self, event ): event.Skip()", "onButton23Click( self, event ): event.Skip() def onButton24Click( self, event ):", "0 ) ) gbSizer1.Add( self.m_button02, wx.GBPosition( 0, 2 ), wx.GBSpan(", "wx.GBSpan( 1, 1 ), wx.ALL, 5 ) self.m_button20 = wx.Button(", "), wx.GBSpan( 1, 1 ), wx.ALL, 5 ) self.m_button01 =", "self.m_button23.SetBackgroundColour( wx.Colour( 255, 0, 0 ) ) gbSizer1.Add( self.m_button23, wx.GBPosition(", "########################################################################### ## Python code generated with wxFormBuilder (version Aug 8", "wx.MenuItem( self.m_menu1, wx.ID_ANY, u\"Save\", wx.EmptyString, wx.ITEM_NORMAL ) self.m_menu1.Append( self.m_menuItem1 )", "self, event ): event.Skip() def onButton33Click( self, event ): event.Skip()", "self.onButton01Click ) self.m_button02.Bind( wx.EVT_BUTTON, self.onButton02Click ) self.m_button03.Bind( wx.EVT_BUTTON, self.onButton03Click )", "self.m_button00 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ),", "wx.EVT_BUTTON, self.onButton02Click ) self.m_button03.Bind( wx.EVT_BUTTON, self.onButton03Click ) self.m_button04.Bind( wx.EVT_BUTTON, self.onButton04Click", "): def __init__( self, parent ): wx.Frame.__init__ ( self, parent,", "self.m_button20 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ),", "self.m_button41 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ),", "in your derived class def onButton00Click( self, event ): event.Skip()", "self.m_button11.SetBackgroundColour( wx.Colour( 255, 0, 0 ) ) gbSizer1.Add( self.m_button11, wx.GBPosition(", "wx.ALL, 5 ) self.m_button13 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition,", "self.m_button31.Bind( wx.EVT_BUTTON, self.onButton31Click ) self.m_button32.Bind( wx.EVT_BUTTON, self.onButton32Click ) self.m_button33.Bind( wx.EVT_BUTTON,", ") self.Bind( wx.EVT_MENU, self.OnMenuOpenSelect, id = self.m_menuItem3.GetId() ) self.Bind( wx.EVT_MENU,", "self.SetSizer( gbSizer1 ) self.Layout() self.m_menubar1 = wx.MenuBar( 0 ) self.m_menu1", "id = self.m_menuItem1.GetId() ) self.Bind( wx.EVT_MENU, self.OnMenuQuitSelect, id = self.m_menuItem2.GetId()", "self.m_button43.SetBackgroundColour( wx.Colour( 255, 0, 0 ) ) gbSizer1.Add( self.m_button43, wx.GBPosition(", "def onButton31Click( self, event ): event.Skip() def onButton32Click( self, event", "wx.Size( 50,50 ), 0 ) self.m_button12.SetBackgroundColour( wx.Colour( 255, 0, 0", "0 ) self.m_button21.SetBackgroundColour( wx.Colour( 255, 0, 0 ) ) gbSizer1.Add(", "self.m_button10.Bind( wx.EVT_BUTTON, self.onButton10Click ) self.m_button11.Bind( wx.EVT_BUTTON, self.onButton11Click ) self.m_button12.Bind( wx.EVT_BUTTON,", "self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button03.SetBackgroundColour(", "0 ) self.m_button00.SetBackgroundColour( wx.Colour( 255, 0, 0 ) ) gbSizer1.Add(", "0, 0 ) ) gbSizer1.Add( self.m_button43, wx.GBPosition( 4, 3 ),", ") self.m_button12.SetBackgroundColour( wx.Colour( 255, 0, 0 ) ) gbSizer1.Add( self.m_button12,", "1 ), wx.GBSpan( 1, 1 ), wx.ALL, 5 ) self.m_button02", "1, 1 ), wx.ALL, 5 ) self.m_button03 = wx.Button( self,", "wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button13.SetBackgroundColour( wx.Colour( 255,", "0 ) self.m_button33.SetBackgroundColour( wx.Colour( 255, 0, 0 ) ) gbSizer1.Add(", "wx.Frame ): def __init__( self, parent ): wx.Frame.__init__ ( self,", ") gbSizer1.Add( self.m_button13, wx.GBPosition( 1, 3 ), wx.GBSpan( 1, 1", "), wx.GBSpan( 1, 1 ), wx.ALL, 5 ) self.m_button04 =", "self.m_button30 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ),", "wx.EVT_BUTTON, self.onButton23Click ) self.m_button24.Bind( wx.EVT_BUTTON, self.onButton24Click ) self.m_button30.Bind( wx.EVT_BUTTON, self.onButton30Click", "), wx.GBSpan( 1, 1 ), wx.ALL, 5 ) self.m_button21 =", "wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button00.SetBackgroundColour( wx.Colour( 255,", "wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button04.SetBackgroundColour( wx.Colour(", "): event.Skip() def onButton20Click( self, event ): event.Skip() def onButton21Click(", "): event.Skip() def onButton40Click( self, event ): event.Skip() def onButton41Click(", "gbSizer1.Add( self.m_button24, wx.GBPosition( 2, 4 ), wx.GBSpan( 1, 1 ),", "self.m_button04 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ),", "= wx.MenuItem( self.m_menu1, wx.ID_ANY, u\"Save\", wx.EmptyString, wx.ITEM_NORMAL ) self.m_menu1.Append( self.m_menuItem1", "wx.GBPosition( 1, 3 ), wx.GBSpan( 1, 1 ), wx.ALL, 5", ") self.m_button34 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50", "def OnMenuOpenSelect( self, event ): event.Skip() def OnMenuSaveSelect( self, event", "wx.Size( 50,50 ), 0 ) self.m_button14.SetBackgroundColour( wx.Colour( 255, 0, 0", "), 0 ) self.m_button42.SetBackgroundColour( wx.Colour( 255, 0, 0 ) )", ") self.m_button03.Bind( wx.EVT_BUTTON, self.onButton03Click ) self.m_button04.Bind( wx.EVT_BUTTON, self.onButton04Click ) self.m_button10.Bind(", "wx.ALL, 5 ) self.m_button04 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition,", "wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button20.SetBackgroundColour( wx.Colour( 255, 0,", "= wx.DEFAULT_FRAME_STYLE|wx.TAB_TRAVERSAL ) self.SetSizeHints( wx.DefaultSize, wx.DefaultSize ) gbSizer1 = wx.GridBagSizer(", "wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button01.SetBackgroundColour( wx.Colour( 255,", ") self.m_button14 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50", "wx.GBSpan( 1, 1 ), wx.ALL, 5 ) self.m_button01 = wx.Button(", "self.onButton42Click ) self.m_button43.Bind( wx.EVT_BUTTON, self.onButton43Click ) self.m_button44.Bind( wx.EVT_BUTTON, self.onButton44Click )", "5 ) self.m_button12 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size(", ") self.m_button02.SetBackgroundColour( wx.Colour( 255, 0, 0 ) ) gbSizer1.Add( self.m_button02,", ") self.m_button10.Bind( wx.EVT_BUTTON, self.onButton10Click ) self.m_button11.Bind( wx.EVT_BUTTON, self.onButton11Click ) self.m_button12.Bind(", "wx.EmptyString, wx.ITEM_NORMAL ) self.m_menu2.Append( self.m_menuItem4 ) self.m_menubar1.Append( self.m_menu2, u\"export\" )", "0 ) self.m_button12.SetBackgroundColour( wx.Colour( 255, 0, 0 ) ) gbSizer1.Add(", "def onButton13Click( self, event ): event.Skip() def onButton14Click( self, event", "1 ), wx.ALL, 5 ) self.m_button32 = wx.Button( self, wx.ID_ANY,", "0 ) ) gbSizer1.Add( self.m_button00, wx.GBPosition( 0, 0 ), wx.GBSpan(", "wx.EmptyString, wx.ITEM_NORMAL ) self.m_menu1.Append( self.m_menuItem3 ) self.m_menuItem1 = wx.MenuItem( self.m_menu1,", "), wx.GBSpan( 1, 1 ), wx.ALL, 5 ) self.m_button22 =", "1, 1 ), wx.ALL, 5 ) self.m_button24 = wx.Button( self,", ") # Connect Events self.m_button00.Bind( wx.EVT_BUTTON, self.onButton00Click ) self.m_button01.Bind( wx.EVT_BUTTON,", "wx.GBSpan( 1, 1 ), wx.ALL, 5 ) self.m_button22 = wx.Button(", "self.m_button00, wx.GBPosition( 0, 0 ), wx.GBSpan( 1, 1 ), wx.ALL,", ") self.m_button03.SetBackgroundColour( wx.Colour( 255, 0, 0 ) ) gbSizer1.Add( self.m_button03,", "event.Skip() def onButton01Click( self, event ): event.Skip() def onButton02Click( self,", "wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button00.SetBackgroundColour( wx.Colour(", "self.m_button10, wx.GBPosition( 1, 0 ), wx.GBSpan( 1, 1 ), wx.ALL,", ") self.m_menuItem2 = wx.MenuItem( self.m_menu1, wx.ID_ANY, u\"quit\", wx.EmptyString, wx.ITEM_NORMAL )", "), 0 ) self.m_button14.SetBackgroundColour( wx.Colour( 255, 0, 0 ) )", "0, 0 ) ) gbSizer1.Add( self.m_button31, wx.GBPosition( 3, 1 ),", "5 ) self.m_button41 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size(", "u\"export\" ) self.SetMenuBar( self.m_menubar1 ) self.Centre( wx.BOTH ) # Connect", "4, 0 ), wx.GBSpan( 1, 1 ), wx.ALL, 5 )", "1, 1 ), wx.ALL, 5 ) self.m_button20 = wx.Button( self,", "1 ), wx.ALL, 5 ) self.m_button12 = wx.Button( self, wx.ID_ANY,", "), 0 ) self.m_button01.SetBackgroundColour( wx.Colour( 255, 0, 0 ) )", "wx.ALL, 5 ) self.m_button01 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition,", "): event.Skip() def onButton33Click( self, event ): event.Skip() def onButton34Click(", "OnMenuSaveSelect( self, event ): event.Skip() def OnMenuQuitSelect( self, event ):", "onButton34Click( self, event ): event.Skip() def onButton40Click( self, event ):", "3, 2 ), wx.GBSpan( 1, 1 ), wx.ALL, 5 )", "wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button03.SetBackgroundColour( wx.Colour( 255,", "0 ) self.m_button41.SetBackgroundColour( wx.Colour( 255, 0, 0 ) ) gbSizer1.Add(", "wx.EVT_MENU, self.OnMenuQuitSelect, id = self.m_menuItem2.GetId() ) self.Bind( wx.EVT_MENU, self.OnExportPythonSelect, id", "255, 0, 0 ) ) gbSizer1.Add( self.m_button40, wx.GBPosition( 4, 0", "wx.EVT_BUTTON, self.onButton40Click ) self.m_button41.Bind( wx.EVT_BUTTON, self.onButton41Click ) self.m_button42.Bind( wx.EVT_BUTTON, self.onButton42Click", "self, event ): event.Skip() def onButton12Click( self, event ): event.Skip()", "self.m_button31 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ),", ") gbSizer1.Add( self.m_button20, wx.GBPosition( 2, 0 ), wx.GBSpan( 1, 1", "wx.Size( 50,50 ), 0 ) self.m_button32.SetBackgroundColour( wx.Colour( 255, 0, 0", ") self.m_button22.SetBackgroundColour( wx.Colour( 255, 0, 0 ) ) gbSizer1.Add( self.m_button22,", ") self.m_button32 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50", "*NOT* EDIT THIS FILE! ########################################################################### import wx import wx.xrc ###########################################################################", "handlers, overide them in your derived class def onButton00Click( self,", "wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button04.SetBackgroundColour( wx.Colour( 255, 0,", "255, 0, 0 ) ) gbSizer1.Add( self.m_button12, wx.GBPosition( 1, 2", "50,50 ), 0 ) self.m_button20.SetBackgroundColour( wx.Colour( 255, 0, 0 )", "), wx.GBSpan( 1, 1 ), wx.ALL, 5 ) self.m_button44 =", "wx.EmptyString, wx.ITEM_NORMAL ) self.m_menu1.Append( self.m_menuItem2 ) self.m_menubar1.Append( self.m_menu1, u\"File\" )", "self.m_menu1.Append( self.m_menuItem3 ) self.m_menuItem1 = wx.MenuItem( self.m_menu1, wx.ID_ANY, u\"Save\", wx.EmptyString,", "), 0 ) self.m_button00.SetBackgroundColour( wx.Colour( 255, 0, 0 ) )", "wx.GBSpan( 1, 1 ), wx.ALL, 5 ) self.m_button02 = wx.Button(", "self.m_button20.Bind( wx.EVT_BUTTON, self.onButton20Click ) self.m_button21.Bind( wx.EVT_BUTTON, self.onButton21Click ) self.m_button22.Bind( wx.EVT_BUTTON,", "5 ) self.m_button44 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size(", "wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button34.SetBackgroundColour( wx.Colour(", "1, 1 ), wx.ALL, 5 ) self.SetSizer( gbSizer1 ) self.Layout()", "def onButton03Click( self, event ): event.Skip() def onButton04Click( self, event", "onButton42Click( self, event ): event.Skip() def onButton43Click( self, event ):", "0, 0 ), wx.GBSpan( 1, 1 ), wx.ALL, 5 )", "5 ) self.m_button20 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size(", "wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button34.SetBackgroundColour( wx.Colour( 255, 0,", "255, 0, 0 ) ) gbSizer1.Add( self.m_button41, wx.GBPosition( 4, 1", "self, event ): event.Skip() def OnMenuSaveSelect( self, event ): event.Skip()", "gbSizer1.Add( self.m_button00, wx.GBPosition( 0, 0 ), wx.GBSpan( 1, 1 ),", "wx.Size( 50,50 ), 0 ) self.m_button20.SetBackgroundColour( wx.Colour( 255, 0, 0", "255, 0, 0 ) ) gbSizer1.Add( self.m_button21, wx.GBPosition( 2, 1", "self.m_button02, wx.GBPosition( 0, 2 ), wx.GBSpan( 1, 1 ), wx.ALL,", "self.m_button24 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ),", "255, 0, 0 ) ) gbSizer1.Add( self.m_button24, wx.GBPosition( 2, 4", "wx.GBSpan( 1, 1 ), wx.ALL, 5 ) self.m_button10 = wx.Button(", "4, 1 ), wx.GBSpan( 1, 1 ), wx.ALL, 5 )", "def onButton33Click( self, event ): event.Skip() def onButton34Click( self, event", ") self.SetMenuBar( self.m_menubar1 ) self.Centre( wx.BOTH ) # Connect Events", "0 ) self.m_button14.SetBackgroundColour( wx.Colour( 255, 0, 0 ) ) gbSizer1.Add(", "3, 3 ), wx.GBSpan( 1, 1 ), wx.ALL, 5 )", "self.m_button22.SetBackgroundColour( wx.Colour( 255, 0, 0 ) ) gbSizer1.Add( self.m_button22, wx.GBPosition(", ") self.m_button44.SetBackgroundColour( wx.Colour( 255, 0, 0 ) ) gbSizer1.Add( self.m_button44,", "50,50 ), 0 ) self.m_button00.SetBackgroundColour( wx.Colour( 255, 0, 0 )", "), 0 ) self.m_button11.SetBackgroundColour( wx.Colour( 255, 0, 0 ) )", "wx.ALL, 5 ) self.m_button40 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition,", "4 ), wx.GBSpan( 1, 1 ), wx.ALL, 5 ) self.m_button20", "wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button14.SetBackgroundColour( wx.Colour( 255, 0,", "0, 0 ) ) gbSizer1.Add( self.m_button00, wx.GBPosition( 0, 0 ),", "2, 1 ), wx.GBSpan( 1, 1 ), wx.ALL, 5 )", "0, 0 ) ) gbSizer1.Add( self.m_button03, wx.GBPosition( 0, 3 ),", "0 ) ) gbSizer1.Add( self.m_button04, wx.GBPosition( 0, 4 ), wx.GBSpan(", "2, 2 ), wx.GBSpan( 1, 1 ), wx.ALL, 5 )", "wx.ALL, 5 ) self.m_button30 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition,", "self.m_button20.SetBackgroundColour( wx.Colour( 255, 0, 0 ) ) gbSizer1.Add( self.m_button20, wx.GBPosition(", "self.onButton32Click ) self.m_button33.Bind( wx.EVT_BUTTON, self.onButton33Click ) self.m_button34.Bind( wx.EVT_BUTTON, self.onButton34Click )", "wx.GBPosition( 4, 2 ), wx.GBSpan( 1, 1 ), wx.ALL, 5", "), 0 ) self.m_button31.SetBackgroundColour( wx.Colour( 255, 0, 0 ) )", "def onButton02Click( self, event ): event.Skip() def onButton03Click( self, event", "gbSizer1.Add( self.m_button11, wx.GBPosition( 1, 1 ), wx.GBSpan( 1, 1 ),", "1 ), wx.ALL, 5 ) self.m_button40 = wx.Button( self, wx.ID_ANY,", "wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button41.SetBackgroundColour( wx.Colour( 255, 0,", "8 2018) ## http://www.wxformbuilder.org/ ## ## PLEASE DO *NOT* EDIT", "0, 0 ) ) gbSizer1.Add( self.m_button40, wx.GBPosition( 4, 0 ),", ") ) gbSizer1.Add( self.m_button14, wx.GBPosition( 1, 4 ), wx.GBSpan( 1,", ") self.m_button42.Bind( wx.EVT_BUTTON, self.onButton42Click ) self.m_button43.Bind( wx.EVT_BUTTON, self.onButton43Click ) self.m_button44.Bind(", "0 ) self.m_button23.SetBackgroundColour( wx.Colour( 255, 0, 0 ) ) gbSizer1.Add(", "self.m_button13.SetBackgroundColour( wx.Colour( 255, 0, 0 ) ) gbSizer1.Add( self.m_button13, wx.GBPosition(", "wx.ALL, 5 ) self.m_button24 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition,", "pos = wx.Point( 0,0 ), size = wx.Size( 767,507 ),", "wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button21.SetBackgroundColour( wx.Colour( 255,", "wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button02.SetBackgroundColour( wx.Colour( 255,", "wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button40.SetBackgroundColour( wx.Colour( 255, 0,", "wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button41.SetBackgroundColour( wx.Colour(", "wx.EVT_BUTTON, self.onButton12Click ) self.m_button13.Bind( wx.EVT_BUTTON, self.onButton13Click ) self.m_button14.Bind( wx.EVT_BUTTON, self.onButton14Click", "), wx.ALL, 5 ) self.m_button11 = wx.Button( self, wx.ID_ANY, wx.EmptyString,", "self, event ): event.Skip() def onButton04Click( self, event ): event.Skip()", "event.Skip() def OnMenuOpenSelect( self, event ): event.Skip() def OnMenuSaveSelect( self,", "), 0 ) self.m_button41.SetBackgroundColour( wx.Colour( 255, 0, 0 ) )", "wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button13.SetBackgroundColour( wx.Colour(", "self.m_button42.Bind( wx.EVT_BUTTON, self.onButton42Click ) self.m_button43.Bind( wx.EVT_BUTTON, self.onButton43Click ) self.m_button44.Bind( wx.EVT_BUTTON,", "wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button42.SetBackgroundColour( wx.Colour( 255,", "): wx.Frame.__init__ ( self, parent, id = wx.ID_ANY, title =", "gbSizer1.Add( self.m_button02, wx.GBPosition( 0, 2 ), wx.GBSpan( 1, 1 ),", ") gbSizer1.Add( self.m_button42, wx.GBPosition( 4, 2 ), wx.GBSpan( 1, 1", "wx.EVT_MENU, self.OnExportPythonSelect, id = self.m_menuItem4.GetId() ) def __del__( self ):", "2, 3 ), wx.GBSpan( 1, 1 ), wx.ALL, 5 )", "wx.GBPosition( 2, 2 ), wx.GBSpan( 1, 1 ), wx.ALL, 5", "= self.m_menuItem3.GetId() ) self.Bind( wx.EVT_MENU, self.OnMenuSaveSelect, id = self.m_menuItem1.GetId() )", "self.m_button41, wx.GBPosition( 4, 1 ), wx.GBSpan( 1, 1 ), wx.ALL,", "wx.Colour( 255, 0, 0 ) ) gbSizer1.Add( self.m_button02, wx.GBPosition( 0,", "), wx.ALL, 5 ) self.m_button01 = wx.Button( self, wx.ID_ANY, wx.EmptyString,", "event.Skip() def onButton14Click( self, event ): event.Skip() def onButton20Click( self,", "255, 0, 0 ) ) gbSizer1.Add( self.m_button34, wx.GBPosition( 3, 4", "event.Skip() def onButton33Click( self, event ): event.Skip() def onButton34Click( self,", "event.Skip() def onButton24Click( self, event ): event.Skip() def onButton30Click( self,", "self.Centre( wx.BOTH ) # Connect Events self.m_button00.Bind( wx.EVT_BUTTON, self.onButton00Click )", "event.Skip() def onButton13Click( self, event ): event.Skip() def onButton14Click( self,", "): event.Skip() def onButton32Click( self, event ): event.Skip() def onButton33Click(", "self.m_button32, wx.GBPosition( 3, 2 ), wx.GBSpan( 1, 1 ), wx.ALL,", "1, 1 ), wx.ALL, 5 ) self.m_button41 = wx.Button( self,", "0 ) self.m_menu1 = wx.Menu() self.m_menuItem3 = wx.MenuItem( self.m_menu1, wx.ID_ANY,", "wx.Size( 767,507 ), style = wx.DEFAULT_FRAME_STYLE|wx.TAB_TRAVERSAL ) self.SetSizeHints( wx.DefaultSize, wx.DefaultSize", "self.m_button34, wx.GBPosition( 3, 4 ), wx.GBSpan( 1, 1 ), wx.ALL,", ") self.m_button13 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50", "event ): event.Skip() def onButton21Click( self, event ): event.Skip() def", "5 ) self.m_button30 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size(", "wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button23.SetBackgroundColour( wx.Colour( 255,", "0 ) self.m_button31.SetBackgroundColour( wx.Colour( 255, 0, 0 ) ) gbSizer1.Add(", "self.m_button24.SetBackgroundColour( wx.Colour( 255, 0, 0 ) ) gbSizer1.Add( self.m_button24, wx.GBPosition(", "= wx.MenuBar( 0 ) self.m_menu1 = wx.Menu() self.m_menuItem3 = wx.MenuItem(", "self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button43.SetBackgroundColour(", "self.m_button42 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ),", "event.Skip() def onButton31Click( self, event ): event.Skip() def onButton32Click( self,", "2 ), wx.GBSpan( 1, 1 ), wx.ALL, 5 ) self.m_button23", "-*- coding: utf-8 -*- ########################################################################### ## Python code generated with", "wx.GBPosition( 4, 0 ), wx.GBSpan( 1, 1 ), wx.ALL, 5", "wx.GBPosition( 3, 4 ), wx.GBSpan( 1, 1 ), wx.ALL, 5", ") self.m_button41 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50", "wx.Size( 50,50 ), 0 ) self.m_button44.SetBackgroundColour( wx.Colour( 255, 0, 0", "self.m_menu2 = wx.Menu() self.m_menuItem4 = wx.MenuItem( self.m_menu2, wx.ID_ANY, u\"python\", wx.EmptyString,", "self.m_button42, wx.GBPosition( 4, 2 ), wx.GBSpan( 1, 1 ), wx.ALL,", "2018) ## http://www.wxformbuilder.org/ ## ## PLEASE DO *NOT* EDIT THIS", "), wx.ALL, 5 ) self.m_button32 = wx.Button( self, wx.ID_ANY, wx.EmptyString,", "), wx.ALL, 5 ) self.m_button43 = wx.Button( self, wx.ID_ANY, wx.EmptyString,", "wx.Colour( 255, 0, 0 ) ) gbSizer1.Add( self.m_button34, wx.GBPosition( 3,", "wx.MenuBar( 0 ) self.m_menu1 = wx.Menu() self.m_menuItem3 = wx.MenuItem( self.m_menu1,", "), wx.GBSpan( 1, 1 ), wx.ALL, 5 ) self.m_button41 =", "50,50 ), 0 ) self.m_button33.SetBackgroundColour( wx.Colour( 255, 0, 0 )", "self, parent ): wx.Frame.__init__ ( self, parent, id = wx.ID_ANY,", ") self.m_button21 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50", ") self.m_button43.Bind( wx.EVT_BUTTON, self.onButton43Click ) self.m_button44.Bind( wx.EVT_BUTTON, self.onButton44Click ) self.Bind(", ") self.m_menu2 = wx.Menu() self.m_menuItem4 = wx.MenuItem( self.m_menu2, wx.ID_ANY, u\"python\",", "0, 3 ), wx.GBSpan( 1, 1 ), wx.ALL, 5 )", "wx.Colour( 255, 0, 0 ) ) gbSizer1.Add( self.m_button32, wx.GBPosition( 3,", "self, event ): event.Skip() def onButton31Click( self, event ): event.Skip()", "self.m_menu2, u\"export\" ) self.SetMenuBar( self.m_menubar1 ) self.Centre( wx.BOTH ) #", "onButton32Click( self, event ): event.Skip() def onButton33Click( self, event ):", "self.m_button44.Bind( wx.EVT_BUTTON, self.onButton44Click ) self.Bind( wx.EVT_MENU, self.OnMenuOpenSelect, id = self.m_menuItem3.GetId()", ") gbSizer1.Add( self.m_button32, wx.GBPosition( 3, 2 ), wx.GBSpan( 1, 1", ") self.m_button42 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50", ") gbSizer1.Add( self.m_button43, wx.GBPosition( 4, 3 ), wx.GBSpan( 1, 1", "), wx.ALL, 5 ) self.m_button44 = wx.Button( self, wx.ID_ANY, wx.EmptyString,", "255, 0, 0 ) ) gbSizer1.Add( self.m_button33, wx.GBPosition( 3, 3", "pass # Virtual event handlers, overide them in your derived", "wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button14.SetBackgroundColour( wx.Colour( 255,", "onButton24Click( self, event ): event.Skip() def onButton30Click( self, event ):", "self.m_button24.Bind( wx.EVT_BUTTON, self.onButton24Click ) self.m_button30.Bind( wx.EVT_BUTTON, self.onButton30Click ) self.m_button31.Bind( wx.EVT_BUTTON,", "0 ) self.m_button22.SetBackgroundColour( wx.Colour( 255, 0, 0 ) ) gbSizer1.Add(", "): event.Skip() def onButton02Click( self, event ): event.Skip() def onButton03Click(", "self.m_menuItem2 = wx.MenuItem( self.m_menu1, wx.ID_ANY, u\"quit\", wx.EmptyString, wx.ITEM_NORMAL ) self.m_menu1.Append(", "wx.EVT_BUTTON, self.onButton42Click ) self.m_button43.Bind( wx.EVT_BUTTON, self.onButton43Click ) self.m_button44.Bind( wx.EVT_BUTTON, self.onButton44Click", "def onButton40Click( self, event ): event.Skip() def onButton41Click( self, event", "def OnMenuSaveSelect( self, event ): event.Skip() def OnMenuQuitSelect( self, event", "u\"Save\", wx.EmptyString, wx.ITEM_NORMAL ) self.m_menu1.Append( self.m_menuItem1 ) self.m_menuItem2 = wx.MenuItem(", "1 ), wx.ALL, 5 ) self.m_button03 = wx.Button( self, wx.ID_ANY,", "gbSizer1 ) self.Layout() self.m_menubar1 = wx.MenuBar( 0 ) self.m_menu1 =", "0 ) ) gbSizer1.Add( self.m_button11, wx.GBPosition( 1, 1 ), wx.GBSpan(", "self.m_button23, wx.GBPosition( 2, 3 ), wx.GBSpan( 1, 1 ), wx.ALL,", "def onButton41Click( self, event ): event.Skip() def onButton42Click( self, event", "self, event ): event.Skip() def onButton02Click( self, event ): event.Skip()", ") ) gbSizer1.Add( self.m_button12, wx.GBPosition( 1, 2 ), wx.GBSpan( 1,", "), 0 ) self.m_button12.SetBackgroundColour( wx.Colour( 255, 0, 0 ) )", "wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button24.SetBackgroundColour( wx.Colour( 255, 0,", "them in your derived class def onButton00Click( self, event ):", "self.m_button11 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ),", "wx.Colour( 255, 0, 0 ) ) gbSizer1.Add( self.m_button22, wx.GBPosition( 2,", "), wx.GBSpan( 1, 1 ), wx.ALL, 5 ) self.m_button24 =", "0 ) ) gbSizer1.Add( self.m_button31, wx.GBPosition( 3, 1 ), wx.GBSpan(", ") ) gbSizer1.Add( self.m_button43, wx.GBPosition( 4, 3 ), wx.GBSpan( 1,", "self.m_menuItem4 = wx.MenuItem( self.m_menu2, wx.ID_ANY, u\"python\", wx.EmptyString, wx.ITEM_NORMAL ) self.m_menu2.Append(", "self.m_menubar1 ) self.Centre( wx.BOTH ) # Connect Events self.m_button00.Bind( wx.EVT_BUTTON,", ") self.m_button20.SetBackgroundColour( wx.Colour( 255, 0, 0 ) ) gbSizer1.Add( self.m_button20,", "self.m_button20, wx.GBPosition( 2, 0 ), wx.GBSpan( 1, 1 ), wx.ALL,", "wx.Frame.__init__ ( self, parent, id = wx.ID_ANY, title = wx.EmptyString,", "event ): event.Skip() def OnMenuOpenSelect( self, event ): event.Skip() def", ") self.m_button43 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50", "1 ), wx.ALL, 5 ) self.m_button31 = wx.Button( self, wx.ID_ANY,", "wx.EVT_BUTTON, self.onButton13Click ) self.m_button14.Bind( wx.EVT_BUTTON, self.onButton14Click ) self.m_button20.Bind( wx.EVT_BUTTON, self.onButton20Click", "wx.Size( 50,50 ), 0 ) self.m_button02.SetBackgroundColour( wx.Colour( 255, 0, 0", "255, 0, 0 ) ) gbSizer1.Add( self.m_button31, wx.GBPosition( 3, 1", "1, 1 ), wx.ALL, 5 ) self.m_button33 = wx.Button( self,", ") self.m_button12 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50", "wx.GBPosition( 2, 1 ), wx.GBSpan( 1, 1 ), wx.ALL, 5", "self, event ): event.Skip() def onButton20Click( self, event ): event.Skip()", "def onButton43Click( self, event ): event.Skip() def onButton44Click( self, event", "): event.Skip() def onButton21Click( self, event ): event.Skip() def onButton22Click(", "self.m_button14 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ),", "wx.GBSpan( 1, 1 ), wx.ALL, 5 ) self.m_button43 = wx.Button(", "wx.ALL, 5 ) self.m_button43 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition,", "wx.EVT_BUTTON, self.onButton41Click ) self.m_button42.Bind( wx.EVT_BUTTON, self.onButton42Click ) self.m_button43.Bind( wx.EVT_BUTTON, self.onButton43Click", "0, 0 ) ) gbSizer1.Add( self.m_button11, wx.GBPosition( 1, 1 ),", ") self.m_button04.Bind( wx.EVT_BUTTON, self.onButton04Click ) self.m_button10.Bind( wx.EVT_BUTTON, self.onButton10Click ) self.m_button11.Bind(", "event.Skip() def onButton20Click( self, event ): event.Skip() def onButton21Click( self,", "PLEASE DO *NOT* EDIT THIS FILE! ########################################################################### import wx import", "), 0 ) self.m_button24.SetBackgroundColour( wx.Colour( 255, 0, 0 ) )", "wx.ITEM_NORMAL ) self.m_menu1.Append( self.m_menuItem2 ) self.m_menubar1.Append( self.m_menu1, u\"File\" ) self.m_menu2", "event ): event.Skip() def onButton12Click( self, event ): event.Skip() def", "wx.Size( 50,50 ), 0 ) self.m_button01.SetBackgroundColour( wx.Colour( 255, 0, 0", ") gbSizer1.Add( self.m_button02, wx.GBPosition( 0, 2 ), wx.GBSpan( 1, 1", "5 ) self.m_button34 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size(", "wx.Size( 50,50 ), 0 ) self.m_button21.SetBackgroundColour( wx.Colour( 255, 0, 0", "1 ), wx.ALL, 5 ) self.m_button33 = wx.Button( self, wx.ID_ANY,", ") ) gbSizer1.Add( self.m_button42, wx.GBPosition( 4, 2 ), wx.GBSpan( 1,", "self.m_menuItem4.GetId() ) def __del__( self ): pass # Virtual event", "import wx.xrc ########################################################################### ## Class MyFrame1 ########################################################################### class MyFrame1 (", "event.Skip() def onButton04Click( self, event ): event.Skip() def onButton10Click( self,", "wx.Menu() self.m_menuItem4 = wx.MenuItem( self.m_menu2, wx.ID_ANY, u\"python\", wx.EmptyString, wx.ITEM_NORMAL )", "onButton04Click( self, event ): event.Skip() def onButton10Click( self, event ):", "wx.Menu() self.m_menuItem3 = wx.MenuItem( self.m_menu1, wx.ID_ANY, u\"Open\", wx.EmptyString, wx.ITEM_NORMAL )", "self.m_button42.SetBackgroundColour( wx.Colour( 255, 0, 0 ) ) gbSizer1.Add( self.m_button42, wx.GBPosition(", "self.m_button03 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ),", "onButton33Click( self, event ): event.Skip() def onButton34Click( self, event ):", "self, event ): event.Skip() def OnMenuQuitSelect( self, event ): event.Skip()", "1 ), wx.ALL, 5 ) self.m_button42 = wx.Button( self, wx.ID_ANY,", "self.m_button22.Bind( wx.EVT_BUTTON, self.onButton22Click ) self.m_button23.Bind( wx.EVT_BUTTON, self.onButton23Click ) self.m_button24.Bind( wx.EVT_BUTTON,", ") self.m_button40 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50", "): event.Skip() def onButton11Click( self, event ): event.Skip() def onButton12Click(", "self.m_button31, wx.GBPosition( 3, 1 ), wx.GBSpan( 1, 1 ), wx.ALL,", "self.onButton44Click ) self.Bind( wx.EVT_MENU, self.OnMenuOpenSelect, id = self.m_menuItem3.GetId() ) self.Bind(", ") gbSizer1.Add( self.m_button04, wx.GBPosition( 0, 4 ), wx.GBSpan( 1, 1", "self.m_menuItem1 ) self.m_menuItem2 = wx.MenuItem( self.m_menu1, wx.ID_ANY, u\"quit\", wx.EmptyString, wx.ITEM_NORMAL", "self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button42.SetBackgroundColour(", "): event.Skip() def onButton24Click( self, event ): event.Skip() def onButton30Click(", "1 ), wx.ALL, 5 ) self.m_button21 = wx.Button( self, wx.ID_ANY,", "self.onButton31Click ) self.m_button32.Bind( wx.EVT_BUTTON, self.onButton32Click ) self.m_button33.Bind( wx.EVT_BUTTON, self.onButton33Click )", "3 ), wx.GBSpan( 1, 1 ), wx.ALL, 5 ) self.m_button34", ") gbSizer1.Add( self.m_button41, wx.GBPosition( 4, 1 ), wx.GBSpan( 1, 1", ") self.m_button01.SetBackgroundColour( wx.Colour( 255, 0, 0 ) ) gbSizer1.Add( self.m_button01,", "event ): event.Skip() def onButton11Click( self, event ): event.Skip() def", "1, 1 ), wx.ALL, 5 ) self.m_button31 = wx.Button( self,", "1, 1 ), wx.ALL, 5 ) self.m_button40 = wx.Button( self,", "gbSizer1.Add( self.m_button32, wx.GBPosition( 3, 2 ), wx.GBSpan( 1, 1 ),", "wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button22.SetBackgroundColour( wx.Colour(", "wx.Colour( 255, 0, 0 ) ) gbSizer1.Add( self.m_button21, wx.GBPosition( 2,", "wx.GBPosition( 4, 4 ), wx.GBSpan( 1, 1 ), wx.ALL, 5", "0 ), wx.GBSpan( 1, 1 ), wx.ALL, 5 ) self.m_button01", ") self.m_button02.Bind( wx.EVT_BUTTON, self.onButton02Click ) self.m_button03.Bind( wx.EVT_BUTTON, self.onButton03Click ) self.m_button04.Bind(", "wx.EVT_BUTTON, self.onButton14Click ) self.m_button20.Bind( wx.EVT_BUTTON, self.onButton20Click ) self.m_button21.Bind( wx.EVT_BUTTON, self.onButton21Click", "gbSizer1.Add( self.m_button22, wx.GBPosition( 2, 2 ), wx.GBSpan( 1, 1 ),", "wx.Colour( 255, 0, 0 ) ) gbSizer1.Add( self.m_button14, wx.GBPosition( 1,", "wx.GBSpan( 1, 1 ), wx.ALL, 5 ) self.m_button34 = wx.Button(", "wx.EVT_BUTTON, self.onButton30Click ) self.m_button31.Bind( wx.EVT_BUTTON, self.onButton31Click ) self.m_button32.Bind( wx.EVT_BUTTON, self.onButton32Click", "event ): event.Skip() def onButton34Click( self, event ): event.Skip() def", "def onButton30Click( self, event ): event.Skip() def onButton31Click( self, event", "event.Skip() def onButton32Click( self, event ): event.Skip() def onButton33Click( self,", "wx.EVT_BUTTON, self.onButton10Click ) self.m_button11.Bind( wx.EVT_BUTTON, self.onButton11Click ) self.m_button12.Bind( wx.EVT_BUTTON, self.onButton12Click", "), size = wx.Size( 767,507 ), style = wx.DEFAULT_FRAME_STYLE|wx.TAB_TRAVERSAL )", "wx.EmptyString, wx.ITEM_NORMAL ) self.m_menu1.Append( self.m_menuItem1 ) self.m_menuItem2 = wx.MenuItem( self.m_menu1,", "self.m_button44.SetBackgroundColour( wx.Colour( 255, 0, 0 ) ) gbSizer1.Add( self.m_button44, wx.GBPosition(", "def onButton42Click( self, event ): event.Skip() def onButton43Click( self, event", "event ): event.Skip() def onButton32Click( self, event ): event.Skip() def", "0 ) self.m_button03.SetBackgroundColour( wx.Colour( 255, 0, 0 ) ) gbSizer1.Add(", "50,50 ), 0 ) self.m_button30.SetBackgroundColour( wx.Colour( 255, 0, 0 )", "event ): event.Skip() def onButton24Click( self, event ): event.Skip() def", "wx.Colour( 255, 0, 0 ) ) gbSizer1.Add( self.m_button13, wx.GBPosition( 1,", "self.m_button43, wx.GBPosition( 4, 3 ), wx.GBSpan( 1, 1 ), wx.ALL,", "self.m_button02.Bind( wx.EVT_BUTTON, self.onButton02Click ) self.m_button03.Bind( wx.EVT_BUTTON, self.onButton03Click ) self.m_button04.Bind( wx.EVT_BUTTON,", "self.m_button01 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ),", "wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button30.SetBackgroundColour( wx.Colour( 255, 0,", "): event.Skip() def onButton23Click( self, event ): event.Skip() def onButton24Click(", "self.m_button14, wx.GBPosition( 1, 4 ), wx.GBSpan( 1, 1 ), wx.ALL,", "0 ) ) gbSizer1.Add( self.m_button22, wx.GBPosition( 2, 2 ), wx.GBSpan(", "wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button23.SetBackgroundColour( wx.Colour(", ") ) gbSizer1.Add( self.m_button00, wx.GBPosition( 0, 0 ), wx.GBSpan( 1,", "## Python code generated with wxFormBuilder (version Aug 8 2018)", "wx.MenuItem( self.m_menu1, wx.ID_ANY, u\"Open\", wx.EmptyString, wx.ITEM_NORMAL ) self.m_menu1.Append( self.m_menuItem3 )", "self.m_button01.SetBackgroundColour( wx.Colour( 255, 0, 0 ) ) gbSizer1.Add( self.m_button01, wx.GBPosition(", "255, 0, 0 ) ) gbSizer1.Add( self.m_button20, wx.GBPosition( 2, 0", "), wx.GBSpan( 1, 1 ), wx.ALL, 5 ) self.m_button13 =", "wx.Size( 50,50 ), 0 ) self.m_button23.SetBackgroundColour( wx.Colour( 255, 0, 0", "self.m_button32.SetBackgroundColour( wx.Colour( 255, 0, 0 ) ) gbSizer1.Add( self.m_button32, wx.GBPosition(", "wx.Colour( 255, 0, 0 ) ) gbSizer1.Add( self.m_button30, wx.GBPosition( 3,", "0 ) ) gbSizer1.Add( self.m_button40, wx.GBPosition( 4, 0 ), wx.GBSpan(", "self, event ): event.Skip() def onButton32Click( self, event ): event.Skip()", "self.m_button04, wx.GBPosition( 0, 4 ), wx.GBSpan( 1, 1 ), wx.ALL,", "gbSizer1.Add( self.m_button41, wx.GBPosition( 4, 1 ), wx.GBSpan( 1, 1 ),", "wx.DefaultSize ) gbSizer1 = wx.GridBagSizer( 0, 0 ) gbSizer1.SetFlexibleDirection( wx.BOTH", "wx.Size( 50,50 ), 0 ) self.m_button13.SetBackgroundColour( wx.Colour( 255, 0, 0", "0, 0 ) ) gbSizer1.Add( self.m_button33, wx.GBPosition( 3, 3 ),", ") self.m_button02 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50", ") self.m_button33 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50", "50,50 ), 0 ) self.m_button01.SetBackgroundColour( wx.Colour( 255, 0, 0 )", "5 ) self.m_button01 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size(", "self.m_button44, wx.GBPosition( 4, 4 ), wx.GBSpan( 1, 1 ), wx.ALL,", "self.m_button34.SetBackgroundColour( wx.Colour( 255, 0, 0 ) ) gbSizer1.Add( self.m_button34, wx.GBPosition(", "self.OnExportPythonSelect, id = self.m_menuItem4.GetId() ) def __del__( self ): pass", "event ): event.Skip() def onButton04Click( self, event ): event.Skip() def", "self, event ): event.Skip() def onButton10Click( self, event ): event.Skip()", "): event.Skip() def onButton10Click( self, event ): event.Skip() def onButton11Click(", ") def __del__( self ): pass # Virtual event handlers,", "wx.GBPosition( 1, 4 ), wx.GBSpan( 1, 1 ), wx.ALL, 5", "def onButton44Click( self, event ): event.Skip() def OnMenuOpenSelect( self, event", "self, event ): event.Skip() def OnExportPythonSelect( self, event ): event.Skip()", "self.m_button03.Bind( wx.EVT_BUTTON, self.onButton03Click ) self.m_button04.Bind( wx.EVT_BUTTON, self.onButton04Click ) self.m_button10.Bind( wx.EVT_BUTTON,", "255, 0, 0 ) ) gbSizer1.Add( self.m_button11, wx.GBPosition( 1, 1", "self.m_button33.Bind( wx.EVT_BUTTON, self.onButton33Click ) self.m_button34.Bind( wx.EVT_BUTTON, self.onButton34Click ) self.m_button40.Bind( wx.EVT_BUTTON,", "0 ) ) gbSizer1.Add( self.m_button33, wx.GBPosition( 3, 3 ), wx.GBSpan(", "wx.Size( 50,50 ), 0 ) self.m_button04.SetBackgroundColour( wx.Colour( 255, 0, 0", "self.m_menuItem4 ) self.m_menubar1.Append( self.m_menu2, u\"export\" ) self.SetMenuBar( self.m_menubar1 ) self.Centre(", "def onButton14Click( self, event ): event.Skip() def onButton20Click( self, event", "id = self.m_menuItem4.GetId() ) def __del__( self ): pass #", "wx.Colour( 255, 0, 0 ) ) gbSizer1.Add( self.m_button04, wx.GBPosition( 0,", "0, 1 ), wx.GBSpan( 1, 1 ), wx.ALL, 5 )", "self.m_button32.Bind( wx.EVT_BUTTON, self.onButton32Click ) self.m_button33.Bind( wx.EVT_BUTTON, self.onButton33Click ) self.m_button34.Bind( wx.EVT_BUTTON,", "onButton02Click( self, event ): event.Skip() def onButton03Click( self, event ):", "wx.GBSpan( 1, 1 ), wx.ALL, 5 ) self.m_button42 = wx.Button(", "self.onButton24Click ) self.m_button30.Bind( wx.EVT_BUTTON, self.onButton30Click ) self.m_button31.Bind( wx.EVT_BUTTON, self.onButton31Click )", "self.m_button41.Bind( wx.EVT_BUTTON, self.onButton41Click ) self.m_button42.Bind( wx.EVT_BUTTON, self.onButton42Click ) self.m_button43.Bind( wx.EVT_BUTTON,", "0 ) ) gbSizer1.Add( self.m_button14, wx.GBPosition( 1, 4 ), wx.GBSpan(", "wx.GBPosition( 4, 3 ), wx.GBSpan( 1, 1 ), wx.ALL, 5", "wx.EVT_BUTTON, self.onButton31Click ) self.m_button32.Bind( wx.EVT_BUTTON, self.onButton32Click ) self.m_button33.Bind( wx.EVT_BUTTON, self.onButton33Click", "1, 1 ), wx.ALL, 5 ) self.m_button02 = wx.Button( self,", "50,50 ), 0 ) self.m_button42.SetBackgroundColour( wx.Colour( 255, 0, 0 )", "self.onButton22Click ) self.m_button23.Bind( wx.EVT_BUTTON, self.onButton23Click ) self.m_button24.Bind( wx.EVT_BUTTON, self.onButton24Click )", "wx.GBSpan( 1, 1 ), wx.ALL, 5 ) self.m_button11 = wx.Button(", "event.Skip() def onButton23Click( self, event ): event.Skip() def onButton24Click( self,", "), wx.ALL, 5 ) self.m_button14 = wx.Button( self, wx.ID_ANY, wx.EmptyString,", "0 ) self.m_button20.SetBackgroundColour( wx.Colour( 255, 0, 0 ) ) gbSizer1.Add(", "wx.Colour( 255, 0, 0 ) ) gbSizer1.Add( self.m_button00, wx.GBPosition( 0,", "event.Skip() def onButton12Click( self, event ): event.Skip() def onButton13Click( self,", "wx.GBPosition( 1, 2 ), wx.GBSpan( 1, 1 ), wx.ALL, 5", "event.Skip() def onButton11Click( self, event ): event.Skip() def onButton12Click( self,", "1 ), wx.ALL, 5 ) self.m_button10 = wx.Button( self, wx.ID_ANY,", "u\"quit\", wx.EmptyString, wx.ITEM_NORMAL ) self.m_menu1.Append( self.m_menuItem2 ) self.m_menubar1.Append( self.m_menu1, u\"File\"", "): event.Skip() def onButton31Click( self, event ): event.Skip() def onButton32Click(", "generated with wxFormBuilder (version Aug 8 2018) ## http://www.wxformbuilder.org/ ##", "), wx.ALL, 5 ) self.m_button31 = wx.Button( self, wx.ID_ANY, wx.EmptyString,", "), wx.ALL, 5 ) self.m_button40 = wx.Button( self, wx.ID_ANY, wx.EmptyString,", ") ) gbSizer1.Add( self.m_button40, wx.GBPosition( 4, 0 ), wx.GBSpan( 1,", ") ) gbSizer1.Add( self.m_button41, wx.GBPosition( 4, 1 ), wx.GBSpan( 1,", ") self.m_menu2.Append( self.m_menuItem4 ) self.m_menubar1.Append( self.m_menu2, u\"export\" ) self.SetMenuBar( self.m_menubar1", "self.m_button04.Bind( wx.EVT_BUTTON, self.onButton04Click ) self.m_button10.Bind( wx.EVT_BUTTON, self.onButton10Click ) self.m_button11.Bind( wx.EVT_BUTTON,", "self.onButton02Click ) self.m_button03.Bind( wx.EVT_BUTTON, self.onButton03Click ) self.m_button04.Bind( wx.EVT_BUTTON, self.onButton04Click )", "self.m_button00.Bind( wx.EVT_BUTTON, self.onButton00Click ) self.m_button01.Bind( wx.EVT_BUTTON, self.onButton01Click ) self.m_button02.Bind( wx.EVT_BUTTON,", "wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button01.SetBackgroundColour( wx.Colour( 255, 0,", "EDIT THIS FILE! ########################################################################### import wx import wx.xrc ########################################################################### ##", "50,50 ), 0 ) self.m_button31.SetBackgroundColour( wx.Colour( 255, 0, 0 )", "THIS FILE! ########################################################################### import wx import wx.xrc ########################################################################### ## Class", ") gbSizer1.Add( self.m_button33, wx.GBPosition( 3, 3 ), wx.GBSpan( 1, 1", "wx.GBSpan( 1, 1 ), wx.ALL, 5 ) self.m_button40 = wx.Button(", "wx.GBSpan( 1, 1 ), wx.ALL, 5 ) self.m_button33 = wx.Button(", "0 ) ) gbSizer1.Add( self.m_button12, wx.GBPosition( 1, 2 ), wx.GBSpan(", "wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button43.SetBackgroundColour( wx.Colour( 255, 0,", "255, 0, 0 ) ) gbSizer1.Add( self.m_button44, wx.GBPosition( 4, 4", "1 ), wx.ALL, 5 ) self.m_button20 = wx.Button( self, wx.ID_ANY,", "wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button21.SetBackgroundColour( wx.Colour(", "self, event ): event.Skip() def onButton14Click( self, event ): event.Skip()", "self.onButton00Click ) self.m_button01.Bind( wx.EVT_BUTTON, self.onButton01Click ) self.m_button02.Bind( wx.EVT_BUTTON, self.onButton02Click )", "gbSizer1 = wx.GridBagSizer( 0, 0 ) gbSizer1.SetFlexibleDirection( wx.BOTH ) gbSizer1.SetNonFlexibleGrowMode(", "self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button10.SetBackgroundColour(", "5 ) self.m_button03 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size(", "wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button03.SetBackgroundColour( wx.Colour( 255, 0,", ") self.m_button04.SetBackgroundColour( wx.Colour( 255, 0, 0 ) ) gbSizer1.Add( self.m_button04,", "3, 1 ), wx.GBSpan( 1, 1 ), wx.ALL, 5 )", "5 ) self.m_button32 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size(", "): event.Skip() def onButton30Click( self, event ): event.Skip() def onButton31Click(", "def onButton10Click( self, event ): event.Skip() def onButton11Click( self, event", "self.m_button03, wx.GBPosition( 0, 3 ), wx.GBSpan( 1, 1 ), wx.ALL,", "wx.GBSpan( 1, 1 ), wx.ALL, 5 ) self.m_button13 = wx.Button(", "self.m_menu1 = wx.Menu() self.m_menuItem3 = wx.MenuItem( self.m_menu1, wx.ID_ANY, u\"Open\", wx.EmptyString,", ") ) gbSizer1.Add( self.m_button13, wx.GBPosition( 1, 3 ), wx.GBSpan( 1,", "wx.ALL, 5 ) self.m_button44 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition,", ") self.m_button24 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50", "50,50 ), 0 ) self.m_button41.SetBackgroundColour( wx.Colour( 255, 0, 0 )", "wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button02.SetBackgroundColour( wx.Colour( 255, 0,", "3 ), wx.GBSpan( 1, 1 ), wx.ALL, 5 ) self.m_button44", "self.m_button24, wx.GBPosition( 2, 4 ), wx.GBSpan( 1, 1 ), wx.ALL,", "self.m_button13, wx.GBPosition( 1, 3 ), wx.GBSpan( 1, 1 ), wx.ALL,", "), wx.GBSpan( 1, 1 ), wx.ALL, 5 ) self.m_button30 =", "wx.GBPosition( 0, 3 ), wx.GBSpan( 1, 1 ), wx.ALL, 5", ") self.m_button44 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50", "coding: utf-8 -*- ########################################################################### ## Python code generated with wxFormBuilder", "wx.GBSpan( 1, 1 ), wx.ALL, 5 ) self.m_button24 = wx.Button(", "), wx.ALL, 5 ) self.SetSizer( gbSizer1 ) self.Layout() self.m_menubar1 =", "wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button12.SetBackgroundColour( wx.Colour( 255,", "1 ), wx.ALL, 5 ) self.m_button23 = wx.Button( self, wx.ID_ANY,", "wx.Size( 50,50 ), 0 ) self.m_button00.SetBackgroundColour( wx.Colour( 255, 0, 0", "self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button13.SetBackgroundColour(", "wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button43.SetBackgroundColour( wx.Colour(", "def onButton32Click( self, event ): event.Skip() def onButton33Click( self, event", ") ) gbSizer1.Add( self.m_button34, wx.GBPosition( 3, 4 ), wx.GBSpan( 1,", "), wx.GBSpan( 1, 1 ), wx.ALL, 5 ) self.m_button14 =", ") self.m_button03 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50", "1, 1 ), wx.GBSpan( 1, 1 ), wx.ALL, 5 )", ") ) gbSizer1.Add( self.m_button24, wx.GBPosition( 2, 4 ), wx.GBSpan( 1,", "), wx.GBSpan( 1, 1 ), wx.ALL, 5 ) self.m_button20 =", "2 ), wx.GBSpan( 1, 1 ), wx.ALL, 5 ) self.m_button43", "= self.m_menuItem2.GetId() ) self.Bind( wx.EVT_MENU, self.OnExportPythonSelect, id = self.m_menuItem4.GetId() )", "self.onButton23Click ) self.m_button24.Bind( wx.EVT_BUTTON, self.onButton24Click ) self.m_button30.Bind( wx.EVT_BUTTON, self.onButton30Click )", "event ): event.Skip() def onButton02Click( self, event ): event.Skip() def", ") self.m_menubar1.Append( self.m_menu2, u\"export\" ) self.SetMenuBar( self.m_menubar1 ) self.Centre( wx.BOTH", "gbSizer1.Add( self.m_button30, wx.GBPosition( 3, 0 ), wx.GBSpan( 1, 1 ),", "255, 0, 0 ) ) gbSizer1.Add( self.m_button00, wx.GBPosition( 0, 0", ") self.m_button14.Bind( wx.EVT_BUTTON, self.onButton14Click ) self.m_button20.Bind( wx.EVT_BUTTON, self.onButton20Click ) self.m_button21.Bind(", "self.m_button41.SetBackgroundColour( wx.Colour( 255, 0, 0 ) ) gbSizer1.Add( self.m_button41, wx.GBPosition(", "self.onButton11Click ) self.m_button12.Bind( wx.EVT_BUTTON, self.onButton12Click ) self.m_button13.Bind( wx.EVT_BUTTON, self.onButton13Click )", "wx.GBPosition( 2, 0 ), wx.GBSpan( 1, 1 ), wx.ALL, 5", "gbSizer1.Add( self.m_button04, wx.GBPosition( 0, 4 ), wx.GBSpan( 1, 1 ),", "), 0 ) self.m_button23.SetBackgroundColour( wx.Colour( 255, 0, 0 ) )", "self ): pass # Virtual event handlers, overide them in", "def onButton00Click( self, event ): event.Skip() def onButton01Click( self, event", "), 0 ) self.m_button02.SetBackgroundColour( wx.Colour( 255, 0, 0 ) )", "), 0 ) self.m_button33.SetBackgroundColour( wx.Colour( 255, 0, 0 ) )", "0 ), wx.GBSpan( 1, 1 ), wx.ALL, 5 ) self.m_button41", "0 ) ) gbSizer1.Add( self.m_button24, wx.GBPosition( 2, 4 ), wx.GBSpan(", "wx.GBSpan( 1, 1 ), wx.ALL, 5 ) self.m_button41 = wx.Button(", "self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button11.SetBackgroundColour(", ") gbSizer1.Add( self.m_button30, wx.GBPosition( 3, 0 ), wx.GBSpan( 1, 1", ") self.m_button04 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50", "u\"python\", wx.EmptyString, wx.ITEM_NORMAL ) self.m_menu2.Append( self.m_menuItem4 ) self.m_menubar1.Append( self.m_menu2, u\"export\"", "), wx.GBSpan( 1, 1 ), wx.ALL, 5 ) self.m_button11 =", "self.m_button40 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ),", "self.m_button03.SetBackgroundColour( wx.Colour( 255, 0, 0 ) ) gbSizer1.Add( self.m_button03, wx.GBPosition(", "self.OnMenuOpenSelect, id = self.m_menuItem3.GetId() ) self.Bind( wx.EVT_MENU, self.OnMenuSaveSelect, id =", "wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button24.SetBackgroundColour( wx.Colour( 255,", ") ) gbSizer1.Add( self.m_button23, wx.GBPosition( 2, 3 ), wx.GBSpan( 1,", "50,50 ), 0 ) self.m_button34.SetBackgroundColour( wx.Colour( 255, 0, 0 )", "self.m_menu2, wx.ID_ANY, u\"python\", wx.EmptyString, wx.ITEM_NORMAL ) self.m_menu2.Append( self.m_menuItem4 ) self.m_menubar1.Append(", "gbSizer1.Add( self.m_button20, wx.GBPosition( 2, 0 ), wx.GBSpan( 1, 1 ),", ") self.m_button22 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50", "3, 4 ), wx.GBSpan( 1, 1 ), wx.ALL, 5 )", "0 ) ) gbSizer1.Add( self.m_button44, wx.GBPosition( 4, 4 ), wx.GBSpan(", "self.m_menu1, wx.ID_ANY, u\"Open\", wx.EmptyString, wx.ITEM_NORMAL ) self.m_menu1.Append( self.m_menuItem3 ) self.m_menuItem1", "= self.m_menuItem1.GetId() ) self.Bind( wx.EVT_MENU, self.OnMenuQuitSelect, id = self.m_menuItem2.GetId() )", "= self.m_menuItem4.GetId() ) def __del__( self ): pass # Virtual", "event ): event.Skip() def onButton03Click( self, event ): event.Skip() def", "self.m_button33, wx.GBPosition( 3, 3 ), wx.GBSpan( 1, 1 ), wx.ALL,", "wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button11.SetBackgroundColour( wx.Colour( 255,", "), wx.ALL, 5 ) self.m_button23 = wx.Button( self, wx.ID_ANY, wx.EmptyString,", "wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button32.SetBackgroundColour( wx.Colour( 255, 0,", "0, 0 ) ) gbSizer1.Add( self.m_button02, wx.GBPosition( 0, 2 ),", "3 ), wx.GBSpan( 1, 1 ), wx.ALL, 5 ) self.m_button24", "wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button12.SetBackgroundColour( wx.Colour( 255, 0,", "wx.ALL, 5 ) self.m_button23 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition,", ") self.m_button43.SetBackgroundColour( wx.Colour( 255, 0, 0 ) ) gbSizer1.Add( self.m_button43,", "OnMenuQuitSelect( self, event ): event.Skip() def OnExportPythonSelect( self, event ):", "self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button12.SetBackgroundColour(", "wx.xrc ########################################################################### ## Class MyFrame1 ########################################################################### class MyFrame1 ( wx.Frame", "wx.EVT_BUTTON, self.onButton03Click ) self.m_button04.Bind( wx.EVT_BUTTON, self.onButton04Click ) self.m_button10.Bind( wx.EVT_BUTTON, self.onButton10Click", "self.onButton33Click ) self.m_button34.Bind( wx.EVT_BUTTON, self.onButton34Click ) self.m_button40.Bind( wx.EVT_BUTTON, self.onButton40Click )", "wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ), 0 ) self.m_button34.SetBackgroundColour( wx.Colour( 255,", "wx.ALL, 5 ) self.SetSizer( gbSizer1 ) self.Layout() self.m_menubar1 = wx.MenuBar(", "wx.FLEX_GROWMODE_SPECIFIED ) self.m_button00 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size(", ") self.m_button40.SetBackgroundColour( wx.Colour( 255, 0, 0 ) ) gbSizer1.Add( self.m_button40,", "self.OnMenuSaveSelect, id = self.m_menuItem1.GetId() ) self.Bind( wx.EVT_MENU, self.OnMenuQuitSelect, id =", "event.Skip() def onButton34Click( self, event ): event.Skip() def onButton40Click( self,", "self.m_button10 = wx.Button( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 50,50 ),", "4 ), wx.GBSpan( 1, 1 ), wx.ALL, 5 ) self.m_button10", ") self.m_menu1.Append( self.m_menuItem3 ) self.m_menuItem1 = wx.MenuItem( self.m_menu1, wx.ID_ANY, u\"Save\",", "########################################################################### class MyFrame1 ( wx.Frame ): def __init__( self, parent", "1, 3 ), wx.GBSpan( 1, 1 ), wx.ALL, 5 )", "), 0 ) self.m_button22.SetBackgroundColour( wx.Colour( 255, 0, 0 ) )" ]
[ "task. :copyright: (c) 2016-2020 by dry-python team. :license: BSD, see", "LICENSE for more details. \"\"\" from _dependencies.contrib.celery import shared_task from", "\"\"\" from _dependencies.contrib.celery import shared_task from _dependencies.contrib.celery import task __all__", "\"\"\" dependencies.contrib.celery --------------------------- This module implements injectable Celery task. :copyright:", ":license: BSD, see LICENSE for more details. \"\"\" from _dependencies.contrib.celery", "more details. \"\"\" from _dependencies.contrib.celery import shared_task from _dependencies.contrib.celery import", "2016-2020 by dry-python team. :license: BSD, see LICENSE for more", "(c) 2016-2020 by dry-python team. :license: BSD, see LICENSE for", "<reponame>nicoddemus/dependencies \"\"\" dependencies.contrib.celery --------------------------- This module implements injectable Celery task.", "details. \"\"\" from _dependencies.contrib.celery import shared_task from _dependencies.contrib.celery import task", "team. :license: BSD, see LICENSE for more details. \"\"\" from", "from _dependencies.contrib.celery import shared_task from _dependencies.contrib.celery import task __all__ =", "Celery task. :copyright: (c) 2016-2020 by dry-python team. :license: BSD,", "implements injectable Celery task. :copyright: (c) 2016-2020 by dry-python team.", ":copyright: (c) 2016-2020 by dry-python team. :license: BSD, see LICENSE", "This module implements injectable Celery task. :copyright: (c) 2016-2020 by", "_dependencies.contrib.celery import shared_task from _dependencies.contrib.celery import task __all__ = [\"shared_task\",", "dry-python team. :license: BSD, see LICENSE for more details. \"\"\"", "see LICENSE for more details. \"\"\" from _dependencies.contrib.celery import shared_task", "import shared_task from _dependencies.contrib.celery import task __all__ = [\"shared_task\", \"task\"]", "BSD, see LICENSE for more details. \"\"\" from _dependencies.contrib.celery import", "for more details. \"\"\" from _dependencies.contrib.celery import shared_task from _dependencies.contrib.celery", "injectable Celery task. :copyright: (c) 2016-2020 by dry-python team. :license:", "dependencies.contrib.celery --------------------------- This module implements injectable Celery task. :copyright: (c)", "--------------------------- This module implements injectable Celery task. :copyright: (c) 2016-2020", "module implements injectable Celery task. :copyright: (c) 2016-2020 by dry-python", "by dry-python team. :license: BSD, see LICENSE for more details." ]
[ "f, g: lambda *a, **kw: g(f(*a, **kw)), funcs) else: raise", "(w,h), (128,128,128)) new_image.paste(image, (dx, dy)) image = new_image # flip", "*= val x[x>1] = 1 x[x<0] = 0 image_data =", "val) if rand()<.5 else 1/rand(1, val) x = rgb_to_hsv(np.array(image)/255.) x[...,", "max(0, int(max_bbox[1] - random.uniform(0, max_u_trans)*2)) crop_xmax = max(w_img, int(max_bbox[2] +", "取得所有bbox中的最大bbox #包含所有目標框的最大框到各個邊的距離 max_l_trans = max_bbox[0] max_u_trans = max_bbox[1] max_r_trans =", "= box[:, [0,2]]*nw/iw + dx box[:, [1,3]] = box[:, [1,3]]*nh/ih", "= image.crop((crop_x_min, crop_y_min, crop_x_max, crop_y_max)) # (left, upper, right, lower)", "(128,128,128)) new_image.paste(image, (dx, dy)) image = new_image # flip image", "get_random_data(annotation_line, input_shape, random=True, max_boxes=20, jitter=.3, hue=.1, sat=1.5, val=1.5, proc_img=True): '''random", "arbitrarily many functions, evaluated left to right. Reference: https://mathieularose.com/function-composition-in-python/ \"\"\"", "box[:, 0] box_h = box[:, 3] - box[:, 1] box", "h y_max = 0 for bbox in box: x_min =", "= min(h, crop_y_max) cropped = image.crop((crop_x_min, crop_y_min, crop_x_max, crop_y_max)) #", "iw, ih = image.size h, w = input_shape box =", "flip: image = image.transpose(Image.FLIP_LEFT_RIGHT) # distort image hue = rand(-hue,", "flip: box[:, [0,2]] = w - box[:, [2,0]] box[:, 0:2][box[:,", "functions, evaluated left to right. Reference: https://mathieularose.com/function-composition-in-python/ \"\"\" # return", "else 1/rand(1, val) x = rgb_to_hsv(np.array(image)/255.) x[..., 0] += hue", "box_h>1)] # discard invalid box if len(box)>max_boxes: box = box[:max_boxes]", "if len(box)>max_boxes: box = box[:max_boxes] box_data[:len(box)] = box return image_data,", "= annotation_line.split() image = Image.open(line[0]) iw, ih = image.size h,", "np.random.shuffle(box) if len(box)>max_boxes: box = box[:max_boxes] box[:, [0,2]] = box[:,", "int(y_min - rand(0, d_to_top)) crop_x_max = int(x_max + rand(0, d_to_right))", "int(rand(0, w-nw)) dy = int(rand(0, h-nh)) new_image = Image.new('RGB', (w,h),", "box #標框線 # light_blue = (255,200,100) # for boxs in", "x_min d_to_right = w - x_max d_to_top = y_min d_to_bottom", "= rand()<.5 if flip: image = image.transpose(Image.FLIP_LEFT_RIGHT) # distort image", "image_data, box_data def get_random_data2(annotation_line, input_shape, random=True, max_boxes=20, jitter=.3, hue=.1, sat=1.5,", "len(box)>max_boxes: box = box[:max_boxes] box[:,0] = box[:,0]-crop_y_min box[:,1] = box[:,1]-crop_y_min", "= box[:, [0, 2]] - crop_xmin box[:, [1, 3]] =", "min(w/iw, h/ih) nw = int(iw*scale) nh = int(ih*scale) image =", "image.resize((nw,nh), Image.BICUBIC) # place image dx = int(rand(0, w-nw)) dy", "- random.uniform(0, max_l_trans)*2)) crop_ymin = max(0, int(max_bbox[1] - random.uniform(0, max_u_trans)*2))", "# light_blue = (255,200,100) # for boxs in box: #", "随机扩展这个最小范围 crop_x_min = int(x_min - rand(0, d_to_left)) crop_y_min = int(y_min", "invalid box if len(box)>max_boxes: box = box[:max_boxes] box_data[:len(box)] = box", "box_data # resize image new_ar = w/h * rand(1-jitter,1+jitter)/rand(1-jitter,1+jitter) scale", "= box return image_data, box_data # resize image new_ar =", "w-nw)) dy = int(rand(0, h-nh)) new_image = Image.new('RGB', (w,h), (128,128,128))", "Image.BICUBIC) # place image dx = int(rand(0, w-nw)) dy =", "box[:, 0:2][box[:, 0:2]<0] = 0 box[:, 2][box[:, 2]>w] = w", "for box in line[1:]]) max_bbox = np.concatenate([np.min(box[:, 0:2], axis=0), np.max(box[:,", "# distort image hue = rand(-hue, hue) sat = rand(1,", "sat=1.5, val=1.5, proc_img=True): line = annotation_line.split() img = cv2.imread(line[0]) h_img,", "rand(a=0, b=1): return np.random.rand()*(b-a) + a def get_random_data(annotation_line, input_shape, random=True,", "box = np.array([np.array(list(map(int,box.split(',')))) for box in line[1:]]) x_min = w", "box_data[:len(box)] = box return image_data, box_data def get_random_data2(annotation_line, input_shape, random=True,", "bbox[2]) y_max = max(y_max, bbox[3]) name = bbox[4] # 包含所有目标框的最小框到各个边的距离", "+ dy if flip: box[:, [0,2]] = w - box[:,", "= max(0, crop_x_min) crop_y_min = max(0, crop_y_min) crop_x_max = min(w,", "a def get_random_data(annotation_line, input_shape, random=True, max_boxes=20, jitter=.3, hue=.1, sat=1.5, val=1.5,", "new_image.paste(cropped, (dx, dy)) image_data = np.array(new_image)/255. box_data = np.zeros((max_boxes,5)) if", "1] box = box[np.logical_and(box_w>1, box_h>1)] # discard invalid box if", "real-time data augmentation''' line = annotation_line.split() image = Image.open(line[0]) w,", "cv2.rectangle(img2,(boxs[0],boxs[1]),(boxs[2],boxs[3]),light_blue,2) # writename=os.path.basename(line[0]) #取檔名 # cv2.imshow('My Image', img2) # cv2.waitKey(0)", "box[:max_boxes] box[:, [0,2]] = box[:, [0,2]]*scale + dx box[:, [1,3]]", "= box return image_data, box_data def get_random_data2(annotation_line, input_shape, random=True, max_boxes=20,", "d_to_right = w - x_max d_to_top = y_min d_to_bottom =", "box[:, 1] box = box[np.logical_and(box_w>1, box_h>1)] # discard invalid box", "with unchanged aspect ratio using padding''' iw, ih = image.size", "= box[:max_boxes] box[:, [0, 2]] = box[:, [0, 2]] -", "14 dx, dy = input_shape box = np.array([np.array(list(map(int,box.split(',')))) for box", "augmentation''' line = annotation_line.split() image = Image.open(line[0]) w, h =", "box if len(box)>max_boxes: box = box[:max_boxes] box_data[:len(box)] = box return", "bbox[3]) name = bbox[4] # 包含所有目标框的最小框到各个边的距离 d_to_left = x_min d_to_right", "y_min = min(y_min, bbox[1]) x_max = max(x_max, bbox[2]) y_max =", "nh = int(ih*scale) image = image.resize((nw,nh), Image.BICUBIC) new_image = Image.new('RGB',", "functions.\"\"\" from functools import reduce from PIL import Image import", "= 1 x[x<0] = 0 image_data = hsv_to_rgb(x) # numpy", "lambda *a, **kw: g(f(*a, **kw)), funcs) else: raise ValueError('Composition of", "input_shape box = np.array([np.array(list(map(int,box.split(',')))) for box in line[1:]]) if not", "crop_y_max)) # (left, upper, right, lower) new_image = Image.new('RGB', (w,h),", "val=1.5, proc_img=True): '''random preprocessing for real-time data augmentation''' line =", "g(f(*a, **kw)), funcs) else: raise ValueError('Composition of empty sequence not", "image.size #13 14 dx, dy = input_shape box = np.array([np.array(list(map(int,box.split(','))))", "(h-nh)//2 image_data=0 if proc_img: image = image.resize((nw,nh), Image.BICUBIC) new_image =", "= int(x_min - rand(0, d_to_left)) crop_y_min = int(y_min - rand(0,", "1] *= sat x[..., 2] *= val x[x>1] = 1", "crop_y_max = int(y_max + rand(0, d_to_bottom)) # 确保不出界 crop_x_min =", "box[:,1]-crop_y_min box[:,2] = box[:,2]-crop_x_min box[:,3] = box[:,3]-crop_y_min box_data[:len(box)] = box", "= size scale = min(w/iw, h/ih) nw = int(iw*scale) nh", "_ = img.shape w, h = input_shape box = np.array([np.array(list(map(int,box.split(','))))", "= max_bbox[0] max_u_trans = max_bbox[1] max_r_trans = w_img - max_bbox[2]", "# correct boxes box_data = np.zeros((max_boxes,5)) if len(box)>0: np.random.shuffle(box) box[:,", "[1,3]]*nh/ih + dy if flip: box[:, [0,2]] = w -", "annotation_line.split() image = Image.open(line[0]) w, h = image.size #13 14", "box[:,2] = box[:,2]-crop_x_min box[:,3] = box[:,3]-crop_y_min box_data[:len(box)] = box return", "2) if new_ar < 1: nh = int(scale*h) nw =", "def compose(*funcs): \"\"\"Compose arbitrarily many functions, evaluated left to right.", "**kw: g(f(*a, **kw)), funcs) else: raise ValueError('Composition of empty sequence", "- crop_xmin box[:, [1, 3]] = box[:, [1, 3]] -", "image.crop((crop_x_min, crop_y_min, crop_x_max, crop_y_max)) # (left, upper, right, lower) new_image", "box = box[:max_boxes] box_data[:len(box)] = box #標框線 # light_blue =", "y_min d_to_bottom = h - y_max # 随机扩展这个最小范围 crop_x_min =", "sat=1.5, val=1.5, proc_img=True): '''random preprocessing for real-time data augmentation''' line", "x_min = w x_max = 0 y_min = h y_max", "box return image_data, box_data def get_random_data2(annotation_line, input_shape, random=True, max_boxes=20, jitter=.3,", "nw = int(iw*scale) nh = int(ih*scale) image = image.resize((nw,nh), Image.BICUBIC)", "= rand(1, val) if rand()<.5 else 1/rand(1, val) x =", "box if len(box)>max_boxes: box = box[:max_boxes] box_data[:len(box)] = box #標框線", "max(0, int(max_bbox[0] - random.uniform(0, max_l_trans)*2)) crop_ymin = max(0, int(max_bbox[1] -", "max(x_max, bbox[2]) y_max = max(y_max, bbox[3]) name = bbox[4] #", "dx box[:, [1,3]] = box[:, [1,3]]*scale + dy box_data[:len(box)] =", "d_to_bottom)) # 确保不出界 crop_x_min = max(0, crop_x_min) crop_y_min = max(0,", "max_bbox[0] max_u_trans = max_bbox[1] max_r_trans = w_img - max_bbox[2] max_d_trans", "img = img[crop_ymin : crop_ymax, crop_xmin : crop_xmax] #進行裁剪 image", "[0,2]]*nw/iw + dx box[:, [1,3]] = box[:, [1,3]]*nh/ih + dy", "lower) new_image = Image.new('RGB', (w,h), (128,128,128)) new_image.paste(cropped, (dx, dy)) image_data", "from PIL import Image import numpy as np from matplotlib.colors", "- rand(0, d_to_top)) crop_x_max = int(x_max + rand(0, d_to_right)) crop_y_max", "= box[:, [0,2]]*scale + dx box[:, [1,3]] = box[:, [1,3]]*scale", "get_random_data2(annotation_line, input_shape, random=True, max_boxes=20, jitter=.3, hue=.1, sat=1.5, val=1.5, proc_img=True): '''random", "= image.size w, h = size scale = min(w/iw, h/ih)", "x[..., 0][x[..., 0]<0] += 1 x[..., 1] *= sat x[...,", "len(box)>0: np.random.shuffle(box) if len(box)>max_boxes: box = box[:max_boxes] box[:, [0,2]] =", "3][box[:, 3]>h] = h box_w = box[:, 2] - box[:,", "= w/h * rand(1-jitter,1+jitter)/rand(1-jitter,1+jitter) scale = rand(.25, 2) if new_ar", "max(0, crop_x_min) crop_y_min = max(0, crop_y_min) crop_x_max = min(w, crop_x_max)", "= w x_max = 0 y_min = h y_max =", "+= 1 x[..., 1] *= sat x[..., 2] *= val", "matplotlib.colors import rgb_to_hsv, hsv_to_rgb def compose(*funcs): \"\"\"Compose arbitrarily many functions,", "array, 0 to 1 # correct boxes box_data = np.zeros((max_boxes,5))", "min(h, crop_y_max) cropped = image.crop((crop_x_min, crop_y_min, crop_x_max, crop_y_max)) # (left,", "input_shape, max_boxes=20, jitter=.3, hue=.1, sat=1.5, val=1.5, proc_img=True): line = annotation_line.split()", "new_image.paste(image, (0, 0)) #將轉為PIL格式的圖片 貼到灰色圖片中 img2 = cv2.cvtColor(np.asarray(new_image),cv2.COLOR_RGB2BGR) #再將格式轉回cv2 box_data", "Image.new('RGB', (w,h), (128,128,128)) new_image.paste(image, (dx, dy)) image = new_image #", "(128,128,128)) new_image.paste(image, ((w-nw)//2, (h-nh)//2)) return new_image def rand(a=0, b=1): return", "in box: x_min = min(x_min, bbox[0]) y_min = min(y_min, bbox[1])", "= h box_w = box[:, 2] - box[:, 0] box_h", "x: reduce(lambda v, f: f(v), funcs, x) if funcs: return", "if proc_img: image = image.resize((nw,nh), Image.BICUBIC) new_image = Image.new('RGB', (w,h),", "box_data[:len(box)] = box #標框線 # light_blue = (255,200,100) # for", "rand(.25, 2) if new_ar < 1: nh = int(scale*h) nw", "sat x[..., 2] *= val x[x>1] = 1 x[x<0] =", "+ rand(0, d_to_right)) crop_y_max = int(y_max + rand(0, d_to_bottom)) #", "= img[crop_ymin : crop_ymax, crop_xmin : crop_xmax] #進行裁剪 image =", "x) if funcs: return reduce(lambda f, g: lambda *a, **kw:", "h = image.size #13 14 dx, dy = input_shape box", "box[:, [1,3]] = box[:, [1,3]]*scale + dy box_data[:len(box)] = box", "d_to_bottom = h - y_max # 随机扩展这个最小范围 crop_x_min = int(x_min", "+ a def get_random_data(annotation_line, input_shape, random=True, max_boxes=20, jitter=.3, hue=.1, sat=1.5,", "= new_image # flip image or not flip = rand()<.5", "random.uniform(0, max_r_trans)*2)) crop_ymax = max(h_img, int(max_bbox[3] + random.uniform(0, max_d_trans)*2)) img", "boxes box_data = np.zeros((max_boxes,5)) if len(box)>0: np.random.shuffle(box) box[:, [0,2]] =", "import numpy as np from matplotlib.colors import rgb_to_hsv, hsv_to_rgb def", "= max_bbox[1] max_r_trans = w_img - max_bbox[2] max_d_trans = h_img", "in line[1:]]) if not random: # resize image scale =", "= int(nh*new_ar) else: nw = int(scale*w) nh = int(nw/new_ar) image", "box[:, [2,0]] box[:, 0:2][box[:, 0:2]<0] = 0 box[:, 2][box[:, 2]>w]", "= max(y_max, bbox[3]) name = bbox[4] # 包含所有目标框的最小框到各个边的距离 d_to_left =", "int(iw*scale) nh = int(ih*scale) dx = (w-nw)//2 dy = (h-nh)//2", "np.zeros((max_boxes,5)) if len(box)>0: np.random.shuffle(box) box[:, [0,2]] = box[:, [0,2]]*nw/iw +", "int(x_min - rand(0, d_to_left)) crop_y_min = int(y_min - rand(0, d_to_top))", "dy = int(rand(0, h-nh)) new_image = Image.new('RGB', (w,h), (128,128,128)) new_image.paste(image,", "min(x_min, bbox[0]) y_min = min(y_min, bbox[1]) x_max = max(x_max, bbox[2])", "dx = int(rand(0, w-nw)) dy = int(rand(0, h-nh)) new_image =", "*a, **kw: g(f(*a, **kw)), funcs) else: raise ValueError('Composition of empty", "= rand(-hue, hue) sat = rand(1, sat) if rand()<.5 else", "= annotation_line.split() img = cv2.imread(line[0]) h_img, w_img, _ = img.shape", "numpy array, 0 to 1 # correct boxes box_data =", "2] - box[:, 0] box_h = box[:, 3] - box[:,", "letterbox_image(image, size): '''resize image with unchanged aspect ratio using padding'''", "for box in line[1:]]) if not random: # resize image", "box[:, [0,2]]*nw/iw + dx box[:, [1,3]] = box[:, [1,3]]*nh/ih +", "= int(iw*scale) nh = int(ih*scale) image = image.resize((nw,nh), Image.BICUBIC) new_image", "'''resize image with unchanged aspect ratio using padding''' iw, ih", "= 0 image_data = hsv_to_rgb(x) # numpy array, 0 to", "iw, ih = image.size w, h = size scale =", "random.uniform(0, max_l_trans)*2)) crop_ymin = max(0, int(max_bbox[1] - random.uniform(0, max_u_trans)*2)) crop_xmax", "max(h_img, int(max_bbox[3] + random.uniform(0, max_d_trans)*2)) img = img[crop_ymin : crop_ymax,", "d_to_right)) crop_y_max = int(y_max + rand(0, d_to_bottom)) # 确保不出界 crop_x_min", "reduce from PIL import Image import numpy as np from", "= (255,200,100) # for boxs in box: # cv2.rectangle(img2,(boxs[0],boxs[1]),(boxs[2],boxs[3]),light_blue,2) #", "= int(iw*scale) nh = int(ih*scale) dx = (w-nw)//2 dy =", "#隨機擴展框最大範圍 crop_xmin = max(0, int(max_bbox[0] - random.uniform(0, max_l_trans)*2)) crop_ymin =", "else: raise ValueError('Composition of empty sequence not supported.') def letterbox_image(image,", "= (w-nw)//2 dy = (h-nh)//2 image_data=0 if proc_img: image =", "image_data = np.array(new_image)/255. # correct boxes box_data = np.zeros((max_boxes,5)) if", "d_to_left = x_min d_to_right = w - x_max d_to_top =", "boxs in box: # cv2.rectangle(img2,(boxs[0],boxs[1]),(boxs[2],boxs[3]),light_blue,2) # writename=os.path.basename(line[0]) #取檔名 # cv2.imshow('My", "x = rgb_to_hsv(np.array(image)/255.) x[..., 0] += hue x[..., 0][x[..., 0]>1]", "not supported.') def letterbox_image(image, size): '''resize image with unchanged aspect", "#產出一個(416,416)的灰色圖片 new_image.paste(image, (0, 0)) #將轉為PIL格式的圖片 貼到灰色圖片中 img2 = cv2.cvtColor(np.asarray(new_image),cv2.COLOR_RGB2BGR) #再將格式轉回cv2", "box[:, [0,2]] = box[:, [0,2]]*nw/iw + dx box[:, [1,3]] =", "box = box[:max_boxes] box_data[:len(box)] = box return image_data, box_data def", "= w - x_max d_to_top = y_min d_to_bottom = h", "y_max # 随机扩展这个最小范围 crop_x_min = int(x_min - rand(0, d_to_left)) crop_y_min", "from functools import reduce from PIL import Image import numpy", "box = np.array([np.array(list(map(int,box.split(',')))) for box in line[1:]]) if not random:", "reduce(lambda f, g: lambda *a, **kw: g(f(*a, **kw)), funcs) else:", "= h - y_max # 随机扩展这个最小范围 crop_x_min = int(x_min -", "= box[:,0]-crop_y_min box[:,1] = box[:,1]-crop_y_min box[:,2] = box[:,2]-crop_x_min box[:,3] =", "min(y_min, bbox[1]) x_max = max(x_max, bbox[2]) y_max = max(y_max, bbox[3])", "- max_bbox[2] max_d_trans = h_img - max_bbox[3] #隨機擴展框最大範圍 crop_xmin =", "using padding''' iw, ih = image.size w, h = size", "import rgb_to_hsv, hsv_to_rgb def compose(*funcs): \"\"\"Compose arbitrarily many functions, evaluated", "if len(box)>max_boxes: box = box[:max_boxes] box_data[:len(box)] = box #標框線 #", "box_data[:len(box)] = box return image_data, box_data # resize image new_ar", "0][x[..., 0]>1] -= 1 x[..., 0][x[..., 0]<0] += 1 x[...,", "rgb_to_hsv, hsv_to_rgb def compose(*funcs): \"\"\"Compose arbitrarily many functions, evaluated left", "crop_y_min) crop_x_max = min(w, crop_x_max) crop_y_max = min(h, crop_y_max) cropped", "max_bbox[1] max_r_trans = w_img - max_bbox[2] max_d_trans = h_img -", "crop_x_min) crop_y_min = max(0, crop_y_min) crop_x_max = min(w, crop_x_max) crop_y_max", "d_to_top = y_min d_to_bottom = h - y_max # 随机扩展这个最小范围", "(h-nh)//2)) return new_image def rand(a=0, b=1): return np.random.rand()*(b-a) + a", "image.transpose(Image.FLIP_LEFT_RIGHT) # distort image hue = rand(-hue, hue) sat =", "if len(box)>max_boxes: box = box[:max_boxes] box[:, [0,2]] = box[:, [0,2]]*scale", "right, lower) new_image = Image.new('RGB', (w,h), (128,128,128)) new_image.paste(cropped, (dx, dy))", "image = Image.open(line[0]) w, h = image.size #13 14 dx,", "crop_y_min = max(0, crop_y_min) crop_x_max = min(w, crop_x_max) crop_y_max =", "- box[:, 0] box_h = box[:, 3] - box[:, 1]", ": crop_ymax, crop_xmin : crop_xmax] #進行裁剪 image = Image.fromarray(cv2.cvtColor(img,cv2.COLOR_BGR2RGB)) #因為目前圖片格式是cv2,因此要轉換為PIL格式做貼上的語法", "np from matplotlib.colors import rgb_to_hsv, hsv_to_rgb def compose(*funcs): \"\"\"Compose arbitrarily", "line[1:]]) max_bbox = np.concatenate([np.min(box[:, 0:2], axis=0), np.max(box[:, 2:4], axis=0)], axis=-1)#", "box = box[:max_boxes] box[:, [0,2]] = box[:, [0,2]]*scale + dx", "box[:, [0,2]] = w - box[:, [2,0]] box[:, 0:2][box[:, 0:2]<0]", "int(max_bbox[2] + random.uniform(0, max_r_trans)*2)) crop_ymax = max(h_img, int(max_bbox[3] + random.uniform(0,", "= image.transpose(Image.FLIP_LEFT_RIGHT) # distort image hue = rand(-hue, hue) sat", "box_data def get_random_data2(annotation_line, input_shape, max_boxes=20, jitter=.3, hue=.1, sat=1.5, val=1.5, proc_img=True):", "image.size w, h = size scale = min(w/iw, h/ih) nw", "= input_shape box = np.array([np.array(list(map(int,box.split(',')))) for box in line[1:]]) if", "= box[:,1]-crop_y_min box[:,2] = box[:,2]-crop_x_min box[:,3] = box[:,3]-crop_y_min box_data[:len(box)] =", "[1, 3]] = box[:, [1, 3]] - crop_ymin box[:, 2][box[:,", "right. Reference: https://mathieularose.com/function-composition-in-python/ \"\"\" # return lambda x: reduce(lambda v,", "= hsv_to_rgb(x) # numpy array, 0 to 1 # correct", "image or not flip = rand()<.5 if flip: image =", "= box[:max_boxes] box_data[:len(box)] = box #標框線 # light_blue = (255,200,100)", "[0, 2]] - crop_xmin box[:, [1, 3]] = box[:, [1,", "image.resize((nw,nh), Image.BICUBIC) new_image = Image.new('RGB', size, (128,128,128)) new_image.paste(image, ((w-nw)//2, (h-nh)//2))", "line[1:]]) x_min = w x_max = 0 y_min = h", ": crop_xmax] #進行裁剪 image = Image.fromarray(cv2.cvtColor(img,cv2.COLOR_BGR2RGB)) #因為目前圖片格式是cv2,因此要轉換為PIL格式做貼上的語法 new_image = Image.new('RGB',", "(w,h), (128,128,128)) new_image.paste(image, (dx, dy)) image_data = np.array(new_image)/255. # correct", "0 y_min = h y_max = 0 for bbox in", "funcs) else: raise ValueError('Composition of empty sequence not supported.') def", "flip image or not flip = rand()<.5 if flip: image", "1/rand(1, val) x = rgb_to_hsv(np.array(image)/255.) x[..., 0] += hue x[...,", "Image import numpy as np from matplotlib.colors import rgb_to_hsv, hsv_to_rgb", "box[:, [0,2]] = box[:, [0,2]]*scale + dx box[:, [1,3]] =", "= max(x_max, bbox[2]) y_max = max(y_max, bbox[3]) name = bbox[4]", "box[:, [1,3]] = box[:, [1,3]]*nh/ih + dy if flip: box[:,", "= 0 y_min = h y_max = 0 for bbox", "= input_shape box = np.array([np.array(list(map(int,box.split(',')))) for box in line[1:]]) max_bbox", "min(w/iw, h/ih) nw = int(iw*scale) nh = int(ih*scale) dx =", "val = rand(1, val) if rand()<.5 else 1/rand(1, val) x", "many functions, evaluated left to right. Reference: https://mathieularose.com/function-composition-in-python/ \"\"\" #", "len(box)>0: np.random.shuffle(box) box[:, [0,2]] = box[:, [0,2]]*nw/iw + dx box[:,", "import Image import numpy as np from matplotlib.colors import rgb_to_hsv,", "rand(1, sat) if rand()<.5 else 1/rand(1, sat) val = rand(1,", "= annotation_line.split() image = Image.open(line[0]) w, h = image.size #13", "= min(y_min, bbox[1]) x_max = max(x_max, bbox[2]) y_max = max(y_max,", "h = input_shape box = np.array([np.array(list(map(int,box.split(',')))) for box in line[1:]])", "new_image = Image.new('RGB', size, (128,128,128)) new_image.paste(image, ((w-nw)//2, (h-nh)//2)) return new_image", "np.array(new_image)/255. # correct boxes box_data = np.zeros((max_boxes,5)) if len(box)>0: np.random.shuffle(box)", "Image.new('RGB', (w,h), (128,128,128)) #產出一個(416,416)的灰色圖片 new_image.paste(image, (0, 0)) #將轉為PIL格式的圖片 貼到灰色圖片中 img2", "funcs, x) if funcs: return reduce(lambda f, g: lambda *a,", "h-nh)) new_image = Image.new('RGB', (w,h), (128,128,128)) new_image.paste(image, (dx, dy)) image", "= image.resize((nw,nh), Image.BICUBIC) # place image dx = int(rand(0, w-nw))", "((w-nw)//2, (h-nh)//2)) return new_image def rand(a=0, b=1): return np.random.rand()*(b-a) +", "(left, upper, right, lower) new_image = Image.new('RGB', (w,h), (128,128,128)) new_image.paste(cropped,", "ValueError('Composition of empty sequence not supported.') def letterbox_image(image, size): '''resize", "crop_xmin : crop_xmax] #進行裁剪 image = Image.fromarray(cv2.cvtColor(img,cv2.COLOR_BGR2RGB)) #因為目前圖片格式是cv2,因此要轉換為PIL格式做貼上的語法 new_image =", "- box[:, [2,0]] box[:, 0:2][box[:, 0:2]<0] = 0 box[:, 2][box[:,", "len(box)>max_boxes: box = box[:max_boxes] box[:, [0, 2]] = box[:, [0,", "dy)) image = new_image # flip image or not flip", "h_img - max_bbox[3] #隨機擴展框最大範圍 crop_xmin = max(0, int(max_bbox[0] - random.uniform(0,", "box[:, [0, 2]] = box[:, [0, 2]] - crop_xmin box[:,", "nh = int(scale*h) nw = int(nh*new_ar) else: nw = int(scale*w)", "#將轉為PIL格式的圖片 貼到灰色圖片中 img2 = cv2.cvtColor(np.asarray(new_image),cv2.COLOR_RGB2BGR) #再將格式轉回cv2 box_data = np.zeros((max_boxes,5)) #box最多有max_boxes個,即shap->(20,5)", "= box[:max_boxes] box[:,0] = box[:,0]-crop_y_min box[:,1] = box[:,1]-crop_y_min box[:,2] =", "np.zeros((max_boxes,5)) if len(box)>0: np.random.shuffle(box) if len(box)>max_boxes: box = box[:max_boxes] box[:,", "f(v), funcs, x) if funcs: return reduce(lambda f, g: lambda", "\"\"\"Compose arbitrarily many functions, evaluated left to right. Reference: https://mathieularose.com/function-composition-in-python/", "size, (128,128,128)) new_image.paste(image, ((w-nw)//2, (h-nh)//2)) return new_image def rand(a=0, b=1):", "y_max = 0 for bbox in box: x_min = min(x_min,", "box return image_data, box_data # resize image new_ar = w/h", "[0,2]]*scale + dx box[:, [1,3]] = box[:, [1,3]]*scale + dy", "line = annotation_line.split() image = Image.open(line[0]) iw, ih = image.size", "numpy as np from matplotlib.colors import rgb_to_hsv, hsv_to_rgb def compose(*funcs):", "box_data = np.zeros((max_boxes,5)) if len(box)>0: np.random.shuffle(box) box[:, [0,2]] = box[:,", "dx box[:, [1,3]] = box[:, [1,3]]*nh/ih + dy if flip:", "img2 = cv2.cvtColor(np.asarray(new_image),cv2.COLOR_RGB2BGR) #再將格式轉回cv2 box_data = np.zeros((max_boxes,5)) #box最多有max_boxes個,即shap->(20,5) #將剪裁後位移的框與原始框進行相減,避免變換之後的值過大或過小,並去除異常的box if", "= min(w/iw, h/ih) nw = int(iw*scale) nh = int(ih*scale) image", "image = image.resize((nw,nh), Image.BICUBIC) # place image dx = int(rand(0,", "data augmentation''' line = annotation_line.split() image = Image.open(line[0]) w, h", "hue=.1, sat=1.5, val=1.5, proc_img=True): '''random preprocessing for real-time data augmentation'''", "line = annotation_line.split() img = cv2.imread(line[0]) h_img, w_img, _ =", "w_img, _ = img.shape w, h = input_shape box =", "crop_ymin box[:, 2][box[:, 2]>w] = w box[:, 3][box[:, 3]>h] =", "(w,h), (128,128,128)) #產出一個(416,416)的灰色圖片 new_image.paste(image, (0, 0)) #將轉為PIL格式的圖片 貼到灰色圖片中 img2 =", "= int(scale*h) nw = int(nh*new_ar) else: nw = int(scale*w) nh", "rand(0, d_to_bottom)) # 确保不出界 crop_x_min = max(0, crop_x_min) crop_y_min =", "of empty sequence not supported.') def letterbox_image(image, size): '''resize image", "= box[:, 3] - box[:, 1] box = box[np.logical_and(box_w>1, box_h>1)]", "\"\"\"Miscellaneous utility functions.\"\"\" from functools import reduce from PIL import", "supported.') def letterbox_image(image, size): '''resize image with unchanged aspect ratio", "box[:, [0, 2]] - crop_xmin box[:, [1, 3]] = box[:,", "= np.array([np.array(list(map(int,box.split(',')))) for box in line[1:]]) if not random: #", "h/ih) nw = int(iw*scale) nh = int(ih*scale) image = image.resize((nw,nh),", "Image.fromarray(cv2.cvtColor(img,cv2.COLOR_BGR2RGB)) #因為目前圖片格式是cv2,因此要轉換為PIL格式做貼上的語法 new_image = Image.new('RGB', (w,h), (128,128,128)) #產出一個(416,416)的灰色圖片 new_image.paste(image, (0,", "random=True, max_boxes=20, jitter=.3, hue=.1, sat=1.5, val=1.5, proc_img=True): '''random preprocessing for", "2]>w] = w box[:, 3][box[:, 3]>h] = h box_w =", "empty sequence not supported.') def letterbox_image(image, size): '''resize image with", "1 x[x<0] = 0 image_data = hsv_to_rgb(x) # numpy array,", "bbox[0]) y_min = min(y_min, bbox[1]) x_max = max(x_max, bbox[2]) y_max", "box[:max_boxes] box_data[:len(box)] = box return image_data, box_data def get_random_data2(annotation_line, input_shape,", "import reduce from PIL import Image import numpy as np", "dy)) image_data = np.array(new_image)/255. # correct boxes box_data = np.zeros((max_boxes,5))", "np.random.shuffle(box) if len(box)>max_boxes: box = box[:max_boxes] box[:,0] = box[:,0]-crop_y_min box[:,1]", "int(max_bbox[0] - random.uniform(0, max_l_trans)*2)) crop_ymin = max(0, int(max_bbox[1] - random.uniform(0,", "0)) #將轉為PIL格式的圖片 貼到灰色圖片中 img2 = cv2.cvtColor(np.asarray(new_image),cv2.COLOR_RGB2BGR) #再將格式轉回cv2 box_data = np.zeros((max_boxes,5))", "#因為目前圖片格式是cv2,因此要轉換為PIL格式做貼上的語法 new_image = Image.new('RGB', (w,h), (128,128,128)) #產出一個(416,416)的灰色圖片 new_image.paste(image, (0, 0))", "box: # cv2.rectangle(img2,(boxs[0],boxs[1]),(boxs[2],boxs[3]),light_blue,2) # writename=os.path.basename(line[0]) #取檔名 # cv2.imshow('My Image', img2)", "x[..., 2] *= val x[x>1] = 1 x[x<0] = 0", "x[x>1] = 1 x[x<0] = 0 image_data = hsv_to_rgb(x) #", "place image dx = int(rand(0, w-nw)) dy = int(rand(0, h-nh))", "def get_random_data2(annotation_line, input_shape, random=True, max_boxes=20, jitter=.3, hue=.1, sat=1.5, val=1.5, proc_img=True):", "# return lambda x: reduce(lambda v, f: f(v), funcs, x)", "axis=0)], axis=-1)# 取得所有bbox中的最大bbox #包含所有目標框的最大框到各個邊的距離 max_l_trans = max_bbox[0] max_u_trans = max_bbox[1]", "if funcs: return reduce(lambda f, g: lambda *a, **kw: g(f(*a,", "len(box)>max_boxes: box = box[:max_boxes] box[:, [0,2]] = box[:, [0,2]]*scale +", "dy = input_shape box = np.array([np.array(list(map(int,box.split(',')))) for box in line[1:]])", "reduce(lambda v, f: f(v), funcs, x) if funcs: return reduce(lambda", "3]] - crop_ymin box[:, 2][box[:, 2]>w] = w box[:, 3][box[:,", "max(0, crop_y_min) crop_x_max = min(w, crop_x_max) crop_y_max = min(h, crop_y_max)", "box[:,1] = box[:,1]-crop_y_min box[:,2] = box[:,2]-crop_x_min box[:,3] = box[:,3]-crop_y_min box_data[:len(box)]", "dy)) image_data = np.array(new_image)/255. box_data = np.zeros((max_boxes,5)) if len(box)>0: np.random.shuffle(box)", "= box return image_data, box_data def get_random_data2(annotation_line, input_shape, max_boxes=20, jitter=.3,", "= Image.new('RGB', (w,h), (128,128,128)) new_image.paste(image, (dx, dy)) image = new_image", "w - box[:, [2,0]] box[:, 0:2][box[:, 0:2]<0] = 0 box[:,", "= image.resize((nw,nh), Image.BICUBIC) new_image = Image.new('RGB', (w,h), (128,128,128)) new_image.paste(image, (dx,", "correct boxes box_data = np.zeros((max_boxes,5)) if len(box)>0: np.random.shuffle(box) box[:, [0,2]]", "not flip = rand()<.5 if flip: image = image.transpose(Image.FLIP_LEFT_RIGHT) #", "= h y_max = 0 for bbox in box: x_min", "crop_ymax, crop_xmin : crop_xmax] #進行裁剪 image = Image.fromarray(cv2.cvtColor(img,cv2.COLOR_BGR2RGB)) #因為目前圖片格式是cv2,因此要轉換為PIL格式做貼上的語法 new_image", "1 x[..., 1] *= sat x[..., 2] *= val x[x>1]", "= input_shape box = np.array([np.array(list(map(int,box.split(',')))) for box in line[1:]]) x_min", "image_data = np.array(new_image)/255. box_data = np.zeros((max_boxes,5)) if len(box)>0: np.random.shuffle(box) if", "scale = min(w/iw, h/ih) nw = int(iw*scale) nh = int(ih*scale)", "= image.size #13 14 dx, dy = input_shape box =", "scale = rand(.25, 2) if new_ar < 1: nh =", "get_random_data2(annotation_line, input_shape, max_boxes=20, jitter=.3, hue=.1, sat=1.5, val=1.5, proc_img=True): line =", "rand(1-jitter,1+jitter)/rand(1-jitter,1+jitter) scale = rand(.25, 2) if new_ar < 1: nh", "- max_bbox[3] #隨機擴展框最大範圍 crop_xmin = max(0, int(max_bbox[0] - random.uniform(0, max_l_trans)*2))", "crop_x_max, crop_y_max)) # (left, upper, right, lower) new_image = Image.new('RGB',", "to right. Reference: https://mathieularose.com/function-composition-in-python/ \"\"\" # return lambda x: reduce(lambda", "rand(-hue, hue) sat = rand(1, sat) if rand()<.5 else 1/rand(1,", "- x_max d_to_top = y_min d_to_bottom = h - y_max", "img = cv2.imread(line[0]) h_img, w_img, _ = img.shape w, h", "w/h * rand(1-jitter,1+jitter)/rand(1-jitter,1+jitter) scale = rand(.25, 2) if new_ar <", "2]] = box[:, [0, 2]] - crop_xmin box[:, [1, 3]]", "x[..., 1] *= sat x[..., 2] *= val x[x>1] =", "if flip: box[:, [0,2]] = w - box[:, [2,0]] box[:,", "= Image.new('RGB', (w,h), (128,128,128)) #產出一個(416,416)的灰色圖片 new_image.paste(image, (0, 0)) #將轉為PIL格式的圖片 貼到灰色圖片中", "max_u_trans = max_bbox[1] max_r_trans = w_img - max_bbox[2] max_d_trans =", "box[:,3] = box[:,3]-crop_y_min box_data[:len(box)] = box return image_data, box_data def", "[1,3]] = box[:, [1,3]]*scale + dy box_data[:len(box)] = box return", "nw = int(iw*scale) nh = int(ih*scale) dx = (w-nw)//2 dy", "= np.zeros((max_boxes,5)) if len(box)>0: np.random.shuffle(box) box[:, [0,2]] = box[:, [0,2]]*nw/iw", "# 确保不出界 crop_x_min = max(0, crop_x_min) crop_y_min = max(0, crop_y_min)", "int(max_bbox[1] - random.uniform(0, max_u_trans)*2)) crop_xmax = max(w_img, int(max_bbox[2] + random.uniform(0,", "box = box[:max_boxes] box[:, [0, 2]] = box[:, [0, 2]]", "image_data=0 if proc_img: image = image.resize((nw,nh), Image.BICUBIC) new_image = Image.new('RGB',", "max_r_trans = w_img - max_bbox[2] max_d_trans = h_img - max_bbox[3]", "image with unchanged aspect ratio using padding''' iw, ih =", "if len(box)>0: np.random.shuffle(box) if len(box)>max_boxes: box = box[:max_boxes] box[:, [0,2]]", "rand()<.5 else 1/rand(1, val) x = rgb_to_hsv(np.array(image)/255.) x[..., 0] +=", "h box_w = box[:, 2] - box[:, 0] box_h =", "(255,200,100) # for boxs in box: # cv2.rectangle(img2,(boxs[0],boxs[1]),(boxs[2],boxs[3]),light_blue,2) # writename=os.path.basename(line[0])", "crop_x_max) crop_y_max = min(h, crop_y_max) cropped = image.crop((crop_x_min, crop_y_min, crop_x_max,", "max_r_trans)*2)) crop_ymax = max(h_img, int(max_bbox[3] + random.uniform(0, max_d_trans)*2)) img =", "box[:max_boxes] box_data[:len(box)] = box #標框線 # light_blue = (255,200,100) #", "image = Image.open(line[0]) iw, ih = image.size h, w =", "hue x[..., 0][x[..., 0]>1] -= 1 x[..., 0][x[..., 0]<0] +=", "\"\"\" # return lambda x: reduce(lambda v, f: f(v), funcs,", "= w box[:, 3][box[:, 3]>h] = h box_w = box[:,", "w x_max = 0 y_min = h y_max = 0", "len(box)>0: np.random.shuffle(box) if len(box)>max_boxes: box = box[:max_boxes] box[:,0] = box[:,0]-crop_y_min", "unchanged aspect ratio using padding''' iw, ih = image.size w,", "b=1): return np.random.rand()*(b-a) + a def get_random_data(annotation_line, input_shape, random=True, max_boxes=20,", "= rgb_to_hsv(np.array(image)/255.) x[..., 0] += hue x[..., 0][x[..., 0]>1] -=", "h_img, w_img, _ = img.shape w, h = input_shape box", "input_shape box = np.array([np.array(list(map(int,box.split(',')))) for box in line[1:]]) max_bbox =", "else 1/rand(1, sat) val = rand(1, val) if rand()<.5 else", "0][x[..., 0]<0] += 1 x[..., 1] *= sat x[..., 2]", "box[:, [1, 3]] = box[:, [1, 3]] - crop_ymin box[:,", "sat = rand(1, sat) if rand()<.5 else 1/rand(1, sat) val", "确保不出界 crop_x_min = max(0, crop_x_min) crop_y_min = max(0, crop_y_min) crop_x_max", "#取檔名 # cv2.imshow('My Image', img2) # cv2.waitKey(0) return img2, box_data", "+ dy box_data[:len(box)] = box return image_data, box_data # resize", "if rand()<.5 else 1/rand(1, sat) val = rand(1, val) if", "line[1:]]) if not random: # resize image scale = min(w/iw,", "1 # correct boxes box_data = np.zeros((max_boxes,5)) if len(box)>0: np.random.shuffle(box)", "x_max d_to_top = y_min d_to_bottom = h - y_max #", "img.shape w, h = input_shape box = np.array([np.array(list(map(int,box.split(',')))) for box", "axis=-1)# 取得所有bbox中的最大bbox #包含所有目標框的最大框到各個邊的距離 max_l_trans = max_bbox[0] max_u_trans = max_bbox[1] max_r_trans", "= (h-nh)//2 image_data=0 if proc_img: image = image.resize((nw,nh), Image.BICUBIC) new_image", "y_min = h y_max = 0 for bbox in box:", "len(box)>max_boxes: box = box[:max_boxes] box_data[:len(box)] = box return image_data, box_data", "raise ValueError('Composition of empty sequence not supported.') def letterbox_image(image, size):", "crop_ymax = max(h_img, int(max_bbox[3] + random.uniform(0, max_d_trans)*2)) img = img[crop_ymin", "0:2]<0] = 0 box[:, 2][box[:, 2]>w] = w box[:, 3][box[:,", "np.array([np.array(list(map(int,box.split(',')))) for box in line[1:]]) x_min = w x_max =", "new_image = Image.new('RGB', (w,h), (128,128,128)) new_image.paste(image, (dx, dy)) image_data =", "(w-nw)//2 dy = (h-nh)//2 image_data=0 if proc_img: image = image.resize((nw,nh),", "# correct boxes box_data = np.zeros((max_boxes,5)) if len(box)>0: np.random.shuffle(box) if", "image = new_image # flip image or not flip =", "dx, dy = input_shape box = np.array([np.array(list(map(int,box.split(',')))) for box in", "# (left, upper, right, lower) new_image = Image.new('RGB', (w,h), (128,128,128))", "[0,2]] = box[:, [0,2]]*scale + dx box[:, [1,3]] = box[:,", "img[crop_ymin : crop_ymax, crop_xmin : crop_xmax] #進行裁剪 image = Image.fromarray(cv2.cvtColor(img,cv2.COLOR_BGR2RGB))", "= cv2.cvtColor(np.asarray(new_image),cv2.COLOR_RGB2BGR) #再將格式轉回cv2 box_data = np.zeros((max_boxes,5)) #box最多有max_boxes個,即shap->(20,5) #將剪裁後位移的框與原始框進行相減,避免變換之後的值過大或過小,並去除異常的box if len(box)>0:", "w = input_shape box = np.array([np.array(list(map(int,box.split(',')))) for box in line[1:]])", "- crop_ymin box[:, 2][box[:, 2]>w] = w box[:, 3][box[:, 3]>h]", "Image.new('RGB', (w,h), (128,128,128)) new_image.paste(image, (dx, dy)) image_data = np.array(new_image)/255. #", "= cv2.imread(line[0]) h_img, w_img, _ = img.shape w, h =", "[2,0]] box[:, 0:2][box[:, 0:2]<0] = 0 box[:, 2][box[:, 2]>w] =", "crop_y_min = int(y_min - rand(0, d_to_top)) crop_x_max = int(x_max +", "annotation_line.split() img = cv2.imread(line[0]) h_img, w_img, _ = img.shape w,", "val=1.5, proc_img=True): line = annotation_line.split() img = cv2.imread(line[0]) h_img, w_img,", "return new_image def rand(a=0, b=1): return np.random.rand()*(b-a) + a def", "w, h = size scale = min(w/iw, h/ih) nw =", "image hue = rand(-hue, hue) sat = rand(1, sat) if", "crop_xmin = max(0, int(max_bbox[0] - random.uniform(0, max_l_trans)*2)) crop_ymin = max(0,", "len(box)>max_boxes: box = box[:max_boxes] box_data[:len(box)] = box #標框線 # light_blue", "0]>1] -= 1 x[..., 0][x[..., 0]<0] += 1 x[..., 1]", "rand()<.5 else 1/rand(1, sat) val = rand(1, val) if rand()<.5", "crop_y_min, crop_x_max, crop_y_max)) # (left, upper, right, lower) new_image =", "box[:, [1,3]]*nh/ih + dy if flip: box[:, [0,2]] = w", "box_w = box[:, 2] - box[:, 0] box_h = box[:,", "#再將格式轉回cv2 box_data = np.zeros((max_boxes,5)) #box最多有max_boxes個,即shap->(20,5) #將剪裁後位移的框與原始框進行相減,避免變換之後的值過大或過小,並去除異常的box if len(box)>0: np.random.shuffle(box) if", "* rand(1-jitter,1+jitter)/rand(1-jitter,1+jitter) scale = rand(.25, 2) if new_ar < 1:", "image scale = min(w/iw, h/ih) nw = int(iw*scale) nh =", "dx = (w-nw)//2 dy = (h-nh)//2 image_data=0 if proc_img: image", "= int(y_max + rand(0, d_to_bottom)) # 确保不出界 crop_x_min = max(0,", "random.uniform(0, max_d_trans)*2)) img = img[crop_ymin : crop_ymax, crop_xmin : crop_xmax]", "np.array([np.array(list(map(int,box.split(',')))) for box in line[1:]]) if not random: # resize", "# resize image scale = min(w/iw, h/ih) nw = int(iw*scale)", "nh = int(nw/new_ar) image = image.resize((nw,nh), Image.BICUBIC) # place image", "in line[1:]]) x_min = w x_max = 0 y_min =", "sat) val = rand(1, val) if rand()<.5 else 1/rand(1, val)", "- random.uniform(0, max_u_trans)*2)) crop_xmax = max(w_img, int(max_bbox[2] + random.uniform(0, max_r_trans)*2))", "not random: # resize image scale = min(w/iw, h/ih) nw", "box in line[1:]]) if not random: # resize image scale", "Image.BICUBIC) new_image = Image.new('RGB', size, (128,128,128)) new_image.paste(image, ((w-nw)//2, (h-nh)//2)) return", "proc_img=True): line = annotation_line.split() img = cv2.imread(line[0]) h_img, w_img, _", "boxes box_data = np.zeros((max_boxes,5)) if len(box)>0: np.random.shuffle(box) if len(box)>max_boxes: box", "= min(w, crop_x_max) crop_y_max = min(h, crop_y_max) cropped = image.crop((crop_x_min,", "rand(0, d_to_left)) crop_y_min = int(y_min - rand(0, d_to_top)) crop_x_max =", "if flip: image = image.transpose(Image.FLIP_LEFT_RIGHT) # distort image hue =", "0] box_h = box[:, 3] - box[:, 1] box =", "dy if flip: box[:, [0,2]] = w - box[:, [2,0]]", "w, h = input_shape box = np.array([np.array(list(map(int,box.split(',')))) for box in", "# writename=os.path.basename(line[0]) #取檔名 # cv2.imshow('My Image', img2) # cv2.waitKey(0) return", "proc_img=True): '''random preprocessing for real-time data augmentation''' line = annotation_line.split()", "= Image.new('RGB', size, (128,128,128)) new_image.paste(image, ((w-nw)//2, (h-nh)//2)) return new_image def", "0 to 1 # correct boxes box_data = np.zeros((max_boxes,5)) if", "= 0 for bbox in box: x_min = min(x_min, bbox[0])", "= rand(1, sat) if rand()<.5 else 1/rand(1, sat) val =", "np.random.shuffle(box) if len(box)>max_boxes: box = box[:max_boxes] box[:, [0, 2]] =", "= int(ih*scale) dx = (w-nw)//2 dy = (h-nh)//2 image_data=0 if", "[1,3]]*scale + dy box_data[:len(box)] = box return image_data, box_data #", "image new_ar = w/h * rand(1-jitter,1+jitter)/rand(1-jitter,1+jitter) scale = rand(.25, 2)", "int(max_bbox[3] + random.uniform(0, max_d_trans)*2)) img = img[crop_ymin : crop_ymax, crop_xmin", "= np.array(new_image)/255. box_data = np.zeros((max_boxes,5)) if len(box)>0: np.random.shuffle(box) if len(box)>max_boxes:", "= box[:, 2] - box[:, 0] box_h = box[:, 3]", "(128,128,128)) new_image.paste(cropped, (dx, dy)) image_data = np.array(new_image)/255. box_data = np.zeros((max_boxes,5))", "box[:, 2] - box[:, 0] box_h = box[:, 3] -", "= image.size h, w = input_shape box = np.array([np.array(list(map(int,box.split(',')))) for", "box = np.array([np.array(list(map(int,box.split(',')))) for box in line[1:]]) max_bbox = np.concatenate([np.min(box[:,", "lambda x: reduce(lambda v, f: f(v), funcs, x) if funcs:", "w, h = image.size #13 14 dx, dy = input_shape", "flip = rand()<.5 if flip: image = image.transpose(Image.FLIP_LEFT_RIGHT) # distort", "if len(box)>0: np.random.shuffle(box) if len(box)>max_boxes: box = box[:max_boxes] box[:,0] =", "new_image.paste(image, (dx, dy)) image_data = np.array(new_image)/255. # correct boxes box_data", "#包含所有目標框的最大框到各個邊的距離 max_l_trans = max_bbox[0] max_u_trans = max_bbox[1] max_r_trans = w_img", "= box[:max_boxes] box_data[:len(box)] = box return image_data, box_data def get_random_data2(annotation_line,", "w box[:, 3][box[:, 3]>h] = h box_w = box[:, 2]", "= np.concatenate([np.min(box[:, 0:2], axis=0), np.max(box[:, 2:4], axis=0)], axis=-1)# 取得所有bbox中的最大bbox #包含所有目標框的最大框到各個邊的距離", "crop_xmax = max(w_img, int(max_bbox[2] + random.uniform(0, max_r_trans)*2)) crop_ymax = max(h_img,", "box[:,0]-crop_y_min box[:,1] = box[:,1]-crop_y_min box[:,2] = box[:,2]-crop_x_min box[:,3] = box[:,3]-crop_y_min", "bbox[1]) x_max = max(x_max, bbox[2]) y_max = max(y_max, bbox[3]) name", "= rand(.25, 2) if new_ar < 1: nh = int(scale*h)", "crop_y_max) cropped = image.crop((crop_x_min, crop_y_min, crop_x_max, crop_y_max)) # (left, upper,", "if len(box)>max_boxes: box = box[:max_boxes] box[:,0] = box[:,0]-crop_y_min box[:,1] =", "d_to_left)) crop_y_min = int(y_min - rand(0, d_to_top)) crop_x_max = int(x_max", "max_u_trans)*2)) crop_xmax = max(w_img, int(max_bbox[2] + random.uniform(0, max_r_trans)*2)) crop_ymax =", "h = size scale = min(w/iw, h/ih) nw = int(iw*scale)", "max(w_img, int(max_bbox[2] + random.uniform(0, max_r_trans)*2)) crop_ymax = max(h_img, int(max_bbox[3] +", "2]] - crop_xmin box[:, [1, 3]] = box[:, [1, 3]]", "貼到灰色圖片中 img2 = cv2.cvtColor(np.asarray(new_image),cv2.COLOR_RGB2BGR) #再將格式轉回cv2 box_data = np.zeros((max_boxes,5)) #box最多有max_boxes個,即shap->(20,5) #將剪裁後位移的框與原始框進行相減,避免變換之後的值過大或過小,並去除異常的box", "(128,128,128)) #產出一個(416,416)的灰色圖片 new_image.paste(image, (0, 0)) #將轉為PIL格式的圖片 貼到灰色圖片中 img2 = cv2.cvtColor(np.asarray(new_image),cv2.COLOR_RGB2BGR)", "jitter=.3, hue=.1, sat=1.5, val=1.5, proc_img=True): '''random preprocessing for real-time data", "# cv2.rectangle(img2,(boxs[0],boxs[1]),(boxs[2],boxs[3]),light_blue,2) # writename=os.path.basename(line[0]) #取檔名 # cv2.imshow('My Image', img2) #", "int(ih*scale) image = image.resize((nw,nh), Image.BICUBIC) new_image = Image.new('RGB', size, (128,128,128))", "max_bbox[3] #隨機擴展框最大範圍 crop_xmin = max(0, int(max_bbox[0] - random.uniform(0, max_l_trans)*2)) crop_ymin", "bbox[4] # 包含所有目标框的最小框到各个边的距离 d_to_left = x_min d_to_right = w -", "= np.array([np.array(list(map(int,box.split(',')))) for box in line[1:]]) max_bbox = np.concatenate([np.min(box[:, 0:2],", "max_l_trans)*2)) crop_ymin = max(0, int(max_bbox[1] - random.uniform(0, max_u_trans)*2)) crop_xmax =", "= box[:, [1,3]]*nh/ih + dy if flip: box[:, [0,2]] =", "return image_data, box_data def get_random_data2(annotation_line, input_shape, max_boxes=20, jitter=.3, hue=.1, sat=1.5,", "= x_min d_to_right = w - x_max d_to_top = y_min", "x_min = min(x_min, bbox[0]) y_min = min(y_min, bbox[1]) x_max =", "max_l_trans = max_bbox[0] max_u_trans = max_bbox[1] max_r_trans = w_img -", "#13 14 dx, dy = input_shape box = np.array([np.array(list(map(int,box.split(',')))) for", "box[:, 3] - box[:, 1] box = box[np.logical_and(box_w>1, box_h>1)] #", "proc_img: image = image.resize((nw,nh), Image.BICUBIC) new_image = Image.new('RGB', (w,h), (128,128,128))", "line = annotation_line.split() image = Image.open(line[0]) w, h = image.size", "= int(y_min - rand(0, d_to_top)) crop_x_max = int(x_max + rand(0,", "hue=.1, sat=1.5, val=1.5, proc_img=True): line = annotation_line.split() img = cv2.imread(line[0])", "+ random.uniform(0, max_d_trans)*2)) img = img[crop_ymin : crop_ymax, crop_xmin :", "for bbox in box: x_min = min(x_min, bbox[0]) y_min =", "= np.array([np.array(list(map(int,box.split(',')))) for box in line[1:]]) x_min = w x_max", "0] += hue x[..., 0][x[..., 0]>1] -= 1 x[..., 0][x[...,", "# flip image or not flip = rand()<.5 if flip:", "= Image.new('RGB', (w,h), (128,128,128)) new_image.paste(image, (dx, dy)) image_data = np.array(new_image)/255.", "x_max = max(x_max, bbox[2]) y_max = max(y_max, bbox[3]) name =", "w - x_max d_to_top = y_min d_to_bottom = h -", "int(y_max + rand(0, d_to_bottom)) # 确保不出界 crop_x_min = max(0, crop_x_min)", "= max(h_img, int(max_bbox[3] + random.uniform(0, max_d_trans)*2)) img = img[crop_ymin :", "funcs: return reduce(lambda f, g: lambda *a, **kw: g(f(*a, **kw)),", "preprocessing for real-time data augmentation''' line = annotation_line.split() image =", "dy box_data[:len(box)] = box return image_data, box_data # resize image", "Image.BICUBIC) new_image = Image.new('RGB', (w,h), (128,128,128)) new_image.paste(image, (dx, dy)) image_data", "= int(rand(0, h-nh)) new_image = Image.new('RGB', (w,h), (128,128,128)) new_image.paste(image, (dx,", "[1, 3]] - crop_ymin box[:, 2][box[:, 2]>w] = w box[:,", "rgb_to_hsv(np.array(image)/255.) x[..., 0] += hue x[..., 0][x[..., 0]>1] -= 1", "Reference: https://mathieularose.com/function-composition-in-python/ \"\"\" # return lambda x: reduce(lambda v, f:", "0 image_data = hsv_to_rgb(x) # numpy array, 0 to 1", "val x[x>1] = 1 x[x<0] = 0 image_data = hsv_to_rgb(x)", "#標框線 # light_blue = (255,200,100) # for boxs in box:", "image = Image.fromarray(cv2.cvtColor(img,cv2.COLOR_BGR2RGB)) #因為目前圖片格式是cv2,因此要轉換為PIL格式做貼上的語法 new_image = Image.new('RGB', (w,h), (128,128,128)) #產出一個(416,416)的灰色圖片", "box[:max_boxes] box[:, [0, 2]] = box[:, [0, 2]] - crop_xmin", "augmentation''' line = annotation_line.split() image = Image.open(line[0]) iw, ih =", "functools import reduce from PIL import Image import numpy as", "max_bbox[2] max_d_trans = h_img - max_bbox[3] #隨機擴展框最大範圍 crop_xmin = max(0,", "'''random preprocessing for real-time data augmentation''' line = annotation_line.split() image", "box in line[1:]]) x_min = w x_max = 0 y_min", "Image.new('RGB', (w,h), (128,128,128)) new_image.paste(cropped, (dx, dy)) image_data = np.array(new_image)/255. box_data", "new_image.paste(image, ((w-nw)//2, (h-nh)//2)) return new_image def rand(a=0, b=1): return np.random.rand()*(b-a)", "padding''' iw, ih = image.size w, h = size scale", "if not random: # resize image scale = min(w/iw, h/ih)", "= bbox[4] # 包含所有目标框的最小框到各个边的距离 d_to_left = x_min d_to_right = w", "= w_img - max_bbox[2] max_d_trans = h_img - max_bbox[3] #隨機擴展框最大範圍", "+ random.uniform(0, max_r_trans)*2)) crop_ymax = max(h_img, int(max_bbox[3] + random.uniform(0, max_d_trans)*2))", "return lambda x: reduce(lambda v, f: f(v), funcs, x) if", "left to right. Reference: https://mathieularose.com/function-composition-in-python/ \"\"\" # return lambda x:", "rand(1, val) if rand()<.5 else 1/rand(1, val) x = rgb_to_hsv(np.array(image)/255.)", "= box[:, [1, 3]] - crop_ymin box[:, 2][box[:, 2]>w] =", "np.random.rand()*(b-a) + a def get_random_data(annotation_line, input_shape, random=True, max_boxes=20, jitter=.3, hue=.1,", "v, f: f(v), funcs, x) if funcs: return reduce(lambda f,", "= int(scale*w) nh = int(nw/new_ar) image = image.resize((nw,nh), Image.BICUBIC) #", "utility functions.\"\"\" from functools import reduce from PIL import Image", "1/rand(1, sat) val = rand(1, val) if rand()<.5 else 1/rand(1,", "Image.open(line[0]) w, h = image.size #13 14 dx, dy =", "cropped = image.crop((crop_x_min, crop_y_min, crop_x_max, crop_y_max)) # (left, upper, right,", "# 包含所有目标框的最小框到各个边的距离 d_to_left = x_min d_to_right = w - x_max", "image_data, box_data # resize image new_ar = w/h * rand(1-jitter,1+jitter)/rand(1-jitter,1+jitter)", "image = image.transpose(Image.FLIP_LEFT_RIGHT) # distort image hue = rand(-hue, hue)", "(0, 0)) #將轉為PIL格式的圖片 貼到灰色圖片中 img2 = cv2.cvtColor(np.asarray(new_image),cv2.COLOR_RGB2BGR) #再將格式轉回cv2 box_data =", "[0,2]] = w - box[:, [2,0]] box[:, 0:2][box[:, 0:2]<0] =", "for real-time data augmentation''' line = annotation_line.split() image = Image.open(line[0])", "box[:, [1, 3]] - crop_ymin box[:, 2][box[:, 2]>w] = w", "new_ar = w/h * rand(1-jitter,1+jitter)/rand(1-jitter,1+jitter) scale = rand(.25, 2) if", "ratio using padding''' iw, ih = image.size w, h =", "random: # resize image scale = min(w/iw, h/ih) nw =", "= 0 box[:, 2][box[:, 2]>w] = w box[:, 3][box[:, 3]>h]", "= np.array(new_image)/255. # correct boxes box_data = np.zeros((max_boxes,5)) if len(box)>0:", "1: nh = int(scale*h) nw = int(nh*new_ar) else: nw =", "axis=0), np.max(box[:, 2:4], axis=0)], axis=-1)# 取得所有bbox中的最大bbox #包含所有目標框的最大框到各個邊的距離 max_l_trans = max_bbox[0]", "= max(0, int(max_bbox[1] - random.uniform(0, max_u_trans)*2)) crop_xmax = max(w_img, int(max_bbox[2]", "#box最多有max_boxes個,即shap->(20,5) #將剪裁後位移的框與原始框進行相減,避免變換之後的值過大或過小,並去除異常的box if len(box)>0: np.random.shuffle(box) if len(box)>max_boxes: box = box[:max_boxes]", "2][box[:, 2]>w] = w box[:, 3][box[:, 3]>h] = h box_w", "= int(nw/new_ar) image = image.resize((nw,nh), Image.BICUBIC) # place image dx", "box_data[:len(box)] = box return image_data, box_data def get_random_data2(annotation_line, input_shape, max_boxes=20,", "if len(box)>0: np.random.shuffle(box) if len(box)>max_boxes: box = box[:max_boxes] box[:, [0,", "0:2][box[:, 0:2]<0] = 0 box[:, 2][box[:, 2]>w] = w box[:,", "2:4], axis=0)], axis=-1)# 取得所有bbox中的最大bbox #包含所有目標框的最大框到各個邊的距離 max_l_trans = max_bbox[0] max_u_trans =", "size): '''resize image with unchanged aspect ratio using padding''' iw,", "if len(box)>0: np.random.shuffle(box) box[:, [0,2]] = box[:, [0,2]]*nw/iw + dx", "1 x[..., 0][x[..., 0]<0] += 1 x[..., 1] *= sat", "-= 1 x[..., 0][x[..., 0]<0] += 1 x[..., 1] *=", "2] *= val x[x>1] = 1 x[x<0] = 0 image_data", "= h_img - max_bbox[3] #隨機擴展框最大範圍 crop_xmin = max(0, int(max_bbox[0] -", "crop_xmin box[:, [1, 3]] = box[:, [1, 3]] - crop_ymin", "in box: # cv2.rectangle(img2,(boxs[0],boxs[1]),(boxs[2],boxs[3]),light_blue,2) # writename=os.path.basename(line[0]) #取檔名 # cv2.imshow('My Image',", "# resize image new_ar = w/h * rand(1-jitter,1+jitter)/rand(1-jitter,1+jitter) scale =", "upper, right, lower) new_image = Image.new('RGB', (w,h), (128,128,128)) new_image.paste(cropped, (dx,", "(dx, dy)) image_data = np.array(new_image)/255. box_data = np.zeros((max_boxes,5)) if len(box)>0:", "max_d_trans = h_img - max_bbox[3] #隨機擴展框最大範圍 crop_xmin = max(0, int(max_bbox[0]", "box_data = np.zeros((max_boxes,5)) if len(box)>0: np.random.shuffle(box) if len(box)>max_boxes: box =", "(w,h), (128,128,128)) new_image.paste(cropped, (dx, dy)) image_data = np.array(new_image)/255. box_data =", "# place image dx = int(rand(0, w-nw)) dy = int(rand(0,", "[1,3]] = box[:, [1,3]]*nh/ih + dy if flip: box[:, [0,2]]", "= y_min d_to_bottom = h - y_max # 随机扩展这个最小范围 crop_x_min", "= min(w/iw, h/ih) nw = int(iw*scale) nh = int(ih*scale) dx", "crop_xmax] #進行裁剪 image = Image.fromarray(cv2.cvtColor(img,cv2.COLOR_BGR2RGB)) #因為目前圖片格式是cv2,因此要轉換為PIL格式做貼上的語法 new_image = Image.new('RGB', (w,h),", "writename=os.path.basename(line[0]) #取檔名 # cv2.imshow('My Image', img2) # cv2.waitKey(0) return img2,", "new_image # flip image or not flip = rand()<.5 if", "for box in line[1:]]) x_min = w x_max = 0", "np.zeros((max_boxes,5)) #box最多有max_boxes個,即shap->(20,5) #將剪裁後位移的框與原始框進行相減,避免變換之後的值過大或過小,並去除異常的box if len(box)>0: np.random.shuffle(box) if len(box)>max_boxes: box =", "Image.new('RGB', size, (128,128,128)) new_image.paste(image, ((w-nw)//2, (h-nh)//2)) return new_image def rand(a=0,", "< 1: nh = int(scale*h) nw = int(nh*new_ar) else: nw", "box_data def get_random_data2(annotation_line, input_shape, random=True, max_boxes=20, jitter=.3, hue=.1, sat=1.5, val=1.5,", "rand(0, d_to_top)) crop_x_max = int(x_max + rand(0, d_to_right)) crop_y_max =", "evaluated left to right. Reference: https://mathieularose.com/function-composition-in-python/ \"\"\" # return lambda", "resize image new_ar = w/h * rand(1-jitter,1+jitter)/rand(1-jitter,1+jitter) scale = rand(.25,", "= max(0, int(max_bbox[0] - random.uniform(0, max_l_trans)*2)) crop_ymin = max(0, int(max_bbox[1]", "h, w = input_shape box = np.array([np.array(list(map(int,box.split(',')))) for box in", "- y_max # 随机扩展这个最小范围 crop_x_min = int(x_min - rand(0, d_to_left))", "crop_x_min = max(0, crop_x_min) crop_y_min = max(0, crop_y_min) crop_x_max =", "包含所有目标框的最小框到各个边的距离 d_to_left = x_min d_to_right = w - x_max d_to_top", "nw = int(nh*new_ar) else: nw = int(scale*w) nh = int(nw/new_ar)", "= img.shape w, h = input_shape box = np.array([np.array(list(map(int,box.split(',')))) for", "g: lambda *a, **kw: g(f(*a, **kw)), funcs) else: raise ValueError('Composition", "# for boxs in box: # cv2.rectangle(img2,(boxs[0],boxs[1]),(boxs[2],boxs[3]),light_blue,2) # writename=os.path.basename(line[0]) #取檔名", "as np from matplotlib.colors import rgb_to_hsv, hsv_to_rgb def compose(*funcs): \"\"\"Compose", "discard invalid box if len(box)>max_boxes: box = box[:max_boxes] box_data[:len(box)] =", "new_image def rand(a=0, b=1): return np.random.rand()*(b-a) + a def get_random_data(annotation_line,", "- rand(0, d_to_left)) crop_y_min = int(y_min - rand(0, d_to_top)) crop_x_max", "nh = int(ih*scale) dx = (w-nw)//2 dy = (h-nh)//2 image_data=0", "= w - box[:, [2,0]] box[:, 0:2][box[:, 0:2]<0] = 0", "- box[:, 1] box = box[np.logical_and(box_w>1, box_h>1)] # discard invalid", "PIL import Image import numpy as np from matplotlib.colors import", "x[..., 0][x[..., 0]>1] -= 1 x[..., 0][x[..., 0]<0] += 1", "cv2.imread(line[0]) h_img, w_img, _ = img.shape w, h = input_shape", "np.array([np.array(list(map(int,box.split(',')))) for box in line[1:]]) max_bbox = np.concatenate([np.min(box[:, 0:2], axis=0),", "from matplotlib.colors import rgb_to_hsv, hsv_to_rgb def compose(*funcs): \"\"\"Compose arbitrarily many", "min(w, crop_x_max) crop_y_max = min(h, crop_y_max) cropped = image.crop((crop_x_min, crop_y_min,", "image.size h, w = input_shape box = np.array([np.array(list(map(int,box.split(',')))) for box", "new_image = Image.new('RGB', (w,h), (128,128,128)) #產出一個(416,416)的灰色圖片 new_image.paste(image, (0, 0)) #將轉為PIL格式的圖片", "aspect ratio using padding''' iw, ih = image.size w, h", "= int(ih*scale) image = image.resize((nw,nh), Image.BICUBIC) new_image = Image.new('RGB', size,", "*= sat x[..., 2] *= val x[x>1] = 1 x[x<0]", "# numpy array, 0 to 1 # correct boxes box_data", "box in line[1:]]) max_bbox = np.concatenate([np.min(box[:, 0:2], axis=0), np.max(box[:, 2:4],", "= min(x_min, bbox[0]) y_min = min(y_min, bbox[1]) x_max = max(x_max,", "new_image = Image.new('RGB', (w,h), (128,128,128)) new_image.paste(cropped, (dx, dy)) image_data =", "image = image.resize((nw,nh), Image.BICUBIC) new_image = Image.new('RGB', (w,h), (128,128,128)) new_image.paste(image,", "max_boxes=20, jitter=.3, hue=.1, sat=1.5, val=1.5, proc_img=True): line = annotation_line.split() img", "box[:, 2][box[:, 2]>w] = w box[:, 3][box[:, 3]>h] = h", "else: nw = int(scale*w) nh = int(nw/new_ar) image = image.resize((nw,nh),", "0:2], axis=0), np.max(box[:, 2:4], axis=0)], axis=-1)# 取得所有bbox中的最大bbox #包含所有目標框的最大框到各個邊的距離 max_l_trans =", "box[:,0] = box[:,0]-crop_y_min box[:,1] = box[:,1]-crop_y_min box[:,2] = box[:,2]-crop_x_min box[:,3]", "int(x_max + rand(0, d_to_right)) crop_y_max = int(y_max + rand(0, d_to_bottom))", "image = image.resize((nw,nh), Image.BICUBIC) new_image = Image.new('RGB', size, (128,128,128)) new_image.paste(image,", "[0,2]] = box[:, [0,2]]*nw/iw + dx box[:, [1,3]] = box[:,", "return image_data, box_data def get_random_data2(annotation_line, input_shape, random=True, max_boxes=20, jitter=.3, hue=.1,", "box[:,3]-crop_y_min box_data[:len(box)] = box return image_data, box_data def get_random_data2(annotation_line, input_shape,", "max_boxes=20, jitter=.3, hue=.1, sat=1.5, val=1.5, proc_img=True): '''random preprocessing for real-time", "return reduce(lambda f, g: lambda *a, **kw: g(f(*a, **kw)), funcs)", "(128,128,128)) new_image.paste(image, (dx, dy)) image_data = np.array(new_image)/255. # correct boxes", "int(ih*scale) dx = (w-nw)//2 dy = (h-nh)//2 image_data=0 if proc_img:", "w_img - max_bbox[2] max_d_trans = h_img - max_bbox[3] #隨機擴展框最大範圍 crop_xmin", "sequence not supported.') def letterbox_image(image, size): '''resize image with unchanged", "int(scale*w) nh = int(nw/new_ar) image = image.resize((nw,nh), Image.BICUBIC) # place", "box[:,2]-crop_x_min box[:,3] = box[:,3]-crop_y_min box_data[:len(box)] = box return image_data, box_data", "3]>h] = h box_w = box[:, 2] - box[:, 0]", "+= hue x[..., 0][x[..., 0]>1] -= 1 x[..., 0][x[..., 0]<0]", "np.max(box[:, 2:4], axis=0)], axis=-1)# 取得所有bbox中的最大bbox #包含所有目標框的最大框到各個邊的距離 max_l_trans = max_bbox[0] max_u_trans", "x_max = 0 y_min = h y_max = 0 for", "(dx, dy)) image_data = np.array(new_image)/255. # correct boxes box_data =", "def letterbox_image(image, size): '''resize image with unchanged aspect ratio using", "crop_y_max = min(h, crop_y_max) cropped = image.crop((crop_x_min, crop_y_min, crop_x_max, crop_y_max))", "crop_ymin = max(0, int(max_bbox[1] - random.uniform(0, max_u_trans)*2)) crop_xmax = max(w_img,", "ih = image.size w, h = size scale = min(w/iw,", "f: f(v), funcs, x) if funcs: return reduce(lambda f, g:", "[0, 2]] = box[:, [0, 2]] - crop_xmin box[:, [1,", "= max(0, crop_y_min) crop_x_max = min(w, crop_x_max) crop_y_max = min(h,", "box_data = np.zeros((max_boxes,5)) #box最多有max_boxes個,即shap->(20,5) #將剪裁後位移的框與原始框進行相減,避免變換之後的值過大或過小,並去除異常的box if len(box)>0: np.random.shuffle(box) if len(box)>max_boxes:", "int(nh*new_ar) else: nw = int(scale*w) nh = int(nw/new_ar) image =", "x[x<0] = 0 image_data = hsv_to_rgb(x) # numpy array, 0", "box_h = box[:, 3] - box[:, 1] box = box[np.logical_and(box_w>1,", "h/ih) nw = int(iw*scale) nh = int(ih*scale) dx = (w-nw)//2", "or not flip = rand()<.5 if flip: image = image.transpose(Image.FLIP_LEFT_RIGHT)", "0 box[:, 2][box[:, 2]>w] = w box[:, 3][box[:, 3]>h] =", "(dx, dy)) image = new_image # flip image or not", "sat) if rand()<.5 else 1/rand(1, sat) val = rand(1, val)", "box[:, [0,2]]*scale + dx box[:, [1,3]] = box[:, [1,3]]*scale +", "hue = rand(-hue, hue) sat = rand(1, sat) if rand()<.5", "box[:max_boxes] box[:,0] = box[:,0]-crop_y_min box[:,1] = box[:,1]-crop_y_min box[:,2] = box[:,2]-crop_x_min", "rand()<.5 if flip: image = image.transpose(Image.FLIP_LEFT_RIGHT) # distort image hue", "nw = int(scale*w) nh = int(nw/new_ar) image = image.resize((nw,nh), Image.BICUBIC)", "# 随机扩展这个最小范围 crop_x_min = int(x_min - rand(0, d_to_left)) crop_y_min =", "np.array(new_image)/255. box_data = np.zeros((max_boxes,5)) if len(box)>0: np.random.shuffle(box) if len(box)>max_boxes: box", "new_image = Image.new('RGB', (w,h), (128,128,128)) new_image.paste(image, (dx, dy)) image =", "int(scale*h) nw = int(nh*new_ar) else: nw = int(scale*w) nh =", "crop_x_min = int(x_min - rand(0, d_to_left)) crop_y_min = int(y_min -", "light_blue = (255,200,100) # for boxs in box: # cv2.rectangle(img2,(boxs[0],boxs[1]),(boxs[2],boxs[3]),light_blue,2)", "new_ar < 1: nh = int(scale*h) nw = int(nh*new_ar) else:", "name = bbox[4] # 包含所有目标框的最小框到各个边的距离 d_to_left = x_min d_to_right =", "rand(0, d_to_right)) crop_y_max = int(y_max + rand(0, d_to_bottom)) # 确保不出界", "y_max = max(y_max, bbox[3]) name = bbox[4] # 包含所有目标框的最小框到各个边的距离 d_to_left", "return np.random.rand()*(b-a) + a def get_random_data(annotation_line, input_shape, random=True, max_boxes=20, jitter=.3,", "box[:, [1,3]]*scale + dy box_data[:len(box)] = box return image_data, box_data", "box: x_min = min(x_min, bbox[0]) y_min = min(y_min, bbox[1]) x_max", "to 1 # correct boxes box_data = np.zeros((max_boxes,5)) if len(box)>0:", "= Image.open(line[0]) w, h = image.size #13 14 dx, dy", "0 for bbox in box: x_min = min(x_min, bbox[0]) y_min", "return image_data, box_data # resize image new_ar = w/h *", "+ dx box[:, [1,3]] = box[:, [1,3]]*nh/ih + dy if", "= box[np.logical_and(box_w>1, box_h>1)] # discard invalid box if len(box)>max_boxes: box", "val) x = rgb_to_hsv(np.array(image)/255.) x[..., 0] += hue x[..., 0][x[...,", "input_shape box = np.array([np.array(list(map(int,box.split(',')))) for box in line[1:]]) x_min =", "correct boxes box_data = np.zeros((max_boxes,5)) if len(box)>0: np.random.shuffle(box) if len(box)>max_boxes:", "crop_x_max = int(x_max + rand(0, d_to_right)) crop_y_max = int(y_max +", "image_data, box_data def get_random_data2(annotation_line, input_shape, max_boxes=20, jitter=.3, hue=.1, sat=1.5, val=1.5,", "#將剪裁後位移的框與原始框進行相減,避免變換之後的值過大或過小,並去除異常的box if len(box)>0: np.random.shuffle(box) if len(box)>max_boxes: box = box[:max_boxes] box[:,", "bbox in box: x_min = min(x_min, bbox[0]) y_min = min(y_min,", "= Image.open(line[0]) iw, ih = image.size h, w = input_shape", "hue) sat = rand(1, sat) if rand()<.5 else 1/rand(1, sat)", "annotation_line.split() image = Image.open(line[0]) iw, ih = image.size h, w", "cv2.cvtColor(np.asarray(new_image),cv2.COLOR_RGB2BGR) #再將格式轉回cv2 box_data = np.zeros((max_boxes,5)) #box最多有max_boxes個,即shap->(20,5) #將剪裁後位移的框與原始框進行相減,避免變換之後的值過大或過小,並去除異常的box if len(box)>0: np.random.shuffle(box)", "crop_x_max = min(w, crop_x_max) crop_y_max = min(h, crop_y_max) cropped =", "def get_random_data(annotation_line, input_shape, random=True, max_boxes=20, jitter=.3, hue=.1, sat=1.5, val=1.5, proc_img=True):", "= box[:, [1,3]]*scale + dy box_data[:len(box)] = box return image_data,", "jitter=.3, hue=.1, sat=1.5, val=1.5, proc_img=True): line = annotation_line.split() img =", "image dx = int(rand(0, w-nw)) dy = int(rand(0, h-nh)) new_image", "np.zeros((max_boxes,5)) if len(box)>0: np.random.shuffle(box) if len(box)>max_boxes: box = box[:max_boxes] box[:,0]", "ih = image.size h, w = input_shape box = np.array([np.array(list(map(int,box.split(','))))", "box return image_data, box_data def get_random_data2(annotation_line, input_shape, max_boxes=20, jitter=.3, hue=.1,", "new_image.paste(image, (dx, dy)) image = new_image # flip image or", "int(nw/new_ar) image = image.resize((nw,nh), Image.BICUBIC) # place image dx =", "dy = (h-nh)//2 image_data=0 if proc_img: image = image.resize((nw,nh), Image.BICUBIC)", "len(box)>0: np.random.shuffle(box) if len(box)>max_boxes: box = box[:max_boxes] box[:, [0, 2]]", "random.uniform(0, max_u_trans)*2)) crop_xmax = max(w_img, int(max_bbox[2] + random.uniform(0, max_r_trans)*2)) crop_ymax", "= int(rand(0, w-nw)) dy = int(rand(0, h-nh)) new_image = Image.new('RGB',", "compose(*funcs): \"\"\"Compose arbitrarily many functions, evaluated left to right. Reference:", "https://mathieularose.com/function-composition-in-python/ \"\"\" # return lambda x: reduce(lambda v, f: f(v),", "if len(box)>max_boxes: box = box[:max_boxes] box[:, [0, 2]] = box[:,", "def get_random_data2(annotation_line, input_shape, max_boxes=20, jitter=.3, hue=.1, sat=1.5, val=1.5, proc_img=True): line", "hsv_to_rgb(x) # numpy array, 0 to 1 # correct boxes", "# discard invalid box if len(box)>max_boxes: box = box[:max_boxes] box_data[:len(box)]", "distort image hue = rand(-hue, hue) sat = rand(1, sat)", "= Image.new('RGB', (w,h), (128,128,128)) new_image.paste(cropped, (dx, dy)) image_data = np.array(new_image)/255.", "for boxs in box: # cv2.rectangle(img2,(boxs[0],boxs[1]),(boxs[2],boxs[3]),light_blue,2) # writename=os.path.basename(line[0]) #取檔名 #", "h - y_max # 随机扩展这个最小范围 crop_x_min = int(x_min - rand(0,", "= box #標框線 # light_blue = (255,200,100) # for boxs", "= np.zeros((max_boxes,5)) #box最多有max_boxes個,即shap->(20,5) #將剪裁後位移的框與原始框進行相減,避免變換之後的值過大或過小,並去除異常的box if len(box)>0: np.random.shuffle(box) if len(box)>max_boxes: box", "hsv_to_rgb def compose(*funcs): \"\"\"Compose arbitrarily many functions, evaluated left to", "np.random.shuffle(box) box[:, [0,2]] = box[:, [0,2]]*nw/iw + dx box[:, [1,3]]", "def rand(a=0, b=1): return np.random.rand()*(b-a) + a def get_random_data(annotation_line, input_shape,", "resize image scale = min(w/iw, h/ih) nw = int(iw*scale) nh", "**kw)), funcs) else: raise ValueError('Composition of empty sequence not supported.')", "max_d_trans)*2)) img = img[crop_ymin : crop_ymax, crop_xmin : crop_xmax] #進行裁剪", "d_to_top)) crop_x_max = int(x_max + rand(0, d_to_right)) crop_y_max = int(y_max", "if rand()<.5 else 1/rand(1, val) x = rgb_to_hsv(np.array(image)/255.) x[..., 0]", "in line[1:]]) max_bbox = np.concatenate([np.min(box[:, 0:2], axis=0), np.max(box[:, 2:4], axis=0)],", "0]<0] += 1 x[..., 1] *= sat x[..., 2] *=", "+ rand(0, d_to_bottom)) # 确保不出界 crop_x_min = max(0, crop_x_min) crop_y_min", "max(y_max, bbox[3]) name = bbox[4] # 包含所有目标框的最小框到各个边的距离 d_to_left = x_min", "image_data = hsv_to_rgb(x) # numpy array, 0 to 1 #", "= box[:,3]-crop_y_min box_data[:len(box)] = box return image_data, box_data def get_random_data2(annotation_line,", "3]] = box[:, [1, 3]] - crop_ymin box[:, 2][box[:, 2]>w]", "box = box[np.logical_and(box_w>1, box_h>1)] # discard invalid box if len(box)>max_boxes:", "x[..., 0] += hue x[..., 0][x[..., 0]>1] -= 1 x[...,", "box[np.logical_and(box_w>1, box_h>1)] # discard invalid box if len(box)>max_boxes: box =", "= max(w_img, int(max_bbox[2] + random.uniform(0, max_r_trans)*2)) crop_ymax = max(h_img, int(max_bbox[3]", "#進行裁剪 image = Image.fromarray(cv2.cvtColor(img,cv2.COLOR_BGR2RGB)) #因為目前圖片格式是cv2,因此要轉換為PIL格式做貼上的語法 new_image = Image.new('RGB', (w,h), (128,128,128))", "Image.open(line[0]) iw, ih = image.size h, w = input_shape box", "max_bbox = np.concatenate([np.min(box[:, 0:2], axis=0), np.max(box[:, 2:4], axis=0)], axis=-1)# 取得所有bbox中的最大bbox", "int(rand(0, h-nh)) new_image = Image.new('RGB', (w,h), (128,128,128)) new_image.paste(image, (dx, dy))", "= Image.fromarray(cv2.cvtColor(img,cv2.COLOR_BGR2RGB)) #因為目前圖片格式是cv2,因此要轉換為PIL格式做貼上的語法 new_image = Image.new('RGB', (w,h), (128,128,128)) #產出一個(416,416)的灰色圖片 new_image.paste(image,", "np.concatenate([np.min(box[:, 0:2], axis=0), np.max(box[:, 2:4], axis=0)], axis=-1)# 取得所有bbox中的最大bbox #包含所有目標框的最大框到各個邊的距離 max_l_trans", "int(iw*scale) nh = int(ih*scale) image = image.resize((nw,nh), Image.BICUBIC) new_image =", "+ dx box[:, [1,3]] = box[:, [1,3]]*scale + dy box_data[:len(box)]", "3] - box[:, 1] box = box[np.logical_and(box_w>1, box_h>1)] # discard", "box[:, 3][box[:, 3]>h] = h box_w = box[:, 2] -", "= int(x_max + rand(0, d_to_right)) crop_y_max = int(y_max + rand(0,", "input_shape, random=True, max_boxes=20, jitter=.3, hue=.1, sat=1.5, val=1.5, proc_img=True): '''random preprocessing", "= np.zeros((max_boxes,5)) if len(box)>0: np.random.shuffle(box) if len(box)>max_boxes: box = box[:max_boxes]", "size scale = min(w/iw, h/ih) nw = int(iw*scale) nh =", "= image.resize((nw,nh), Image.BICUBIC) new_image = Image.new('RGB', size, (128,128,128)) new_image.paste(image, ((w-nw)//2,", "box = box[:max_boxes] box[:,0] = box[:,0]-crop_y_min box[:,1] = box[:,1]-crop_y_min box[:,2]", "data augmentation''' line = annotation_line.split() image = Image.open(line[0]) iw, ih", "image.resize((nw,nh), Image.BICUBIC) new_image = Image.new('RGB', (w,h), (128,128,128)) new_image.paste(image, (dx, dy))", "= box[:max_boxes] box[:, [0,2]] = box[:, [0,2]]*scale + dx box[:,", "= box[:,2]-crop_x_min box[:,3] = box[:,3]-crop_y_min box_data[:len(box)] = box return image_data,", "if new_ar < 1: nh = int(scale*h) nw = int(nh*new_ar)", "real-time data augmentation''' line = annotation_line.split() image = Image.open(line[0]) iw," ]
[ "pathlib logging.basicConfig(level=logging.INFO) # Dirs ROOT_DIR = pathlib.Path(__file__).parent.absolute() DUMP_DIR = ROOT_DIR", "logging.basicConfig(level=logging.INFO) # Dirs ROOT_DIR = pathlib.Path(__file__).parent.absolute() DUMP_DIR = ROOT_DIR /", "import pathlib logging.basicConfig(level=logging.INFO) # Dirs ROOT_DIR = pathlib.Path(__file__).parent.absolute() DUMP_DIR =", "<gh_stars>0 import logging import pathlib logging.basicConfig(level=logging.INFO) # Dirs ROOT_DIR =", "# Dirs ROOT_DIR = pathlib.Path(__file__).parent.absolute() DUMP_DIR = ROOT_DIR / 'dumps'", "logging import pathlib logging.basicConfig(level=logging.INFO) # Dirs ROOT_DIR = pathlib.Path(__file__).parent.absolute() DUMP_DIR", "import logging import pathlib logging.basicConfig(level=logging.INFO) # Dirs ROOT_DIR = pathlib.Path(__file__).parent.absolute()" ]
[ "week. The results expose the current and previous rankings as", "abbreviation, 'name': name, 'rank': int(rank), 'week': int(week), 'date': date, 'previous':", "weekly_rankings @property def current_extended(self): \"\"\" Returns a ``list`` of ``dictionaries``", "Each dictionary has the following structure:: { 'abbreviation': Team's abbreviation,", "requested year to pull rankings from. Defaults to the most", "rank_details = { 'abbreviation': abbreviation, 'name': name, 'rank': int(rank), 'week':", "= page('table#ap tbody tr').items() weekly_rankings = [] week = 0", "element. Each dictionary has the following structure:: { 'abbreviation': Team's", "import re from pyquery import PyQuery as pq from ..", "week. Find and retrieve all AP rankings for the requested", "Each week contains information about the name, abbreviation, rank, movement,", "of the abbreviation, require special parsing as it is located", "_find_rankings(self, year): \"\"\" Retrieve the rankings for each week. Find", "= [] week = 0 for team in rankings: if", "rankings were released, such as '2017-12-03'. Can also be 'Final'", "requested year to pull rankings from. Returns ------- PyQuery object", "list is a dictionary of team information such as name,", "team : PyQuery object A PyQuery object representing a single", "%s\" % RANKINGS_URL) raise ValueError(output) rankings = page('table#ap tbody tr').items()", "ladder have a positive number while drops yield a negative", "``int`` and each value is a ``list`` of ``dictionaries`` containing", "PyQuery object A PyQuery object representing a single row in", "page('table#ap tbody tr').items() weekly_rankings = [] week = 0 for", "week. Within each list is a dictionary of team information", "of the rankings published by the Associated Press to easily", "each key is a ``string`` of the team's abbreviation and", "embedded within the 'school_name' tag and, in the case of", "such as 19 (int), 'date': Date the rankings were released,", "rankings on a week-by-week basis. Grab a list of the", "not hit the first if statement in the loop above.", "is located in the middle of a URI. The name", "where the first string is the team's abbreviation, such as", "'Final' for the final rankings or 'Preseason' for preseason rankings", "all AP rankings for the requested year and combine them", "team, 'previous') change = utils._parse_field(RANKINGS_SCHEME, team, 'change') if 'decrease' in", "page for the requested year and create a PyQuery object.", "as an ``int`` and each value is a ``list`` of", "and previous rankings as well as the movement for each", "rankings were released, such as '2017-03-01'. Can also be 'Final'", "the #25 team will be the last element. Each dictionary", "Parameters ---------- year : string (optional) A string of the", "import RANKINGS_SCHEME, RANKINGS_URL from six.moves.urllib.error import HTTPError class Rankings: \"\"\"", "Returns a ``dictionary`` of the most recent rankings from the", "team): \"\"\" Retrieve team's name and abbreviation. The team's name", "\"\"\" def __init__(self, year=None): self._rankings = {} self._find_rankings(year) def _pull_rankings_page(self,", "six.moves.urllib.error import HTTPError class Rankings: \"\"\" Get all Associated Press", "and week number the results were published on. Parameters ----------", "that didn't move have 0 (int) }, ... ], ...", "name and abbreviation are returned for the requested school. Parameters", "first string is the team's abbreviation, such as 'PURDUE' and", "self._rankings = {} self._find_rankings(year) def _pull_rankings_page(self, year): \"\"\" Download the", "the abbreviation, require special parsing as it is located in", "change = utils._parse_field(RANKINGS_SCHEME, team, 'change') if 'decrease' in str(team(RANKINGS_SCHEME['change'])): change", "the rankings published by the Associated Press to easily query", "'week': Week number for the results, such as 19 (int),", "complete(self): \"\"\" Returns a ``dictionary`` where each key is a", "and teams that didn't move have 0 (int) }, ...", "not page: output = (\"Can't pull rankings page. Ensure the", "for the current week (int), 'week': Week number for the", "def _pull_rankings_page(self, year): \"\"\" Download the rankings page. Download the", "abbreviation are returned for the requested school. Parameters ---------- team", "list might not necessarily be in the same order as", "it is located in the middle of a URI. The", "[ { 'abbreviation': Team's abbreviation, such as 'PURDUE' (str), 'name':", "down the rankings. Moves up the ladder have a positive", "rankings from. Returns ------- PyQuery object Returns a PyQuery object", "the rankings page. Returns ------- tuple (string, string) Returns a", "and abbreviation are returned for the requested school. Parameters ----------", "positive number while drops yield a negative number and teams", "\"\"\" Retrieve the rankings for each week. Find and retrieve", "year): \"\"\" Download the rankings page. Download the rankings page", "int(change) * -1 elif 'increase' in str(team(RANKINGS_SCHEME['change'])): try: change =", "most recent AP rankings. The list is ordered in terms", "team('td[data-stat=\"school_name\"] a').text() return abbreviation, name def _find_rankings(self, year): \"\"\" Retrieve", "an ``int`` of the team's rank for the current week.", "(str), 'previous': The team's previous rank, if applicable (str), 'change':", "the final rankings or 'Preseason' for preseason rankings (str), 'previous':", "the most recent rankings from the Associated Press where each", "drops yield a negative number and teams that didn't move", "in the same order as the rankings. The overall dictionary", "'date': Date the rankings were released, such as '2017-03-01'. Can", "containing the AP rankings for each week. Within each list", "\"\"\" if not year: year = utils._find_year_for_season('ncaaf') page = self._pull_rankings_page(year)", "parsing as it is located in the middle of a", "'Purdue'. \"\"\" name_tag = team('td[data-stat=\"school_name\"]') abbreviation = re.sub(r'.*/cfb/schools/', '', str(name_tag('a')))", "rankings_dict = {} for team in self.current_extended: rankings_dict[team['abbreviation']] = team['rank']", "Download the rankings page for the requested year and create", "the Associated Press to easily query the hierarchy of teams", "'date': date, 'previous': previous, 'change': change } weekly_rankings.append(rank_details) # Add", "the team moved up or down the rankings. Moves up", "rankings: if 'class=\"thead\"' in str(team): self._rankings[int(week)] = weekly_rankings weekly_rankings =", "where each key is a ``string`` of the team's abbreviation", "the team's name, such as 'Purdue'. \"\"\" name_tag = team('td[data-stat=\"school_name\"]')", "``dictionary`` of the most recent rankings from the Associated Press", "= sorted(self._rankings[latest_week], key=lambda k: k['rank']) return ordered_dict @property def current(self):", "rankings. The overall dictionary has the following structure:: { week", "a ``list`` of ``dictionaries`` containing the AP rankings for each", "tag and, in the case of the abbreviation, require special", "move have 0 (int) } \"\"\" latest_week = max(self._rankings.keys()) ordered_dict", "a dictionary of team information such as name, abbreviation, rank,", "the following URL \" \"exists: %s\" % RANKINGS_URL) raise ValueError(output)", "from. Returns ------- PyQuery object Returns a PyQuery object of", "while drops yield a negative number and teams that didn't", "Retrieve the rankings for each week. Find and retrieve all", "'change') if 'decrease' in str(team(RANKINGS_SCHEME['change'])): change = int(change) * -1", "and hence will not hit the first if statement in", "each list is a dictionary of team information such as", "page: output = (\"Can't pull rankings page. Ensure the following", "recent AP rankings. The list is ordered in terms of", "information such as name, abbreviation, rank, and more. Note that", "terms of the ranking so the #1 team will be", "str(team(RANKINGS_SCHEME['change'])): change = int(change) * -1 elif 'increase' in str(team(RANKINGS_SCHEME['change'])):", "information about the name, abbreviation, rank, movement, and previous rank", "'increase' in str(team(RANKINGS_SCHEME['change'])): try: change = int(change) except ValueError: change", "has the following structure:: { week number, ie 16 (int):", "(int): [ { 'abbreviation': Team's abbreviation, such as 'PURDUE' (str),", "previous rank, if applicable (str), 'change': The amount the team", "= {} self._find_rankings(year) def _pull_rankings_page(self, year): \"\"\" Download the rankings", "on the rankings page. Returns ------- tuple (string, string) Returns", "return ordered_dict @property def current(self): \"\"\" Returns a ``dictionary`` of", "# row and hence will not hit the first if", "is not terminated with another header # row and hence", "rankings which is not terminated with another header # row", "about the name, abbreviation, rank, movement, and previous rank for", "'rank': int(rank), 'week': int(week), 'date': date, 'previous': previous, 'change': change", "The team's previous rank, if applicable (str), 'change': The amount", "and the second string is the team's name, such as", "per-week basis. Each week contains information about the name, abbreviation,", "results, such as 19 (int), 'date': Date the rankings were", "'PURDUE' and the second string is the team's name, such", "has the following structure:: { 'abbreviation': Team's abbreviation, such as", "latest_week = max(self._rankings.keys()) ordered_dict = sorted(self._rankings[latest_week], key=lambda k: k['rank']) return", "movement, and previous rank for each team as well as", "19 (int), 'date': Date the rankings were released, such as", "tbody tr').items() weekly_rankings = [] week = 0 for team", "team moved up or down the rankings. Moves up the", "rank, and more. Note that the list might not necessarily", "results were published on. Parameters ---------- year : string A", "Week number for the results, such as 19 (int), 'date':", "= team['rank'] return rankings_dict @property def complete(self): \"\"\" Returns a", "be in the same order as the rankings. The overall", "as well as the movement for each team in the", "= self._get_team(team) rank = utils._parse_field(RANKINGS_SCHEME, team, 'rank') week = utils._parse_field(RANKINGS_SCHEME,", "requested year and create a PyQuery object. Parameters ---------- year", "weekly_rankings.append(rank_details) # Add the final rankings which is not terminated", "team, 'rank') week = utils._parse_field(RANKINGS_SCHEME, team, 'week') date = utils._parse_field(RANKINGS_SCHEME,", "will not hit the first if statement in the loop", "as 16 (int), 'date': Date the rankings were released, such", "previous = utils._parse_field(RANKINGS_SCHEME, team, 'previous') change = utils._parse_field(RANKINGS_SCHEME, team, 'change')", "except ValueError: change = 0 else: change = 0 rank_details", "(str), 'name': Team's full name, such as 'Purdue' (str), 'rank':", "which is not terminated with another header # row and", "key is a week number as an ``int`` and each", "16 (int), 'date': Date the rankings were released, such as", "and retrieve all AP rankings for the requested year and", "rank, if applicable (str), 'change': The amount the team moved", "of teams each week. The results expose the current and", "with another header # row and hence will not hit", "= utils._parse_field(RANKINGS_SCHEME, team, 'week') date = utils._parse_field(RANKINGS_SCHEME, team, 'date') previous", "return abbreviation, name def _find_rankings(self, year): \"\"\" Retrieve the rankings", "Associated Press to easily query the hierarchy of teams each", "URI. The name and abbreviation are returned for the requested", "didn't move have 0 (int) }, ... ], ... }", "in the loop above. self._rankings[int(week)] = weekly_rankings @property def current_extended(self):", "object of the rankings HTML page. \"\"\" try: return pq(RANKINGS_URL", "a week number as an ``int`` and each value is", "team in rankings: if 'class=\"thead\"' in str(team): self._rankings[int(week)] = weekly_rankings", "= weekly_rankings @property def current_extended(self): \"\"\" Returns a ``list`` of", "string (optional) A string of the requested year to pull", "a tuple of two strings where the first string is", "pull rankings page. Ensure the following URL \" \"exists: %s\"", "first if statement in the loop above. self._rankings[int(week)] = weekly_rankings", "structure:: { 'abbreviation': Team's abbreviation, such as 'PURDUE' (str), 'name':", "be the last element. Each dictionary has the following structure::", "same order as the rankings. The overall dictionary has the", "'change': The amount the team moved up or down the", "number the results were published on. Parameters ---------- year :", "Find and retrieve all AP rankings for the requested year", "name = team('td[data-stat=\"school_name\"] a').text() return abbreviation, name def _find_rankings(self, year):", "Returns ------- tuple (string, string) Returns a tuple of two", "AP rankings for the requested year and combine them on", "the most recent season. \"\"\" def __init__(self, year=None): self._rankings =", "name def _find_rankings(self, year): \"\"\" Retrieve the rankings for each", "number as an ``int`` and each value is a ``list``", "class Rankings: \"\"\" Get all Associated Press (AP) rankings on", "object Returns a PyQuery object of the rankings HTML page.", "and abbreviation are embedded within the 'school_name' tag and, in", "the 'school_name' tag and, in the case of the abbreviation,", "strings where the first string is the team's abbreviation, such", "'week') date = utils._parse_field(RANKINGS_SCHEME, team, 'date') previous = utils._parse_field(RANKINGS_SCHEME, team,", "is the team's name, such as 'Purdue'. \"\"\" name_tag =", "= 0 else: change = 0 rank_details = { 'abbreviation':", "element and the #25 team will be the last element.", "the current week (int), 'week': Week number for the results,", "for preseason rankings (str), 'previous': The team's previous rank, if", "'date': Date the rankings were released, such as '2017-12-03'. Can", "requested school. Parameters ---------- team : PyQuery object A PyQuery", "PyQuery object Returns a PyQuery object of the rankings HTML", "'name': name, 'rank': int(rank), 'week': int(week), 'date': date, 'previous': previous,", "last element. Each dictionary has the following structure:: { 'abbreviation':", "team will be in the first element and the #25", "team in the list. Parameters ---------- year : string (optional)", "as 'PURDUE' (str), 'name': Team's full name, such as 'Purdue'", "previous rankings as well as the movement for each team", "season. \"\"\" def __init__(self, year=None): self._rankings = {} self._find_rankings(year) def", "the ranking so the #1 team will be in the", "the requested school. Parameters ---------- team : PyQuery object A", "team information such as name, abbreviation, rank, and more. Note", "team as well as the date and week number the", "the final rankings which is not terminated with another header", "{ 'abbreviation': Team's abbreviation, such as 'PURDUE' (str), 'name': Team's", "from .constants import RANKINGS_SCHEME, RANKINGS_URL from six.moves.urllib.error import HTTPError class", "within the 'school_name' tag and, in the case of the", "week = utils._parse_field(RANKINGS_SCHEME, team, 'week') date = utils._parse_field(RANKINGS_SCHEME, team, 'date')", "as the date and week number the results were published", "recent rankings from the Associated Press where each key is", "``list`` of ``dictionaries`` of the most recent AP rankings. The", "is ordered in terms of the ranking so the #1", "the current week. \"\"\" rankings_dict = {} for team in", "@property def complete(self): \"\"\" Returns a ``dictionary`` where each key", "string) Returns a tuple of two strings where the first", "movement for each team in the list. Parameters ---------- year", "date, 'previous': previous, 'change': change } weekly_rankings.append(rank_details) # Add the", "\"\"\" name_tag = team('td[data-stat=\"school_name\"]') abbreviation = re.sub(r'.*/cfb/schools/', '', str(name_tag('a'))) abbreviation", "Team's rank for the current week (int), 'week': Week number", "applicable (str), 'change': The amount the team moved up or", "import utils from .constants import RANKINGS_SCHEME, RANKINGS_URL from six.moves.urllib.error import", "rankings. Moves up the ladder have a positive number while", "on a per-week basis. Each week contains information about the", "weekly_rankings = [] continue abbreviation, name = self._get_team(team) rank =", "utils._parse_field(RANKINGS_SCHEME, team, 'week') date = utils._parse_field(RANKINGS_SCHEME, team, 'date') previous =", "* -1 elif 'increase' in str(team(RANKINGS_SCHEME['change'])): try: change = int(change)", "if not year: year = utils._find_year_for_season('ncaaf') page = self._pull_rankings_page(year) if", "tuple (string, string) Returns a tuple of two strings where", "Associated Press (AP) rankings on a week-by-week basis. Grab a", "{ week number, ie 16 (int): [ { 'abbreviation': Team's", "such as 'PURDUE' (str), 'name': Team's full name, such as", "import PyQuery as pq from .. import utils from .constants", "Moves up the ladder have a positive number while drops", "Press where each key is a ``string`` of the team's", "and combine them on a per-week basis. Each week contains", "pull rankings from. Returns ------- PyQuery object Returns a PyQuery", "the first if statement in the loop above. self._rankings[int(week)] =", "'abbreviation': Team's abbreviation, such as 'PURDUE' (str), 'name': Team's full", "each value is a ``list`` of ``dictionaries`` containing the AP", "year to pull rankings from. Defaults to the most recent", "AP rankings. The list is ordered in terms of the", "return pq(RANKINGS_URL % year) except HTTPError: return None def _get_team(self,", "the movement for each team in the list. Parameters ----------", "of ``dictionaries`` containing the AP rankings for each week. Within", "def current_extended(self): \"\"\" Returns a ``list`` of ``dictionaries`` of the", "{} for team in self.current_extended: rankings_dict[team['abbreviation']] = team['rank'] return rankings_dict", "0 rank_details = { 'abbreviation': abbreviation, 'name': name, 'rank': int(rank),", "retrieve all AP rankings for the requested year and combine", "abbreviation are embedded within the 'school_name' tag and, in the", "The name and abbreviation are returned for the requested school.", "ValueError(output) rankings = page('table#ap tbody tr').items() weekly_rankings = [] week", "of the most recent rankings from the Associated Press where", "a ``string`` of the team's abbreviation and each value is", "page. Ensure the following URL \" \"exists: %s\" % RANKINGS_URL)", "year = utils._find_year_for_season('ncaaf') page = self._pull_rankings_page(year) if not page: output", "rankings or 'Preseason' for preseason rankings (str), 'previous': The team's", "Parameters ---------- year : string A string of the requested", "a PyQuery object. Parameters ---------- year : string A string", "are embedded within the 'school_name' tag and, in the case", "\"\"\" latest_week = max(self._rankings.keys()) ordered_dict = sorted(self._rankings[latest_week], key=lambda k: k['rank'])", "if statement in the loop above. self._rankings[int(week)] = weekly_rankings @property", "special parsing as it is located in the middle of", "'', abbreviation) name = team('td[data-stat=\"school_name\"] a').text() return abbreviation, name def", "object representing a single row in a table on the", "a negative number and teams that didn't move have 0", "The team's name and abbreviation are embedded within the 'school_name'", "pq(RANKINGS_URL % year) except HTTPError: return None def _get_team(self, team):", "PyQuery object of the rankings HTML page. \"\"\" try: return", "= team('td[data-stat=\"school_name\"] a').text() return abbreviation, name def _find_rankings(self, year): \"\"\"", "first element and the #25 team will be the last", "= { 'abbreviation': abbreviation, 'name': name, 'rank': int(rank), 'week': int(week),", "second string is the team's name, such as 'Purdue'. \"\"\"", "re from pyquery import PyQuery as pq from .. import", "output = (\"Can't pull rankings page. Ensure the following URL", "value is an ``int`` of the team's rank for the", "in self.current_extended: rankings_dict[team['abbreviation']] = team['rank'] return rankings_dict @property def complete(self):", "a PyQuery object of the rankings HTML page. \"\"\" try:", "= utils._parse_field(RANKINGS_SCHEME, team, 'rank') week = utils._parse_field(RANKINGS_SCHEME, team, 'week') date", "ValueError: change = 0 else: change = 0 rank_details =", "up or down the rankings. Moves up the ladder have", "rankings page. Returns ------- tuple (string, string) Returns a tuple", "(AP) rankings on a week-by-week basis. Grab a list of", "= (\"Can't pull rankings page. Ensure the following URL \"", "0 for team in rankings: if 'class=\"thead\"' in str(team): self._rankings[int(week)]", "located in the middle of a URI. The name and", "for each week. Within each list is a dictionary of", "also be 'Final' for the final rankings or 'Preseason' for", "return rankings_dict @property def complete(self): \"\"\" Returns a ``dictionary`` where", "(optional) A string of the requested year to pull rankings", "str(team): self._rankings[int(week)] = weekly_rankings weekly_rankings = [] continue abbreviation, name", "the case of the abbreviation, require special parsing as it", "dictionary has the following structure:: { 'abbreviation': Team's abbreviation, such", "from six.moves.urllib.error import HTTPError class Rankings: \"\"\" Get all Associated", "(int), 'date': Date the rankings were released, such as '2017-03-01'.", "teams that didn't move have 0 (int) }, ... ],", "---------- team : PyQuery object A PyQuery object representing a", "try: change = int(change) except ValueError: change = 0 else:", "such as name, abbreviation, rank, and more. Note that the", "(str), 'change': The amount the team moved up or down", "easily query the hierarchy of teams each week. The results", "a ``dictionary`` where each key is a week number as", "returned for the requested school. Parameters ---------- team : PyQuery", "string is the team's name, such as 'Purdue'. \"\"\" name_tag", "name, abbreviation, rank, movement, and previous rank for each team", "following URL \" \"exists: %s\" % RANKINGS_URL) raise ValueError(output) rankings", "name, such as 'Purdue' (str), 'rank': Team's rank for the", "page. Returns ------- tuple (string, string) Returns a tuple of", "well as the movement for each team in the list.", "to pull rankings from. \"\"\" if not year: year =", "statement in the loop above. self._rankings[int(week)] = weekly_rankings @property def", "rankings from the Associated Press where each key is a", "current week. \"\"\" rankings_dict = {} for team in self.current_extended:", "0 (int) } \"\"\" latest_week = max(self._rankings.keys()) ordered_dict = sorted(self._rankings[latest_week],", "number for the results, such as 19 (int), 'date': Date", "def current(self): \"\"\" Returns a ``dictionary`` of the most recent", "self._get_team(team) rank = utils._parse_field(RANKINGS_SCHEME, team, 'rank') week = utils._parse_field(RANKINGS_SCHEME, team,", "'school_name' tag and, in the case of the abbreviation, require", "'2017-03-01'. Can also be 'Final' for the final rankings or", "@property def current_extended(self): \"\"\" Returns a ``list`` of ``dictionaries`` of", ": string A string of the requested year to pull", "the results were published on. Parameters ---------- year : string", "of the requested year to pull rankings from. \"\"\" if", "row and hence will not hit the first if statement", "a ``list`` of ``dictionaries`` of the most recent AP rankings.", "basis. Grab a list of the rankings published by the", "from. \"\"\" if not year: year = utils._find_year_for_season('ncaaf') page =", "team's abbreviation, such as 'PURDUE' and the second string is", "expose the current and previous rankings as well as the", "or down the rankings. Moves up the ladder have a", "on a week-by-week basis. Grab a list of the rankings", "two strings where the first string is the team's abbreviation,", "in a table on the rankings page. Returns ------- tuple", "is the team's abbreviation, such as 'PURDUE' and the second", "Returns a ``list`` of ``dictionaries`` of the most recent AP", "'week': Week number for the results, such as 16 (int),", "abbreviation, such as 'PURDUE' and the second string is the", "self.current_extended: rankings_dict[team['abbreviation']] = team['rank'] return rankings_dict @property def complete(self): \"\"\"", "0 else: change = 0 rank_details = { 'abbreviation': abbreviation,", "year and combine them on a per-week basis. Each week", "the rankings page. Download the rankings page for the requested", "= weekly_rankings weekly_rankings = [] continue abbreviation, name = self._get_team(team)", "from pyquery import PyQuery as pq from .. import utils", "ranking so the #1 team will be in the first", "in str(team): self._rankings[int(week)] = weekly_rankings weekly_rankings = [] continue abbreviation,", "number for the results, such as 16 (int), 'date': Date", "------- tuple (string, string) Returns a tuple of two strings", "re.sub(r'/.*', '', abbreviation) name = team('td[data-stat=\"school_name\"] a').text() return abbreviation, name", "have 0 (int) }, ... ], ... } \"\"\" return", "abbreviation = re.sub(r'/.*', '', abbreviation) name = team('td[data-stat=\"school_name\"] a').text() return", "the date and week number the results were published on.", "abbreviation) name = team('td[data-stat=\"school_name\"] a').text() return abbreviation, name def _find_rankings(self,", "them on a per-week basis. Each week contains information about", "rankings for the requested year and combine them on a", "sorted(self._rankings[latest_week], key=lambda k: k['rank']) return ordered_dict @property def current(self): \"\"\"", "def complete(self): \"\"\" Returns a ``dictionary`` where each key is", "import HTTPError class Rankings: \"\"\" Get all Associated Press (AP)", "rank for the current week. \"\"\" rankings_dict = {} for", "each week. Within each list is a dictionary of team", "= re.sub(r'.*/cfb/schools/', '', str(name_tag('a'))) abbreviation = re.sub(r'/.*', '', abbreviation) name", "_get_team(self, team): \"\"\" Retrieve team's name and abbreviation. The team's", "of the requested year to pull rankings from. Defaults to", "{ 'abbreviation': abbreviation, 'name': name, 'rank': int(rank), 'week': int(week), 'date':", "abbreviation, such as 'PURDUE' (str), 'name': Team's full name, such", "as pq from .. import utils from .constants import RANKINGS_SCHEME,", "for team in rankings: if 'class=\"thead\"' in str(team): self._rankings[int(week)] =", "rankings. The list is ordered in terms of the ranking", "continue abbreviation, name = self._get_team(team) rank = utils._parse_field(RANKINGS_SCHEME, team, 'rank')", "``int`` of the team's rank for the current week. \"\"\"", "Can also be 'Final' for the final rankings or 'Preseason'", "team's previous rank, if applicable (str), 'change': The amount the", "abbreviation, name = self._get_team(team) rank = utils._parse_field(RANKINGS_SCHEME, team, 'rank') week", "by the Associated Press to easily query the hierarchy of", "team's abbreviation and each value is an ``int`` of the", "year : string A string of the requested year to", "in str(team(RANKINGS_SCHEME['change'])): try: change = int(change) except ValueError: change =", "as the movement for each team in the list. Parameters", "utils._parse_field(RANKINGS_SCHEME, team, 'change') if 'decrease' in str(team(RANKINGS_SCHEME['change'])): change = int(change)", "% RANKINGS_URL) raise ValueError(output) rankings = page('table#ap tbody tr').items() weekly_rankings", "hence will not hit the first if statement in the", "PyQuery as pq from .. import utils from .constants import", "year to pull rankings from. Returns ------- PyQuery object Returns", "to pull rankings from. Defaults to the most recent season.", "a ``dictionary`` of the most recent rankings from the Associated", "each key is a week number as an ``int`` and", "\"\"\" rankings_dict = {} for team in self.current_extended: rankings_dict[team['abbreviation']] =", "utils from .constants import RANKINGS_SCHEME, RANKINGS_URL from six.moves.urllib.error import HTTPError", "number while drops yield a negative number and teams that", "not necessarily be in the same order as the rankings.", "the team's rank for the current week. \"\"\" rankings_dict =", "'week': int(week), 'date': date, 'previous': previous, 'change': change } weekly_rankings.append(rank_details)", "of two strings where the first string is the team's", "self._pull_rankings_page(year) if not page: output = (\"Can't pull rankings page.", "or 'Preseason' for preseason rankings (str), 'previous': The team's previous", "preseason rankings (str), 'previous': The team's previous rank, if applicable", "query the hierarchy of teams each week. The results expose", "except HTTPError: return None def _get_team(self, team): \"\"\" Retrieve team's", "= team('td[data-stat=\"school_name\"]') abbreviation = re.sub(r'.*/cfb/schools/', '', str(name_tag('a'))) abbreviation = re.sub(r'/.*',", "of the most recent AP rankings. The list is ordered", "= utils._parse_field(RANKINGS_SCHEME, team, 'date') previous = utils._parse_field(RANKINGS_SCHEME, team, 'previous') change", "change = int(change) * -1 elif 'increase' in str(team(RANKINGS_SCHEME['change'])): try:", "of the rankings HTML page. \"\"\" try: return pq(RANKINGS_URL %", "Retrieve team's name and abbreviation. The team's name and abbreviation", "self._rankings[int(week)] = weekly_rankings weekly_rankings = [] continue abbreviation, name =", "if not page: output = (\"Can't pull rankings page. Ensure", "create a PyQuery object. Parameters ---------- year : string A", "change = 0 else: change = 0 rank_details = {", "pull rankings from. Defaults to the most recent season. \"\"\"", "each value is an ``int`` of the team's rank for", "Associated Press where each key is a ``string`` of the", "(int), 'week': Week number for the results, such as 16", "rankings for each week. Within each list is a dictionary", "utils._parse_field(RANKINGS_SCHEME, team, 'previous') change = utils._parse_field(RANKINGS_SCHEME, team, 'change') if 'decrease'", "Get all Associated Press (AP) rankings on a week-by-week basis.", "[] continue abbreviation, name = self._get_team(team) rank = utils._parse_field(RANKINGS_SCHEME, team,", "= [] continue abbreviation, name = self._get_team(team) rank = utils._parse_field(RANKINGS_SCHEME,", ".constants import RANKINGS_SCHEME, RANKINGS_URL from six.moves.urllib.error import HTTPError class Rankings:", "week = 0 for team in rankings: if 'class=\"thead\"' in", "'previous') change = utils._parse_field(RANKINGS_SCHEME, team, 'change') if 'decrease' in str(team(RANKINGS_SCHEME['change'])):", "week. \"\"\" rankings_dict = {} for team in self.current_extended: rankings_dict[team['abbreviation']]", "ie 16 (int): [ { 'abbreviation': Team's abbreviation, such as", "year=None): self._rankings = {} self._find_rankings(year) def _pull_rankings_page(self, year): \"\"\" Download", "URL \" \"exists: %s\" % RANKINGS_URL) raise ValueError(output) rankings =", "table on the rankings page. Returns ------- tuple (string, string)", "previous, 'change': change } weekly_rankings.append(rank_details) # Add the final rankings", "the #1 team will be in the first element and", "current week (int), 'week': Week number for the results, such", "for team in self.current_extended: rankings_dict[team['abbreviation']] = team['rank'] return rankings_dict @property", "for each week. Find and retrieve all AP rankings for", "were released, such as '2017-03-01'. Can also be 'Final' for", "{} self._find_rankings(year) def _pull_rankings_page(self, year): \"\"\" Download the rankings page.", ".. import utils from .constants import RANKINGS_SCHEME, RANKINGS_URL from six.moves.urllib.error", "team's name, such as 'Purdue'. \"\"\" name_tag = team('td[data-stat=\"school_name\"]') abbreviation", "rankings = page('table#ap tbody tr').items() weekly_rankings = [] week =", "be in the first element and the #25 team will", "following structure:: { 'abbreviation': Team's abbreviation, such as 'PURDUE' (str),", "name, abbreviation, rank, and more. Note that the list might", "the AP rankings for each week. Within each list is", "def _get_team(self, team): \"\"\" Retrieve team's name and abbreviation. The", "Returns a tuple of two strings where the first string", "is a week number as an ``int`` and each value", "the ladder have a positive number while drops yield a", "year): \"\"\" Retrieve the rankings for each week. Find and", "the first element and the #25 team will be the", "current(self): \"\"\" Returns a ``dictionary`` of the most recent rankings", "previous rank for each team as well as the date", "list is ordered in terms of the ranking so the", "in the list. Parameters ---------- year : string (optional) A", "Note that the list might not necessarily be in the", "else: change = 0 rank_details = { 'abbreviation': abbreviation, 'name':", "rankings for each week. Find and retrieve all AP rankings", "16 (int): [ { 'abbreviation': Team's abbreviation, such as 'PURDUE'", "team's name and abbreviation. The team's name and abbreviation are", "each week. Find and retrieve all AP rankings for the", "string A string of the requested year to pull rankings", "'name': Team's full name, such as 'Purdue' (str), 'rank': Team's", "a positive number while drops yield a negative number and", "weekly_rankings weekly_rankings = [] continue abbreviation, name = self._get_team(team) rank", "such as 'Purdue' (str), 'rank': Team's rank for the current", "'Purdue' (str), 'rank': Team's rank for the current week (int),", "the results, such as 19 (int), 'date': Date the rankings", "page. Download the rankings page for the requested year and", "another header # row and hence will not hit the", "The amount the team moved up or down the rankings.", "if 'decrease' in str(team(RANKINGS_SCHEME['change'])): change = int(change) * -1 elif", "int(rank), 'week': int(week), 'date': date, 'previous': previous, 'change': change }", "AP rankings for each week. Within each list is a", "above. self._rankings[int(week)] = weekly_rankings @property def current_extended(self): \"\"\" Returns a", "change } weekly_rankings.append(rank_details) # Add the final rankings which is", "'abbreviation': abbreviation, 'name': name, 'rank': int(rank), 'week': int(week), 'date': date,", "abbreviation, require special parsing as it is located in the", "name_tag = team('td[data-stat=\"school_name\"]') abbreviation = re.sub(r'.*/cfb/schools/', '', str(name_tag('a'))) abbreviation =", "all Associated Press (AP) rankings on a week-by-week basis. Grab", "have 0 (int) } \"\"\" latest_week = max(self._rankings.keys()) ordered_dict =", "requested year and combine them on a per-week basis. Each", "team will be the last element. Each dictionary has the", "as well as the date and week number the results", "for each team in the list. Parameters ---------- year :", "results expose the current and previous rankings as well as", "rankings from. Defaults to the most recent season. \"\"\" def", "string is the team's abbreviation, such as 'PURDUE' and the", "current_extended(self): \"\"\" Returns a ``list`` of ``dictionaries`` of the most", "as 'Purdue' (str), 'rank': Team's rank for the current week", "in the case of the abbreviation, require special parsing as", "middle of a URI. The name and abbreviation are returned", "---------- year : string (optional) A string of the requested", "\"\"\" Retrieve team's name and abbreviation. The team's name and", "as 'Purdue'. \"\"\" name_tag = team('td[data-stat=\"school_name\"]') abbreviation = re.sub(r'.*/cfb/schools/', '',", "the same order as the rankings. The overall dictionary has", "Within each list is a dictionary of team information such", "will be in the first element and the #25 team", "the rankings for each week. Find and retrieve all AP", "released, such as '2017-12-03'. Can also be 'Final' for the", "the first string is the team's abbreviation, such as 'PURDUE'", "contains information about the name, abbreviation, rank, movement, and previous", "so the #1 team will be in the first element", "Press to easily query the hierarchy of teams each week.", "\"\"\" Download the rankings page. Download the rankings page for", "single row in a table on the rankings page. Returns", "week number, ie 16 (int): [ { 'abbreviation': Team's abbreviation,", "---------- year : string A string of the requested year", "if applicable (str), 'change': The amount the team moved up", "'change': change } weekly_rankings.append(rank_details) # Add the final rankings which", "raise ValueError(output) rankings = page('table#ap tbody tr').items() weekly_rankings = []", "'decrease' in str(team(RANKINGS_SCHEME['change'])): change = int(change) * -1 elif 'increase'", "are returned for the requested school. Parameters ---------- team :", "the loop above. self._rankings[int(week)] = weekly_rankings @property def current_extended(self): \"\"\"", "the team's abbreviation and each value is an ``int`` of", "and each value is a ``list`` of ``dictionaries`` containing the", "rankings_dict @property def complete(self): \"\"\" Returns a ``dictionary`` where each", "key=lambda k: k['rank']) return ordered_dict @property def current(self): \"\"\" Returns", "might not necessarily be in the same order as the", "the list. Parameters ---------- year : string (optional) A string", "dictionary of team information such as name, abbreviation, rank, and", "= int(change) * -1 elif 'increase' in str(team(RANKINGS_SCHEME['change'])): try: change", "Press (AP) rankings on a week-by-week basis. Grab a list", "HTTPError class Rankings: \"\"\" Get all Associated Press (AP) rankings", "name, such as 'Purdue'. \"\"\" name_tag = team('td[data-stat=\"school_name\"]') abbreviation =", ": PyQuery object A PyQuery object representing a single row", "case of the abbreviation, require special parsing as it is", "most recent season. \"\"\" def __init__(self, year=None): self._rankings = {}", "structure:: { week number, ie 16 (int): [ { 'abbreviation':", "abbreviation. The team's name and abbreviation are embedded within the", "more. Note that the list might not necessarily be in", "teams that didn't move have 0 (int) } \"\"\" latest_week", "the last element. Each dictionary has the following structure:: {", "\"\"\" Returns a ``list`` of ``dictionaries`` of the most recent", "such as '2017-03-01'. Can also be 'Final' for the final", "as 19 (int), 'date': Date the rankings were released, such", "and, in the case of the abbreviation, require special parsing", "(str), 'rank': Team's rank for the current week (int), 'week':", "pq from .. import utils from .constants import RANKINGS_SCHEME, RANKINGS_URL", "HTML page. \"\"\" try: return pq(RANKINGS_URL % year) except HTTPError:", "to easily query the hierarchy of teams each week. The", "str(name_tag('a'))) abbreviation = re.sub(r'/.*', '', abbreviation) name = team('td[data-stat=\"school_name\"] a').text()", "-1 elif 'increase' in str(team(RANKINGS_SCHEME['change'])): try: change = int(change) except", "year and create a PyQuery object. Parameters ---------- year :", "from. Defaults to the most recent season. \"\"\" def __init__(self,", "school. Parameters ---------- team : PyQuery object A PyQuery object", "necessarily be in the same order as the rankings. The", "Returns a PyQuery object of the rankings HTML page. \"\"\"", "the requested year to pull rankings from. Defaults to the", "for the current week. \"\"\" rankings_dict = {} for team", "(int), 'week': Week number for the results, such as 19", "team, 'date') previous = utils._parse_field(RANKINGS_SCHEME, team, 'previous') change = utils._parse_field(RANKINGS_SCHEME,", "rank for each team as well as the date and", "the hierarchy of teams each week. The results expose the", ": string (optional) A string of the requested year to", "week-by-week basis. Grab a list of the rankings published by", "a list of the rankings published by the Associated Press", "rank, movement, and previous rank for each team as well", "terminated with another header # row and hence will not", "for the results, such as 19 (int), 'date': Date the", "recent season. \"\"\" def __init__(self, year=None): self._rankings = {} self._find_rankings(year)", "representing a single row in a table on the rankings", "#1 team will be in the first element and the", "team, 'week') date = utils._parse_field(RANKINGS_SCHEME, team, 'date') previous = utils._parse_field(RANKINGS_SCHEME,", "row in a table on the rankings page. Returns -------", "that didn't move have 0 (int) } \"\"\" latest_week =", "such as 'PURDUE' and the second string is the team's", "'', str(name_tag('a'))) abbreviation = re.sub(r'/.*', '', abbreviation) name = team('td[data-stat=\"school_name\"]", "list of the rankings published by the Associated Press to", "abbreviation, rank, movement, and previous rank for each team as", "page = self._pull_rankings_page(year) if not page: output = (\"Can't pull", "week number the results were published on. Parameters ---------- year", "name = self._get_team(team) rank = utils._parse_field(RANKINGS_SCHEME, team, 'rank') week =", "week contains information about the name, abbreviation, rank, movement, and", "moved up or down the rankings. Moves up the ladder", "A string of the requested year to pull rankings from.", "\"\"\" try: return pq(RANKINGS_URL % year) except HTTPError: return None", "= utils._find_year_for_season('ncaaf') page = self._pull_rankings_page(year) if not page: output =", "team['rank'] return rankings_dict @property def complete(self): \"\"\" Returns a ``dictionary``", "and the #25 team will be the last element. Each", "@property def current(self): \"\"\" Returns a ``dictionary`` of the most", "the requested year to pull rankings from. \"\"\" if not", "of team information such as name, abbreviation, rank, and more.", "where each key is a week number as an ``int``", "for each team as well as the date and week", "'rank') week = utils._parse_field(RANKINGS_SCHEME, team, 'week') date = utils._parse_field(RANKINGS_SCHEME, team,", "\"\"\" Returns a ``dictionary`` where each key is a week", "the rankings HTML page. \"\"\" try: return pq(RANKINGS_URL % year)", "team, 'change') if 'decrease' in str(team(RANKINGS_SCHEME['change'])): change = int(change) *", "is an ``int`` of the team's rank for the current", "is a dictionary of team information such as name, abbreviation,", "rankings_dict[team['abbreviation']] = team['rank'] return rankings_dict @property def complete(self): \"\"\" Returns", "list. Parameters ---------- year : string (optional) A string of", "from .. import utils from .constants import RANKINGS_SCHEME, RANKINGS_URL from", "in the first element and the #25 team will be", "on. Parameters ---------- year : string A string of the", "ordered_dict @property def current(self): \"\"\" Returns a ``dictionary`` of the", "most recent rankings from the Associated Press where each key", "well as the date and week number the results were", "Week number for the results, such as 16 (int), 'date':", "such as '2017-12-03'. Can also be 'Final' for the final", "year: year = utils._find_year_for_season('ncaaf') page = self._pull_rankings_page(year) if not page:", "amount the team moved up or down the rankings. Moves", "'class=\"thead\"' in str(team): self._rankings[int(week)] = weekly_rankings weekly_rankings = [] continue", "utils._parse_field(RANKINGS_SCHEME, team, 'date') previous = utils._parse_field(RANKINGS_SCHEME, team, 'previous') change =", "a single row in a table on the rankings page.", "from the Associated Press where each key is a ``string``", "k: k['rank']) return ordered_dict @property def current(self): \"\"\" Returns a", "results, such as 16 (int), 'date': Date the rankings were", "each team as well as the date and week number", "as '2017-12-03'. Can also be 'Final' for the final rankings", "'previous': previous, 'change': change } weekly_rankings.append(rank_details) # Add the final", "= 0 for team in rankings: if 'class=\"thead\"' in str(team):", "try: return pq(RANKINGS_URL % year) except HTTPError: return None def", "__init__(self, year=None): self._rankings = {} self._find_rankings(year) def _pull_rankings_page(self, year): \"\"\"", "def __init__(self, year=None): self._rankings = {} self._find_rankings(year) def _pull_rankings_page(self, year):", "(int), 'date': Date the rankings were released, such as '2017-12-03'.", "ordered in terms of the ranking so the #1 team", "be 'Final' for the final rankings or 'Preseason' for preseason", "number and teams that didn't move have 0 (int) }", "the requested year to pull rankings from. Returns ------- PyQuery", "Parameters ---------- team : PyQuery object A PyQuery object representing", "number and teams that didn't move have 0 (int) },", "abbreviation = re.sub(r'.*/cfb/schools/', '', str(name_tag('a'))) abbreviation = re.sub(r'/.*', '', abbreviation)", "self._find_rankings(year) def _pull_rankings_page(self, year): \"\"\" Download the rankings page. Download", "will be the last element. Each dictionary has the following", "each team in the list. Parameters ---------- year : string", "string of the requested year to pull rankings from. \"\"\"", "rankings published by the Associated Press to easily query the", "str(team(RANKINGS_SCHEME['change'])): try: change = int(change) except ValueError: change = 0", "'PURDUE' (str), 'name': Team's full name, such as 'Purdue' (str),", "'previous': The team's previous rank, if applicable (str), 'change': The", "object. Parameters ---------- year : string A string of the", "order as the rankings. The overall dictionary has the following", "The overall dictionary has the following structure:: { week number,", "change = 0 rank_details = { 'abbreviation': abbreviation, 'name': name,", "the middle of a URI. The name and abbreviation are", "utils._parse_field(RANKINGS_SCHEME, team, 'rank') week = utils._parse_field(RANKINGS_SCHEME, team, 'week') date =", "for the requested year and create a PyQuery object. Parameters", "that the list might not necessarily be in the same", "team's rank for the current week. \"\"\" rankings_dict = {}", "the list might not necessarily be in the same order", "basis. Each week contains information about the name, abbreviation, rank,", "as 'PURDUE' and the second string is the team's name,", "the rankings. The overall dictionary has the following structure:: {", "abbreviation and each value is an ``int`` of the team's", "#25 team will be the last element. Each dictionary has", "(\"Can't pull rankings page. Ensure the following URL \" \"exists:", "yield a negative number and teams that didn't move have", "each week. The results expose the current and previous rankings", "team in self.current_extended: rankings_dict[team['abbreviation']] = team['rank'] return rankings_dict @property def", "elif 'increase' in str(team(RANKINGS_SCHEME['change'])): try: change = int(change) except ValueError:", "'Preseason' for preseason rankings (str), 'previous': The team's previous rank,", "as the rankings. The overall dictionary has the following structure::", "the Associated Press where each key is a ``string`` of", "The results expose the current and previous rankings as well", "week number as an ``int`` and each value is a", "requested year to pull rankings from. \"\"\" if not year:", "the requested year and create a PyQuery object. Parameters ----------", "Team's abbreviation, such as 'PURDUE' (str), 'name': Team's full name,", "in rankings: if 'class=\"thead\"' in str(team): self._rankings[int(week)] = weekly_rankings weekly_rankings", "and create a PyQuery object. Parameters ---------- year : string", "string of the requested year to pull rankings from. Defaults", "= 0 rank_details = { 'abbreviation': abbreviation, 'name': name, 'rank':", "a table on the rankings page. Returns ------- tuple (string,", "Defaults to the most recent season. \"\"\" def __init__(self, year=None):", "abbreviation, rank, and more. Note that the list might not", "object A PyQuery object representing a single row in a", "in terms of the ranking so the #1 team will", "published by the Associated Press to easily query the hierarchy", "``list`` of ``dictionaries`` containing the AP rankings for each week.", "teams each week. The results expose the current and previous", "and teams that didn't move have 0 (int) } \"\"\"", "\"\"\" Get all Associated Press (AP) rankings on a week-by-week", "(string, string) Returns a tuple of two strings where the", "abbreviation, name def _find_rankings(self, year): \"\"\" Retrieve the rankings for", "the rankings were released, such as '2017-03-01'. Can also be", "number, ie 16 (int): [ { 'abbreviation': Team's abbreviation, such", "utils._find_year_for_season('ncaaf') page = self._pull_rankings_page(year) if not page: output = (\"Can't", "the most recent AP rankings. The list is ordered in", "header # row and hence will not hit the first", "year : string (optional) A string of the requested year", "rankings from. \"\"\" if not year: year = utils._find_year_for_season('ncaaf') page", "= int(change) except ValueError: change = 0 else: change =", "value is a ``list`` of ``dictionaries`` containing the AP rankings", "A PyQuery object representing a single row in a table", "the following structure:: { week number, ie 16 (int): [", "= max(self._rankings.keys()) ordered_dict = sorted(self._rankings[latest_week], key=lambda k: k['rank']) return ordered_dict", "of the team's abbreviation and each value is an ``int``", "PyQuery object representing a single row in a table on", "the following structure:: { 'abbreviation': Team's abbreviation, such as 'PURDUE'", "a').text() return abbreviation, name def _find_rankings(self, year): \"\"\" Retrieve the", "the results, such as 16 (int), 'date': Date the rankings", "page. \"\"\" try: return pq(RANKINGS_URL % year) except HTTPError: return", "for the results, such as 16 (int), 'date': Date the", "team('td[data-stat=\"school_name\"]') abbreviation = re.sub(r'.*/cfb/schools/', '', str(name_tag('a'))) abbreviation = re.sub(r'/.*', '',", "move have 0 (int) }, ... ], ... } \"\"\"", "in str(team(RANKINGS_SCHEME['change'])): change = int(change) * -1 elif 'increase' in", "the rankings were released, such as '2017-12-03'. Can also be", "PyQuery object. Parameters ---------- year : string A string of", "final rankings which is not terminated with another header #", "``dictionaries`` of the most recent AP rankings. The list is", "rankings (str), 'previous': The team's previous rank, if applicable (str),", "in the middle of a URI. The name and abbreviation", "team's name and abbreviation are embedded within the 'school_name' tag", "loop above. self._rankings[int(week)] = weekly_rankings @property def current_extended(self): \"\"\" Returns", "an ``int`` and each value is a ``list`` of ``dictionaries``", "ordered_dict = sorted(self._rankings[latest_week], key=lambda k: k['rank']) return ordered_dict @property def", "the rankings. Moves up the ladder have a positive number", "combine them on a per-week basis. Each week contains information", "RANKINGS_URL) raise ValueError(output) rankings = page('table#ap tbody tr').items() weekly_rankings =", "and abbreviation. The team's name and abbreviation are embedded within", "the rankings page for the requested year and create a", "not terminated with another header # row and hence will", "Returns a ``dictionary`` where each key is a week number", "as it is located in the middle of a URI.", "to pull rankings from. Returns ------- PyQuery object Returns a", "current and previous rankings as well as the movement for", "Team's full name, such as 'Purdue' (str), 'rank': Team's rank", "0 (int) }, ... ], ... } \"\"\" return self._rankings", "name and abbreviation are embedded within the 'school_name' tag and,", "re.sub(r'.*/cfb/schools/', '', str(name_tag('a'))) abbreviation = re.sub(r'/.*', '', abbreviation) name =", "'2017-12-03'. Can also be 'Final' for the final rankings or", "a per-week basis. Each week contains information about the name,", "of a URI. The name and abbreviation are returned for", "max(self._rankings.keys()) ordered_dict = sorted(self._rankings[latest_week], key=lambda k: k['rank']) return ordered_dict @property", "negative number and teams that didn't move have 0 (int)", "} weekly_rankings.append(rank_details) # Add the final rankings which is not", "Rankings: \"\"\" Get all Associated Press (AP) rankings on a", "Date the rankings were released, such as '2017-12-03'. Can also", "rankings page. Download the rankings page for the requested year", "the team's abbreviation, such as 'PURDUE' and the second string", "have a positive number while drops yield a negative number", "= utils._parse_field(RANKINGS_SCHEME, team, 'previous') change = utils._parse_field(RANKINGS_SCHEME, team, 'change') if", "and more. Note that the list might not necessarily be", "% year) except HTTPError: return None def _get_team(self, team): \"\"\"", "change = int(change) except ValueError: change = 0 else: change", "RANKINGS_SCHEME, RANKINGS_URL from six.moves.urllib.error import HTTPError class Rankings: \"\"\" Get", "a week-by-week basis. Grab a list of the rankings published", "of the requested year to pull rankings from. Returns -------", "date and week number the results were published on. Parameters", "tr').items() weekly_rankings = [] week = 0 for team in", "require special parsing as it is located in the middle", "as '2017-03-01'. Can also be 'Final' for the final rankings", "such as 'Purdue'. \"\"\" name_tag = team('td[data-stat=\"school_name\"]') abbreviation = re.sub(r'.*/cfb/schools/',", "= {} for team in self.current_extended: rankings_dict[team['abbreviation']] = team['rank'] return", "\" \"exists: %s\" % RANKINGS_URL) raise ValueError(output) rankings = page('table#ap", "------- PyQuery object Returns a PyQuery object of the rankings", "tuple of two strings where the first string is the", "rankings as well as the movement for each team in", "int(change) except ValueError: change = 0 else: change = 0", "is a ``list`` of ``dictionaries`` containing the AP rankings for", "name, 'rank': int(rank), 'week': int(week), 'date': date, 'previous': previous, 'change':", "Returns ------- PyQuery object Returns a PyQuery object of the", "the requested year and combine them on a per-week basis.", "published on. Parameters ---------- year : string A string of", "The list is ordered in terms of the ranking so", "full name, such as 'Purdue' (str), 'rank': Team's rank for", "Date the rankings were released, such as '2017-03-01'. Can also", "for the final rankings or 'Preseason' for preseason rankings (str),", "'date') previous = utils._parse_field(RANKINGS_SCHEME, team, 'previous') change = utils._parse_field(RANKINGS_SCHEME, team,", "and previous rank for each team as well as the", "not year: year = utils._find_year_for_season('ncaaf') page = self._pull_rankings_page(year) if not", "Ensure the following URL \" \"exists: %s\" % RANKINGS_URL) raise", "hierarchy of teams each week. The results expose the current", "and each value is an ``int`` of the team's rank", "up the ladder have a positive number while drops yield", "} \"\"\" latest_week = max(self._rankings.keys()) ordered_dict = sorted(self._rankings[latest_week], key=lambda k:", "overall dictionary has the following structure:: { week number, ie", "Add the final rankings which is not terminated with another", "``dictionaries`` containing the AP rankings for each week. Within each", "to the most recent season. \"\"\" def __init__(self, year=None): self._rankings", "return None def _get_team(self, team): \"\"\" Retrieve team's name and", "of the ranking so the #1 team will be in", "didn't move have 0 (int) } \"\"\" latest_week = max(self._rankings.keys())", "Grab a list of the rankings published by the Associated", "(int) } \"\"\" latest_week = max(self._rankings.keys()) ordered_dict = sorted(self._rankings[latest_week], key=lambda", "dictionary has the following structure:: { week number, ie 16", "= re.sub(r'/.*', '', abbreviation) name = team('td[data-stat=\"school_name\"] a').text() return abbreviation,", "def _find_rankings(self, year): \"\"\" Retrieve the rankings for each week.", "# Add the final rankings which is not terminated with", "= self._pull_rankings_page(year) if not page: output = (\"Can't pull rankings", "year) except HTTPError: return None def _get_team(self, team): \"\"\" Retrieve", "key is a ``string`` of the team's abbreviation and each", "``string`` of the team's abbreviation and each value is an", "Download the rankings page. Download the rankings page for the", "for the requested year and combine them on a per-week", "RANKINGS_URL from six.moves.urllib.error import HTTPError class Rankings: \"\"\" Get all", "hit the first if statement in the loop above. self._rankings[int(week)]", "rank for the current week (int), 'week': Week number for", "name and abbreviation. The team's name and abbreviation are embedded", "a URI. The name and abbreviation are returned for the", "if 'class=\"thead\"' in str(team): self._rankings[int(week)] = weekly_rankings weekly_rankings = []", "date = utils._parse_field(RANKINGS_SCHEME, team, 'date') previous = utils._parse_field(RANKINGS_SCHEME, team, 'previous')", "\"\"\" Returns a ``dictionary`` of the most recent rankings from", "the current and previous rankings as well as the movement", "``dictionary`` where each key is a week number as an", "pull rankings from. \"\"\" if not year: year = utils._find_year_for_season('ncaaf')", "[] week = 0 for team in rankings: if 'class=\"thead\"'", "rankings page for the requested year and create a PyQuery", "the name, abbreviation, rank, movement, and previous rank for each", "is a ``string`` of the team's abbreviation and each value", "k['rank']) return ordered_dict @property def current(self): \"\"\" Returns a ``dictionary``", "the second string is the team's name, such as 'Purdue'.", "were published on. Parameters ---------- year : string A string", "released, such as '2017-03-01'. Can also be 'Final' for the", "for the requested school. Parameters ---------- team : PyQuery object", "pyquery import PyQuery as pq from .. import utils from", "week (int), 'week': Week number for the results, such as", "string of the requested year to pull rankings from. Returns", "of ``dictionaries`` of the most recent AP rankings. The list", "None def _get_team(self, team): \"\"\" Retrieve team's name and abbreviation.", "year to pull rankings from. \"\"\" if not year: year", "weekly_rankings = [] week = 0 for team in rankings:", "rank = utils._parse_field(RANKINGS_SCHEME, team, 'rank') week = utils._parse_field(RANKINGS_SCHEME, team, 'week')", "int(week), 'date': date, 'previous': previous, 'change': change } weekly_rankings.append(rank_details) #", "\"exists: %s\" % RANKINGS_URL) raise ValueError(output) rankings = page('table#ap tbody", "final rankings or 'Preseason' for preseason rankings (str), 'previous': The", "were released, such as '2017-12-03'. Can also be 'Final' for", "self._rankings[int(week)] = weekly_rankings @property def current_extended(self): \"\"\" Returns a ``list``", "such as 16 (int), 'date': Date the rankings were released,", "HTTPError: return None def _get_team(self, team): \"\"\" Retrieve team's name", "'rank': Team's rank for the current week (int), 'week': Week", "of the team's rank for the current week. \"\"\" rankings_dict", "following structure:: { week number, ie 16 (int): [ {", "_pull_rankings_page(self, year): \"\"\" Download the rankings page. Download the rankings", "as name, abbreviation, rank, and more. Note that the list", "rankings page. Ensure the following URL \" \"exists: %s\" %", "= utils._parse_field(RANKINGS_SCHEME, team, 'change') if 'decrease' in str(team(RANKINGS_SCHEME['change'])): change =", "rankings HTML page. \"\"\" try: return pq(RANKINGS_URL % year) except" ]
[ "wrapper(*args, **kwargs): if ding.enable_hpc_rl: shape = shape_fn(args, kwargs) if is_cls_method:", "... }, ... } ``` Besides, `per_fn_limit` means the max", "'vtrace_error': ['hpc_rll.rl_utils.vtrace', 'VTrace'], } fn_str = fn_name_mapping[fn_name] cls = getattr(importlib.import_module(fn_str[0]),", "is_cls_method=False) def dist_nstep_td_error( data: namedtuple, gamma: float, v_min: float, v_max:", "['hpc_rll.rl_utils.td', 'DistNStepTD'], 'LSTM': ['hpc_rll.torch_utils.network.rnn', 'LSTM'], 'ppo_error': ['hpc_rll.rl_utils.ppo', 'PPO'], 'q_nstep_td_error': ['hpc_rll.rl_utils.td',", "'UPGO'], 'vtrace_error': ['hpc_rll.rl_utils.vtrace', 'VTrace'], } fn_str = fn_name_mapping[fn_name] cls =", "k == 'lambda_': k = 'lambda' clean_kwargs[k] = v nouse_kwargs", "list(set(kwargs.keys()).difference(set(include_kwargs))) if len(nouse_args) > 0 or len(nouse_kwargs) > 0: logging.warn(", "k = 'lambda' clean_kwargs[k] = v nouse_kwargs = list(set(kwargs.keys()).difference(set(include_kwargs))) if", "logging from collections import OrderedDict from functools import wraps import", "True, it means the function we wrap is a method", "'gamma', 'v_min', 'v_max'], which means `data`, `gamma`, `v_min` and `v_max`", "{}, index {} of args are dropped, and keys {}", "list of key of the kwargs need to be set", "`include_kwargs` can deal with all type of input, such as", "['hpc_rll.torch_utils.network.rnn', 'LSTM'], 'ppo_error': ['hpc_rll.rl_utils.ppo', 'PPO'], 'q_nstep_td_error': ['hpc_rll.rl_utils.td', 'QNStepTD'], 'q_nstep_td_error_with_rescale': ['hpc_rll.rl_utils.td',", "= args[1:] clean_args = [] for i in include_args: if", "- A: Here we show a normal `hpc_fns`: ``` hpc_fns", "as (data, gamma, v_min=v_min, v_max=v_max) and (data, gamma, v_min, v_max).", "introduce `hpc_wrapper`: ``` @hpc_wrapper(shape_fn=shape_fn_dntd, namedtuple_data=True, include_args=[0,1,2,3], include_kwargs=['data', 'gamma', 'v_min', 'v_max'],", "be put into args. We will get rid of `self`", "import ding ''' Overview: `hpc_wrapper` is the wrapper for functions", "need to be set at the same time? - A:", "'fn_name1': { 'runtime_name1': hpc_fn1, 'runtime_name2': hpc_fn2, ... }, ... }", "= register_runtime_fn(fn_name, runtime_name, shape) else: hpc_fn = hpc_fns[fn_name][runtime_name] if is_cls_method:", "be set at the same time? - A: Yes. `include_args`", "if is_cls_method: args = args[1:] clean_args = [] for i", "getattr(importlib.import_module(fn_str[0]), fn_str[1]) hpc_fn = cls(*shape).cuda() if fn_name not in hpc_fns:", "method of a class. `self` will be put into args.", "normal `hpc_fns`: ``` hpc_fns = { 'fn_name1': { 'runtime_name1': hpc_fn1,", "clean_kwargs = {} for k, v in kwargs.items(): if k", "hpc_fn2, ... }, ... } ``` Besides, `per_fn_limit` means the", "def register_runtime_fn(fn_name, runtime_name, shape): fn_name_mapping = { 'gae': ['hpc_rll.rl_utils.gae', 'GAE'],", "nouse_args = list(set(list(range(len(args)))).difference(set(include_args))) clean_kwargs = {} for k, v in", "set at the same time? - A: Yes. `include_args` and", "for s in shape]) if fn_name not in hpc_fns or", "'v_min', 'v_max'], is_cls_method=False) def dist_nstep_td_error( data: namedtuple, gamma: float, v_min:", "``` Parameters: - shape_fn (:obj:`function`): a function which return the", "of kwargs are dropped.'.format( runtime_name, nouse_args, nouse_kwargs ) ) if", "if namedtuple_data: data = args[0] # args[0] is a namedtuple", "args[0] # args[0] is a namedtuple return hpc_fn(*data, *clean_args[1:], **clean_kwargs)", "'lambda' clean_kwargs[k] = v nouse_kwargs = list(set(kwargs.keys()).difference(set(include_kwargs))) if len(nouse_args) >", "`per_fn_limit` means the max length of `hpc_fns[fn_name]`. When new function", "'v_max'], which means `data`, `gamma`, `v_min` and `v_max` will be", "set in hpc function. - is_cls_method (:obj:`bool`): If True, it", "= 1, ) -> torch.Tensor: ... ``` Parameters: - shape_fn", "a simple method. Q&A: - Q: Is `include_args` and `include_kwargs`", "hpc function. As shown in the sample, include_kwargs=['data', 'gamma', 'v_min',", "- Q: Is `include_args` and `include_kwargs` need to be set", "are supported by hpc. If a function is wrapped by", "n_atom: int, nstep: int = 1, ) -> torch.Tensor: ...", "'upgo_loss': ['hpc_rll.rl_utils.upgo', 'UPGO'], 'vtrace_error': ['hpc_rll.rl_utils.vtrace', 'VTrace'], } fn_str = fn_name_mapping[fn_name]", "a sample to introduce `hpc_wrapper`: ``` @hpc_wrapper(shape_fn=shape_fn_dntd, namedtuple_data=True, include_args=[0,1,2,3], include_kwargs=['data',", "to introduce `hpc_wrapper`: ``` @hpc_wrapper(shape_fn=shape_fn_dntd, namedtuple_data=True, include_args=[0,1,2,3], include_kwargs=['data', 'gamma', 'v_min',", "fn_str[1]) hpc_fn = cls(*shape).cuda() if fn_name not in hpc_fns: hpc_fns[fn_name]", "in hpc_fns: hpc_fns[fn_name] = OrderedDict() hpc_fns[fn_name][runtime_name] = hpc_fn while len(hpc_fns[fn_name])", "args are dropped, and keys {} of kwargs are dropped.'.format(", "in kwargs.items(): if k in include_kwargs: if k == 'lambda_':", "'GAE'], 'dist_nstep_td_error': ['hpc_rll.rl_utils.td', 'DistNStepTD'], 'LSTM': ['hpc_rll.torch_utils.network.rnn', 'LSTM'], 'ppo_error': ['hpc_rll.rl_utils.ppo', 'PPO'],", "be set in hpc function. As shown in the sample,", "include_args=[0,1,2,3], which means `data`, `gamma`, `v_min` and `v_max` will be", "v_max=v_max) and (data, gamma, v_min, v_max). - Q: What is", "method. Q&A: - Q: Is `include_args` and `include_kwargs` need to", "3 def register_runtime_fn(fn_name, runtime_name, shape): fn_name_mapping = { 'gae': ['hpc_rll.rl_utils.gae',", "include_kwargs=[], is_cls_method=False): def decorate(fn): @wraps(fn) def wrapper(*args, **kwargs): if ding.enable_hpc_rl:", "shape_fn(args, kwargs) if is_cls_method: fn_name = args[0].__class__.__name__ else: fn_name =", "wraps import ding ''' Overview: `hpc_wrapper` is the wrapper for", "from `hpc_fns[fn_name]`. ''' hpc_fns = {} per_fn_limit = 3 def", "hpc. We will use the following code as a sample", "[str(s) for s in shape]) if fn_name not in hpc_fns", "else: fn_name = fn.__name__ runtime_name = '_'.join([fn_name] + [str(s) for", "OrderedDict from functools import wraps import ding ''' Overview: `hpc_wrapper`", "be popped from `hpc_fns[fn_name]`. ''' hpc_fns = {} per_fn_limit =", "or runtime_name not in hpc_fns[fn_name]: hpc_fn = register_runtime_fn(fn_name, runtime_name, shape)", "as its fn_name. If False, it means the function is", "def dist_nstep_td_error( data: namedtuple, gamma: float, v_min: float, v_max: float,", "of `hpc_fns[fn_name]`. When new function comes, the oldest function will", "or len(nouse_kwargs) > 0: logging.warn( 'in {}, index {} of", "``` Besides, `per_fn_limit` means the max length of `hpc_fns[fn_name]`. When", "in include_kwargs: if k == 'lambda_': k = 'lambda' clean_kwargs[k]", "Yes. `include_args` and `include_kwargs` can deal with all type of", "in include_args: if i < len(args): clean_args.append(args[i]) nouse_args = list(set(list(range(len(args)))).difference(set(include_args)))", "clean_kwargs[k] = v nouse_kwargs = list(set(kwargs.keys()).difference(set(include_kwargs))) if len(nouse_args) > 0", "by hpc. If a function is wrapped by it, we", "- include_args (:obj:`list`): a list of index of the args", "- include_kwargs (:obj:`list`): a list of key of the kwargs", "comes, the oldest function will be popped from `hpc_fns[fn_name]`. '''", "i in include_args: if i < len(args): clean_args.append(args[i]) nouse_args =", "`gamma`, `v_min` and `v_max` will be set in hpc function.", "'v_max'], is_cls_method=False) def dist_nstep_td_error( data: namedtuple, gamma: float, v_min: float,", "in hpc function. - include_kwargs (:obj:`list`): a list of key", "'runtime_name1': hpc_fn1, 'runtime_name2': hpc_fn2, ... }, ... } ``` Besides,", "the function implemented by hpc. We will use the following", "a function which return the shape needed by hpc function.", "get rid of `self` in args. Besides, we will use", "> 0 or len(nouse_kwargs) > 0: logging.warn( 'in {}, index", "= '_'.join([fn_name] + [str(s) for s in shape]) if fn_name", "as a sample to introduce `hpc_wrapper`: ``` @hpc_wrapper(shape_fn=shape_fn_dntd, namedtuple_data=True, include_args=[0,1,2,3],", "dist_nstep_td_error( data: namedtuple, gamma: float, v_min: float, v_max: float, n_atom:", "shape_fn (:obj:`function`): a function which return the shape needed by", "the wrapper for functions which are supported by hpc. If", "i < len(args): clean_args.append(args[i]) nouse_args = list(set(list(range(len(args)))).difference(set(include_args))) clean_kwargs = {}", "v_min: float, v_max: float, n_atom: int, nstep: int = 1,", "that the hpc function needs. - nametuple_data (:obj:`bool`): If True,", "hpc_fn(*data, *clean_args[1:], **clean_kwargs) else: return hpc_fn(*clean_args, **clean_kwargs) else: return fn(*args,", "`hpc_fns[fn_name]`. When new function comes, the oldest function will be", "Q: Is `include_args` and `include_kwargs` need to be set at", "namedtuple_data=True, include_args=[0,1,2,3], include_kwargs=['data', 'gamma', 'v_min', 'v_max'], is_cls_method=False) def dist_nstep_td_error( data:", "fn_name. If False, it means the function is a simple", "= 'lambda' clean_kwargs[k] = v nouse_kwargs = list(set(kwargs.keys()).difference(set(include_kwargs))) if len(nouse_args)", "collections import OrderedDict from functools import wraps import ding '''", "*clean_args[1:], **clean_kwargs) else: return hpc_fn(*clean_args, **clean_kwargs) else: return fn(*args, **kwargs)", "the kwargs need to be set in hpc function. As", "- is_cls_method (:obj:`bool`): If True, it means the function we", "args. We will get rid of `self` in args. Besides,", "A: Here we show a normal `hpc_fns`: ``` hpc_fns =", "hpc_fn(*clean_args, **clean_kwargs) else: return fn(*args, **kwargs) return wrapper return decorate", "If False, nametuple data will remain its `nametuple` type. -", "function we wrap is a method of a class. `self`", "in shape]) if fn_name not in hpc_fns or runtime_name not", "== 'lambda_': k = 'lambda' clean_kwargs[k] = v nouse_kwargs =", "if len(nouse_args) > 0 or len(nouse_kwargs) > 0: logging.warn( 'in", "dropped.'.format( runtime_name, nouse_args, nouse_kwargs ) ) if namedtuple_data: data =", "'VTrace'], } fn_str = fn_name_mapping[fn_name] cls = getattr(importlib.import_module(fn_str[0]), fn_str[1]) hpc_fn", "the same time? - A: Yes. `include_args` and `include_kwargs` can", "float, n_atom: int, nstep: int = 1, ) -> torch.Tensor:", "fn_name not in hpc_fns or runtime_name not in hpc_fns[fn_name]: hpc_fn", "rid of `self` in args. Besides, we will use its", "`include_args` and `include_kwargs` need to be set at the same", "`hpc_fns`: ``` hpc_fns = { 'fn_name1': { 'runtime_name1': hpc_fn1, 'runtime_name2':", "Overview: `hpc_wrapper` is the wrapper for functions which are supported", "hpc_fns[fn_name].popitem(last=False) # print(hpc_fns) return hpc_fn def hpc_wrapper(shape_fn=None, namedtuple_data=False, include_args=[], include_kwargs=[],", "same time? - A: Yes. `include_args` and `include_kwargs` can deal", "a method of a class. `self` will be put into", "per_fn_limit: hpc_fns[fn_name].popitem(last=False) # print(hpc_fns) return hpc_fn def hpc_wrapper(shape_fn=None, namedtuple_data=False, include_args=[],", "set in hpc function. As shown in the sample, include_kwargs=['data',", "all type of input, such as (data, gamma, v_min=v_min, v_max=v_max)", "hpc_fn = cls(*shape).cuda() if fn_name not in hpc_fns: hpc_fns[fn_name] =", "'TDLambda'], 'upgo_loss': ['hpc_rll.rl_utils.upgo', 'UPGO'], 'vtrace_error': ['hpc_rll.rl_utils.vtrace', 'VTrace'], } fn_str =", "class. `self` will be put into args. We will get", "'QNStepTDRescale'], 'ScatterConnection': ['hpc_rll.torch_utils.network.scatter_connection', 'ScatterConnection'], 'td_lambda_error': ['hpc_rll.rl_utils.td', 'TDLambda'], 'upgo_loss': ['hpc_rll.rl_utils.upgo', 'UPGO'],", "True, when hpc function is called, it will be called", "and (data, gamma, v_min, v_max). - Q: What is `hpc_fns`?", "will use its classname as its fn_name. If False, it", "{ 'gae': ['hpc_rll.rl_utils.gae', 'GAE'], 'dist_nstep_td_error': ['hpc_rll.rl_utils.td', 'DistNStepTD'], 'LSTM': ['hpc_rll.torch_utils.network.rnn', 'LSTM'],", "include_args (:obj:`list`): a list of index of the args need", "If False, it means the function is a simple method.", "called as hpc_function(*nametuple). If False, nametuple data will remain its", "(:obj:`function`): a function which return the shape needed by hpc", "`v_max` will be set in hpc function. - include_kwargs (:obj:`list`):", "show a normal `hpc_fns`: ``` hpc_fns = { 'fn_name1': {", "logging.warn( 'in {}, index {} of args are dropped, and", "<filename>ding/hpc_rl/wrapper.py import importlib from ditk import logging from collections import", "namedtuple_data=False, include_args=[], include_kwargs=[], is_cls_method=False): def decorate(fn): @wraps(fn) def wrapper(*args, **kwargs):", "= { 'gae': ['hpc_rll.rl_utils.gae', 'GAE'], 'dist_nstep_td_error': ['hpc_rll.rl_utils.td', 'DistNStepTD'], 'LSTM': ['hpc_rll.torch_utils.network.rnn',", "runtime_name, shape) else: hpc_fn = hpc_fns[fn_name][runtime_name] if is_cls_method: args =", "['hpc_rll.rl_utils.gae', 'GAE'], 'dist_nstep_td_error': ['hpc_rll.rl_utils.td', 'DistNStepTD'], 'LSTM': ['hpc_rll.torch_utils.network.rnn', 'LSTM'], 'ppo_error': ['hpc_rll.rl_utils.ppo',", "= hpc_fns[fn_name][runtime_name] if is_cls_method: args = args[1:] clean_args = []", "of args are dropped, and keys {} of kwargs are", "args need to be set in hpc function. As shown", "= v nouse_kwargs = list(set(kwargs.keys()).difference(set(include_kwargs))) if len(nouse_args) > 0 or", "from functools import wraps import ding ''' Overview: `hpc_wrapper` is", "needs. - nametuple_data (:obj:`bool`): If True, when hpc function is", "False, nametuple data will remain its `nametuple` type. - include_args", "shape]) if fn_name not in hpc_fns or runtime_name not in", "= hpc_fn while len(hpc_fns[fn_name]) > per_fn_limit: hpc_fns[fn_name].popitem(last=False) # print(hpc_fns) return", "wrapper for functions which are supported by hpc. If a", "hpc_fns[fn_name][runtime_name] if is_cls_method: args = args[1:] clean_args = [] for", "if i < len(args): clean_args.append(args[i]) nouse_args = list(set(list(range(len(args)))).difference(set(include_args))) clean_kwargs =", "the function is a simple method. Q&A: - Q: Is", "'q_nstep_td_error': ['hpc_rll.rl_utils.td', 'QNStepTD'], 'q_nstep_td_error_with_rescale': ['hpc_rll.rl_utils.td', 'QNStepTDRescale'], 'ScatterConnection': ['hpc_rll.torch_utils.network.scatter_connection', 'ScatterConnection'], 'td_lambda_error':", "its classname as its fn_name. If False, it means the", "is a simple method. Q&A: - Q: Is `include_args` and", "= { 'fn_name1': { 'runtime_name1': hpc_fn1, 'runtime_name2': hpc_fn2, ... },", "by it, we will search for its hpc type and", "fn_name not in hpc_fns: hpc_fns[fn_name] = OrderedDict() hpc_fns[fn_name][runtime_name] = hpc_fn", "return hpc_fn def hpc_wrapper(shape_fn=None, namedtuple_data=False, include_args=[], include_kwargs=[], is_cls_method=False): def decorate(fn):", "the sample, include_kwargs=['data', 'gamma', 'v_min', 'v_max'], which means `data`, `gamma`,", "are dropped.'.format( runtime_name, nouse_args, nouse_kwargs ) ) if namedtuple_data: data", "is_cls_method: args = args[1:] clean_args = [] for i in", "function needs. - nametuple_data (:obj:`bool`): If True, when hpc function", "from ditk import logging from collections import OrderedDict from functools", "of a class. `self` will be put into args. We", "len(args): clean_args.append(args[i]) nouse_args = list(set(list(range(len(args)))).difference(set(include_args))) clean_kwargs = {} for k,", "In fact, it returns all args that the hpc function", "of the args need to be set in hpc function.", "gamma, v_min=v_min, v_max=v_max) and (data, gamma, v_min, v_max). - Q:", "hpc_fn = hpc_fns[fn_name][runtime_name] if is_cls_method: args = args[1:] clean_args =", "and `include_kwargs` need to be set at the same time?", "function is wrapped by it, we will search for its", "gamma, v_min, v_max). - Q: What is `hpc_fns`? - A:", "kwargs.items(): if k in include_kwargs: if k == 'lambda_': k", "functions which are supported by hpc. If a function is", "v_max: float, n_atom: int, nstep: int = 1, ) ->", "sample, include_kwargs=['data', 'gamma', 'v_min', 'v_max'], which means `data`, `gamma`, `v_min`", "for k, v in kwargs.items(): if k in include_kwargs: if", "hpc_fn while len(hpc_fns[fn_name]) > per_fn_limit: hpc_fns[fn_name].popitem(last=False) # print(hpc_fns) return hpc_fn", "shown in the sample, include_args=[0,1,2,3], which means `data`, `gamma`, `v_min`", "cls(*shape).cuda() if fn_name not in hpc_fns: hpc_fns[fn_name] = OrderedDict() hpc_fns[fn_name][runtime_name]", "of `self` in args. Besides, we will use its classname", "set in hpc function. - include_kwargs (:obj:`list`): a list of", "means the function is a simple method. Q&A: - Q:", "v_min, v_max). - Q: What is `hpc_fns`? - A: Here", "k, v in kwargs.items(): if k in include_kwargs: if k", "and `v_max` will be set in hpc function. - is_cls_method", "and keys {} of kwargs are dropped.'.format( runtime_name, nouse_args, nouse_kwargs", "shown in the sample, include_kwargs=['data', 'gamma', 'v_min', 'v_max'], which means", "and `include_kwargs` can deal with all type of input, such", "- Q: What is `hpc_fns`? - A: Here we show", "per_fn_limit = 3 def register_runtime_fn(fn_name, runtime_name, shape): fn_name_mapping = {", "function. In fact, it returns all args that the hpc", "the following code as a sample to introduce `hpc_wrapper`: ```", "hpc_fn1, 'runtime_name2': hpc_fn2, ... }, ... } ``` Besides, `per_fn_limit`", "wrap is a method of a class. `self` will be", "a list of index of the args need to be", "... } ``` Besides, `per_fn_limit` means the max length of", "be set in hpc function. - include_kwargs (:obj:`list`): a list", "with all type of input, such as (data, gamma, v_min=v_min,", "hpc_fn = register_runtime_fn(fn_name, runtime_name, shape) else: hpc_fn = hpc_fns[fn_name][runtime_name] if", "If a function is wrapped by it, we will search", "all args that the hpc function needs. - nametuple_data (:obj:`bool`):", "''' hpc_fns = {} per_fn_limit = 3 def register_runtime_fn(fn_name, runtime_name,", "'ScatterConnection': ['hpc_rll.torch_utils.network.scatter_connection', 'ScatterConnection'], 'td_lambda_error': ['hpc_rll.rl_utils.td', 'TDLambda'], 'upgo_loss': ['hpc_rll.rl_utils.upgo', 'UPGO'], 'vtrace_error':", "hpc_fns: hpc_fns[fn_name] = OrderedDict() hpc_fns[fn_name][runtime_name] = hpc_fn while len(hpc_fns[fn_name]) >", "in hpc function. As shown in the sample, include_args=[0,1,2,3], which", "import importlib from ditk import logging from collections import OrderedDict", "namedtuple_data: data = args[0] # args[0] is a namedtuple return", "{} per_fn_limit = 3 def register_runtime_fn(fn_name, runtime_name, shape): fn_name_mapping =", "'gamma', 'v_min', 'v_max'], is_cls_method=False) def dist_nstep_td_error( data: namedtuple, gamma: float,", "Parameters: - shape_fn (:obj:`function`): a function which return the shape", "it means the function is a simple method. Q&A: -", "fn_name = fn.__name__ runtime_name = '_'.join([fn_name] + [str(s) for s", "v nouse_kwargs = list(set(kwargs.keys()).difference(set(include_kwargs))) if len(nouse_args) > 0 or len(nouse_kwargs)", "function is a simple method. Q&A: - Q: Is `include_args`", "= shape_fn(args, kwargs) if is_cls_method: fn_name = args[0].__class__.__name__ else: fn_name", "list(set(list(range(len(args)))).difference(set(include_args))) clean_kwargs = {} for k, v in kwargs.items(): if", "into args. We will get rid of `self` in args.", "float, v_max: float, n_atom: int, nstep: int = 1, )", "= fn_name_mapping[fn_name] cls = getattr(importlib.import_module(fn_str[0]), fn_str[1]) hpc_fn = cls(*shape).cuda() if", "= cls(*shape).cuda() if fn_name not in hpc_fns: hpc_fns[fn_name] = OrderedDict()", "When new function comes, the oldest function will be popped", "fn_name = args[0].__class__.__name__ else: fn_name = fn.__name__ runtime_name = '_'.join([fn_name]", "kwargs are dropped.'.format( runtime_name, nouse_args, nouse_kwargs ) ) if namedtuple_data:", "= [] for i in include_args: if i < len(args):", "is called, it will be called as hpc_function(*nametuple). If False,", "function. - is_cls_method (:obj:`bool`): If True, it means the function", "of input, such as (data, gamma, v_min=v_min, v_max=v_max) and (data,", "a normal `hpc_fns`: ``` hpc_fns = { 'fn_name1': { 'runtime_name1':", "if fn_name not in hpc_fns: hpc_fns[fn_name] = OrderedDict() hpc_fns[fn_name][runtime_name] =", "hpc function. - is_cls_method (:obj:`bool`): If True, it means the", "will use the following code as a sample to introduce", "['hpc_rll.rl_utils.td', 'TDLambda'], 'upgo_loss': ['hpc_rll.rl_utils.upgo', 'UPGO'], 'vtrace_error': ['hpc_rll.rl_utils.vtrace', 'VTrace'], } fn_str", "hpc function. In fact, it returns all args that the", "shape = shape_fn(args, kwargs) if is_cls_method: fn_name = args[0].__class__.__name__ else:", "import logging from collections import OrderedDict from functools import wraps", "namedtuple, gamma: float, v_min: float, v_max: float, n_atom: int, nstep:", "args = args[1:] clean_args = [] for i in include_args:", "the hpc function needs. - nametuple_data (:obj:`bool`): If True, when", "in hpc_fns or runtime_name not in hpc_fns[fn_name]: hpc_fn = register_runtime_fn(fn_name,", "not in hpc_fns[fn_name]: hpc_fn = register_runtime_fn(fn_name, runtime_name, shape) else: hpc_fn", "- nametuple_data (:obj:`bool`): If True, when hpc function is called,", "def decorate(fn): @wraps(fn) def wrapper(*args, **kwargs): if ding.enable_hpc_rl: shape =", "the function we wrap is a method of a class.", "namedtuple return hpc_fn(*data, *clean_args[1:], **clean_kwargs) else: return hpc_fn(*clean_args, **clean_kwargs) else:", ") ) if namedtuple_data: data = args[0] # args[0] is", "will be set in hpc function. - include_kwargs (:obj:`list`): a", "float, v_min: float, v_max: float, n_atom: int, nstep: int =", "the max length of `hpc_fns[fn_name]`. When new function comes, the", "Q: What is `hpc_fns`? - A: Here we show a", "implemented by hpc. We will use the following code as", "in hpc_fns[fn_name]: hpc_fn = register_runtime_fn(fn_name, runtime_name, shape) else: hpc_fn =", "called, it will be called as hpc_function(*nametuple). If False, nametuple", "`nametuple` type. - include_args (:obj:`list`): a list of index of", "it returns all args that the hpc function needs. -", "hpc_fns or runtime_name not in hpc_fns[fn_name]: hpc_fn = register_runtime_fn(fn_name, runtime_name,", "hpc_fns[fn_name] = OrderedDict() hpc_fns[fn_name][runtime_name] = hpc_fn while len(hpc_fns[fn_name]) > per_fn_limit:", "importlib from ditk import logging from collections import OrderedDict from", "and return the function implemented by hpc. We will use", "ding.enable_hpc_rl: shape = shape_fn(args, kwargs) if is_cls_method: fn_name = args[0].__class__.__name__", "fn_str = fn_name_mapping[fn_name] cls = getattr(importlib.import_module(fn_str[0]), fn_str[1]) hpc_fn = cls(*shape).cuda()", "it, we will search for its hpc type and return", "data = args[0] # args[0] is a namedtuple return hpc_fn(*data,", "runtime_name = '_'.join([fn_name] + [str(s) for s in shape]) if", "we will use its classname as its fn_name. If False,", "If True, it means the function we wrap is a", "use the following code as a sample to introduce `hpc_wrapper`:", "function which return the shape needed by hpc function. In", "max length of `hpc_fns[fn_name]`. When new function comes, the oldest", "while len(hpc_fns[fn_name]) > per_fn_limit: hpc_fns[fn_name].popitem(last=False) # print(hpc_fns) return hpc_fn def", "clean_args.append(args[i]) nouse_args = list(set(list(range(len(args)))).difference(set(include_args))) clean_kwargs = {} for k, v", "function comes, the oldest function will be popped from `hpc_fns[fn_name]`.", "< len(args): clean_args.append(args[i]) nouse_args = list(set(list(range(len(args)))).difference(set(include_args))) clean_kwargs = {} for", "'in {}, index {} of args are dropped, and keys", "`hpc_wrapper`: ``` @hpc_wrapper(shape_fn=shape_fn_dntd, namedtuple_data=True, include_args=[0,1,2,3], include_kwargs=['data', 'gamma', 'v_min', 'v_max'], is_cls_method=False)", "> per_fn_limit: hpc_fns[fn_name].popitem(last=False) # print(hpc_fns) return hpc_fn def hpc_wrapper(shape_fn=None, namedtuple_data=False,", "args that the hpc function needs. - nametuple_data (:obj:`bool`): If", "index of the args need to be set in hpc", "time? - A: Yes. `include_args` and `include_kwargs` can deal with", "'QNStepTD'], 'q_nstep_td_error_with_rescale': ['hpc_rll.rl_utils.td', 'QNStepTDRescale'], 'ScatterConnection': ['hpc_rll.torch_utils.network.scatter_connection', 'ScatterConnection'], 'td_lambda_error': ['hpc_rll.rl_utils.td', 'TDLambda'],", "runtime_name not in hpc_fns[fn_name]: hpc_fn = register_runtime_fn(fn_name, runtime_name, shape) else:", "we wrap is a method of a class. `self` will", "else: hpc_fn = hpc_fns[fn_name][runtime_name] if is_cls_method: args = args[1:] clean_args", "will get rid of `self` in args. Besides, we will", "type. - include_args (:obj:`list`): a list of index of the", "+ [str(s) for s in shape]) if fn_name not in", "will remain its `nametuple` type. - include_args (:obj:`list`): a list", "supported by hpc. If a function is wrapped by it,", "len(hpc_fns[fn_name]) > per_fn_limit: hpc_fns[fn_name].popitem(last=False) # print(hpc_fns) return hpc_fn def hpc_wrapper(shape_fn=None,", "it means the function we wrap is a method of", "include_kwargs: if k == 'lambda_': k = 'lambda' clean_kwargs[k] =", "We will use the following code as a sample to", "'LSTM': ['hpc_rll.torch_utils.network.rnn', 'LSTM'], 'ppo_error': ['hpc_rll.rl_utils.ppo', 'PPO'], 'q_nstep_td_error': ['hpc_rll.rl_utils.td', 'QNStepTD'], 'q_nstep_td_error_with_rescale':", "hpc type and return the function implemented by hpc. We", "in hpc function. As shown in the sample, include_kwargs=['data', 'gamma',", "in args. Besides, we will use its classname as its", "args[0] is a namedtuple return hpc_fn(*data, *clean_args[1:], **clean_kwargs) else: return", "if is_cls_method: fn_name = args[0].__class__.__name__ else: fn_name = fn.__name__ runtime_name", "import wraps import ding ''' Overview: `hpc_wrapper` is the wrapper", "by hpc. We will use the following code as a", "}, ... } ``` Besides, `per_fn_limit` means the max length", "(:obj:`list`): a list of index of the args need to", "such as (data, gamma, v_min=v_min, v_max=v_max) and (data, gamma, v_min,", "function. - include_kwargs (:obj:`list`): a list of key of the", "`hpc_wrapper` is the wrapper for functions which are supported by", "def hpc_wrapper(shape_fn=None, namedtuple_data=False, include_args=[], include_kwargs=[], is_cls_method=False): def decorate(fn): @wraps(fn) def", "its hpc type and return the function implemented by hpc.", "0 or len(nouse_kwargs) > 0: logging.warn( 'in {}, index {}", "as hpc_function(*nametuple). If False, nametuple data will remain its `nametuple`", "= getattr(importlib.import_module(fn_str[0]), fn_str[1]) hpc_fn = cls(*shape).cuda() if fn_name not in", "nouse_kwargs ) ) if namedtuple_data: data = args[0] # args[0]", "fact, it returns all args that the hpc function needs.", "of key of the kwargs need to be set in", "is_cls_method: fn_name = args[0].__class__.__name__ else: fn_name = fn.__name__ runtime_name =", "will be called as hpc_function(*nametuple). If False, nametuple data will", "nouse_args, nouse_kwargs ) ) if namedtuple_data: data = args[0] #", "include_args=[0,1,2,3], include_kwargs=['data', 'gamma', 'v_min', 'v_max'], is_cls_method=False) def dist_nstep_td_error( data: namedtuple,", "shape): fn_name_mapping = { 'gae': ['hpc_rll.rl_utils.gae', 'GAE'], 'dist_nstep_td_error': ['hpc_rll.rl_utils.td', 'DistNStepTD'],", "`include_kwargs` need to be set at the same time? -", "hpc_fns = {} per_fn_limit = 3 def register_runtime_fn(fn_name, runtime_name, shape):", "in the sample, include_args=[0,1,2,3], which means `data`, `gamma`, `v_min` and", "OrderedDict() hpc_fns[fn_name][runtime_name] = hpc_fn while len(hpc_fns[fn_name]) > per_fn_limit: hpc_fns[fn_name].popitem(last=False) #", "# print(hpc_fns) return hpc_fn def hpc_wrapper(shape_fn=None, namedtuple_data=False, include_args=[], include_kwargs=[], is_cls_method=False):", "return hpc_fn(*clean_args, **clean_kwargs) else: return fn(*args, **kwargs) return wrapper return", "index {} of args are dropped, and keys {} of", "'PPO'], 'q_nstep_td_error': ['hpc_rll.rl_utils.td', 'QNStepTD'], 'q_nstep_td_error_with_rescale': ['hpc_rll.rl_utils.td', 'QNStepTDRescale'], 'ScatterConnection': ['hpc_rll.torch_utils.network.scatter_connection', 'ScatterConnection'],", "} fn_str = fn_name_mapping[fn_name] cls = getattr(importlib.import_module(fn_str[0]), fn_str[1]) hpc_fn =", "**kwargs): if ding.enable_hpc_rl: shape = shape_fn(args, kwargs) if is_cls_method: fn_name", "'DistNStepTD'], 'LSTM': ['hpc_rll.torch_utils.network.rnn', 'LSTM'], 'ppo_error': ['hpc_rll.rl_utils.ppo', 'PPO'], 'q_nstep_td_error': ['hpc_rll.rl_utils.td', 'QNStepTD'],", "if fn_name not in hpc_fns or runtime_name not in hpc_fns[fn_name]:", "if ding.enable_hpc_rl: shape = shape_fn(args, kwargs) if is_cls_method: fn_name =", "the args need to be set in hpc function. As", "A: Yes. `include_args` and `include_kwargs` can deal with all type", "v in kwargs.items(): if k in include_kwargs: if k ==", "means `data`, `gamma`, `v_min` and `v_max` will be set in", "if k == 'lambda_': k = 'lambda' clean_kwargs[k] = v", "and `v_max` will be set in hpc function. - include_kwargs", "['hpc_rll.rl_utils.td', 'QNStepTD'], 'q_nstep_td_error_with_rescale': ['hpc_rll.rl_utils.td', 'QNStepTDRescale'], 'ScatterConnection': ['hpc_rll.torch_utils.network.scatter_connection', 'ScatterConnection'], 'td_lambda_error': ['hpc_rll.rl_utils.td',", "[] for i in include_args: if i < len(args): clean_args.append(args[i])", "hpc function needs. - nametuple_data (:obj:`bool`): If True, when hpc", "import OrderedDict from functools import wraps import ding ''' Overview:", "key of the kwargs need to be set in hpc", "we show a normal `hpc_fns`: ``` hpc_fns = { 'fn_name1':", "be called as hpc_function(*nametuple). If False, nametuple data will remain", "the shape needed by hpc function. In fact, it returns", "function will be popped from `hpc_fns[fn_name]`. ''' hpc_fns = {}", "register_runtime_fn(fn_name, runtime_name, shape): fn_name_mapping = { 'gae': ['hpc_rll.rl_utils.gae', 'GAE'], 'dist_nstep_td_error':", "'ScatterConnection'], 'td_lambda_error': ['hpc_rll.rl_utils.td', 'TDLambda'], 'upgo_loss': ['hpc_rll.rl_utils.upgo', 'UPGO'], 'vtrace_error': ['hpc_rll.rl_utils.vtrace', 'VTrace'],", "s in shape]) if fn_name not in hpc_fns or runtime_name", "input, such as (data, gamma, v_min=v_min, v_max=v_max) and (data, gamma,", "len(nouse_args) > 0 or len(nouse_kwargs) > 0: logging.warn( 'in {},", "shape) else: hpc_fn = hpc_fns[fn_name][runtime_name] if is_cls_method: args = args[1:]", "nametuple data will remain its `nametuple` type. - include_args (:obj:`list`):", "decorate(fn): @wraps(fn) def wrapper(*args, **kwargs): if ding.enable_hpc_rl: shape = shape_fn(args,", "set in hpc function. As shown in the sample, include_args=[0,1,2,3],", "Besides, `per_fn_limit` means the max length of `hpc_fns[fn_name]`. When new", "= 3 def register_runtime_fn(fn_name, runtime_name, shape): fn_name_mapping = { 'gae':", "hpc_fn def hpc_wrapper(shape_fn=None, namedtuple_data=False, include_args=[], include_kwargs=[], is_cls_method=False): def decorate(fn): @wraps(fn)", "is the wrapper for functions which are supported by hpc.", "shape needed by hpc function. In fact, it returns all", "{ 'runtime_name1': hpc_fn1, 'runtime_name2': hpc_fn2, ... }, ... } ```", "'lambda_': k = 'lambda' clean_kwargs[k] = v nouse_kwargs = list(set(kwargs.keys()).difference(set(include_kwargs)))", "> 0: logging.warn( 'in {}, index {} of args are", "needed by hpc function. In fact, it returns all args", "{} of kwargs are dropped.'.format( runtime_name, nouse_args, nouse_kwargs ) )", "Besides, we will use its classname as its fn_name. If", "= list(set(list(range(len(args)))).difference(set(include_args))) clean_kwargs = {} for k, v in kwargs.items():", "oldest function will be popped from `hpc_fns[fn_name]`. ''' hpc_fns =", "runtime_name, shape): fn_name_mapping = { 'gae': ['hpc_rll.rl_utils.gae', 'GAE'], 'dist_nstep_td_error': ['hpc_rll.rl_utils.td',", "`v_max` will be set in hpc function. - is_cls_method (:obj:`bool`):", "functools import wraps import ding ''' Overview: `hpc_wrapper` is the", "ditk import logging from collections import OrderedDict from functools import", "} ``` Besides, `per_fn_limit` means the max length of `hpc_fns[fn_name]`.", "of the kwargs need to be set in hpc function.", "keys {} of kwargs are dropped.'.format( runtime_name, nouse_args, nouse_kwargs )", "data: namedtuple, gamma: float, v_min: float, v_max: float, n_atom: int,", "`hpc_fns`? - A: Here we show a normal `hpc_fns`: ```", "for functions which are supported by hpc. If a function", "use its classname as its fn_name. If False, it means", "runtime_name, nouse_args, nouse_kwargs ) ) if namedtuple_data: data = args[0]", "'td_lambda_error': ['hpc_rll.rl_utils.td', 'TDLambda'], 'upgo_loss': ['hpc_rll.rl_utils.upgo', 'UPGO'], 'vtrace_error': ['hpc_rll.rl_utils.vtrace', 'VTrace'], }", "gamma: float, v_min: float, v_max: float, n_atom: int, nstep: int", "**clean_kwargs) else: return hpc_fn(*clean_args, **clean_kwargs) else: return fn(*args, **kwargs) return", "function implemented by hpc. We will use the following code", "`data`, `gamma`, `v_min` and `v_max` will be set in hpc", "fn.__name__ runtime_name = '_'.join([fn_name] + [str(s) for s in shape])", "= {} for k, v in kwargs.items(): if k in", "hpc function. As shown in the sample, include_args=[0,1,2,3], which means", "will search for its hpc type and return the function", "is_cls_method (:obj:`bool`): If True, it means the function we wrap", "hpc_fns[fn_name][runtime_name] = hpc_fn while len(hpc_fns[fn_name]) > per_fn_limit: hpc_fns[fn_name].popitem(last=False) # print(hpc_fns)", "which return the shape needed by hpc function. In fact,", "function is called, it will be called as hpc_function(*nametuple). If", "the oldest function will be popped from `hpc_fns[fn_name]`. ''' hpc_fns", "-> torch.Tensor: ... ``` Parameters: - shape_fn (:obj:`function`): a function", ") -> torch.Tensor: ... ``` Parameters: - shape_fn (:obj:`function`): a", "wrapped by it, we will search for its hpc type", "(data, gamma, v_min=v_min, v_max=v_max) and (data, gamma, v_min, v_max). -", "which are supported by hpc. If a function is wrapped", "torch.Tensor: ... ``` Parameters: - shape_fn (:obj:`function`): a function which", "will be set in hpc function. - is_cls_method (:obj:`bool`): If", "nametuple_data (:obj:`bool`): If True, when hpc function is called, it", "['hpc_rll.torch_utils.network.scatter_connection', 'ScatterConnection'], 'td_lambda_error': ['hpc_rll.rl_utils.td', 'TDLambda'], 'upgo_loss': ['hpc_rll.rl_utils.upgo', 'UPGO'], 'vtrace_error': ['hpc_rll.rl_utils.vtrace',", "include_args=[], include_kwargs=[], is_cls_method=False): def decorate(fn): @wraps(fn) def wrapper(*args, **kwargs): if", "`v_min` and `v_max` will be set in hpc function. -", "def wrapper(*args, **kwargs): if ding.enable_hpc_rl: shape = shape_fn(args, kwargs) if", "(:obj:`bool`): If True, when hpc function is called, it will", "- A: Yes. `include_args` and `include_kwargs` can deal with all", "not in hpc_fns or runtime_name not in hpc_fns[fn_name]: hpc_fn =", "hpc. If a function is wrapped by it, we will", "be set in hpc function. - is_cls_method (:obj:`bool`): If True,", "following code as a sample to introduce `hpc_wrapper`: ``` @hpc_wrapper(shape_fn=shape_fn_dntd,", "- shape_fn (:obj:`function`): a function which return the shape needed", "at the same time? - A: Yes. `include_args` and `include_kwargs`", "'LSTM'], 'ppo_error': ['hpc_rll.rl_utils.ppo', 'PPO'], 'q_nstep_td_error': ['hpc_rll.rl_utils.td', 'QNStepTD'], 'q_nstep_td_error_with_rescale': ['hpc_rll.rl_utils.td', 'QNStepTDRescale'],", "will be popped from `hpc_fns[fn_name]`. ''' hpc_fns = {} per_fn_limit", "it will be called as hpc_function(*nametuple). If False, nametuple data", "= fn.__name__ runtime_name = '_'.join([fn_name] + [str(s) for s in", "'runtime_name2': hpc_fn2, ... }, ... } ``` Besides, `per_fn_limit` means", "by hpc function. In fact, it returns all args that", "`hpc_fns[fn_name]`. ''' hpc_fns = {} per_fn_limit = 3 def register_runtime_fn(fn_name,", "fn_name_mapping = { 'gae': ['hpc_rll.rl_utils.gae', 'GAE'], 'dist_nstep_td_error': ['hpc_rll.rl_utils.td', 'DistNStepTD'], 'LSTM':", "`self` in args. Besides, we will use its classname as", "= args[0] # args[0] is a namedtuple return hpc_fn(*data, *clean_args[1:],", "hpc_function(*nametuple). If False, nametuple data will remain its `nametuple` type.", "`self` will be put into args. We will get rid", "returns all args that the hpc function needs. - nametuple_data", "put into args. We will get rid of `self` in", "Is `include_args` and `include_kwargs` need to be set at the", "len(nouse_kwargs) > 0: logging.warn( 'in {}, index {} of args", "If True, when hpc function is called, it will be", "args[0].__class__.__name__ else: fn_name = fn.__name__ runtime_name = '_'.join([fn_name] + [str(s)", "k in include_kwargs: if k == 'lambda_': k = 'lambda'", "dropped, and keys {} of kwargs are dropped.'.format( runtime_name, nouse_args,", "hpc_fns[fn_name]: hpc_fn = register_runtime_fn(fn_name, runtime_name, shape) else: hpc_fn = hpc_fns[fn_name][runtime_name]", "1, ) -> torch.Tensor: ... ``` Parameters: - shape_fn (:obj:`function`):", "= args[0].__class__.__name__ else: fn_name = fn.__name__ runtime_name = '_'.join([fn_name] +", "As shown in the sample, include_kwargs=['data', 'gamma', 'v_min', 'v_max'], which", "is a namedtuple return hpc_fn(*data, *clean_args[1:], **clean_kwargs) else: return hpc_fn(*clean_args,", "type of input, such as (data, gamma, v_min=v_min, v_max=v_max) and", "include_kwargs (:obj:`list`): a list of key of the kwargs need", "is `hpc_fns`? - A: Here we show a normal `hpc_fns`:", "for i in include_args: if i < len(args): clean_args.append(args[i]) nouse_args", "['hpc_rll.rl_utils.vtrace', 'VTrace'], } fn_str = fn_name_mapping[fn_name] cls = getattr(importlib.import_module(fn_str[0]), fn_str[1])", "a namedtuple return hpc_fn(*data, *clean_args[1:], **clean_kwargs) else: return hpc_fn(*clean_args, **clean_kwargs)", "popped from `hpc_fns[fn_name]`. ''' hpc_fns = {} per_fn_limit = 3", "new function comes, the oldest function will be popped from", "v_min=v_min, v_max=v_max) and (data, gamma, v_min, v_max). - Q: What", "function. As shown in the sample, include_args=[0,1,2,3], which means `data`,", "return the function implemented by hpc. We will use the", "remain its `nametuple` type. - include_args (:obj:`list`): a list of", "a function is wrapped by it, we will search for", "cls = getattr(importlib.import_module(fn_str[0]), fn_str[1]) hpc_fn = cls(*shape).cuda() if fn_name not", "in the sample, include_kwargs=['data', 'gamma', 'v_min', 'v_max'], which means `data`,", "@wraps(fn) def wrapper(*args, **kwargs): if ding.enable_hpc_rl: shape = shape_fn(args, kwargs)", "we will search for its hpc type and return the", "sample, include_args=[0,1,2,3], which means `data`, `gamma`, `v_min` and `v_max` will", "hpc_fns = { 'fn_name1': { 'runtime_name1': hpc_fn1, 'runtime_name2': hpc_fn2, ...", "'q_nstep_td_error_with_rescale': ['hpc_rll.rl_utils.td', 'QNStepTDRescale'], 'ScatterConnection': ['hpc_rll.torch_utils.network.scatter_connection', 'ScatterConnection'], 'td_lambda_error': ['hpc_rll.rl_utils.td', 'TDLambda'], 'upgo_loss':", "`include_args` and `include_kwargs` can deal with all type of input,", "sample to introduce `hpc_wrapper`: ``` @hpc_wrapper(shape_fn=shape_fn_dntd, namedtuple_data=True, include_args=[0,1,2,3], include_kwargs=['data', 'gamma',", "args. Besides, we will use its classname as its fn_name.", "of index of the args need to be set in", "``` @hpc_wrapper(shape_fn=shape_fn_dntd, namedtuple_data=True, include_args=[0,1,2,3], include_kwargs=['data', 'gamma', 'v_min', 'v_max'], is_cls_method=False) def", "''' Overview: `hpc_wrapper` is the wrapper for functions which are", "nstep: int = 1, ) -> torch.Tensor: ... ``` Parameters:", "0: logging.warn( 'in {}, index {} of args are dropped,", "# args[0] is a namedtuple return hpc_fn(*data, *clean_args[1:], **clean_kwargs) else:", "As shown in the sample, include_args=[0,1,2,3], which means `data`, `gamma`,", "is_cls_method=False): def decorate(fn): @wraps(fn) def wrapper(*args, **kwargs): if ding.enable_hpc_rl: shape", "to be set at the same time? - A: Yes.", "register_runtime_fn(fn_name, runtime_name, shape) else: hpc_fn = hpc_fns[fn_name][runtime_name] if is_cls_method: args", "the sample, include_args=[0,1,2,3], which means `data`, `gamma`, `v_min` and `v_max`", "type and return the function implemented by hpc. We will", "include_kwargs=['data', 'gamma', 'v_min', 'v_max'], is_cls_method=False) def dist_nstep_td_error( data: namedtuple, gamma:", "int, nstep: int = 1, ) -> torch.Tensor: ... ```", "ding ''' Overview: `hpc_wrapper` is the wrapper for functions which", "int = 1, ) -> torch.Tensor: ... ``` Parameters: -", "length of `hpc_fns[fn_name]`. When new function comes, the oldest function", "['hpc_rll.rl_utils.upgo', 'UPGO'], 'vtrace_error': ['hpc_rll.rl_utils.vtrace', 'VTrace'], } fn_str = fn_name_mapping[fn_name] cls", "clean_args = [] for i in include_args: if i <", "(:obj:`list`): a list of key of the kwargs need to", "{} of args are dropped, and keys {} of kwargs", "False, it means the function is a simple method. Q&A:", "its `nametuple` type. - include_args (:obj:`list`): a list of index", "(:obj:`bool`): If True, it means the function we wrap is", ") if namedtuple_data: data = args[0] # args[0] is a", "need to be set in hpc function. As shown in", "= list(set(kwargs.keys()).difference(set(include_kwargs))) if len(nouse_args) > 0 or len(nouse_kwargs) > 0:", "{ 'fn_name1': { 'runtime_name1': hpc_fn1, 'runtime_name2': hpc_fn2, ... }, ...", "``` hpc_fns = { 'fn_name1': { 'runtime_name1': hpc_fn1, 'runtime_name2': hpc_fn2,", "include_kwargs=['data', 'gamma', 'v_min', 'v_max'], which means `data`, `gamma`, `v_min` and", "its fn_name. If False, it means the function is a", "means the function we wrap is a method of a", "will be put into args. We will get rid of", "else: return hpc_fn(*clean_args, **clean_kwargs) else: return fn(*args, **kwargs) return wrapper", "Q&A: - Q: Is `include_args` and `include_kwargs` need to be", "not in hpc_fns: hpc_fns[fn_name] = OrderedDict() hpc_fns[fn_name][runtime_name] = hpc_fn while", "hpc function is called, it will be called as hpc_function(*nametuple).", "@hpc_wrapper(shape_fn=shape_fn_dntd, namedtuple_data=True, include_args=[0,1,2,3], include_kwargs=['data', 'gamma', 'v_min', 'v_max'], is_cls_method=False) def dist_nstep_td_error(", "from collections import OrderedDict from functools import wraps import ding", "= OrderedDict() hpc_fns[fn_name][runtime_name] = hpc_fn while len(hpc_fns[fn_name]) > per_fn_limit: hpc_fns[fn_name].popitem(last=False)", "which means `data`, `gamma`, `v_min` and `v_max` will be set", "simple method. Q&A: - Q: Is `include_args` and `include_kwargs` need", "We will get rid of `self` in args. Besides, we", "if k in include_kwargs: if k == 'lambda_': k =", "'v_min', 'v_max'], which means `data`, `gamma`, `v_min` and `v_max` will", "for its hpc type and return the function implemented by", "(data, gamma, v_min, v_max). - Q: What is `hpc_fns`? -", "code as a sample to introduce `hpc_wrapper`: ``` @hpc_wrapper(shape_fn=shape_fn_dntd, namedtuple_data=True,", "hpc function. - include_kwargs (:obj:`list`): a list of key of", "['hpc_rll.rl_utils.td', 'QNStepTDRescale'], 'ScatterConnection': ['hpc_rll.torch_utils.network.scatter_connection', 'ScatterConnection'], 'td_lambda_error': ['hpc_rll.rl_utils.td', 'TDLambda'], 'upgo_loss': ['hpc_rll.rl_utils.upgo',", "print(hpc_fns) return hpc_fn def hpc_wrapper(shape_fn=None, namedtuple_data=False, include_args=[], include_kwargs=[], is_cls_method=False): def", "'dist_nstep_td_error': ['hpc_rll.rl_utils.td', 'DistNStepTD'], 'LSTM': ['hpc_rll.torch_utils.network.rnn', 'LSTM'], 'ppo_error': ['hpc_rll.rl_utils.ppo', 'PPO'], 'q_nstep_td_error':", "fn_name_mapping[fn_name] cls = getattr(importlib.import_module(fn_str[0]), fn_str[1]) hpc_fn = cls(*shape).cuda() if fn_name", "can deal with all type of input, such as (data,", "kwargs) if is_cls_method: fn_name = args[0].__class__.__name__ else: fn_name = fn.__name__", "args[1:] clean_args = [] for i in include_args: if i", "to be set in hpc function. As shown in the", "kwargs need to be set in hpc function. As shown", "in hpc function. - is_cls_method (:obj:`bool`): If True, it means", "nouse_kwargs = list(set(kwargs.keys()).difference(set(include_kwargs))) if len(nouse_args) > 0 or len(nouse_kwargs) >", "What is `hpc_fns`? - A: Here we show a normal", "'_'.join([fn_name] + [str(s) for s in shape]) if fn_name not", "a class. `self` will be put into args. We will", "return the shape needed by hpc function. In fact, it", "means the max length of `hpc_fns[fn_name]`. When new function comes,", "classname as its fn_name. If False, it means the function", "v_max). - Q: What is `hpc_fns`? - A: Here we", "{} for k, v in kwargs.items(): if k in include_kwargs:", "when hpc function is called, it will be called as", "'ppo_error': ['hpc_rll.rl_utils.ppo', 'PPO'], 'q_nstep_td_error': ['hpc_rll.rl_utils.td', 'QNStepTD'], 'q_nstep_td_error_with_rescale': ['hpc_rll.rl_utils.td', 'QNStepTDRescale'], 'ScatterConnection':", "deal with all type of input, such as (data, gamma,", "... ``` Parameters: - shape_fn (:obj:`function`): a function which return", "are dropped, and keys {} of kwargs are dropped.'.format( runtime_name,", "= {} per_fn_limit = 3 def register_runtime_fn(fn_name, runtime_name, shape): fn_name_mapping", "hpc_wrapper(shape_fn=None, namedtuple_data=False, include_args=[], include_kwargs=[], is_cls_method=False): def decorate(fn): @wraps(fn) def wrapper(*args,", "list of index of the args need to be set", "function. As shown in the sample, include_kwargs=['data', 'gamma', 'v_min', 'v_max'],", "['hpc_rll.rl_utils.ppo', 'PPO'], 'q_nstep_td_error': ['hpc_rll.rl_utils.td', 'QNStepTD'], 'q_nstep_td_error_with_rescale': ['hpc_rll.rl_utils.td', 'QNStepTDRescale'], 'ScatterConnection': ['hpc_rll.torch_utils.network.scatter_connection',", "include_args: if i < len(args): clean_args.append(args[i]) nouse_args = list(set(list(range(len(args)))).difference(set(include_args))) clean_kwargs", "is a method of a class. `self` will be put", "data will remain its `nametuple` type. - include_args (:obj:`list`): a", "Here we show a normal `hpc_fns`: ``` hpc_fns = {", "a list of key of the kwargs need to be", "'gae': ['hpc_rll.rl_utils.gae', 'GAE'], 'dist_nstep_td_error': ['hpc_rll.rl_utils.td', 'DistNStepTD'], 'LSTM': ['hpc_rll.torch_utils.network.rnn', 'LSTM'], 'ppo_error':", "search for its hpc type and return the function implemented", "is wrapped by it, we will search for its hpc", "return hpc_fn(*data, *clean_args[1:], **clean_kwargs) else: return hpc_fn(*clean_args, **clean_kwargs) else: return" ]
[ "the count of int(s) in passed array. def number_of_occurrences(s, xs):", "#Return the count of int(s) in passed array. def number_of_occurrences(s,", "count of int(s) in passed array. def number_of_occurrences(s, xs): return", "of int(s) in passed array. def number_of_occurrences(s, xs): return xs.count(s)" ]
[ "# https://github.com/telegramdesktop/tdesktop/blob/4bf66cb6e93f3965b40084771b595e93d0b11bcd/Telegram/SourceFiles/codegen/scheme/codegen_scheme.py#L57-L62 WHITELISTED_MISMATCHING_IDS = { # 0 represents any layer", "fullname if '.' in fullname: self.namespace, self.name = fullname.split('.', maxsplit=1)", "' ' + ' '.join([repr(arg) for arg in self.args]) else:", "'{{{}:{}}}'.format(self.name, real_type) else: return '{}:{}'.format(self.name, real_type) def __repr__(self): return str(self).replace(':date',", "'#': self.flag_indicator = True self.type = None self.is_generic = False", "the only type that can # be inferred is if", "in whitelist: assert self.id == self.infer_id(),\\ 'Invalid inferred ID for", "use (read/write) its ID # as pinpointed on issue #81.", "self.result = result self.is_function = is_function self.id = None if", "An example of such case is ipPort in # help.configSpecial", "following_types == 'functions' continue try: result = _from_line(line, is_function, layer=layer)", "' + ' '.join([repr(arg) for arg in self.args]) else: args", "'was_online')): self.type = 'date' self.generic_definition = generic_definition def type_hint(self): type", "line = line[:comment_index] line = line.strip() if not line: continue", "Special case: some types can be inferred, which makes it", "left as None (the default) self.can_be_inferred = name == 'random_id'", "Bool; 0x997275b5, # boolTrue#997275b5 = Bool; 0x3fedd339, # true#3fedd339 =", "= following_types == 'functions' continue try: result = _from_line(line, is_function,", "layer used on the specified scheme.tl file.\"\"\" layer_regex = re.compile(r'^//\\s*LAYER\\s*(\\d+)$')", "continue try: result = _from_line(line, is_function, layer=layer) if not ignore_core", "type representation by updating it as required real_type = self.type", "self.generic_definition: return '{{{}:{}}}'.format(self.name, real_type) else: return '{}:{}'.format(self.name, real_type) def __repr__(self):", "arg_type.startswith('!') # Strip the exclamation mark always to have only", "if any, of the TL object :param result: The result", "x: x.is_flag or x.can_be_inferred) def __repr__(self, ignore_id=False): if self.id is", "False self.is_flag = False self.skip_constructor_id = False self.flag_index = -1", "Currently the only type that can # be inferred is", "= generic_definition def type_hint(self): type = self.type if '.' in", "{t:Type} # [ t ] = Vector t;\" raise ValueError('Cannot", "the type is \"int\", # we can safely assume that", "re.search(r'(\\b|_)date\\b', name) or name in ('expires', 'expires_at', 'was_online')): self.type =", "'{}:{}'.format(self.name, real_type) def __repr__(self): return str(self).replace(':date', ':int').replace('?date', '?int') def _from_line(line,", "args=[TLArg(name, arg_type, brace != '') for brace, name, arg_type in", "__repr__(self, ignore_id=False): if self.id is None or ignore_id: hex_id =", "] = Vector t;\" raise ValueError('Cannot parse TLObject {}'.format(line)) args_match", "the real type representation by updating it as required real_type", "type? :param layer: The layer this TLObject belongs to. \"\"\"", "# The name may contain \"date\" in it, if this", "flag_match.group(2) # Then check if the type is a Vector<REAL_TYPE>", "ID :param args: The arguments, if any, of the TL", "assume that this should be treated as a \"date\" object.", "name is 'random_id', to which a # random ID will", "have only the name self.type = arg_type.lstrip('!') # The type", "the vector self.type = vector_match.group(1) # See use_vector_id. An example", "self.type = arg_type.lstrip('!') # The type may be a flag", "( 0xbc799737, # boolFalse#bc799737 = Bool; 0x997275b5, # boolTrue#997275b5 =", "the TL object :param is_function: Is the object a function", "'str', 'date': 'Optional[datetime]', # None date = 0 timestamp 'bytes':", "Update the type to match the one inside the vector", "the arguments properly sorted and ready to plug-in into a", "is_function, layer): \"\"\" Initializes a new TLObject, given its properties.", "(namespace.name) The namespace can be omitted. :param object_id: The hexadecimal", "default =None) \"\"\" return sorted(self.args, key=lambda x: x.is_flag or x.can_be_inferred)", "that can # be inferred is if the name is", "makes it # less annoying to type. Currently the only", "to match the one inside the vector self.type = vector_match.group(1)", "TL object :param result: The result type of the TL", "representation = representation\\ .replace(':bytes ', ':string ')\\ .replace('?bytes ', '?string", "line) if match: following_types = match.group(1) is_function = following_types ==", "be flags if arg_type == '#': self.flag_indicator = True self.type", "= line.find('//') if comment_index != -1: line = line[:comment_index] line", "= re.sub( r' \\w+:flags\\.\\d+\\?true', r'', representation ) return crc32(representation.encode('ascii')) class", "args: The arguments, if any, of the TL object :param", "the type is a Vector<REAL_TYPE> vector_match = re.match(r'[Vv]ector<([\\w\\d.]+)>', self.type) if", "self.skip_constructor_id = True # The name may contain \"date\" in", "as a \"date\" object. # Note that this is not", "if self.id is None or ignore_id: hex_id = '' else:", "TLObject {}'.format(line)) args_match = re.findall( r'({)?' r'(\\w+)' r':' r'([\\w\\d<>#.?!]+)' r'}?',", "'' return '{}{}{} = {}'.format(self.fullname, hex_id, args, self.result) def infer_id(self):", "the type to match the one inside the vector self.type", "as e: if 'vector#1cb5c415' not in str(e): raise def find_layer(file_path):", ":param fullname: The fullname of the TL object (namespace.name) The", "'.join([repr(arg) for arg in self.args]) else: args = '' return", "The type of the .tl argument :param generic_definition: Is the", "type != 'date': result = 'Optional[{}]'.format(result) return result def __str__(self):", "key=lambda x: x.is_flag or x.can_be_inferred) def __repr__(self, ignore_id=False): if self.id", "type to match the one inside the vector self.type =", "Is the object a function or a type? :param layer:", "to. \"\"\" # The name can or not have a", "a function or a type? :param layer: The layer this", "self.type.split('.')[-1][0].islower(): self.skip_constructor_id = True # The name may contain \"date\"", "Vector<REAL_TYPE> vector_match = re.match(r'[Vv]ector<([\\w\\d.]+)>', self.type) if vector_match: self.is_vector = True", "r'([\\w\\d<>#.?]+);$', # '<result.type>;' line ) if match is None: #", "updating it as required real_type = self.type if self.flag_indicator: real_type", "boolFalse#bc799737 = Bool; 0x997275b5, # boolTrue#997275b5 = Bool; 0x3fedd339, #", "is determined by a previous argument # However, we assume", "open(file_path, encoding='utf-8') as file: is_function = False for line in", "brace != '') for brace, name, arg_type in args_match] )", "r'([\\w\\d<>#.?!]+)' r'}?', line ) return TLObject( fullname=match.group(1), object_id=match.group(2), result=match.group(3), is_function=is_function,", "# boolTrue#997275b5 = Bool; 0x3fedd339, # true#3fedd339 = True; 0x1cb5c415,", "= self.infer_id() else: self.id = int(object_id, base=16) whitelist = WHITELISTED_MISMATCHING_IDS[0]", "' ').replace('>', '')\\ .replace('{', '').replace('}', '') representation = re.sub( r'", "specified scheme.tl file.\"\"\" layer_regex = re.compile(r'^//\\s*LAYER\\s*(\\d+)$') with open(file_path, encoding='utf-8') as", "we can safely assume that this should be treated as", "result def __str__(self): # Find the real type representation by", "crc32 from ..utils import snake_to_camel_case CORE_TYPES = ( 0xbc799737, #", "Find the real type representation by updating it as required", "TLObject: def __init__(self, fullname, object_id, args, result, is_function, layer): \"\"\"", "match the exact type, not the \"flagged\" one self.type =", "line ) if match is None: # Probably \"vector#1cb5c415 {t:Type}", "a given .tl file.\"\"\" with open(file_path, encoding='utf-8') as file: is_function", "pinpointed on issue #81. self.use_vector_id = self.type[0] == 'V' #", ") return crc32(representation.encode('ascii')) class TLArg: def __init__(self, name, arg_type, generic_definition):", "'date' self.generic_definition = generic_definition def type_hint(self): type = self.type if", "{}'.format(line)) args_match = re.findall( r'({)?' r'(\\w+)' r':' r'([\\w\\d<>#.?!]+)' r'}?', line", "name == 'random_id' # The type can be an indicator", "other arguments will be flags if arg_type == '#': self.flag_indicator", "line = line.strip() if not line: continue match = re.match('---(\\w+)---',", "of the TL object (namespace.name) The namespace can be omitted.", "be assigned if left as None (the default) self.can_be_inferred =", "file: is_function = False for line in file: comment_index =", "if comment_index != -1: line = line[:comment_index] line = line.strip()", "self.fullname = fullname if '.' in fullname: self.namespace, self.name =", "= fullname.split('.', maxsplit=1) else: self.namespace, self.name = None, fullname self.args", "Vector t;\" raise ValueError('Cannot parse TLObject {}'.format(line)) args_match = re.findall(", "args = '' return '{}{}{} = {}'.format(self.fullname, hex_id, args, self.result)", "the flags name; this # is determined by a previous", "= _from_line(line, is_function, layer=layer) if not ignore_core or result.id not", "'' else: hex_id = '#{:08x}'.format(self.id) if self.args: args = '", "return result def __str__(self): # Find the real type representation", ":param args: The arguments, if any, of the TL object", "if self.type.split('.')[-1][0].islower(): self.skip_constructor_id = True # The name may contain", "is None: self.id = self.infer_id() else: self.id = int(object_id, base=16)", "can # be inferred is if the name is 'random_id',", "representation by updating it as required real_type = self.type if", "the .tl argument :param arg_type: The type of the .tl", "= None, fullname self.args = args self.result = result self.is_function", "or ignore_id: hex_id = '' else: hex_id = '#{:08x}'.format(self.id) if", "None self.is_generic = False else: self.flag_indicator = False self.is_generic =", "for ' + repr(self) self.class_name = snake_to_camel_case( self.name, suffix='Request' if", "type, not the \"flagged\" one self.type = flag_match.group(2) # Then", "inferred will go last so they can default =None) \"\"\"", "flag_match = re.match(r'flags.(\\d+)\\?([\\w<>.]+)', self.type) if flag_match: self.is_flag = True self.flag_index", "self.flag_index = int(flag_match.group(1)) # Update the type to match the", "self.type = flag_match.group(2) # Then check if the type is", "is_function = following_types == 'functions' continue try: result = _from_line(line,", "self.fullname not in whitelist: assert self.id == self.infer_id(),\\ 'Invalid inferred", "to have only the name self.type = arg_type.lstrip('!') # The", "argument will always be called 'flags' flag_match = re.match(r'flags.(\\d+)\\?([\\w<>.]+)', self.type)", "== '#': self.flag_indicator = True self.type = None self.is_generic =", "'int', 'long': 'int', 'int128': 'int', 'int256': 'int', 'string': 'str', 'date':", "this is the case and the type is \"int\", #", "object :param result: The result type of the TL object", "'List[{}]'.format(result) if self.is_flag and type != 'date': result = 'Optional[{}]'.format(result)", "is not a valid Telegram object, but it's easier to", "object_id, args, result, is_function, layer): \"\"\" Initializes a new TLObject,", "a flag (flags.IDX?REAL_TYPE) # Note that 'flags' is NOT the", "r'^([\\w.]+)' # 'name' r'(?:#([0-9a-fA-F]+))?' # '#optionalcode' r'(?:\\s{?\\w+:[\\w\\d<>#.?!]+}?)*' # '{args:.0?type}' r'\\s=\\s'", "= self.type if self.flag_indicator: real_type = '#' if self.is_vector: if", "def find_layer(file_path): \"\"\"Finds the layer used on the specified scheme.tl", "if not ignore_core or result.id not in CORE_TYPES: yield result", "as file: for line in file: match = layer_regex.match(line) if", "indicator that other arguments will be flags if arg_type ==", "self.flag_index = -1 # Special case: some types can be", "it is a constructor and we use (read/write) its ID", "'self' else name # Default values self.is_vector = False self.is_flag", "else: return '{}:{}'.format(self.name, real_type) def __repr__(self): return str(self).replace(':date', ':int').replace('?date', '?int')", "those which can be inferred will go last so they", "not uppercase, then # it is a constructor and we", "real_type = 'vector<{}>'.format(real_type) if self.is_generic: real_type = '!{}'.format(real_type) if self.is_flag:", "\"date\" in it, if this is the case and the", "= list(a for a in self.sorted_args() if not (a.flag_indicator or", "Probably \"vector#1cb5c415 {t:Type} # [ t ] = Vector t;\"", "self.skip_constructor_id = False self.flag_index = -1 # Special case: some", "None: self.id = self.infer_id() else: self.id = int(object_id, base=16) whitelist", "TL object :param is_function: Is the object a function or", "\"\"\"Returns the arguments properly sorted and ready to plug-in into", "if not line: continue match = re.match('---(\\w+)---', line) if match:", "match: following_types = match.group(1) is_function = following_types == 'functions' continue", "# Probably \"vector#1cb5c415 {t:Type} # [ t ] = Vector", "'').replace('}', '') representation = re.sub( r' \\w+:flags\\.\\d+\\?true', r'', representation )", "if 'vector#1cb5c415' not in str(e): raise def find_layer(file_path): \"\"\"Finds the", "ignore_core or result.id not in CORE_TYPES: yield result except ValueError", "= ' r'([\\w\\d<>#.?]+);$', # '<result.type>;' line ) if match is", "if self.is_vector: if self.use_vector_id: real_type = 'Vector<{}>'.format(real_type) else: real_type =", "None, fullname self.args = args self.result = result self.is_function =", "{ # 0 represents any layer 0: {'ipPortSecret', 'accessPointRule', 'help.configSimple'},", "be inferred will go last so they can default =None)", "should be treated as a \"date\" object. # Note that", "is_function: Is the object a function or a type? :param", "[ t ] = Vector t;\" raise ValueError('Cannot parse TLObject", "if name == 'self' else name # Default values self.is_vector", "self.can_be_inferred = name == 'random_id' # The type can be", "= 'Optional[{}]'.format(result) return result def __str__(self): # Find the real", "arg_type == '#': self.flag_indicator = True self.type = None self.is_generic", "self.is_flag = True self.flag_index = int(flag_match.group(1)) # Update the type", "a # random ID will be assigned if left as", "= args self.result = result self.is_function = is_function self.id =", "or a.generic_definition)) def sorted_args(self): \"\"\"Returns the arguments properly sorted and", "hex_id, args, self.result) def infer_id(self): representation = self.__repr__(ignore_id=True) representation =", "'string': 'str', 'date': 'Optional[datetime]', # None date = 0 timestamp", "suffix='Request' if self.is_function else '') self.real_args = list(a for a", "= re.match('---(\\w+)---', line) if match: following_types = match.group(1) is_function =", "self.name = None, fullname self.args = args self.result = result", "type can be an indicator that other arguments will be", "not ignore_core or result.id not in CORE_TYPES: yield result except", "0x997275b5, # boolTrue#997275b5 = Bool; 0x3fedd339, # true#3fedd339 = True;", "= -1 # Special case: some types can be inferred,", "'?string ')\\ .replace('<', ' ').replace('>', '')\\ .replace('{', '').replace('}', '') representation", "= line.strip() if not line: continue match = re.match('---(\\w+)---', line)", "which can be inferred will go last so they can", "def __repr__(self, ignore_id=False): if self.id is None or ignore_id: hex_id", "representation ) return crc32(representation.encode('ascii')) class TLArg: def __init__(self, name, arg_type,", "= type.split('.')[1] result = { 'int': 'int', 'long': 'int', 'int128':", "true#3fedd339 = True; 0x1cb5c415, # vector#1cb5c415 {t:Type} # [ t", "required real_type = self.type if self.flag_indicator: real_type = '#' if", "result except ValueError as e: if 'vector#1cb5c415' not in str(e):", "= Vector t; ) # https://github.com/telegramdesktop/tdesktop/blob/4bf66cb6e93f3965b40084771b595e93d0b11bcd/Telegram/SourceFiles/codegen/scheme/codegen_scheme.py#L57-L62 WHITELISTED_MISMATCHING_IDS = { #", "= {}'.format(self.fullname, hex_id, args, self.result) def infer_id(self): representation = self.__repr__(ignore_id=True)", "If the type's first letter is not uppercase, then #", "-1: line = line[:comment_index] line = line.strip() if not line:", "the TL object (namespace.name) The namespace can be omitted. :param", "with open(file_path, encoding='utf-8') as file: is_function = False for line", "file: for line in file: match = layer_regex.match(line) if match:", "ignore_id: hex_id = '' else: hex_id = '#{:08x}'.format(self.id) if self.args:", "name; this # is determined by a previous argument #", "'name' r'(?:#([0-9a-fA-F]+))?' # '#optionalcode' r'(?:\\s{?\\w+:[\\w\\d<>#.?!]+}?)*' # '{args:.0?type}' r'\\s=\\s' # '", "or not have a namespace self.fullname = fullname if '.'", "arguments will be flags if arg_type == '#': self.flag_indicator =", "+ ' '.join([repr(arg) for arg in self.args]) else: args =", "self.is_vector = True # If the type's first letter is", "{ 'int': 'int', 'long': 'int', 'int128': 'int', 'int256': 'int', 'string':", "Vector t; ) # https://github.com/telegramdesktop/tdesktop/blob/4bf66cb6e93f3965b40084771b595e93d0b11bcd/Telegram/SourceFiles/codegen/scheme/codegen_scheme.py#L57-L62 WHITELISTED_MISMATCHING_IDS = { # 0", "type may be a flag (flags.IDX?REAL_TYPE) # Note that 'flags'", "= int(object_id, base=16) whitelist = WHITELISTED_MISMATCHING_IDS[0] |\\ WHITELISTED_MISMATCHING_IDS.get(layer, set()) if", "properly sorted and ready to plug-in into a Python's method", "self.infer_id() else: self.id = int(object_id, base=16) whitelist = WHITELISTED_MISMATCHING_IDS[0] |\\", "self.use_vector_id = self.type[0] == 'V' # Update the type to", "of the TL object :param is_function: Is the object a", "x.is_flag or x.can_be_inferred) def __repr__(self, ignore_id=False): if self.id is None", "is a constructor and we use (read/write) its ID #", "if vector_match: self.is_vector = True # If the type's first", "ID will be assigned if left as None (the default)", "sorted(self.args, key=lambda x: x.is_flag or x.can_be_inferred) def __repr__(self, ignore_id=False): if", "type. Currently the only type that can # be inferred", "Update the type to match the exact type, not the", "match.group(1) is_function = following_types == 'functions' continue try: result =", "= False else: self.flag_indicator = False self.is_generic = arg_type.startswith('!') #", "fullname: The fullname of the TL object (namespace.name) The namespace", "encoding='utf-8') as file: for line in file: match = layer_regex.match(line)", "\"\"\" return sorted(self.args, key=lambda x: x.is_flag or x.can_be_inferred) def __repr__(self,", "\\w+:flags\\.\\d+\\?true', r'', representation ) return crc32(representation.encode('ascii')) class TLArg: def __init__(self,", "(flags.IDX?REAL_TYPE) # Note that 'flags' is NOT the flags name;", "!= -1: line = line[:comment_index] line = line.strip() if not", "'random_id' # The type can be an indicator that other", "the exact type, not the \"flagged\" one self.type = flag_match.group(2)", "constructor and we use (read/write) its ID # as pinpointed", "if self.generic_definition: return '{{{}:{}}}'.format(self.name, real_type) else: return '{}:{}'.format(self.name, real_type) def", "ignore_id=False): if self.id is None or ignore_id: hex_id = ''", "def sorted_args(self): \"\"\"Returns the arguments properly sorted and ready to", "the specified scheme.tl file.\"\"\" layer_regex = re.compile(r'^//\\s*LAYER\\s*(\\d+)$') with open(file_path, encoding='utf-8')", "# [ t ] = Vector t; ) # https://github.com/telegramdesktop/tdesktop/blob/4bf66cb6e93f3965b40084771b595e93d0b11bcd/Telegram/SourceFiles/codegen/scheme/codegen_scheme.py#L57-L62", "zlib import crc32 from ..utils import snake_to_camel_case CORE_TYPES = (", "== 'functions' continue try: result = _from_line(line, is_function, layer=layer) if", "and type != 'date': result = 'Optional[{}]'.format(result) return result def", "if left as None (the default) self.can_be_inferred = name ==", "0x1cb5c415, # vector#1cb5c415 {t:Type} # [ t ] = Vector", "if the name is 'random_id', to which a # random", "go last so they can default =None) \"\"\" return sorted(self.args,", "\"flagged\" one self.type = flag_match.group(2) # Then check if the", "is the case and the type is \"int\", # we", "fullname: self.namespace, self.name = fullname.split('.', maxsplit=1) else: self.namespace, self.name =", "# be inferred is if the name is 'random_id', to", "'help.configSimple'}, 77: {'channel'}, 78: {'channel'} } class TLObject: def __init__(self,", "== 'self' else name # Default values self.is_vector = False", "valid Telegram object, but it's easier to work with if", "flags if arg_type == '#': self.flag_indicator = True self.type =", "parse TLObject {}'.format(line)) args_match = re.findall( r'({)?' r'(\\w+)' r':' r'([\\w\\d<>#.?!]+)'", "# However, we assume that the argument will always be", "..utils import snake_to_camel_case CORE_TYPES = ( 0xbc799737, # boolFalse#bc799737 =", "type to match the exact type, not the \"flagged\" one", "name can or not have a namespace self.fullname = fullname", "return crc32(representation.encode('ascii')) class TLArg: def __init__(self, name, arg_type, generic_definition): \"\"\"", "else: self.flag_indicator = False self.is_generic = arg_type.startswith('!') # Strip the", "# '<result.type>;' line ) if match is None: # Probably", "by a previous argument # However, we assume that the", "self.class_name = snake_to_camel_case( self.name, suffix='Request' if self.is_function else '') self.real_args", "not the \"flagged\" one self.type = flag_match.group(2) # Then check", "flags and those which can be inferred will go last", "= True # If the type's first letter is not", "safely assume that this should be treated as a \"date\"", "always to have only the name self.type = arg_type.lstrip('!') #", "omitted. :param object_id: The hexadecimal string representing the object ID", "inferred is if the name is 'random_id', to which a", "self.type = 'date' self.generic_definition = generic_definition def type_hint(self): type =", "'Vector<{}>'.format(real_type) else: real_type = 'vector<{}>'.format(real_type) if self.is_generic: real_type = '!{}'.format(real_type)", "if self.flag_indicator: real_type = '#' if self.is_vector: if self.use_vector_id: real_type", "string representing the object ID :param args: The arguments, if", "'Invalid inferred ID for ' + repr(self) self.class_name = snake_to_camel_case(", "from a given .tl file.\"\"\" with open(file_path, encoding='utf-8') as file:", "The name can or not have a namespace self.fullname =", "# boolFalse#bc799737 = Bool; 0x997275b5, # boolTrue#997275b5 = Bool; 0x3fedd339,", "of such case is ipPort in # help.configSpecial if self.type.split('.')[-1][0].islower():", "fullname, object_id, args, result, is_function, layer): \"\"\" Initializes a new", "= ' ' + ' '.join([repr(arg) for arg in self.args])", "self.namespace, self.name = fullname.split('.', maxsplit=1) else: self.namespace, self.name = None,", "type_hint(self): type = self.type if '.' in type: type =", "result = { 'int': 'int', 'long': 'int', 'int128': 'int', 'int256':", "= 'List[{}]'.format(result) if self.is_flag and type != 'date': result =", "self.__repr__(ignore_id=True) representation = representation\\ .replace(':bytes ', ':string ')\\ .replace('?bytes ',", "may contain \"date\" in it, if this is the case", "self.type = vector_match.group(1) # See use_vector_id. An example of such", "'expires_at', 'was_online')): self.type = 'date' self.generic_definition = generic_definition def type_hint(self):", "!= 'date': result = 'Optional[{}]'.format(result) return result def __str__(self): #", "0 represents any layer 0: {'ipPortSecret', 'accessPointRule', 'help.configSimple'}, 77: {'channel'},", "Strip the exclamation mark always to have only the name", "self.generic_definition = generic_definition def type_hint(self): type = self.type if '.'", "always be called 'flags' flag_match = re.match(r'flags.(\\d+)\\?([\\w<>.]+)', self.type) if flag_match:", "as file: is_function = False for line in file: comment_index", "return sorted(self.args, key=lambda x: x.is_flag or x.can_be_inferred) def __repr__(self, ignore_id=False):", "generic_definition: Is the argument a generic definition? (i.e. {X:Type}) \"\"\"", "] = Vector t; ) # https://github.com/telegramdesktop/tdesktop/blob/4bf66cb6e93f3965b40084771b595e93d0b11bcd/Telegram/SourceFiles/codegen/scheme/codegen_scheme.py#L57-L62 WHITELISTED_MISMATCHING_IDS = {", "self.type) if vector_match: self.is_vector = True # If the type's", "' = ' r'([\\w\\d<>#.?]+);$', # '<result.type>;' line ) if match", "True # The name may contain \"date\" in it, if", "return TLObject( fullname=match.group(1), object_id=match.group(2), result=match.group(3), is_function=is_function, layer=layer, args=[TLArg(name, arg_type, brace", "case is ipPort in # help.configSpecial if self.type.split('.')[-1][0].islower(): self.skip_constructor_id =", "https://github.com/telegramdesktop/tdesktop/blob/4bf66cb6e93f3965b40084771b595e93d0b11bcd/Telegram/SourceFiles/codegen/scheme/codegen_scheme.py#L57-L62 WHITELISTED_MISMATCHING_IDS = { # 0 represents any layer 0:", "values self.is_vector = False self.is_flag = False self.skip_constructor_id = False", "t ] = Vector t;\" raise ValueError('Cannot parse TLObject {}'.format(line))", "some types can be inferred, which makes it # less", "ValueError as e: if 'vector#1cb5c415' not in str(e): raise def", "'int256': 'int', 'string': 'str', 'date': 'Optional[datetime]', # None date =", "= 'Vector<{}>'.format(real_type) else: real_type = 'vector<{}>'.format(real_type) if self.is_generic: real_type =", "def __init__(self, fullname, object_id, args, result, is_function, layer): \"\"\" Initializes", "if self.fullname not in whitelist: assert self.id == self.infer_id(),\\ 'Invalid", "if flag_match: self.is_flag = True self.flag_index = int(flag_match.group(1)) # Update", "be an indicator that other arguments will be flags if", "in it, if this is the case and the type", "'accessPointRule', 'help.configSimple'}, 77: {'channel'}, 78: {'channel'} } class TLObject: def", "self.is_flag and type != 'date': result = 'Optional[{}]'.format(result) return result", "is \"int\", # we can safely assume that this should", "result = _from_line(line, is_function, layer=layer) if not ignore_core or result.id", "= match.group(1) is_function = following_types == 'functions' continue try: result", "# Strip the exclamation mark always to have only the", "The arguments, if any, of the TL object :param result:", "self.sorted_args() if not (a.flag_indicator or a.generic_definition)) def sorted_args(self): \"\"\"Returns the", "(a.flag_indicator or a.generic_definition)) def sorted_args(self): \"\"\"Returns the arguments properly sorted", "hex_id = '' else: hex_id = '#{:08x}'.format(self.id) if self.args: args", "# Special case: some types can be inferred, which makes", "raise ValueError('Cannot parse TLObject {}'.format(line)) args_match = re.findall( r'({)?' r'(\\w+)'", "set()) if self.fullname not in whitelist: assert self.id == self.infer_id(),\\", "self.type == 'int' and ( re.search(r'(\\b|_)date\\b', name) or name in", "= int(flag_match.group(1)) # Update the type to match the exact", "object. # Note that this is not a valid Telegram", "'#{:08x}'.format(self.id) if self.args: args = ' ' + ' '.join([repr(arg)", "= True; 0x1cb5c415, # vector#1cb5c415 {t:Type} # [ t ]", "x.can_be_inferred) def __repr__(self, ignore_id=False): if self.id is None or ignore_id:", "str(e): raise def find_layer(file_path): \"\"\"Finds the layer used on the", "re.match(r'flags.(\\d+)\\?([\\w<>.]+)', self.type) if flag_match: self.is_flag = True self.flag_index = int(flag_match.group(1))", "vector_match = re.match(r'[Vv]ector<([\\w\\d.]+)>', self.type) if vector_match: self.is_vector = True #", "TLObject, given its properties. :param fullname: The fullname of the", "such case is ipPort in # help.configSpecial if self.type.split('.')[-1][0].islower(): self.skip_constructor_id", "method yields TLObjects from a given .tl file.\"\"\" with open(file_path,", "The layer this TLObject belongs to. \"\"\" # The name", "result self.is_function = is_function self.id = None if object_id is", "'{args:.0?type}' r'\\s=\\s' # ' = ' r'([\\w\\d<>#.?]+);$', # '<result.type>;' line", "the name self.type = arg_type.lstrip('!') # The type may be", "CORE_TYPES = ( 0xbc799737, # boolFalse#bc799737 = Bool; 0x997275b5, #", "[ t ] = Vector t; ) # https://github.com/telegramdesktop/tdesktop/blob/4bf66cb6e93f3965b40084771b595e93d0b11bcd/Telegram/SourceFiles/codegen/scheme/codegen_scheme.py#L57-L62 WHITELISTED_MISMATCHING_IDS", ":param layer: The layer this TLObject belongs to. \"\"\" #", "a namespace self.fullname = fullname if '.' in fullname: self.namespace,", "arg in self.args]) else: args = '' return '{}{}{} =", "def __str__(self): # Find the real type representation by updating", "77: {'channel'}, 78: {'channel'} } class TLObject: def __init__(self, fullname,", "( re.search(r'(\\b|_)date\\b', name) or name in ('expires', 'expires_at', 'was_online')): self.type", "which a # random ID will be assigned if left", "{t:Type} # [ t ] = Vector t; ) #", "from zlib import crc32 from ..utils import snake_to_camel_case CORE_TYPES =", "'flags.{}?{}'.format(self.flag_index, real_type) if self.generic_definition: return '{{{}:{}}}'.format(self.name, real_type) else: return '{}:{}'.format(self.name,", "they can default =None) \"\"\" return sorted(self.args, key=lambda x: x.is_flag", "vector_match.group(1) # See use_vector_id. An example of such case is", "be inferred is if the name is 'random_id', to which", "is ipPort in # help.configSpecial if self.type.split('.')[-1][0].islower(): self.skip_constructor_id = True", "be treated as a \"date\" object. # Note that this", "representing the object ID :param args: The arguments, if any,", "the exclamation mark always to have only the name self.type", "in type: type = type.split('.')[1] result = { 'int': 'int',", "_from_line(line, is_function, layer): match = re.match( r'^([\\w.]+)' # 'name' r'(?:#([0-9a-fA-F]+))?'", "raise def find_layer(file_path): \"\"\"Finds the layer used on the specified", "None or ignore_id: hex_id = '' else: hex_id = '#{:08x}'.format(self.id)", "= '!{}'.format(real_type) if self.is_flag: real_type = 'flags.{}?{}'.format(self.flag_index, real_type) if self.generic_definition:", "from ..utils import snake_to_camel_case CORE_TYPES = ( 0xbc799737, # boolFalse#bc799737", "flag_match: self.is_flag = True self.flag_index = int(flag_match.group(1)) # Update the", "None: # Probably \"vector#1cb5c415 {t:Type} # [ t ] =", "except ValueError as e: if 'vector#1cb5c415' not in str(e): raise", "is if the name is 'random_id', to which a #", "used on the specified scheme.tl file.\"\"\" layer_regex = re.compile(r'^//\\s*LAYER\\s*(\\d+)$') with", "ID for ' + repr(self) self.class_name = snake_to_camel_case( self.name, suffix='Request'", "# we can safely assume that this should be treated", "for line in file: comment_index = line.find('//') if comment_index !=", "not have a namespace self.fullname = fullname if '.' in", "'vector<{}>'.format(real_type) if self.is_generic: real_type = '!{}'.format(real_type) if self.is_flag: real_type =", "comment_index != -1: line = line[:comment_index] line = line.strip() if", "real_type = 'Vector<{}>'.format(real_type) else: real_type = 'vector<{}>'.format(real_type) if self.is_generic: real_type", "r'(?:#([0-9a-fA-F]+))?' # '#optionalcode' r'(?:\\s{?\\w+:[\\w\\d<>#.?!]+}?)*' # '{args:.0?type}' r'\\s=\\s' # ' =", "# The name can or not have a namespace self.fullname", "\"\"\" # The name can or not have a namespace", "== 'int' and ( re.search(r'(\\b|_)date\\b', name) or name in ('expires',", "and those which can be inferred will go last so", "import snake_to_camel_case CORE_TYPES = ( 0xbc799737, # boolFalse#bc799737 = Bool;", "Initializes a new TLObject, given its properties. :param fullname: The", "can be omitted. :param object_id: The hexadecimal string representing the", "name self.type = arg_type.lstrip('!') # The type may be a", "vector_match: self.is_vector = True # If the type's first letter", "file.\"\"\" layer_regex = re.compile(r'^//\\s*LAYER\\s*(\\d+)$') with open(file_path, encoding='utf-8') as file: for", "Then check if the type is a Vector<REAL_TYPE> vector_match =", "= name == 'random_id' # The type can be an", "match = re.match( r'^([\\w.]+)' # 'name' r'(?:#([0-9a-fA-F]+))?' # '#optionalcode' r'(?:\\s{?\\w+:[\\w\\d<>#.?!]+}?)*'", "snake_to_camel_case CORE_TYPES = ( 0xbc799737, # boolFalse#bc799737 = Bool; 0x997275b5,", "= False self.skip_constructor_id = False self.flag_index = -1 # Special", "else: real_type = 'vector<{}>'.format(real_type) if self.is_generic: real_type = '!{}'.format(real_type) if", "' + repr(self) self.class_name = snake_to_camel_case( self.name, suffix='Request' if self.is_function", "in self.sorted_args() if not (a.flag_indicator or a.generic_definition)) def sorted_args(self): \"\"\"Returns", "type's first letter is not uppercase, then # it is", "= False for line in file: comment_index = line.find('//') if", "in file: comment_index = line.find('//') if comment_index != -1: line", "issue #81. self.use_vector_id = self.type[0] == 'V' # Update the", "'int', 'int256': 'int', 'string': 'str', 'date': 'Optional[datetime]', # None date", "may be a flag (flags.IDX?REAL_TYPE) # Note that 'flags' is", "a new .tl argument :param name: The name of the", "generic_definition): \"\"\" Initializes a new .tl argument :param name: The", "r'\\s=\\s' # ' = ' r'([\\w\\d<>#.?]+);$', # '<result.type>;' line )", "repr(self) self.class_name = snake_to_camel_case( self.name, suffix='Request' if self.is_function else '')", "arg_type, generic_definition): \"\"\" Initializes a new .tl argument :param name:", "arguments properly sorted and ready to plug-in into a Python's", "called 'flags' flag_match = re.match(r'flags.(\\d+)\\?([\\w<>.]+)', self.type) if flag_match: self.is_flag =", "'long': 'int', 'int128': 'int', 'int256': 'int', 'string': 'str', 'date': 'Optional[datetime]',", "self.name = fullname.split('.', maxsplit=1) else: self.namespace, self.name = None, fullname", "object, but it's easier to work with if self.type ==", "if self.is_vector: result = 'List[{}]'.format(result) if self.is_flag and type !=", "if self.is_generic: real_type = '!{}'.format(real_type) if self.is_flag: real_type = 'flags.{}?{}'.format(self.flag_index,", "'<result.type>;' line ) if match is None: # Probably \"vector#1cb5c415", "\"\"\" self.name = 'is_self' if name == 'self' else name", "# '#optionalcode' r'(?:\\s{?\\w+:[\\w\\d<>#.?!]+}?)*' # '{args:.0?type}' r'\\s=\\s' # ' = '", "representation = self.__repr__(ignore_id=True) representation = representation\\ .replace(':bytes ', ':string ')\\", "will be assigned if left as None (the default) self.can_be_inferred", "Python's method header (i.e., flags and those which can be", "ID # as pinpointed on issue #81. self.use_vector_id = self.type[0]", "__init__(self, fullname, object_id, args, result, is_function, layer): \"\"\" Initializes a", "# 'name' r'(?:#([0-9a-fA-F]+))?' # '#optionalcode' r'(?:\\s{?\\w+:[\\w\\d<>#.?!]+}?)*' # '{args:.0?type}' r'\\s=\\s' #", "')\\ .replace('?bytes ', '?string ')\\ .replace('<', ' ').replace('>', '')\\ .replace('{',", "args_match] ) def parse_tl(file_path, layer, ignore_core=False): \"\"\"This method yields TLObjects", ".replace('{', '').replace('}', '') representation = re.sub( r' \\w+:flags\\.\\d+\\?true', r'', representation", "have a namespace self.fullname = fullname if '.' in fullname:", "a in self.sorted_args() if not (a.flag_indicator or a.generic_definition)) def sorted_args(self):", "= False self.flag_index = -1 # Special case: some types", "# 0 represents any layer 0: {'ipPortSecret', 'accessPointRule', 'help.configSimple'}, 77:", "as None (the default) self.can_be_inferred = name == 'random_id' #", "= re.match(r'flags.(\\d+)\\?([\\w<>.]+)', self.type) if flag_match: self.is_flag = True self.flag_index =", "treated as a \"date\" object. # Note that this is", "by updating it as required real_type = self.type if self.flag_indicator:", "boolTrue#997275b5 = Bool; 0x3fedd339, # true#3fedd339 = True; 0x1cb5c415, #", "= result self.is_function = is_function self.id = None if object_id", "to type. Currently the only type that can # be", "NOT the flags name; this # is determined by a", "'') self.real_args = list(a for a in self.sorted_args() if not", "'!{}'.format(real_type) if self.is_flag: real_type = 'flags.{}?{}'.format(self.flag_index, real_type) if self.generic_definition: return", "line[:comment_index] line = line.strip() if not line: continue match =", "for arg in self.args]) else: args = '' return '{}{}{}", "any layer 0: {'ipPortSecret', 'accessPointRule', 'help.configSimple'}, 77: {'channel'}, 78: {'channel'}", "fullname=match.group(1), object_id=match.group(2), result=match.group(3), is_function=is_function, layer=layer, args=[TLArg(name, arg_type, brace != '')", "!= '') for brace, name, arg_type in args_match] ) def", ":param name: The name of the .tl argument :param arg_type:", "exclamation mark always to have only the name self.type =", "that the argument will always be called 'flags' flag_match =", "However, we assume that the argument will always be called", "def infer_id(self): representation = self.__repr__(ignore_id=True) representation = representation\\ .replace(':bytes ',", "layer): \"\"\" Initializes a new TLObject, given its properties. :param", "'?int') def _from_line(line, is_function, layer): match = re.match( r'^([\\w.]+)' #", "self.type) if flag_match: self.is_flag = True self.flag_index = int(flag_match.group(1)) #", "r' \\w+:flags\\.\\d+\\?true', r'', representation ) return crc32(representation.encode('ascii')) class TLArg: def", "self.args = args self.result = result self.is_function = is_function self.id", "self.name, suffix='Request' if self.is_function else '') self.real_args = list(a for", "re.compile(r'^//\\s*LAYER\\s*(\\d+)$') with open(file_path, encoding='utf-8') as file: for line in file:", "result type of the TL object :param is_function: Is the", "it, if this is the case and the type is", ".replace(':bytes ', ':string ')\\ .replace('?bytes ', '?string ')\\ .replace('<', '", "{'channel'} } class TLObject: def __init__(self, fullname, object_id, args, result,", "= True self.flag_index = int(flag_match.group(1)) # Update the type to", "return '{{{}:{}}}'.format(self.name, real_type) else: return '{}:{}'.format(self.name, real_type) def __repr__(self): return", "r':' r'([\\w\\d<>#.?!]+)' r'}?', line ) return TLObject( fullname=match.group(1), object_id=match.group(2), result=match.group(3),", "name may contain \"date\" in it, if this is the", "TLObject( fullname=match.group(1), object_id=match.group(2), result=match.group(3), is_function=is_function, layer=layer, args=[TLArg(name, arg_type, brace !=", "which makes it # less annoying to type. Currently the", "re.match( r'^([\\w.]+)' # 'name' r'(?:#([0-9a-fA-F]+))?' # '#optionalcode' r'(?:\\s{?\\w+:[\\w\\d<>#.?!]+}?)*' # '{args:.0?type}'", "The type may be a flag (flags.IDX?REAL_TYPE) # Note that", "True; 0x1cb5c415, # vector#1cb5c415 {t:Type} # [ t ] =", "t; ) # https://github.com/telegramdesktop/tdesktop/blob/4bf66cb6e93f3965b40084771b595e93d0b11bcd/Telegram/SourceFiles/codegen/scheme/codegen_scheme.py#L57-L62 WHITELISTED_MISMATCHING_IDS = { # 0 represents", "TL object (namespace.name) The namespace can be omitted. :param object_id:", ":param arg_type: The type of the .tl argument :param generic_definition:", "on issue #81. self.use_vector_id = self.type[0] == 'V' # Update", "'flags' is NOT the flags name; this # is determined", "type.split('.')[1] result = { 'int': 'int', 'long': 'int', 'int128': 'int',", "'int', 'string': 'str', 'date': 'Optional[datetime]', # None date = 0", "hex_id = '#{:08x}'.format(self.id) if self.args: args = ' ' +", "be a flag (flags.IDX?REAL_TYPE) # Note that 'flags' is NOT", "__str__(self): # Find the real type representation by updating it", "type that can # be inferred is if the name", "is_function, layer=layer) if not ignore_core or result.id not in CORE_TYPES:", "class TLArg: def __init__(self, name, arg_type, generic_definition): \"\"\" Initializes a", "maxsplit=1) else: self.namespace, self.name = None, fullname self.args = args", "'')\\ .replace('{', '').replace('}', '') representation = re.sub( r' \\w+:flags\\.\\d+\\?true', r'',", "assume that the argument will always be called 'flags' flag_match", "layer=layer) if not ignore_core or result.id not in CORE_TYPES: yield", "the one inside the vector self.type = vector_match.group(1) # See", "if self.is_function else '') self.real_args = list(a for a in", "= fullname if '.' in fullname: self.namespace, self.name = fullname.split('.',", "r'', representation ) return crc32(representation.encode('ascii')) class TLArg: def __init__(self, name,", ":param result: The result type of the TL object :param", "self.id == self.infer_id(),\\ 'Invalid inferred ID for ' + repr(self)", "TLArg: def __init__(self, name, arg_type, generic_definition): \"\"\" Initializes a new", "}.get(type, \"Type{}\".format(type)) if self.is_vector: result = 'List[{}]'.format(result) if self.is_flag and", "line.find('//') if comment_index != -1: line = line[:comment_index] line =", "self.result) def infer_id(self): representation = self.__repr__(ignore_id=True) representation = representation\\ .replace(':bytes", "args, result, is_function, layer): \"\"\" Initializes a new TLObject, given", "for a in self.sorted_args() if not (a.flag_indicator or a.generic_definition)) def", "is_function self.id = None if object_id is None: self.id =", "is None or ignore_id: hex_id = '' else: hex_id =", "e: if 'vector#1cb5c415' not in str(e): raise def find_layer(file_path): \"\"\"Finds", "given its properties. :param fullname: The fullname of the TL", "self.is_generic: real_type = '!{}'.format(real_type) if self.is_flag: real_type = 'flags.{}?{}'.format(self.flag_index, real_type)", "if match: following_types = match.group(1) is_function = following_types == 'functions'", "= 'flags.{}?{}'.format(self.flag_index, real_type) if self.generic_definition: return '{{{}:{}}}'.format(self.name, real_type) else: return", "yield result except ValueError as e: if 'vector#1cb5c415' not in", "vector self.type = vector_match.group(1) # See use_vector_id. An example of", "True self.flag_index = int(flag_match.group(1)) # Update the type to match", "whitelist = WHITELISTED_MISMATCHING_IDS[0] |\\ WHITELISTED_MISMATCHING_IDS.get(layer, set()) if self.fullname not in", "inferred ID for ' + repr(self) self.class_name = snake_to_camel_case( self.name,", "can safely assume that this should be treated as a", "layer_regex = re.compile(r'^//\\s*LAYER\\s*(\\d+)$') with open(file_path, encoding='utf-8') as file: for line", "if object_id is None: self.id = self.infer_id() else: self.id =", "= ( 0xbc799737, # boolFalse#bc799737 = Bool; 0x997275b5, # boolTrue#997275b5", "last so they can default =None) \"\"\" return sorted(self.args, key=lambda", "real_type = self.type if self.flag_indicator: real_type = '#' if self.is_vector:", "encoding='utf-8') as file: is_function = False for line in file:", "of the TL object :param result: The result type of", "self.args]) else: args = '' return '{}{}{} = {}'.format(self.fullname, hex_id,", "self.id is None or ignore_id: hex_id = '' else: hex_id", "header (i.e., flags and those which can be inferred will", "definition? (i.e. {X:Type}) \"\"\" self.name = 'is_self' if name ==", "brace, name, arg_type in args_match] ) def parse_tl(file_path, layer, ignore_core=False):", "parse_tl(file_path, layer, ignore_core=False): \"\"\"This method yields TLObjects from a given", "return '{}:{}'.format(self.name, real_type) def __repr__(self): return str(self).replace(':date', ':int').replace('?date', '?int') def", "# less annoying to type. Currently the only type that", ") return TLObject( fullname=match.group(1), object_id=match.group(2), result=match.group(3), is_function=is_function, layer=layer, args=[TLArg(name, arg_type,", "file.\"\"\" with open(file_path, encoding='utf-8') as file: is_function = False for", "== 'V' # Update the type to match the one", ".replace('?bytes ', '?string ')\\ .replace('<', ' ').replace('>', '')\\ .replace('{', '').replace('}',", "None date = 0 timestamp 'bytes': 'bytes', 'true': 'bool', }.get(type,", "will always be called 'flags' flag_match = re.match(r'flags.(\\d+)\\?([\\w<>.]+)', self.type) if", "name, arg_type in args_match] ) def parse_tl(file_path, layer, ignore_core=False): \"\"\"This", "# random ID will be assigned if left as None", "+ repr(self) self.class_name = snake_to_camel_case( self.name, suffix='Request' if self.is_function else", "{X:Type}) \"\"\" self.name = 'is_self' if name == 'self' else", "inside the vector self.type = vector_match.group(1) # See use_vector_id. An", "can be inferred will go last so they can default", "'') representation = re.sub( r' \\w+:flags\\.\\d+\\?true', r'', representation ) return", "= self.type if '.' in type: type = type.split('.')[1] result", "date = 0 timestamp 'bytes': 'bytes', 'true': 'bool', }.get(type, \"Type{}\".format(type))", "result=match.group(3), is_function=is_function, layer=layer, args=[TLArg(name, arg_type, brace != '') for brace,", "continue match = re.match('---(\\w+)---', line) if match: following_types = match.group(1)", "\"date\" object. # Note that this is not a valid", "real type representation by updating it as required real_type =", "(the default) self.can_be_inferred = name == 'random_id' # The type", "re from zlib import crc32 from ..utils import snake_to_camel_case CORE_TYPES", "{'channel'}, 78: {'channel'} } class TLObject: def __init__(self, fullname, object_id,", "re.findall( r'({)?' r'(\\w+)' r':' r'([\\w\\d<>#.?!]+)' r'}?', line ) return TLObject(", "argument a generic definition? (i.e. {X:Type}) \"\"\" self.name = 'is_self'", "method header (i.e., flags and those which can be inferred", "# it is a constructor and we use (read/write) its", "# Note that this is not a valid Telegram object,", "'vector#1cb5c415' not in str(e): raise def find_layer(file_path): \"\"\"Finds the layer", "else: self.namespace, self.name = None, fullname self.args = args self.result", "to which a # random ID will be assigned if", "')\\ .replace('<', ' ').replace('>', '')\\ .replace('{', '').replace('}', '') representation =", "any, of the TL object :param result: The result type", "if match is None: # Probably \"vector#1cb5c415 {t:Type} # [", "=None) \"\"\" return sorted(self.args, key=lambda x: x.is_flag or x.can_be_inferred) def", "type of the .tl argument :param generic_definition: Is the argument", "for brace, name, arg_type in args_match] ) def parse_tl(file_path, layer,", "argument :param name: The name of the .tl argument :param", "if self.is_flag: real_type = 'flags.{}?{}'.format(self.flag_index, real_type) if self.generic_definition: return '{{{}:{}}}'.format(self.name,", "if self.type == 'int' and ( re.search(r'(\\b|_)date\\b', name) or name", "real_type = '!{}'.format(real_type) if self.is_flag: real_type = 'flags.{}?{}'.format(self.flag_index, real_type) if", "= True # The name may contain \"date\" in it,", "if self.is_flag and type != 'date': result = 'Optional[{}]'.format(result) return", "then # it is a constructor and we use (read/write)", "self.args: args = ' ' + ' '.join([repr(arg) for arg", "ignore_core=False): \"\"\"This method yields TLObjects from a given .tl file.\"\"\"", "fullname of the TL object (namespace.name) The namespace can be", "in fullname: self.namespace, self.name = fullname.split('.', maxsplit=1) else: self.namespace, self.name", "\"\"\" Initializes a new .tl argument :param name: The name", "the .tl argument :param generic_definition: Is the argument a generic", "of the .tl argument :param generic_definition: Is the argument a", "previous argument # However, we assume that the argument will", "object ID :param args: The arguments, if any, of the", "with if self.type == 'int' and ( re.search(r'(\\b|_)date\\b', name) or", "new TLObject, given its properties. :param fullname: The fullname of", "The name of the .tl argument :param arg_type: The type", "flags name; this # is determined by a previous argument", "type is a Vector<REAL_TYPE> vector_match = re.match(r'[Vv]ector<([\\w\\d.]+)>', self.type) if vector_match:", "result = 'Optional[{}]'.format(result) return result def __str__(self): # Find the", "# Find the real type representation by updating it as", "self.is_generic = False else: self.flag_indicator = False self.is_generic = arg_type.startswith('!')", "self.type = None self.is_generic = False else: self.flag_indicator = False", "= Bool; 0x997275b5, # boolTrue#997275b5 = Bool; 0x3fedd339, # true#3fedd339", "'date': 'Optional[datetime]', # None date = 0 timestamp 'bytes': 'bytes',", "object a function or a type? :param layer: The layer", "or name in ('expires', 'expires_at', 'was_online')): self.type = 'date' self.generic_definition", "if '.' in fullname: self.namespace, self.name = fullname.split('.', maxsplit=1) else:", "False self.skip_constructor_id = False self.flag_index = -1 # Special case:", "= None self.is_generic = False else: self.flag_indicator = False self.is_generic", "arg_type: The type of the .tl argument :param generic_definition: Is", "re.sub( r' \\w+:flags\\.\\d+\\?true', r'', representation ) return crc32(representation.encode('ascii')) class TLArg:", "can be an indicator that other arguments will be flags", "name of the .tl argument :param arg_type: The type of", "an indicator that other arguments will be flags if arg_type", "int(object_id, base=16) whitelist = WHITELISTED_MISMATCHING_IDS[0] |\\ WHITELISTED_MISMATCHING_IDS.get(layer, set()) if self.fullname", "and ready to plug-in into a Python's method header (i.e.,", "to plug-in into a Python's method header (i.e., flags and", "will be flags if arg_type == '#': self.flag_indicator = True", "arg_type.lstrip('!') # The type may be a flag (flags.IDX?REAL_TYPE) #", "False self.flag_index = -1 # Special case: some types can", "ready to plug-in into a Python's method header (i.e., flags", "and the type is \"int\", # we can safely assume", "self.flag_indicator = True self.type = None self.is_generic = False else:", "None (the default) self.can_be_inferred = name == 'random_id' # The", "if arg_type == '#': self.flag_indicator = True self.type = None", "representation\\ .replace(':bytes ', ':string ')\\ .replace('?bytes ', '?string ')\\ .replace('<',", "= True self.type = None self.is_generic = False else: self.flag_indicator", "= vector_match.group(1) # See use_vector_id. An example of such case", "self.is_function else '') self.real_args = list(a for a in self.sorted_args()", ") # https://github.com/telegramdesktop/tdesktop/blob/4bf66cb6e93f3965b40084771b595e93d0b11bcd/Telegram/SourceFiles/codegen/scheme/codegen_scheme.py#L57-L62 WHITELISTED_MISMATCHING_IDS = { # 0 represents any", "def parse_tl(file_path, layer, ignore_core=False): \"\"\"This method yields TLObjects from a", "so they can default =None) \"\"\" return sorted(self.args, key=lambda x:", "use_vector_id. An example of such case is ipPort in #", "result.id not in CORE_TYPES: yield result except ValueError as e:", "The type can be an indicator that other arguments will", "else: hex_id = '#{:08x}'.format(self.id) if self.args: args = ' '", "= '' return '{}{}{} = {}'.format(self.fullname, hex_id, args, self.result) def", "new .tl argument :param name: The name of the .tl", "self.type if self.flag_indicator: real_type = '#' if self.is_vector: if self.use_vector_id:", ".tl argument :param generic_definition: Is the argument a generic definition?", "the type's first letter is not uppercase, then # it", "False else: self.flag_indicator = False self.is_generic = arg_type.startswith('!') # Strip", "True self.type = None self.is_generic = False else: self.flag_indicator =", "= re.match( r'^([\\w.]+)' # 'name' r'(?:#([0-9a-fA-F]+))?' # '#optionalcode' r'(?:\\s{?\\w+:[\\w\\d<>#.?!]+}?)*' #", "type = type.split('.')[1] result = { 'int': 'int', 'long': 'int',", "= arg_type.lstrip('!') # The type may be a flag (flags.IDX?REAL_TYPE)", "on the specified scheme.tl file.\"\"\" layer_regex = re.compile(r'^//\\s*LAYER\\s*(\\d+)$') with open(file_path,", "'.' in fullname: self.namespace, self.name = fullname.split('.', maxsplit=1) else: self.namespace,", "self.is_vector: if self.use_vector_id: real_type = 'Vector<{}>'.format(real_type) else: real_type = 'vector<{}>'.format(real_type)", "to work with if self.type == 'int' and ( re.search(r'(\\b|_)date\\b',", "re.match(r'[Vv]ector<([\\w\\d.]+)>', self.type) if vector_match: self.is_vector = True # If the", "and ( re.search(r'(\\b|_)date\\b', name) or name in ('expires', 'expires_at', 'was_online')):", "self.use_vector_id: real_type = 'Vector<{}>'.format(real_type) else: real_type = 'vector<{}>'.format(real_type) if self.is_generic:", "= is_function self.id = None if object_id is None: self.id", "layer: The layer this TLObject belongs to. \"\"\" # The", "types can be inferred, which makes it # less annoying", "'true': 'bool', }.get(type, \"Type{}\".format(type)) if self.is_vector: result = 'List[{}]'.format(result) if", "real_type) if self.generic_definition: return '{{{}:{}}}'.format(self.name, real_type) else: return '{}:{}'.format(self.name, real_type)", "= snake_to_camel_case( self.name, suffix='Request' if self.is_function else '') self.real_args =", "plug-in into a Python's method header (i.e., flags and those", "self.is_generic = arg_type.startswith('!') # Strip the exclamation mark always to", "= self.type[0] == 'V' # Update the type to match", "given .tl file.\"\"\" with open(file_path, encoding='utf-8') as file: is_function =", "file: comment_index = line.find('//') if comment_index != -1: line =", "'functions' continue try: result = _from_line(line, is_function, layer=layer) if not", "\"\"\"This method yields TLObjects from a given .tl file.\"\"\" with", "# The type can be an indicator that other arguments", "TLObjects from a given .tl file.\"\"\" with open(file_path, encoding='utf-8') as", "r'({)?' r'(\\w+)' r':' r'([\\w\\d<>#.?!]+)' r'}?', line ) return TLObject( fullname=match.group(1),", "None if object_id is None: self.id = self.infer_id() else: self.id", "line: continue match = re.match('---(\\w+)---', line) if match: following_types =", "self.name = 'is_self' if name == 'self' else name #", "namespace self.fullname = fullname if '.' in fullname: self.namespace, self.name", "that this should be treated as a \"date\" object. #", "args, self.result) def infer_id(self): representation = self.__repr__(ignore_id=True) representation = representation\\", "':string ')\\ .replace('?bytes ', '?string ')\\ .replace('<', ' ').replace('>', '')\\", "first letter is not uppercase, then # it is a", "real_type = 'flags.{}?{}'.format(self.flag_index, real_type) if self.generic_definition: return '{{{}:{}}}'.format(self.name, real_type) else:", "= Vector t;\" raise ValueError('Cannot parse TLObject {}'.format(line)) args_match =", "comment_index = line.find('//') if comment_index != -1: line = line[:comment_index]", "# Default values self.is_vector = False self.is_flag = False self.skip_constructor_id", "contain \"date\" in it, if this is the case and", "_from_line(line, is_function, layer=layer) if not ignore_core or result.id not in", "it's easier to work with if self.type == 'int' and", "return str(self).replace(':date', ':int').replace('?date', '?int') def _from_line(line, is_function, layer): match =", "'date': result = 'Optional[{}]'.format(result) return result def __str__(self): # Find", "layer=layer, args=[TLArg(name, arg_type, brace != '') for brace, name, arg_type", "as required real_type = self.type if self.flag_indicator: real_type = '#'", "= False self.is_flag = False self.skip_constructor_id = False self.flag_index =", "following_types = match.group(1) is_function = following_types == 'functions' continue try:", "int(flag_match.group(1)) # Update the type to match the exact type,", "is not uppercase, then # it is a constructor and", "result = 'List[{}]'.format(result) if self.is_flag and type != 'date': result", "= False self.is_generic = arg_type.startswith('!') # Strip the exclamation mark", "flag (flags.IDX?REAL_TYPE) # Note that 'flags' is NOT the flags", "but it's easier to work with if self.type == 'int'", "import crc32 from ..utils import snake_to_camel_case CORE_TYPES = ( 0xbc799737,", "work with if self.type == 'int' and ( re.search(r'(\\b|_)date\\b', name)", "be inferred, which makes it # less annoying to type.", "namespace can be omitted. :param object_id: The hexadecimal string representing", "only the name self.type = arg_type.lstrip('!') # The type may", "# as pinpointed on issue #81. self.use_vector_id = self.type[0] ==", "be called 'flags' flag_match = re.match(r'flags.(\\d+)\\?([\\w<>.]+)', self.type) if flag_match: self.is_flag", "78: {'channel'} } class TLObject: def __init__(self, fullname, object_id, args,", "a generic definition? (i.e. {X:Type}) \"\"\" self.name = 'is_self' if", "line ) return TLObject( fullname=match.group(1), object_id=match.group(2), result=match.group(3), is_function=is_function, layer=layer, args=[TLArg(name,", ".tl file.\"\"\" with open(file_path, encoding='utf-8') as file: is_function = False", "# Then check if the type is a Vector<REAL_TYPE> vector_match", "real_type) else: return '{}:{}'.format(self.name, real_type) def __repr__(self): return str(self).replace(':date', ':int').replace('?date',", "this is not a valid Telegram object, but it's easier", "= 'is_self' if name == 'self' else name # Default", "name, arg_type, generic_definition): \"\"\" Initializes a new .tl argument :param", "match the one inside the vector self.type = vector_match.group(1) #", "help.configSpecial if self.type.split('.')[-1][0].islower(): self.skip_constructor_id = True # The name may", "The namespace can be omitted. :param object_id: The hexadecimal string", "'#' if self.is_vector: if self.use_vector_id: real_type = 'Vector<{}>'.format(real_type) else: real_type", "try: result = _from_line(line, is_function, layer=layer) if not ignore_core or", "find_layer(file_path): \"\"\"Finds the layer used on the specified scheme.tl file.\"\"\"", "its properties. :param fullname: The fullname of the TL object", "be omitted. :param object_id: The hexadecimal string representing the object", "WHITELISTED_MISMATCHING_IDS[0] |\\ WHITELISTED_MISMATCHING_IDS.get(layer, set()) if self.fullname not in whitelist: assert", "WHITELISTED_MISMATCHING_IDS = { # 0 represents any layer 0: {'ipPortSecret',", "# The type may be a flag (flags.IDX?REAL_TYPE) # Note", "# help.configSpecial if self.type.split('.')[-1][0].islower(): self.skip_constructor_id = True # The name", "result: The result type of the TL object :param is_function:", ":param generic_definition: Is the argument a generic definition? (i.e. {X:Type})", "argument # However, we assume that the argument will always", "argument :param arg_type: The type of the .tl argument :param", "open(file_path, encoding='utf-8') as file: for line in file: match =", "# Update the type to match the exact type, not", "r'(?:\\s{?\\w+:[\\w\\d<>#.?!]+}?)*' # '{args:.0?type}' r'\\s=\\s' # ' = ' r'([\\w\\d<>#.?]+);$', #", "# ' = ' r'([\\w\\d<>#.?]+);$', # '<result.type>;' line ) if", "re.match('---(\\w+)---', line) if match: following_types = match.group(1) is_function = following_types", "if self.args: args = ' ' + ' '.join([repr(arg) for", "Telegram object, but it's easier to work with if self.type", "self.is_flag: real_type = 'flags.{}?{}'.format(self.flag_index, real_type) if self.generic_definition: return '{{{}:{}}}'.format(self.name, real_type)", "will go last so they can default =None) \"\"\" return", "is None: # Probably \"vector#1cb5c415 {t:Type} # [ t ]", "yields TLObjects from a given .tl file.\"\"\" with open(file_path, encoding='utf-8')", "self.is_flag = False self.skip_constructor_id = False self.flag_index = -1 #", "is 'random_id', to which a # random ID will be", "name == 'self' else name # Default values self.is_vector =", "is NOT the flags name; this # is determined by", "= re.findall( r'({)?' r'(\\w+)' r':' r'([\\w\\d<>#.?!]+)' r'}?', line ) return", "'Optional[datetime]', # None date = 0 timestamp 'bytes': 'bytes', 'true':", "0xbc799737, # boolFalse#bc799737 = Bool; 0x997275b5, # boolTrue#997275b5 = Bool;", "self.flag_indicator = False self.is_generic = arg_type.startswith('!') # Strip the exclamation", "ValueError('Cannot parse TLObject {}'.format(line)) args_match = re.findall( r'({)?' r'(\\w+)' r':'", "The result type of the TL object :param is_function: Is", "object_id=match.group(2), result=match.group(3), is_function=is_function, layer=layer, args=[TLArg(name, arg_type, brace != '') for", "if '.' in type: type = type.split('.')[1] result = {", "0x3fedd339, # true#3fedd339 = True; 0x1cb5c415, # vector#1cb5c415 {t:Type} #", "assert self.id == self.infer_id(),\\ 'Invalid inferred ID for ' +", "inferred, which makes it # less annoying to type. Currently", "('expires', 'expires_at', 'was_online')): self.type = 'date' self.generic_definition = generic_definition def", "= '#' if self.is_vector: if self.use_vector_id: real_type = 'Vector<{}>'.format(real_type) else:", "list(a for a in self.sorted_args() if not (a.flag_indicator or a.generic_definition))", "else: args = '' return '{}{}{} = {}'.format(self.fullname, hex_id, args,", "import re from zlib import crc32 from ..utils import snake_to_camel_case", "or a type? :param layer: The layer this TLObject belongs", "self.real_args = list(a for a in self.sorted_args() if not (a.flag_indicator", "sorted and ready to plug-in into a Python's method header", "line.strip() if not line: continue match = re.match('---(\\w+)---', line) if", "def __init__(self, name, arg_type, generic_definition): \"\"\" Initializes a new .tl", "\"vector#1cb5c415 {t:Type} # [ t ] = Vector t;\" raise", "(i.e., flags and those which can be inferred will go", "or x.can_be_inferred) def __repr__(self, ignore_id=False): if self.id is None or", "in ('expires', 'expires_at', 'was_online')): self.type = 'date' self.generic_definition = generic_definition", "(i.e. {X:Type}) \"\"\" self.name = 'is_self' if name == 'self'", ") def parse_tl(file_path, layer, ignore_core=False): \"\"\"This method yields TLObjects from", "self.infer_id(),\\ 'Invalid inferred ID for ' + repr(self) self.class_name =", "= self.__repr__(ignore_id=True) representation = representation\\ .replace(':bytes ', ':string ')\\ .replace('?bytes", ".tl argument :param name: The name of the .tl argument", "name in ('expires', 'expires_at', 'was_online')): self.type = 'date' self.generic_definition =", "in CORE_TYPES: yield result except ValueError as e: if 'vector#1cb5c415'", "object :param is_function: Is the object a function or a", "determined by a previous argument # However, we assume that", "if the type is a Vector<REAL_TYPE> vector_match = re.match(r'[Vv]ector<([\\w\\d.]+)>', self.type)", ") if match is None: # Probably \"vector#1cb5c415 {t:Type} #", "str(self).replace(':date', ':int').replace('?date', '?int') def _from_line(line, is_function, layer): match = re.match(", "True # If the type's first letter is not uppercase,", "'int' and ( re.search(r'(\\b|_)date\\b', name) or name in ('expires', 'expires_at',", "one inside the vector self.type = vector_match.group(1) # See use_vector_id.", "self.type[0] == 'V' # Update the type to match the", "name # Default values self.is_vector = False self.is_flag = False", "self.is_vector = False self.is_flag = False self.skip_constructor_id = False self.flag_index", "one self.type = flag_match.group(2) # Then check if the type", "this should be treated as a \"date\" object. # Note", "the name is 'random_id', to which a # random ID", "as pinpointed on issue #81. self.use_vector_id = self.type[0] == 'V'", "the \"flagged\" one self.type = flag_match.group(2) # Then check if", "# Note that 'flags' is NOT the flags name; this", "a constructor and we use (read/write) its ID # as", "name: The name of the .tl argument :param arg_type: The", "if self.use_vector_id: real_type = 'Vector<{}>'.format(real_type) else: real_type = 'vector<{}>'.format(real_type) if", "function or a type? :param layer: The layer this TLObject", "a previous argument # However, we assume that the argument", "__repr__(self): return str(self).replace(':date', ':int').replace('?date', '?int') def _from_line(line, is_function, layer): match", "'bytes': 'bytes', 'true': 'bool', }.get(type, \"Type{}\".format(type)) if self.is_vector: result =", "(read/write) its ID # as pinpointed on issue #81. self.use_vector_id", "self.is_vector: result = 'List[{}]'.format(result) if self.is_flag and type != 'date':", "layer 0: {'ipPortSecret', 'accessPointRule', 'help.configSimple'}, 77: {'channel'}, 78: {'channel'} }", "= { 'int': 'int', 'long': 'int', 'int128': 'int', 'int256': 'int',", "# [ t ] = Vector t;\" raise ValueError('Cannot parse", ":param object_id: The hexadecimal string representing the object ID :param", "\"\"\" Initializes a new TLObject, given its properties. :param fullname:", "self.id = int(object_id, base=16) whitelist = WHITELISTED_MISMATCHING_IDS[0] |\\ WHITELISTED_MISMATCHING_IDS.get(layer, set())", "less annoying to type. Currently the only type that can", "real_type) def __repr__(self): return str(self).replace(':date', ':int').replace('?date', '?int') def _from_line(line, is_function,", "= '' else: hex_id = '#{:08x}'.format(self.id) if self.args: args =", "CORE_TYPES: yield result except ValueError as e: if 'vector#1cb5c415' not", "return '{}{}{} = {}'.format(self.fullname, hex_id, args, self.result) def infer_id(self): representation", "case: some types can be inferred, which makes it #", "whitelist: assert self.id == self.infer_id(),\\ 'Invalid inferred ID for '", "a.generic_definition)) def sorted_args(self): \"\"\"Returns the arguments properly sorted and ready", "example of such case is ipPort in # help.configSpecial if", "easier to work with if self.type == 'int' and (", "TLObject belongs to. \"\"\" # The name can or not", "Bool; 0x3fedd339, # true#3fedd339 = True; 0x1cb5c415, # vector#1cb5c415 {t:Type}", "' r'([\\w\\d<>#.?]+);$', # '<result.type>;' line ) if match is None:", "a \"date\" object. # Note that this is not a", "not a valid Telegram object, but it's easier to work", "= re.match(r'[Vv]ector<([\\w\\d.]+)>', self.type) if vector_match: self.is_vector = True # If", "ipPort in # help.configSpecial if self.type.split('.')[-1][0].islower(): self.skip_constructor_id = True #", "'bytes', 'true': 'bool', }.get(type, \"Type{}\".format(type)) if self.is_vector: result = 'List[{}]'.format(result)", "in self.args]) else: args = '' return '{}{}{} = {}'.format(self.fullname,", "not line: continue match = re.match('---(\\w+)---', line) if match: following_types", "is_function = False for line in file: comment_index = line.find('//')", "Is the argument a generic definition? (i.e. {X:Type}) \"\"\" self.name", "# See use_vector_id. An example of such case is ipPort", "vector#1cb5c415 {t:Type} # [ t ] = Vector t; )", "it # less annoying to type. Currently the only type", "False self.is_generic = arg_type.startswith('!') # Strip the exclamation mark always", "the case and the type is \"int\", # we can", "# vector#1cb5c415 {t:Type} # [ t ] = Vector t;", "that this is not a valid Telegram object, but it's", "the TL object :param result: The result type of the", "this # is determined by a previous argument # However,", "self.id = self.infer_id() else: self.id = int(object_id, base=16) whitelist =", "def type_hint(self): type = self.type if '.' in type: type", "with open(file_path, encoding='utf-8') as file: for line in file: match", "not in str(e): raise def find_layer(file_path): \"\"\"Finds the layer used", "= None if object_id is None: self.id = self.infer_id() else:", "self.id = None if object_id is None: self.id = self.infer_id()", "only type that can # be inferred is if the", "False for line in file: comment_index = line.find('//') if comment_index", "= 'date' self.generic_definition = generic_definition def type_hint(self): type = self.type", "= arg_type.startswith('!') # Strip the exclamation mark always to have", "the object a function or a type? :param layer: The", "arg_type in args_match] ) def parse_tl(file_path, layer, ignore_core=False): \"\"\"This method", "result, is_function, layer): \"\"\" Initializes a new TLObject, given its", "into a Python's method header (i.e., flags and those which", "annoying to type. Currently the only type that can #", "and we use (read/write) its ID # as pinpointed on", "of the .tl argument :param arg_type: The type of the", "', ':string ')\\ .replace('?bytes ', '?string ')\\ .replace('<', ' ').replace('>',", "can be inferred, which makes it # less annoying to", "'is_self' if name == 'self' else name # Default values", "type: type = type.split('.')[1] result = { 'int': 'int', 'long':", "a new TLObject, given its properties. :param fullname: The fullname", "the object ID :param args: The arguments, if any, of", "else: self.id = int(object_id, base=16) whitelist = WHITELISTED_MISMATCHING_IDS[0] |\\ WHITELISTED_MISMATCHING_IDS.get(layer,", "r'}?', line ) return TLObject( fullname=match.group(1), object_id=match.group(2), result=match.group(3), is_function=is_function, layer=layer,", "in args_match] ) def parse_tl(file_path, layer, ignore_core=False): \"\"\"This method yields", "for line in file: match = layer_regex.match(line) if match: return", "if not (a.flag_indicator or a.generic_definition)) def sorted_args(self): \"\"\"Returns the arguments", "':int').replace('?date', '?int') def _from_line(line, is_function, layer): match = re.match( r'^([\\w.]+)'", "to match the exact type, not the \"flagged\" one self.type", ".tl argument :param arg_type: The type of the .tl argument", "exact type, not the \"flagged\" one self.type = flag_match.group(2) #", "= 0 timestamp 'bytes': 'bytes', 'true': 'bool', }.get(type, \"Type{}\".format(type)) if", "'bool', }.get(type, \"Type{}\".format(type)) if self.is_vector: result = 'List[{}]'.format(result) if self.is_flag", "The fullname of the TL object (namespace.name) The namespace can", "type = self.type if '.' in type: type = type.split('.')[1]", "t;\" raise ValueError('Cannot parse TLObject {}'.format(line)) args_match = re.findall( r'({)?'", "\"Type{}\".format(type)) if self.is_vector: result = 'List[{}]'.format(result) if self.is_flag and type", "= { # 0 represents any layer 0: {'ipPortSecret', 'accessPointRule',", "args self.result = result self.is_function = is_function self.id = None", "self.is_function = is_function self.id = None if object_id is None:", "== self.infer_id(),\\ 'Invalid inferred ID for ' + repr(self) self.class_name", "object_id is None: self.id = self.infer_id() else: self.id = int(object_id,", "= '#{:08x}'.format(self.id) if self.args: args = ' ' + '", "class TLObject: def __init__(self, fullname, object_id, args, result, is_function, layer):", "= representation\\ .replace(':bytes ', ':string ')\\ .replace('?bytes ', '?string ')\\", "else name # Default values self.is_vector = False self.is_flag =", "a valid Telegram object, but it's easier to work with", "snake_to_camel_case( self.name, suffix='Request' if self.is_function else '') self.real_args = list(a", "self.namespace, self.name = None, fullname self.args = args self.result =", "# Update the type to match the one inside the", "or result.id not in CORE_TYPES: yield result except ValueError as", "Initializes a new .tl argument :param name: The name of", "layer this TLObject belongs to. \"\"\" # The name can", "# is determined by a previous argument # However, we", "The name may contain \"date\" in it, if this is", "that other arguments will be flags if arg_type == '#':", "not in CORE_TYPES: yield result except ValueError as e: if", "in str(e): raise def find_layer(file_path): \"\"\"Finds the layer used on", "we assume that the argument will always be called 'flags'", "is a Vector<REAL_TYPE> vector_match = re.match(r'[Vv]ector<([\\w\\d.]+)>', self.type) if vector_match: self.is_vector", "'{}{}{} = {}'.format(self.fullname, hex_id, args, self.result) def infer_id(self): representation =", "its ID # as pinpointed on issue #81. self.use_vector_id =", "= flag_match.group(2) # Then check if the type is a", "', '?string ')\\ .replace('<', ' ').replace('>', '')\\ .replace('{', '').replace('}', '')", "__init__(self, name, arg_type, generic_definition): \"\"\" Initializes a new .tl argument", "r'(\\w+)' r':' r'([\\w\\d<>#.?!]+)' r'}?', line ) return TLObject( fullname=match.group(1), object_id=match.group(2),", "'#optionalcode' r'(?:\\s{?\\w+:[\\w\\d<>#.?!]+}?)*' # '{args:.0?type}' r'\\s=\\s' # ' = ' r'([\\w\\d<>#.?]+);$',", "this TLObject belongs to. \"\"\" # The name can or", "'V' # Update the type to match the one inside", "' '.join([repr(arg) for arg in self.args]) else: args = ''", "Note that 'flags' is NOT the flags name; this #", "line in file: comment_index = line.find('//') if comment_index != -1:", "# true#3fedd339 = True; 0x1cb5c415, # vector#1cb5c415 {t:Type} # [", "uppercase, then # it is a constructor and we use", "def _from_line(line, is_function, layer): match = re.match( r'^([\\w.]+)' # 'name'", "-1 # Special case: some types can be inferred, which", "can default =None) \"\"\" return sorted(self.args, key=lambda x: x.is_flag or", "the layer used on the specified scheme.tl file.\"\"\" layer_regex =", "{}'.format(self.fullname, hex_id, args, self.result) def infer_id(self): representation = self.__repr__(ignore_id=True) representation", "real_type = '#' if self.is_vector: if self.use_vector_id: real_type = 'Vector<{}>'.format(real_type)", "'Optional[{}]'.format(result) return result def __str__(self): # Find the real type", "in # help.configSpecial if self.type.split('.')[-1][0].islower(): self.skip_constructor_id = True # The", "a Python's method header (i.e., flags and those which can", "case and the type is \"int\", # we can safely", "layer, ignore_core=False): \"\"\"This method yields TLObjects from a given .tl", "generic definition? (i.e. {X:Type}) \"\"\" self.name = 'is_self' if name", "args = ' ' + ' '.join([repr(arg) for arg in", "infer_id(self): representation = self.__repr__(ignore_id=True) representation = representation\\ .replace(':bytes ', ':string", "The hexadecimal string representing the object ID :param args: The", "that 'flags' is NOT the flags name; this # is", "if this is the case and the type is \"int\",", "\"int\", # we can safely assume that this should be", "is_function=is_function, layer=layer, args=[TLArg(name, arg_type, brace != '') for brace, name,", "line in file: match = layer_regex.match(line) if match: return int(match.group(1))", "object_id: The hexadecimal string representing the object ID :param args:", "'int128': 'int', 'int256': 'int', 'string': 'str', 'date': 'Optional[datetime]', # None", "crc32(representation.encode('ascii')) class TLArg: def __init__(self, name, arg_type, generic_definition): \"\"\" Initializes", "t ] = Vector t; ) # https://github.com/telegramdesktop/tdesktop/blob/4bf66cb6e93f3965b40084771b595e93d0b11bcd/Telegram/SourceFiles/codegen/scheme/codegen_scheme.py#L57-L62 WHITELISTED_MISMATCHING_IDS =", "the argument a generic definition? (i.e. {X:Type}) \"\"\" self.name =", "check if the type is a Vector<REAL_TYPE> vector_match = re.match(r'[Vv]ector<([\\w\\d.]+)>',", "the type to match the exact type, not the \"flagged\"", "representation = re.sub( r' \\w+:flags\\.\\d+\\?true', r'', representation ) return crc32(representation.encode('ascii'))", "'random_id', to which a # random ID will be assigned", "we use (read/write) its ID # as pinpointed on issue", "= re.compile(r'^//\\s*LAYER\\s*(\\d+)$') with open(file_path, encoding='utf-8') as file: for line in", "arg_type, brace != '') for brace, name, arg_type in args_match]", "0: {'ipPortSecret', 'accessPointRule', 'help.configSimple'}, 77: {'channel'}, 78: {'channel'} } class", "name) or name in ('expires', 'expires_at', 'was_online')): self.type = 'date'", "|\\ WHITELISTED_MISMATCHING_IDS.get(layer, set()) if self.fullname not in whitelist: assert self.id", "random ID will be assigned if left as None (the", "args_match = re.findall( r'({)?' r'(\\w+)' r':' r'([\\w\\d<>#.?!]+)' r'}?', line )", "not (a.flag_indicator or a.generic_definition)) def sorted_args(self): \"\"\"Returns the arguments properly", ":param is_function: Is the object a function or a type?", "fullname.split('.', maxsplit=1) else: self.namespace, self.name = None, fullname self.args =", "a type? :param layer: The layer this TLObject belongs to.", "match is None: # Probably \"vector#1cb5c415 {t:Type} # [ t", "sorted_args(self): \"\"\"Returns the arguments properly sorted and ready to plug-in", "{'ipPortSecret', 'accessPointRule', 'help.configSimple'}, 77: {'channel'}, 78: {'channel'} } class TLObject:", "'.' in type: type = type.split('.')[1] result = { 'int':", "the argument will always be called 'flags' flag_match = re.match(r'flags.(\\d+)\\?([\\w<>.]+)',", "Note that this is not a valid Telegram object, but", "layer): match = re.match( r'^([\\w.]+)' # 'name' r'(?:#([0-9a-fA-F]+))?' # '#optionalcode'", "def __repr__(self): return str(self).replace(':date', ':int').replace('?date', '?int') def _from_line(line, is_function, layer):", "fullname self.args = args self.result = result self.is_function = is_function", ".replace('<', ' ').replace('>', '')\\ .replace('{', '').replace('}', '') representation = re.sub(", "default) self.can_be_inferred = name == 'random_id' # The type can", "object (namespace.name) The namespace can be omitted. :param object_id: The", "= WHITELISTED_MISMATCHING_IDS[0] |\\ WHITELISTED_MISMATCHING_IDS.get(layer, set()) if self.fullname not in whitelist:", "mark always to have only the name self.type = arg_type.lstrip('!')", "# If the type's first letter is not uppercase, then", "type is \"int\", # we can safely assume that this", "# None date = 0 timestamp 'bytes': 'bytes', 'true': 'bool',", "# '{args:.0?type}' r'\\s=\\s' # ' = ' r'([\\w\\d<>#.?]+);$', # '<result.type>;'", "type of the TL object :param is_function: Is the object", "self.type if '.' in type: type = type.split('.')[1] result =", "base=16) whitelist = WHITELISTED_MISMATCHING_IDS[0] |\\ WHITELISTED_MISMATCHING_IDS.get(layer, set()) if self.fullname not", "assigned if left as None (the default) self.can_be_inferred = name", "match = re.match('---(\\w+)---', line) if match: following_types = match.group(1) is_function", "Default values self.is_vector = False self.is_flag = False self.skip_constructor_id =", "can or not have a namespace self.fullname = fullname if", "argument :param generic_definition: Is the argument a generic definition? (i.e.", "'int': 'int', 'long': 'int', 'int128': 'int', 'int256': 'int', 'string': 'str',", "WHITELISTED_MISMATCHING_IDS.get(layer, set()) if self.fullname not in whitelist: assert self.id ==", "timestamp 'bytes': 'bytes', 'true': 'bool', }.get(type, \"Type{}\".format(type)) if self.is_vector: result", "not in whitelist: assert self.id == self.infer_id(),\\ 'Invalid inferred ID", "'') for brace, name, arg_type in args_match] ) def parse_tl(file_path,", "= 'vector<{}>'.format(real_type) if self.is_generic: real_type = '!{}'.format(real_type) if self.is_flag: real_type", "generic_definition def type_hint(self): type = self.type if '.' in type:", "= line[:comment_index] line = line.strip() if not line: continue match", "'int', 'int128': 'int', 'int256': 'int', 'string': 'str', 'date': 'Optional[datetime]', #", "0 timestamp 'bytes': 'bytes', 'true': 'bool', }.get(type, \"Type{}\".format(type)) if self.is_vector:", "scheme.tl file.\"\"\" layer_regex = re.compile(r'^//\\s*LAYER\\s*(\\d+)$') with open(file_path, encoding='utf-8') as file:", "properties. :param fullname: The fullname of the TL object (namespace.name)", "#81. self.use_vector_id = self.type[0] == 'V' # Update the type", "= Bool; 0x3fedd339, # true#3fedd339 = True; 0x1cb5c415, # vector#1cb5c415", "arguments, if any, of the TL object :param result: The", "self.flag_indicator: real_type = '#' if self.is_vector: if self.use_vector_id: real_type =", "} class TLObject: def __init__(self, fullname, object_id, args, result, is_function,", "').replace('>', '')\\ .replace('{', '').replace('}', '') representation = re.sub( r' \\w+:flags\\.\\d+\\?true',", "represents any layer 0: {'ipPortSecret', 'accessPointRule', 'help.configSimple'}, 77: {'channel'}, 78:", "else '') self.real_args = list(a for a in self.sorted_args() if", "'flags' flag_match = re.match(r'flags.(\\d+)\\?([\\w<>.]+)', self.type) if flag_match: self.is_flag = True", "See use_vector_id. An example of such case is ipPort in", "\"\"\"Finds the layer used on the specified scheme.tl file.\"\"\" layer_regex", "is_function, layer): match = re.match( r'^([\\w.]+)' # 'name' r'(?:#([0-9a-fA-F]+))?' #", "hexadecimal string representing the object ID :param args: The arguments,", "letter is not uppercase, then # it is a constructor", "it as required real_type = self.type if self.flag_indicator: real_type =", "belongs to. \"\"\" # The name can or not have", "a Vector<REAL_TYPE> vector_match = re.match(r'[Vv]ector<([\\w\\d.]+)>', self.type) if vector_match: self.is_vector =", "== 'random_id' # The type can be an indicator that" ]
[ "out == None: fail(\"either name or out must be set\")", "name that is used to load the resource. The default", "adds an action that compiles a single .resx file into", "generate. src: The .resx source file that is transformed into", "name of the output file (if name should not be", "<reponame>purkhusid/rules_dotnet \"Actions for compiling resx files\" load( \"@io_bazel_rules_dotnet//dotnet/private:providers.bzl\", \"DotnetResourceInfo\", )", "name of the file to generate. src: The .resx source", "custom resgen program to use. Returns: DotnetResourceInfo: [DotnetResourceInfo](api.md#dotnetresourceinfo). \"\"\" if", "== None: fail(\"either name or out must be set\") if", "name or out must be set\") if not out: result", "\"\" and out == None: fail(\"either name or out must", "creation resolve = dotnet._ctx.resolve_tools(tools = [customresgen]) inputs = src.files.to_list() if", "basename of the file name (no subfolder). out: An alternative", "[DotnetResourceInfo](api.md#dotnetresourceinfo). \"\"\" if name == \"\" and out == None:", "resolve[0].to_list(), tools = customresgen.default_runfiles.files, outputs = [result], executable = customresgen.files_to_run,", "result = dotnet.actions.declare_file(name + \".resources\") else: result = dotnet.actions.declare_file(out) args", "= customresgen.files_to_run, arguments = [args], env = {\"RUNFILES_MANIFEST_FILE\": customresgen.files_to_run.runfiles_manifest.path}, mnemonic", "== \"Target\": args.add_all(source.files) else: args.add(source) args.add(output) return args def emit_resx_core(", "\"Target\" else [src] dotnet.actions.run( inputs = inputs + resolve[0].to_list(), tools", "args.add(source) args.add(output) return args def emit_resx_core( dotnet, name = \"\",", "= None): \"\"\"The function adds an action that compiles a", "or out must be set\") if not out: result =", "\"@io_bazel_rules_dotnet//dotnet/private:providers.bzl\", \"DotnetResourceInfo\", ) def _make_runner_arglist(dotnet, source, output, resgen): args =", "type(source) == \"Target\": args.add_all(source.files) else: args.add(source) args.add(output) return args def", "the basename of the file name (no subfolder). out: An", "subfolder). out: An alternative name of the output file (if", "command to extrace shell path and force runfiles creation resolve", "src: The .resx source file that is transformed into .resources", "DotnetResourceInfo: [DotnetResourceInfo](api.md#dotnetresourceinfo). \"\"\" if name == \"\" and out ==", "src, result, customresgen.files_to_run.executable.path) # We use the command to extrace", ") def _make_runner_arglist(dotnet, source, output, resgen): args = dotnet.actions.args() if", "the resource; the name that is used to load the", "resgen program to use. Returns: DotnetResourceInfo: [DotnetResourceInfo](api.md#dotnetresourceinfo). \"\"\" if name", "(if name should not be used). customresgen: custom resgen program", "files are permitted. identifier: The logical name for the resource;", "\"\"\" if name == \"\" and out == None: fail(\"either", "\".resources\") else: result = dotnet.actions.declare_file(out) args = _make_runner_arglist(dotnet, src, result,", "identifier: The logical name for the resource; the name that", "file into .resources file. Returns [DotnetResourceInfo](api.md#dotnetresourceinfo). Args: dotnet: [DotnetContextInfo](api.md#dotnetcontextinfo). name:", "file. Only `.resx` files are permitted. identifier: The logical name", "= [customresgen]) inputs = src.files.to_list() if type(src) == \"Target\" else", "executable = customresgen.files_to_run, arguments = [args], env = {\"RUNFILES_MANIFEST_FILE\": customresgen.files_to_run.runfiles_manifest.path},", "into .resources file. Returns [DotnetResourceInfo](api.md#dotnetresourceinfo). Args: dotnet: [DotnetContextInfo](api.md#dotnetcontextinfo). name: name", "name == \"\" and out == None: fail(\"either name or", "\"Target\": args.add_all(source.files) else: args.add(source) args.add(output) return args def emit_resx_core( dotnet,", "(no subfolder). out: An alternative name of the output file", "dotnet.actions.args() if type(source) == \"Target\": args.add_all(source.files) else: args.add(source) args.add(output) return", "result = dotnet.actions.declare_file(out) args = _make_runner_arglist(dotnet, src, result, customresgen.files_to_run.executable.path) #", "name should not be used). customresgen: custom resgen program to", "is the basename of the file name (no subfolder). out:", "use. Returns: DotnetResourceInfo: [DotnetResourceInfo](api.md#dotnetresourceinfo). \"\"\" if name == \"\" and", "out: result = dotnet.actions.declare_file(name + \".resources\") else: result = dotnet.actions.declare_file(out)", "\":\" + dotnet.label.name ), ) return DotnetResourceInfo( name = name,", "of the file name (no subfolder). out: An alternative name", "customresgen.files_to_run, arguments = [args], env = {\"RUNFILES_MANIFEST_FILE\": customresgen.files_to_run.runfiles_manifest.path}, mnemonic =", "and force runfiles creation resolve = dotnet._ctx.resolve_tools(tools = [customresgen]) inputs", "source, output, resgen): args = dotnet.actions.args() if type(source) == \"Target\":", "output, resgen): args = dotnet.actions.args() if type(source) == \"Target\": args.add_all(source.files)", "args def emit_resx_core( dotnet, name = \"\", src = None,", "Returns [DotnetResourceInfo](api.md#dotnetresourceinfo). Args: dotnet: [DotnetContextInfo](api.md#dotnetcontextinfo). name: name of the file", "Only `.resx` files are permitted. identifier: The logical name for", "out: An alternative name of the output file (if name", "the file name (no subfolder). out: An alternative name of", "\"DotnetResourceInfo\", ) def _make_runner_arglist(dotnet, source, output, resgen): args = dotnet.actions.args()", "src.files.to_list() if type(src) == \"Target\" else [src] dotnet.actions.run( inputs =", ".resx source file that is transformed into .resources file. Only", "tools = customresgen.default_runfiles.files, outputs = [result], executable = customresgen.files_to_run, arguments", "[customresgen]) inputs = src.files.to_list() if type(src) == \"Target\" else [src]", "compiles a single .resx file into .resources file. Returns [DotnetResourceInfo](api.md#dotnetresourceinfo).", "is used to load the resource. The default is the", "{\"RUNFILES_MANIFEST_FILE\": customresgen.files_to_run.runfiles_manifest.path}, mnemonic = \"CoreResxCompile\", input_manifests = resolve[1], progress_message =", "return args def emit_resx_core( dotnet, name = \"\", src =", "is transformed into .resources file. Only `.resx` files are permitted.", "= None, out = None, customresgen = None): \"\"\"The function", "resoources\" + dotnet.label.package + \":\" + dotnet.label.name ), ) return", "Returns: DotnetResourceInfo: [DotnetResourceInfo](api.md#dotnetresourceinfo). \"\"\" if name == \"\" and out", "alternative name of the output file (if name should not", "We use the command to extrace shell path and force", "output file (if name should not be used). customresgen: custom", "= [result], executable = customresgen.files_to_run, arguments = [args], env =", ".resources file. Returns [DotnetResourceInfo](api.md#dotnetresourceinfo). Args: dotnet: [DotnetContextInfo](api.md#dotnetcontextinfo). name: name of", "customresgen.files_to_run.executable.path) # We use the command to extrace shell path", "default is the basename of the file name (no subfolder).", "the file to generate. src: The .resx source file that", "if type(src) == \"Target\" else [src] dotnet.actions.run( inputs = inputs", "= \"CoreResxCompile\", input_manifests = resolve[1], progress_message = ( \"Compiling resoources\"", "must be set\") if not out: result = dotnet.actions.declare_file(name +", "+ resolve[0].to_list(), tools = customresgen.default_runfiles.files, outputs = [result], executable =", ".resources file. Only `.resx` files are permitted. identifier: The logical", "for the resource; the name that is used to load", "= dotnet.actions.declare_file(out) args = _make_runner_arglist(dotnet, src, result, customresgen.files_to_run.executable.path) # We", "customresgen: custom resgen program to use. Returns: DotnetResourceInfo: [DotnetResourceInfo](api.md#dotnetresourceinfo). \"\"\"", "load the resource. The default is the basename of the", "args = dotnet.actions.args() if type(source) == \"Target\": args.add_all(source.files) else: args.add(source)", "should not be used). customresgen: custom resgen program to use.", "\"CoreResxCompile\", input_manifests = resolve[1], progress_message = ( \"Compiling resoources\" +", "input_manifests = resolve[1], progress_message = ( \"Compiling resoources\" + dotnet.label.package", "None, identifier = None, out = None, customresgen = None):", "== \"\" and out == None: fail(\"either name or out", "of the file to generate. src: The .resx source file", "The .resx source file that is transformed into .resources file.", "None: fail(\"either name or out must be set\") if not", "return DotnetResourceInfo( name = name, result = result, identifier =", "force runfiles creation resolve = dotnet._ctx.resolve_tools(tools = [customresgen]) inputs =", "mnemonic = \"CoreResxCompile\", input_manifests = resolve[1], progress_message = ( \"Compiling", "`.resx` files are permitted. identifier: The logical name for the", "that is used to load the resource. The default is", "dotnet.actions.declare_file(out) args = _make_runner_arglist(dotnet, src, result, customresgen.files_to_run.executable.path) # We use", "= {\"RUNFILES_MANIFEST_FILE\": customresgen.files_to_run.runfiles_manifest.path}, mnemonic = \"CoreResxCompile\", input_manifests = resolve[1], progress_message", "if not out: result = dotnet.actions.declare_file(name + \".resources\") else: result", "), ) return DotnetResourceInfo( name = name, result = result,", "+ \":\" + dotnet.label.name ), ) return DotnetResourceInfo( name =", "to use. Returns: DotnetResourceInfo: [DotnetResourceInfo](api.md#dotnetresourceinfo). \"\"\" if name == \"\"", "# We use the command to extrace shell path and", "customresgen.files_to_run.runfiles_manifest.path}, mnemonic = \"CoreResxCompile\", input_manifests = resolve[1], progress_message = (", "= None, identifier = None, out = None, customresgen =", "files\" load( \"@io_bazel_rules_dotnet//dotnet/private:providers.bzl\", \"DotnetResourceInfo\", ) def _make_runner_arglist(dotnet, source, output, resgen):", "to extrace shell path and force runfiles creation resolve =", "else [src] dotnet.actions.run( inputs = inputs + resolve[0].to_list(), tools =", "inputs = inputs + resolve[0].to_list(), tools = customresgen.default_runfiles.files, outputs =", "= ( \"Compiling resoources\" + dotnet.label.package + \":\" + dotnet.label.name", "None, customresgen = None): \"\"\"The function adds an action that", "path and force runfiles creation resolve = dotnet._ctx.resolve_tools(tools = [customresgen])", "customresgen = None): \"\"\"The function adds an action that compiles", "dotnet.actions.run( inputs = inputs + resolve[0].to_list(), tools = customresgen.default_runfiles.files, outputs", "dotnet.label.package + \":\" + dotnet.label.name ), ) return DotnetResourceInfo( name", "a single .resx file into .resources file. Returns [DotnetResourceInfo](api.md#dotnetresourceinfo). Args:", "inputs = src.files.to_list() if type(src) == \"Target\" else [src] dotnet.actions.run(", "name = \"\", src = None, identifier = None, out", "= src.files.to_list() if type(src) == \"Target\" else [src] dotnet.actions.run( inputs", "source file that is transformed into .resources file. Only `.resx`", "dotnet._ctx.resolve_tools(tools = [customresgen]) inputs = src.files.to_list() if type(src) == \"Target\"", "\"\", src = None, identifier = None, out = None,", "An alternative name of the output file (if name should", "emit_resx_core( dotnet, name = \"\", src = None, identifier =", "= \"\", src = None, identifier = None, out =", "Args: dotnet: [DotnetContextInfo](api.md#dotnetcontextinfo). name: name of the file to generate.", "= dotnet._ctx.resolve_tools(tools = [customresgen]) inputs = src.files.to_list() if type(src) ==", "extrace shell path and force runfiles creation resolve = dotnet._ctx.resolve_tools(tools", "+ \".resources\") else: result = dotnet.actions.declare_file(out) args = _make_runner_arglist(dotnet, src,", "args.add_all(source.files) else: args.add(source) args.add(output) return args def emit_resx_core( dotnet, name", "identifier = None, out = None, customresgen = None): \"\"\"The", "logical name for the resource; the name that is used", "runfiles creation resolve = dotnet._ctx.resolve_tools(tools = [customresgen]) inputs = src.files.to_list()", "outputs = [result], executable = customresgen.files_to_run, arguments = [args], env", "None): \"\"\"The function adds an action that compiles a single", "load( \"@io_bazel_rules_dotnet//dotnet/private:providers.bzl\", \"DotnetResourceInfo\", ) def _make_runner_arglist(dotnet, source, output, resgen): args", "type(src) == \"Target\" else [src] dotnet.actions.run( inputs = inputs +", "progress_message = ( \"Compiling resoources\" + dotnet.label.package + \":\" +", "\"Actions for compiling resx files\" load( \"@io_bazel_rules_dotnet//dotnet/private:providers.bzl\", \"DotnetResourceInfo\", ) def", "that compiles a single .resx file into .resources file. Returns", "+ dotnet.label.name ), ) return DotnetResourceInfo( name = name, result", "arguments = [args], env = {\"RUNFILES_MANIFEST_FILE\": customresgen.files_to_run.runfiles_manifest.path}, mnemonic = \"CoreResxCompile\",", "not be used). customresgen: custom resgen program to use. Returns:", "inputs + resolve[0].to_list(), tools = customresgen.default_runfiles.files, outputs = [result], executable", "= dotnet.actions.declare_file(name + \".resources\") else: result = dotnet.actions.declare_file(out) args =", "customresgen.default_runfiles.files, outputs = [result], executable = customresgen.files_to_run, arguments = [args],", "use the command to extrace shell path and force runfiles", "file. Returns [DotnetResourceInfo](api.md#dotnetresourceinfo). Args: dotnet: [DotnetContextInfo](api.md#dotnetcontextinfo). name: name of the", "resolve = dotnet._ctx.resolve_tools(tools = [customresgen]) inputs = src.files.to_list() if type(src)", "_make_runner_arglist(dotnet, src, result, customresgen.files_to_run.executable.path) # We use the command to", "compiling resx files\" load( \"@io_bazel_rules_dotnet//dotnet/private:providers.bzl\", \"DotnetResourceInfo\", ) def _make_runner_arglist(dotnet, source,", "resolve[1], progress_message = ( \"Compiling resoources\" + dotnet.label.package + \":\"", "to generate. src: The .resx source file that is transformed", "file to generate. src: The .resx source file that is", "into .resources file. Only `.resx` files are permitted. identifier: The", "name: name of the file to generate. src: The .resx", "an action that compiles a single .resx file into .resources", "if name == \"\" and out == None: fail(\"either name", "out = None, customresgen = None): \"\"\"The function adds an", "single .resx file into .resources file. Returns [DotnetResourceInfo](api.md#dotnetresourceinfo). Args: dotnet:", "set\") if not out: result = dotnet.actions.declare_file(name + \".resources\") else:", "def emit_resx_core( dotnet, name = \"\", src = None, identifier", "args.add(output) return args def emit_resx_core( dotnet, name = \"\", src", "to load the resource. The default is the basename of", "the resource. The default is the basename of the file", "the output file (if name should not be used). customresgen:", "the command to extrace shell path and force runfiles creation", "are permitted. identifier: The logical name for the resource; the", "resx files\" load( \"@io_bazel_rules_dotnet//dotnet/private:providers.bzl\", \"DotnetResourceInfo\", ) def _make_runner_arglist(dotnet, source, output,", "[src] dotnet.actions.run( inputs = inputs + resolve[0].to_list(), tools = customresgen.default_runfiles.files,", "used). customresgen: custom resgen program to use. Returns: DotnetResourceInfo: [DotnetResourceInfo](api.md#dotnetresourceinfo).", "dotnet: [DotnetContextInfo](api.md#dotnetcontextinfo). name: name of the file to generate. src:", "of the output file (if name should not be used).", "the name that is used to load the resource. The", "transformed into .resources file. Only `.resx` files are permitted. identifier:", "args = _make_runner_arglist(dotnet, src, result, customresgen.files_to_run.executable.path) # We use the", "for compiling resx files\" load( \"@io_bazel_rules_dotnet//dotnet/private:providers.bzl\", \"DotnetResourceInfo\", ) def _make_runner_arglist(dotnet,", "= [args], env = {\"RUNFILES_MANIFEST_FILE\": customresgen.files_to_run.runfiles_manifest.path}, mnemonic = \"CoreResxCompile\", input_manifests", "name for the resource; the name that is used to", "( \"Compiling resoources\" + dotnet.label.package + \":\" + dotnet.label.name ),", "resource; the name that is used to load the resource.", "= _make_runner_arglist(dotnet, src, result, customresgen.files_to_run.executable.path) # We use the command", "== \"Target\" else [src] dotnet.actions.run( inputs = inputs + resolve[0].to_list(),", "be used). customresgen: custom resgen program to use. Returns: DotnetResourceInfo:", "not out: result = dotnet.actions.declare_file(name + \".resources\") else: result =", "env = {\"RUNFILES_MANIFEST_FILE\": customresgen.files_to_run.runfiles_manifest.path}, mnemonic = \"CoreResxCompile\", input_manifests = resolve[1],", "src = None, identifier = None, out = None, customresgen", "dotnet.actions.declare_file(name + \".resources\") else: result = dotnet.actions.declare_file(out) args = _make_runner_arglist(dotnet,", "= inputs + resolve[0].to_list(), tools = customresgen.default_runfiles.files, outputs = [result],", "\"Compiling resoources\" + dotnet.label.package + \":\" + dotnet.label.name ), )", "file that is transformed into .resources file. Only `.resx` files", "that is transformed into .resources file. Only `.resx` files are", "+ dotnet.label.package + \":\" + dotnet.label.name ), ) return DotnetResourceInfo(", "DotnetResourceInfo( name = name, result = result, identifier = identifier,", "def _make_runner_arglist(dotnet, source, output, resgen): args = dotnet.actions.args() if type(source)", "The logical name for the resource; the name that is", "used to load the resource. The default is the basename", "[result], executable = customresgen.files_to_run, arguments = [args], env = {\"RUNFILES_MANIFEST_FILE\":", "name = name, result = result, identifier = identifier, )", "= None, customresgen = None): \"\"\"The function adds an action", "function adds an action that compiles a single .resx file", "None, out = None, customresgen = None): \"\"\"The function adds", "[DotnetResourceInfo](api.md#dotnetresourceinfo). Args: dotnet: [DotnetContextInfo](api.md#dotnetcontextinfo). name: name of the file to", "[args], env = {\"RUNFILES_MANIFEST_FILE\": customresgen.files_to_run.runfiles_manifest.path}, mnemonic = \"CoreResxCompile\", input_manifests =", "program to use. Returns: DotnetResourceInfo: [DotnetResourceInfo](api.md#dotnetresourceinfo). \"\"\" if name ==", ") return DotnetResourceInfo( name = name, result = result, identifier", "file name (no subfolder). out: An alternative name of the", "fail(\"either name or out must be set\") if not out:", "name (no subfolder). out: An alternative name of the output", "shell path and force runfiles creation resolve = dotnet._ctx.resolve_tools(tools =", "file (if name should not be used). customresgen: custom resgen", "dotnet, name = \"\", src = None, identifier = None,", "= resolve[1], progress_message = ( \"Compiling resoources\" + dotnet.label.package +", "= customresgen.default_runfiles.files, outputs = [result], executable = customresgen.files_to_run, arguments =", "permitted. identifier: The logical name for the resource; the name", "resgen): args = dotnet.actions.args() if type(source) == \"Target\": args.add_all(source.files) else:", ".resx file into .resources file. Returns [DotnetResourceInfo](api.md#dotnetresourceinfo). Args: dotnet: [DotnetContextInfo](api.md#dotnetcontextinfo).", "_make_runner_arglist(dotnet, source, output, resgen): args = dotnet.actions.args() if type(source) ==", "The default is the basename of the file name (no", "dotnet.label.name ), ) return DotnetResourceInfo( name = name, result =", "resource. The default is the basename of the file name", "\"\"\"The function adds an action that compiles a single .resx", "be set\") if not out: result = dotnet.actions.declare_file(name + \".resources\")", "[DotnetContextInfo](api.md#dotnetcontextinfo). name: name of the file to generate. src: The", "else: result = dotnet.actions.declare_file(out) args = _make_runner_arglist(dotnet, src, result, customresgen.files_to_run.executable.path)", "if type(source) == \"Target\": args.add_all(source.files) else: args.add(source) args.add(output) return args", "result, customresgen.files_to_run.executable.path) # We use the command to extrace shell", "= dotnet.actions.args() if type(source) == \"Target\": args.add_all(source.files) else: args.add(source) args.add(output)", "action that compiles a single .resx file into .resources file.", "and out == None: fail(\"either name or out must be", "else: args.add(source) args.add(output) return args def emit_resx_core( dotnet, name =", "out must be set\") if not out: result = dotnet.actions.declare_file(name" ]
[ "and intialized to a list. class Net(torch.nn.Linear): x: torch.jit.Final[int] def", "that has __constants__ set to something that is not a", "# Make the helper files in test/ importable pytorch_test_dir =", "= os.path.dirname(os.path.dirname(os.path.realpath(__file__))) sys.path.append(pytorch_test_dir) if __name__ == '__main__': raise RuntimeError(\"This test", "class TestModules(JitTestCase): def test_script_module_with_constants_list(self): \"\"\" Test that a module that", "def test_script_module_with_constants_list(self): \"\"\" Test that a module that has __constants__", "from torch.testing._internal.jit_utils import JitTestCase # Make the helper files in", "set to something that is not a set can be", "in test/ importable pytorch_test_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) sys.path.append(pytorch_test_dir) if __name__ ==", "import JitTestCase # Make the helper files in test/ importable", "scripted. \"\"\" # torch.nn.Linear has a __constants__ attribute defined #", "the helper files in test/ importable pytorch_test_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) sys.path.append(pytorch_test_dir)", "'__main__': raise RuntimeError(\"This test file is not meant to be", "torch import os import sys from torch.testing._internal.jit_utils import JitTestCase #", "pytorch_test_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) sys.path.append(pytorch_test_dir) if __name__ == '__main__': raise RuntimeError(\"This", "test/test_jit.py TESTNAME\\n\\n\" \"instead.\") class TestModules(JitTestCase): def test_script_module_with_constants_list(self): \"\"\" Test that", "== '__main__': raise RuntimeError(\"This test file is not meant to", "be run directly, use:\\n\\n\" \"\\tpython test/test_jit.py TESTNAME\\n\\n\" \"instead.\") class TestModules(JitTestCase):", "use:\\n\\n\" \"\\tpython test/test_jit.py TESTNAME\\n\\n\" \"instead.\") class TestModules(JitTestCase): def test_script_module_with_constants_list(self): \"\"\"", "is not a set can be scripted. \"\"\" # torch.nn.Linear", "helper files in test/ importable pytorch_test_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) sys.path.append(pytorch_test_dir) if", "if __name__ == '__main__': raise RuntimeError(\"This test file is not", "# and intialized to a list. class Net(torch.nn.Linear): x: torch.jit.Final[int]", "Net(torch.nn.Linear): x: torch.jit.Final[int] def __init__(self): super().__init__(5, 10) self.x = 0", "TESTNAME\\n\\n\" \"instead.\") class TestModules(JitTestCase): def test_script_module_with_constants_list(self): \"\"\" Test that a", "class Net(torch.nn.Linear): x: torch.jit.Final[int] def __init__(self): super().__init__(5, 10) self.x =", "a module that has __constants__ set to something that is", "__name__ == '__main__': raise RuntimeError(\"This test file is not meant", "torch.testing._internal.jit_utils import JitTestCase # Make the helper files in test/", "test_script_module_with_constants_list(self): \"\"\" Test that a module that has __constants__ set", "file is not meant to be run directly, use:\\n\\n\" \"\\tpython", "not meant to be run directly, use:\\n\\n\" \"\\tpython test/test_jit.py TESTNAME\\n\\n\"", "\"\\tpython test/test_jit.py TESTNAME\\n\\n\" \"instead.\") class TestModules(JitTestCase): def test_script_module_with_constants_list(self): \"\"\" Test", "[\"oncall: jit\"] import torch import os import sys from torch.testing._internal.jit_utils", "JitTestCase # Make the helper files in test/ importable pytorch_test_dir", "\"\"\" # torch.nn.Linear has a __constants__ attribute defined # and", "Owner(s): [\"oncall: jit\"] import torch import os import sys from", "__constants__ attribute defined # and intialized to a list. class", "import os import sys from torch.testing._internal.jit_utils import JitTestCase # Make", "that is not a set can be scripted. \"\"\" #", "attribute defined # and intialized to a list. class Net(torch.nn.Linear):", "meant to be run directly, use:\\n\\n\" \"\\tpython test/test_jit.py TESTNAME\\n\\n\" \"instead.\")", "importable pytorch_test_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) sys.path.append(pytorch_test_dir) if __name__ == '__main__': raise", "import sys from torch.testing._internal.jit_utils import JitTestCase # Make the helper", "__constants__ set to something that is not a set can", "Make the helper files in test/ importable pytorch_test_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))", "has a __constants__ attribute defined # and intialized to a", "can be scripted. \"\"\" # torch.nn.Linear has a __constants__ attribute", "set can be scripted. \"\"\" # torch.nn.Linear has a __constants__", "# Owner(s): [\"oncall: jit\"] import torch import os import sys", "module that has __constants__ set to something that is not", "not a set can be scripted. \"\"\" # torch.nn.Linear has", "list. class Net(torch.nn.Linear): x: torch.jit.Final[int] def __init__(self): super().__init__(5, 10) self.x", "x: torch.jit.Final[int] def __init__(self): super().__init__(5, 10) self.x = 0 self.checkModule(Net(),", "\"instead.\") class TestModules(JitTestCase): def test_script_module_with_constants_list(self): \"\"\" Test that a module", "# torch.nn.Linear has a __constants__ attribute defined # and intialized", "to be run directly, use:\\n\\n\" \"\\tpython test/test_jit.py TESTNAME\\n\\n\" \"instead.\") class", "test/ importable pytorch_test_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) sys.path.append(pytorch_test_dir) if __name__ == '__main__':", "a __constants__ attribute defined # and intialized to a list.", "test file is not meant to be run directly, use:\\n\\n\"", "is not meant to be run directly, use:\\n\\n\" \"\\tpython test/test_jit.py", "directly, use:\\n\\n\" \"\\tpython test/test_jit.py TESTNAME\\n\\n\" \"instead.\") class TestModules(JitTestCase): def test_script_module_with_constants_list(self):", "sys.path.append(pytorch_test_dir) if __name__ == '__main__': raise RuntimeError(\"This test file is", "to a list. class Net(torch.nn.Linear): x: torch.jit.Final[int] def __init__(self): super().__init__(5,", "torch.jit.Final[int] def __init__(self): super().__init__(5, 10) self.x = 0 self.checkModule(Net(), (torch.randn(5),))", "Test that a module that has __constants__ set to something", "raise RuntimeError(\"This test file is not meant to be run", "defined # and intialized to a list. class Net(torch.nn.Linear): x:", "os.path.dirname(os.path.dirname(os.path.realpath(__file__))) sys.path.append(pytorch_test_dir) if __name__ == '__main__': raise RuntimeError(\"This test file", "jit\"] import torch import os import sys from torch.testing._internal.jit_utils import", "a set can be scripted. \"\"\" # torch.nn.Linear has a", "intialized to a list. class Net(torch.nn.Linear): x: torch.jit.Final[int] def __init__(self):", "files in test/ importable pytorch_test_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) sys.path.append(pytorch_test_dir) if __name__", "to something that is not a set can be scripted.", "a list. class Net(torch.nn.Linear): x: torch.jit.Final[int] def __init__(self): super().__init__(5, 10)", "RuntimeError(\"This test file is not meant to be run directly,", "sys from torch.testing._internal.jit_utils import JitTestCase # Make the helper files", "import torch import os import sys from torch.testing._internal.jit_utils import JitTestCase", "has __constants__ set to something that is not a set", "torch.nn.Linear has a __constants__ attribute defined # and intialized to", "os import sys from torch.testing._internal.jit_utils import JitTestCase # Make the", "be scripted. \"\"\" # torch.nn.Linear has a __constants__ attribute defined", "run directly, use:\\n\\n\" \"\\tpython test/test_jit.py TESTNAME\\n\\n\" \"instead.\") class TestModules(JitTestCase): def", "TestModules(JitTestCase): def test_script_module_with_constants_list(self): \"\"\" Test that a module that has", "that a module that has __constants__ set to something that", "something that is not a set can be scripted. \"\"\"", "\"\"\" Test that a module that has __constants__ set to" ]
[ "import time import pybullet as p import pybullet_data import cv2", "pybullet_data import cv2 if __name__ == \"__main__\": env = gym.make(\"pix_sample_arena-v0\")", "as p import pybullet_data import cv2 if __name__ == \"__main__\":", "__name__ == \"__main__\": env = gym.make(\"pix_sample_arena-v0\") x = 0 while", "== \"__main__\": env = gym.make(\"pix_sample_arena-v0\") x = 0 while True:", "pix_sample_arena import time import pybullet as p import pybullet_data import", "time import pybullet as p import pybullet_data import cv2 if", "env = gym.make(\"pix_sample_arena-v0\") x = 0 while True: p.stepSimulation() time.sleep(100)", "pybullet as p import pybullet_data import cv2 if __name__ ==", "<filename>pixelate_task_1.py import gym import pix_sample_arena import time import pybullet as", "if __name__ == \"__main__\": env = gym.make(\"pix_sample_arena-v0\") x = 0", "import pix_sample_arena import time import pybullet as p import pybullet_data", "import pybullet as p import pybullet_data import cv2 if __name__", "import pybullet_data import cv2 if __name__ == \"__main__\": env =", "p import pybullet_data import cv2 if __name__ == \"__main__\": env", "gym import pix_sample_arena import time import pybullet as p import", "import gym import pix_sample_arena import time import pybullet as p", "import cv2 if __name__ == \"__main__\": env = gym.make(\"pix_sample_arena-v0\") x", "cv2 if __name__ == \"__main__\": env = gym.make(\"pix_sample_arena-v0\") x =", "\"__main__\": env = gym.make(\"pix_sample_arena-v0\") x = 0 while True: p.stepSimulation()" ]
[ "parse_time @pytest.mark.parametrize( \"time_input, expected\", [ (\"12:13\", time(hour=12, minute=13)), (\"12:13:14\", time(hour=12,", ") def test_manually_time_parsing(time_input: str, expected: time): assert __parse_time_manually(time_input) == expected,", "\"manual time parsing has gone wrong\" @pytest.mark.parametrize( \"time_input, expected\", [", "from datetime import time import pytest from i3_battery_block_vgg.timeparser import __parse_time_manually", "second=14)), ('00:54:00', time(hour=0, minute=54, second=0)) ] ) def test_manually_time_parsing(time_input: str,", "time import pytest from i3_battery_block_vgg.timeparser import __parse_time_manually from i3_battery_block_vgg.timeparser import", "time(hour=12, minute=13, second=14)), ('00:54:00', time(hour=0, minute=54, second=0)) ] ) def", "from i3_battery_block_vgg.timeparser import parse_time @pytest.mark.parametrize( \"time_input, expected\", [ (\"12:13\", time(hour=12,", "] ) def test_manually_time_parsing(time_input: str, expected: time): assert __parse_time_manually(time_input) ==", "<gh_stars>0 from datetime import time import pytest from i3_battery_block_vgg.timeparser import", "has gone wrong\" @pytest.mark.parametrize( \"time_input, expected\", [ (\"12:13\", time(hour=12, minute=13)),", "== expected, \"manual time parsing has gone wrong\" @pytest.mark.parametrize( \"time_input,", "str, expected: time): assert __parse_time_manually(time_input) == expected, \"manual time parsing", "expected: time): assert __parse_time_manually(time_input) == expected, \"manual time parsing has", "__parse_time_manually(time_input) == expected, \"manual time parsing has gone wrong\" @pytest.mark.parametrize(", ") def test_time_parsing(time_input: str, expected: time): assert parse_time(time_input) == expected,", "import time import pytest from i3_battery_block_vgg.timeparser import __parse_time_manually from i3_battery_block_vgg.timeparser", "parsing has gone wrong\" @pytest.mark.parametrize( \"time_input, expected\", [ (\"12:13\", time(hour=12,", "('00:54:00', time(hour=0, minute=54, second=0)) ] ) def test_manually_time_parsing(time_input: str, expected:", "time): assert parse_time(time_input) == expected, \"time parsing has gone wrong\"", "pytest from i3_battery_block_vgg.timeparser import __parse_time_manually from i3_battery_block_vgg.timeparser import parse_time @pytest.mark.parametrize(", "expected: time): assert parse_time(time_input) == expected, \"time parsing has gone", "minute=54, second=0)) ] ) def test_time_parsing(time_input: str, expected: time): assert", "minute=54, second=0)) ] ) def test_manually_time_parsing(time_input: str, expected: time): assert", "time): assert __parse_time_manually(time_input) == expected, \"manual time parsing has gone", "second=0)) ] ) def test_time_parsing(time_input: str, expected: time): assert parse_time(time_input)", "(\"12:13\", time(hour=12, minute=13)), (\"12:13:14\", time(hour=12, minute=13, second=14)), ('00:54:00', time(hour=0, minute=54,", "('00:54:00', time(hour=0, minute=54, second=0)) ] ) def test_time_parsing(time_input: str, expected:", "from i3_battery_block_vgg.timeparser import __parse_time_manually from i3_battery_block_vgg.timeparser import parse_time @pytest.mark.parametrize( \"time_input,", "test_time_parsing(time_input: str, expected: time): assert parse_time(time_input) == expected, \"time parsing", "datetime import time import pytest from i3_battery_block_vgg.timeparser import __parse_time_manually from", "time(hour=12, minute=13)), (\"12:13:14\", time(hour=12, minute=13, second=14)), ('00:54:00', time(hour=0, minute=54, second=0))", "import parse_time @pytest.mark.parametrize( \"time_input, expected\", [ (\"12:13\", time(hour=12, minute=13)), (\"12:13:14\",", "gone wrong\" @pytest.mark.parametrize( \"time_input, expected\", [ (\"12:13\", time(hour=12, minute=13)), (\"12:13:14\",", "@pytest.mark.parametrize( \"time_input, expected\", [ (\"12:13\", time(hour=12, minute=13)), (\"12:13:14\", time(hour=12, minute=13,", "test_manually_time_parsing(time_input: str, expected: time): assert __parse_time_manually(time_input) == expected, \"manual time", "assert __parse_time_manually(time_input) == expected, \"manual time parsing has gone wrong\"", "minute=13, second=14)), ('00:54:00', time(hour=0, minute=54, second=0)) ] ) def test_time_parsing(time_input:", "import __parse_time_manually from i3_battery_block_vgg.timeparser import parse_time @pytest.mark.parametrize( \"time_input, expected\", [", "time parsing has gone wrong\" @pytest.mark.parametrize( \"time_input, expected\", [ (\"12:13\",", "second=14)), ('00:54:00', time(hour=0, minute=54, second=0)) ] ) def test_time_parsing(time_input: str,", "expected\", [ (\"12:13\", time(hour=12, minute=13)), (\"12:13:14\", time(hour=12, minute=13, second=14)), ('00:54:00',", "wrong\" @pytest.mark.parametrize( \"time_input, expected\", [ (\"12:13\", time(hour=12, minute=13)), (\"12:13:14\", time(hour=12,", "[ (\"12:13\", time(hour=12, minute=13)), (\"12:13:14\", time(hour=12, minute=13, second=14)), ('00:54:00', time(hour=0,", "i3_battery_block_vgg.timeparser import parse_time @pytest.mark.parametrize( \"time_input, expected\", [ (\"12:13\", time(hour=12, minute=13)),", "(\"12:13:14\", time(hour=12, minute=13, second=14)), ('00:54:00', time(hour=0, minute=54, second=0)) ] )", "str, expected: time): assert parse_time(time_input) == expected, \"time parsing has", "i3_battery_block_vgg.timeparser import __parse_time_manually from i3_battery_block_vgg.timeparser import parse_time @pytest.mark.parametrize( \"time_input, expected\",", "minute=13)), (\"12:13:14\", time(hour=12, minute=13, second=14)), ('00:54:00', time(hour=0, minute=54, second=0)) ]", "expected, \"manual time parsing has gone wrong\" @pytest.mark.parametrize( \"time_input, expected\",", "\"time_input, expected\", [ (\"12:13\", time(hour=12, minute=13)), (\"12:13:14\", time(hour=12, minute=13, second=14)),", "time(hour=0, minute=54, second=0)) ] ) def test_manually_time_parsing(time_input: str, expected: time):", "import pytest from i3_battery_block_vgg.timeparser import __parse_time_manually from i3_battery_block_vgg.timeparser import parse_time", "] ) def test_time_parsing(time_input: str, expected: time): assert parse_time(time_input) ==", "def test_manually_time_parsing(time_input: str, expected: time): assert __parse_time_manually(time_input) == expected, \"manual", "def test_time_parsing(time_input: str, expected: time): assert parse_time(time_input) == expected, \"time", "second=0)) ] ) def test_manually_time_parsing(time_input: str, expected: time): assert __parse_time_manually(time_input)", "time(hour=0, minute=54, second=0)) ] ) def test_time_parsing(time_input: str, expected: time):", "minute=13, second=14)), ('00:54:00', time(hour=0, minute=54, second=0)) ] ) def test_manually_time_parsing(time_input:", "__parse_time_manually from i3_battery_block_vgg.timeparser import parse_time @pytest.mark.parametrize( \"time_input, expected\", [ (\"12:13\"," ]
[ "coefficients.coeff]) @generator def construct(mod): \"\"\"Implement this module for input 'x'.\"\"\"", "for input 'x'.\"\"\" x = mod.x taps = list() for", "-> (%y: i32) # CHECK: hw.constant 1 # CHECK: hw.constant", "{coeff = [62, 42, 6]}, module_name = \"PolyComputeForCoeff_62_42_6\", unused_parameter =", "coefficients): self.coefficients = coefficients class Coefficients: def __init__(self, coeff): self.coeff", "\"top\" # CHECK: label=\"top\"; # CHECK: [shape=record,label=\"{hw.constant\\ni32\\n\\nvalue: 23 : i32}\"];", "= \"example2\", opNames = [\"x\"], parameters = {coefficients = {coeff", "newPartialSum = comb.AddOp.create( partialSum, comb.MulOp.create(coeffVal, currPow)) taps.append(newPartialSum) # Final output", "parameters = {coefficients = {coeff = [1, 2, 3, 4,", "i32) # CHECK: [[REG0:%.+]] = \"pycde.PolynomialCompute\"(%c23_i32) {instanceName = \"example\", opNames", "poly.y} poly = Polynomial() poly.graph() # CHECK-LABEL: digraph \"top\" #", "FileCheck %s from __future__ import annotations import mlir import pycde", "module, externmodule, generator, types, dim) from circt.dialects import comb, hw", "inputs = [] outputs = [('y', types.i32)] def build(self, top):", "= hw.ConstantOp.create(i32, 23) poly = PolynomialCompute(Coefficients([62, 42, 6]))(\"example\", x=x) PolynomialCompute(coefficients=Coefficients([62,", "CHECK: hw.constant 5 # CHECK-NOT: hw.module @pycde.PolynomialCompute print(\"\\n\\n=== Verilog ===\")", "hw.constant 2 # CHECK: hw.constant 3 # CHECK: hw.constant 4", "= [4, 42], parameters = {}} : (i32) -> i32", "[4, 42], opNames = [\"x\"], parameters = {}, resultNames =", "@externmodule(\"supercooldevice\") class CoolPolynomialCompute: x = Input(types.i32) y = Output(types.i32) def", "x = Input(types.i32) y = Output(types.i32) def __init__(self, coefficients): self.coefficients", "x=x) return {\"y\": poly.y} poly = Polynomial() poly.graph() # CHECK-LABEL:", "comb.MulOp.create(coeffVal, currPow)) taps.append(newPartialSum) # Final output return {\"y\": taps[-1]} return", "# CHECK-LABEL: module PolyComputeForCoeff_62_42_6( # CHECK: input [31:0] x, #", "hw.instance \"example2\" @PolyComputeForCoeff_62_42_6(%example.y) {parameters = {}} : (i32) -> i32", "range(power)] currPow = comb.MulOp.create(*x_power) newPartialSum = comb.AddOp.create( partialSum, comb.MulOp.create(coeffVal, currPow))", "Output, Parameter, module, externmodule, generator, types, dim) from circt.dialects import", "\"example2\", opNames = [\"x\"], parameters = {coefficients = {coeff =", "@top # CHECK: %example.y = hw.instance \"example\" @PolyComputeForCoeff_62_42_6(%c23_i32) {parameters =", "Verilog === poly.print_verilog() # CHECK-LABEL: module PolyComputeForCoeff_62_42_6( # CHECK: input", "PolynomialCompute: \"\"\"Module to compute ax^3 + bx^2 + cx +", "@PolyComputeForCoeff_62_42_6(%c23_i32) {parameters = {}} : (i32) -> i32 # CHECK:", "PolynomialCompute(Coefficients([1, 2, 3, 4, 5]))(\"example2\", x=poly.y) CoolPolynomialCompute([4, 42], x=x) return", "(%y: i32) # CHECK: hw.constant 62 # CHECK: hw.constant 42", "import pycde from pycde import (Input, Output, Parameter, module, externmodule,", "@module def PolynomialCompute(coefficients: Coefficients): class PolynomialCompute: \"\"\"Module to compute ax^3", "@PolyComputeForCoeff_1_2_3_4_5(%x: i32) -> (%y: i32) # CHECK: hw.constant 1 #", "hw.module @PolyComputeForCoeff_62_42_6(%x: i32) -> (%y: i32) # CHECK: hw.constant 62", "4, 5]}, module_name = \"PolyComputeForCoeff_1_2_3_4_5\", unused_parameter = true}, resultNames =", "'_'.join( [str(x) for x in coefficients.coeff]) @generator def construct(mod): \"\"\"Implement", "str): \"\"\"coefficients is in 'd' -> 'a' order.\"\"\" self.instanceName =", "# CHECK-LABEL: === Verilog === poly.print_verilog() # CHECK-LABEL: module PolyComputeForCoeff_62_42_6(", "else: partialSum = taps[-1] if power == 1: currPow =", "CHECK: [[REG0:%.+]] = \"pycde.PolynomialCompute\"(%c23_i32) {instanceName = \"example\", opNames = [\"x\"],", "\"example\" @PolyComputeForCoeff_62_42_6(%c23_i32) {parameters = {}} : (i32) -> i32 #", "__future__ import annotations import mlir import pycde from pycde import", "y = Output(types.int(8 * 4)) unused_parameter = Parameter(True) def __init__(self,", "CHECK-LABEL: hw.module @PolyComputeForCoeff_62_42_6(%x: i32) -> (%y: i32) # CHECK: hw.constant", "= [\"x\"], parameters = {}, resultNames = [\"y\"]} : (i32)", "import annotations import mlir import pycde from pycde import (Input,", "* 4)) unused_parameter = Parameter(True) def __init__(self, name: str): \"\"\"coefficients", "hw.instance \"example\" @PolyComputeForCoeff_62_42_6(%c23_i32) {parameters = {}} : (i32) -> i32", "=== poly.print_verilog() # CHECK-LABEL: module PolyComputeForCoeff_62_42_6( # CHECK: input [31:0]", "= hw.instance \"example2\" @PolyComputeForCoeff_62_42_6(%example.y) {parameters = {}} : (i32) ->", "== 0: newPartialSum = coeffVal.result else: partialSum = taps[-1] if", "CHECK-NOT: hw.module @pycde.PolynomialCompute print(\"\\n\\n=== Verilog ===\") # CHECK-LABEL: === Verilog", "%example2.y_0 = hw.instance \"example2\" @PolyComputeForCoeff_1_2_3_4_5(%example.y) {parameters = {}} : (i32)", "(%y: i32) # CHECK: hw.constant 1 # CHECK: hw.constant 2", "[62, 42, 6]}, module_name = \"PolyComputeForCoeff_62_42_6\", unused_parameter = true}, resultNames", "# CHECK: hw.output [[REG0]] : i32 poly.generate() poly.print() # CHECK-LABEL:", "partialSum, comb.MulOp.create(coeffVal, currPow)) taps.append(newPartialSum) # Final output return {\"y\": taps[-1]}", "coeffVal = hw.ConstantOp.create(types.i32, coeff) if power == 0: newPartialSum =", ": (i32) -> i32 # CHECK: %example2.y = hw.instance \"example2\"", "parameters = {}, resultNames = [\"y\"]} : (i32) -> i32", "i32 poly.generate() poly.print() # CHECK-LABEL: hw.module @top # CHECK: %example.y", "1 # CHECK: hw.constant 2 # CHECK: hw.constant 3 #", "list() for power, coeff in enumerate(coefficients.coeff): coeffVal = hw.ConstantOp.create(types.i32, coeff)", "= hw.ConstantOp.create(types.i32, coeff) if power == 0: newPartialSum = coeffVal.result", "= mod.x taps = list() for power, coeff in enumerate(coefficients.coeff):", "= [\"x\"], parameters = {coefficients = {coeff = [1, 2,", "d for design-time coefficients\"\"\" # Evaluate polynomial for 'x'. x", "+ '_'.join( [str(x) for x in coefficients.coeff]) @generator def construct(mod):", "= true}, resultNames = [\"y\"]} : (i32) -> i32 #", "# CHECK: %example.y = hw.instance \"example\" @PolyComputeForCoeff_62_42_6(%c23_i32) {parameters = {}}", "\"pycde.PolynomialCompute\"([[REG0]]) {instanceName = \"example2\", opNames = [\"x\"], parameters = {coefficients", "# Final output return {\"y\": taps[-1]} return PolynomialCompute @externmodule(\"supercooldevice\") class", "return {\"y\": taps[-1]} return PolynomialCompute @externmodule(\"supercooldevice\") class CoolPolynomialCompute: x =", "[\"x\"], parameters = {}, resultNames = [\"y\"]} : (i32) ->", "6]))(\"example2\", x=poly.y) PolynomialCompute(Coefficients([1, 2, 3, 4, 5]))(\"example2\", x=poly.y) CoolPolynomialCompute([4, 42],", "true}, resultNames = [\"y\"]} : (i32) -> i32 # CHECK:", "0: newPartialSum = coeffVal.result else: partialSum = taps[-1] if power", "coeff): self.coeff = coeff class Polynomial(pycde.System): inputs = [] outputs", "\"PolyComputeForCoeff_62_42_6\", unused_parameter = true}, resultNames = [\"y\"]} : (i32) ->", "def construct(mod): \"\"\"Implement this module for input 'x'.\"\"\" x =", "if power == 0: newPartialSum = coeffVal.result else: partialSum =", "= [4, 42], opNames = [\"x\"], parameters = {}, resultNames", "4 # CHECK: hw.constant 5 # CHECK-NOT: hw.module @pycde.PolynomialCompute print(\"\\n\\n===", "# CHECK: [[REG1:%.+]] = \"pycde.PolynomialCompute\"([[REG0]]) {instanceName = \"example2\", opNames =", "CHECK: hw.constant 42 # CHECK: hw.constant 6 # CHECK-LABEL: hw.module", "[[REG1:%.+]] = \"pycde.PolynomialCompute\"([[REG0]]) {instanceName = \"example2\", opNames = [\"x\"], parameters", "# CHECK: input [31:0] x, # CHECK: output [31:0] y);", "poly = PolynomialCompute(Coefficients([62, 42, 6]))(\"example\", x=x) PolynomialCompute(coefficients=Coefficients([62, 42, 6]))(\"example2\", x=poly.y)", "poly.print() # CHECK-LABEL: hw.module @top() -> (%y: i32) # CHECK:", "= {coeff = [1, 2, 3, 4, 5]}, module_name =", "# CHECK: [shape=record,label=\"{hw.constant\\ni32\\n\\nvalue: 23 : i32}\"]; poly.print() # CHECK-LABEL: hw.module", "annotations import mlir import pycde from pycde import (Input, Output,", "x=poly.y) PolynomialCompute(Coefficients([1, 2, 3, 4, 5]))(\"example2\", x=poly.y) CoolPolynomialCompute([4, 42], x=x)", "= Polynomial() poly.graph() # CHECK-LABEL: digraph \"top\" # CHECK: label=\"top\";", "Parameter(True) def __init__(self, name: str): \"\"\"coefficients is in 'd' ->", "%PYTHON% %s 2>&1 | FileCheck %s from __future__ import annotations", "def get_module_name(): return \"PolyComputeForCoeff_\" + '_'.join( [str(x) for x in", "Parameter, module, externmodule, generator, types, dim) from circt.dialects import comb,", "currPow = x else: x_power = [x for i in", "resultNames = [\"y\"]} : (i32) -> i32 # CHECK: [[REG2:%.+]]", "hw.ConstantOp.create(types.i32, coeff) if power == 0: newPartialSum = coeffVal.result else:", "'a' order.\"\"\" self.instanceName = name @staticmethod def get_module_name(): return \"PolyComputeForCoeff_\"", "# CHECK-LABEL: hw.module @PolyComputeForCoeff_62_42_6(%x: i32) -> (%y: i32) # CHECK:", "name @staticmethod def get_module_name(): return \"PolyComputeForCoeff_\" + '_'.join( [str(x) for", "x else: x_power = [x for i in range(power)] currPow", "return \"PolyComputeForCoeff_\" + '_'.join( [str(x) for x in coefficients.coeff]) @generator", "-> i32 # CHECK: %pycde.CoolPolynomialCompute.y = hw.instance \"pycde.CoolPolynomialCompute\" @supercooldevice(%c23_i32) {coefficients", "= {}} : (i32) -> i32 # CHECK: %example2.y_0 =", ": (i32) -> i32 # CHECK: [[REG3:%.+]] = \"pycde.CoolPolynomialCompute\"(%c23_i32) {coefficients", "62 # CHECK: hw.constant 42 # CHECK: hw.constant 6 #", "hw.output [[REG0]] : i32 poly.generate() poly.print() # CHECK-LABEL: hw.module @top", "opNames = [\"x\"], parameters = {}, resultNames = [\"y\"]} :", "+ cx + d for design-time coefficients\"\"\" # Evaluate polynomial", "@staticmethod def get_module_name(): return \"PolyComputeForCoeff_\" + '_'.join( [str(x) for x", "{\"y\": poly.y} poly = Polynomial() poly.graph() # CHECK-LABEL: digraph \"top\"", "newPartialSum = coeffVal.result else: partialSum = taps[-1] if power ==", "module_name = \"PolyComputeForCoeff_1_2_3_4_5\", unused_parameter = true}, resultNames = [\"y\"]} :", "i32 # CHECK: %example2.y_0 = hw.instance \"example2\" @PolyComputeForCoeff_1_2_3_4_5(%example.y) {parameters =", "hw.module @top() -> (%y: i32) # CHECK: [[REG0:%.+]] = \"pycde.PolynomialCompute\"(%c23_i32)", "= {}} : (i32) -> i32 # CHECK: %example2.y =", "2>&1 | FileCheck %s from __future__ import annotations import mlir", "taps[-1] if power == 1: currPow = x else: x_power", "(i32) -> i32 # CHECK: [[REG3:%.+]] = \"pycde.CoolPolynomialCompute\"(%c23_i32) {coefficients =", "[1, 2, 3, 4, 5]}, module_name = \"PolyComputeForCoeff_1_2_3_4_5\", unused_parameter =", "{parameters = {}} : (i32) -> i32 # CHECK: %example2.y_0", "(i32) -> i32 # CHECK-LABEL: hw.module @PolyComputeForCoeff_62_42_6(%x: i32) -> (%y:", "PolyComputeForCoeff_62_42_6( # CHECK: input [31:0] x, # CHECK: output [31:0]", "= [x for i in range(power)] currPow = comb.MulOp.create(*x_power) newPartialSum", "CHECK-LABEL: hw.module @top # CHECK: %example.y = hw.instance \"example\" @PolyComputeForCoeff_62_42_6(%c23_i32)", "import (Input, Output, Parameter, module, externmodule, generator, types, dim) from", "\"\"\"Module to compute ax^3 + bx^2 + cx + d", "PolynomialCompute @externmodule(\"supercooldevice\") class CoolPolynomialCompute: x = Input(types.i32) y = Output(types.i32)", "i32 # CHECK: hw.output [[REG0]] : i32 poly.generate() poly.print() #", "parameters = {}} : (i32) -> i32 # CHECK-LABEL: hw.module", "-> (%y: i32) # CHECK: [[REG0:%.+]] = \"pycde.PolynomialCompute\"(%c23_i32) {instanceName =", "= [\"y\"]} : (i32) -> i32 # CHECK: [[REG1:%.+]] =", "ax^3 + bx^2 + cx + d for design-time coefficients\"\"\"", "hw.ConstantOp.create(i32, 23) poly = PolynomialCompute(Coefficients([62, 42, 6]))(\"example\", x=x) PolynomialCompute(coefficients=Coefficients([62, 42,", "coeffVal.result else: partialSum = taps[-1] if power == 1: currPow", "name: str): \"\"\"coefficients is in 'd' -> 'a' order.\"\"\" self.instanceName", "= [\"y\"]} : (i32) -> i32 # CHECK: [[REG3:%.+]] =", "4)) unused_parameter = Parameter(True) def __init__(self, name: str): \"\"\"coefficients is", "from circt.dialects import comb, hw @module def PolynomialCompute(coefficients: Coefficients): class", "= Output(types.int(8 * 4)) unused_parameter = Parameter(True) def __init__(self, name:", "CHECK: hw.constant 4 # CHECK: hw.constant 5 # CHECK-NOT: hw.module", "2, 3, 4, 5]}, module_name = \"PolyComputeForCoeff_1_2_3_4_5\", unused_parameter = true},", "CHECK: %example2.y = hw.instance \"example2\" @PolyComputeForCoeff_62_42_6(%example.y) {parameters = {}} :", "[\"x\"], parameters = {coefficients = {coeff = [62, 42, 6]},", "module PolyComputeForCoeff_62_42_6( # CHECK: input [31:0] x, # CHECK: output", "== 1: currPow = x else: x_power = [x for", "\"pycde.CoolPolynomialCompute\"(%c23_i32) {coefficients = [4, 42], opNames = [\"x\"], parameters =", "[x for i in range(power)] currPow = comb.MulOp.create(*x_power) newPartialSum =", "# CHECK: [[REG3:%.+]] = \"pycde.CoolPolynomialCompute\"(%c23_i32) {coefficients = [4, 42], opNames", "{coeff = [1, 2, 3, 4, 5]}, module_name = \"PolyComputeForCoeff_1_2_3_4_5\",", "hw.module @PolyComputeForCoeff_1_2_3_4_5(%x: i32) -> (%y: i32) # CHECK: hw.constant 1", "= Input(types.i32) y = Output(types.int(8 * 4)) unused_parameter = Parameter(True)", "output return {\"y\": taps[-1]} return PolynomialCompute @externmodule(\"supercooldevice\") class CoolPolynomialCompute: x", "@PolyComputeForCoeff_1_2_3_4_5(%example.y) {parameters = {}} : (i32) -> i32 # CHECK:", "mlir import pycde from pycde import (Input, Output, Parameter, module,", "currPow)) taps.append(newPartialSum) # Final output return {\"y\": taps[-1]} return PolynomialCompute", "42, 6]))(\"example\", x=x) PolynomialCompute(coefficients=Coefficients([62, 42, 6]))(\"example2\", x=poly.y) PolynomialCompute(Coefficients([1, 2, 3,", "__init__(self, name: str): \"\"\"coefficients is in 'd' -> 'a' order.\"\"\"", "= Parameter(True) def __init__(self, name: str): \"\"\"coefficients is in 'd'", "self.instanceName = name @staticmethod def get_module_name(): return \"PolyComputeForCoeff_\" + '_'.join(", "Input(types.i32) y = Output(types.i32) def __init__(self, coefficients): self.coefficients = coefficients", "42, 6]))(\"example2\", x=poly.y) PolynomialCompute(Coefficients([1, 2, 3, 4, 5]))(\"example2\", x=poly.y) CoolPolynomialCompute([4,", "def __init__(self, coeff): self.coeff = coeff class Polynomial(pycde.System): inputs =", "hw.constant 4 # CHECK: hw.constant 5 # CHECK-NOT: hw.module @pycde.PolynomialCompute", "# CHECK: %example2.y = hw.instance \"example2\" @PolyComputeForCoeff_62_42_6(%example.y) {parameters = {}}", "pycde import (Input, Output, Parameter, module, externmodule, generator, types, dim)", "parameters = {coefficients = {coeff = [62, 42, 6]}, module_name", "42], parameters = {}} : (i32) -> i32 # CHECK-LABEL:", "x=x) PolynomialCompute(coefficients=Coefficients([62, 42, 6]))(\"example2\", x=poly.y) PolynomialCompute(Coefficients([1, 2, 3, 4, 5]))(\"example2\",", "{coefficients = {coeff = [1, 2, 3, 4, 5]}, module_name", "comb.MulOp.create(*x_power) newPartialSum = comb.AddOp.create( partialSum, comb.MulOp.create(coeffVal, currPow)) taps.append(newPartialSum) # Final", "module for input 'x'.\"\"\" x = mod.x taps = list()", "self.coefficients = coefficients class Coefficients: def __init__(self, coeff): self.coeff =", "\"example2\" @PolyComputeForCoeff_1_2_3_4_5(%example.y) {parameters = {}} : (i32) -> i32 #", ": (i32) -> i32 # CHECK: [[REG2:%.+]] = \"pycde.PolynomialCompute\"([[REG0]]) {instanceName", ": i32 poly.generate() poly.print() # CHECK-LABEL: hw.module @top # CHECK:", "CHECK: hw.constant 3 # CHECK: hw.constant 4 # CHECK: hw.constant", "= \"PolyComputeForCoeff_62_42_6\", unused_parameter = true}, resultNames = [\"y\"]} : (i32)", "\"\"\"Implement this module for input 'x'.\"\"\" x = mod.x taps", "CHECK-LABEL: === Verilog === poly.print_verilog() # CHECK-LABEL: module PolyComputeForCoeff_62_42_6( #", "-> i32 # CHECK: %example2.y = hw.instance \"example2\" @PolyComputeForCoeff_62_42_6(%example.y) {parameters", "@supercooldevice(%c23_i32) {coefficients = [4, 42], parameters = {}} : (i32)", "Coefficients): class PolynomialCompute: \"\"\"Module to compute ax^3 + bx^2 +", "Coefficients: def __init__(self, coeff): self.coeff = coeff class Polynomial(pycde.System): inputs", "pycde from pycde import (Input, Output, Parameter, module, externmodule, generator,", "= [\"y\"]} : (i32) -> i32 # CHECK: [[REG2:%.+]] =", "CHECK: [shape=record,label=\"{hw.constant\\ni32\\n\\nvalue: 23 : i32}\"]; poly.print() # CHECK-LABEL: hw.module @top()", "{instanceName = \"example\", opNames = [\"x\"], parameters = {coefficients =", "+ bx^2 + cx + d for design-time coefficients\"\"\" #", "%example.y = hw.instance \"example\" @PolyComputeForCoeff_62_42_6(%c23_i32) {parameters = {}} : (i32)", "@PolyComputeForCoeff_62_42_6(%x: i32) -> (%y: i32) # CHECK: hw.constant 62 #", "23) poly = PolynomialCompute(Coefficients([62, 42, 6]))(\"example\", x=x) PolynomialCompute(coefficients=Coefficients([62, 42, 6]))(\"example2\",", "{coefficients = [4, 42], parameters = {}} : (i32) ->", "[\"y\"]} : (i32) -> i32 # CHECK: hw.output [[REG0]] :", "@generator def construct(mod): \"\"\"Implement this module for input 'x'.\"\"\" x", "3, 4, 5]))(\"example2\", x=poly.y) CoolPolynomialCompute([4, 42], x=x) return {\"y\": poly.y}", "polynomial for 'x'. x = Input(types.i32) y = Output(types.int(8 *", "= \"pycde.PolynomialCompute\"(%c23_i32) {instanceName = \"example\", opNames = [\"x\"], parameters =", "= \"example\", opNames = [\"x\"], parameters = {coefficients = {coeff", "label=\"top\"; # CHECK: [shape=record,label=\"{hw.constant\\ni32\\n\\nvalue: 23 : i32}\"]; poly.print() # CHECK-LABEL:", "= \"pycde.PolynomialCompute\"([[REG0]]) {instanceName = \"example2\", opNames = [\"x\"], parameters =", "outputs = [('y', types.i32)] def build(self, top): i32 = types.i32", "# CHECK: hw.constant 3 # CHECK: hw.constant 4 # CHECK:", "poly.print() # CHECK-LABEL: hw.module @top # CHECK: %example.y = hw.instance", "CHECK-LABEL: hw.module @PolyComputeForCoeff_1_2_3_4_5(%x: i32) -> (%y: i32) # CHECK: hw.constant", "taps[-1]} return PolynomialCompute @externmodule(\"supercooldevice\") class CoolPolynomialCompute: x = Input(types.i32) y", "= coeffVal.result else: partialSum = taps[-1] if power == 1:", "1: currPow = x else: x_power = [x for i", "Final output return {\"y\": taps[-1]} return PolynomialCompute @externmodule(\"supercooldevice\") class CoolPolynomialCompute:", "CHECK: hw.constant 2 # CHECK: hw.constant 3 # CHECK: hw.constant", "-> i32 # CHECK: [[REG3:%.+]] = \"pycde.CoolPolynomialCompute\"(%c23_i32) {coefficients = [4,", "power == 0: newPartialSum = coeffVal.result else: partialSum = taps[-1]", "| FileCheck %s from __future__ import annotations import mlir import", "# CHECK: hw.constant 4 # CHECK: hw.constant 5 # CHECK-NOT:", "taps.append(newPartialSum) # Final output return {\"y\": taps[-1]} return PolynomialCompute @externmodule(\"supercooldevice\")", "= Output(types.i32) def __init__(self, coefficients): self.coefficients = coefficients class Coefficients:", "= [62, 42, 6]}, module_name = \"PolyComputeForCoeff_62_42_6\", unused_parameter = true},", "42], x=x) return {\"y\": poly.y} poly = Polynomial() poly.graph() #", "(Input, Output, Parameter, module, externmodule, generator, types, dim) from circt.dialects", "= [1, 2, 3, 4, 5]}, module_name = \"PolyComputeForCoeff_1_2_3_4_5\", unused_parameter", "x = Input(types.i32) y = Output(types.int(8 * 4)) unused_parameter =", "class Polynomial(pycde.System): inputs = [] outputs = [('y', types.i32)] def", "build(self, top): i32 = types.i32 x = hw.ConstantOp.create(i32, 23) poly", "poly = Polynomial() poly.graph() # CHECK-LABEL: digraph \"top\" # CHECK:", "Input(types.i32) y = Output(types.int(8 * 4)) unused_parameter = Parameter(True) def", "= {coefficients = {coeff = [62, 42, 6]}, module_name =", "PolynomialCompute(Coefficients([62, 42, 6]))(\"example\", x=x) PolynomialCompute(coefficients=Coefficients([62, 42, 6]))(\"example2\", x=poly.y) PolynomialCompute(Coefficients([1, 2,", "(i32) -> i32 # CHECK: %pycde.CoolPolynomialCompute.y = hw.instance \"pycde.CoolPolynomialCompute\" @supercooldevice(%c23_i32)", "design-time coefficients\"\"\" # Evaluate polynomial for 'x'. x = Input(types.i32)", "'x'. x = Input(types.i32) y = Output(types.int(8 * 4)) unused_parameter", "(i32) -> i32 # CHECK: [[REG2:%.+]] = \"pycde.PolynomialCompute\"([[REG0]]) {instanceName =", "x=poly.y) CoolPolynomialCompute([4, 42], x=x) return {\"y\": poly.y} poly = Polynomial()", "@PolyComputeForCoeff_62_42_6(%example.y) {parameters = {}} : (i32) -> i32 # CHECK:", "[\"y\"]} : (i32) -> i32 # CHECK: [[REG2:%.+]] = \"pycde.PolynomialCompute\"([[REG0]])", "dim) from circt.dialects import comb, hw @module def PolynomialCompute(coefficients: Coefficients):", "if power == 1: currPow = x else: x_power =", "Polynomial(pycde.System): inputs = [] outputs = [('y', types.i32)] def build(self,", "Verilog ===\") # CHECK-LABEL: === Verilog === poly.print_verilog() # CHECK-LABEL:", "= hw.instance \"example2\" @PolyComputeForCoeff_1_2_3_4_5(%example.y) {parameters = {}} : (i32) ->", "CHECK-LABEL: hw.module @top() -> (%y: i32) # CHECK: [[REG0:%.+]] =", "%s from __future__ import annotations import mlir import pycde from", "hw.constant 5 # CHECK-NOT: hw.module @pycde.PolynomialCompute print(\"\\n\\n=== Verilog ===\") #", "%s 2>&1 | FileCheck %s from __future__ import annotations import", "self.coeff = coeff class Polynomial(pycde.System): inputs = [] outputs =", "for i in range(power)] currPow = comb.MulOp.create(*x_power) newPartialSum = comb.AddOp.create(", "resultNames = [\"y\"]} : (i32) -> i32 # CHECK: hw.output", "hw.instance \"pycde.CoolPolynomialCompute\" @supercooldevice(%c23_i32) {coefficients = [4, 42], parameters = {}}", "[\"x\"], parameters = {coefficients = {coeff = [1, 2, 3,", "\"PolyComputeForCoeff_1_2_3_4_5\", unused_parameter = true}, resultNames = [\"y\"]} : (i32) ->", "-> 'a' order.\"\"\" self.instanceName = name @staticmethod def get_module_name(): return", "resultNames = [\"y\"]} : (i32) -> i32 # CHECK: [[REG1:%.+]]", "taps = list() for power, coeff in enumerate(coefficients.coeff): coeffVal =", "i32 # CHECK: [[REG1:%.+]] = \"pycde.PolynomialCompute\"([[REG0]]) {instanceName = \"example2\", opNames", "is in 'd' -> 'a' order.\"\"\" self.instanceName = name @staticmethod", "CHECK: hw.output [[REG0]] : i32 poly.generate() poly.print() # CHECK-LABEL: hw.module", "i32 # CHECK: %example2.y = hw.instance \"example2\" @PolyComputeForCoeff_62_42_6(%example.y) {parameters =", "import comb, hw @module def PolynomialCompute(coefficients: Coefficients): class PolynomialCompute: \"\"\"Module", "power, coeff in enumerate(coefficients.coeff): coeffVal = hw.ConstantOp.create(types.i32, coeff) if power", "# CHECK: label=\"top\"; # CHECK: [shape=record,label=\"{hw.constant\\ni32\\n\\nvalue: 23 : i32}\"]; poly.print()", "# CHECK: %pycde.CoolPolynomialCompute.y = hw.instance \"pycde.CoolPolynomialCompute\" @supercooldevice(%c23_i32) {coefficients = [4,", "hw @module def PolynomialCompute(coefficients: Coefficients): class PolynomialCompute: \"\"\"Module to compute", "x_power = [x for i in range(power)] currPow = comb.MulOp.create(*x_power)", "CoolPolynomialCompute([4, 42], x=x) return {\"y\": poly.y} poly = Polynomial() poly.graph()", "\"\"\"coefficients is in 'd' -> 'a' order.\"\"\" self.instanceName = name", "# CHECK: hw.constant 1 # CHECK: hw.constant 2 # CHECK:", "[[REG0:%.+]] = \"pycde.PolynomialCompute\"(%c23_i32) {instanceName = \"example\", opNames = [\"x\"], parameters", "hw.module @top # CHECK: %example.y = hw.instance \"example\" @PolyComputeForCoeff_62_42_6(%c23_i32) {parameters", "+ d for design-time coefficients\"\"\" # Evaluate polynomial for 'x'.", "mod.x taps = list() for power, coeff in enumerate(coefficients.coeff): coeffVal", "\"PolyComputeForCoeff_\" + '_'.join( [str(x) for x in coefficients.coeff]) @generator def", "from __future__ import annotations import mlir import pycde from pycde", "= [\"x\"], parameters = {coefficients = {coeff = [62, 42,", "= types.i32 x = hw.ConstantOp.create(i32, 23) poly = PolynomialCompute(Coefficients([62, 42,", "= coefficients class Coefficients: def __init__(self, coeff): self.coeff = coeff", "{}} : (i32) -> i32 # CHECK-LABEL: hw.module @PolyComputeForCoeff_62_42_6(%x: i32)", "for design-time coefficients\"\"\" # Evaluate polynomial for 'x'. x =", "(i32) -> i32 # CHECK: hw.output [[REG0]] : i32 poly.generate()", ": (i32) -> i32 # CHECK: [[REG1:%.+]] = \"pycde.PolynomialCompute\"([[REG0]]) {instanceName", ": i32}\"]; poly.print() # CHECK-LABEL: hw.module @top() -> (%y: i32)", "5 # CHECK-NOT: hw.module @pycde.PolynomialCompute print(\"\\n\\n=== Verilog ===\") # CHECK-LABEL:", "= PolynomialCompute(Coefficients([62, 42, 6]))(\"example\", x=x) PolynomialCompute(coefficients=Coefficients([62, 42, 6]))(\"example2\", x=poly.y) PolynomialCompute(Coefficients([1,", "3 # CHECK: hw.constant 4 # CHECK: hw.constant 5 #", "class CoolPolynomialCompute: x = Input(types.i32) y = Output(types.i32) def __init__(self,", "= taps[-1] if power == 1: currPow = x else:", "# CHECK-NOT: hw.module @pycde.PolynomialCompute print(\"\\n\\n=== Verilog ===\") # CHECK-LABEL: ===", "\"example\", opNames = [\"x\"], parameters = {coefficients = {coeff =", "types.i32 x = hw.ConstantOp.create(i32, 23) poly = PolynomialCompute(Coefficients([62, 42, 6]))(\"example\",", "i32) -> (%y: i32) # CHECK: hw.constant 1 # CHECK:", "unused_parameter = true}, resultNames = [\"y\"]} : (i32) -> i32", "{}} : (i32) -> i32 # CHECK: %example2.y_0 = hw.instance", "= \"PolyComputeForCoeff_1_2_3_4_5\", unused_parameter = true}, resultNames = [\"y\"]} : (i32)", "hw.constant 6 # CHECK-LABEL: hw.module @PolyComputeForCoeff_1_2_3_4_5(%x: i32) -> (%y: i32)", "i32}\"]; poly.print() # CHECK-LABEL: hw.module @top() -> (%y: i32) #", "types.i32)] def build(self, top): i32 = types.i32 x = hw.ConstantOp.create(i32,", "CHECK-LABEL: module PolyComputeForCoeff_62_42_6( # CHECK: input [31:0] x, # CHECK:", "-> i32 # CHECK: hw.output [[REG0]] : i32 poly.generate() poly.print()", "hw.constant 42 # CHECK: hw.constant 6 # CHECK-LABEL: hw.module @PolyComputeForCoeff_1_2_3_4_5(%x:", "for 'x'. x = Input(types.i32) y = Output(types.int(8 * 4))", "power == 1: currPow = x else: x_power = [x", "-> i32 # CHECK: [[REG1:%.+]] = \"pycde.PolynomialCompute\"([[REG0]]) {instanceName = \"example2\",", "= {coefficients = {coeff = [1, 2, 3, 4, 5]},", "for power, coeff in enumerate(coefficients.coeff): coeffVal = hw.ConstantOp.create(types.i32, coeff) if", "# CHECK-LABEL: hw.module @top() -> (%y: i32) # CHECK: [[REG0:%.+]]", "i32) # CHECK: hw.constant 1 # CHECK: hw.constant 2 #", "i in range(power)] currPow = comb.MulOp.create(*x_power) newPartialSum = comb.AddOp.create( partialSum,", "__init__(self, coefficients): self.coefficients = coefficients class Coefficients: def __init__(self, coeff):", "in range(power)] currPow = comb.MulOp.create(*x_power) newPartialSum = comb.AddOp.create( partialSum, comb.MulOp.create(coeffVal,", "{parameters = {}} : (i32) -> i32 # CHECK: %example2.y", "3, 4, 5]}, module_name = \"PolyComputeForCoeff_1_2_3_4_5\", unused_parameter = true}, resultNames", "def __init__(self, coefficients): self.coefficients = coefficients class Coefficients: def __init__(self,", "= {}} : (i32) -> i32 # CHECK-LABEL: hw.module @PolyComputeForCoeff_62_42_6(%x:", "===\") # CHECK-LABEL: === Verilog === poly.print_verilog() # CHECK-LABEL: module", "x = mod.x taps = list() for power, coeff in", "partialSum = taps[-1] if power == 1: currPow = x", "else: x_power = [x for i in range(power)] currPow =", "[] outputs = [('y', types.i32)] def build(self, top): i32 =", "in coefficients.coeff]) @generator def construct(mod): \"\"\"Implement this module for input", "{instanceName = \"example2\", opNames = [\"x\"], parameters = {coefficients =", "coefficients class Coefficients: def __init__(self, coeff): self.coeff = coeff class", "6]}, module_name = \"PolyComputeForCoeff_62_42_6\", unused_parameter = true}, resultNames = [\"y\"]}", "comb, hw @module def PolynomialCompute(coefficients: Coefficients): class PolynomialCompute: \"\"\"Module to", "construct(mod): \"\"\"Implement this module for input 'x'.\"\"\" x = mod.x", "input 'x'.\"\"\" x = mod.x taps = list() for power,", "CHECK: label=\"top\"; # CHECK: [shape=record,label=\"{hw.constant\\ni32\\n\\nvalue: 23 : i32}\"]; poly.print() #", "# CHECK: %example2.y_0 = hw.instance \"example2\" @PolyComputeForCoeff_1_2_3_4_5(%example.y) {parameters = {}}", "2, 3, 4, 5]))(\"example2\", x=poly.y) CoolPolynomialCompute([4, 42], x=x) return {\"y\":", "i32 = types.i32 x = hw.ConstantOp.create(i32, 23) poly = PolynomialCompute(Coefficients([62,", "# CHECK-LABEL: hw.module @PolyComputeForCoeff_1_2_3_4_5(%x: i32) -> (%y: i32) # CHECK:", "hw.instance \"example2\" @PolyComputeForCoeff_1_2_3_4_5(%example.y) {parameters = {}} : (i32) -> i32", "to compute ax^3 + bx^2 + cx + d for", "# CHECK-LABEL: hw.module @top # CHECK: %example.y = hw.instance \"example\"", "[shape=record,label=\"{hw.constant\\ni32\\n\\nvalue: 23 : i32}\"]; poly.print() # CHECK-LABEL: hw.module @top() ->", "= [('y', types.i32)] def build(self, top): i32 = types.i32 x", "= hw.instance \"example\" @PolyComputeForCoeff_62_42_6(%c23_i32) {parameters = {}} : (i32) ->", "circt.dialects import comb, hw @module def PolynomialCompute(coefficients: Coefficients): class PolynomialCompute:", ": (i32) -> i32 # CHECK: %pycde.CoolPolynomialCompute.y = hw.instance \"pycde.CoolPolynomialCompute\"", "print(\"\\n\\n=== Verilog ===\") # CHECK-LABEL: === Verilog === poly.print_verilog() #", "{coefficients = {coeff = [62, 42, 6]}, module_name = \"PolyComputeForCoeff_62_42_6\",", "externmodule, generator, types, dim) from circt.dialects import comb, hw @module", "CHECK: %example2.y_0 = hw.instance \"example2\" @PolyComputeForCoeff_1_2_3_4_5(%example.y) {parameters = {}} :", "Output(types.i32) def __init__(self, coefficients): self.coefficients = coefficients class Coefficients: def", "hw.constant 1 # CHECK: hw.constant 2 # CHECK: hw.constant 3", "[[REG3:%.+]] = \"pycde.CoolPolynomialCompute\"(%c23_i32) {coefficients = [4, 42], opNames = [\"x\"],", "hw.constant 3 # CHECK: hw.constant 4 # CHECK: hw.constant 5", "cx + d for design-time coefficients\"\"\" # Evaluate polynomial for", "{coefficients = [4, 42], opNames = [\"x\"], parameters = {},", "unused_parameter = Parameter(True) def __init__(self, name: str): \"\"\"coefficients is in", "top): i32 = types.i32 x = hw.ConstantOp.create(i32, 23) poly =", "%example2.y = hw.instance \"example2\" @PolyComputeForCoeff_62_42_6(%example.y) {parameters = {}} : (i32)", "= list() for power, coeff in enumerate(coefficients.coeff): coeffVal = hw.ConstantOp.create(types.i32,", "\"pycde.CoolPolynomialCompute\" @supercooldevice(%c23_i32) {coefficients = [4, 42], parameters = {}} :", "class PolynomialCompute: \"\"\"Module to compute ax^3 + bx^2 + cx", "2 # CHECK: hw.constant 3 # CHECK: hw.constant 4 #", "coefficients\"\"\" # Evaluate polynomial for 'x'. x = Input(types.i32) y", "# CHECK: [[REG2:%.+]] = \"pycde.PolynomialCompute\"([[REG0]]) {instanceName = \"example2\", opNames =", ": (i32) -> i32 # CHECK-LABEL: hw.module @PolyComputeForCoeff_62_42_6(%x: i32) ->", "poly.generate() poly.print() # CHECK-LABEL: hw.module @top # CHECK: %example.y =", "CHECK: hw.constant 6 # CHECK-LABEL: hw.module @PolyComputeForCoeff_1_2_3_4_5(%x: i32) -> (%y:", "= Input(types.i32) y = Output(types.i32) def __init__(self, coefficients): self.coefficients =", "42], opNames = [\"x\"], parameters = {}, resultNames = [\"y\"]}", ": (i32) -> i32 # CHECK: %example2.y_0 = hw.instance \"example2\"", "[('y', types.i32)] def build(self, top): i32 = types.i32 x =", "in 'd' -> 'a' order.\"\"\" self.instanceName = name @staticmethod def", "-> (%y: i32) # CHECK: hw.constant 62 # CHECK: hw.constant", "types, dim) from circt.dialects import comb, hw @module def PolynomialCompute(coefficients:", "# Evaluate polynomial for 'x'. x = Input(types.i32) y =", "\"pycde.PolynomialCompute\"(%c23_i32) {instanceName = \"example\", opNames = [\"x\"], parameters = {coefficients", "in enumerate(coefficients.coeff): coeffVal = hw.ConstantOp.create(types.i32, coeff) if power == 0:", "= comb.MulOp.create(*x_power) newPartialSum = comb.AddOp.create( partialSum, comb.MulOp.create(coeffVal, currPow)) taps.append(newPartialSum) #", "# CHECK: hw.constant 42 # CHECK: hw.constant 6 # CHECK-LABEL:", "# CHECK: hw.constant 5 # CHECK-NOT: hw.module @pycde.PolynomialCompute print(\"\\n\\n=== Verilog", "poly.graph() # CHECK-LABEL: digraph \"top\" # CHECK: label=\"top\"; # CHECK:", "= x else: x_power = [x for i in range(power)]", "coeff in enumerate(coefficients.coeff): coeffVal = hw.ConstantOp.create(types.i32, coeff) if power ==", "for x in coefficients.coeff]) @generator def construct(mod): \"\"\"Implement this module", "= \"pycde.CoolPolynomialCompute\"(%c23_i32) {coefficients = [4, 42], opNames = [\"x\"], parameters", "-> i32 # CHECK: %example2.y_0 = hw.instance \"example2\" @PolyComputeForCoeff_1_2_3_4_5(%example.y) {parameters", "<filename>frontends/PyCDE/test/polynomial.py # RUN: %PYTHON% %s 2>&1 | FileCheck %s from", "order.\"\"\" self.instanceName = name @staticmethod def get_module_name(): return \"PolyComputeForCoeff_\" +", "= {coeff = [62, 42, 6]}, module_name = \"PolyComputeForCoeff_62_42_6\", unused_parameter", "y = Output(types.i32) def __init__(self, coefficients): self.coefficients = coefficients class", "6]))(\"example\", x=x) PolynomialCompute(coefficients=Coefficients([62, 42, 6]))(\"example2\", x=poly.y) PolynomialCompute(Coefficients([1, 2, 3, 4,", "i32 # CHECK: [[REG3:%.+]] = \"pycde.CoolPolynomialCompute\"(%c23_i32) {coefficients = [4, 42],", "comb.AddOp.create( partialSum, comb.MulOp.create(coeffVal, currPow)) taps.append(newPartialSum) # Final output return {\"y\":", "# RUN: %PYTHON% %s 2>&1 | FileCheck %s from __future__", "[4, 42], parameters = {}} : (i32) -> i32 #", "poly.print_verilog() # CHECK-LABEL: module PolyComputeForCoeff_62_42_6( # CHECK: input [31:0] x,", "CHECK-LABEL: digraph \"top\" # CHECK: label=\"top\"; # CHECK: [shape=record,label=\"{hw.constant\\ni32\\n\\nvalue: 23", "bx^2 + cx + d for design-time coefficients\"\"\" # Evaluate", "{}} : (i32) -> i32 # CHECK: %example2.y = hw.instance", "resultNames = [\"y\"]} : (i32) -> i32 # CHECK: [[REG3:%.+]]", "[str(x) for x in coefficients.coeff]) @generator def construct(mod): \"\"\"Implement this", "currPow = comb.MulOp.create(*x_power) newPartialSum = comb.AddOp.create( partialSum, comb.MulOp.create(coeffVal, currPow)) taps.append(newPartialSum)", "# CHECK: hw.constant 62 # CHECK: hw.constant 42 # CHECK:", "def PolynomialCompute(coefficients: Coefficients): class PolynomialCompute: \"\"\"Module to compute ax^3 +", "generator, types, dim) from circt.dialects import comb, hw @module def", "def build(self, top): i32 = types.i32 x = hw.ConstantOp.create(i32, 23)", "[\"y\"]} : (i32) -> i32 # CHECK: [[REG1:%.+]] = \"pycde.PolynomialCompute\"([[REG0]])", "42 # CHECK: hw.constant 6 # CHECK-LABEL: hw.module @PolyComputeForCoeff_1_2_3_4_5(%x: i32)", "# CHECK: hw.constant 2 # CHECK: hw.constant 3 # CHECK:", "CHECK: hw.constant 1 # CHECK: hw.constant 2 # CHECK: hw.constant", "i32 # CHECK: [[REG2:%.+]] = \"pycde.PolynomialCompute\"([[REG0]]) {instanceName = \"example2\", opNames", "{parameters = {}} : (i32) -> i32 # CHECK: %pycde.CoolPolynomialCompute.y", "-> i32 # CHECK: [[REG2:%.+]] = \"pycde.PolynomialCompute\"([[REG0]]) {instanceName = \"example2\",", "this module for input 'x'.\"\"\" x = mod.x taps =", "Output(types.int(8 * 4)) unused_parameter = Parameter(True) def __init__(self, name: str):", "opNames = [\"x\"], parameters = {coefficients = {coeff = [1,", "hw.constant 62 # CHECK: hw.constant 42 # CHECK: hw.constant 6", "(%y: i32) # CHECK: [[REG0:%.+]] = \"pycde.PolynomialCompute\"(%c23_i32) {instanceName = \"example\",", "\"example2\" @PolyComputeForCoeff_62_42_6(%example.y) {parameters = {}} : (i32) -> i32 #", "%pycde.CoolPolynomialCompute.y = hw.instance \"pycde.CoolPolynomialCompute\" @supercooldevice(%c23_i32) {coefficients = [4, 42], parameters", "Evaluate polynomial for 'x'. x = Input(types.i32) y = Output(types.int(8", "return PolynomialCompute @externmodule(\"supercooldevice\") class CoolPolynomialCompute: x = Input(types.i32) y =", "return {\"y\": poly.y} poly = Polynomial() poly.graph() # CHECK-LABEL: digraph", "'d' -> 'a' order.\"\"\" self.instanceName = name @staticmethod def get_module_name():", "digraph \"top\" # CHECK: label=\"top\"; # CHECK: [shape=record,label=\"{hw.constant\\ni32\\n\\nvalue: 23 :", "enumerate(coefficients.coeff): coeffVal = hw.ConstantOp.create(types.i32, coeff) if power == 0: newPartialSum", "@pycde.PolynomialCompute print(\"\\n\\n=== Verilog ===\") # CHECK-LABEL: === Verilog === poly.print_verilog()", "[[REG0]] : i32 poly.generate() poly.print() # CHECK-LABEL: hw.module @top #", "42, 6]}, module_name = \"PolyComputeForCoeff_62_42_6\", unused_parameter = true}, resultNames =", "CHECK: [[REG3:%.+]] = \"pycde.CoolPolynomialCompute\"(%c23_i32) {coefficients = [4, 42], opNames =", "=== Verilog === poly.print_verilog() # CHECK-LABEL: module PolyComputeForCoeff_62_42_6( # CHECK:", "= hw.instance \"pycde.CoolPolynomialCompute\" @supercooldevice(%c23_i32) {coefficients = [4, 42], parameters =", "compute ax^3 + bx^2 + cx + d for design-time", "# CHECK: hw.constant 6 # CHECK-LABEL: hw.module @PolyComputeForCoeff_1_2_3_4_5(%x: i32) ->", "= [\"y\"]} : (i32) -> i32 # CHECK: hw.output [[REG0]]", "def __init__(self, name: str): \"\"\"coefficients is in 'd' -> 'a'", "@top() -> (%y: i32) # CHECK: [[REG0:%.+]] = \"pycde.PolynomialCompute\"(%c23_i32) {instanceName", "(i32) -> i32 # CHECK: %example2.y_0 = hw.instance \"example2\" @PolyComputeForCoeff_1_2_3_4_5(%example.y)", "module_name = \"PolyComputeForCoeff_62_42_6\", unused_parameter = true}, resultNames = [\"y\"]} :", "CHECK: [[REG1:%.+]] = \"pycde.PolynomialCompute\"([[REG0]]) {instanceName = \"example2\", opNames = [\"x\"],", "= comb.AddOp.create( partialSum, comb.MulOp.create(coeffVal, currPow)) taps.append(newPartialSum) # Final output return", "RUN: %PYTHON% %s 2>&1 | FileCheck %s from __future__ import", "CHECK: [[REG2:%.+]] = \"pycde.PolynomialCompute\"([[REG0]]) {instanceName = \"example2\", opNames = [\"x\"],", "[[REG2:%.+]] = \"pycde.PolynomialCompute\"([[REG0]]) {instanceName = \"example2\", opNames = [\"x\"], parameters", "[\"y\"]} : (i32) -> i32 # CHECK: [[REG3:%.+]] = \"pycde.CoolPolynomialCompute\"(%c23_i32)", "6 # CHECK-LABEL: hw.module @PolyComputeForCoeff_1_2_3_4_5(%x: i32) -> (%y: i32) #", "import mlir import pycde from pycde import (Input, Output, Parameter,", "i32 # CHECK-LABEL: hw.module @PolyComputeForCoeff_62_42_6(%x: i32) -> (%y: i32) #", "CoolPolynomialCompute: x = Input(types.i32) y = Output(types.i32) def __init__(self, coefficients):", "hw.module @pycde.PolynomialCompute print(\"\\n\\n=== Verilog ===\") # CHECK-LABEL: === Verilog ===", "i32 # CHECK: %pycde.CoolPolynomialCompute.y = hw.instance \"pycde.CoolPolynomialCompute\" @supercooldevice(%c23_i32) {coefficients =", "5]))(\"example2\", x=poly.y) CoolPolynomialCompute([4, 42], x=x) return {\"y\": poly.y} poly =", "from pycde import (Input, Output, Parameter, module, externmodule, generator, types,", ": (i32) -> i32 # CHECK: hw.output [[REG0]] : i32", "CHECK: %pycde.CoolPolynomialCompute.y = hw.instance \"pycde.CoolPolynomialCompute\" @supercooldevice(%c23_i32) {coefficients = [4, 42],", "{}, resultNames = [\"y\"]} : (i32) -> i32 # CHECK:", "= {}} : (i32) -> i32 # CHECK: %pycde.CoolPolynomialCompute.y =", "-> i32 # CHECK-LABEL: hw.module @PolyComputeForCoeff_62_42_6(%x: i32) -> (%y: i32)", "get_module_name(): return \"PolyComputeForCoeff_\" + '_'.join( [str(x) for x in coefficients.coeff])", "= name @staticmethod def get_module_name(): return \"PolyComputeForCoeff_\" + '_'.join( [str(x)", "class Coefficients: def __init__(self, coeff): self.coeff = coeff class Polynomial(pycde.System):", "CHECK: %example.y = hw.instance \"example\" @PolyComputeForCoeff_62_42_6(%c23_i32) {parameters = {}} :", "i32) -> (%y: i32) # CHECK: hw.constant 62 # CHECK:", "Polynomial() poly.graph() # CHECK-LABEL: digraph \"top\" # CHECK: label=\"top\"; #", "i32) # CHECK: hw.constant 62 # CHECK: hw.constant 42 #", "CHECK: hw.constant 62 # CHECK: hw.constant 42 # CHECK: hw.constant", "= coeff class Polynomial(pycde.System): inputs = [] outputs = [('y',", "(i32) -> i32 # CHECK: %example2.y = hw.instance \"example2\" @PolyComputeForCoeff_62_42_6(%example.y)", "x = hw.ConstantOp.create(i32, 23) poly = PolynomialCompute(Coefficients([62, 42, 6]))(\"example\", x=x)", "= {}, resultNames = [\"y\"]} : (i32) -> i32 #", "'x'.\"\"\" x = mod.x taps = list() for power, coeff", "23 : i32}\"]; poly.print() # CHECK-LABEL: hw.module @top() -> (%y:", "= [] outputs = [('y', types.i32)] def build(self, top): i32", "opNames = [\"x\"], parameters = {coefficients = {coeff = [62,", "5]}, module_name = \"PolyComputeForCoeff_1_2_3_4_5\", unused_parameter = true}, resultNames = [\"y\"]}", "{\"y\": taps[-1]} return PolynomialCompute @externmodule(\"supercooldevice\") class CoolPolynomialCompute: x = Input(types.i32)", "4, 5]))(\"example2\", x=poly.y) CoolPolynomialCompute([4, 42], x=x) return {\"y\": poly.y} poly", "x in coefficients.coeff]) @generator def construct(mod): \"\"\"Implement this module for", "__init__(self, coeff): self.coeff = coeff class Polynomial(pycde.System): inputs = []", "# CHECK-LABEL: digraph \"top\" # CHECK: label=\"top\"; # CHECK: [shape=record,label=\"{hw.constant\\ni32\\n\\nvalue:", "coeff) if power == 0: newPartialSum = coeffVal.result else: partialSum", "PolynomialCompute(coefficients=Coefficients([62, 42, 6]))(\"example2\", x=poly.y) PolynomialCompute(Coefficients([1, 2, 3, 4, 5]))(\"example2\", x=poly.y)", "PolynomialCompute(coefficients: Coefficients): class PolynomialCompute: \"\"\"Module to compute ax^3 + bx^2", "coeff class Polynomial(pycde.System): inputs = [] outputs = [('y', types.i32)]", "# CHECK: [[REG0:%.+]] = \"pycde.PolynomialCompute\"(%c23_i32) {instanceName = \"example\", opNames =", "(i32) -> i32 # CHECK: [[REG1:%.+]] = \"pycde.PolynomialCompute\"([[REG0]]) {instanceName =", "{}} : (i32) -> i32 # CHECK: %pycde.CoolPolynomialCompute.y = hw.instance" ]
[ "/usr/bin/env python import arc import sys import os def retrieve(uc,", "for service in retriever]))) # Get all the ExecutionTargets on", "we want to query the LDAP GLUE2 tree arc.Endpoint(\"piff.hep.lu.se\", arc.Endpoint.COMPUTINGINFO,", "finish before we destroy the objects they may use import", "discovered ComputingServices: sys.stdout.write(\"Discovered ComputingServices: %s\\n\"%(\", \".join([service.Name for service in retriever])))", "here we want to wait until all the results arrive", "%d\\n\"%len(targets)) # Query the local infosys (COMPUTINGINFO) of computing elements", "computing elements computing_elements = [ # for piff, we specify", "endpoints) # the constructor of the ComputingServiceRetriever returns immediately sys.stdout.write('\\n')", "we don't specify the type (the InterfaceName) # we let", "all possibilities arc.Endpoint(\"pgs03.grid.upjs.sk\", arc.Endpoint.COMPUTINGINFO) ] retriever2 = retrieve(uc, computing_elements) #", "\".join([service.Name for service in retriever3]))) # wait for all the", "import os def retrieve(uc, endpoints): # The ComputingServiceRetriever needs the", "arc.ComputingServiceRetriever(uc, endpoints) # the constructor of the ComputingServiceRetriever returns immediately", "Services registries = [ # for the index1, we specify", "on these ComputingServices: %d\\n\"%len(targets)) # Query the local infosys (COMPUTINGINFO)", "uc.ProxyPath(\"/tmp/x509up_u%s\" % os.getuid()) uc.CACertificatesDirectory(\"/etc/grid-security/certificates\") # Query two registries (index servers)", "Creating a UserConfig object with the user's proxy # and", "in retriever3]))) # wait for all the background threads to", "the system try all possibilities arc.Endpoint(\"pgs03.grid.upjs.sk\", arc.Endpoint.COMPUTINGINFO) ] retriever2 =", "UserConfig to know which credentials # to use in case", "# for the arc-emi.grid.upjs.sk, we don't specify the type (the", "arc.Endpoint(\"arc-emi.grid.upjs.sk/O=Grid/Mds-Vo-Name=ARC-EMI\", arc.Endpoint.REGISTRY), arc.Endpoint(\"piff.hep.lu.se\", arc.Endpoint.COMPUTINGINFO, \"org.nordugrid.ldapglue2\") ] retriever3 = retrieve(uc, endpoints)", "time: endpoints = [ arc.Endpoint(\"arc-emi.grid.upjs.sk/O=Grid/Mds-Vo-Name=ARC-EMI\", arc.Endpoint.REGISTRY), arc.Endpoint(\"piff.hep.lu.se\", arc.Endpoint.COMPUTINGINFO, \"org.nordugrid.ldapglue2\") ]", "we specify that we want to query the LDAP GLUE2", "for Computing Services registries = [ # for the index1,", "possibilities arc.Endpoint(\"arc-emi.grid.upjs.sk/O=Grid/Mds-Vo-Name=ARC-EMI\", arc.Endpoint.REGISTRY) ] retriever = retrieve(uc, registries) # The", "the trusted CA certificates uc = arc.UserConfig() uc.ProxyPath(\"/tmp/x509up_u%s\" % os.getuid())", "it is an EGIIS service arc.Endpoint(\"index1.nordugrid.org:2135/Mds-Vo-name=NorduGrid,o=grid\", arc.Endpoint.REGISTRY, \"org.nordugrid.ldapegiis\"), # for", "know which credentials # to use in case of HTTPS", "retriever2 = retrieve(uc, computing_elements) # Get all the ExecutionTargets on", "example(): # Creating a UserConfig object with the user's proxy", "case of HTTPS connections retriever = arc.ComputingServiceRetriever(uc, endpoints) # the", "retriever def example(): # Creating a UserConfig object with the", "immediately sys.stdout.write('\\n') sys.stdout.write(\"ComputingServiceRetriever created with the following endpoints:\\n\") for endpoint", "for the arc-emi.grid.upjs.sk, we don't specify the type (the InterfaceName)", "want to wait until all the results arrive sys.stdout.write(\"Waiting for", "= [ arc.Endpoint(\"arc-emi.grid.upjs.sk/O=Grid/Mds-Vo-Name=ARC-EMI\", arc.Endpoint.REGISTRY), arc.Endpoint(\"piff.hep.lu.se\", arc.Endpoint.COMPUTINGINFO, \"org.nordugrid.ldapglue2\") ] retriever3 =", "sys.stdout.write('\\n') sys.stdout.write(\"ComputingServiceRetriever created with the following endpoints:\\n\") for endpoint in", "GLUE2 tree arc.Endpoint(\"piff.hep.lu.se\", arc.Endpoint.COMPUTINGINFO, \"org.nordugrid.ldapglue2\"), # for pgs03, we don't", "system try all possibilities arc.Endpoint(\"pgs03.grid.upjs.sk\", arc.Endpoint.COMPUTINGINFO) ] retriever2 = retrieve(uc,", "threads to finish before we destroy the objects they may", "LDAP GLUE2 tree arc.Endpoint(\"piff.hep.lu.se\", arc.Endpoint.COMPUTINGINFO, \"org.nordugrid.ldapglue2\"), # for pgs03, we", "ComputingServices targets = retriever.GetExecutionTargets() sys.stdout.write(\"Number of ExecutionTargets on these ComputingServices:", "= retrieve(uc, registries) # The retriever acts as a list", "arc.Endpoint(\"pgs03.grid.upjs.sk\", arc.Endpoint.COMPUTINGINFO) ] retriever2 = retrieve(uc, computing_elements) # Get all", "sys.stdout.write(\"%s\\n\"%str(target)) # Query both registries and computing elements at the", "(COMPUTINGINFO) of computing elements computing_elements = [ # for piff,", "UserConfig object with the user's proxy # and the path", "retriever = retrieve(uc, registries) # The retriever acts as a", "created with the following endpoints:\\n\") for endpoint in endpoints: sys.stdout.write(\"-", "(index servers) for Computing Services registries = [ # for", "@atexit.register def wait_exit(): arc.ThreadInitializer().waitExit() # arc.Logger.getRootLogger().addDestination(arc.LogStream(sys.stderr)) # arc.Logger.getRootLogger().setThreshold(arc.DEBUG) # run", "# Query the local infosys (COMPUTINGINFO) of computing elements computing_elements", "= retriever2.GetExecutionTargets() sys.stdout.write(\"The discovered ExecutionTargets:\\n\") for target in targets2: sys.stdout.write(\"%s\\n\"%str(target))", "\"org.nordugrid.ldapglue2\"), # for pgs03, we don't specify the interface, we", "[ arc.Endpoint(\"arc-emi.grid.upjs.sk/O=Grid/Mds-Vo-Name=ARC-EMI\", arc.Endpoint.REGISTRY), arc.Endpoint(\"piff.hep.lu.se\", arc.Endpoint.COMPUTINGINFO, \"org.nordugrid.ldapglue2\") ] retriever3 = retrieve(uc,", "we want to wait until all the results arrive sys.stdout.write(\"Waiting", "CA certificates uc = arc.UserConfig() uc.ProxyPath(\"/tmp/x509up_u%s\" % os.getuid()) uc.CACertificatesDirectory(\"/etc/grid-security/certificates\") #", "# for piff, we specify that we want to query", "\".join([service.Name for service in retriever]))) # Get all the ExecutionTargets", "# The retriever acts as a list containing all the", "of ExecutionTargets on these ComputingServices: %d\\n\"%len(targets)) # Query the local", "] retriever3 = retrieve(uc, endpoints) sys.stdout.write(\"Discovered ComputingServices: %s\\n\"%(\", \".join([service.Name for", "# wait for all the background threads to finish before", "all the ExecutionTargets on these ComputingServices targets = retriever.GetExecutionTargets() sys.stdout.write(\"Number", "endpoints) sys.stdout.write(\"Discovered ComputingServices: %s\\n\"%(\", \".join([service.Name for service in retriever3]))) #", "registries = [ # for the index1, we specify that", "connections retriever = arc.ComputingServiceRetriever(uc, endpoints) # the constructor of the", "all the background threads to finish before we destroy the", "credentials # to use in case of HTTPS connections retriever", "ExecutionTargets on these ComputingServices: %d\\n\"%len(targets)) # Query the local infosys", "return retriever def example(): # Creating a UserConfig object with", "import atexit @atexit.register def wait_exit(): arc.ThreadInitializer().waitExit() # arc.Logger.getRootLogger().addDestination(arc.LogStream(sys.stderr)) # arc.Logger.getRootLogger().setThreshold(arc.DEBUG)", "we let the system to try all possibilities arc.Endpoint(\"arc-emi.grid.upjs.sk/O=Grid/Mds-Vo-Name=ARC-EMI\", arc.Endpoint.REGISTRY)", "the constructor of the ComputingServiceRetriever returns immediately sys.stdout.write('\\n') sys.stdout.write(\"ComputingServiceRetriever created", "retriever3]))) # wait for all the background threads to finish", "of computing elements computing_elements = [ # for piff, we", "before we destroy the objects they may use import atexit", "registries and computing elements at the same time: endpoints =", "# The ComputingServiceRetriever needs the UserConfig to know which credentials", "wait for all the background threads to finish before we", "sys.stdout.write(\"ComputingServiceRetriever created with the following endpoints:\\n\") for endpoint in endpoints:", "Get all the ExecutionTargets on these ComputingServices targets = retriever.GetExecutionTargets()", "endpoints:\\n\") for endpoint in endpoints: sys.stdout.write(\"- %s\\n\"%endpoint.str()) # here we", "we let the system try all possibilities arc.Endpoint(\"pgs03.grid.upjs.sk\", arc.Endpoint.COMPUTINGINFO) ]", "on these ComputingServices targets2 = retriever2.GetExecutionTargets() sys.stdout.write(\"The discovered ExecutionTargets:\\n\") for", "system to try all possibilities arc.Endpoint(\"arc-emi.grid.upjs.sk/O=Grid/Mds-Vo-Name=ARC-EMI\", arc.Endpoint.REGISTRY) ] retriever =", "arc.Endpoint(\"index1.nordugrid.org:2135/Mds-Vo-name=NorduGrid,o=grid\", arc.Endpoint.REGISTRY, \"org.nordugrid.ldapegiis\"), # for the arc-emi.grid.upjs.sk, we don't specify", "try all possibilities arc.Endpoint(\"pgs03.grid.upjs.sk\", arc.Endpoint.COMPUTINGINFO) ] retriever2 = retrieve(uc, computing_elements)", "type (the InterfaceName) # we let the system to try", "ExecutionTargets on these ComputingServices targets = retriever.GetExecutionTargets() sys.stdout.write(\"Number of ExecutionTargets", "targets2 = retriever2.GetExecutionTargets() sys.stdout.write(\"The discovered ExecutionTargets:\\n\") for target in targets2:", "the background threads to finish before we destroy the objects", "we specify that it is an EGIIS service arc.Endpoint(\"index1.nordugrid.org:2135/Mds-Vo-name=NorduGrid,o=grid\", arc.Endpoint.REGISTRY,", "# and the path of the trusted CA certificates uc", "retriever acts as a list containing all the discovered ComputingServices:", "ExecutionTargets on these ComputingServices targets2 = retriever2.GetExecutionTargets() sys.stdout.write(\"The discovered ExecutionTargets:\\n\")", "path of the trusted CA certificates uc = arc.UserConfig() uc.ProxyPath(\"/tmp/x509up_u%s\"", "% os.getuid()) uc.CACertificatesDirectory(\"/etc/grid-security/certificates\") # Query two registries (index servers) for", "piff, we specify that we want to query the LDAP", "local infosys (COMPUTINGINFO) of computing elements computing_elements = [ #", "use in case of HTTPS connections retriever = arc.ComputingServiceRetriever(uc, endpoints)", "for the index1, we specify that it is an EGIIS", "sys.stdout.write(\"The discovered ExecutionTargets:\\n\") for target in targets2: sys.stdout.write(\"%s\\n\"%str(target)) # Query", "arc import sys import os def retrieve(uc, endpoints): # The", "use import atexit @atexit.register def wait_exit(): arc.ThreadInitializer().waitExit() # arc.Logger.getRootLogger().addDestination(arc.LogStream(sys.stderr)) #", "background threads to finish before we destroy the objects they", "index1, we specify that it is an EGIIS service arc.Endpoint(\"index1.nordugrid.org:2135/Mds-Vo-name=NorduGrid,o=grid\",", "of HTTPS connections retriever = arc.ComputingServiceRetriever(uc, endpoints) # the constructor", "list containing all the discovered ComputingServices: sys.stdout.write(\"Discovered ComputingServices: %s\\n\"%(\", \".join([service.Name", "Computing Services registries = [ # for the index1, we", "ExecutionTargets:\\n\") for target in targets2: sys.stdout.write(\"%s\\n\"%str(target)) # Query both registries", "possibilities arc.Endpoint(\"pgs03.grid.upjs.sk\", arc.Endpoint.COMPUTINGINFO) ] retriever2 = retrieve(uc, computing_elements) # Get", "the same time: endpoints = [ arc.Endpoint(\"arc-emi.grid.upjs.sk/O=Grid/Mds-Vo-Name=ARC-EMI\", arc.Endpoint.REGISTRY), arc.Endpoint(\"piff.hep.lu.se\", arc.Endpoint.COMPUTINGINFO,", "registries (index servers) for Computing Services registries = [ #", "results...\\n\") retriever.wait() return retriever def example(): # Creating a UserConfig", "service in retriever3]))) # wait for all the background threads", "[ # for piff, we specify that we want to", "target in targets2: sys.stdout.write(\"%s\\n\"%str(target)) # Query both registries and computing", "acts as a list containing all the discovered ComputingServices: sys.stdout.write(\"Discovered", "(the InterfaceName) # we let the system to try all", "in case of HTTPS connections retriever = arc.ComputingServiceRetriever(uc, endpoints) #", "The retriever acts as a list containing all the discovered", "sys.stdout.write(\"Number of ExecutionTargets on these ComputingServices: %d\\n\"%len(targets)) # Query the", "following endpoints:\\n\") for endpoint in endpoints: sys.stdout.write(\"- %s\\n\"%endpoint.str()) # here", "may use import atexit @atexit.register def wait_exit(): arc.ThreadInitializer().waitExit() # arc.Logger.getRootLogger().addDestination(arc.LogStream(sys.stderr))", "service arc.Endpoint(\"index1.nordugrid.org:2135/Mds-Vo-name=NorduGrid,o=grid\", arc.Endpoint.REGISTRY, \"org.nordugrid.ldapegiis\"), # for the arc-emi.grid.upjs.sk, we don't", "uc = arc.UserConfig() uc.ProxyPath(\"/tmp/x509up_u%s\" % os.getuid()) uc.CACertificatesDirectory(\"/etc/grid-security/certificates\") # Query two", "the ExecutionTargets on these ComputingServices targets = retriever.GetExecutionTargets() sys.stdout.write(\"Number of", "infosys (COMPUTINGINFO) of computing elements computing_elements = [ # for", "elements computing_elements = [ # for piff, we specify that", "arc.ThreadInitializer().waitExit() # arc.Logger.getRootLogger().addDestination(arc.LogStream(sys.stderr)) # arc.Logger.getRootLogger().setThreshold(arc.DEBUG) # run the example example()", "] retriever2 = retrieve(uc, computing_elements) # Get all the ExecutionTargets", "want to query the LDAP GLUE2 tree arc.Endpoint(\"piff.hep.lu.se\", arc.Endpoint.COMPUTINGINFO, \"org.nordugrid.ldapglue2\"),", "ComputingServices: %d\\n\"%len(targets)) # Query the local infosys (COMPUTINGINFO) of computing", "in endpoints: sys.stdout.write(\"- %s\\n\"%endpoint.str()) # here we want to wait", "# the constructor of the ComputingServiceRetriever returns immediately sys.stdout.write('\\n') sys.stdout.write(\"ComputingServiceRetriever", "Query the local infosys (COMPUTINGINFO) of computing elements computing_elements =", "%s\\n\"%(\", \".join([service.Name for service in retriever3]))) # wait for all", "user's proxy # and the path of the trusted CA", "arc.Endpoint(\"arc-emi.grid.upjs.sk/O=Grid/Mds-Vo-Name=ARC-EMI\", arc.Endpoint.REGISTRY) ] retriever = retrieve(uc, registries) # The retriever", "retriever]))) # Get all the ExecutionTargets on these ComputingServices targets", "endpoint in endpoints: sys.stdout.write(\"- %s\\n\"%endpoint.str()) # here we want to", "object with the user's proxy # and the path of", "uc.CACertificatesDirectory(\"/etc/grid-security/certificates\") # Query two registries (index servers) for Computing Services", "the ExecutionTargets on these ComputingServices targets2 = retriever2.GetExecutionTargets() sys.stdout.write(\"The discovered", "of the trusted CA certificates uc = arc.UserConfig() uc.ProxyPath(\"/tmp/x509up_u%s\" %", "containing all the discovered ComputingServices: sys.stdout.write(\"Discovered ComputingServices: %s\\n\"%(\", \".join([service.Name for", "in retriever]))) # Get all the ExecutionTargets on these ComputingServices", "retrieve(uc, computing_elements) # Get all the ExecutionTargets on these ComputingServices", "trusted CA certificates uc = arc.UserConfig() uc.ProxyPath(\"/tmp/x509up_u%s\" % os.getuid()) uc.CACertificatesDirectory(\"/etc/grid-security/certificates\")", "that it is an EGIIS service arc.Endpoint(\"index1.nordugrid.org:2135/Mds-Vo-name=NorduGrid,o=grid\", arc.Endpoint.REGISTRY, \"org.nordugrid.ldapegiis\"), #", "until all the results arrive sys.stdout.write(\"Waiting for the results...\\n\") retriever.wait()", "arrive sys.stdout.write(\"Waiting for the results...\\n\") retriever.wait() return retriever def example():", "# for pgs03, we don't specify the interface, we let", "# Get all the ExecutionTargets on these ComputingServices targets =", "on these ComputingServices targets = retriever.GetExecutionTargets() sys.stdout.write(\"Number of ExecutionTargets on", "the user's proxy # and the path of the trusted", "is an EGIIS service arc.Endpoint(\"index1.nordugrid.org:2135/Mds-Vo-name=NorduGrid,o=grid\", arc.Endpoint.REGISTRY, \"org.nordugrid.ldapegiis\"), # for the", "# Get all the ExecutionTargets on these ComputingServices targets2 =", "specify that it is an EGIIS service arc.Endpoint(\"index1.nordugrid.org:2135/Mds-Vo-name=NorduGrid,o=grid\", arc.Endpoint.REGISTRY, \"org.nordugrid.ldapegiis\"),", "ComputingServices: sys.stdout.write(\"Discovered ComputingServices: %s\\n\"%(\", \".join([service.Name for service in retriever]))) #", "= retriever.GetExecutionTargets() sys.stdout.write(\"Number of ExecutionTargets on these ComputingServices: %d\\n\"%len(targets)) #", "HTTPS connections retriever = arc.ComputingServiceRetriever(uc, endpoints) # the constructor of", "elements at the same time: endpoints = [ arc.Endpoint(\"arc-emi.grid.upjs.sk/O=Grid/Mds-Vo-Name=ARC-EMI\", arc.Endpoint.REGISTRY),", "these ComputingServices: %d\\n\"%len(targets)) # Query the local infosys (COMPUTINGINFO) of", "sys import os def retrieve(uc, endpoints): # The ComputingServiceRetriever needs", "= [ # for the index1, we specify that it", "retrieve(uc, registries) # The retriever acts as a list containing", "ComputingServiceRetriever needs the UserConfig to know which credentials # to", "arc.Endpoint(\"piff.hep.lu.se\", arc.Endpoint.COMPUTINGINFO, \"org.nordugrid.ldapglue2\"), # for pgs03, we don't specify the", "= arc.ComputingServiceRetriever(uc, endpoints) # the constructor of the ComputingServiceRetriever returns", "ComputingServices: %s\\n\"%(\", \".join([service.Name for service in retriever3]))) # wait for", "arc-emi.grid.upjs.sk, we don't specify the type (the InterfaceName) # we", "to finish before we destroy the objects they may use", "retrieve(uc, endpoints): # The ComputingServiceRetriever needs the UserConfig to know", "The ComputingServiceRetriever needs the UserConfig to know which credentials #", "retrieve(uc, endpoints) sys.stdout.write(\"Discovered ComputingServices: %s\\n\"%(\", \".join([service.Name for service in retriever3])))", "wait until all the results arrive sys.stdout.write(\"Waiting for the results...\\n\")", "endpoints): # The ComputingServiceRetriever needs the UserConfig to know which", "all the ExecutionTargets on these ComputingServices targets2 = retriever2.GetExecutionTargets() sys.stdout.write(\"The", "and computing elements at the same time: endpoints = [", "def example(): # Creating a UserConfig object with the user's", "os.getuid()) uc.CACertificatesDirectory(\"/etc/grid-security/certificates\") # Query two registries (index servers) for Computing", "arc.Endpoint.REGISTRY, \"org.nordugrid.ldapegiis\"), # for the arc-emi.grid.upjs.sk, we don't specify the", "don't specify the interface, we let the system try all", "ComputingServiceRetriever returns immediately sys.stdout.write('\\n') sys.stdout.write(\"ComputingServiceRetriever created with the following endpoints:\\n\")", "arc.Endpoint.REGISTRY) ] retriever = retrieve(uc, registries) # The retriever acts", "the results arrive sys.stdout.write(\"Waiting for the results...\\n\") retriever.wait() return retriever", "sys.stdout.write(\"Discovered ComputingServices: %s\\n\"%(\", \".join([service.Name for service in retriever3]))) # wait", "pgs03, we don't specify the interface, we let the system", "these ComputingServices targets2 = retriever2.GetExecutionTargets() sys.stdout.write(\"The discovered ExecutionTargets:\\n\") for target", "these ComputingServices targets = retriever.GetExecutionTargets() sys.stdout.write(\"Number of ExecutionTargets on these", "to wait until all the results arrive sys.stdout.write(\"Waiting for the", "tree arc.Endpoint(\"piff.hep.lu.se\", arc.Endpoint.COMPUTINGINFO, \"org.nordugrid.ldapglue2\"), # for pgs03, we don't specify", "# here we want to wait until all the results", "= [ # for piff, we specify that we want", "let the system to try all possibilities arc.Endpoint(\"arc-emi.grid.upjs.sk/O=Grid/Mds-Vo-Name=ARC-EMI\", arc.Endpoint.REGISTRY) ]", "an EGIIS service arc.Endpoint(\"index1.nordugrid.org:2135/Mds-Vo-name=NorduGrid,o=grid\", arc.Endpoint.REGISTRY, \"org.nordugrid.ldapegiis\"), # for the arc-emi.grid.upjs.sk,", "retriever2.GetExecutionTargets() sys.stdout.write(\"The discovered ExecutionTargets:\\n\") for target in targets2: sys.stdout.write(\"%s\\n\"%str(target)) #", "proxy # and the path of the trusted CA certificates", "retriever.GetExecutionTargets() sys.stdout.write(\"Number of ExecutionTargets on these ComputingServices: %d\\n\"%len(targets)) # Query", "with the following endpoints:\\n\") for endpoint in endpoints: sys.stdout.write(\"- %s\\n\"%endpoint.str())", "in targets2: sys.stdout.write(\"%s\\n\"%str(target)) # Query both registries and computing elements", "the UserConfig to know which credentials # to use in", "specify that we want to query the LDAP GLUE2 tree", "# for the index1, we specify that it is an", "the following endpoints:\\n\") for endpoint in endpoints: sys.stdout.write(\"- %s\\n\"%endpoint.str()) #", "query the LDAP GLUE2 tree arc.Endpoint(\"piff.hep.lu.se\", arc.Endpoint.COMPUTINGINFO, \"org.nordugrid.ldapglue2\"), # for", "endpoints = [ arc.Endpoint(\"arc-emi.grid.upjs.sk/O=Grid/Mds-Vo-Name=ARC-EMI\", arc.Endpoint.REGISTRY), arc.Endpoint(\"piff.hep.lu.se\", arc.Endpoint.COMPUTINGINFO, \"org.nordugrid.ldapglue2\") ] retriever3", "the interface, we let the system try all possibilities arc.Endpoint(\"pgs03.grid.upjs.sk\",", "same time: endpoints = [ arc.Endpoint(\"arc-emi.grid.upjs.sk/O=Grid/Mds-Vo-Name=ARC-EMI\", arc.Endpoint.REGISTRY), arc.Endpoint(\"piff.hep.lu.se\", arc.Endpoint.COMPUTINGINFO, \"org.nordugrid.ldapglue2\")", "targets = retriever.GetExecutionTargets() sys.stdout.write(\"Number of ExecutionTargets on these ComputingServices: %d\\n\"%len(targets))", "\"org.nordugrid.ldapglue2\") ] retriever3 = retrieve(uc, endpoints) sys.stdout.write(\"Discovered ComputingServices: %s\\n\"%(\", \".join([service.Name", "let the system try all possibilities arc.Endpoint(\"pgs03.grid.upjs.sk\", arc.Endpoint.COMPUTINGINFO) ] retriever2", "sys.stdout.write(\"Waiting for the results...\\n\") retriever.wait() return retriever def example(): #", "both registries and computing elements at the same time: endpoints", "EGIIS service arc.Endpoint(\"index1.nordugrid.org:2135/Mds-Vo-name=NorduGrid,o=grid\", arc.Endpoint.REGISTRY, \"org.nordugrid.ldapegiis\"), # for the arc-emi.grid.upjs.sk, we", "arc.Endpoint.COMPUTINGINFO, \"org.nordugrid.ldapglue2\"), # for pgs03, we don't specify the interface,", "# we let the system to try all possibilities arc.Endpoint(\"arc-emi.grid.upjs.sk/O=Grid/Mds-Vo-Name=ARC-EMI\",", "Get all the ExecutionTargets on these ComputingServices targets2 = retriever2.GetExecutionTargets()", "[ # for the index1, we specify that it is", "ComputingServices targets2 = retriever2.GetExecutionTargets() sys.stdout.write(\"The discovered ExecutionTargets:\\n\") for target in", "for the results...\\n\") retriever.wait() return retriever def example(): # Creating", "# Creating a UserConfig object with the user's proxy #", "# to use in case of HTTPS connections retriever =", "don't specify the type (the InterfaceName) # we let the", "arc.Endpoint.COMPUTINGINFO, \"org.nordugrid.ldapglue2\") ] retriever3 = retrieve(uc, endpoints) sys.stdout.write(\"Discovered ComputingServices: %s\\n\"%(\",", "atexit @atexit.register def wait_exit(): arc.ThreadInitializer().waitExit() # arc.Logger.getRootLogger().addDestination(arc.LogStream(sys.stderr)) # arc.Logger.getRootLogger().setThreshold(arc.DEBUG) #", "retriever.wait() return retriever def example(): # Creating a UserConfig object", "import arc import sys import os def retrieve(uc, endpoints): #", "for target in targets2: sys.stdout.write(\"%s\\n\"%str(target)) # Query both registries and", "service in retriever]))) # Get all the ExecutionTargets on these", "#! /usr/bin/env python import arc import sys import os def", "to try all possibilities arc.Endpoint(\"arc-emi.grid.upjs.sk/O=Grid/Mds-Vo-Name=ARC-EMI\", arc.Endpoint.REGISTRY) ] retriever = retrieve(uc,", "the local infosys (COMPUTINGINFO) of computing elements computing_elements = [", "certificates uc = arc.UserConfig() uc.ProxyPath(\"/tmp/x509up_u%s\" % os.getuid()) uc.CACertificatesDirectory(\"/etc/grid-security/certificates\") # Query", "python import arc import sys import os def retrieve(uc, endpoints):", "we don't specify the interface, we let the system try", "retriever3 = retrieve(uc, endpoints) sys.stdout.write(\"Discovered ComputingServices: %s\\n\"%(\", \".join([service.Name for service", "computing_elements) # Get all the ExecutionTargets on these ComputingServices targets2", "objects they may use import atexit @atexit.register def wait_exit(): arc.ThreadInitializer().waitExit()", "needs the UserConfig to know which credentials # to use", "to query the LDAP GLUE2 tree arc.Endpoint(\"piff.hep.lu.se\", arc.Endpoint.COMPUTINGINFO, \"org.nordugrid.ldapglue2\"), #", "endpoints: sys.stdout.write(\"- %s\\n\"%endpoint.str()) # here we want to wait until", "# Query both registries and computing elements at the same", "as a list containing all the discovered ComputingServices: sys.stdout.write(\"Discovered ComputingServices:", "os def retrieve(uc, endpoints): # The ComputingServiceRetriever needs the UserConfig", "returns immediately sys.stdout.write('\\n') sys.stdout.write(\"ComputingServiceRetriever created with the following endpoints:\\n\") for", "%s\\n\"%(\", \".join([service.Name for service in retriever]))) # Get all the", "Query both registries and computing elements at the same time:", "the index1, we specify that it is an EGIIS service", "which credentials # to use in case of HTTPS connections", "with the user's proxy # and the path of the", "results arrive sys.stdout.write(\"Waiting for the results...\\n\") retriever.wait() return retriever def", "the arc-emi.grid.upjs.sk, we don't specify the type (the InterfaceName) #", "interface, we let the system try all possibilities arc.Endpoint(\"pgs03.grid.upjs.sk\", arc.Endpoint.COMPUTINGINFO)", "all the discovered ComputingServices: sys.stdout.write(\"Discovered ComputingServices: %s\\n\"%(\", \".join([service.Name for service", "and the path of the trusted CA certificates uc =", "] retriever = retrieve(uc, registries) # The retriever acts as", "at the same time: endpoints = [ arc.Endpoint(\"arc-emi.grid.upjs.sk/O=Grid/Mds-Vo-Name=ARC-EMI\", arc.Endpoint.REGISTRY), arc.Endpoint(\"piff.hep.lu.se\",", "import sys import os def retrieve(uc, endpoints): # The ComputingServiceRetriever", "try all possibilities arc.Endpoint(\"arc-emi.grid.upjs.sk/O=Grid/Mds-Vo-Name=ARC-EMI\", arc.Endpoint.REGISTRY) ] retriever = retrieve(uc, registries)", "for piff, we specify that we want to query the", "we destroy the objects they may use import atexit @atexit.register", "to use in case of HTTPS connections retriever = arc.ComputingServiceRetriever(uc,", "the discovered ComputingServices: sys.stdout.write(\"Discovered ComputingServices: %s\\n\"%(\", \".join([service.Name for service in", "all possibilities arc.Endpoint(\"arc-emi.grid.upjs.sk/O=Grid/Mds-Vo-Name=ARC-EMI\", arc.Endpoint.REGISTRY) ] retriever = retrieve(uc, registries) #", "= arc.UserConfig() uc.ProxyPath(\"/tmp/x509up_u%s\" % os.getuid()) uc.CACertificatesDirectory(\"/etc/grid-security/certificates\") # Query two registries", "for service in retriever3]))) # wait for all the background", "the objects they may use import atexit @atexit.register def wait_exit():", "= retrieve(uc, endpoints) sys.stdout.write(\"Discovered ComputingServices: %s\\n\"%(\", \".join([service.Name for service in", "def retrieve(uc, endpoints): # The ComputingServiceRetriever needs the UserConfig to", "computing_elements = [ # for piff, we specify that we", "arc.Endpoint(\"piff.hep.lu.se\", arc.Endpoint.COMPUTINGINFO, \"org.nordugrid.ldapglue2\") ] retriever3 = retrieve(uc, endpoints) sys.stdout.write(\"Discovered ComputingServices:", "InterfaceName) # we let the system to try all possibilities", "for endpoint in endpoints: sys.stdout.write(\"- %s\\n\"%endpoint.str()) # here we want", "\"org.nordugrid.ldapegiis\"), # for the arc-emi.grid.upjs.sk, we don't specify the type", "retriever = arc.ComputingServiceRetriever(uc, endpoints) # the constructor of the ComputingServiceRetriever", "arc.Endpoint.COMPUTINGINFO) ] retriever2 = retrieve(uc, computing_elements) # Get all the", "Query two registries (index servers) for Computing Services registries =", "sys.stdout.write(\"- %s\\n\"%endpoint.str()) # here we want to wait until all", "the system to try all possibilities arc.Endpoint(\"arc-emi.grid.upjs.sk/O=Grid/Mds-Vo-Name=ARC-EMI\", arc.Endpoint.REGISTRY) ] retriever", "destroy the objects they may use import atexit @atexit.register def", "a list containing all the discovered ComputingServices: sys.stdout.write(\"Discovered ComputingServices: %s\\n\"%(\",", "arc.Endpoint.REGISTRY), arc.Endpoint(\"piff.hep.lu.se\", arc.Endpoint.COMPUTINGINFO, \"org.nordugrid.ldapglue2\") ] retriever3 = retrieve(uc, endpoints) sys.stdout.write(\"Discovered", "def wait_exit(): arc.ThreadInitializer().waitExit() # arc.Logger.getRootLogger().addDestination(arc.LogStream(sys.stderr)) # arc.Logger.getRootLogger().setThreshold(arc.DEBUG) # run the", "for pgs03, we don't specify the interface, we let the", "specify the type (the InterfaceName) # we let the system", "to know which credentials # to use in case of", "specify the interface, we let the system try all possibilities", "arc.UserConfig() uc.ProxyPath(\"/tmp/x509up_u%s\" % os.getuid()) uc.CACertificatesDirectory(\"/etc/grid-security/certificates\") # Query two registries (index", "all the results arrive sys.stdout.write(\"Waiting for the results...\\n\") retriever.wait() return", "= retrieve(uc, computing_elements) # Get all the ExecutionTargets on these", "for all the background threads to finish before we destroy", "a UserConfig object with the user's proxy # and the", "the LDAP GLUE2 tree arc.Endpoint(\"piff.hep.lu.se\", arc.Endpoint.COMPUTINGINFO, \"org.nordugrid.ldapglue2\"), # for pgs03,", "%s\\n\"%endpoint.str()) # here we want to wait until all the", "the path of the trusted CA certificates uc = arc.UserConfig()", "targets2: sys.stdout.write(\"%s\\n\"%str(target)) # Query both registries and computing elements at", "ComputingServices: %s\\n\"%(\", \".join([service.Name for service in retriever]))) # Get all", "servers) for Computing Services registries = [ # for the", "the ComputingServiceRetriever returns immediately sys.stdout.write('\\n') sys.stdout.write(\"ComputingServiceRetriever created with the following", "constructor of the ComputingServiceRetriever returns immediately sys.stdout.write('\\n') sys.stdout.write(\"ComputingServiceRetriever created with", "# Query two registries (index servers) for Computing Services registries", "the type (the InterfaceName) # we let the system to", "of the ComputingServiceRetriever returns immediately sys.stdout.write('\\n') sys.stdout.write(\"ComputingServiceRetriever created with the", "wait_exit(): arc.ThreadInitializer().waitExit() # arc.Logger.getRootLogger().addDestination(arc.LogStream(sys.stderr)) # arc.Logger.getRootLogger().setThreshold(arc.DEBUG) # run the example", "that we want to query the LDAP GLUE2 tree arc.Endpoint(\"piff.hep.lu.se\",", "registries) # The retriever acts as a list containing all", "discovered ExecutionTargets:\\n\") for target in targets2: sys.stdout.write(\"%s\\n\"%str(target)) # Query both", "computing elements at the same time: endpoints = [ arc.Endpoint(\"arc-emi.grid.upjs.sk/O=Grid/Mds-Vo-Name=ARC-EMI\",", "they may use import atexit @atexit.register def wait_exit(): arc.ThreadInitializer().waitExit() #", "sys.stdout.write(\"Discovered ComputingServices: %s\\n\"%(\", \".join([service.Name for service in retriever]))) # Get", "the results...\\n\") retriever.wait() return retriever def example(): # Creating a", "two registries (index servers) for Computing Services registries = [" ]
[ "tried to change private viewability of exploration %s ' 'but", "if activity_rights is None: return False elif activity_rights.is_published(): return bool(", "unpublish the activity. \"\"\" committer_id = committer.user_id activity_rights = _get_activity_rights(activity_type,", "logging from constants import constants from core.domain import activity_services from", "subscription_services.subscribe_to_exploration( assignee_id, exploration_id) def release_ownership_of_exploration(committer, exploration_id): \"\"\"Releases ownership of the", "Exception( 'This user already can translate this %s.' % activity_type)", "[{ 'cmd': CMD_RELEASE_OWNERSHIP, }] _save_activity_rights( committer_id, activity_rights, activity_type, '%s ownership", "2.0 (the \"License\"); # you may not use this file", "Exception( 'Trying to change viewability status of this exploration to", "an activity editor. \"\"\" return bool(user_id in self.editor_ids) def is_translator(self,", "Returns: ActivityRights. The rights object for the collection. Raises: EntityNotFoundError.", "The committer does not have release rights. \"\"\" committer_id =", "rights object for the collection. Raises: EntityNotFoundError. The collection with", "ROLE_TRANSLATOR: if (activity_rights.is_editor(assignee_id) or activity_rights.is_translator(assignee_id) or activity_rights.is_owner(assignee_id)): raise Exception( 'This", "[] for model in exp_rights_models: if model is None: exp_models_list.append(None)", "a clone of another exploration. \"\"\" exploration_rights = get_exploration_rights(exploration_id) return", "The type of activity. Possible values: constants.ACTIVITY_TYPE_EXPLORATION constants.ACTIVITY_TYPE_COLLECTION activity_rights: ActivityRights.", "raise Exception('Invalid role: %s' % new_role) commit_message = 'Changed role", "action. assignee_id: str. ID of the user whose role is", "str. ID of the collection. strict: bool. Whether to raise", "viewable_if_private=activity_rights_model.viewable_if_private, first_published_msec=activity_rights_model.first_published_msec ) def _save_activity_rights( committer_id, activity_rights, activity_type, commit_message, commit_cmds):", "is public. \"\"\" exploration_rights = get_exploration_rights(exploration_id) return exploration_rights.status == ACTIVITY_STATUS_PUBLIC", "True elif (activity_rights.is_private() and (role_services.ACTION_DELETE_OWNED_PRIVATE_ACTIVITY in user.actions) and activity_rights.is_owner(user.user_id)): return", "status of this exploration cannot be changed.') old_viewable_if_private = exploration_rights.viewable_if_private", "model is None: exp_models_list.append(None) else: exp_models_list.append( get_activity_rights_from_model( model, constants.ACTIVITY_TYPE_EXPLORATION)) return", "edit this activity. \"\"\" if activity_rights is None: return False", "for the rights/publication status of an activity (an exploration or", "allows a private exploration to be viewed by anyone with", "owner_ids=collection_rights.owner_ids, editor_ids=collection_rights.editor_ids, translator_ids=collection_rights.translator_ids, viewer_ids=collection_rights.viewer_ids, community_owned=collection_rights.community_owned, status=collection_rights.status, viewable_if_private=collection_rights.viewable_if_private, first_published_msec=collection_rights.first_published_msec ).commit(committer_id, 'Created", "assignee_id, exploration_id) def release_ownership_of_exploration(committer, exploration_id): \"\"\"Releases ownership of the given", "commit_cmds) def _update_exploration_summary(activity_rights): \"\"\"Updates the exploration summary for the activity", "None) def _update_activity_summary(activity_type, activity_rights): \"\"\"Updates the activity summary for the", "%ss can be edited by anyone.' % activity_type) activity_rights.editor_ids.append(assignee_id) if", "\"\"\"Checks whether the user can edit given activity. Args: user:", "committer_id = committer.user_id exploration_rights = get_exploration_rights(exploration_id) # The user who", "collection_id is not found in the datastore. \"\"\" model =", "collection_id): \"\"\"Unpublishes the given collection. Args: committer: UserActionsInfo. UserActionsInfo object", "in activity_rights.viewer_ids: activity_rights.viewer_ids.remove(assignee_id) old_role = ROLE_VIEWER elif new_role == ROLE_TRANSLATOR:", "return True return False def _assign_role( committer, assignee_id, new_role, activity_id,", "status=collection_rights.status, viewable_if_private=collection_rights.viewable_if_private, first_published_msec=collection_rights.first_published_msec ).commit(committer_id, 'Created new collection', commit_cmds) subscription_services.subscribe_to_collection(committer_id, collection_id)", "if role_services.ACTION_PUBLISH_ANY_ACTIVITY in user.actions: return True if role_services.ACTION_PUBLISH_OWNED_ACTIVITY in user.actions:", "\"\"\"Unpublishes the given exploration. Args: committer: UserActionsInfo. UserActionsInfo object for", "if assignee_id in activity_rights.editor_ids: activity_rights.editor_ids.remove(assignee_id) old_role = ROLE_EDITOR if assignee_id", "can already view the activity. Exception. The activity is already", "of activity %s ' 'but was refused permission.' % (", "\"\"\"Publishes the given collection. It is the responsibility of the", "viewable_if_private=False, first_published_msec=None): self.id = exploration_id self.owner_ids = owner_ids self.editor_ids =", "owners, editors, translators and viewers lists overlap, or if a", "exploration's rights object. If viewable_if_private is True, this allows a", "(self.owner_ids or self.editor_ids or self.translator_ids or self.viewer_ids): raise utils.ValidationError( 'Community-owned", "Oppia Authors. All Rights Reserved. # # Licensed under the", "the given activity. \"\"\" from core.domain import collection_services collection_services.update_collection_summary( activity_rights.id,", "since the Epoch. \"\"\" activity_rights = _get_activity_rights(activity_type, activity_id) commit_cmds =", "ROLE_EDITOR]: subscription_services.subscribe_to_collection( assignee_id, collection_id) def release_ownership_of_collection(committer, collection_id): \"\"\"Releases ownership of", "exploration_rights = ActivityRights( exploration_id, [committer_id], [], [], []) commit_cmds =", "return get_activity_rights_from_model( model, constants.ACTIVITY_TYPE_EXPLORATION) def get_multiple_exploration_rights_by_ids(exp_ids): \"\"\"Returns a list of", "the responsibility of the caller to check that the collection", "is not already set before updating it. Args: activity_type: str.", "to the datastore. Args: committer_id: str. ID of the committer.", "activity. Returns: bool. Whether the user can release ownership for", "or activity_rights.is_editor(user.user_id) or activity_rights.is_translator(user.user_id)): return True if (activity_rights.community_owned or (role_services.ACTION_EDIT_ANY_ACTIVITY", "== constants.ACTIVITY_TYPE_EXPLORATION: _update_exploration_summary(activity_rights) elif activity_type == constants.ACTIVITY_TYPE_COLLECTION: _update_collection_summary(activity_rights) def update_activity_first_published_msec(", "return None return get_activity_rights_from_model( model, constants.ACTIVITY_TYPE_EXPLORATION) def get_multiple_exploration_rights_by_ids(exp_ids): \"\"\"Returns a", "self.viewer_ids): raise utils.ValidationError( 'Community-owned explorations should have no owners, '", "with the link. Args: committer: UserActionsInfo. UserActionsInfo object for the", "[], []) commit_cmds = [{'cmd': CMD_CREATE_NEW}] exp_models.ExplorationRightsModel( id=exploration_rights.id, owner_ids=exploration_rights.owner_ids, editor_ids=exploration_rights.editor_ids,", "permission to perform change action. Exception. If the viewable_if_private property", "License for the specific language governing permissions and # limitations", "import models import feconf import utils current_user_services = models.Registry.import_current_user_services() (collection_models,", "update action. activity_id: str. ID of the activity. activity_type: str.", "is not found in the datastore. \"\"\" model = collection_models.CollectionRightsModel.get(", "the community. Args: committer: UserActionsInfo. UserActionsInfo object for the committer.", "given user to the given role and subscribes the assignee", "of associated activity. Args: activity_rights: ActivityRights. The rights object for", "Reserved. # # Licensed under the Apache License, Version 2.0", "if activity_rights.status != ACTIVITY_STATUS_PRIVATE: raise Exception( 'Public %ss can be", "activity_rights): \"\"\"Checks whether the user can edit given activity. Args:", "of inline imports by refactoring code. from core.domain import exp_services", "import user_services from core.platform import models import feconf import utils", "new role: One of ROLE_OWNER ROLE_EDITOR ROLE_TRANSLATOR ROLE_VIEWER activity_id: str.", "in activity_rights.translator_ids: activity_rights.translator_ids.remove(assignee_id) old_role = ROLE_TRANSLATOR if assignee_id in activity_rights.viewer_ids:", "committer_id: str. ID of the committer. activity_rights: ActivityRights. The rights", "first_published_msec=collection_rights.first_published_msec ).commit(committer_id, 'Created new collection', commit_cmds) subscription_services.subscribe_to_collection(committer_id, collection_id) def get_collection_rights(collection_id,", "the given activity. Returns: bool. Whether the user can delete", "editor_ids=exploration_rights.editor_ids, translator_ids=exploration_rights.translator_ids, viewer_ids=exploration_rights.viewer_ids, community_owned=exploration_rights.community_owned, status=exploration_rights.status, viewable_if_private=exploration_rights.viewable_if_private, first_published_msec=exploration_rights.first_published_msec, ).commit(committer_id, 'Created new", "role and actions for given user. activity_rights: ActivityRights or None.", "or activity_rights.is_translator(assignee_id) or activity_rights.is_owner(assignee_id)): raise Exception( 'This user already can", "\"\"\"Updates the first_published_msec field for the given activity. The caller", "if activity_rights.community_owned: raise Exception( 'Community-owned %ss can be edited by", "Args: committer: UserActionsInfo. UserActionsInfo object for the user who is", "or activity_rights.cloned_from): return False if (role_services.ACTION_MODIFY_ROLES_FOR_ANY_ACTIVITY in user.actions): return True", "check that the collection is valid prior to publication. Args:", "associated activity. Args: activity_rights: ActivityRights. The rights object for the", "if activity_rights.is_owner(user.user_id): return True return False def check_can_unpublish_activity(user, activity_rights): \"\"\"Checks", "return False def check_can_unpublish_activity(user, activity_rights): \"\"\"Checks whether the user can", "_save_activity_rights( committer_id, activity_rights, activity_type, '%s ownership released to the community.'", "% editor_translator) if editor_viewer: raise utils.ValidationError( 'A user cannot be", "model, constants.ACTIVITY_TYPE_EXPLORATION) def get_multiple_exploration_rights_by_ids(exp_ids): \"\"\"Returns a list of ActivityRights objects", "model.viewable_if_private = activity_rights.viewable_if_private model.first_published_msec = activity_rights.first_published_msec model.commit(committer_id, commit_message, commit_cmds) def", "True elif (activity_rights.is_published() and (role_services.ACTION_DELETE_ANY_PUBLIC_ACTIVITY in user.actions)): return True return", "exploration_id, constants.ACTIVITY_TYPE_EXPLORATION) def unpublish_exploration(committer, exploration_id): \"\"\"Unpublishes the given exploration. Args:", "False if (activity_rights.is_owner(user.user_id) or activity_rights.is_editor(user.user_id)): return True if (activity_rights.community_owned or", "exp_rights_models: if model is None: exp_models_list.append(None) else: exp_models_list.append( get_activity_rights_from_model( model,", "in activity_rights.viewer_ids: activity_rights.viewer_ids.remove(assignee_id) old_role = ROLE_VIEWER elif new_role == ROLE_VIEWER:", "\"\"\" if self.community_owned: if (self.owner_ids or self.editor_ids or self.translator_ids or", "Args: collection_id: str. ID of the collection. strict: bool. Whether", "[ROLE_OWNER, ROLE_EDITOR, ROLE_TRANSLATOR]: subscription_services.subscribe_to_exploration( assignee_id, exploration_id) def release_ownership_of_exploration(committer, exploration_id): \"\"\"Releases", "_assign_role. \"\"\" _assign_role( committer, assignee_id, new_role, collection_id, constants.ACTIVITY_TYPE_COLLECTION) if new_role", "for the committer. collection_id: str. ID of the collection. Raises:", "= activity_rights.translator_ids model.community_owned = activity_rights.community_owned model.status = activity_rights.status model.viewable_if_private =", "[] commit_cmds = [{ 'cmd': CMD_RELEASE_OWNERSHIP, }] _save_activity_rights( committer_id, activity_rights,", "activity. Returns: bool. Whether the user can modify roles for", "released to the community.' % activity_type, commit_cmds) _update_activity_summary(activity_type, activity_rights) def", "published.' % activity_type) _change_activity_status( committer_id, activity_id, activity_type, ACTIVITY_STATUS_PUBLIC, '%s published.'", "from core.domain import collection_services collection_services.update_collection_summary( activity_rights.id, None) def _update_activity_summary(activity_type, activity_rights):", "exploration summary for the activity associated with the given rights", "The user can already translate the activity. Exception. The activity", "collection_id): \"\"\"Publishes the given collection. It is the responsibility of", "%s' % ( assignee_username, old_role, new_role) commit_cmds = [{ 'cmd':", "utils.get_current_time_in_millisecs()) _save_activity_rights( committer_id, activity_rights, activity_type, commit_message, commit_cmds) _update_activity_summary(activity_type, activity_rights) def", "'assignee_id': assignee_id, 'old_role': old_role, 'new_role': new_role }] _save_activity_rights( committer_id, activity_rights,", "'new_role': new_role }] _save_activity_rights( committer_id, activity_rights, activity_type, commit_message, commit_cmds) _update_activity_summary(activity_type,", "viewed by anyone with the link. Args: committer: UserActionsInfo. UserActionsInfo", "import utils current_user_services = models.Registry.import_current_user_services() (collection_models, exp_models,) = models.Registry.import_models([ models.NAMES.collection,", "by refactoring code. from core.domain import exp_services exp_services.update_exploration_summary( activity_rights.id, None)", "# limitations under the License. \"\"\"Domain objects and functions that", "if (activity_rights.is_owner(user.user_id) or activity_rights.is_editor(user.user_id) or activity_rights.is_translator(user.user_id)): return True if (activity_rights.community_owned", "return bool(self.status == ACTIVITY_STATUS_PUBLIC) def is_private(self): \"\"\"Checks whether activity is", "of the activity. commit_message: str. The human-written commit message for", "from the datastore. activity_type: str. The type of activity. Possible", "committer: UserActionsInfo. UserActionsInfo object for the committer. activity_id: str. ID", "status of an activity (an exploration or a collection). \"\"\"", "values: constants.ACTIVITY_TYPE_EXPLORATION constants.ACTIVITY_TYPE_COLLECTION activity_rights: ActivityRights. The rights object for the", "return False elif activity_rights.is_published(): return bool( role_services.ACTION_PLAY_ANY_PUBLIC_ACTIVITY in user.actions) elif", "publish given activity. \"\"\" if activity_rights is None: return False", "owns this %s.' % activity_type) activity_rights.owner_ids.append(assignee_id) if assignee_id in activity_rights.viewer_ids:", "exploration ids. Args: exp_ids: list(str). List of exploration ids. Returns:", "ActivityRights. The rights object for the given activity. \"\"\" from", "else: raise Exception( 'Cannot get activity rights for unknown activity", "user, activity_rights) def check_can_publish_activity(user, activity_rights): \"\"\"Checks whether the user can", "get_collection_rights(collection_id) return user_services.get_human_readable_user_ids( collection_rights.owner_ids) def is_collection_private(collection_id): \"\"\"Returns whether the collection", "refactoring code. from core.domain import exp_services exp_services.update_exploration_summary( activity_rights.id, None) def", "exploration cannot be changed.') old_viewable_if_private = exploration_rights.viewable_if_private if old_viewable_if_private ==", "the activity. Exception. The user can already translate the activity.", "type of activity. Possible values: constants.ACTIVITY_TYPE_EXPLORATION constants.ACTIVITY_TYPE_COLLECTION Returns: ActivityRights. The", "how these cmds are interpreted preserve # backward-compatibility with previous", "already owns this %s.' % activity_type) activity_rights.owner_ids.append(assignee_id) if assignee_id in", "}] activity_rights.first_published_msec = first_published_msec _save_activity_rights( feconf.SYSTEM_COMMITTER_ID, activity_rights, activity_type, 'set first", "activity rights for unknown activity type: %s' % ( activity_type))", "constants.ACTIVITY_TYPE_COLLECTION: _update_collection_summary(activity_rights) def update_activity_first_published_msec( activity_type, activity_id, first_published_msec): \"\"\"Updates the first_published_msec", "\"\"\"Creates a new collection rights object and saves it to", "self, exploration_id, owner_ids, editor_ids, translator_ids, viewer_ids, community_owned=False, cloned_from=None, status=ACTIVITY_STATUS_PRIVATE, viewable_if_private=False,", "'This user already can edit this %s.' % activity_type) if", "private. Args: collection_id: str. ID of the collection. Returns: bool.", "OF ANY KIND, either express or implied. # See the", "ROLE_MODERATOR = 'moderator' class ActivityRights(object): \"\"\"Domain object for the rights/publication", "viewers specified.') owner_editor = set(self.owner_ids).intersection(set(self.editor_ids)) owner_translator = set(self.owner_ids).intersection( set(self.translator_ids)) owner_viewer", "activity_id: str. ID of the activity. Returns: ActivityRights. The rights", "refused permission.' % ( committer_id, assignee_id, new_role, activity_id)) raise Exception(", "Returns: bool. Whether user is an activity translator. \"\"\" return", "See the License for the specific language governing permissions and", "or activity_rights.is_viewer(user.user_id) or activity_rights.is_owner(user.user_id) or activity_rights.is_editor(user.user_id) or activity_rights.is_translator(user.user_id) or activity_rights.viewable_if_private)", "an exception from _release_ownership_of_activity. \"\"\" _release_ownership_of_activity( committer, exploration_id, constants.ACTIVITY_TYPE_EXPLORATION) def", "'editor' ROLE_TRANSLATOR = 'translator' ROLE_VIEWER = 'viewer' ROLE_NONE = 'none'", "old_viewable_if_private, 'new_viewable_if_private': viewable_if_private, }] commit_message = ( 'Made exploration viewable", "given activity. \"\"\" if activity_rights is None: return False if", "if activity_rights.first_published_msec is None: activity_rights.first_published_msec = ( utils.get_current_time_in_millisecs()) _save_activity_rights( committer_id,", "unpublish_exploration(committer, exploration_id): \"\"\"Unpublishes the given exploration. Args: committer: UserActionsInfo. UserActionsInfo", "ROLE_OWNER ROLE_EDITOR ROLE_TRANSLATOR ROLE_VIEWER activity_id: str. ID of the activity.", "to in writing, software # distributed under the License is", "the user can unpublish given activity. Args: user: UserActionsInfo. Object", "who is performing the action. activity_id: str. ID of the", "True, 'owner_names': [], 'editor_names': [], 'translator_names': [], 'viewer_names': [], 'viewable_if_private':", "str. The type of activity. Possible values: constants.ACTIVITY_TYPE_EXPLORATION constants.ACTIVITY_TYPE_COLLECTION Returns:", "\"\"\" _release_ownership_of_activity( committer, collection_id, constants.ACTIVITY_TYPE_COLLECTION) def publish_collection(committer, collection_id): \"\"\"Publishes the", "def is_collection_private(collection_id): \"\"\"Returns whether the collection is private. Args: collection_id:", "activity_rights.editor_ids.remove(assignee_id) old_role = ROLE_EDITOR if assignee_id in activity_rights.translator_ids: activity_rights.translator_ids.remove(assignee_id) old_role", "Exception( 'This user already can edit this %s.' % activity_type)", "potentially throw an exception from _release_ownership_of_activity. \"\"\" _release_ownership_of_activity( committer, exploration_id,", "{ 'cloned_from': self.cloned_from, 'status': self.status, 'community_owned': False, 'owner_names': user_services.get_human_readable_user_ids( self.owner_ids),", "Returns: ActivityRights. The rights object for the given exploration. Raises:", "or agreed to in writing, software # distributed under the", "new exploration', commit_cmds) subscription_services.subscribe_to_exploration( committer_id, exploration_id) def get_exploration_rights(exploration_id, strict=True): \"\"\"Retrieves", "UserActionsInfo. UserActionsInfo object for the committer. activity_id: str. ID of", "already set before updating it. Args: activity_type: str. The type", "== ACTIVITY_STATUS_PRIVATE def is_exploration_public(exploration_id): \"\"\"Returns whether exploration is public. Args:", "user already can view this %s.' % activity_type) if activity_rights.status", "model in exp_rights_models: if model is None: exp_models_list.append(None) else: exp_models_list.append(", "\"\"\"Returns whether the exploration is a clone of another exploration.", "can be edited by anyone.' % activity_type) activity_rights.editor_ids.append(assignee_id) if assignee_id", "to a valid user in the system. Args: committer: UserActionsInfo.", "activity is already publicly viewable. Exception. The role is invalid.", "with the link). Raises: Exception. The committer does not have", "validate(self): \"\"\"Validates an ActivityRights object. Raises: utils.ValidationError: if any of", "to %s, ' 'but that is already the current value.'", "collection_id: str. ID of the collection. Raises: Exception. This could", "translator_ids self.viewer_ids = viewer_ids self.community_owned = community_owned self.cloned_from = cloned_from", "Returns: ActivityRights. The rights object created from the model. \"\"\"", "and actions for given user. activity_rights: ActivityRights or None. Rights", "None. Id of the user. Returns: bool. Whether user is", "not found in the datastore. \"\"\" model = exp_models.ExplorationRightsModel.get( exploration_id,", "activity_id: str. ID of the activity. activity_type: str. The type", "activity. Possible values: constants.ACTIVITY_TYPE_EXPLORATION constants.ACTIVITY_TYPE_COLLECTION new_status: str. The new status", "the committer. exploration_id: str. ID of the exploration. assignee_id: str.", "commit_cmds) def create_new_exploration_rights(exploration_id, committer_id): \"\"\"Creates a new exploration rights object", "the user. Returns: bool. Whether user is an activity translator.", "'editors, translators or viewers specified.') if self.community_owned and self.status ==", "activity_rights.viewer_ids.remove(assignee_id) old_role = ROLE_VIEWER elif new_role == ROLE_VIEWER: if (activity_rights.is_owner(assignee_id)", "datastore. Subscribes the committer to the new exploration. Args: exploration_id:", "# coding: utf-8 # # Copyright 2014 The Oppia Authors.", "exploration has owners, editors, translators or viewers specified. \"\"\" if", "activity_rights.viewable_if_private model.first_published_msec = activity_rights.first_published_msec model.commit(committer_id, commit_message, commit_cmds) def _update_exploration_summary(activity_rights): \"\"\"Updates", "'moderator' class ActivityRights(object): \"\"\"Domain object for the rights/publication status of", "TODO(msl): get rid of inline imports by refactoring code. from", "raise an error if ID is not found. Returns: ActivityRights.", "logging.error( 'User %s tried to publish %s %s but was", "user in the system. Args: committer: UserActionsInfo. The UserActionsInfo object", "compliance with the License. # You may obtain a copy", "or activity_rights.is_editor(assignee_id) or activity_rights.is_viewer(assignee_id)): raise Exception( 'This user already can", "All Rights Reserved. # # Licensed under the Apache License,", "the collection is private. Args: collection_id: str. ID of the", "object for the collection. Raises: EntityNotFoundError. The collection with ID", "already translate the activity. Exception. The activity is already publicly", "exploration. strict: bool. Whether to raise an error if there", "the activity. Exception. The activity is already publicly editable. Exception.", "the new collection. Args: collection_id: str. ID of the collection.", "activity_type, commit_message, commit_cmds) _update_activity_summary(activity_type, activity_rights) def _publish_activity(committer, activity_id, activity_type): \"\"\"Publishes", "throw an exception from _release_ownership_of_activity. \"\"\" _release_ownership_of_activity( committer, collection_id, constants.ACTIVITY_TYPE_COLLECTION)", "return False if (activity_rights.is_owner(user.user_id) or activity_rights.is_editor(user.user_id) or activity_rights.is_translator(user.user_id)): return True", "elif activity_rights.is_private(): return bool( (role_services.ACTION_PLAY_ANY_PRIVATE_ACTIVITY in user.actions) or activity_rights.is_viewer(user.user_id) or", "published.' % activity_type) def _unpublish_activity(committer, activity_id, activity_type): \"\"\"Unpublishes the given", "its private viewability. if not check_can_publish_activity(committer, exploration_rights): logging.error( 'User %s", "[] activity_rights.editor_ids = [] activity_rights.viewer_ids = [] commit_cmds = [{", "False if (role_services.ACTION_MODIFY_ROLES_FOR_ANY_ACTIVITY in user.actions): return True if (role_services.ACTION_MODIFY_ROLES_FOR_OWNED_ACTIVITY in", "has owners, editors, translators or viewers specified. \"\"\" if self.community_owned:", "bool. Whether the user can release ownership for given activity.", "%s of activity %s ' 'but was refused permission.' %", "activity_rights.is_private(): return bool( (role_services.ACTION_PLAY_ANY_PRIVATE_ACTIVITY in user.actions) or activity_rights.is_viewer(user.user_id) or activity_rights.is_owner(user.user_id)", "owner_viewer = set(self.owner_ids).intersection(set(self.viewer_ids)) editor_translator = set(self.editor_ids).intersection( set(self.translator_ids)) editor_viewer = set(self.editor_ids).intersection(set(self.viewer_ids))", "rights/publication status of an activity (an exploration or a collection).", "activity_rights: ActivityRights. The rights object for the given activity. activity_type:", "the given activity. Raises: Exception. activity_type provided is unknown. \"\"\"", "models.Registry.import_current_user_services() (collection_models, exp_models,) = models.Registry.import_models([ models.NAMES.collection, models.NAMES.exploration ]) # IMPORTANT:", "return False if (role_services.ACTION_MODIFY_ROLES_FOR_ANY_ACTIVITY in user.actions): return True if (role_services.ACTION_MODIFY_ROLES_FOR_OWNED_ACTIVITY", "assignee_id in activity_rights.editor_ids: activity_rights.editor_ids.remove(assignee_id) old_role = ROLE_EDITOR if assignee_id in", "def check_can_delete_activity(user, activity_rights): \"\"\"Checks whether the user can delete given", "activity_rights.first_published_msec = first_published_msec _save_activity_rights( feconf.SYSTEM_COMMITTER_ID, activity_rights, activity_type, 'set first published", "to publication. Args: committer: UserActionsInfo. UserActionsInfo object for the committer.", "commit_cmds = [{ 'cmd': cmd_type, 'old_status': old_status, 'new_status': new_status }]", "rights object for the given activity. \"\"\" if activity_type ==", "(activity_rights.is_editor(assignee_id) or activity_rights.is_translator(assignee_id) or activity_rights.is_owner(assignee_id)): raise Exception( 'This user already", "not use this file except in compliance with the License.", "of this exploration to %s, ' 'but that is already", "imports by refactoring code. from core.domain import exp_services exp_services.update_exploration_summary( activity_rights.id,", "role_services.ACTION_PUBLISH_OWNED_ACTIVITY in user.actions: if activity_rights.is_owner(user.user_id): return True return False def", "Raises: EntityNotFoundError. The collection with ID collection_id is not found", "was refused ' 'permission.' % (committer_id, activity_type, activity_id)) raise Exception('This", "user can translate given activity. Args: user: UserActionsInfo. Object having", "if activity_rights.community_owned: raise Exception( 'Community-owned %ss can be translated by", "activity_rights.is_owner(user.user_id): return True return False def check_can_unpublish_activity(user, activity_rights): \"\"\"Checks whether", "def assign_role_for_exploration( committer, exploration_id, assignee_id, new_role): \"\"\"Assigns a user to", "you may not use this file except in compliance with", "these cmds are interpreted preserve # backward-compatibility with previous exploration", "that the exploration is valid prior to publication. Args: committer:", "\"\"\"Checks whether activity is private. Returns: bool. Whether activity is", "role: One of ROLE_OWNER ROLE_EDITOR ROLE_TRANSLATOR Raises: Exception. This could", "of rights object containing ActivityRights object for existing exploration or", "community_owned=False, cloned_from=None, status=ACTIVITY_STATUS_PRIVATE, viewable_if_private=False, first_published_msec=None): self.id = exploration_id self.owner_ids =", "id=collection_rights.id, owner_ids=collection_rights.owner_ids, editor_ids=collection_rights.editor_ids, translator_ids=collection_rights.translator_ids, viewer_ids=collection_rights.viewer_ids, community_owned=collection_rights.community_owned, status=collection_rights.status, viewable_if_private=collection_rights.viewable_if_private, first_published_msec=collection_rights.first_published_msec ).commit(committer_id,", "activity. Returns: bool. Whether the user can publish given activity.", "of ActivityRights suitable for use by the frontend. \"\"\" if", "viewer of activity. Args: user_id: str or None. Id of", "published. Returns: bool. Whether activity is published. \"\"\" return bool(self.status", "clone of another exploration. Args: exploration_id: str. ID of the", "new status of the activity. commit_message: str. The human-written commit", "ActivityRights object for existing exploration or None. \"\"\" exp_rights_models =", "can publish given activity. Args: user: UserActionsInfo. Object having user_id,", "from _release_ownership_of_activity. \"\"\" _release_ownership_of_activity( committer, collection_id, constants.ACTIVITY_TYPE_COLLECTION) def publish_collection(committer, collection_id):", "activity_id) # Rights functions for activities. def assign_role_for_exploration( committer, exploration_id,", "(role_services.ACTION_DELETE_ANY_PUBLIC_ACTIVITY in user.actions)): return True return False def check_can_modify_activity_roles(user, activity_rights):", "activity_id, activity_type): \"\"\"Unpublishes the given activity. Args: committer: UserActionsInfo. UserActionsInfo", "an exception from _assign_role. \"\"\" _assign_role( committer, assignee_id, new_role, exploration_id,", "str. The type of activity. Possible values: constants.ACTIVITY_TYPE_EXPLORATION constants.ACTIVITY_TYPE_COLLECTION activity_id:", "ROLE_EDITOR = 'editor' ROLE_TRANSLATOR = 'translator' ROLE_VIEWER = 'viewer' ROLE_NONE", "is private. \"\"\" collection_rights = get_collection_rights(collection_id) return collection_rights.status == ACTIVITY_STATUS_PRIVATE", "of the exploration. assignee_id: str. ID of the user whose", "assignee to future exploration updates. The caller should ensure that", "viewable_if_private, }] commit_message = ( 'Made exploration viewable to anyone", "bool. Whether to raise an error if there is no", "whether the collection is private. Args: collection_id: str. ID of", "to check that the exploration is valid prior to publication.", "and activity_rights.is_owner(user.user_id)): return True elif (activity_rights.is_published() and (role_services.ACTION_DELETE_ANY_PUBLIC_ACTIVITY in user.actions)):", "Returns: dict. A dict version of ActivityRights suitable for use", "in the datastore. \"\"\" model = exp_models.ExplorationRightsModel.get( exploration_id, strict=strict) if", "The rights object for the given activity. \"\"\" if activity_type", "no exploration matching the given ID. Returns: ActivityRights. The rights", "the activity. activity_type: str. The type of activity. Possible values:", "activity_type) if activity_rights.community_owned: raise Exception( 'Community-owned %ss can be edited", "the committer. \"\"\" collection_rights = ActivityRights( collection_id, [committer_id], [], [],", "None: return None return get_activity_rights_from_model( model, constants.ACTIVITY_TYPE_EXPLORATION) def get_multiple_exploration_rights_by_ids(exp_ids): \"\"\"Returns", "of the exploration. Returns: bool. Whether the exploration is a", "old_role = ROLE_VIEWER elif new_role == ROLE_TRANSLATOR: if (activity_rights.is_editor(assignee_id) or", "have rights to unpublish the activity. \"\"\" committer_id = committer.user_id", "new_role == ROLE_VIEWER: if (activity_rights.is_owner(assignee_id) or activity_rights.is_editor(assignee_id) or activity_rights.is_viewer(assignee_id)): raise", "(collection_models, exp_models,) = models.Registry.import_models([ models.NAMES.collection, models.NAMES.exploration ]) # IMPORTANT: Ensure", "'new_first_published_msec': first_published_msec }] activity_rights.first_published_msec = first_published_msec _save_activity_rights( feconf.SYSTEM_COMMITTER_ID, activity_rights, activity_type,", "True if (activity_rights.community_owned or (role_services.ACTION_EDIT_ANY_ACTIVITY in user.actions)): return True if", "private. Returns: bool. Whether activity is private. \"\"\" return bool(self.status", "activity_type, activity_id, first_published_msec): \"\"\"Updates the first_published_msec field for the given", "The name of the new role: One of ROLE_OWNER ROLE_EDITOR", "( committer_id, assignee_id, new_role, activity_id)) raise Exception( 'UnauthorizedUserException: Could not", "collection_models.CollectionRightsModel.get( collection_id, strict=strict) if model is None: return None return", "be viewed by anyone with the link. Args: committer: UserActionsInfo.", "str or None. Id of the user. Returns: bool. Whether", "'but that is already the current value.' % viewable_if_private) exploration_rights.viewable_if_private", "the owners for this collection from the datastore. Args: collection_id:", "= 'Changed role of %s from %s to %s' %", "limitations under the License. \"\"\"Domain objects and functions that manage", "return None return get_activity_rights_from_model( model, constants.ACTIVITY_TYPE_COLLECTION) def get_collection_owner_names(collection_id): \"\"\"Retrieves the", "suitable for use by the frontend. \"\"\" if self.community_owned: return", "= [{ 'cmd': cmd_type, 'old_status': old_status, 'new_status': new_status }] if", "activity_type provided is unknown. \"\"\" if activity_type == constants.ACTIVITY_TYPE_EXPLORATION: return", "rights object containing ActivityRights object for existing exploration or None.", "specified.') if self.community_owned and self.status == ACTIVITY_STATUS_PRIVATE: raise utils.ValidationError( 'Community-owned", "False if activity_rights.community_owned: return False if activity_rights.is_published(): if role_services.ACTION_UNPUBLISH_ANY_PUBLIC_ACTIVITY in", "not. \"\"\" exploration_rights = get_exploration_rights(exploration_id) return exploration_rights.status == ACTIVITY_STATUS_PRIVATE def", "ActivityRights. The rights object for the given exploration. Raises: EntityNotFoundError.", "models.NAMES.collection, models.NAMES.exploration ]) # IMPORTANT: Ensure that all changes to", "updates. The caller should ensure that assignee_id corresponds to a", "viewed by anyone.' % activity_type) activity_rights.viewer_ids.append(assignee_id) else: raise Exception('Invalid role:", "activity_rights.community_owned: raise Exception( 'Community-owned %ss can be translated by anyone.'", "= 'none' ROLE_ADMIN = 'admin' ROLE_MODERATOR = 'moderator' class ActivityRights(object):", "return False if role_services.ACTION_EDIT_OWNED_ACTIVITY not in user.actions: return False if", "get_multiple_exploration_rights_by_ids(exp_ids): \"\"\"Returns a list of ActivityRights objects for given exploration", "models import feconf import utils current_user_services = models.Registry.import_current_user_services() (collection_models, exp_models,)", "Whether the given activity can be accessed by the given", "of ROLE_OWNER ROLE_EDITOR ROLE_TRANSLATOR Raises: Exception. This could potentially throw", "\"\"\"Checks whether the user can publish given activity. Args: user:", "'new_viewable_if_private': viewable_if_private, }] commit_message = ( 'Made exploration viewable to", "exploration_id self.owner_ids = owner_ids self.editor_ids = editor_ids self.translator_ids = translator_ids", "Descriptive message for the commit. commit_cmds: list(dict). A list of", "exploration viewable only to invited playtesters.') _save_activity_rights( committer_id, exploration_rights, constants.ACTIVITY_TYPE_EXPLORATION,", "Id of the user. Returns: bool. Whether user is an", "viewable only to invited playtesters.') _save_activity_rights( committer_id, exploration_rights, constants.ACTIVITY_TYPE_EXPLORATION, commit_message,", "Raises: Exception. This could potentially throw an exception from _publish_activity.", "rights object for the given exploration. Raises: EntityNotFoundError. The exploration", "import activity_services from core.domain import role_services from core.domain import subscription_services", "editor_ids, translator_ids, viewer_ids, community_owned=False, cloned_from=None, status=ACTIVITY_STATUS_PRIVATE, viewable_if_private=False, first_published_msec=None): self.id =", "can edit this %s.' % activity_type) if activity_rights.community_owned: raise Exception(", "constants.ACTIVITY_TYPE_EXPLORATION constants.ACTIVITY_TYPE_COLLECTION activity_id: str. ID of the activity. Returns: ActivityRights.", "allow user %s to be a(n) %s of activity %s", "the activity. Returns: ActivityRights. The rights object associated with the", "\"\"\"Checks whether the user can unpublish given activity. Args: user:", "or None. Id of the user. Returns: bool. Whether user", "old_role = ROLE_VIEWER elif new_role == ROLE_VIEWER: if (activity_rights.is_owner(assignee_id) or", "or self.translator_ids or self.viewer_ids): raise utils.ValidationError( 'Community-owned explorations should have", "from _publish_activity. \"\"\" _publish_activity( committer, collection_id, constants.ACTIVITY_TYPE_COLLECTION) def unpublish_collection(committer, collection_id):", "models.Registry.import_models([ models.NAMES.collection, models.NAMES.exploration ]) # IMPORTANT: Ensure that all changes", "updating it. Args: activity_type: str. The type of activity. Possible", "the activity. first_published_msec: float. First publication time in milliseconds since", "of the user who is performing the update action. activity_id:", "'admin' ROLE_MODERATOR = 'moderator' class ActivityRights(object): \"\"\"Domain object for the", "not check_can_unpublish_activity(committer, activity_rights): logging.error( 'User %s tried to unpublish %s", "be both an owner and a viewer: %s' % owner_viewer)", "new_role, exploration_id, constants.ACTIVITY_TYPE_EXPLORATION) if new_role in [ROLE_OWNER, ROLE_EDITOR, ROLE_TRANSLATOR]: subscription_services.subscribe_to_exploration(", "!= ACTIVITY_STATUS_PRIVATE: activity_rights.viewer_ids = [] if activity_rights.first_published_msec is None: activity_rights.first_published_msec", "exploration_id, assignee_id, new_role): \"\"\"Assigns a user to the given role", "str. ID of the exploration. committer_id: str. ID of the", "activity_rights: ActivityRights. The rights object for the given activity. \"\"\"", "def check_can_publish_activity(user, activity_rights): \"\"\"Checks whether the user can publish given", "Whether the user can publish given activity. \"\"\" if activity_rights", "if activity_rights.is_owner(assignee_id): raise Exception('This user already owns this %s.' %", "the viewable_if_private property is already as desired. \"\"\" committer_id =", "activity. Args: committer: UserActionsInfo. UserActionsInfo object for the committer. activity_id:", "is None: return False if role_services.ACTION_EDIT_OWNED_ACTIVITY not in user.actions: return", "get_exploration_rights(exploration_id, strict=True): \"\"\"Retrieves the rights for this exploration from the", "activity_type == constants.ACTIVITY_TYPE_COLLECTION: _update_collection_summary(activity_rights) def update_activity_first_published_msec( activity_type, activity_id, first_published_msec): \"\"\"Updates", "the datastore. # Do not modify the definitions of CMD", "\"\"\" model = collection_models.CollectionRightsModel.get( collection_id, strict=strict) if model is None:", "of the committer. activity_rights: ActivityRights. The rights object for the", "= viewer_ids self.community_owned = community_owned self.cloned_from = cloned_from self.status =", "def publish_exploration(committer, exploration_id): \"\"\"Publishes the given exploration. It is the", "performing the action. assignee_id: str. ID of the user whose", "of ActivityRights objects for given exploration ids. Args: exp_ids: list(str).", "ActivityRights( collection_id, [committer_id], [], [], []) commit_cmds = [{'cmd': CMD_CREATE_NEW}]", "exploration_id, [committer_id], [], [], []) commit_cmds = [{'cmd': CMD_CREATE_NEW}] exp_models.ExplorationRightsModel(", "the action. activity_id: str. ID of the activity. activity_type: str.", "Rights object for the given activity. Returns: bool. Whether the", "be accessed by the given user. \"\"\" if activity_rights is", "committer, collection_id, constants.ACTIVITY_TYPE_COLLECTION) def unpublish_collection(committer, collection_id): \"\"\"Unpublishes the given collection.", "exploration is public. \"\"\" exploration_rights = get_exploration_rights(exploration_id) return exploration_rights.status ==", "import exp_services exp_services.update_exploration_summary( activity_rights.id, None) def _update_collection_summary(activity_rights): \"\"\"Updates the collection", "'owner_names': [], 'editor_names': [], 'translator_names': [], 'viewer_names': [], 'viewable_if_private': self.viewable_if_private,", "user already owns this %s.' % activity_type) activity_rights.owner_ids.append(assignee_id) if assignee_id", "def check_can_access_activity(user, activity_rights): \"\"\"Checks whether the user can access given", "bool(exploration_rights.cloned_from) def create_new_collection_rights(collection_id, committer_id): \"\"\"Creates a new collection rights object", "from _publish_activity. \"\"\" _publish_activity( committer, exploration_id, constants.ACTIVITY_TYPE_EXPLORATION) def unpublish_exploration(committer, exploration_id):", "Args: activity_type: str. The type of activity. Possible values: constants.ACTIVITY_TYPE_EXPLORATION", "Whether to raise an error if ID is not found.", "message for this change. \"\"\" activity_rights = _get_activity_rights(activity_type, activity_id) old_status", "ownership of the given activity to the community. Args: committer:", "translators or viewers specified.') if self.community_owned and self.status == ACTIVITY_STATUS_PRIVATE:", "ACTIVITY_STATUS_PUBLIC def _get_activity_rights(activity_type, activity_id): \"\"\"Retrieves the rights object for the", "self.viewer_ids), 'viewable_if_private': self.viewable_if_private, } def is_owner(self, user_id): \"\"\"Checks whether given", "viewers specified.') if self.community_owned and self.status == ACTIVITY_STATUS_PRIVATE: raise utils.ValidationError(", "_get_activity_rights(activity_type, activity_id) old_status = activity_rights.status activity_rights.status = new_status if activity_type", "activity_id)) raise Exception( 'The ownership of this %s cannot be", "check_can_edit_activity(user, activity_rights): \"\"\"Checks whether the user can edit given activity.", "if translator_viewer: raise utils.ValidationError( 'A user cannot be both a", "collection_id: str. ID of the collection. Returns: list(str). Human-readable usernames", "ROLE_OWNER ROLE_EDITOR ROLE_TRANSLATOR Raises: Exception. This could potentially throw an", "the given ID. Returns: ActivityRights. The rights object for the", "'Created new collection', commit_cmds) subscription_services.subscribe_to_collection(committer_id, collection_id) def get_collection_rights(collection_id, strict=True): \"\"\"Retrieves", "activity_rights = _get_activity_rights(activity_type, activity_id) commit_cmds = [{ 'cmd': CMD_UPDATE_FIRST_PUBLISHED_MSEC, 'old_first_published_msec':", "user can unpublish given activity. \"\"\" if activity_rights is None:", "activity_id, activity_type): \"\"\"Publishes the given activity. Args: committer: UserActionsInfo. UserActionsInfo", "permission.' % (committer_id, activity_type, activity_id)) raise Exception( 'The ownership of", "activity_rights): logging.error( 'User %s tried to unpublish %s %s but", "the given activity. Returns: bool. Whether the user can unpublish", "old_role, new_role) commit_cmds = [{ 'cmd': CMD_CHANGE_ROLE, 'assignee_id': assignee_id, 'old_role':", "cmd_type = CMD_CHANGE_EXPLORATION_STATUS elif activity_type == constants.ACTIVITY_TYPE_COLLECTION: cmd_type = CMD_CHANGE_COLLECTION_STATUS", "owner of activity. Args: user_id: str or None. Id of", "'User %s tried to release ownership of %s %s but", "a viewer: %s' % editor_viewer) if translator_viewer: raise utils.ValidationError( 'A", "objects for given exploration ids. Args: exp_ids: list(str). List of", "exploration_rights.viewable_if_private = viewable_if_private commit_cmds = [{ 'cmd': CMD_CHANGE_PRIVATE_VIEWABILITY, 'old_viewable_if_private': old_viewable_if_private,", "the viewable_if_private attribute for the given exploration's rights object. If", "CMD_UPDATE_FIRST_PUBLISHED_MSEC, 'old_first_published_msec': activity_rights.first_published_msec, 'new_first_published_msec': first_published_msec }] activity_rights.first_published_msec = first_published_msec _save_activity_rights(", "set(self.owner_ids).intersection(set(self.editor_ids)) owner_translator = set(self.owner_ids).intersection( set(self.translator_ids)) owner_viewer = set(self.owner_ids).intersection(set(self.viewer_ids)) editor_translator =", "committer_id, activity_id, activity_type, ACTIVITY_STATUS_PRIVATE, '%s unpublished.' % activity_type) activity_services.remove_featured_activity(activity_type, activity_id)", "editor. \"\"\" return bool(user_id in self.editor_ids) def is_translator(self, user_id): \"\"\"Checks", "release rights. \"\"\" committer_id = committer.user_id activity_rights = _get_activity_rights(activity_type, activity_id)", "this exploration to %s, ' 'but that is already the", "activity based on its type. Args: activity_type: str. The type", "is None: exp_models_list.append(None) else: exp_models_list.append( get_activity_rights_from_model( model, constants.ACTIVITY_TYPE_EXPLORATION)) return exp_models_list", "and self.viewer_ids: raise utils.ValidationError( 'Public explorations should have no viewers", "}] commit_message = ( 'Made exploration viewable to anyone with", "= get_collection_rights(collection_id) return collection_rights.status == ACTIVITY_STATUS_PRIVATE def is_collection_public(collection_id): \"\"\"Returns whether", "the given activity associated with the given rights object. The", "owners for this collection from the datastore. Args: collection_id: str.", "utils.ValidationError( 'Community-owned explorations should have no owners, ' 'editors, translators", "the collection summary for the given activity associated with the", "new_role, activity_id, activity_type): \"\"\"Assigns a new role to the user.", "Exception( 'Cannot get activity rights for unknown activity type: %s'", "'A user cannot be both a translator and a viewer:", "both a translator and a viewer: %s' % translator_viewer) def", "for the activity associated with the given rights object. The", "old_role = ROLE_EDITOR if assignee_id in activity_rights.translator_ids: activity_rights.translator_ids.remove(assignee_id) old_role =", "assignee_username, old_role, new_role) commit_cmds = [{ 'cmd': CMD_CHANGE_ROLE, 'assignee_id': assignee_id,", "activity_type, new_status, commit_message): \"\"\"Changes the status of the given activity.", "( utils.get_current_time_in_millisecs()) _save_activity_rights( committer_id, activity_rights, activity_type, commit_message, commit_cmds) _update_activity_summary(activity_type, activity_rights)", "file except in compliance with the License. # You may", "activity_type == constants.ACTIVITY_TYPE_EXPLORATION: _update_exploration_summary(activity_rights) elif activity_type == constants.ACTIVITY_TYPE_COLLECTION: _update_collection_summary(activity_rights) def", "Args: collection_id: str. ID of the collection. Returns: list(str). Human-readable", "get_exploration_rights(exploration_id) return exploration_rights.status == ACTIVITY_STATUS_PUBLIC def is_exploration_cloned(exploration_id): \"\"\"Returns whether the", "already can edit this %s.' % activity_type) if activity_rights.community_owned: raise", "owner and a translator: %s' % owner_translator) if owner_viewer: raise", "activity_rights.status = new_status if activity_type == constants.ACTIVITY_TYPE_EXPLORATION: cmd_type = CMD_CHANGE_EXPLORATION_STATUS", "publication time in milliseconds since the Epoch. \"\"\" activity_rights =", "return True if (activity_rights.community_owned or (role_services.ACTION_EDIT_ANY_ACTIVITY in user.actions)): return True", "is private. Returns: bool. Whether activity is private. \"\"\" return", "ExplorationRights or CollectionRights domain object to the datastore. Args: committer_id:", "caller is responsible for ensuring that this value is not", "is unknown. \"\"\" if activity_type == constants.ACTIVITY_TYPE_EXPLORATION: return get_exploration_rights(activity_id, strict=False)", "The rights object for the given activity. \"\"\" from core.domain", "Returns: bool. Whether the given user can edit this activity.", "error if ID is not found. Returns: ActivityRights. The rights", "whether the user can modify roles for given activity. Args:", "editor_ids self.translator_ids = translator_ids self.viewer_ids = viewer_ids self.community_owned = community_owned", "the committer. \"\"\" exploration_rights = ActivityRights( exploration_id, [committer_id], [], [],", "user.actions)): return True if (activity_rights.is_published() and (role_services.ACTION_EDIT_ANY_PUBLIC_ACTIVITY in user.actions)): return", "model is None: return None return get_activity_rights_from_model( model, constants.ACTIVITY_TYPE_EXPLORATION) def", "this value is not already set before updating it. Args:", "to the community.' % activity_type, commit_cmds) _update_activity_summary(activity_type, activity_rights) def _change_activity_status(", "caller to check that the collection is valid prior to", "if owner_viewer: raise utils.ValidationError( 'A user cannot be both an", "activity_type) _change_activity_status( committer_id, activity_id, activity_type, ACTIVITY_STATUS_PUBLIC, '%s published.' % activity_type)", "None: return False elif activity_rights.is_published(): return bool( role_services.ACTION_PLAY_ANY_PUBLIC_ACTIVITY in user.actions)", "activity_type) activity_services.remove_featured_activity(activity_type, activity_id) # Rights functions for activities. def assign_role_for_exploration(", "activity_rights): \"\"\"Checks whether the user can access given activity. Args:", "type of activity. Possible values: constants.ACTIVITY_TYPE_EXPLORATION constants.ACTIVITY_TYPE_COLLECTION Raise: Exception. The", "same as the ID of associated activity. Args: activity_type: str.", "str. ID of the collection. Returns: list(str). Human-readable usernames (or", "rights for this exploration from the datastore. Args: exploration_id: str.", "changed.') old_viewable_if_private = exploration_rights.viewable_if_private if old_viewable_if_private == viewable_if_private: raise Exception(", "activity_rights.is_owner(user.user_id): return True return False def check_can_release_ownership(user, activity_rights): \"\"\"Checks whether", "created from the model. \"\"\" return ActivityRights( activity_rights_model.id, activity_rights_model.owner_ids, activity_rights_model.editor_ids,", "for the collection. Raises: EntityNotFoundError. The collection with ID collection_id", "be changed.') old_viewable_if_private = exploration_rights.viewable_if_private if old_viewable_if_private == viewable_if_private: raise", "= 'moderator' class ActivityRights(object): \"\"\"Domain object for the rights/publication status", "if self.community_owned: if (self.owner_ids or self.editor_ids or self.translator_ids or self.viewer_ids):", "% ( activity_type)) def check_can_access_activity(user, activity_rights): \"\"\"Checks whether the user", "[{'cmd': CMD_CREATE_NEW}] exp_models.ExplorationRightsModel( id=exploration_rights.id, owner_ids=exploration_rights.owner_ids, editor_ids=exploration_rights.editor_ids, translator_ids=exploration_rights.translator_ids, viewer_ids=exploration_rights.viewer_ids, community_owned=exploration_rights.community_owned, status=exploration_rights.status,", "\"\"\"Assign the given user to the given role and subscribes", "activity_rights) def check_can_publish_activity(user, activity_rights): \"\"\"Checks whether the user can publish", "msec', commit_cmds) def create_new_exploration_rights(exploration_id, committer_id): \"\"\"Creates a new exploration rights", "collection is public. \"\"\" collection_rights = get_collection_rights(collection_id) return collection_rights.status ==", "'viewer_names': [], 'viewable_if_private': self.viewable_if_private, } else: return { 'cloned_from': self.cloned_from,", "KIND, either express or implied. # See the License for", "= 'change_role' CMD_CHANGE_EXPLORATION_STATUS = 'change_exploration_status' CMD_CHANGE_COLLECTION_STATUS = 'change_collection_status' CMD_CHANGE_PRIVATE_VIEWABILITY =", "the datastore. activity_type: str. The type of activity. Possible values:", "str. The type of activity. Possible values: constants.ACTIVITY_TYPE_EXPLORATION constants.ACTIVITY_TYPE_COLLECTION commit_message:", "activity. Possible values: constants.ACTIVITY_TYPE_EXPLORATION constants.ACTIVITY_TYPE_COLLECTION commit_message: str. Descriptive message for", "viewer: %s' % editor_viewer) if translator_viewer: raise utils.ValidationError( 'A user", "viewable_if_private: raise Exception( 'Trying to change viewability status of this", "only to invited playtesters.') _save_activity_rights( committer_id, exploration_rights, constants.ACTIVITY_TYPE_EXPLORATION, commit_message, commit_cmds)", "a valid user in the system. Args: committer: UserActionsInfo. UserActionsInfo", "the frontend. \"\"\" if self.community_owned: return { 'cloned_from': self.cloned_from, 'status':", "the given activity. Returns: bool. Whether the user can publish", "object for the committer. activity_id: str. ID of the activity.", "that the collection is valid prior to publication. Args: committer:", "core.domain import role_services from core.domain import subscription_services from core.domain import", "given collection. It is the responsibility of the caller to", "the committer. activity_rights: ActivityRights. The rights object for the given", "of CMD keys that already exist. CMD_CREATE_NEW = 'create_new' CMD_CHANGE_ROLE", "the given role and subscribes the assignee to future exploration", "user %s to be a(n) %s of activity %s '", "and (role_services.ACTION_DELETE_OWNED_PRIVATE_ACTIVITY in user.actions) and activity_rights.is_owner(user.user_id)): return True elif (activity_rights.is_published()", "new_role }] _save_activity_rights( committer_id, activity_rights, activity_type, commit_message, commit_cmds) _update_activity_summary(activity_type, activity_rights)", "can modify roles for given activity. \"\"\" if activity_rights is", "of activity. Args: user_id: str or None. Id of the", "of the committer. \"\"\" exploration_rights = ActivityRights( exploration_id, [committer_id], [],", "rights from the datastore. activity_type: str. The type of activity.", "(the \"License\"); # you may not use this file except", "community_owned=exploration_rights.community_owned, status=exploration_rights.status, viewable_if_private=exploration_rights.viewable_if_private, first_published_msec=exploration_rights.first_published_msec, ).commit(committer_id, 'Created new exploration', commit_cmds) subscription_services.subscribe_to_exploration(", "# Do not modify the definitions of CMD keys that", "is None: return False if role_services.ACTION_DELETE_ANY_ACTIVITY in user.actions: return True", "Args: exp_ids: list(str). List of exploration ids. Returns: list(ActivityRights or", "self.viewer_ids: raise utils.ValidationError( 'Public explorations should have no viewers specified.')", "of activity. Possible values: constants.ACTIVITY_TYPE_EXPLORATION constants.ACTIVITY_TYPE_COLLECTION commit_message: str. Descriptive message", "= ActivityRights( collection_id, [committer_id], [], [], []) commit_cmds = [{'cmd':", "in user.actions: return False if (activity_rights.is_owner(user.user_id) or activity_rights.is_editor(user.user_id) or activity_rights.is_translator(user.user_id)):", "publicly translatable. Exception. The user can already view the activity.", "Returns: bool. Whether the exploration is public. \"\"\" exploration_rights =", "user.actions) and activity_rights.is_owner(user.user_id)): return True elif (activity_rights.is_published() and (role_services.ACTION_DELETE_ANY_PUBLIC_ACTIVITY in", "of this exploration cannot be changed.') old_viewable_if_private = exploration_rights.viewable_if_private if", "is_exploration_public(exploration_id): \"\"\"Returns whether exploration is public. Args: exploration_id: str. ID", "the given activity. Returns: bool. Whether the given activity can", "ID of the activity. activity_type: str. The type of activity.", "throw an exception from _unpublish_activity. \"\"\" _unpublish_activity( committer, exploration_id, constants.ACTIVITY_TYPE_EXPLORATION)", "for the committer. exploration_id: str. ID of the exploration. Raises:", "<reponame>netajik/oppia<gh_stars>0 # coding: utf-8 # # Copyright 2014 The Oppia", "or if a community-owned exploration has owners, editors, translators or", "summary for the activity associated with the given rights object.", "user cannot be both an owner and a viewer: %s'", "and functions that manage rights for various user actions.\"\"\" import", "%s' % owner_viewer) if editor_translator: raise utils.ValidationError( 'A user cannot", "name of the new role: One of ROLE_OWNER ROLE_EDITOR Raises:", "user.actions: return False if (activity_rights.is_owner(user.user_id) or activity_rights.is_editor(user.user_id) or activity_rights.is_translator(user.user_id)): return", "_publish_activity(committer, activity_id, activity_type): \"\"\"Publishes the given activity. Args: committer: UserActionsInfo.", "return get_activity_rights_from_model( model, constants.ACTIVITY_TYPE_COLLECTION) def get_collection_owner_names(collection_id): \"\"\"Retrieves the owners for", "edit given activity. Args: user: UserActionsInfo. Object having user_id, role", "return True return False def check_can_release_ownership(user, activity_rights): \"\"\"Checks whether the", "== ACTIVITY_STATUS_PUBLIC def is_exploration_cloned(exploration_id): \"\"\"Returns whether the exploration is a", "can already edit the activity. Exception. The user can already", "community. Args: committer: UserActionsInfo. UserActionsInfo object for the committer. exploration_id:", "None: exp_models_list.append(None) else: exp_models_list.append( get_activity_rights_from_model( model, constants.ACTIVITY_TYPE_EXPLORATION)) return exp_models_list def", "activity_rights.translator_ids.remove(assignee_id) old_role = ROLE_TRANSLATOR if assignee_id in activity_rights.viewer_ids: activity_rights.viewer_ids.remove(assignee_id) old_role", "# # Unless required by applicable law or agreed to", "committer to the new exploration. Args: exploration_id: str. ID of", "publicly viewable. Exception. The role is invalid. \"\"\" committer_id =", "not in user.actions: return False if (activity_rights.is_owner(user.user_id) or activity_rights.is_editor(user.user_id)): return", "ID of associated activity. Args: activity_rights: ActivityRights. The rights object", "activity_rights) def _release_ownership_of_activity(committer, activity_id, activity_type): \"\"\"Releases ownership of the given", "commit_cmds) _update_activity_summary(activity_type, activity_rights) def _change_activity_status( committer_id, activity_id, activity_type, new_status, commit_message):", "str. ID of the committer. \"\"\" exploration_rights = ActivityRights( exploration_id,", "True if (activity_rights.is_published() and (role_services.ACTION_EDIT_ANY_PUBLIC_ACTIVITY in user.actions)): return True return", "Exception('This user already owns this %s.' % activity_type) activity_rights.owner_ids.append(assignee_id) if", "from _unpublish_activity. \"\"\" _unpublish_activity( committer, exploration_id, constants.ACTIVITY_TYPE_EXPLORATION) # Rights functions", "viewability status of this exploration to %s, ' 'but that", "if new_role in [ROLE_OWNER, ROLE_EDITOR]: subscription_services.subscribe_to_collection( assignee_id, collection_id) def release_ownership_of_collection(committer,", "value.' % viewable_if_private) exploration_rights.viewable_if_private = viewable_if_private commit_cmds = [{ 'cmd':", "system. Args: committer: UserActionsInfo. UserActionsInfo object for the committer. collection_id:", "Args: exploration_id: str. ID of the exploration. committer_id: str. ID", "can be accessed by the given user. \"\"\" if activity_rights", "dict. A dict version of ActivityRights suitable for use by", "in user.actions): return True if (role_services.ACTION_MODIFY_ROLES_FOR_OWNED_ACTIVITY in user.actions): if activity_rights.is_owner(user.user_id):", "object for the given activity based on its type. Args:", "from constants import constants from core.domain import activity_services from core.domain", "self.id = exploration_id self.owner_ids = owner_ids self.editor_ids = editor_ids self.translator_ids", "the given user to the given role and subscribes the", "%s tried to unpublish %s %s but was refused '", "object associated with the given activity. Raises: Exception. activity_type provided", "valid user in the system. Args: committer: UserActionsInfo. The UserActionsInfo", "\"\"\"Sets the viewable_if_private attribute for the given exploration's rights object.", "exploration_rights, constants.ACTIVITY_TYPE_EXPLORATION, commit_message, commit_cmds) _update_exploration_summary(exploration_rights) def publish_exploration(committer, exploration_id): \"\"\"Publishes the", "implied. # See the License for the specific language governing", "both an owner and an editor: %s' % owner_editor) if", "for ensuring that this value is not already set before", "%s cannot be published.' % activity_type) _change_activity_status( committer_id, activity_id, activity_type,", "bool(user_id in self.editor_ids) def is_translator(self, user_id): \"\"\"Checks whether given user", "constants.ACTIVITY_TYPE_EXPLORATION: _update_exploration_summary(activity_rights) elif activity_type == constants.ACTIVITY_TYPE_COLLECTION: _update_collection_summary(activity_rights) def update_activity_first_published_msec( activity_type,", "constants.ACTIVITY_TYPE_EXPLORATION constants.ACTIVITY_TYPE_COLLECTION Raise: Exception. The committer does not have release", "'The viewability status of this exploration cannot be changed.') old_viewable_if_private", "collection. Raises: Exception. This could potentially throw an exception from", "activity_rights.translator_ids: activity_rights.translator_ids.remove(assignee_id) old_role = ROLE_TRANSLATOR if assignee_id in activity_rights.viewer_ids: activity_rights.viewer_ids.remove(assignee_id)", "One of ROLE_OWNER ROLE_EDITOR ROLE_TRANSLATOR Raises: Exception. This could potentially", "activity_rights.cloned_from: return False if activity_rights.is_published(): return False if role_services.ACTION_PUBLISH_ANY_ACTIVITY in", "cmd_type, 'old_status': old_status, 'new_status': new_status }] if new_status != ACTIVITY_STATUS_PRIVATE:", "commit_message = ( 'Made exploration viewable to anyone with the", "inline imports by refactoring code. from core.domain import exp_services exp_services.update_exploration_summary(", "activity. The caller is responsible for ensuring that this value", "\"\"\"Returns whether exploration is public. Args: exploration_id: str. ID of", "or activity_rights.is_translator(user.user_id)): return True if (activity_rights.community_owned or (role_services.ACTION_EDIT_ANY_ACTIVITY in user.actions)):", "truncated email addresses) of owners for this collection. \"\"\" collection_rights", "changed. new_role: str. The name of the new role: One", "\"\"\"Checks whether the user can translate given activity. Args: user:", "list of commands describing what kind of commit was done.", "the rights object for the given activity based on its", "not check_can_release_ownership(committer, activity_rights): logging.error( 'User %s tried to release ownership", "be both an editor and a translator: %s' % editor_translator)", "activity_rights.status != ACTIVITY_STATUS_PRIVATE: raise Exception( 'Public %ss can be viewed", "the exploration should be made viewable (by anyone with the", "in msec', commit_cmds) def create_new_exploration_rights(exploration_id, committer_id): \"\"\"Creates a new exploration", "(an exploration or a collection). \"\"\" def __init__( self, exploration_id,", "viewers specified. \"\"\" if self.community_owned: if (self.owner_ids or self.editor_ids or", "activity_rights = _get_activity_rights(activity_type, activity_id) old_status = activity_rights.status activity_rights.status = new_status", "a community-owned exploration has owners, editors, translators or viewers specified.", "datastore. Args: exploration_id: str. ID of the exploration. strict: bool.", "ROLE_TRANSLATOR elif new_role == ROLE_EDITOR: if (activity_rights.is_editor(assignee_id) or activity_rights.is_owner(assignee_id)): raise", "commit_message, commit_cmds) _update_activity_summary(activity_type, activity_rights) def _publish_activity(committer, activity_id, activity_type): \"\"\"Publishes the", "return exploration_rights.status == ACTIVITY_STATUS_PRIVATE def is_exploration_public(exploration_id): \"\"\"Returns whether exploration is", "def validate(self): \"\"\"Validates an ActivityRights object. Raises: utils.ValidationError: if any", "should be made viewable (by anyone with the link). Raises:", "= ROLE_VIEWER if assignee_id in activity_rights.editor_ids: activity_rights.editor_ids.remove(assignee_id) old_role = ROLE_EDITOR", "object for the given activity. \"\"\" if activity_type == constants.ACTIVITY_TYPE_EXPLORATION:", "exploration should be made viewable (by anyone with the link).", "The ID of rights object is the same as the", "viewer_ids=exploration_rights.viewer_ids, community_owned=exploration_rights.community_owned, status=exploration_rights.status, viewable_if_private=exploration_rights.viewable_if_private, first_published_msec=exploration_rights.first_published_msec, ).commit(committer_id, 'Created new exploration', commit_cmds)", "collection. Raises: EntityNotFoundError. The collection with ID collection_id is not", "the committer. activity_id: str. ID of the activity. activity_type: str.", "whether given user is owner of activity. Args: user_id: str", "committer. collection_id: str. ID of the collection. Raises: Exception. This", "bool(user_id in self.translator_ids) def is_viewer(self, user_id): \"\"\"Checks whether given user", "not in user.actions: return False if (activity_rights.is_owner(user.user_id) or activity_rights.is_editor(user.user_id) or", "if role_services.ACTION_PUBLISH_OWNED_ACTIVITY in user.actions: if activity_rights.is_owner(user.user_id): return True return False", "object for the committer. collection_id: str. ID of the collection.", "\"\"\"Returns a dict suitable for use by the frontend. Returns:", "exploration %s ' 'but was refused permission.' % (committer_id, exploration_id))", "for the user who is performing the action. assignee_id: str.", "was ' 'refused permission.' % (committer_id, activity_type, activity_id)) raise Exception(", "model = exp_models.ExplorationRightsModel.get( exploration_id, strict=strict) if model is None: return", "or activity_rights.is_translator(user.user_id) or activity_rights.viewable_if_private) def check_can_edit_activity(user, activity_rights): \"\"\"Checks whether the", "return True return False def check_can_modify_activity_roles(user, activity_rights): \"\"\"Checks whether the", "the activity associated with the given rights object. The ID", "exception from _release_ownership_of_activity. \"\"\" _release_ownership_of_activity( committer, exploration_id, constants.ACTIVITY_TYPE_EXPLORATION) def set_private_viewability_of_exploration(", "if activity_rights.community_owned: return False if activity_rights.is_published(): if role_services.ACTION_UNPUBLISH_ANY_PUBLIC_ACTIVITY in user.actions:", "= editor_ids self.translator_ids = translator_ids self.viewer_ids = viewer_ids self.community_owned =", "get_activity_rights_from_model( model, constants.ACTIVITY_TYPE_EXPLORATION) def get_multiple_exploration_rights_by_ids(exp_ids): \"\"\"Returns a list of ActivityRights", "action. Exception. If the viewable_if_private property is already as desired.", "(activity_rights.community_owned or (role_services.ACTION_EDIT_ANY_ACTIVITY in user.actions)): return True if (activity_rights.is_published() and", "ID of the collection. Raises: Exception. This could potentially throw", "def _update_collection_summary(activity_rights): \"\"\"Updates the collection summary for the given activity", "role.') assignee_username = user_services.get_username(assignee_id) old_role = ROLE_NONE if new_role ==", "from the datastore. Args: exploration_id: str. ID of the exploration.", "utils.ValidationError( 'A user cannot be both an owner and a", "assign new role.') assignee_username = user_services.get_username(assignee_id) old_role = ROLE_NONE if", "to be viewed by anyone with the link. Args: committer:", "the given exploration. Raises: EntityNotFoundError. The exploration with ID exploration_id", "Unless required by applicable law or agreed to in writing,", "ROLE_NONE = 'none' ROLE_ADMIN = 'admin' ROLE_MODERATOR = 'moderator' class", "= activity_rights.community_owned model.status = activity_rights.status model.viewable_if_private = activity_rights.viewable_if_private model.first_published_msec =", "activity_rights.status model.viewable_if_private = activity_rights.viewable_if_private model.first_published_msec = activity_rights.first_published_msec model.commit(committer_id, commit_message, commit_cmds)", "get_collection_rights(collection_id, strict=True): \"\"\"Retrieves the rights for this collection from the", "\"\"\"Checks whether the user can modify roles for given activity.", "constants.ACTIVITY_TYPE_COLLECTION Raise: Exception. The committer does not have release rights.", "= [] activity_rights.viewer_ids = [] commit_cmds = [{ 'cmd': CMD_RELEASE_OWNERSHIP,", "ROLE_EDITOR: if (activity_rights.is_editor(assignee_id) or activity_rights.is_owner(assignee_id)): raise Exception( 'This user already", "be viewed by anyone.' % activity_type) activity_rights.viewer_ids.append(assignee_id) else: raise Exception('Invalid", "an ExplorationRights or CollectionRights domain object to the datastore. Args:", "the specific language governing permissions and # limitations under the", "first_published_msec field for the given activity. The caller is responsible", "exploration. viewable_if_private: bool. Whether the exploration should be made viewable", "the given exploration. Args: committer: UserActionsInfo. UserActionsInfo object for the", "role and subscribes the assignee to future exploration updates. The", "of the new role: One of ROLE_OWNER ROLE_EDITOR ROLE_TRANSLATOR Raises:", "from _assign_role. \"\"\" _assign_role( committer, assignee_id, new_role, exploration_id, constants.ACTIVITY_TYPE_EXPLORATION) if", "committer, assignee_id, new_role, exploration_id, constants.ACTIVITY_TYPE_EXPLORATION) if new_role in [ROLE_OWNER, ROLE_EDITOR,", "self.editor_ids) def is_translator(self, user_id): \"\"\"Checks whether given user is translator", "Exception. This could potentially throw an exception from _publish_activity. \"\"\"", "if owner_translator: raise utils.ValidationError( 'A user cannot be both an", "ActivityRights( exploration_id, [committer_id], [], [], []) commit_cmds = [{'cmd': CMD_CREATE_NEW}]", "'UnauthorizedUserException: Could not assign new role.') assignee_username = user_services.get_username(assignee_id) old_role", "ROLE_NONE if new_role == ROLE_OWNER: if activity_rights.is_owner(assignee_id): raise Exception('This user", "edit this %s.' % activity_type) if activity_rights.community_owned: raise Exception( 'Community-owned", "\"\"\" # TODO(msl): get rid of inline imports by refactoring", "user can release ownership for given activity. \"\"\" if activity_rights", "of the collection. Returns: list(str). Human-readable usernames (or truncated email", "activity_type, activity_id)) raise Exception('This %s cannot be unpublished.' % activity_type)", "return bool(user_id in self.owner_ids) def is_editor(self, user_id): \"\"\"Checks whether given", "\"\"\" return ActivityRights( activity_rights_model.id, activity_rights_model.owner_ids, activity_rights_model.editor_ids, activity_rights_model.translator_ids, activity_rights_model.viewer_ids, community_owned=activity_rights_model.community_owned, cloned_from=(", "user can modify roles for given activity. \"\"\" if activity_rights", "'This user already can view this %s.' % activity_type) if", "whether the user can publish given activity. Args: user: UserActionsInfo.", "constants.ACTIVITY_TYPE_COLLECTION) def publish_collection(committer, collection_id): \"\"\"Publishes the given collection. It is", "if (self.owner_ids or self.editor_ids or self.translator_ids or self.viewer_ids): raise utils.ValidationError(", "check_can_modify_activity_roles(user, activity_rights): \"\"\"Checks whether the user can modify roles for", "activity. \"\"\" committer_id = committer.user_id activity_rights = _get_activity_rights(activity_type, activity_id) if", "'User %s tried to publish %s %s but was refused", "Whether activity is private. \"\"\" return bool(self.status == ACTIVITY_STATUS_PRIVATE) def", "given user is editor of activity. Args: user_id: str or", "and an editor: %s' % owner_editor) if owner_translator: raise utils.ValidationError(", "exploration_rights = get_exploration_rights(exploration_id) return exploration_rights.status == ACTIVITY_STATUS_PUBLIC def is_exploration_cloned(exploration_id): \"\"\"Returns", "return True if (role_services.ACTION_MODIFY_ROLES_FOR_OWNED_ACTIVITY in user.actions): if activity_rights.is_owner(user.user_id): return True", "a(n) %s of activity %s ' 'but was refused permission.'", "cannot be published.' % activity_type) _change_activity_status( committer_id, activity_id, activity_type, ACTIVITY_STATUS_PUBLIC,", "'cmd': CMD_CHANGE_PRIVATE_VIEWABILITY, 'old_viewable_if_private': old_viewable_if_private, 'new_viewable_if_private': viewable_if_private, }] commit_message = (", "for this collection. \"\"\" collection_rights = get_collection_rights(collection_id) return user_services.get_human_readable_user_ids( collection_rights.owner_ids)", "core.domain import subscription_services from core.domain import user_services from core.platform import", "committer: UserActionsInfo. UserActionInfo object for the user who is performing", "activity_type, activity_id)) raise Exception('This %s cannot be published.' % activity_type)", "'Made exploration viewable to anyone with the link.' if viewable_if_private", "role_services.ACTION_PUBLISH_ANY_ACTIVITY in user.actions: return True if role_services.ACTION_PUBLISH_OWNED_ACTIVITY in user.actions: if", "None: return False if activity_rights.is_private(): return False return check_can_modify_activity_roles( user,", "is None: return False if activity_rights.community_owned: return False if activity_rights.is_published():", "exception from _assign_role. \"\"\" _assign_role( committer, assignee_id, new_role, collection_id, constants.ACTIVITY_TYPE_COLLECTION)", "Whether user is an activity owner. \"\"\" return bool(user_id in", "committer.user_id activity_rights = _get_activity_rights(activity_type, activity_id) if not check_can_unpublish_activity(committer, activity_rights): logging.error(", "dict version of ActivityRights suitable for use by the frontend.", "the committer to the new collection. Args: collection_id: str. ID", "Returns: bool. Whether the user can modify roles for given", "def is_translator(self, user_id): \"\"\"Checks whether given user is translator of", "The committer does not have rights to publish the activity.", "and subscribes the assignee to future exploration updates. The caller", "the frontend. Returns: dict. A dict version of ActivityRights suitable", "%s tried to change private viewability of exploration %s '", "Returns: bool. Whether user is an activity viewer. \"\"\" return", "the datastore. Args: committer_id: str. ID of the committer. activity_rights:", "is private. Args: exploration_id: str. ID of the exploration. Returns:", "Exception( 'UnauthorizedUserException: Could not assign new role.') assignee_username = user_services.get_username(assignee_id)", "user.actions: if activity_rights.is_owner(user.user_id): return True return False def check_can_unpublish_activity(user, activity_rights):", "exploration_id, constants.ACTIVITY_TYPE_EXPLORATION) # Rights functions for collections. def assign_role_for_collection( committer,", "committer_id, activity_rights, activity_type, commit_message, commit_cmds): \"\"\"Saves an ExplorationRights or CollectionRights", "new role: One of ROLE_OWNER ROLE_EDITOR Raises: Exception. This could", "\"\"\"Domain objects and functions that manage rights for various user", "a new role to the user. Args: committer: UserActionsInfo. UserActionInfo", "exp_services.update_exploration_summary( activity_rights.id, None) def _update_collection_summary(activity_rights): \"\"\"Updates the collection summary for", "the ID of associated activity. Args: activity_type: str. The type", "\"\"\" exploration_rights = get_exploration_rights(exploration_id) return exploration_rights.status == ACTIVITY_STATUS_PUBLIC def is_exploration_cloned(exploration_id):", "bool. Whether the user can publish given activity. \"\"\" if", "'translator' ROLE_VIEWER = 'viewer' ROLE_NONE = 'none' ROLE_ADMIN = 'admin'", "activity_rights.status activity_rights.status = new_status if activity_type == constants.ACTIVITY_TYPE_EXPLORATION: cmd_type =", "'editor_names': user_services.get_human_readable_user_ids( self.editor_ids), 'translator_names': user_services.get_human_readable_user_ids( self.translator_ids), 'viewer_names': user_services.get_human_readable_user_ids( self.viewer_ids), 'viewable_if_private':", "role: One of ROLE_OWNER ROLE_EDITOR Raises: Exception. This could potentially", "tried to unpublish %s %s but was refused ' 'permission.'", "the model. \"\"\" return ActivityRights( activity_rights_model.id, activity_rights_model.owner_ids, activity_rights_model.editor_ids, activity_rights_model.translator_ids, activity_rights_model.viewer_ids,", "the collection. Raises: EntityNotFoundError. The collection with ID collection_id is", "rights for various user actions.\"\"\" import logging from constants import", "%s but was refused ' 'permission.' % (committer_id, activity_type, activity_id))", "of the collection. Returns: bool. Whether the collection is public.", "Returns: bool. Whether the collection is private. \"\"\" collection_rights =", "= 'release_ownership' CMD_UPDATE_FIRST_PUBLISHED_MSEC = 'update_first_published_msec' ACTIVITY_STATUS_PRIVATE = constants.ACTIVITY_STATUS_PRIVATE ACTIVITY_STATUS_PUBLIC =", "owner_ids=exploration_rights.owner_ids, editor_ids=exploration_rights.editor_ids, translator_ids=exploration_rights.translator_ids, viewer_ids=exploration_rights.viewer_ids, community_owned=exploration_rights.community_owned, status=exploration_rights.status, viewable_if_private=exploration_rights.viewable_if_private, first_published_msec=exploration_rights.first_published_msec, ).commit(committer_id, 'Created", "list of ActivityRights objects for given exploration ids. Args: exp_ids:", "ActivityRights objects for given exploration ids. Args: exp_ids: list(str). List", "%ss can be viewed by anyone.' % activity_type) activity_rights.viewer_ids.append(assignee_id) else:", "an activity owner. \"\"\" return bool(user_id in self.owner_ids) def is_editor(self,", "user can publish given activity. \"\"\" if activity_rights is None:", "for activities. def assign_role_for_exploration( committer, exploration_id, assignee_id, new_role): \"\"\"Assigns a", "'Public %ss can be viewed by anyone.' % activity_type) activity_rights.viewer_ids.append(assignee_id)", "to the given role and subscribes the assignee to future", "self.status, 'community_owned': True, 'owner_names': [], 'editor_names': [], 'translator_names': [], 'viewer_names':", "collection. committer_id: str. ID of the committer. \"\"\" collection_rights =", "'cmd': CMD_UPDATE_FIRST_PUBLISHED_MSEC, 'old_first_published_msec': activity_rights.first_published_msec, 'new_first_published_msec': first_published_msec }] activity_rights.first_published_msec = first_published_msec", "[], 'viewable_if_private': self.viewable_if_private, } else: return { 'cloned_from': self.cloned_from, 'status':", "explorations should have no owners, ' 'editors, translators or viewers", "the exploration. Returns: bool. Whether the exploration is private or", "\"\"\" return bool(user_id in self.viewer_ids) def is_published(self): \"\"\"Checks whether activity", "activity_rights.is_translator(user.user_id) or activity_rights.viewable_if_private) def check_can_edit_activity(user, activity_rights): \"\"\"Checks whether the user", "activity_rights.first_published_msec is None: activity_rights.first_published_msec = ( utils.get_current_time_in_millisecs()) _save_activity_rights( committer_id, activity_rights,", "ROLE_VIEWER elif new_role == ROLE_TRANSLATOR: if (activity_rights.is_editor(assignee_id) or activity_rights.is_translator(assignee_id) or", "previous exploration snapshots in the datastore. # Do not modify", "assignee_id in activity_rights.translator_ids: activity_rights.translator_ids.remove(assignee_id) old_role = ROLE_TRANSLATOR if assignee_id in", "of the activity. first_published_msec: float. First publication time in milliseconds", "_get_activity_rights(activity_type, activity_id) if not check_can_unpublish_activity(committer, activity_rights): logging.error( 'User %s tried", "activity_rights.editor_ids model.viewer_ids = activity_rights.viewer_ids model.translator_ids = activity_rights.translator_ids model.community_owned = activity_rights.community_owned", "is_exploration_private(exploration_id): \"\"\"Returns whether exploration is private. Args: exploration_id: str. ID", "the collection is public. \"\"\" collection_rights = get_collection_rights(collection_id) return collection_rights.status", "Returns: bool. Whether the collection is public. \"\"\" collection_rights =", "Whether the given user can translate this activity. \"\"\" if", "This could potentially throw an exception from _unpublish_activity. \"\"\" _unpublish_activity(", "'owner' ROLE_EDITOR = 'editor' ROLE_TRANSLATOR = 'translator' ROLE_VIEWER = 'viewer'", "the committer. collection_id: str. ID of the collection. Raises: Exception.", "return get_collection_rights(activity_id, strict=False) else: raise Exception( 'Cannot get activity rights", "values: constants.ACTIVITY_TYPE_EXPLORATION constants.ACTIVITY_TYPE_COLLECTION Raises: Exception. The committer does not have", "The type of activity. Possible values: constants.ACTIVITY_TYPE_EXPLORATION constants.ACTIVITY_TYPE_COLLECTION Returns: ActivityRights.", "\"\"\"Saves an ExplorationRights or CollectionRights domain object to the datastore.", "new_status }] if new_status != ACTIVITY_STATUS_PRIVATE: activity_rights.viewer_ids = [] if", "get_exploration_rights(exploration_id) # The user who can publish activity can change", "str. The type of activity. Possible values: constants.ACTIVITY_TYPE_EXPLORATION constants.ACTIVITY_TYPE_COLLECTION Raise:", "Returns: list(str). Human-readable usernames (or truncated email addresses) of owners", "exploration. Returns: bool. Whether the exploration is public. \"\"\" exploration_rights", "Subscribes the committer to the new collection. Args: collection_id: str.", "activity can change its private viewability. if not check_can_publish_activity(committer, exploration_rights):", "and subscribes the assignee to future collection updates. The caller", "or self.editor_ids or self.translator_ids or self.viewer_ids): raise utils.ValidationError( 'Community-owned explorations", "return False if (activity_rights.is_owner(user.user_id) or activity_rights.is_editor(user.user_id)): return True if (activity_rights.community_owned", "UserActionInfo object for the user who is performing the action.", "model, constants.ACTIVITY_TYPE_EXPLORATION)) return exp_models_list def is_exploration_private(exploration_id): \"\"\"Returns whether exploration is", "exploration. It is the responsibility of the caller to check", "# Rights functions for activities. def assign_role_for_exploration( committer, exploration_id, assignee_id,", "Possible values: constants.ACTIVITY_TYPE_EXPLORATION constants.ACTIVITY_TYPE_COLLECTION Returns: ActivityRights. The rights object created", "in user.actions: return False if (activity_rights.is_owner(user.user_id) or activity_rights.is_editor(user.user_id)): return True", "is distributed on an \"AS-IS\" BASIS, # WITHOUT WARRANTIES OR", "activity_type, commit_message, commit_cmds): \"\"\"Saves an ExplorationRights or CollectionRights domain object", "done. \"\"\" activity_rights.validate() if activity_type == constants.ACTIVITY_TYPE_EXPLORATION: model_cls = exp_models.ExplorationRightsModel", "get_collection_rights(activity_id, strict=False) else: raise Exception( 'Cannot get activity rights for", "is already publicly editable. Exception. The activity is already publicly", "\"\"\"Returns whether the collection is private. Args: collection_id: str. ID", "user cannot be both a translator and a viewer: %s'", "constants.ACTIVITY_TYPE_COLLECTION new_status: str. The new status of the activity. commit_message:", "= ( 'Made exploration viewable to anyone with the link.'", "\"\"\"Constructs an ActivityRights object from the given activity rights model.", "user is translator of activity. Args: user_id: str or None.", "published time in msec', commit_cmds) def create_new_exploration_rights(exploration_id, committer_id): \"\"\"Creates a", "raise utils.ValidationError( 'Community-owned explorations should have no owners, ' 'editors,", "delete given activity. \"\"\" if activity_rights is None: return False", "(committer_id, activity_type, activity_id)) raise Exception('This %s cannot be published.' %", "The new status of the activity. commit_message: str. The human-written", "publish_collection(committer, collection_id): \"\"\"Publishes the given collection. It is the responsibility", "datastore. Args: collection_id: str. ID of the collection. strict: bool.", "collection_id: str. ID of the collection. Returns: bool. Whether the", "not have release rights. \"\"\" committer_id = committer.user_id activity_rights =", "translatable. Exception. The user can already view the activity. Exception.", "You may obtain a copy of the License at #", "any of the owners, editors, translators and viewers lists overlap,", "rights object for the given activity. \"\"\" from core.domain import", "activity_rights.is_owner(user.user_id) or activity_rights.is_editor(user.user_id) or activity_rights.is_translator(user.user_id) or activity_rights.viewable_if_private) def check_can_edit_activity(user, activity_rights):", "publicly editable. Exception. The activity is already publicly translatable. Exception.", "return False return check_can_modify_activity_roles( user, activity_rights) def check_can_publish_activity(user, activity_rights): \"\"\"Checks", "a dict suitable for use by the frontend. Returns: dict.", "_get_activity_rights(activity_type, activity_id) if not check_can_release_ownership(committer, activity_rights): logging.error( 'User %s tried", "Whether user is an activity translator. \"\"\" return bool(user_id in", "= owner_ids self.editor_ids = editor_ids self.translator_ids = translator_ids self.viewer_ids =", "\"\"\" _release_ownership_of_activity( committer, exploration_id, constants.ACTIVITY_TYPE_EXPLORATION) def set_private_viewability_of_exploration( committer, exploration_id, viewable_if_private):", "role_services from core.domain import subscription_services from core.domain import user_services from", "the definitions of CMD keys that already exist. CMD_CREATE_NEW =", "it. Args: activity_type: str. The type of activity. Possible values:", "this %s.' % activity_type) activity_rights.owner_ids.append(assignee_id) if assignee_id in activity_rights.viewer_ids: activity_rights.viewer_ids.remove(assignee_id)", "ActivityRights object from the given activity rights model. Args: activity_rights_model:", "existing exploration or None. \"\"\" exp_rights_models = exp_models.ExplorationRightsModel.get_multi( exp_ids) exp_models_list", "activity_id) if not check_can_publish_activity(committer, activity_rights): logging.error( 'User %s tried to", "is_translator(self, user_id): \"\"\"Checks whether given user is translator of activity.", "False def _assign_role( committer, assignee_id, new_role, activity_id, activity_type): \"\"\"Assigns a", "ID of the activity. Returns: ActivityRights. The rights object associated", "the user. Args: committer: UserActionsInfo. UserActionInfo object for the user", "set_private_viewability_of_exploration( committer, exploration_id, viewable_if_private): \"\"\"Sets the viewable_if_private attribute for the", "Whether the user can delete given activity. \"\"\" if activity_rights", "field for the given activity. The caller is responsible for", "raise Exception( 'The ownership of this %s cannot be released.'", "= model_cls.get(activity_rights.id, strict=False) model.owner_ids = activity_rights.owner_ids model.editor_ids = activity_rights.editor_ids model.viewer_ids", "activity_rights.viewer_ids = [] if activity_rights.first_published_msec is None: activity_rights.first_published_msec = (", "ownership of the given exploration to the community. Args: committer:", "an activity translator. \"\"\" return bool(user_id in self.translator_ids) def is_viewer(self,", "strict=False) elif activity_type == constants.ACTIVITY_TYPE_COLLECTION: return get_collection_rights(activity_id, strict=False) else: raise", "viewable_if_private is True, this allows a private exploration to be", "values: constants.ACTIVITY_TYPE_EXPLORATION constants.ACTIVITY_TYPE_COLLECTION activity_id: str. ID of the activity. first_published_msec:", "bool. Whether user is an activity translator. \"\"\" return bool(user_id", "in user.actions) and activity_rights.is_owner(user.user_id)): return True elif (activity_rights.is_published() and (role_services.ACTION_DELETE_ANY_PUBLIC_ACTIVITY", "publish activity can change its private viewability. if not check_can_publish_activity(committer,", "if self.community_owned: return { 'cloned_from': self.cloned_from, 'status': self.status, 'community_owned': True,", "user. Returns: bool. Whether user is an activity editor. \"\"\"", "if old_viewable_if_private == viewable_if_private: raise Exception( 'Trying to change viewability", "UserActionsInfo. UserActionInfo object for the user who is performing the", "human-written commit message for this change. \"\"\" activity_rights = _get_activity_rights(activity_type,", "cloned_from=None, status=ACTIVITY_STATUS_PRIVATE, viewable_if_private=False, first_published_msec=None): self.id = exploration_id self.owner_ids = owner_ids", "collection. Returns: bool. Whether the collection is private. \"\"\" collection_rights", "Ensure that all changes to how these cmds are interpreted", "elif activity_type == constants.ACTIVITY_TYPE_COLLECTION: cmd_type = CMD_CHANGE_COLLECTION_STATUS commit_cmds = [{", "# TODO(msl): get rid of inline imports by refactoring code.", "elif (activity_rights.is_published() and (role_services.ACTION_DELETE_ANY_PUBLIC_ACTIVITY in user.actions)): return True return False", "specified. \"\"\" if self.community_owned: if (self.owner_ids or self.editor_ids or self.translator_ids", "True if (role_services.ACTION_MODIFY_ROLES_FOR_OWNED_ACTIVITY in user.actions): if activity_rights.is_owner(user.user_id): return True return", "given collection. Args: committer: UserActionsInfo. UserActionsInfo object for the committer.", "# Copyright 2014 The Oppia Authors. All Rights Reserved. #", "_update_exploration_summary(activity_rights): \"\"\"Updates the exploration summary for the activity associated with", "activity_type) activity_rights.editor_ids.append(assignee_id) if assignee_id in activity_rights.translator_ids: activity_rights.translator_ids.remove(assignee_id) old_role = ROLE_TRANSLATOR", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "the License. \"\"\"Domain objects and functions that manage rights for", "collection_id) def get_collection_rights(collection_id, strict=True): \"\"\"Retrieves the rights for this collection", "owners for this collection. \"\"\" collection_rights = get_collection_rights(collection_id) return user_services.get_human_readable_user_ids(", "if activity_rights is None: return False if activity_rights.community_owned: return False", "ownership of this %s cannot be released.' % activity_type) activity_rights.community_owned", "Exception. If the viewable_if_private property is already as desired. \"\"\"", "the given activity. Args: committer: UserActionsInfo. UserActionsInfo object for the", "return bool( (role_services.ACTION_PLAY_ANY_PRIVATE_ACTIVITY in user.actions) or activity_rights.is_viewer(user.user_id) or activity_rights.is_owner(user.user_id) or", "This could potentially throw an exception from _release_ownership_of_activity. \"\"\" _release_ownership_of_activity(", "activity associated with the given rights object. The ID of", "'Community-owned %ss can be translated by anyone.' % activity_type) activity_rights.translator_ids.append(assignee_id)", "community. Args: committer: UserActionsInfo. UserActionsInfo object for the user who", "self.translator_ids) def is_viewer(self, user_id): \"\"\"Checks whether given user is viewer", "private viewability of exploration %s ' 'but was refused permission.'", "ACTIVITY_STATUS_PRIVATE: raise Exception( 'Public %ss can be viewed by anyone.'", "from core.domain import exp_services exp_services.update_exploration_summary( activity_rights.id, None) def _update_collection_summary(activity_rights): \"\"\"Updates", "committer, exploration_id, constants.ACTIVITY_TYPE_EXPLORATION) def set_private_viewability_of_exploration( committer, exploration_id, viewable_if_private): \"\"\"Sets the", "user_id, role and actions for given user. activity_rights: AcitivityRights or", "utf-8 # # Copyright 2014 The Oppia Authors. All Rights", "new_role): \"\"\"Assigns a user to the given role and subscribes", "check_can_modify_activity_roles(committer, activity_rights): logging.error( 'User %s tried to allow user %s", "given role and subscribes the assignee to future exploration updates.", "the new role: One of ROLE_OWNER ROLE_EDITOR ROLE_TRANSLATOR ROLE_VIEWER activity_id:", "collection rights object and saves it to the datastore. Subscribes", "new_role == ROLE_TRANSLATOR: if (activity_rights.is_editor(assignee_id) or activity_rights.is_translator(assignee_id) or activity_rights.is_owner(assignee_id)): raise", "committer_id, activity_rights, activity_type, '%s ownership released to the community.' %", "_save_activity_rights( committer_id, activity_rights, activity_type, commit_message, commit_cmds) _update_activity_summary(activity_type, activity_rights) def _publish_activity(committer,", "= exp_models.ExplorationRightsModel elif activity_type == constants.ACTIVITY_TYPE_COLLECTION: model_cls = collection_models.CollectionRightsModel model", "committer_id: str. ID of the user who is performing the", "if role_services.ACTION_EDIT_OWNED_ACTIVITY not in user.actions: return False if (activity_rights.is_owner(user.user_id) or", "bool. Whether the given activity can be accessed by the", "the user can delete given activity. \"\"\" if activity_rights is", "commit_cmds: list(dict). A list of commands describing what kind of", "it to the datastore. Subscribes the committer to the new", "user can edit this activity. \"\"\" if activity_rights is None:", "activity_rights.translator_ids: activity_rights.translator_ids.remove(assignee_id) old_role = ROLE_TRANSLATOR elif new_role == ROLE_EDITOR: if", ") def _save_activity_rights( committer_id, activity_rights, activity_type, commit_message, commit_cmds): \"\"\"Saves an", "is None: return False elif activity_rights.is_published(): return bool( role_services.ACTION_PLAY_ANY_PUBLIC_ACTIVITY in", "\"\"\"Unpublishes the given collection. Args: committer: UserActionsInfo. UserActionsInfo object for", "%s ' 'but was refused permission.' % ( committer_id, assignee_id,", "given activity. \"\"\" from core.domain import collection_services collection_services.update_collection_summary( activity_rights.id, None)", "for the committer. exploration_id: str. ID of the exploration. viewable_if_private:", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "user_services.get_human_readable_user_ids( self.translator_ids), 'viewer_names': user_services.get_human_readable_user_ids( self.viewer_ids), 'viewable_if_private': self.viewable_if_private, } def is_owner(self,", "of the activity. Returns: ActivityRights. The rights object associated with", "whether the user can release ownership for given activity. Args:", "elif new_role == ROLE_EDITOR: if (activity_rights.is_editor(assignee_id) or activity_rights.is_owner(assignee_id)): raise Exception(", "of another exploration. \"\"\" exploration_rights = get_exploration_rights(exploration_id) return bool(exploration_rights.cloned_from) def", "the collection. Raises: Exception. This could potentially throw an exception", "collection. It is the responsibility of the caller to check", "License. # You may obtain a copy of the License", "True return False def _assign_role( committer, assignee_id, new_role, activity_id, activity_type):", "ROLE_VIEWER = 'viewer' ROLE_NONE = 'none' ROLE_ADMIN = 'admin' ROLE_MODERATOR", "can access given activity. Args: user: UserActionsInfo. Object having user_id,", "return bool(self.status == ACTIVITY_STATUS_PRIVATE) def get_activity_rights_from_model(activity_rights_model, activity_type): \"\"\"Constructs an ActivityRights", "\"\"\"Checks whether given user is viewer of activity. Args: user_id:", "model.translator_ids = activity_rights.translator_ids model.community_owned = activity_rights.community_owned model.status = activity_rights.status model.viewable_if_private", "Do not modify the definitions of CMD keys that already", "is invalid. \"\"\" committer_id = committer.user_id activity_rights = _get_activity_rights(activity_type, activity_id)", "old_status, 'new_status': new_status }] if new_status != ACTIVITY_STATUS_PRIVATE: activity_rights.viewer_ids =", "cmds are interpreted preserve # backward-compatibility with previous exploration snapshots", "exp_models.ExplorationRightsModel.get_multi( exp_ids) exp_models_list = [] for model in exp_rights_models: if", "the datastore. \"\"\" model = exp_models.ExplorationRightsModel.get( exploration_id, strict=strict) if model", "collection_services collection_services.update_collection_summary( activity_rights.id, None) def _update_activity_summary(activity_type, activity_rights): \"\"\"Updates the activity", "False if role_services.ACTION_EDIT_OWNED_ACTIVITY not in user.actions: return False if (activity_rights.is_owner(user.user_id)", "== ACTIVITY_STATUS_PRIVATE) def get_activity_rights_from_model(activity_rights_model, activity_type): \"\"\"Constructs an ActivityRights object from", "new_role: str. The name of the new role: One of", "exploration', commit_cmds) subscription_services.subscribe_to_exploration( committer_id, exploration_id) def get_exploration_rights(exploration_id, strict=True): \"\"\"Retrieves the", "if assignee_id in activity_rights.translator_ids: activity_rights.translator_ids.remove(assignee_id) old_role = ROLE_TRANSLATOR elif new_role", "for this change. \"\"\" activity_rights = _get_activity_rights(activity_type, activity_id) old_status =", "\"\"\"Retrieves the rights for this exploration from the datastore. Args:", "class ActivityRights(object): \"\"\"Domain object for the rights/publication status of an", "activity viewer. \"\"\" return bool(user_id in self.viewer_ids) def is_published(self): \"\"\"Checks", "strict=True): \"\"\"Retrieves the rights for this exploration from the datastore.", "given collection to the community. Args: committer: UserActionsInfo. UserActionsInfo object", "% activity_type) if activity_rights.status != ACTIVITY_STATUS_PRIVATE: raise Exception( 'Public %ss", "exp_models_list = [] for model in exp_rights_models: if model is", "having user_id, role and actions for given user. activity_rights: AcitivityRights", "activity_id, activity_type): \"\"\"Releases ownership of the given activity to the", "the rights for this exploration from the datastore. Args: exploration_id:", "user_services from core.platform import models import feconf import utils current_user_services", "or activity_rights.is_owner(assignee_id)): raise Exception( 'This user already can edit this", "in [ROLE_OWNER, ROLE_EDITOR]: subscription_services.subscribe_to_collection( assignee_id, collection_id) def release_ownership_of_collection(committer, collection_id): \"\"\"Releases", "is_collection_private(collection_id): \"\"\"Returns whether the collection is private. Args: collection_id: str.", "return check_can_modify_activity_roles( user, activity_rights) def check_can_publish_activity(user, activity_rights): \"\"\"Checks whether the", "self.community_owned and self.status == ACTIVITY_STATUS_PRIVATE: raise utils.ValidationError( 'Community-owned explorations cannot", "the given exploration's rights object. If viewable_if_private is True, this", "exist. CMD_CREATE_NEW = 'create_new' CMD_CHANGE_ROLE = 'change_role' CMD_CHANGE_EXPLORATION_STATUS = 'change_exploration_status'", "frontend. \"\"\" if self.community_owned: return { 'cloned_from': self.cloned_from, 'status': self.status,", "old_status = activity_rights.status activity_rights.status = new_status if activity_type == constants.ACTIVITY_TYPE_EXPLORATION:", "found in the datastore. \"\"\" model = exp_models.ExplorationRightsModel.get( exploration_id, strict=strict)", "if activity_rights.is_published(): return False if role_services.ACTION_PUBLISH_ANY_ACTIVITY in user.actions: return True", "str. Descriptive message for the commit. commit_cmds: list(dict). A list", "EntityNotFoundError. The collection with ID collection_id is not found in", "_release_ownership_of_activity( committer, exploration_id, constants.ACTIVITY_TYPE_EXPLORATION) def set_private_viewability_of_exploration( committer, exploration_id, viewable_if_private): \"\"\"Sets", "actions for given user. activity_rights: ActivityRights or None. Rights object", "new_role): \"\"\"Assign the given user to the given role and", "public. Args: collection_id: str. ID of the collection. Returns: bool.", "user: UserActionsInfo. Object having user_id, role and actions for given", "activity_rights): \"\"\"Checks whether the user can publish given activity. Args:", "type: %s' % ( activity_type)) def check_can_access_activity(user, activity_rights): \"\"\"Checks whether", "constants.ACTIVITY_TYPE_EXPLORATION: return get_exploration_rights(activity_id, strict=False) elif activity_type == constants.ACTIVITY_TYPE_COLLECTION: return get_collection_rights(activity_id,", "user.actions) elif activity_rights.is_private(): return bool( (role_services.ACTION_PLAY_ANY_PRIVATE_ACTIVITY in user.actions) or activity_rights.is_viewer(user.user_id)", "ID of the committer. \"\"\" collection_rights = ActivityRights( collection_id, [committer_id],", "exploration is private. Args: exploration_id: str. ID of the exploration.", "and a viewer: %s' % editor_viewer) if translator_viewer: raise utils.ValidationError(", "status self.viewable_if_private = viewable_if_private self.first_published_msec = first_published_msec def validate(self): \"\"\"Validates", "return bool(user_id in self.translator_ids) def is_viewer(self, user_id): \"\"\"Checks whether given", "from the datastore. Args: collection_id: str. ID of the collection.", "return True elif (activity_rights.is_private() and (role_services.ACTION_DELETE_OWNED_PRIVATE_ACTIVITY in user.actions) and activity_rights.is_owner(user.user_id)):", "ROLE_OWNER: if activity_rights.is_owner(assignee_id): raise Exception('This user already owns this %s.'", "from core.platform import models import feconf import utils current_user_services =", "return { 'cloned_from': self.cloned_from, 'status': self.status, 'community_owned': True, 'owner_names': [],", "CMD_CHANGE_EXPLORATION_STATUS elif activity_type == constants.ACTIVITY_TYPE_COLLECTION: cmd_type = CMD_CHANGE_COLLECTION_STATUS commit_cmds =", "attribute for the given exploration's rights object. If viewable_if_private is", "False return check_can_modify_activity_roles( user, activity_rights) def check_can_publish_activity(user, activity_rights): \"\"\"Checks whether", "ACTIVITY_STATUS_PRIVATE: activity_rights.viewer_ids = [] if activity_rights.first_published_msec is None: activity_rights.first_published_msec =", "new_status if activity_type == constants.ACTIVITY_TYPE_EXPLORATION: cmd_type = CMD_CHANGE_EXPLORATION_STATUS elif activity_type", "by anyone with the link. Args: committer: UserActionsInfo. UserActionsInfo object", "for the given activity. The caller is responsible for ensuring", "of exploration ids. Returns: list(ActivityRights or None). List of rights", "various user actions.\"\"\" import logging from constants import constants from", "A list of commands describing what kind of commit was", "ACTIVITY_STATUS_PRIVATE and self.viewer_ids: raise utils.ValidationError( 'Public explorations should have no", "overlap, or if a community-owned exploration has owners, editors, translators", "new collection', commit_cmds) subscription_services.subscribe_to_collection(committer_id, collection_id) def get_collection_rights(collection_id, strict=True): \"\"\"Retrieves the", "of activity. Possible values: constants.ACTIVITY_TYPE_EXPLORATION constants.ACTIVITY_TYPE_COLLECTION Raise: Exception. The committer", "committer, exploration_id, viewable_if_private): \"\"\"Sets the viewable_if_private attribute for the given", "\"\"\" _assign_role( committer, assignee_id, new_role, collection_id, constants.ACTIVITY_TYPE_COLLECTION) if new_role in", "constants import constants from core.domain import activity_services from core.domain import", "ROLE_TRANSLATOR Raises: Exception. This could potentially throw an exception from", "Whether user is an activity viewer. \"\"\" return bool(user_id in", "activity_type == constants.ACTIVITY_TYPE_EXPLORATION: model_cls = exp_models.ExplorationRightsModel elif activity_type == constants.ACTIVITY_TYPE_COLLECTION:", "of the exploration. viewable_if_private: bool. Whether the exploration should be", "bool. Whether user is an activity owner. \"\"\" return bool(user_id", "is viewer of activity. Args: user_id: str or None. Id", "Raises: Exception. This could potentially throw an exception from _unpublish_activity.", "Raises: utils.ValidationError: if any of the owners, editors, translators and", "responsibility of the caller to check that the collection is", "translator: %s' % owner_translator) if owner_viewer: raise utils.ValidationError( 'A user", "list(ActivityRights or None). List of rights object containing ActivityRights object", "activity_type, commit_message, commit_cmds) _update_activity_summary(activity_type, activity_rights) def _release_ownership_of_activity(committer, activity_id, activity_type): \"\"\"Releases", "if self.community_owned and self.status == ACTIVITY_STATUS_PRIVATE: raise utils.ValidationError( 'Community-owned explorations", "manage rights for various user actions.\"\"\" import logging from constants", "activity. first_published_msec: float. First publication time in milliseconds since the", "model.owner_ids = activity_rights.owner_ids model.editor_ids = activity_rights.editor_ids model.viewer_ids = activity_rights.viewer_ids model.translator_ids", "[{ 'cmd': cmd_type, 'old_status': old_status, 'new_status': new_status }] if new_status", "get_exploration_rights(exploration_id) return bool(exploration_rights.cloned_from) def create_new_collection_rights(collection_id, committer_id): \"\"\"Creates a new collection", "translate given activity. Args: user: UserActionsInfo. Object having user_id, role", "status of the activity. commit_message: str. The human-written commit message", "commit_cmds) subscription_services.subscribe_to_exploration( committer_id, exploration_id) def get_exploration_rights(exploration_id, strict=True): \"\"\"Retrieves the rights", "a translator and a viewer: %s' % translator_viewer) def to_dict(self):", "CMD_CHANGE_ROLE = 'change_role' CMD_CHANGE_EXPLORATION_STATUS = 'change_exploration_status' CMD_CHANGE_COLLECTION_STATUS = 'change_collection_status' CMD_CHANGE_PRIVATE_VIEWABILITY", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "exploration with ID exploration_id was not found in the datastore.", ").commit(committer_id, 'Created new collection', commit_cmds) subscription_services.subscribe_to_collection(committer_id, collection_id) def get_collection_rights(collection_id, strict=True):", "cannot be changed.') old_viewable_if_private = exploration_rights.viewable_if_private if old_viewable_if_private == viewable_if_private:", "exploration is a clone of another exploration. \"\"\" exploration_rights =", "return False if activity_rights.is_private(): return False return check_can_modify_activity_roles( user, activity_rights)", "Raises: Exception. activity_type provided is unknown. \"\"\" if activity_type ==", "if (activity_rights.is_owner(assignee_id) or activity_rights.is_editor(assignee_id) or activity_rights.is_viewer(assignee_id)): raise Exception( 'This user", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "for the specific language governing permissions and # limitations under", "== constants.ACTIVITY_TYPE_EXPLORATION else None), status=activity_rights_model.status, viewable_if_private=activity_rights_model.viewable_if_private, first_published_msec=activity_rights_model.first_published_msec ) def _save_activity_rights(", "= [{ 'cmd': CMD_RELEASE_OWNERSHIP, }] _save_activity_rights( committer_id, activity_rights, activity_type, '%s", "get_collection_rights(collection_id) return collection_rights.status == ACTIVITY_STATUS_PUBLIC def _get_activity_rights(activity_type, activity_id): \"\"\"Retrieves the", "bool. Whether the given user can edit this activity. \"\"\"", "activity_rights.viewer_ids: activity_rights.viewer_ids.remove(assignee_id) old_role = ROLE_VIEWER elif new_role == ROLE_TRANSLATOR: if", "model, constants.ACTIVITY_TYPE_COLLECTION) def get_collection_owner_names(collection_id): \"\"\"Retrieves the owners for this collection", "editor_viewer: raise utils.ValidationError( 'A user cannot be both an editor", "(role_services.ACTION_DELETE_OWNED_PRIVATE_ACTIVITY in user.actions) and activity_rights.is_owner(user.user_id)): return True elif (activity_rights.is_published() and", "= set(self.owner_ids).intersection(set(self.viewer_ids)) editor_translator = set(self.editor_ids).intersection( set(self.translator_ids)) editor_viewer = set(self.editor_ids).intersection(set(self.viewer_ids)) translator_viewer", "for unknown activity type: %s' % ( activity_type)) def check_can_access_activity(user,", "functions that manage rights for various user actions.\"\"\" import logging", "= [] if activity_rights.first_published_msec is None: activity_rights.first_published_msec = ( utils.get_current_time_in_millisecs())", "required by applicable law or agreed to in writing, software", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "the collection. committer_id: str. ID of the committer. \"\"\" collection_rights", "exploration_id: str. ID of the exploration. viewable_if_private: bool. Whether the", "code. from core.domain import exp_services exp_services.update_exploration_summary( activity_rights.id, None) def _update_collection_summary(activity_rights):", "_publish_activity( committer, exploration_id, constants.ACTIVITY_TYPE_EXPLORATION) def unpublish_exploration(committer, exploration_id): \"\"\"Unpublishes the given", "'status': self.status, 'community_owned': False, 'owner_names': user_services.get_human_readable_user_ids( self.owner_ids), 'editor_names': user_services.get_human_readable_user_ids( self.editor_ids),", "False, 'owner_names': user_services.get_human_readable_user_ids( self.owner_ids), 'editor_names': user_services.get_human_readable_user_ids( self.editor_ids), 'translator_names': user_services.get_human_readable_user_ids( self.translator_ids),", "exploration_id) def release_ownership_of_exploration(committer, exploration_id): \"\"\"Releases ownership of the given exploration", "of the owners, editors, translators and viewers lists overlap, or", "an exception from _publish_activity. \"\"\" _publish_activity( committer, collection_id, constants.ACTIVITY_TYPE_COLLECTION) def", "given user is owner of activity. Args: user_id: str or", "property is already as desired. \"\"\" committer_id = committer.user_id exploration_rights", "return False if activity_rights.cloned_from: return False if activity_rights.is_published(): return False", "constants.ACTIVITY_TYPE_EXPLORATION else None), status=activity_rights_model.status, viewable_if_private=activity_rights_model.viewable_if_private, first_published_msec=activity_rights_model.first_published_msec ) def _save_activity_rights( committer_id,", "is the responsibility of the caller to check that the", "The collection with ID collection_id is not found in the", "to raise an error if there is no exploration matching", "activity_rights = _get_activity_rights(activity_type, activity_id) if not check_can_modify_activity_roles(committer, activity_rights): logging.error( 'User", "ROLE_VIEWER elif new_role == ROLE_VIEWER: if (activity_rights.is_owner(assignee_id) or activity_rights.is_editor(assignee_id) or", "in the system. Args: committer: UserActionsInfo. The UserActionsInfo object for", "that already exist. CMD_CREATE_NEW = 'create_new' CMD_CHANGE_ROLE = 'change_role' CMD_CHANGE_EXPLORATION_STATUS", "agreed to in writing, software # distributed under the License", "given activity. activity_type: str. The type of activity. Possible values:", "activity_rights.cloned_from): return False if (role_services.ACTION_MODIFY_ROLES_FOR_ANY_ACTIVITY in user.actions): return True if", "= constants.ACTIVITY_STATUS_PUBLIC ROLE_OWNER = 'owner' ROLE_EDITOR = 'editor' ROLE_TRANSLATOR =", "of the collection. Returns: bool. Whether the collection is private.", "collection. Returns: bool. Whether the collection is public. \"\"\" collection_rights", "already owns the activity. Exception. The user can already edit", "activity_type): \"\"\"Releases ownership of the given activity to the community.", "committer, collection_id, constants.ACTIVITY_TYPE_COLLECTION) def publish_collection(committer, collection_id): \"\"\"Publishes the given collection.", "self.status != ACTIVITY_STATUS_PRIVATE and self.viewer_ids: raise utils.ValidationError( 'Public explorations should", "[{ 'cmd': CMD_UPDATE_FIRST_PUBLISHED_MSEC, 'old_first_published_msec': activity_rights.first_published_msec, 'new_first_published_msec': first_published_msec }] activity_rights.first_published_msec =", "raise utils.ValidationError( 'A user cannot be both a translator and", "Raises: Exception. The committer does not have rights to publish", "= activity_rights.viewer_ids model.translator_ids = activity_rights.translator_ids model.community_owned = activity_rights.community_owned model.status =", "The rights object associated with the given activity. Raises: Exception.", "is already publicly viewable. Exception. The role is invalid. \"\"\"", "given activity. Returns: bool. Whether the user can release ownership", "activity_rights): logging.error( 'User %s tried to allow user %s to", "activity_id)) raise Exception('This %s cannot be published.' % activity_type) _change_activity_status(", "check_can_release_ownership(user, activity_rights): \"\"\"Checks whether the user can release ownership for", "viewable_if_private self.first_published_msec = first_published_msec def validate(self): \"\"\"Validates an ActivityRights object.", "committer: UserActionsInfo. The UserActionsInfo object for the committer. exploration_id: str.", "ID of the user whose role is being changed. new_role:", "already can translate this %s.' % activity_type) if activity_rights.community_owned: raise", "}] _save_activity_rights( committer_id, activity_rights, activity_type, commit_message, commit_cmds) _update_activity_summary(activity_type, activity_rights) def", "for given activity. Args: user: UserActionsInfo. Object having user_id, role", "is_viewer(self, user_id): \"\"\"Checks whether given user is viewer of activity.", "ids. Returns: list(ActivityRights or None). List of rights object containing", "user.actions: return False if (activity_rights.is_owner(user.user_id) or activity_rights.is_editor(user.user_id)): return True if", "def get_activity_rights_from_model(activity_rights_model, activity_type): \"\"\"Constructs an ActivityRights object from the given", "False if role_services.ACTION_DELETE_ANY_ACTIVITY in user.actions: return True elif (activity_rights.is_private() and", "Whether the exploration is private or not. \"\"\" exploration_rights =", "object for existing exploration or None. \"\"\" exp_rights_models = exp_models.ExplorationRightsModel.get_multi(", "Whether activity is published. \"\"\" return bool(self.status == ACTIVITY_STATUS_PUBLIC) def", "activity_type): \"\"\"Assigns a new role to the user. Args: committer:", "str. ID of the activity. activity_type: str. The type of", "this collection from the datastore. Args: collection_id: str. ID of", "ROLE_VIEWER if assignee_id in activity_rights.editor_ids: activity_rights.editor_ids.remove(assignee_id) old_role = ROLE_EDITOR if", "a clone of another exploration. Args: exploration_id: str. ID of", "the collection. Returns: bool. Whether the collection is private. \"\"\"", "of the user. Returns: bool. Whether user is an activity", "commit_cmds) _update_activity_summary(activity_type, activity_rights) def _release_ownership_of_activity(committer, activity_id, activity_type): \"\"\"Releases ownership of", "_update_activity_summary(activity_type, activity_rights): \"\"\"Updates the activity summary for the given activity", "str. ID of the exploration. Raises: Exception. This could potentially", "def _update_exploration_summary(activity_rights): \"\"\"Updates the exploration summary for the activity associated", "or viewers specified.') if self.community_owned and self.status == ACTIVITY_STATUS_PRIVATE: raise", "editor of activity. Args: user_id: str or None. Id of", "can be viewed by anyone.' % activity_type) activity_rights.viewer_ids.append(assignee_id) else: raise", "UserActionsInfo object for the user who is performing the action.", "committer does not have rights to publish the activity. \"\"\"", "or not. \"\"\" exploration_rights = get_exploration_rights(exploration_id) return exploration_rights.status == ACTIVITY_STATUS_PRIVATE", "with the link.' if viewable_if_private else 'Made exploration viewable only", "activity_type) def _unpublish_activity(committer, activity_id, activity_type): \"\"\"Unpublishes the given activity. Args:", "owner_editor) if owner_translator: raise utils.ValidationError( 'A user cannot be both", "activity. Exception. The activity is already publicly editable. Exception. The", "'A user cannot be both an editor and a viewer:", "is public. \"\"\" collection_rights = get_collection_rights(collection_id) return collection_rights.status == ACTIVITY_STATUS_PUBLIC", "elif activity_type == constants.ACTIVITY_TYPE_COLLECTION: model_cls = collection_models.CollectionRightsModel model = model_cls.get(activity_rights.id,", "was refused permission.' % (committer_id, exploration_id)) raise Exception( 'The viewability", "constants.ACTIVITY_STATUS_PRIVATE ACTIVITY_STATUS_PUBLIC = constants.ACTIVITY_STATUS_PUBLIC ROLE_OWNER = 'owner' ROLE_EDITOR = 'editor'", "assignee to future collection updates. The caller should ensure that", "type of activity. Possible values: constants.ACTIVITY_TYPE_EXPLORATION constants.ACTIVITY_TYPE_COLLECTION Raises: Exception. The", "\"\"\" activity_rights = _get_activity_rights(activity_type, activity_id) commit_cmds = [{ 'cmd': CMD_UPDATE_FIRST_PUBLISHED_MSEC,", "Raises: Exception. The committer does not have rights to modify", "user whose role is being changed. new_role: str. The name", "exploration_id: str. ID of the exploration. assignee_id: str. ID of", "'change_collection_status' CMD_CHANGE_PRIVATE_VIEWABILITY = 'change_private_viewability' CMD_RELEASE_OWNERSHIP = 'release_ownership' CMD_UPDATE_FIRST_PUBLISHED_MSEC = 'update_first_published_msec'", "def is_exploration_private(exploration_id): \"\"\"Returns whether exploration is private. Args: exploration_id: str.", "'old_first_published_msec': activity_rights.first_published_msec, 'new_first_published_msec': first_published_msec }] activity_rights.first_published_msec = first_published_msec _save_activity_rights( feconf.SYSTEM_COMMITTER_ID,", "both an editor and a viewer: %s' % editor_viewer) if", "Exception. The user can already view the activity. Exception. The", "logging.error( 'User %s tried to release ownership of %s %s", "in milliseconds since the Epoch. \"\"\" activity_rights = _get_activity_rights(activity_type, activity_id)", "a translator: %s' % owner_translator) if owner_viewer: raise utils.ValidationError( 'A", "use by the frontend. \"\"\" if self.community_owned: return { 'cloned_from':", "exploration_id, owner_ids, editor_ids, translator_ids, viewer_ids, community_owned=False, cloned_from=None, status=ACTIVITY_STATUS_PRIVATE, viewable_if_private=False, first_published_msec=None):", "(activity_rights.is_published() and (role_services.ACTION_EDIT_ANY_PUBLIC_ACTIVITY in user.actions)): return True return False def", "check_can_translate_activity(user, activity_rights): \"\"\"Checks whether the user can translate given activity.", "already the current value.' % viewable_if_private) exploration_rights.viewable_if_private = viewable_if_private commit_cmds", "Exception. The activity is already publicly editable. Exception. The activity", "Args: user: UserActionsInfo. Object having user_id, role and actions for", "object and saves it to the datastore. Subscribes the committer", "from _release_ownership_of_activity. \"\"\" _release_ownership_of_activity( committer, exploration_id, constants.ACTIVITY_TYPE_EXPLORATION) def set_private_viewability_of_exploration( committer,", "role: %s' % new_role) commit_message = 'Changed role of %s", "activity_rights.is_viewer(assignee_id)): raise Exception( 'This user already can view this %s.'", "is being changed. new_role: str. The name of the new", "Exception. The committer does not have rights to publish the", "objects and functions that manage rights for various user actions.\"\"\"", "object is the same as the ID of associated activity.", "bool. Whether the exploration is a clone of another exploration.", "delete given activity. Args: user: UserActionsInfo. Object having user_id, role", "_save_activity_rights( committer_id, activity_rights, activity_type, commit_message, commit_cmds): \"\"\"Saves an ExplorationRights or", "update_activity_first_published_msec( activity_type, activity_id, first_published_msec): \"\"\"Updates the first_published_msec field for the", "in activity_rights.translator_ids: activity_rights.translator_ids.remove(assignee_id) old_role = ROLE_TRANSLATOR elif new_role == ROLE_EDITOR:", "ROLE_EDITOR Raises: Exception. This could potentially throw an exception from", "= ROLE_NONE if new_role == ROLE_OWNER: if activity_rights.is_owner(assignee_id): raise Exception('This", "is None: return False if (activity_rights.community_owned or activity_rights.cloned_from): return False", "else None), status=activity_rights_model.status, viewable_if_private=activity_rights_model.viewable_if_private, first_published_msec=activity_rights_model.first_published_msec ) def _save_activity_rights( committer_id, activity_rights,", "if role_services.ACTION_DELETE_ANY_ACTIVITY in user.actions: return True elif (activity_rights.is_private() and (role_services.ACTION_DELETE_OWNED_PRIVATE_ACTIVITY", "is_published(self): \"\"\"Checks whether activity is published. Returns: bool. Whether activity", "found in the datastore. \"\"\" model = collection_models.CollectionRightsModel.get( collection_id, strict=strict)", "action. activity_id: str. ID of the activity. activity_type: str. The", "actions for given user. activity_rights: AcitivityRights or None. Rights object", "be edited by anyone.' % activity_type) activity_rights.editor_ids.append(assignee_id) if assignee_id in", "commit_cmds = [{ 'cmd': CMD_RELEASE_OWNERSHIP, }] _save_activity_rights( committer_id, activity_rights, activity_type,", "object for the given activity. Returns: bool. Whether the given", "\"\"\" committer_id = committer.user_id activity_rights = _get_activity_rights(activity_type, activity_id) if not", "this exploration from the datastore. Args: exploration_id: str. ID of", "' 'but was refused permission.' % ( committer_id, assignee_id, new_role,", "if not check_can_publish_activity(committer, exploration_rights): logging.error( 'User %s tried to change", "OR CONDITIONS OF ANY KIND, either express or implied. #", "status=ACTIVITY_STATUS_PRIVATE, viewable_if_private=False, first_published_msec=None): self.id = exploration_id self.owner_ids = owner_ids self.editor_ids", "ACTIVITY_STATUS_PRIVATE def is_collection_public(collection_id): \"\"\"Returns whether the collection is public. Args:", "'none' ROLE_ADMIN = 'admin' ROLE_MODERATOR = 'moderator' class ActivityRights(object): \"\"\"Domain", "Returns: bool. Whether activity is published. \"\"\" return bool(self.status ==", "who can publish activity can change its private viewability. if", "check_can_unpublish_activity(user, activity_rights): \"\"\"Checks whether the user can unpublish given activity.", "new_status != ACTIVITY_STATUS_PRIVATE: activity_rights.viewer_ids = [] if activity_rights.first_published_msec is None:", "user_id, role and actions for given user. activity_rights: ActivityRights or", "activity_rights): \"\"\"Checks whether the user can modify roles for given", "committer_id, activity_rights, activity_type, commit_message, commit_cmds) _update_activity_summary(activity_type, activity_rights) def _release_ownership_of_activity(committer, activity_id,", "It is the responsibility of the caller to check that", "activity_rights, activity_type, commit_message, commit_cmds) _update_activity_summary(activity_type, activity_rights) def _release_ownership_of_activity(committer, activity_id, activity_type):", "Args: activity_rights_model: ActivityRightsModel. Activity rights from the datastore. activity_type: str.", "if new_role in [ROLE_OWNER, ROLE_EDITOR, ROLE_TRANSLATOR]: subscription_services.subscribe_to_exploration( assignee_id, exploration_id) def", "= CMD_CHANGE_COLLECTION_STATUS commit_cmds = [{ 'cmd': cmd_type, 'old_status': old_status, 'new_status':", "change private viewability of exploration %s ' 'but was refused", "of the given exploration to the community. Args: committer: UserActionsInfo.", "list(str). List of exploration ids. Returns: list(ActivityRights or None). List", "def is_collection_public(collection_id): \"\"\"Returns whether the collection is public. Args: collection_id:", "activity_rights_model: ActivityRightsModel. Activity rights from the datastore. activity_type: str. The", "False if activity_rights.is_published(): if role_services.ACTION_UNPUBLISH_ANY_PUBLIC_ACTIVITY in user.actions: return True return", "datastore. \"\"\" model = exp_models.ExplorationRightsModel.get( exploration_id, strict=strict) if model is", "ownership for given activity. \"\"\" if activity_rights is None: return", "given exploration. It is the responsibility of the caller to", "return ActivityRights( activity_rights_model.id, activity_rights_model.owner_ids, activity_rights_model.editor_ids, activity_rights_model.translator_ids, activity_rights_model.viewer_ids, community_owned=activity_rights_model.community_owned, cloned_from=( activity_rights_model.cloned_from", "activity. \"\"\" # TODO(msl): get rid of inline imports by", "in user.actions)): return True if (activity_rights.is_published() and (role_services.ACTION_EDIT_ANY_PUBLIC_ACTIVITY in user.actions)):", "have rights to publish the activity. \"\"\" committer_id = committer.user_id", "constants from core.domain import activity_services from core.domain import role_services from", "= 'create_new' CMD_CHANGE_ROLE = 'change_role' CMD_CHANGE_EXPLORATION_STATUS = 'change_exploration_status' CMD_CHANGE_COLLECTION_STATUS =", "owner_translator) if owner_viewer: raise utils.ValidationError( 'A user cannot be both", "set(self.editor_ids).intersection( set(self.viewer_ids)) if owner_editor: raise utils.ValidationError( 'A user cannot be", "viewer: %s' % translator_viewer) def to_dict(self): \"\"\"Returns a dict suitable", "law or agreed to in writing, software # distributed under", "return True return False def check_can_unpublish_activity(user, activity_rights): \"\"\"Checks whether the", "'viewer' ROLE_NONE = 'none' ROLE_ADMIN = 'admin' ROLE_MODERATOR = 'moderator'", "is already the current value.' % viewable_if_private) exploration_rights.viewable_if_private = viewable_if_private", "== ROLE_OWNER: if activity_rights.is_owner(assignee_id): raise Exception('This user already owns this", "given user. activity_rights: ActivityRights or None. Rights object for the", "subscription_services.subscribe_to_collection( assignee_id, collection_id) def release_ownership_of_collection(committer, collection_id): \"\"\"Releases ownership of the", "exploration_id) def get_exploration_rights(exploration_id, strict=True): \"\"\"Retrieves the rights for this exploration", "_update_exploration_summary(exploration_rights) def publish_exploration(committer, exploration_id): \"\"\"Publishes the given exploration. It is", "an \"AS-IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "object for the given activity. Returns: bool. Whether the user", "the new exploration. Args: exploration_id: str. ID of the exploration.", "Exception. The committer does not have rights to unpublish the", "'release_ownership' CMD_UPDATE_FIRST_PUBLISHED_MSEC = 'update_first_published_msec' ACTIVITY_STATUS_PRIVATE = constants.ACTIVITY_STATUS_PRIVATE ACTIVITY_STATUS_PUBLIC = constants.ACTIVITY_STATUS_PUBLIC", "self.first_published_msec = first_published_msec def validate(self): \"\"\"Validates an ActivityRights object. Raises:", "by the frontend. Returns: dict. A dict version of ActivityRights", "activity_rights.community_owned model.status = activity_rights.status model.viewable_if_private = activity_rights.viewable_if_private model.first_published_msec = activity_rights.first_published_msec", "(activity_rights.is_owner(assignee_id) or activity_rights.is_editor(assignee_id) or activity_rights.is_viewer(assignee_id)): raise Exception( 'This user already", "tried to allow user %s to be a(n) %s of", "constants.ACTIVITY_TYPE_COLLECTION Returns: ActivityRights. The rights object created from the model.", "return { 'cloned_from': self.cloned_from, 'status': self.status, 'community_owned': False, 'owner_names': user_services.get_human_readable_user_ids(", "and self.status == ACTIVITY_STATUS_PRIVATE: raise utils.ValidationError( 'Community-owned explorations cannot be", "Returns: bool. Whether the user can delete given activity. \"\"\"", "or activity_rights.is_owner(assignee_id)): raise Exception( 'This user already can translate this", "committer. collection_id: str. ID of the collection. assignee_id: str. ID", "= models.Registry.import_current_user_services() (collection_models, exp_models,) = models.Registry.import_models([ models.NAMES.collection, models.NAMES.exploration ]) #", "as desired. \"\"\" committer_id = committer.user_id exploration_rights = get_exploration_rights(exploration_id) #", "\"\"\"Updates the activity summary for the given activity associated with", "exception from _publish_activity. \"\"\" _publish_activity( committer, exploration_id, constants.ACTIVITY_TYPE_EXPLORATION) def unpublish_exploration(committer,", "given exploration. Args: committer: UserActionsInfo. UserActionsInfo object for the committer.", "may obtain a copy of the License at # #", "the rights/publication status of an activity (an exploration or a", "activity_rights_model.translator_ids, activity_rights_model.viewer_ids, community_owned=activity_rights_model.community_owned, cloned_from=( activity_rights_model.cloned_from if activity_type == constants.ACTIVITY_TYPE_EXPLORATION else", "\"\"\" if activity_rights is None: return False if activity_rights.is_private(): return", "activity_type == constants.ACTIVITY_TYPE_COLLECTION: return get_collection_rights(activity_id, strict=False) else: raise Exception( 'Cannot", "associated activity. Args: activity_type: str. The type of activity. Possible", "cannot be both an editor and a viewer: %s' %", "exception from _publish_activity. \"\"\" _publish_activity( committer, collection_id, constants.ACTIVITY_TYPE_COLLECTION) def unpublish_collection(committer,", "collection_id, constants.ACTIVITY_TYPE_COLLECTION) if new_role in [ROLE_OWNER, ROLE_EDITOR]: subscription_services.subscribe_to_collection( assignee_id, collection_id)", "\"\"\"Updates the exploration summary for the activity associated with the", "activity_rights.is_owner(assignee_id): raise Exception('This user already owns this %s.' % activity_type)", "given activity. The caller is responsible for ensuring that this", "'viewable_if_private': self.viewable_if_private, } def is_owner(self, user_id): \"\"\"Checks whether given user", "can edit this activity. \"\"\" if activity_rights is None: return", "= ROLE_TRANSLATOR if assignee_id in activity_rights.viewer_ids: activity_rights.viewer_ids.remove(assignee_id) old_role = ROLE_VIEWER", "activity_type) _change_activity_status( committer_id, activity_id, activity_type, ACTIVITY_STATUS_PRIVATE, '%s unpublished.' % activity_type)", "committer. exploration_id: str. ID of the exploration. assignee_id: str. ID", "an exception from _release_ownership_of_activity. \"\"\" _release_ownership_of_activity( committer, collection_id, constants.ACTIVITY_TYPE_COLLECTION) def", "may not use this file except in compliance with the", "cannot be both an owner and an editor: %s' %", "user is an activity viewer. \"\"\" return bool(user_id in self.viewer_ids)", "check that the exploration is valid prior to publication. Args:", "% ( assignee_username, old_role, new_role) commit_cmds = [{ 'cmd': CMD_CHANGE_ROLE,", "str. The human-written commit message for this change. \"\"\" activity_rights", "= get_exploration_rights(exploration_id) return exploration_rights.status == ACTIVITY_STATUS_PUBLIC def is_exploration_cloned(exploration_id): \"\"\"Returns whether", "committer_id = committer.user_id activity_rights = _get_activity_rights(activity_type, activity_id) if not check_can_publish_activity(committer,", "in the system. Args: committer: UserActionsInfo. UserActionsInfo object for the", "ROLE_TRANSLATOR ROLE_VIEWER activity_id: str. ID of the activity. activity_type: str.", "this file except in compliance with the License. # You", "to publish %s %s but was refused ' 'permission.' %", "first_published_msec=None): self.id = exploration_id self.owner_ids = owner_ids self.editor_ids = editor_ids", "activity. Possible values: constants.ACTIVITY_TYPE_EXPLORATION constants.ACTIVITY_TYPE_COLLECTION Returns: ActivityRights. The rights object", "object for the user who is performing the action. assignee_id:", "ROLE_EDITOR ROLE_TRANSLATOR Raises: Exception. This could potentially throw an exception", "def publish_collection(committer, collection_id): \"\"\"Publishes the given collection. It is the", "\"\"\"Returns a list of ActivityRights objects for given exploration ids.", "return False def _assign_role( committer, assignee_id, new_role, activity_id, activity_type): \"\"\"Assigns", "is the same as the ID of associated activity. Args:", "bool. Whether the collection is public. \"\"\" collection_rights = get_collection_rights(collection_id)", "activity. Returns: bool. Whether the user can delete given activity.", "if assignee_id in activity_rights.viewer_ids: activity_rights.viewer_ids.remove(assignee_id) old_role = ROLE_VIEWER if assignee_id", "# # Licensed under the Apache License, Version 2.0 (the", "True return False def check_can_unpublish_activity(user, activity_rights): \"\"\"Checks whether the user", "bool. Whether the exploration is public. \"\"\" exploration_rights = get_exploration_rights(exploration_id)", "an editor and a translator: %s' % editor_translator) if editor_viewer:", "Exception('Invalid role: %s' % new_role) commit_message = 'Changed role of", "'The ownership of this %s cannot be released.' % activity_type)", "Exception. This could potentially throw an exception from _release_ownership_of_activity. \"\"\"", "\"\"\" if activity_rights is None: return False if activity_rights.cloned_from: return", "Raises: Exception. The committer does not have rights to unpublish", "user_services.get_username(assignee_id) old_role = ROLE_NONE if new_role == ROLE_OWNER: if activity_rights.is_owner(assignee_id):", "collection_id) def release_ownership_of_collection(committer, collection_id): \"\"\"Releases ownership of the given collection", "activity_rights.owner_ids model.editor_ids = activity_rights.editor_ids model.viewer_ids = activity_rights.viewer_ids model.translator_ids = activity_rights.translator_ids", "activity_rights is None: return False if (activity_rights.community_owned or activity_rights.cloned_from): return", "of %s %s but was ' 'refused permission.' % (committer_id,", "the activity. commit_message: str. The human-written commit message for this", "user is editor of activity. Args: user_id: str or None.", "does not have release rights. \"\"\" committer_id = committer.user_id activity_rights", "link. Args: committer: UserActionsInfo. UserActionsInfo object for the committer. exploration_id:", "of the collection. assignee_id: str. ID of the user whose", "role is being changed. new_role: str. The name of the", "collection_rights = get_collection_rights(collection_id) return collection_rights.status == ACTIVITY_STATUS_PUBLIC def _get_activity_rights(activity_type, activity_id):", "first_published_msec=exploration_rights.first_published_msec, ).commit(committer_id, 'Created new exploration', commit_cmds) subscription_services.subscribe_to_exploration( committer_id, exploration_id) def", "is not found. Returns: ActivityRights. The rights object for the", "modify roles for given activity. Args: user: UserActionsInfo. Object having", "'old_status': old_status, 'new_status': new_status }] if new_status != ACTIVITY_STATUS_PRIVATE: activity_rights.viewer_ids", "models.NAMES.exploration ]) # IMPORTANT: Ensure that all changes to how", "of the exploration. strict: bool. Whether to raise an error", "The user can already view the activity. Exception. The activity", "self.viewable_if_private = viewable_if_private self.first_published_msec = first_published_msec def validate(self): \"\"\"Validates an", "Exception. The committer does not have release rights. \"\"\" committer_id", "activity_id)) raise Exception('This %s cannot be unpublished.' % activity_type) _change_activity_status(", "= 'viewer' ROLE_NONE = 'none' ROLE_ADMIN = 'admin' ROLE_MODERATOR =", "snapshots in the datastore. # Do not modify the definitions", "{ 'cloned_from': self.cloned_from, 'status': self.status, 'community_owned': True, 'owner_names': [], 'editor_names':", "committer: UserActionsInfo. UserActionsInfo object for the user who is performing", "\"\"\" if activity_rights is None: return False elif activity_rights.is_published(): return", "of %s from %s to %s' % ( assignee_username, old_role,", "in [ROLE_OWNER, ROLE_EDITOR, ROLE_TRANSLATOR]: subscription_services.subscribe_to_exploration( assignee_id, exploration_id) def release_ownership_of_exploration(committer, exploration_id):", "== constants.ACTIVITY_TYPE_COLLECTION: model_cls = collection_models.CollectionRightsModel model = model_cls.get(activity_rights.id, strict=False) model.owner_ids", "activity. Args: committer_id: str. ID of the user who is", "activity_rights, activity_type, 'set first published time in msec', commit_cmds) def", "activity owner. \"\"\" return bool(user_id in self.owner_ids) def is_editor(self, user_id):", "the committer. collection_id: str. ID of the collection. assignee_id: str.", "to the community. Args: committer: UserActionsInfo. UserActionsInfo object for the", "'Created new exploration', commit_cmds) subscription_services.subscribe_to_exploration( committer_id, exploration_id) def get_exploration_rights(exploration_id, strict=True):", "this change. \"\"\" activity_rights = _get_activity_rights(activity_type, activity_id) old_status = activity_rights.status", "# The user who can publish activity can change its", "or activity_rights.is_owner(user.user_id) or activity_rights.is_editor(user.user_id) or activity_rights.is_translator(user.user_id) or activity_rights.viewable_if_private) def check_can_edit_activity(user,", "ACTIVITY_STATUS_PRIVATE, '%s unpublished.' % activity_type) activity_services.remove_featured_activity(activity_type, activity_id) # Rights functions", "user. \"\"\" if activity_rights is None: return False elif activity_rights.is_published():", "if assignee_id in activity_rights.viewer_ids: activity_rights.viewer_ids.remove(assignee_id) old_role = ROLE_VIEWER elif new_role", "editor_translator = set(self.editor_ids).intersection( set(self.translator_ids)) editor_viewer = set(self.editor_ids).intersection(set(self.viewer_ids)) translator_viewer = set(self.editor_ids).intersection(", "given activity. Returns: bool. Whether the user can publish given", "and (role_services.ACTION_DELETE_ANY_PUBLIC_ACTIVITY in user.actions)): return True return False def check_can_modify_activity_roles(user,", "already publicly editable. Exception. The activity is already publicly translatable.", "committer.user_id activity_rights = _get_activity_rights(activity_type, activity_id) if not check_can_release_ownership(committer, activity_rights): logging.error(", "exploration_id: str. ID of the exploration. committer_id: str. ID of", "assignee_id, new_role): \"\"\"Assign the given user to the given role", "commit_cmds = [{'cmd': CMD_CREATE_NEW}] exp_models.ExplorationRightsModel( id=exploration_rights.id, owner_ids=exploration_rights.owner_ids, editor_ids=exploration_rights.editor_ids, translator_ids=exploration_rights.translator_ids, viewer_ids=exploration_rights.viewer_ids,", "on an \"AS-IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "translate the activity. Exception. The activity is already publicly editable.", "'Cannot get activity rights for unknown activity type: %s' %", "or implied. # See the License for the specific language", "not already set before updating it. Args: activity_type: str. The", "the collection. assignee_id: str. ID of the user whose role", "milliseconds since the Epoch. \"\"\" activity_rights = _get_activity_rights(activity_type, activity_id) commit_cmds", "accessed by the given user. \"\"\" if activity_rights is None:", "and a viewer: %s' % translator_viewer) def to_dict(self): \"\"\"Returns a", "_update_collection_summary(activity_rights): \"\"\"Updates the collection summary for the given activity associated", "_get_activity_rights(activity_type, activity_id) if not check_can_modify_activity_roles(committer, activity_rights): logging.error( 'User %s tried", "import role_services from core.domain import subscription_services from core.domain import user_services", "exploration_id): \"\"\"Publishes the given exploration. It is the responsibility of", "if (activity_rights.is_owner(user.user_id) or activity_rights.is_editor(user.user_id)): return True if (activity_rights.community_owned or (role_services.ACTION_EDIT_ANY_ACTIVITY", "datastore. Args: collection_id: str. ID of the collection. Returns: list(str).", "current value.' % viewable_if_private) exploration_rights.viewable_if_private = viewable_if_private commit_cmds = [{", "self.owner_ids = owner_ids self.editor_ids = editor_ids self.translator_ids = translator_ids self.viewer_ids", "is private. \"\"\" return bool(self.status == ACTIVITY_STATUS_PRIVATE) def get_activity_rights_from_model(activity_rights_model, activity_type):", "and # limitations under the License. \"\"\"Domain objects and functions", "to anyone with the link.' if viewable_if_private else 'Made exploration", "exp_ids: list(str). List of exploration ids. Returns: list(ActivityRights or None).", "an exception from _publish_activity. \"\"\" _publish_activity( committer, exploration_id, constants.ACTIVITY_TYPE_EXPLORATION) def", "committer. \"\"\" exploration_rights = ActivityRights( exploration_id, [committer_id], [], [], [])", "assignee_id in activity_rights.translator_ids: activity_rights.translator_ids.remove(assignee_id) old_role = ROLE_TRANSLATOR elif new_role ==", "return exp_models_list def is_exploration_private(exploration_id): \"\"\"Returns whether exploration is private. Args:", "activity_rights_model.id, activity_rights_model.owner_ids, activity_rights_model.editor_ids, activity_rights_model.translator_ids, activity_rights_model.viewer_ids, community_owned=activity_rights_model.community_owned, cloned_from=( activity_rights_model.cloned_from if activity_type", "ActivityRights. The rights object for the given activity. \"\"\" #", "activity_rights.is_editor(user.user_id)): return True if (activity_rights.community_owned or (role_services.ACTION_EDIT_ANY_ACTIVITY in user.actions)): return", "given activity. \"\"\" if activity_type == constants.ACTIVITY_TYPE_EXPLORATION: _update_exploration_summary(activity_rights) elif activity_type", "'change_exploration_status' CMD_CHANGE_COLLECTION_STATUS = 'change_collection_status' CMD_CHANGE_PRIVATE_VIEWABILITY = 'change_private_viewability' CMD_RELEASE_OWNERSHIP = 'release_ownership'", "time in milliseconds since the Epoch. \"\"\" activity_rights = _get_activity_rights(activity_type,", "committer, assignee_id, new_role, collection_id, constants.ACTIVITY_TYPE_COLLECTION) if new_role in [ROLE_OWNER, ROLE_EDITOR]:", "activity_rights.viewer_ids.remove(assignee_id) old_role = ROLE_VIEWER elif new_role == ROLE_TRANSLATOR: if (activity_rights.is_editor(assignee_id)", "\"\"\" if activity_rights is None: return False if activity_rights.community_owned: return", "activity_type, '%s ownership released to the community.' % activity_type, commit_cmds)", "if activity_type == constants.ACTIVITY_TYPE_EXPLORATION: return get_exploration_rights(activity_id, strict=False) elif activity_type ==", "= exploration_rights.viewable_if_private if old_viewable_if_private == viewable_if_private: raise Exception( 'Trying to", "in user.actions)): return True return False def check_can_delete_activity(user, activity_rights): \"\"\"Checks", "= activity_rights.first_published_msec model.commit(committer_id, commit_message, commit_cmds) def _update_exploration_summary(activity_rights): \"\"\"Updates the exploration", "committer: UserActionsInfo. UserActionsInfo object for the committer. collection_id: str. ID", "exploration is public. Args: exploration_id: str. ID of the exploration.", "def to_dict(self): \"\"\"Returns a dict suitable for use by the", "def is_private(self): \"\"\"Checks whether activity is private. Returns: bool. Whether", "object from the given activity rights model. Args: activity_rights_model: ActivityRightsModel.", "committer.user_id activity_rights = _get_activity_rights(activity_type, activity_id) if not check_can_publish_activity(committer, activity_rights): logging.error(", "constants.ACTIVITY_TYPE_EXPLORATION constants.ACTIVITY_TYPE_COLLECTION activity_rights: ActivityRights. The rights object for the given", "coding: utf-8 # # Copyright 2014 The Oppia Authors. All", "self.cloned_from = cloned_from self.status = status self.viewable_if_private = viewable_if_private self.first_published_msec", "is public. Args: collection_id: str. ID of the collection. Returns:", "\"\"\" collection_rights = get_collection_rights(collection_id) return collection_rights.status == ACTIVITY_STATUS_PRIVATE def is_collection_public(collection_id):", "cannot be released.' % activity_type) activity_rights.community_owned = True activity_rights.owner_ids =", "throw an exception from _release_ownership_of_activity. \"\"\" _release_ownership_of_activity( committer, exploration_id, constants.ACTIVITY_TYPE_EXPLORATION)", "utils.ValidationError: if any of the owners, editors, translators and viewers", "in self.owner_ids) def is_editor(self, user_id): \"\"\"Checks whether given user is", "(role_services.ACTION_MODIFY_ROLES_FOR_ANY_ACTIVITY in user.actions): return True if (role_services.ACTION_MODIFY_ROLES_FOR_OWNED_ACTIVITY in user.actions): if", "%s %s but was refused ' 'permission.' % (committer_id, activity_type,", "_change_activity_status( committer_id, activity_id, activity_type, ACTIVITY_STATUS_PRIVATE, '%s unpublished.' % activity_type) activity_services.remove_featured_activity(activity_type,", "constants.ACTIVITY_TYPE_COLLECTION activity_id: str. ID of the activity. first_published_msec: float. First", "None. Rights object for the given activity. Returns: bool. Whether", "ID of the collection. Returns: bool. Whether the collection is", "True return False def check_can_translate_activity(user, activity_rights): \"\"\"Checks whether the user", "the user can modify roles for given activity. Args: user:", "(committer_id, activity_type, activity_id)) raise Exception('This %s cannot be unpublished.' %", "== ACTIVITY_STATUS_PRIVATE: raise utils.ValidationError( 'Community-owned explorations cannot be private.') if", "check_can_delete_activity(user, activity_rights): \"\"\"Checks whether the user can delete given activity.", "old_role = ROLE_TRANSLATOR if assignee_id in activity_rights.viewer_ids: activity_rights.viewer_ids.remove(assignee_id) old_role =", "activity_rights_model.cloned_from if activity_type == constants.ACTIVITY_TYPE_EXPLORATION else None), status=activity_rights_model.status, viewable_if_private=activity_rights_model.viewable_if_private, first_published_msec=activity_rights_model.first_published_msec", "preserve # backward-compatibility with previous exploration snapshots in the datastore.", "activity_rights): \"\"\"Updates the activity summary for the given activity associated", "the ID of associated activity. Args: activity_rights: ActivityRights. The rights", "str. ID of the exploration. assignee_id: str. ID of the", "the given role and subscribes the assignee to future collection", "if model is None: return None return get_activity_rights_from_model( model, constants.ACTIVITY_TYPE_COLLECTION)", "owner_translator: raise utils.ValidationError( 'A user cannot be both an owner", "exploration ids. Returns: list(ActivityRights or None). List of rights object", "CMD_CHANGE_ROLE, 'assignee_id': assignee_id, 'old_role': old_role, 'new_role': new_role }] _save_activity_rights( committer_id,", "The human-written commit message for this change. \"\"\" activity_rights =", "object created from the model. \"\"\" return ActivityRights( activity_rights_model.id, activity_rights_model.owner_ids,", "if a community-owned exploration has owners, editors, translators or viewers", "'A user cannot be both an editor and a translator:", "None: return None return get_activity_rights_from_model( model, constants.ACTIVITY_TYPE_COLLECTION) def get_collection_owner_names(collection_id): \"\"\"Retrieves", "exploration_id, constants.ACTIVITY_TYPE_EXPLORATION) def set_private_viewability_of_exploration( committer, exploration_id, viewable_if_private): \"\"\"Sets the viewable_if_private", "new collection. Args: collection_id: str. ID of the collection. committer_id:", "get_activity_rights_from_model(activity_rights_model, activity_type): \"\"\"Constructs an ActivityRights object from the given activity", "user who is performing the update action. activity_id: str. ID", "str. ID of the exploration. Returns: bool. Whether the exploration", "% activity_type) if activity_rights.community_owned: raise Exception( 'Community-owned %ss can be", "%ss can be translated by anyone.' % activity_type) activity_rights.translator_ids.append(assignee_id) if", "the user can release ownership for given activity. Args: user:", "object to the datastore. Args: committer_id: str. ID of the", "cannot be unpublished.' % activity_type) _change_activity_status( committer_id, activity_id, activity_type, ACTIVITY_STATUS_PRIVATE,", "elif new_role == ROLE_VIEWER: if (activity_rights.is_owner(assignee_id) or activity_rights.is_editor(assignee_id) or activity_rights.is_viewer(assignee_id)):", "editor and a viewer: %s' % editor_viewer) if translator_viewer: raise", "The rights object for the given exploration. Raises: EntityNotFoundError. The", "def _get_activity_rights(activity_type, activity_id): \"\"\"Retrieves the rights object for the given", "be released.' % activity_type) activity_rights.community_owned = True activity_rights.owner_ids = []", "True return False def check_can_modify_activity_roles(user, activity_rights): \"\"\"Checks whether the user", "%s' % new_role) commit_message = 'Changed role of %s from", "Whether the collection is public. \"\"\" collection_rights = get_collection_rights(collection_id) return", "'Public explorations should have no viewers specified.') owner_editor = set(self.owner_ids).intersection(set(self.editor_ids))", "%s cannot be unpublished.' % activity_type) _change_activity_status( committer_id, activity_id, activity_type,", "the community.' % activity_type, commit_cmds) _update_activity_summary(activity_type, activity_rights) def _change_activity_status( committer_id,", "The type of activity. Possible values: constants.ACTIVITY_TYPE_EXPLORATION constants.ACTIVITY_TYPE_COLLECTION new_status: str.", "new_role in [ROLE_OWNER, ROLE_EDITOR]: subscription_services.subscribe_to_collection( assignee_id, collection_id) def release_ownership_of_collection(committer, collection_id):", "ensure that assignee_id corresponds to a valid user in the", "first_published_msec: float. First publication time in milliseconds since the Epoch.", "activity_rights is None: return False if role_services.ACTION_DELETE_ANY_ACTIVITY in user.actions: return", "if ID is not found. Returns: ActivityRights. The rights object", "to_dict(self): \"\"\"Returns a dict suitable for use by the frontend.", "tried to publish %s %s but was refused ' 'permission.'", "exploration_rights.status == ACTIVITY_STATUS_PRIVATE def is_exploration_public(exploration_id): \"\"\"Returns whether exploration is public.", "str. The type of activity. Possible values: constants.ACTIVITY_TYPE_EXPLORATION constants.ACTIVITY_TYPE_COLLECTION Raises:", "%s to %s' % ( assignee_username, old_role, new_role) commit_cmds =", "suitable for use by the frontend. Returns: dict. A dict", "'refused permission.' % (committer_id, activity_type, activity_id)) raise Exception( 'The ownership", "= activity_rights.status activity_rights.status = new_status if activity_type == constants.ACTIVITY_TYPE_EXPLORATION: cmd_type", "'Changed role of %s from %s to %s' % (", "ROLE_TRANSLATOR = 'translator' ROLE_VIEWER = 'viewer' ROLE_NONE = 'none' ROLE_ADMIN", "anyone with the link.' if viewable_if_private else 'Made exploration viewable", "List of rights object containing ActivityRights object for existing exploration", "= get_exploration_rights(exploration_id) # The user who can publish activity can", "kind of commit was done. \"\"\" activity_rights.validate() if activity_type ==", "activity_rights: ActivityRights or None. Rights object for the given activity.", "= user_services.get_username(assignee_id) old_role = ROLE_NONE if new_role == ROLE_OWNER: if", "community. Args: committer: UserActionsInfo. UserActionsInfo object for the committer. collection_id:", "Raise: Exception. The committer does not have release rights. \"\"\"", "bool. Whether user is an activity viewer. \"\"\" return bool(user_id", "ACTIVITY_STATUS_PRIVATE) def get_activity_rights_from_model(activity_rights_model, activity_type): \"\"\"Constructs an ActivityRights object from the", "commit_cmds) subscription_services.subscribe_to_collection(committer_id, collection_id) def get_collection_rights(collection_id, strict=True): \"\"\"Retrieves the rights for", "of the collection. committer_id: str. ID of the committer. \"\"\"", "collection_services.update_collection_summary( activity_rights.id, None) def _update_activity_summary(activity_type, activity_rights): \"\"\"Updates the activity summary", "get activity rights for unknown activity type: %s' % (", "given user can edit this activity. \"\"\" if activity_rights is", "activity. Returns: ActivityRights. The rights object associated with the given", "assignee_id in activity_rights.viewer_ids: activity_rights.viewer_ids.remove(assignee_id) old_role = ROLE_VIEWER elif new_role ==", "def check_can_edit_activity(user, activity_rights): \"\"\"Checks whether the user can edit given", "rights to modify a role. Exception. The user already owns", "def check_can_release_ownership(user, activity_rights): \"\"\"Checks whether the user can release ownership", "activity_rights): \"\"\"Checks whether the user can unpublish given activity. Args:", "the user who is performing the update action. activity_id: str.", "Whether the collection is private. \"\"\" collection_rights = get_collection_rights(collection_id) return", "version of ActivityRights suitable for use by the frontend. \"\"\"", "constants.ACTIVITY_TYPE_EXPLORATION constants.ACTIVITY_TYPE_COLLECTION Returns: ActivityRights. The rights object created from the", "rights object created from the model. \"\"\" return ActivityRights( activity_rights_model.id,", "user is an activity owner. \"\"\" return bool(user_id in self.owner_ids)", "the assignee to future collection updates. The caller should ensure", "def _unpublish_activity(committer, activity_id, activity_type): \"\"\"Unpublishes the given activity. Args: committer:", "is valid prior to publication. Args: committer: UserActionsInfo. UserActionsInfo object", "CMD keys that already exist. CMD_CREATE_NEW = 'create_new' CMD_CHANGE_ROLE =", "raise Exception( 'Community-owned %ss can be translated by anyone.' %", "the exploration summary for the activity associated with the given", "A dict version of ActivityRights suitable for use by the", "user can edit given activity. Args: user: UserActionsInfo. Object having", "found. Returns: ActivityRights. The rights object for the collection. Raises:", "% activity_type) activity_rights.owner_ids.append(assignee_id) if assignee_id in activity_rights.viewer_ids: activity_rights.viewer_ids.remove(assignee_id) old_role =", "activity_rights.is_viewer(user.user_id) or activity_rights.is_owner(user.user_id) or activity_rights.is_editor(user.user_id) or activity_rights.is_translator(user.user_id) or activity_rights.viewable_if_private) def", "The role is invalid. \"\"\" committer_id = committer.user_id activity_rights =", "if editor_viewer: raise utils.ValidationError( 'A user cannot be both an", "in writing, software # distributed under the License is distributed", "'old_viewable_if_private': old_viewable_if_private, 'new_viewable_if_private': viewable_if_private, }] commit_message = ( 'Made exploration", "ActivityRights. The rights object for the given activity. \"\"\" if", "Returns: list(ActivityRights or None). List of rights object containing ActivityRights", "% viewable_if_private) exploration_rights.viewable_if_private = viewable_if_private commit_cmds = [{ 'cmd': CMD_CHANGE_PRIVATE_VIEWABILITY,", "or a collection). \"\"\" def __init__( self, exploration_id, owner_ids, editor_ids,", "raise Exception( 'This user already can translate this %s.' %", "translator_ids=exploration_rights.translator_ids, viewer_ids=exploration_rights.viewer_ids, community_owned=exploration_rights.community_owned, status=exploration_rights.status, viewable_if_private=exploration_rights.viewable_if_private, first_published_msec=exploration_rights.first_published_msec, ).commit(committer_id, 'Created new exploration',", "permission.' % (committer_id, exploration_id)) raise Exception( 'The viewability status of", "activity is private. Returns: bool. Whether activity is private. \"\"\"", "datastore. Subscribes the committer to the new collection. Args: collection_id:", "= [] activity_rights.editor_ids = [] activity_rights.viewer_ids = [] commit_cmds =", "unpublish given activity. \"\"\" if activity_rights is None: return False", "_get_activity_rights(activity_type, activity_id): \"\"\"Retrieves the rights object for the given activity", "= get_exploration_rights(exploration_id) return bool(exploration_rights.cloned_from) def create_new_collection_rights(collection_id, committer_id): \"\"\"Creates a new", "== viewable_if_private: raise Exception( 'Trying to change viewability status of", "is None: return None return get_activity_rights_from_model( model, constants.ACTIVITY_TYPE_COLLECTION) def get_collection_owner_names(collection_id):", "'%s unpublished.' % activity_type) activity_services.remove_featured_activity(activity_type, activity_id) # Rights functions for", "the link). Raises: Exception. The committer does not have the", "collection is public. Args: collection_id: str. ID of the collection.", "commit_cmds = [{ 'cmd': CMD_CHANGE_ROLE, 'assignee_id': assignee_id, 'old_role': old_role, 'new_role':", "% (committer_id, exploration_id)) raise Exception( 'The viewability status of this", "status=activity_rights_model.status, viewable_if_private=activity_rights_model.viewable_if_private, first_published_msec=activity_rights_model.first_published_msec ) def _save_activity_rights( committer_id, activity_rights, activity_type, commit_message,", "== ROLE_VIEWER: if (activity_rights.is_owner(assignee_id) or activity_rights.is_editor(assignee_id) or activity_rights.is_viewer(assignee_id)): raise Exception(", "return True if role_services.ACTION_PUBLISH_OWNED_ACTIVITY in user.actions: if activity_rights.is_owner(user.user_id): return True", "constants.ACTIVITY_TYPE_EXPLORATION constants.ACTIVITY_TYPE_COLLECTION activity_id: str. ID of the activity. first_published_msec: float.", "translator and a viewer: %s' % translator_viewer) def to_dict(self): \"\"\"Returns", "activity editor. \"\"\" return bool(user_id in self.editor_ids) def is_translator(self, user_id):", "\"\"\"Returns whether the collection is public. Args: collection_id: str. ID", "list(str). Human-readable usernames (or truncated email addresses) of owners for", "License, Version 2.0 (the \"License\"); # you may not use", "given activity to the community. Args: committer: UserActionsInfo. UserActionsInfo object", "in activity_rights.viewer_ids: activity_rights.viewer_ids.remove(assignee_id) old_role = ROLE_VIEWER if assignee_id in activity_rights.editor_ids:", "CMD_CREATE_NEW = 'create_new' CMD_CHANGE_ROLE = 'change_role' CMD_CHANGE_EXPLORATION_STATUS = 'change_exploration_status' CMD_CHANGE_COLLECTION_STATUS", "to check that the collection is valid prior to publication.", "str. ID of the user who is performing the update", "editor: %s' % owner_editor) if owner_translator: raise utils.ValidationError( 'A user", "the collection is valid prior to publication. Args: committer: UserActionsInfo.", "caller should ensure that assignee_id corresponds to a valid user", "raise utils.ValidationError( 'A user cannot be both an owner and", "commit. commit_cmds: list(dict). A list of commands describing what kind", "can unpublish given activity. Args: user: UserActionsInfo. Object having user_id,", "activity_rights.community_owned: raise Exception( 'Community-owned %ss can be edited by anyone.'", "def _change_activity_status( committer_id, activity_id, activity_type, new_status, commit_message): \"\"\"Changes the status", "exception from _unpublish_activity. \"\"\" _unpublish_activity( committer, exploration_id, constants.ACTIVITY_TYPE_EXPLORATION) # Rights", "_get_activity_rights(activity_type, activity_id) commit_cmds = [{ 'cmd': CMD_UPDATE_FIRST_PUBLISHED_MSEC, 'old_first_published_msec': activity_rights.first_published_msec, 'new_first_published_msec':", "activity_rights) def _publish_activity(committer, activity_id, activity_type): \"\"\"Publishes the given activity. Args:", "set(self.viewer_ids)) if owner_editor: raise utils.ValidationError( 'A user cannot be both", "[], 'editor_names': [], 'translator_names': [], 'viewer_names': [], 'viewable_if_private': self.viewable_if_private, }", "exploration_id, strict=strict) if model is None: return None return get_activity_rights_from_model(", "ACTIVITY_STATUS_PUBLIC) def is_private(self): \"\"\"Checks whether activity is private. Returns: bool.", "is no exploration matching the given ID. Returns: ActivityRights. The", "exploration is a clone of another exploration. Args: exploration_id: str.", "None: return False if role_services.ACTION_DELETE_ANY_ACTIVITY in user.actions: return True elif", "activity. \"\"\" if activity_rights is None: return False if activity_rights.community_owned:", "'old_role': old_role, 'new_role': new_role }] _save_activity_rights( committer_id, activity_rights, activity_type, commit_message,", "the License for the specific language governing permissions and #", "exploration_id was not found in the datastore. \"\"\" model =", "Returns: ActivityRights. The rights object associated with the given activity.", "user.actions: return True if role_services.ACTION_PUBLISH_OWNED_ACTIVITY in user.actions: if activity_rights.is_owner(user.user_id): return", "constants.ACTIVITY_TYPE_EXPLORATION) # Rights functions for collections. def assign_role_for_collection( committer, collection_id,", "= 'change_exploration_status' CMD_CHANGE_COLLECTION_STATUS = 'change_collection_status' CMD_CHANGE_PRIVATE_VIEWABILITY = 'change_private_viewability' CMD_RELEASE_OWNERSHIP =", "a viewer: %s' % translator_viewer) def to_dict(self): \"\"\"Returns a dict", "set(self.owner_ids).intersection(set(self.viewer_ids)) editor_translator = set(self.editor_ids).intersection( set(self.translator_ids)) editor_viewer = set(self.editor_ids).intersection(set(self.viewer_ids)) translator_viewer =", "ownership of %s %s but was ' 'refused permission.' %", "exploration is private or not. \"\"\" exploration_rights = get_exploration_rights(exploration_id) return", "activity_rights) def _change_activity_status( committer_id, activity_id, activity_type, new_status, commit_message): \"\"\"Changes the", "= 'owner' ROLE_EDITOR = 'editor' ROLE_TRANSLATOR = 'translator' ROLE_VIEWER =", "def is_exploration_public(exploration_id): \"\"\"Returns whether exploration is public. Args: exploration_id: str.", "commit_message): \"\"\"Changes the status of the given activity. Args: committer_id:", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "_update_collection_summary(activity_rights) def update_activity_first_published_msec( activity_type, activity_id, first_published_msec): \"\"\"Updates the first_published_msec field", "(role_services.ACTION_PLAY_ANY_PRIVATE_ACTIVITY in user.actions) or activity_rights.is_viewer(user.user_id) or activity_rights.is_owner(user.user_id) or activity_rights.is_editor(user.user_id) or", "raise Exception( 'Cannot get activity rights for unknown activity type:", "modify roles for given activity. \"\"\" if activity_rights is None:", "ROLE_TRANSLATOR if assignee_id in activity_rights.viewer_ids: activity_rights.viewer_ids.remove(assignee_id) old_role = ROLE_VIEWER elif", "future exploration updates. The caller should ensure that assignee_id corresponds", "private. \"\"\" collection_rights = get_collection_rights(collection_id) return collection_rights.status == ACTIVITY_STATUS_PRIVATE def", "user can access given activity. Args: user: UserActionsInfo. Object having", "of the exploration. committer_id: str. ID of the committer. \"\"\"", "or activity_rights.viewable_if_private) def check_can_edit_activity(user, activity_rights): \"\"\"Checks whether the user can", "functions for activities. def assign_role_for_exploration( committer, exploration_id, assignee_id, new_role): \"\"\"Assigns", "activity. Args: user: UserActionsInfo. Object having user_id, role and actions", "\"\"\"Creates a new exploration rights object and saves it to", "activity_rights.is_owner(assignee_id)): raise Exception( 'This user already can translate this %s.'", "if role_services.ACTION_UNPUBLISH_ANY_PUBLIC_ACTIVITY in user.actions: return True return False def _assign_role(", "else: return { 'cloned_from': self.cloned_from, 'status': self.status, 'community_owned': False, 'owner_names':", "committer does not have rights to modify a role. Exception.", "does not have rights to unpublish the activity. \"\"\" committer_id", "\"\"\"Checks whether given user is translator of activity. Args: user_id:", "collection_models.CollectionRightsModel model = model_cls.get(activity_rights.id, strict=False) model.owner_ids = activity_rights.owner_ids model.editor_ids =", "CMD_CHANGE_COLLECTION_STATUS commit_cmds = [{ 'cmd': cmd_type, 'old_status': old_status, 'new_status': new_status", "_release_ownership_of_activity( committer, collection_id, constants.ACTIVITY_TYPE_COLLECTION) def publish_collection(committer, collection_id): \"\"\"Publishes the given", "ActivityRights. The rights object for the given activity. activity_type: str.", "exploration_rights): logging.error( 'User %s tried to change private viewability of", "[{ 'cmd': CMD_CHANGE_PRIVATE_VIEWABILITY, 'old_viewable_if_private': old_viewable_if_private, 'new_viewable_if_private': viewable_if_private, }] commit_message =", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "'owner_names': user_services.get_human_readable_user_ids( self.owner_ids), 'editor_names': user_services.get_human_readable_user_ids( self.editor_ids), 'translator_names': user_services.get_human_readable_user_ids( self.translator_ids), 'viewer_names':", "set(self.translator_ids)) owner_viewer = set(self.owner_ids).intersection(set(self.viewer_ids)) editor_translator = set(self.editor_ids).intersection( set(self.translator_ids)) editor_viewer =", "raise an error if there is no exploration matching the", "the activity. Exception. The user can already edit the activity.", "First publication time in milliseconds since the Epoch. \"\"\" activity_rights", "def _save_activity_rights( committer_id, activity_rights, activity_type, commit_message, commit_cmds): \"\"\"Saves an ExplorationRights", "collection is private. Args: collection_id: str. ID of the collection.", "of the caller to check that the exploration is valid", "if (activity_rights.is_editor(assignee_id) or activity_rights.is_translator(assignee_id) or activity_rights.is_owner(assignee_id)): raise Exception( 'This user", "\"\"\"Releases ownership of the given exploration to the community. Args:", "community.' % activity_type, commit_cmds) _update_activity_summary(activity_type, activity_rights) def _change_activity_status( committer_id, activity_id,", "assignee_id, 'old_role': old_role, 'new_role': new_role }] _save_activity_rights( committer_id, activity_rights, activity_type,", "private. \"\"\" return bool(self.status == ACTIVITY_STATUS_PRIVATE) def get_activity_rights_from_model(activity_rights_model, activity_type): \"\"\"Constructs", "activity_rights is None: return False if activity_rights.is_private(): return False return", "viewable_if_private: bool. Whether the exploration should be made viewable (by", "potentially throw an exception from _assign_role. \"\"\" _assign_role( committer, assignee_id,", "_unpublish_activity(committer, activity_id, activity_type): \"\"\"Unpublishes the given activity. Args: committer: UserActionsInfo.", "containing ActivityRights object for existing exploration or None. \"\"\" exp_rights_models", "editors, translators or viewers specified. \"\"\" if self.community_owned: if (self.owner_ids", "collection_id, assignee_id, new_role): \"\"\"Assign the given user to the given", "ACTIVITY_STATUS_PRIVATE = constants.ACTIVITY_STATUS_PRIVATE ACTIVITY_STATUS_PUBLIC = constants.ACTIVITY_STATUS_PUBLIC ROLE_OWNER = 'owner' ROLE_EDITOR", "= models.Registry.import_models([ models.NAMES.collection, models.NAMES.exploration ]) # IMPORTANT: Ensure that all", "'User %s tried to unpublish %s %s but was refused", "def release_ownership_of_exploration(committer, exploration_id): \"\"\"Releases ownership of the given exploration to", "def get_multiple_exploration_rights_by_ids(exp_ids): \"\"\"Returns a list of ActivityRights objects for given", "\"\"\"Releases ownership of the given collection to the community. Args:", "\"\"\" exploration_rights = get_exploration_rights(exploration_id) return bool(exploration_rights.cloned_from) def create_new_collection_rights(collection_id, committer_id): \"\"\"Creates", "for given activity. \"\"\" if activity_rights is None: return False", "whether the user can translate given activity. Args: user: UserActionsInfo.", "activity_rights.is_owner(assignee_id)): raise Exception( 'This user already can edit this %s.'", "user is an activity translator. \"\"\" return bool(user_id in self.translator_ids)", "self.translator_ids or self.viewer_ids): raise utils.ValidationError( 'Community-owned explorations should have no", "% translator_viewer) def to_dict(self): \"\"\"Returns a dict suitable for use", "= constants.ACTIVITY_STATUS_PRIVATE ACTIVITY_STATUS_PUBLIC = constants.ACTIVITY_STATUS_PUBLIC ROLE_OWNER = 'owner' ROLE_EDITOR =", "\"\"\" exp_rights_models = exp_models.ExplorationRightsModel.get_multi( exp_ids) exp_models_list = [] for model", "object for the user who is performing the action. activity_id:", "# Unless required by applicable law or agreed to in", "feconf.SYSTEM_COMMITTER_ID, activity_rights, activity_type, 'set first published time in msec', commit_cmds)", "= [{ 'cmd': CMD_CHANGE_ROLE, 'assignee_id': assignee_id, 'old_role': old_role, 'new_role': new_role", "Exception('This %s cannot be published.' % activity_type) _change_activity_status( committer_id, activity_id,", "_update_exploration_summary(activity_rights) elif activity_type == constants.ACTIVITY_TYPE_COLLECTION: _update_collection_summary(activity_rights) def update_activity_first_published_msec( activity_type, activity_id,", "object for the given exploration. Raises: EntityNotFoundError. The exploration with", "to be a(n) %s of activity %s ' 'but was", "model is None: return None return get_activity_rights_from_model( model, constants.ACTIVITY_TYPE_COLLECTION) def", "to future collection updates. The caller should ensure that assignee_id", "is already publicly translatable. Exception. The user can already view", "to future exploration updates. The caller should ensure that assignee_id", "the community. Args: committer: UserActionsInfo. UserActionsInfo object for the user", "given activity rights model. Args: activity_rights_model: ActivityRightsModel. Activity rights from", "was refused permission.' % ( committer_id, assignee_id, new_role, activity_id)) raise", "core.domain import activity_services from core.domain import role_services from core.domain import", "!= ACTIVITY_STATUS_PRIVATE and self.viewer_ids: raise utils.ValidationError( 'Public explorations should have", "'User %s tried to allow user %s to be a(n)", "the user can access given activity. Args: user: UserActionsInfo. Object", "the update action. activity_id: str. ID of the activity. activity_type:", "is True, this allows a private exploration to be viewed", "the permission to perform change action. Exception. If the viewable_if_private", "the Apache License, Version 2.0 (the \"License\"); # you may", "exp_models_list.append(None) else: exp_models_list.append( get_activity_rights_from_model( model, constants.ACTIVITY_TYPE_EXPLORATION)) return exp_models_list def is_exploration_private(exploration_id):", "made viewable (by anyone with the link). Raises: Exception. The", "ID of the committer. \"\"\" exploration_rights = ActivityRights( exploration_id, [committer_id],", "raise Exception( 'This user already can view this %s.' %", "bool. Whether the user can unpublish given activity. \"\"\" if", "activity. \"\"\" if activity_rights is None: return False if activity_rights.is_private():", "activity_type) activity_rights.owner_ids.append(assignee_id) if assignee_id in activity_rights.viewer_ids: activity_rights.viewer_ids.remove(assignee_id) old_role = ROLE_VIEWER", "Raises: Exception. This could potentially throw an exception from _release_ownership_of_activity.", "for collections. def assign_role_for_collection( committer, collection_id, assignee_id, new_role): \"\"\"Assign the", "current_user_services = models.Registry.import_current_user_services() (collection_models, exp_models,) = models.Registry.import_models([ models.NAMES.collection, models.NAMES.exploration ])", "for the given activity. activity_type: str. The type of activity.", "should have no viewers specified.') owner_editor = set(self.owner_ids).intersection(set(self.editor_ids)) owner_translator =", "strict=False) model.owner_ids = activity_rights.owner_ids model.editor_ids = activity_rights.editor_ids model.viewer_ids = activity_rights.viewer_ids", "activity type: %s' % ( activity_type)) def check_can_access_activity(user, activity_rights): \"\"\"Checks", "activity is published. Returns: bool. Whether activity is published. \"\"\"", "_save_activity_rights( committer_id, activity_rights, activity_type, commit_message, commit_cmds) _update_activity_summary(activity_type, activity_rights) def _release_ownership_of_activity(committer,", "the License is distributed on an \"AS-IS\" BASIS, # WITHOUT", "%s' % editor_viewer) if translator_viewer: raise utils.ValidationError( 'A user cannot", "\"\"\" exploration_rights = get_exploration_rights(exploration_id) return exploration_rights.status == ACTIVITY_STATUS_PRIVATE def is_exploration_public(exploration_id):", "Possible values: constants.ACTIVITY_TYPE_EXPLORATION constants.ACTIVITY_TYPE_COLLECTION new_status: str. The new status of", "the commit. commit_cmds: list(dict). A list of commands describing what", "user.actions) or activity_rights.is_viewer(user.user_id) or activity_rights.is_owner(user.user_id) or activity_rights.is_editor(user.user_id) or activity_rights.is_translator(user.user_id) or", "set(self.owner_ids).intersection( set(self.translator_ids)) owner_viewer = set(self.owner_ids).intersection(set(self.viewer_ids)) editor_translator = set(self.editor_ids).intersection( set(self.translator_ids)) editor_viewer", "is performing the action. activity_id: str. ID of the activity.", "activity_rights.is_published(): if role_services.ACTION_UNPUBLISH_ANY_PUBLIC_ACTIVITY in user.actions: return True return False def", "a collection). \"\"\" def __init__( self, exploration_id, owner_ids, editor_ids, translator_ids,", "bool. Whether the collection is private. \"\"\" collection_rights = get_collection_rights(collection_id)", "new role.') assignee_username = user_services.get_username(assignee_id) old_role = ROLE_NONE if new_role", "model. Args: activity_rights_model: ActivityRightsModel. Activity rights from the datastore. activity_type:", "given activity. Args: committer_id: str. ID of the user who", "== constants.ACTIVITY_TYPE_EXPLORATION: return get_exploration_rights(activity_id, strict=False) elif activity_type == constants.ACTIVITY_TYPE_COLLECTION: return", "= [{ 'cmd': CMD_UPDATE_FIRST_PUBLISHED_MSEC, 'old_first_published_msec': activity_rights.first_published_msec, 'new_first_published_msec': first_published_msec }] activity_rights.first_published_msec", "False if (activity_rights.is_owner(user.user_id) or activity_rights.is_editor(user.user_id) or activity_rights.is_translator(user.user_id)): return True if", "activity_services from core.domain import role_services from core.domain import subscription_services from", "Whether the user can modify roles for given activity. \"\"\"", "UserActionsInfo. UserActionsInfo object for the user who is performing the", "ACTIVITY_STATUS_PRIVATE def is_exploration_public(exploration_id): \"\"\"Returns whether exploration is public. Args: exploration_id:", "invited playtesters.') _save_activity_rights( committer_id, exploration_rights, constants.ACTIVITY_TYPE_EXPLORATION, commit_message, commit_cmds) _update_exploration_summary(exploration_rights) def", "= exp_models.ExplorationRightsModel.get_multi( exp_ids) exp_models_list = [] for model in exp_rights_models:", "or self.viewer_ids): raise utils.ValidationError( 'Community-owned explorations should have no owners,", "return False def check_can_release_ownership(user, activity_rights): \"\"\"Checks whether the user can", "Returns: bool. Whether user is an activity editor. \"\"\" return", "with the given activity. Raises: Exception. activity_type provided is unknown.", "_update_activity_summary(activity_type, activity_rights) def _release_ownership_of_activity(committer, activity_id, activity_type): \"\"\"Releases ownership of the", "set(self.editor_ids).intersection(set(self.viewer_ids)) translator_viewer = set(self.editor_ids).intersection( set(self.viewer_ids)) if owner_editor: raise utils.ValidationError( 'A", "def _update_activity_summary(activity_type, activity_rights): \"\"\"Updates the activity summary for the given", "can be translated by anyone.' % activity_type) activity_rights.translator_ids.append(assignee_id) if assignee_id", "Raises: Exception. The committer does not have the permission to", "translator. \"\"\" return bool(user_id in self.translator_ids) def is_viewer(self, user_id): \"\"\"Checks", "ID of the collection. strict: bool. Whether to raise an", "for the given exploration's rights object. If viewable_if_private is True,", "== constants.ACTIVITY_TYPE_EXPLORATION: cmd_type = CMD_CHANGE_EXPLORATION_STATUS elif activity_type == constants.ACTIVITY_TYPE_COLLECTION: cmd_type", "activity_rights): logging.error( 'User %s tried to publish %s %s but", "Args: user_id: str or None. Id of the user. Returns:", "The activity is already publicly editable. Exception. The activity is", "\"\"\"Checks whether given user is owner of activity. Args: user_id:", "valid user in the system. Args: committer: UserActionsInfo. UserActionsInfo object", "for the given activity. \"\"\" if activity_type == constants.ACTIVITY_TYPE_EXPLORATION: _update_exploration_summary(activity_rights)", "= _get_activity_rights(activity_type, activity_id) if not check_can_publish_activity(committer, activity_rights): logging.error( 'User %s", "activity_id) commit_cmds = [{ 'cmd': CMD_UPDATE_FIRST_PUBLISHED_MSEC, 'old_first_published_msec': activity_rights.first_published_msec, 'new_first_published_msec': first_published_msec", "collection is valid prior to publication. Args: committer: UserActionsInfo. UserActionsInfo", "_assign_role( committer, assignee_id, new_role, exploration_id, constants.ACTIVITY_TYPE_EXPLORATION) if new_role in [ROLE_OWNER,", "\"\"\" if activity_rights is None: return False if (activity_rights.community_owned or", "ID of the collection. assignee_id: str. ID of the user", "if activity_rights is None: return False if activity_rights.cloned_from: return False", "exploration_rights.status == ACTIVITY_STATUS_PUBLIC def is_exploration_cloned(exploration_id): \"\"\"Returns whether the exploration is", "Returns: bool. Whether the given user can translate this activity.", "_publish_activity. \"\"\" _publish_activity( committer, exploration_id, constants.ACTIVITY_TYPE_EXPLORATION) def unpublish_exploration(committer, exploration_id): \"\"\"Unpublishes", "%s %s but was ' 'refused permission.' % (committer_id, activity_type,", "the user who is performing the action. activity_id: str. ID", "if there is no exploration matching the given ID. Returns:", "publish the activity. \"\"\" committer_id = committer.user_id activity_rights = _get_activity_rights(activity_type,", "email addresses) of owners for this collection. \"\"\" collection_rights =", "exploration updates. The caller should ensure that assignee_id corresponds to", "desired. \"\"\" committer_id = committer.user_id exploration_rights = get_exploration_rights(exploration_id) # The", "committer_id, exploration_rights, constants.ACTIVITY_TYPE_EXPLORATION, commit_message, commit_cmds) _update_exploration_summary(exploration_rights) def publish_exploration(committer, exploration_id): \"\"\"Publishes", "One of ROLE_OWNER ROLE_EDITOR ROLE_TRANSLATOR ROLE_VIEWER activity_id: str. ID of", "new exploration rights object and saves it to the datastore.", "Exception. The user already owns the activity. Exception. The user", "for the given activity. \"\"\" # TODO(msl): get rid of", "be both an owner and an editor: %s' % owner_editor)", "model_cls.get(activity_rights.id, strict=False) model.owner_ids = activity_rights.owner_ids model.editor_ids = activity_rights.editor_ids model.viewer_ids =", "activity_rights.is_published(): return bool( role_services.ACTION_PLAY_ANY_PUBLIC_ACTIVITY in user.actions) elif activity_rights.is_private(): return bool(", "object. Raises: utils.ValidationError: if any of the owners, editors, translators", "status of the given activity. Args: committer_id: str. ID of", "user cannot be both an owner and a translator: %s'", "editor_viewer) if translator_viewer: raise utils.ValidationError( 'A user cannot be both", "user. Returns: bool. Whether user is an activity translator. \"\"\"", "values: constants.ACTIVITY_TYPE_EXPLORATION constants.ACTIVITY_TYPE_COLLECTION activity_id: str. ID of the activity. Returns:", "collection_rights.status == ACTIVITY_STATUS_PUBLIC def _get_activity_rights(activity_type, activity_id): \"\"\"Retrieves the rights object", "'A user cannot be both an owner and a viewer:", "based on its type. Args: activity_type: str. The type of", "was not found in the datastore. \"\"\" model = exp_models.ExplorationRightsModel.get(", "old_role, 'new_role': new_role }] _save_activity_rights( committer_id, activity_rights, activity_type, commit_message, commit_cmds)", "commit_cmds = [{ 'cmd': CMD_UPDATE_FIRST_PUBLISHED_MSEC, 'old_first_published_msec': activity_rights.first_published_msec, 'new_first_published_msec': first_published_msec }]", "The caller is responsible for ensuring that this value is", "model. \"\"\" return ActivityRights( activity_rights_model.id, activity_rights_model.owner_ids, activity_rights_model.editor_ids, activity_rights_model.translator_ids, activity_rights_model.viewer_ids, community_owned=activity_rights_model.community_owned,", "to perform change action. Exception. If the viewable_if_private property is", "owner_translator = set(self.owner_ids).intersection( set(self.translator_ids)) owner_viewer = set(self.owner_ids).intersection(set(self.viewer_ids)) editor_translator = set(self.editor_ids).intersection(", "values: constants.ACTIVITY_TYPE_EXPLORATION constants.ACTIVITY_TYPE_COLLECTION commit_message: str. Descriptive message for the commit.", "raise Exception('This %s cannot be published.' % activity_type) _change_activity_status( committer_id,", "Exception( 'This user already can view this %s.' % activity_type)", "'cloned_from': self.cloned_from, 'status': self.status, 'community_owned': False, 'owner_names': user_services.get_human_readable_user_ids( self.owner_ids), 'editor_names':", "[] activity_rights.viewer_ids = [] commit_cmds = [{ 'cmd': CMD_RELEASE_OWNERSHIP, }]", "as the ID of associated activity. Args: activity_type: str. The", "= ( utils.get_current_time_in_millisecs()) _save_activity_rights( committer_id, activity_rights, activity_type, commit_message, commit_cmds) _update_activity_summary(activity_type,", "Args: committer: UserActionsInfo. UserActionsInfo object for the committer. activity_id: str.", "on its type. Args: activity_type: str. The type of activity.", "Args: committer: UserActionsInfo. UserActionInfo object for the user who is", "community_owned=collection_rights.community_owned, status=collection_rights.status, viewable_if_private=collection_rights.viewable_if_private, first_published_msec=collection_rights.first_published_msec ).commit(committer_id, 'Created new collection', commit_cmds) subscription_services.subscribe_to_collection(committer_id,", "= _get_activity_rights(activity_type, activity_id) if not check_can_modify_activity_roles(committer, activity_rights): logging.error( 'User %s", "user already can translate this %s.' % activity_type) if activity_rights.community_owned:", "\"\"\"Returns whether exploration is private. Args: exploration_id: str. ID of", "activity_rights.is_editor(assignee_id) or activity_rights.is_viewer(assignee_id)): raise Exception( 'This user already can view", "'%s published.' % activity_type) def _unpublish_activity(committer, activity_id, activity_type): \"\"\"Unpublishes the", "distributed under the License is distributed on an \"AS-IS\" BASIS,", "can edit given activity. Args: user: UserActionsInfo. Object having user_id,", "UserActionsInfo object for the committer. exploration_id: str. ID of the", "assignee_username = user_services.get_username(assignee_id) old_role = ROLE_NONE if new_role == ROLE_OWNER:", "already publicly translatable. Exception. The user can already view the", "saves it to the datastore. Subscribes the committer to the", "str. The type of activity. Possible values: constants.ACTIVITY_TYPE_EXPLORATION constants.ACTIVITY_TYPE_COLLECTION activity_rights:", "is an activity editor. \"\"\" return bool(user_id in self.editor_ids) def", "the given activity. The caller is responsible for ensuring that", "[], [], []) commit_cmds = [{'cmd': CMD_CREATE_NEW}] exp_models.ExplorationRightsModel( id=exploration_rights.id, owner_ids=exploration_rights.owner_ids,", "is performing the update action. activity_id: str. ID of the", "given activity. Args: committer: UserActionsInfo. UserActionsInfo object for the committer.", "an ActivityRights object. Raises: utils.ValidationError: if any of the owners,", "= [{'cmd': CMD_CREATE_NEW}] exp_models.ExplorationRightsModel( id=exploration_rights.id, owner_ids=exploration_rights.owner_ids, editor_ids=exploration_rights.editor_ids, translator_ids=exploration_rights.translator_ids, viewer_ids=exploration_rights.viewer_ids, community_owned=exploration_rights.community_owned,", "assignee_id in activity_rights.viewer_ids: activity_rights.viewer_ids.remove(assignee_id) old_role = ROLE_VIEWER if assignee_id in", "or None. Rights object for the given activity. Returns: bool.", "an editor: %s' % owner_editor) if owner_translator: raise utils.ValidationError( 'A", "ID exploration_id was not found in the datastore. \"\"\" model", "for model in exp_rights_models: if model is None: exp_models_list.append(None) else:", "True if role_services.ACTION_PUBLISH_OWNED_ACTIVITY in user.actions: if activity_rights.is_owner(user.user_id): return True return", "str. The new status of the activity. commit_message: str. The", "'cmd': CMD_CHANGE_ROLE, 'assignee_id': assignee_id, 'old_role': old_role, 'new_role': new_role }] _save_activity_rights(", "import collection_services collection_services.update_collection_summary( activity_rights.id, None) def _update_activity_summary(activity_type, activity_rights): \"\"\"Updates the", "datastore. # Do not modify the definitions of CMD keys", "the owners, editors, translators and viewers lists overlap, or if", "first_published_msec=activity_rights_model.first_published_msec ) def _save_activity_rights( committer_id, activity_rights, activity_type, commit_message, commit_cmds): \"\"\"Saves", "activity_rights.viewer_ids model.translator_ids = activity_rights.translator_ids model.community_owned = activity_rights.community_owned model.status = activity_rights.status", "Whether to raise an error if there is no exploration", "in self.editor_ids) def is_translator(self, user_id): \"\"\"Checks whether given user is", "is already as desired. \"\"\" committer_id = committer.user_id exploration_rights =", "[]) commit_cmds = [{'cmd': CMD_CREATE_NEW}] exp_models.ExplorationRightsModel( id=exploration_rights.id, owner_ids=exploration_rights.owner_ids, editor_ids=exploration_rights.editor_ids, translator_ids=exploration_rights.translator_ids,", "\"\"\" collection_rights = ActivityRights( collection_id, [committer_id], [], [], []) commit_cmds", "activity_id, first_published_msec): \"\"\"Updates the first_published_msec field for the given activity.", "%s tried to allow user %s to be a(n) %s", "tried to release ownership of %s %s but was '", "CMD_RELEASE_OWNERSHIP = 'release_ownership' CMD_UPDATE_FIRST_PUBLISHED_MSEC = 'update_first_published_msec' ACTIVITY_STATUS_PRIVATE = constants.ACTIVITY_STATUS_PRIVATE ACTIVITY_STATUS_PUBLIC", "perform change action. Exception. If the viewable_if_private property is already", "is performing the action. assignee_id: str. ID of the user", "# distributed under the License is distributed on an \"AS-IS\"", "if not check_can_modify_activity_roles(committer, activity_rights): logging.error( 'User %s tried to allow", "set(self.translator_ids)) editor_viewer = set(self.editor_ids).intersection(set(self.viewer_ids)) translator_viewer = set(self.editor_ids).intersection( set(self.viewer_ids)) if owner_editor:", "The rights object created from the model. \"\"\" return ActivityRights(", "ownership for given activity. Args: user: UserActionsInfo. Object having user_id,", "domain object to the datastore. Args: committer_id: str. ID of", "= activity_rights.editor_ids model.viewer_ids = activity_rights.viewer_ids model.translator_ids = activity_rights.translator_ids model.community_owned =", "if (activity_rights.is_published() and (role_services.ACTION_EDIT_ANY_PUBLIC_ACTIVITY in user.actions)): return True return False", "viewable_if_private=exploration_rights.viewable_if_private, first_published_msec=exploration_rights.first_published_msec, ).commit(committer_id, 'Created new exploration', commit_cmds) subscription_services.subscribe_to_exploration( committer_id, exploration_id)", "private. Args: exploration_id: str. ID of the exploration. Returns: bool.", "user who can publish activity can change its private viewability.", "= ROLE_TRANSLATOR elif new_role == ROLE_EDITOR: if (activity_rights.is_editor(assignee_id) or activity_rights.is_owner(assignee_id)):", "%s from %s to %s' % ( assignee_username, old_role, new_role)", "ensuring that this value is not already set before updating", "editor_viewer = set(self.editor_ids).intersection(set(self.viewer_ids)) translator_viewer = set(self.editor_ids).intersection( set(self.viewer_ids)) if owner_editor: raise", "object for the given activity. \"\"\" # TODO(msl): get rid", "for the committer. exploration_id: str. ID of the exploration. assignee_id:", "exploration to the community. Args: committer: UserActionsInfo. UserActionsInfo object for", "= ActivityRights( exploration_id, [committer_id], [], [], []) commit_cmds = [{'cmd':", "Whether the exploration should be made viewable (by anyone with", "this allows a private exploration to be viewed by anyone", "type of activity. Possible values: constants.ACTIVITY_TYPE_EXPLORATION constants.ACTIVITY_TYPE_COLLECTION commit_message: str. Descriptive", "elif activity_rights.is_published(): return bool( role_services.ACTION_PLAY_ANY_PUBLIC_ACTIVITY in user.actions) elif activity_rights.is_private(): return", "or viewers specified. \"\"\" if self.community_owned: if (self.owner_ids or self.editor_ids", "assignee_id, new_role, collection_id, constants.ACTIVITY_TYPE_COLLECTION) if new_role in [ROLE_OWNER, ROLE_EDITOR]: subscription_services.subscribe_to_collection(", "constants.ACTIVITY_TYPE_EXPLORATION: model_cls = exp_models.ExplorationRightsModel elif activity_type == constants.ACTIVITY_TYPE_COLLECTION: model_cls =", "== constants.ACTIVITY_TYPE_COLLECTION: return get_collection_rights(activity_id, strict=False) else: raise Exception( 'Cannot get", "viewable_if_private=collection_rights.viewable_if_private, first_published_msec=collection_rights.first_published_msec ).commit(committer_id, 'Created new collection', commit_cmds) subscription_services.subscribe_to_collection(committer_id, collection_id) def", "the activity summary for the given activity associated with the", "Returns: bool. Whether the given activity can be accessed by", "ANY KIND, either express or implied. # See the License", "def update_activity_first_published_msec( activity_type, activity_id, first_published_msec): \"\"\"Updates the first_published_msec field for", "exploration_rights.viewable_if_private if old_viewable_if_private == viewable_if_private: raise Exception( 'Trying to change", "ID of associated activity. Args: activity_type: str. The type of", "ActivityRights. The rights object created from the model. \"\"\" return", "performing the action. activity_id: str. ID of the activity. activity_type:", "the License. # You may obtain a copy of the", "if new_status != ACTIVITY_STATUS_PRIVATE: activity_rights.viewer_ids = [] if activity_rights.first_published_msec is", "the collection is private. \"\"\" collection_rights = get_collection_rights(collection_id) return collection_rights.status", "_save_activity_rights( committer_id, exploration_rights, constants.ACTIVITY_TYPE_EXPLORATION, commit_message, commit_cmds) _update_exploration_summary(exploration_rights) def publish_exploration(committer, exploration_id):", "= get_exploration_rights(exploration_id) return exploration_rights.status == ACTIVITY_STATUS_PRIVATE def is_exploration_public(exploration_id): \"\"\"Returns whether", "to %s' % ( assignee_username, old_role, new_role) commit_cmds = [{", "the user can translate given activity. Args: user: UserActionsInfo. Object", "# See the License for the specific language governing permissions", "user_services.get_human_readable_user_ids( self.owner_ids), 'editor_names': user_services.get_human_readable_user_ids( self.editor_ids), 'translator_names': user_services.get_human_readable_user_ids( self.translator_ids), 'viewer_names': user_services.get_human_readable_user_ids(", "activity. Returns: bool. Whether the given activity can be accessed", "of exploration %s ' 'but was refused permission.' % (committer_id,", "governing permissions and # limitations under the License. \"\"\"Domain objects", "user already can edit this %s.' % activity_type) if activity_rights.community_owned:", "% activity_type) activity_services.remove_featured_activity(activity_type, activity_id) # Rights functions for activities. def", "check_can_unpublish_activity(committer, activity_rights): logging.error( 'User %s tried to unpublish %s %s", "user is owner of activity. Args: user_id: str or None.", "is published. Returns: bool. Whether activity is published. \"\"\" return", "viewer_ids, community_owned=False, cloned_from=None, status=ACTIVITY_STATUS_PRIVATE, viewable_if_private=False, first_published_msec=None): self.id = exploration_id self.owner_ids", "collection_rights = get_collection_rights(collection_id) return collection_rights.status == ACTIVITY_STATUS_PRIVATE def is_collection_public(collection_id): \"\"\"Returns", "committer.user_id activity_rights = _get_activity_rights(activity_type, activity_id) if not check_can_modify_activity_roles(committer, activity_rights): logging.error(", "the given activity to the community. Args: committer: UserActionsInfo. UserActionsInfo", "\"\"\" activity_rights = _get_activity_rights(activity_type, activity_id) old_status = activity_rights.status activity_rights.status =", "= community_owned self.cloned_from = cloned_from self.status = status self.viewable_if_private =", "None return get_activity_rights_from_model( model, constants.ACTIVITY_TYPE_COLLECTION) def get_collection_owner_names(collection_id): \"\"\"Retrieves the owners", "License is distributed on an \"AS-IS\" BASIS, # WITHOUT WARRANTIES", "under the License. \"\"\"Domain objects and functions that manage rights", "False if role_services.ACTION_PUBLISH_ANY_ACTIVITY in user.actions: return True if role_services.ACTION_PUBLISH_OWNED_ACTIVITY in", "ROLE_EDITOR ROLE_TRANSLATOR ROLE_VIEWER activity_id: str. ID of the activity. activity_type:", "The activity is already publicly translatable. Exception. The user can", "get rid of inline imports by refactoring code. from core.domain", "ACTIVITY_STATUS_PUBLIC = constants.ACTIVITY_STATUS_PUBLIC ROLE_OWNER = 'owner' ROLE_EDITOR = 'editor' ROLE_TRANSLATOR", "if owner_editor: raise utils.ValidationError( 'A user cannot be both an", "a new exploration rights object and saves it to the", "is None: return False if activity_rights.cloned_from: return False if activity_rights.is_published():", "return False def check_can_delete_activity(user, activity_rights): \"\"\"Checks whether the user can", "the exploration is private or not. \"\"\" exploration_rights = get_exploration_rights(exploration_id)", "rights to unpublish the activity. \"\"\" committer_id = committer.user_id activity_rights", "% ( committer_id, assignee_id, new_role, activity_id)) raise Exception( 'UnauthorizedUserException: Could", "CMD_CHANGE_PRIVATE_VIEWABILITY, 'old_viewable_if_private': old_viewable_if_private, 'new_viewable_if_private': viewable_if_private, }] commit_message = ( 'Made", "the given activity. \"\"\" # TODO(msl): get rid of inline", "%s to be a(n) %s of activity %s ' 'but", "self.editor_ids = editor_ids self.translator_ids = translator_ids self.viewer_ids = viewer_ids self.community_owned", "EntityNotFoundError. The exploration with ID exploration_id was not found in", "of another exploration. Args: exploration_id: str. ID of the exploration.", "= first_published_msec _save_activity_rights( feconf.SYSTEM_COMMITTER_ID, activity_rights, activity_type, 'set first published time", "role: One of ROLE_OWNER ROLE_EDITOR ROLE_TRANSLATOR ROLE_VIEWER activity_id: str. ID", "in user.actions: return True return False def _assign_role( committer, assignee_id,", "activity to the community. Args: committer: UserActionsInfo. UserActionsInfo object for", "% activity_type) _change_activity_status( committer_id, activity_id, activity_type, ACTIVITY_STATUS_PRIVATE, '%s unpublished.' %", "should have no owners, ' 'editors, translators or viewers specified.')", "activity_type == constants.ACTIVITY_TYPE_COLLECTION: model_cls = collection_models.CollectionRightsModel model = model_cls.get(activity_rights.id, strict=False)", "activity. \"\"\" if activity_type == constants.ACTIVITY_TYPE_EXPLORATION: _update_exploration_summary(activity_rights) elif activity_type ==", "exp_ids) exp_models_list = [] for model in exp_rights_models: if model", "Human-readable usernames (or truncated email addresses) of owners for this", "object for the rights/publication status of an activity (an exploration", "%s' % editor_translator) if editor_viewer: raise utils.ValidationError( 'A user cannot", "of ROLE_OWNER ROLE_EDITOR Raises: Exception. This could potentially throw an", "\"\"\" if activity_rights is None: return False if role_services.ACTION_DELETE_ANY_ACTIVITY in", "'Community-owned %ss can be edited by anyone.' % activity_type) activity_rights.editor_ids.append(assignee_id)", "ownership released to the community.' % activity_type, commit_cmds) _update_activity_summary(activity_type, activity_rights)", "%s.' % activity_type) if activity_rights.community_owned: raise Exception( 'Community-owned %ss can", "set before updating it. Args: activity_type: str. The type of", "assignee_id, new_role, exploration_id, constants.ACTIVITY_TYPE_EXPLORATION) if new_role in [ROLE_OWNER, ROLE_EDITOR, ROLE_TRANSLATOR]:", "Licensed under the Apache License, Version 2.0 (the \"License\"); #", "invalid. \"\"\" committer_id = committer.user_id activity_rights = _get_activity_rights(activity_type, activity_id) if", "def _publish_activity(committer, activity_id, activity_type): \"\"\"Publishes the given activity. Args: committer:", "activity_type) activity_rights.community_owned = True activity_rights.owner_ids = [] activity_rights.editor_ids = []", "given exploration's rights object. If viewable_if_private is True, this allows", "responsibility of the caller to check that the exploration is", "writing, software # distributed under the License is distributed on", "the collection. Returns: bool. Whether the collection is public. \"\"\"", "constants.ACTIVITY_STATUS_PUBLIC ROLE_OWNER = 'owner' ROLE_EDITOR = 'editor' ROLE_TRANSLATOR = 'translator'", "given user can translate this activity. \"\"\" if activity_rights is", "utils.ValidationError( 'Public explorations should have no viewers specified.') owner_editor =", "ID of the exploration. viewable_if_private: bool. Whether the exploration should", "Raises: Exception. This could potentially throw an exception from _assign_role.", "activity_type: str. The type of activity. Possible values: constants.ACTIVITY_TYPE_EXPLORATION constants.ACTIVITY_TYPE_COLLECTION", "Whether the user can unpublish given activity. \"\"\" if activity_rights", "Returns: bool. Whether the user can unpublish given activity. \"\"\"", "committer_id: str. ID of the committer. \"\"\" exploration_rights = ActivityRights(", "error if there is no exploration matching the given ID.", "None) def _update_collection_summary(activity_rights): \"\"\"Updates the collection summary for the given", "(activity_rights.community_owned or activity_rights.cloned_from): return False if (role_services.ACTION_MODIFY_ROLES_FOR_ANY_ACTIVITY in user.actions): return", "collection_id: str. ID of the collection. strict: bool. Whether to", "of this %s cannot be released.' % activity_type) activity_rights.community_owned =", "caller to check that the exploration is valid prior to", "UserActionsInfo. UserActionsInfo object for the committer. exploration_id: str. ID of", "given user is viewer of activity. Args: user_id: str or", "Exception( 'Community-owned %ss can be edited by anyone.' % activity_type)", "cannot be private.') if self.status != ACTIVITY_STATUS_PRIVATE and self.viewer_ids: raise", "for the given activity. \"\"\" from core.domain import collection_services collection_services.update_collection_summary(", "cannot be both an owner and a translator: %s' %", "exploration. \"\"\" exploration_rights = get_exploration_rights(exploration_id) return bool(exploration_rights.cloned_from) def create_new_collection_rights(collection_id, committer_id):", "is published. \"\"\" return bool(self.status == ACTIVITY_STATUS_PUBLIC) def is_private(self): \"\"\"Checks", "exploration. Args: committer: UserActionsInfo. UserActionsInfo object for the committer. exploration_id:", "the caller to check that the exploration is valid prior", "'change_private_viewability' CMD_RELEASE_OWNERSHIP = 'release_ownership' CMD_UPDATE_FIRST_PUBLISHED_MSEC = 'update_first_published_msec' ACTIVITY_STATUS_PRIVATE = constants.ACTIVITY_STATUS_PRIVATE", "subscription_services.subscribe_to_exploration( committer_id, exploration_id) def get_exploration_rights(exploration_id, strict=True): \"\"\"Retrieves the rights for", "%s tried to publish %s %s but was refused '", "The committer does not have rights to unpublish the activity.", "is responsible for ensuring that this value is not already", "whether activity is published. Returns: bool. Whether activity is published.", "return False if activity_rights.is_published(): return False if role_services.ACTION_PUBLISH_ANY_ACTIVITY in user.actions:", "valid prior to publication. Args: committer: UserActionsInfo. UserActionsInfo object for", "the user. Returns: bool. Whether user is an activity viewer.", "that assignee_id corresponds to a valid user in the system.", "the user can edit given activity. Args: user: UserActionsInfo. Object", "the user can unpublish given activity. \"\"\" if activity_rights is", "unpublished.' % activity_type) activity_services.remove_featured_activity(activity_type, activity_id) # Rights functions for activities.", "or activity_rights.is_editor(user.user_id) or activity_rights.is_translator(user.user_id) or activity_rights.viewable_if_private) def check_can_edit_activity(user, activity_rights): \"\"\"Checks", "activity. \"\"\" if activity_rights is None: return False if role_services.ACTION_DELETE_ANY_ACTIVITY", "private.') if self.status != ACTIVITY_STATUS_PRIVATE and self.viewer_ids: raise utils.ValidationError( 'Public", "of activity. Possible values: constants.ACTIVITY_TYPE_EXPLORATION constants.ACTIVITY_TYPE_COLLECTION Returns: ActivityRights. The rights", "committer_id = committer.user_id activity_rights = _get_activity_rights(activity_type, activity_id) if not check_can_release_ownership(committer,", "community_owned=activity_rights_model.community_owned, cloned_from=( activity_rights_model.cloned_from if activity_type == constants.ACTIVITY_TYPE_EXPLORATION else None), status=activity_rights_model.status,", "user can already edit the activity. Exception. The user can", "for this collection from the datastore. Args: collection_id: str. ID", "the user can publish given activity. Args: user: UserActionsInfo. Object", "committer. \"\"\" collection_rights = ActivityRights( collection_id, [committer_id], [], [], [])", "the given activity. activity_type: str. The type of activity. Possible", "first_published_msec _save_activity_rights( feconf.SYSTEM_COMMITTER_ID, activity_rights, activity_type, 'set first published time in", "%s.' % activity_type) activity_rights.owner_ids.append(assignee_id) if assignee_id in activity_rights.viewer_ids: activity_rights.viewer_ids.remove(assignee_id) old_role", "of activity. Possible values: constants.ACTIVITY_TYPE_EXPLORATION constants.ACTIVITY_TYPE_COLLECTION activity_rights: ActivityRights. The rights", "the exploration. viewable_if_private: bool. Whether the exploration should be made", "the exploration. committer_id: str. ID of the committer. \"\"\" exploration_rights", "activity_rights is None: return False if activity_rights.community_owned: return False if", "the given rights object. The ID of rights object is", "\"\"\" return bool(self.status == ACTIVITY_STATUS_PUBLIC) def is_private(self): \"\"\"Checks whether activity", "of the collection. Raises: Exception. This could potentially throw an", "keys that already exist. CMD_CREATE_NEW = 'create_new' CMD_CHANGE_ROLE = 'change_role'", "exploration from the datastore. Args: exploration_id: str. ID of the", "user can delete given activity. \"\"\" if activity_rights is None:", "= _get_activity_rights(activity_type, activity_id) old_status = activity_rights.status activity_rights.status = new_status if", "throw an exception from _publish_activity. \"\"\" _publish_activity( committer, exploration_id, constants.ACTIVITY_TYPE_EXPLORATION)", "self.viewer_ids = viewer_ids self.community_owned = community_owned self.cloned_from = cloned_from self.status", "translators and viewers lists overlap, or if a community-owned exploration", "role and actions for given user. activity_rights: AcitivityRights or None.", "to release ownership of %s %s but was ' 'refused", "cannot be both a translator and a viewer: %s' %", "= cloned_from self.status = status self.viewable_if_private = viewable_if_private self.first_published_msec =", "already publicly viewable. Exception. The role is invalid. \"\"\" committer_id", "the Epoch. \"\"\" activity_rights = _get_activity_rights(activity_type, activity_id) commit_cmds = [{", "can release ownership for given activity. \"\"\" if activity_rights is", "of the caller to check that the collection is valid", "a role. Exception. The user already owns the activity. Exception.", "str. ID of the activity. Returns: ActivityRights. The rights object", "new role: One of ROLE_OWNER ROLE_EDITOR ROLE_TRANSLATOR Raises: Exception. This", "None: return False if activity_rights.community_owned: return False if activity_rights.is_published(): if", "Possible values: constants.ACTIVITY_TYPE_EXPLORATION constants.ACTIVITY_TYPE_COLLECTION Raises: Exception. The committer does not", "\"\"\"Unpublishes the given activity. Args: committer: UserActionsInfo. UserActionsInfo object for", "associated with the given rights object. The ID of rights", "in user.actions: return True if role_services.ACTION_PUBLISH_OWNED_ACTIVITY in user.actions: if activity_rights.is_owner(user.user_id):", "the exploration is a clone of another exploration. Args: exploration_id:", "\"\"\" return bool(self.status == ACTIVITY_STATUS_PRIVATE) def get_activity_rights_from_model(activity_rights_model, activity_type): \"\"\"Constructs an", "to raise an error if ID is not found. Returns:", "ID. Returns: ActivityRights. The rights object for the given exploration.", "object for the given activity. \"\"\" from core.domain import collection_services", "return bool( role_services.ACTION_PLAY_ANY_PUBLIC_ACTIVITY in user.actions) elif activity_rights.is_private(): return bool( (role_services.ACTION_PLAY_ANY_PRIVATE_ACTIVITY", "def is_exploration_cloned(exploration_id): \"\"\"Returns whether the exploration is a clone of", "of the user whose role is being changed. new_role: str.", "'create_new' CMD_CHANGE_ROLE = 'change_role' CMD_CHANGE_EXPLORATION_STATUS = 'change_exploration_status' CMD_CHANGE_COLLECTION_STATUS = 'change_collection_status'", "an editor and a viewer: %s' % editor_viewer) if translator_viewer:", "return bool(user_id in self.editor_ids) def is_translator(self, user_id): \"\"\"Checks whether given", "' 'refused permission.' % (committer_id, activity_type, activity_id)) raise Exception( 'The", "(activity_rights.is_published() and (role_services.ACTION_DELETE_ANY_PUBLIC_ACTIVITY in user.actions)): return True return False def", "new collection rights object and saves it to the datastore.", "str. ID of the activity. first_published_msec: float. First publication time", "def unpublish_exploration(committer, exploration_id): \"\"\"Unpublishes the given exploration. Args: committer: UserActionsInfo.", "new role to the user. Args: committer: UserActionsInfo. UserActionInfo object", "translated by anyone.' % activity_type) activity_rights.translator_ids.append(assignee_id) if assignee_id in activity_rights.viewer_ids:", "ROLE_EDITOR if assignee_id in activity_rights.translator_ids: activity_rights.translator_ids.remove(assignee_id) old_role = ROLE_TRANSLATOR elif", "first_published_msec }] activity_rights.first_published_msec = first_published_msec _save_activity_rights( feconf.SYSTEM_COMMITTER_ID, activity_rights, activity_type, 'set", "the action. assignee_id: str. ID of the user whose role", "The user who can publish activity can change its private", "2014 The Oppia Authors. All Rights Reserved. # # Licensed", "def get_collection_rights(collection_id, strict=True): \"\"\"Retrieves the rights for this collection from", "can unpublish given activity. \"\"\" if activity_rights is None: return", "to unpublish the activity. \"\"\" committer_id = committer.user_id activity_rights =", "definitions of CMD keys that already exist. CMD_CREATE_NEW = 'create_new'", "False if (activity_rights.community_owned or activity_rights.cloned_from): return False if (role_services.ACTION_MODIFY_ROLES_FOR_ANY_ACTIVITY in", "activity_type): \"\"\"Unpublishes the given activity. Args: committer: UserActionsInfo. UserActionsInfo object", "be private.') if self.status != ACTIVITY_STATUS_PRIVATE and self.viewer_ids: raise utils.ValidationError(", "activity_rights.is_published(): return False if role_services.ACTION_PUBLISH_ANY_ACTIVITY in user.actions: return True if", "False elif activity_rights.is_published(): return bool( role_services.ACTION_PLAY_ANY_PUBLIC_ACTIVITY in user.actions) elif activity_rights.is_private():", "the datastore. Args: collection_id: str. ID of the collection. strict:", "bool( (role_services.ACTION_PLAY_ANY_PRIVATE_ACTIVITY in user.actions) or activity_rights.is_viewer(user.user_id) or activity_rights.is_owner(user.user_id) or activity_rights.is_editor(user.user_id)", "if assignee_id in activity_rights.translator_ids: activity_rights.translator_ids.remove(assignee_id) old_role = ROLE_TRANSLATOR if assignee_id", "if activity_rights.cloned_from: return False if activity_rights.is_published(): return False if role_services.ACTION_PUBLISH_ANY_ACTIVITY", "an exception from _assign_role. \"\"\" _assign_role( committer, assignee_id, new_role, collection_id,", "editor_translator: raise utils.ValidationError( 'A user cannot be both an editor", "exp_rights_models = exp_models.ExplorationRightsModel.get_multi( exp_ids) exp_models_list = [] for model in", "exp_models_list def is_exploration_private(exploration_id): \"\"\"Returns whether exploration is private. Args: exploration_id:", "exploration_rights = get_exploration_rights(exploration_id) return exploration_rights.status == ACTIVITY_STATUS_PRIVATE def is_exploration_public(exploration_id): \"\"\"Returns", "activity_id) old_status = activity_rights.status activity_rights.status = new_status if activity_type ==", "given activity. \"\"\" # TODO(msl): get rid of inline imports", "user can translate this activity. \"\"\" if activity_rights is None:", "= activity_rights.viewable_if_private model.first_published_msec = activity_rights.first_published_msec model.commit(committer_id, commit_message, commit_cmds) def _update_exploration_summary(activity_rights):", "False if activity_rights.is_private(): return False return check_can_modify_activity_roles( user, activity_rights) def", "return user_services.get_human_readable_user_ids( collection_rights.owner_ids) def is_collection_private(collection_id): \"\"\"Returns whether the collection is", "activity_rights.is_editor(user.user_id) or activity_rights.is_translator(user.user_id)): return True if (activity_rights.community_owned or (role_services.ACTION_EDIT_ANY_ACTIVITY in", "private viewability. if not check_can_publish_activity(committer, exploration_rights): logging.error( 'User %s tried", "core.domain import collection_services collection_services.update_collection_summary( activity_rights.id, None) def _update_activity_summary(activity_type, activity_rights): \"\"\"Updates", "owners, ' 'editors, translators or viewers specified.') if self.community_owned and", "provided is unknown. \"\"\" if activity_type == constants.ACTIVITY_TYPE_EXPLORATION: return get_exploration_rights(activity_id,", "this %s cannot be released.' % activity_type) activity_rights.community_owned = True", "if activity_rights.is_owner(user.user_id): return True return False def check_can_release_ownership(user, activity_rights): \"\"\"Checks", "If the viewable_if_private property is already as desired. \"\"\" committer_id", "activity_id): \"\"\"Retrieves the rights object for the given activity based", "activity_id, activity_type): \"\"\"Assigns a new role to the user. Args:", "the given activity. Args: committer_id: str. ID of the user", "== ACTIVITY_STATUS_PUBLIC) def is_private(self): \"\"\"Checks whether activity is private. Returns:", "== constants.ACTIVITY_TYPE_COLLECTION: _update_collection_summary(activity_rights) def update_activity_first_published_msec( activity_type, activity_id, first_published_msec): \"\"\"Updates the", "model.commit(committer_id, commit_message, commit_cmds) def _update_exploration_summary(activity_rights): \"\"\"Updates the exploration summary for", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "%s' % owner_translator) if owner_viewer: raise utils.ValidationError( 'A user cannot", "Returns: bool. Whether user is an activity owner. \"\"\" return", "the exploration is valid prior to publication. Args: committer: UserActionsInfo.", "in user.actions)): return True return False def check_can_modify_activity_roles(user, activity_rights): \"\"\"Checks", "an owner and an editor: %s' % owner_editor) if owner_translator:", "activity. Possible values: constants.ACTIVITY_TYPE_EXPLORATION constants.ACTIVITY_TYPE_COLLECTION activity_id: str. ID of the", "model_cls = exp_models.ExplorationRightsModel elif activity_type == constants.ACTIVITY_TYPE_COLLECTION: model_cls = collection_models.CollectionRightsModel", "the given activity. Returns: bool. Whether the user can modify", "collection from the datastore. Args: collection_id: str. ID of the", "cannot be both an owner and a viewer: %s' %", "of commit was done. \"\"\" activity_rights.validate() if activity_type == constants.ACTIVITY_TYPE_EXPLORATION:", "Returns: bool. Whether the exploration is a clone of another", "exploration_id, viewable_if_private): \"\"\"Sets the viewable_if_private attribute for the given exploration's", "old_role = ROLE_VIEWER if assignee_id in activity_rights.editor_ids: activity_rights.editor_ids.remove(assignee_id) old_role =", "the user. Returns: bool. Whether user is an activity editor.", "import feconf import utils current_user_services = models.Registry.import_current_user_services() (collection_models, exp_models,) =", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "return bool(user_id in self.viewer_ids) def is_published(self): \"\"\"Checks whether activity is", "edited by anyone.' % activity_type) activity_rights.editor_ids.append(assignee_id) if assignee_id in activity_rights.translator_ids:", "def is_viewer(self, user_id): \"\"\"Checks whether given user is viewer of", "[], 'translator_names': [], 'viewer_names': [], 'viewable_if_private': self.viewable_if_private, } else: return", "raise Exception( 'The viewability status of this exploration cannot be", "= set(self.owner_ids).intersection(set(self.editor_ids)) owner_translator = set(self.owner_ids).intersection( set(self.translator_ids)) owner_viewer = set(self.owner_ids).intersection(set(self.viewer_ids)) editor_translator", "ID collection_id is not found in the datastore. \"\"\" model", "bool. Whether the exploration should be made viewable (by anyone", "\"\"\" if activity_rights is None: return False if role_services.ACTION_EDIT_OWNED_ACTIVITY not", "str. ID of the collection. Returns: bool. Whether the collection", "_assign_role( committer, assignee_id, new_role, collection_id, constants.ACTIVITY_TYPE_COLLECTION) if new_role in [ROLE_OWNER,", "activity_rights): logging.error( 'User %s tried to release ownership of %s", "for the given activity based on its type. Args: activity_type:", "'but was refused permission.' % (committer_id, exploration_id)) raise Exception( 'The", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "usernames (or truncated email addresses) of owners for this collection.", "activity_id)) raise Exception( 'UnauthorizedUserException: Could not assign new role.') assignee_username", "activity_services.remove_featured_activity(activity_type, activity_id) # Rights functions for activities. def assign_role_for_exploration( committer,", "subscription_services from core.domain import user_services from core.platform import models import", "collection_rights = get_collection_rights(collection_id) return user_services.get_human_readable_user_ids( collection_rights.owner_ids) def is_collection_private(collection_id): \"\"\"Returns whether", "_unpublish_activity. \"\"\" _unpublish_activity( committer, exploration_id, constants.ACTIVITY_TYPE_EXPLORATION) # Rights functions for", "from the model. \"\"\" return ActivityRights( activity_rights_model.id, activity_rights_model.owner_ids, activity_rights_model.editor_ids, activity_rights_model.translator_ids,", "activity is already publicly translatable. Exception. The user can already", "Exception. The user can already translate the activity. Exception. The", "Rights functions for activities. def assign_role_for_exploration( committer, exploration_id, assignee_id, new_role):", "publish %s %s but was refused ' 'permission.' % (committer_id,", "= first_published_msec def validate(self): \"\"\"Validates an ActivityRights object. Raises: utils.ValidationError:", "CMD_UPDATE_FIRST_PUBLISHED_MSEC = 'update_first_published_msec' ACTIVITY_STATUS_PRIVATE = constants.ACTIVITY_STATUS_PRIVATE ACTIVITY_STATUS_PUBLIC = constants.ACTIVITY_STATUS_PUBLIC ROLE_OWNER", "is private or not. \"\"\" exploration_rights = get_exploration_rights(exploration_id) return exploration_rights.status", "[]) commit_cmds = [{'cmd': CMD_CREATE_NEW}] collection_models.CollectionRightsModel( id=collection_rights.id, owner_ids=collection_rights.owner_ids, editor_ids=collection_rights.editor_ids, translator_ids=collection_rights.translator_ids,", "committer, exploration_id, constants.ACTIVITY_TYPE_EXPLORATION) def unpublish_exploration(committer, exploration_id): \"\"\"Unpublishes the given exploration.", "return collection_rights.status == ACTIVITY_STATUS_PRIVATE def is_collection_public(collection_id): \"\"\"Returns whether the collection", "ACTIVITY_STATUS_PRIVATE: raise utils.ValidationError( 'Community-owned explorations cannot be private.') if self.status", "owner_editor = set(self.owner_ids).intersection(set(self.editor_ids)) owner_translator = set(self.owner_ids).intersection( set(self.translator_ids)) owner_viewer = set(self.owner_ids).intersection(set(self.viewer_ids))", "user_id): \"\"\"Checks whether given user is editor of activity. Args:", "be both an editor and a viewer: %s' % editor_viewer)", "who is performing the update action. activity_id: str. ID of", "object for the given activity. activity_type: str. The type of", "else: exp_models_list.append( get_activity_rights_from_model( model, constants.ACTIVITY_TYPE_EXPLORATION)) return exp_models_list def is_exploration_private(exploration_id): \"\"\"Returns", "anyone with the link). Raises: Exception. The committer does not", "%s ' 'but was refused permission.' % (committer_id, exploration_id)) raise", "activity_rights.first_published_msec model.commit(committer_id, commit_message, commit_cmds) def _update_exploration_summary(activity_rights): \"\"\"Updates the exploration summary", "return False if role_services.ACTION_DELETE_ANY_ACTIVITY in user.actions: return True elif (activity_rights.is_private()", "the datastore. Args: collection_id: str. ID of the collection. Returns:", "unpublish given activity. Args: user: UserActionsInfo. Object having user_id, role", "in user.actions) or activity_rights.is_viewer(user.user_id) or activity_rights.is_owner(user.user_id) or activity_rights.is_editor(user.user_id) or activity_rights.is_translator(user.user_id)", "ID of the exploration. Raises: Exception. This could potentially throw", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "not check_can_modify_activity_roles(committer, activity_rights): logging.error( 'User %s tried to allow user", "ids. Args: exp_ids: list(str). List of exploration ids. Returns: list(ActivityRights", "can view this %s.' % activity_type) if activity_rights.status != ACTIVITY_STATUS_PRIVATE:", "activity_type == constants.ACTIVITY_TYPE_EXPLORATION: cmd_type = CMD_CHANGE_EXPLORATION_STATUS elif activity_type == constants.ACTIVITY_TYPE_COLLECTION:", "_assign_role( committer, assignee_id, new_role, activity_id, activity_type): \"\"\"Assigns a new role", "first published time in msec', commit_cmds) def create_new_exploration_rights(exploration_id, committer_id): \"\"\"Creates", "Rights Reserved. # # Licensed under the Apache License, Version", "the user whose role is being changed. new_role: str. The", "is editor of activity. Args: user_id: str or None. Id", "Subscribes the committer to the new exploration. Args: exploration_id: str.", "dict suitable for use by the frontend. Returns: dict. A", "specific language governing permissions and # limitations under the License.", "str. ID of the committer. activity_rights: ActivityRights. The rights object", "= viewable_if_private self.first_published_msec = first_published_msec def validate(self): \"\"\"Validates an ActivityRights", "be both a translator and a viewer: %s' % translator_viewer)", "False def check_can_translate_activity(user, activity_rights): \"\"\"Checks whether the user can translate", "commit_cmds = [{'cmd': CMD_CREATE_NEW}] collection_models.CollectionRightsModel( id=collection_rights.id, owner_ids=collection_rights.owner_ids, editor_ids=collection_rights.editor_ids, translator_ids=collection_rights.translator_ids, viewer_ids=collection_rights.viewer_ids,", "new_role == ROLE_EDITOR: if (activity_rights.is_editor(assignee_id) or activity_rights.is_owner(assignee_id)): raise Exception( 'This", "return True if (activity_rights.is_published() and (role_services.ACTION_EDIT_ANY_PUBLIC_ACTIVITY in user.actions)): return True", "exploration_id: str. ID of the exploration. strict: bool. Whether to", "already edit the activity. Exception. The user can already translate", "(activity_rights.is_editor(assignee_id) or activity_rights.is_owner(assignee_id)): raise Exception( 'This user already can edit", "Exception. The role is invalid. \"\"\" committer_id = committer.user_id activity_rights", "activity. activity_type: str. The type of activity. Possible values: constants.ACTIVITY_TYPE_EXPLORATION", "True activity_rights.owner_ids = [] activity_rights.editor_ids = [] activity_rights.viewer_ids = []", "publish_exploration(committer, exploration_id): \"\"\"Publishes the given exploration. It is the responsibility", "ROLE_OWNER ROLE_EDITOR Raises: Exception. This could potentially throw an exception", "activity_type, commit_cmds) _update_activity_summary(activity_type, activity_rights) def _change_activity_status( committer_id, activity_id, activity_type, new_status,", "actions.\"\"\" import logging from constants import constants from core.domain import", "ID is not found. Returns: ActivityRights. The rights object for", "release ownership for given activity. Args: user: UserActionsInfo. Object having", "viewable_if_private else 'Made exploration viewable only to invited playtesters.') _save_activity_rights(", "model = model_cls.get(activity_rights.id, strict=False) model.owner_ids = activity_rights.owner_ids model.editor_ids = activity_rights.editor_ids", "private exploration to be viewed by anyone with the link.", "Raises: EntityNotFoundError. The exploration with ID exploration_id was not found", "new_role, activity_id)) raise Exception( 'UnauthorizedUserException: Could not assign new role.')", "( assignee_username, old_role, new_role) commit_cmds = [{ 'cmd': CMD_CHANGE_ROLE, 'assignee_id':", "exploration_id: str. ID of the exploration. Returns: bool. Whether the", "the exploration. Returns: bool. Whether the exploration is public. \"\"\"", "datastore. activity_type: str. The type of activity. Possible values: constants.ACTIVITY_TYPE_EXPLORATION", "describing what kind of commit was done. \"\"\" activity_rights.validate() if", "% (committer_id, activity_type, activity_id)) raise Exception('This %s cannot be unpublished.'", "# you may not use this file except in compliance", "'Community-owned explorations cannot be private.') if self.status != ACTIVITY_STATUS_PRIVATE and", "user. activity_rights: ActivityRights or None. Rights object for the given", "[{ 'cmd': CMD_CHANGE_ROLE, 'assignee_id': assignee_id, 'old_role': old_role, 'new_role': new_role }]", "\"\"\"Publishes the given exploration. It is the responsibility of the", "def _release_ownership_of_activity(committer, activity_id, activity_type): \"\"\"Releases ownership of the given activity", "None: activity_rights.first_published_msec = ( utils.get_current_time_in_millisecs()) _save_activity_rights( committer_id, activity_rights, activity_type, commit_message,", "whether the user can delete given activity. Args: user: UserActionsInfo.", "constants.ACTIVITY_TYPE_EXPLORATION constants.ACTIVITY_TYPE_COLLECTION new_status: str. The new status of the activity.", "potentially throw an exception from _publish_activity. \"\"\" _publish_activity( committer, exploration_id,", "'A user cannot be both an owner and an editor:", "activity_rights is None: return False elif activity_rights.is_published(): return bool( role_services.ACTION_PLAY_ANY_PUBLIC_ACTIVITY", "for various user actions.\"\"\" import logging from constants import constants", "bool. Whether the given user can translate this activity. \"\"\"", "bool(self.status == ACTIVITY_STATUS_PRIVATE) def get_activity_rights_from_model(activity_rights_model, activity_type): \"\"\"Constructs an ActivityRights object", "rights for unknown activity type: %s' % ( activity_type)) def", "Args: committer_id: str. ID of the committer. activity_rights: ActivityRights. The", "return True return False def check_can_translate_activity(user, activity_rights): \"\"\"Checks whether the", "Exception. The activity is already publicly viewable. Exception. The role", "exploration snapshots in the datastore. # Do not modify the", "% activity_type) def _unpublish_activity(committer, activity_id, activity_type): \"\"\"Unpublishes the given activity.", "logging.error( 'User %s tried to change private viewability of exploration", "an owner and a translator: %s' % owner_translator) if owner_viewer:", "is_exploration_cloned(exploration_id): \"\"\"Returns whether the exploration is a clone of another", "\"\"\"Changes the status of the given activity. Args: committer_id: str.", "rights object. If viewable_if_private is True, this allows a private", "Whether the user can release ownership for given activity. \"\"\"", "this %s.' % activity_type) if activity_rights.status != ACTIVITY_STATUS_PRIVATE: raise Exception(", "activity_rights.first_published_msec, 'new_first_published_msec': first_published_msec }] activity_rights.first_published_msec = first_published_msec _save_activity_rights( feconf.SYSTEM_COMMITTER_ID, activity_rights,", "to unpublish %s %s but was refused ' 'permission.' %", "= new_status if activity_type == constants.ACTIVITY_TYPE_EXPLORATION: cmd_type = CMD_CHANGE_EXPLORATION_STATUS elif", "edit the activity. Exception. The user can already translate the", "The rights object for the given activity. \"\"\" # TODO(msl):", "Whether the exploration is a clone of another exploration. \"\"\"", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "constants.ACTIVITY_TYPE_COLLECTION) def unpublish_collection(committer, collection_id): \"\"\"Unpublishes the given collection. Args: committer:", "'translator_names': [], 'viewer_names': [], 'viewable_if_private': self.viewable_if_private, } else: return {", "Args: activity_rights: ActivityRights. The rights object for the given activity.", "committer_id): \"\"\"Creates a new exploration rights object and saves it", "matching the given ID. Returns: ActivityRights. The rights object for", "if activity_rights is None: return False if (activity_rights.community_owned or activity_rights.cloned_from):", "assignee_id corresponds to a valid user in the system. Args:", "activity_id) if not check_can_modify_activity_roles(committer, activity_rights): logging.error( 'User %s tried to", "The user can already edit the activity. Exception. The user", "for the committer. collection_id: str. ID of the collection. assignee_id:", "Whether the given user can edit this activity. \"\"\" if", "given activity can be accessed by the given user. \"\"\"", "The committer does not have rights to modify a role.", "collection summary for the given activity associated with the given", "have rights to modify a role. Exception. The user already", "This could potentially throw an exception from _assign_role. \"\"\" _assign_role(", "committer.user_id exploration_rights = get_exploration_rights(exploration_id) # The user who can publish", "performing the update action. activity_id: str. ID of the activity.", "user.actions)): return True return False def check_can_delete_activity(user, activity_rights): \"\"\"Checks whether", "the given activity. Returns: bool. Whether the given user can", "under the Apache License, Version 2.0 (the \"License\"); # you", "activity_id, activity_type, ACTIVITY_STATUS_PRIVATE, '%s unpublished.' % activity_type) activity_services.remove_featured_activity(activity_type, activity_id) #", "check_can_publish_activity(committer, exploration_rights): logging.error( 'User %s tried to change private viewability", "given rights object. The ID of rights object is the", "commit_cmds): \"\"\"Saves an ExplorationRights or CollectionRights domain object to the", "= ROLE_EDITOR if assignee_id in activity_rights.translator_ids: activity_rights.translator_ids.remove(assignee_id) old_role = ROLE_TRANSLATOR", "assignee_id, collection_id) def release_ownership_of_collection(committer, collection_id): \"\"\"Releases ownership of the given", "get_activity_rights_from_model( model, constants.ACTIVITY_TYPE_EXPLORATION)) return exp_models_list def is_exploration_private(exploration_id): \"\"\"Returns whether exploration", "user cannot be both an owner and an editor: %s'", "user who is performing the action. activity_id: str. ID of", "the collection. Returns: list(str). Human-readable usernames (or truncated email addresses)", "ID of the collection. committer_id: str. ID of the committer.", "release_ownership_of_collection(committer, collection_id): \"\"\"Releases ownership of the given collection to the", "None: return False if role_services.ACTION_EDIT_OWNED_ACTIVITY not in user.actions: return False", "activity_rights.is_private(): return False return check_can_modify_activity_roles( user, activity_rights) def check_can_publish_activity(user, activity_rights):", "a translator: %s' % editor_translator) if editor_viewer: raise utils.ValidationError( 'A", "new exploration. Args: exploration_id: str. ID of the exploration. committer_id:", "def set_private_viewability_of_exploration( committer, exploration_id, viewable_if_private): \"\"\"Sets the viewable_if_private attribute for", "subscription_services.subscribe_to_collection(committer_id, collection_id) def get_collection_rights(collection_id, strict=True): \"\"\"Retrieves the rights for this", "commit_message: str. Descriptive message for the commit. commit_cmds: list(dict). A", "another exploration. \"\"\" exploration_rights = get_exploration_rights(exploration_id) return bool(exploration_rights.cloned_from) def create_new_collection_rights(collection_id,", "of the given collection to the community. Args: committer: UserActionsInfo.", "user_id): \"\"\"Checks whether given user is owner of activity. Args:", "UserActionsInfo. The UserActionsInfo object for the committer. exploration_id: str. ID", "= activity_rights.owner_ids model.editor_ids = activity_rights.editor_ids model.viewer_ids = activity_rights.viewer_ids model.translator_ids =", "user can already view the activity. Exception. The activity is", "activity_rights, activity_type, commit_message, commit_cmds) _update_activity_summary(activity_type, activity_rights) def _publish_activity(committer, activity_id, activity_type):", "ACTIVITY_STATUS_PUBLIC def is_exploration_cloned(exploration_id): \"\"\"Returns whether the exploration is a clone", "[], [], []) commit_cmds = [{'cmd': CMD_CREATE_NEW}] collection_models.CollectionRightsModel( id=collection_rights.id, owner_ids=collection_rights.owner_ids,", "datastore. Args: committer_id: str. ID of the committer. activity_rights: ActivityRights.", "user cannot be both an editor and a translator: %s'", "can release ownership for given activity. Args: user: UserActionsInfo. Object", "'new_status': new_status }] if new_status != ACTIVITY_STATUS_PRIVATE: activity_rights.viewer_ids = []", "not have rights to modify a role. Exception. The user", "self.community_owned = community_owned self.cloned_from = cloned_from self.status = status self.viewable_if_private", "an ActivityRights object from the given activity rights model. Args:", "if editor_translator: raise utils.ValidationError( 'A user cannot be both an", "ActivityRights or None. Rights object for the given activity. Returns:", "\"\"\" if activity_type == constants.ACTIVITY_TYPE_EXPLORATION: _update_exploration_summary(activity_rights) elif activity_type == constants.ACTIVITY_TYPE_COLLECTION:", "from core.domain import subscription_services from core.domain import user_services from core.platform", "the datastore. Subscribes the committer to the new collection. Args:", "raise Exception( 'Community-owned %ss can be edited by anyone.' %", "functions for collections. def assign_role_for_collection( committer, collection_id, assignee_id, new_role): \"\"\"Assign", "exploration. Raises: EntityNotFoundError. The exploration with ID exploration_id was not", "False if activity_rights.cloned_from: return False if activity_rights.is_published(): return False if", "and a translator: %s' % owner_translator) if owner_viewer: raise utils.ValidationError(", "of commands describing what kind of commit was done. \"\"\"", "exploration_rights = get_exploration_rights(exploration_id) return bool(exploration_rights.cloned_from) def create_new_collection_rights(collection_id, committer_id): \"\"\"Creates a", "def _assign_role( committer, assignee_id, new_role, activity_id, activity_type): \"\"\"Assigns a new", "user actions.\"\"\" import logging from constants import constants from core.domain", "(activity_rights.is_private() and (role_services.ACTION_DELETE_OWNED_PRIVATE_ACTIVITY in user.actions) and activity_rights.is_owner(user.user_id)): return True elif", "True return False def check_can_delete_activity(user, activity_rights): \"\"\"Checks whether the user", "owner_viewer: raise utils.ValidationError( 'A user cannot be both an owner", "user can publish given activity. Args: user: UserActionsInfo. Object having", "from core.domain import user_services from core.platform import models import feconf", "unpublished.' % activity_type) _change_activity_status( committer_id, activity_id, activity_type, ACTIVITY_STATUS_PRIVATE, '%s unpublished.'", "committer: UserActionsInfo. UserActionsInfo object for the committer. exploration_id: str. ID", "type. Args: activity_type: str. The type of activity. Possible values:", "that manage rights for various user actions.\"\"\" import logging from", "not have rights to publish the activity. \"\"\" committer_id =", "ActivityRights object. Raises: utils.ValidationError: if any of the owners, editors,", "can delete given activity. Args: user: UserActionsInfo. Object having user_id,", "activity_id, activity_type, new_status, commit_message): \"\"\"Changes the status of the given", "set(self.editor_ids).intersection( set(self.translator_ids)) editor_viewer = set(self.editor_ids).intersection(set(self.viewer_ids)) translator_viewer = set(self.editor_ids).intersection( set(self.viewer_ids)) if", "user is viewer of activity. Args: user_id: str or None.", "The activity is already publicly viewable. Exception. The role is", "throw an exception from _assign_role. \"\"\" _assign_role( committer, assignee_id, new_role,", "activity. Returns: bool. Whether the given user can translate this", "commit_message, commit_cmds) _update_activity_summary(activity_type, activity_rights) def _release_ownership_of_activity(committer, activity_id, activity_type): \"\"\"Releases ownership", "= get_collection_rights(collection_id) return collection_rights.status == ACTIVITY_STATUS_PUBLIC def _get_activity_rights(activity_type, activity_id): \"\"\"Retrieves", "released.' % activity_type) activity_rights.community_owned = True activity_rights.owner_ids = [] activity_rights.editor_ids", "change viewability status of this exploration to %s, ' 'but", "Epoch. \"\"\" activity_rights = _get_activity_rights(activity_type, activity_id) commit_cmds = [{ 'cmd':", "= committer.user_id exploration_rights = get_exploration_rights(exploration_id) # The user who can", "ID of the exploration. strict: bool. Whether to raise an", "activity_rights.viewer_ids.append(assignee_id) else: raise Exception('Invalid role: %s' % new_role) commit_message =", "Exception( 'The ownership of this %s cannot be released.' %", "to the datastore. Subscribes the committer to the new collection.", "user already owns the activity. Exception. The user can already", "constants.ACTIVITY_TYPE_EXPLORATION) def set_private_viewability_of_exploration( committer, exploration_id, viewable_if_private): \"\"\"Sets the viewable_if_private attribute", "Returns: bool. Whether activity is private. \"\"\" return bool(self.status ==", "activity_rights.is_owner(user.user_id)): return True elif (activity_rights.is_published() and (role_services.ACTION_DELETE_ANY_PUBLIC_ACTIVITY in user.actions)): return", "self.status = status self.viewable_if_private = viewable_if_private self.first_published_msec = first_published_msec def", "str. The name of the new role: One of ROLE_OWNER", "activity rights model. Args: activity_rights_model: ActivityRightsModel. Activity rights from the", "\"\"\" exploration_rights = ActivityRights( exploration_id, [committer_id], [], [], []) commit_cmds", "activity can be accessed by the given user. \"\"\" if", "'viewable_if_private': self.viewable_if_private, } else: return { 'cloned_from': self.cloned_from, 'status': self.status,", "strict: bool. Whether to raise an error if ID is", "%s' % translator_viewer) def to_dict(self): \"\"\"Returns a dict suitable for", "changes to how these cmds are interpreted preserve # backward-compatibility", "exploration. committer_id: str. ID of the committer. \"\"\" exploration_rights =", "exploration. Args: exploration_id: str. ID of the exploration. Returns: bool.", "editable. Exception. The activity is already publicly translatable. Exception. The", "user. Returns: bool. Whether user is an activity owner. \"\"\"", "role_services.ACTION_PLAY_ANY_PUBLIC_ACTIVITY in user.actions) elif activity_rights.is_private(): return bool( (role_services.ACTION_PLAY_ANY_PRIVATE_ACTIVITY in user.actions)", "to allow user %s to be a(n) %s of activity", "= committer.user_id activity_rights = _get_activity_rights(activity_type, activity_id) if not check_can_publish_activity(committer, activity_rights):", "value is not already set before updating it. Args: activity_type:", "constants.ACTIVITY_TYPE_COLLECTION: cmd_type = CMD_CHANGE_COLLECTION_STATUS commit_cmds = [{ 'cmd': cmd_type, 'old_status':", "committer. activity_id: str. ID of the activity. activity_type: str. The", "[], 'viewer_names': [], 'viewable_if_private': self.viewable_if_private, } else: return { 'cloned_from':", "activity_rights.id, None) def _update_activity_summary(activity_type, activity_rights): \"\"\"Updates the activity summary for", "have no viewers specified.') owner_editor = set(self.owner_ids).intersection(set(self.editor_ids)) owner_translator = set(self.owner_ids).intersection(", "activity_type == constants.ACTIVITY_TYPE_COLLECTION: cmd_type = CMD_CHANGE_COLLECTION_STATUS commit_cmds = [{ 'cmd':", "= committer.user_id activity_rights = _get_activity_rights(activity_type, activity_id) if not check_can_unpublish_activity(committer, activity_rights):", "bool. Whether activity is published. \"\"\" return bool(self.status == ACTIVITY_STATUS_PUBLIC)", "= ROLE_VIEWER elif new_role == ROLE_TRANSLATOR: if (activity_rights.is_editor(assignee_id) or activity_rights.is_translator(assignee_id)", "both an editor and a translator: %s' % editor_translator) if", "to the new exploration. Args: exploration_id: str. ID of the", "activity_rights.viewer_ids: activity_rights.viewer_ids.remove(assignee_id) old_role = ROLE_VIEWER elif new_role == ROLE_VIEWER: if", "of activity. Possible values: constants.ACTIVITY_TYPE_EXPLORATION constants.ACTIVITY_TYPE_COLLECTION new_status: str. The new", "release_ownership_of_exploration(committer, exploration_id): \"\"\"Releases ownership of the given exploration to the", "cloned_from=( activity_rights_model.cloned_from if activity_type == constants.ACTIVITY_TYPE_EXPLORATION else None), status=activity_rights_model.status, viewable_if_private=activity_rights_model.viewable_if_private,", "The rights object for the given activity. activity_type: str. The", "constants.ACTIVITY_TYPE_EXPLORATION) def get_multiple_exploration_rights_by_ids(exp_ids): \"\"\"Returns a list of ActivityRights objects for", "the user can delete given activity. Args: user: UserActionsInfo. Object", "rights model. Args: activity_rights_model: ActivityRightsModel. Activity rights from the datastore.", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "a list of ActivityRights objects for given exploration ids. Args:", "Authors. All Rights Reserved. # # Licensed under the Apache", "Args: collection_id: str. ID of the collection. Returns: bool. Whether", "License. \"\"\"Domain objects and functions that manage rights for various", "model_cls = collection_models.CollectionRightsModel model = model_cls.get(activity_rights.id, strict=False) model.owner_ids = activity_rights.owner_ids", "exception from _assign_role. \"\"\" _assign_role( committer, assignee_id, new_role, exploration_id, constants.ACTIVITY_TYPE_EXPLORATION)", "assignee_id, new_role, activity_id)) raise Exception( 'UnauthorizedUserException: Could not assign new", "committer. activity_rights: ActivityRights. The rights object for the given activity.", "commit_cmds = [{ 'cmd': CMD_CHANGE_PRIVATE_VIEWABILITY, 'old_viewable_if_private': old_viewable_if_private, 'new_viewable_if_private': viewable_if_private, }]", "# backward-compatibility with previous exploration snapshots in the datastore. #", "return False if activity_rights.community_owned: return False if activity_rights.is_published(): if role_services.ACTION_UNPUBLISH_ANY_PUBLIC_ACTIVITY", "for the commit. commit_cmds: list(dict). A list of commands describing", "exploration_rights = get_exploration_rights(exploration_id) # The user who can publish activity", "object containing ActivityRights object for existing exploration or None. \"\"\"", "exploration_id): \"\"\"Unpublishes the given exploration. Args: committer: UserActionsInfo. UserActionsInfo object", "activity (an exploration or a collection). \"\"\" def __init__( self,", "ActivityRightsModel. Activity rights from the datastore. activity_type: str. The type", "return collection_rights.status == ACTIVITY_STATUS_PUBLIC def _get_activity_rights(activity_type, activity_id): \"\"\"Retrieves the rights", "status of this exploration to %s, ' 'but that is", "\"\"\"Retrieves the rights object for the given activity based on", "activity_type, ACTIVITY_STATUS_PRIVATE, '%s unpublished.' % activity_type) activity_services.remove_featured_activity(activity_type, activity_id) # Rights", "collection to the community. Args: committer: UserActionsInfo. UserActionsInfo object for", "self.community_owned: if (self.owner_ids or self.editor_ids or self.translator_ids or self.viewer_ids): raise", "role_services.ACTION_EDIT_OWNED_ACTIVITY not in user.actions: return False if (activity_rights.is_owner(user.user_id) or activity_rights.is_editor(user.user_id)):", "old_role = ROLE_TRANSLATOR elif new_role == ROLE_EDITOR: if (activity_rights.is_editor(assignee_id) or", "editor_ids=collection_rights.editor_ids, translator_ids=collection_rights.translator_ids, viewer_ids=collection_rights.viewer_ids, community_owned=collection_rights.community_owned, status=collection_rights.status, viewable_if_private=collection_rights.viewable_if_private, first_published_msec=collection_rights.first_published_msec ).commit(committer_id, 'Created new", "who is performing the action. assignee_id: str. ID of the", "ID of rights object is the same as the ID", "Apache License, Version 2.0 (the \"License\"); # you may not", "activity_rights.translator_ids.append(assignee_id) if assignee_id in activity_rights.viewer_ids: activity_rights.viewer_ids.remove(assignee_id) old_role = ROLE_VIEWER elif", "self.cloned_from, 'status': self.status, 'community_owned': True, 'owner_names': [], 'editor_names': [], 'translator_names':", "either express or implied. # See the License for the", "associated with the given activity. Raises: Exception. activity_type provided is", "def get_collection_owner_names(collection_id): \"\"\"Retrieves the owners for this collection from the", "being changed. new_role: str. The name of the new role:", "'viewer_names': user_services.get_human_readable_user_ids( self.viewer_ids), 'viewable_if_private': self.viewable_if_private, } def is_owner(self, user_id): \"\"\"Checks", "if activity_type == constants.ACTIVITY_TYPE_EXPLORATION: cmd_type = CMD_CHANGE_EXPLORATION_STATUS elif activity_type ==", "the first_published_msec field for the given activity. The caller is", "'User %s tried to change private viewability of exploration %s", "exploration is valid prior to publication. Args: committer: UserActionsInfo. UserActionsInfo", "but was refused ' 'permission.' % (committer_id, activity_type, activity_id)) raise", "_save_activity_rights( feconf.SYSTEM_COMMITTER_ID, activity_rights, activity_type, 'set first published time in msec',", "_release_ownership_of_activity. \"\"\" _release_ownership_of_activity( committer, collection_id, constants.ACTIVITY_TYPE_COLLECTION) def publish_collection(committer, collection_id): \"\"\"Publishes", "summary for the given activity associated with the given rights", "activity_rights): \"\"\"Checks whether the user can translate given activity. Args:", "activity_rights.community_owned = True activity_rights.owner_ids = [] activity_rights.editor_ids = [] activity_rights.viewer_ids", "change action. Exception. If the viewable_if_private property is already as", "activity_rights.is_editor(user.user_id) or activity_rights.is_translator(user.user_id) or activity_rights.viewable_if_private) def check_can_edit_activity(user, activity_rights): \"\"\"Checks whether", "= [] for model in exp_rights_models: if model is None:", "the given user. \"\"\" if activity_rights is None: return False", "ROLE_EDITOR, ROLE_TRANSLATOR]: subscription_services.subscribe_to_exploration( assignee_id, exploration_id) def release_ownership_of_exploration(committer, exploration_id): \"\"\"Releases ownership", "self.editor_ids or self.translator_ids or self.viewer_ids): raise utils.ValidationError( 'Community-owned explorations should", "an activity viewer. \"\"\" return bool(user_id in self.viewer_ids) def is_published(self):", "= collection_models.CollectionRightsModel.get( collection_id, strict=strict) if model is None: return None", "activity_rights.editor_ids = [] activity_rights.viewer_ids = [] commit_cmds = [{ 'cmd':", "Returns: bool. Whether the user can release ownership for given", "viewer. \"\"\" return bool(user_id in self.viewer_ids) def is_published(self): \"\"\"Checks whether", "commit_message, commit_cmds) def _update_exploration_summary(activity_rights): \"\"\"Updates the exploration summary for the", "owner_ids self.editor_ids = editor_ids self.translator_ids = translator_ids self.viewer_ids = viewer_ids", "given activity. Raises: Exception. activity_type provided is unknown. \"\"\" if", "collection_id: str. ID of the collection. assignee_id: str. ID of", "ActivityRights(object): \"\"\"Domain object for the rights/publication status of an activity", "of the new role: One of ROLE_OWNER ROLE_EDITOR Raises: Exception.", "activity_rights = _get_activity_rights(activity_type, activity_id) if not check_can_unpublish_activity(committer, activity_rights): logging.error( 'User", "to the new collection. Args: collection_id: str. ID of the", "% activity_type) _change_activity_status( committer_id, activity_id, activity_type, ACTIVITY_STATUS_PUBLIC, '%s published.' %", "= set(self.owner_ids).intersection( set(self.translator_ids)) owner_viewer = set(self.owner_ids).intersection(set(self.viewer_ids)) editor_translator = set(self.editor_ids).intersection( set(self.translator_ids))", "(by anyone with the link). Raises: Exception. The committer does", "commit_message, commit_cmds) _update_exploration_summary(exploration_rights) def publish_exploration(committer, exploration_id): \"\"\"Publishes the given exploration.", "collection_id): \"\"\"Releases ownership of the given collection to the community.", "activity_rights.id, None) def _update_collection_summary(activity_rights): \"\"\"Updates the collection summary for the", "user. activity_rights: AcitivityRights or None. Rights object for the given", "whether the user can access given activity. Args: user: UserActionsInfo.", "the given user can edit this activity. \"\"\" if activity_rights", "False if activity_rights.is_published(): return False if role_services.ACTION_PUBLISH_ANY_ACTIVITY in user.actions: return", "% activity_type, commit_cmds) _update_activity_summary(activity_type, activity_rights) def _change_activity_status( committer_id, activity_id, activity_type,", "ID of the exploration. assignee_id: str. ID of the user", "refused permission.' % (committer_id, exploration_id)) raise Exception( 'The viewability status", "exploration. Args: exploration_id: str. ID of the exploration. committer_id: str.", "with ID collection_id is not found in the datastore. \"\"\"", "should ensure that assignee_id corresponds to a valid user in", "committer does not have the permission to perform change action.", "activity. \"\"\" if activity_rights is None: return False if role_services.ACTION_EDIT_OWNED_ACTIVITY", "None. \"\"\" exp_rights_models = exp_models.ExplorationRightsModel.get_multi( exp_ids) exp_models_list = [] for", "The type of activity. Possible values: constants.ACTIVITY_TYPE_EXPLORATION constants.ACTIVITY_TYPE_COLLECTION Raise: Exception.", "explorations cannot be private.') if self.status != ACTIVITY_STATUS_PRIVATE and self.viewer_ids:", "activity_type, activity_id)) raise Exception( 'The ownership of this %s cannot", "\"\"\" committer_id = committer.user_id exploration_rights = get_exploration_rights(exploration_id) # The user", "committer does not have release rights. \"\"\" committer_id = committer.user_id", "\"\"\"Updates the collection summary for the given activity associated with", "Rights functions for collections. def assign_role_for_collection( committer, collection_id, assignee_id, new_role):", "given user. \"\"\" if activity_rights is None: return False elif", "def is_published(self): \"\"\"Checks whether activity is published. Returns: bool. Whether", "to change viewability status of this exploration to %s, '", "activity_type == constants.ACTIVITY_TYPE_EXPLORATION: return get_exploration_rights(activity_id, strict=False) elif activity_type == constants.ACTIVITY_TYPE_COLLECTION:", "exploration matching the given ID. Returns: ActivityRights. The rights object", "activity_id: str. ID of the activity. first_published_msec: float. First publication", "and a viewer: %s' % owner_viewer) if editor_translator: raise utils.ValidationError(", "activity_rights is None: return False if role_services.ACTION_EDIT_OWNED_ACTIVITY not in user.actions:", "'cmd': CMD_RELEASE_OWNERSHIP, }] _save_activity_rights( committer_id, activity_rights, activity_type, '%s ownership released", "'permission.' % (committer_id, activity_type, activity_id)) raise Exception('This %s cannot be", "bool(user_id in self.viewer_ids) def is_published(self): \"\"\"Checks whether activity is published.", "activity_rights.owner_ids = [] activity_rights.editor_ids = [] activity_rights.viewer_ids = [] commit_cmds", "True, this allows a private exploration to be viewed by", "viewer: %s' % owner_viewer) if editor_translator: raise utils.ValidationError( 'A user", "Returns: bool. Whether the user can publish given activity. \"\"\"", "rid of inline imports by refactoring code. from core.domain import", "return False def check_can_translate_activity(user, activity_rights): \"\"\"Checks whether the user can", "str. ID of the collection. committer_id: str. ID of the", "% activity_type) activity_rights.editor_ids.append(assignee_id) if assignee_id in activity_rights.translator_ids: activity_rights.translator_ids.remove(assignee_id) old_role =", "roles for given activity. \"\"\" if activity_rights is None: return", "the given user can translate this activity. \"\"\" if activity_rights", "for given user. activity_rights: ActivityRights or None. Rights object for", "( 'Made exploration viewable to anyone with the link.' if", "collection). \"\"\" def __init__( self, exploration_id, owner_ids, editor_ids, translator_ids, viewer_ids,", "' 'but that is already the current value.' % viewable_if_private)", "activity_rights.viewer_ids = [] commit_cmds = [{ 'cmd': CMD_RELEASE_OWNERSHIP, }] _save_activity_rights(", "The rights object for the collection. Raises: EntityNotFoundError. The collection", "get_exploration_rights(activity_id, strict=False) elif activity_type == constants.ACTIVITY_TYPE_COLLECTION: return get_collection_rights(activity_id, strict=False) else:", "activity_rights.is_translator(user.user_id)): return True if (activity_rights.community_owned or (role_services.ACTION_EDIT_ANY_ACTIVITY in user.actions)): return", "editor_translator) if editor_viewer: raise utils.ValidationError( 'A user cannot be both", "CMD_CREATE_NEW}] collection_models.CollectionRightsModel( id=collection_rights.id, owner_ids=collection_rights.owner_ids, editor_ids=collection_rights.editor_ids, translator_ids=collection_rights.translator_ids, viewer_ids=collection_rights.viewer_ids, community_owned=collection_rights.community_owned, status=collection_rights.status, viewable_if_private=collection_rights.viewable_if_private,", "(activity_rights.is_owner(user.user_id) or activity_rights.is_editor(user.user_id)): return True if (activity_rights.community_owned or (role_services.ACTION_EDIT_ANY_ACTIVITY in", "Args: collection_id: str. ID of the collection. committer_id: str. ID", "= get_collection_rights(collection_id) return user_services.get_human_readable_user_ids( collection_rights.owner_ids) def is_collection_private(collection_id): \"\"\"Returns whether the", "can publish given activity. \"\"\" if activity_rights is None: return", "activity_type)) def check_can_access_activity(user, activity_rights): \"\"\"Checks whether the user can access", "another exploration. Args: exploration_id: str. ID of the exploration. Returns:", "activity. Returns: bool. Whether the user can unpublish given activity.", "activity %s ' 'but was refused permission.' % ( committer_id,", "collection is private. \"\"\" collection_rights = get_collection_rights(collection_id) return collection_rights.status ==", "anyone.' % activity_type) activity_rights.viewer_ids.append(assignee_id) else: raise Exception('Invalid role: %s' %", "of an activity (an exploration or a collection). \"\"\" def", "return False if role_services.ACTION_PUBLISH_ANY_ACTIVITY in user.actions: return True if role_services.ACTION_PUBLISH_OWNED_ACTIVITY", "'change_role' CMD_CHANGE_EXPLORATION_STATUS = 'change_exploration_status' CMD_CHANGE_COLLECTION_STATUS = 'change_collection_status' CMD_CHANGE_PRIVATE_VIEWABILITY = 'change_private_viewability'", "def is_owner(self, user_id): \"\"\"Checks whether given user is owner of", "the collection. strict: bool. Whether to raise an error if", "check_can_release_ownership(committer, activity_rights): logging.error( 'User %s tried to release ownership of", "\"\"\"Assigns a user to the given role and subscribes the", "= [{ 'cmd': CMD_CHANGE_PRIVATE_VIEWABILITY, 'old_viewable_if_private': old_viewable_if_private, 'new_viewable_if_private': viewable_if_private, }] commit_message", "given user. activity_rights: AcitivityRights or None. Rights object for the", "= activity_rights.status model.viewable_if_private = activity_rights.viewable_if_private model.first_published_msec = activity_rights.first_published_msec model.commit(committer_id, commit_message,", "Args: committer: UserActionsInfo. The UserActionsInfo object for the committer. exploration_id:", "raise utils.ValidationError( 'Community-owned explorations cannot be private.') if self.status !=", "' 'editors, translators or viewers specified.') if self.community_owned and self.status", "for use by the frontend. Returns: dict. A dict version", "whether the user can edit given activity. Args: user: UserActionsInfo.", "def create_new_exploration_rights(exploration_id, committer_id): \"\"\"Creates a new exploration rights object and", "of the activity. activity_type: str. The type of activity. Possible", "} else: return { 'cloned_from': self.cloned_from, 'status': self.status, 'community_owned': False,", "\"\"\" return bool(user_id in self.editor_ids) def is_translator(self, user_id): \"\"\"Checks whether", "model.community_owned = activity_rights.community_owned model.status = activity_rights.status model.viewable_if_private = activity_rights.viewable_if_private model.first_published_msec", "None: return False if activity_rights.cloned_from: return False if activity_rights.is_published(): return", "if viewable_if_private else 'Made exploration viewable only to invited playtesters.')", "get_collection_rights(collection_id) return collection_rights.status == ACTIVITY_STATUS_PRIVATE def is_collection_public(collection_id): \"\"\"Returns whether the", "old_role = ROLE_NONE if new_role == ROLE_OWNER: if activity_rights.is_owner(assignee_id): raise", "not found in the datastore. \"\"\" model = collection_models.CollectionRightsModel.get( collection_id,", "given user is translator of activity. Args: user_id: str or", "UserActionsInfo. UserActionsInfo object for the committer. collection_id: str. ID of", "exploration_id, constants.ACTIVITY_TYPE_EXPLORATION) if new_role in [ROLE_OWNER, ROLE_EDITOR, ROLE_TRANSLATOR]: subscription_services.subscribe_to_exploration( assignee_id,", "does not have rights to publish the activity. \"\"\" committer_id", "does not have the permission to perform change action. Exception.", "not have rights to unpublish the activity. \"\"\" committer_id =", "= True activity_rights.owner_ids = [] activity_rights.editor_ids = [] activity_rights.viewer_ids =", "translator_ids, viewer_ids, community_owned=False, cloned_from=None, status=ACTIVITY_STATUS_PRIVATE, viewable_if_private=False, first_published_msec=None): self.id = exploration_id", "can modify roles for given activity. Args: user: UserActionsInfo. Object", "Args: committer: UserActionsInfo. UserActionsInfo object for the committer. collection_id: str.", "self.owner_ids), 'editor_names': user_services.get_human_readable_user_ids( self.editor_ids), 'translator_names': user_services.get_human_readable_user_ids( self.translator_ids), 'viewer_names': user_services.get_human_readable_user_ids( self.viewer_ids),", "\"AS-IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "user can already translate the activity. Exception. The activity is", "could potentially throw an exception from _publish_activity. \"\"\" _publish_activity( committer,", "CMD_CHANGE_COLLECTION_STATUS = 'change_collection_status' CMD_CHANGE_PRIVATE_VIEWABILITY = 'change_private_viewability' CMD_RELEASE_OWNERSHIP = 'release_ownership' CMD_UPDATE_FIRST_PUBLISHED_MSEC", "return True elif (activity_rights.is_published() and (role_services.ACTION_DELETE_ANY_PUBLIC_ACTIVITY in user.actions)): return True", "roles for given activity. Args: user: UserActionsInfo. Object having user_id,", "an activity (an exploration or a collection). \"\"\" def __init__(", "elif activity_type == constants.ACTIVITY_TYPE_COLLECTION: return get_collection_rights(activity_id, strict=False) else: raise Exception(", "Exception( 'Community-owned %ss can be translated by anyone.' % activity_type)", "' 'but was refused permission.' % (committer_id, exploration_id)) raise Exception(", "constants.ACTIVITY_TYPE_COLLECTION) if new_role in [ROLE_OWNER, ROLE_EDITOR]: subscription_services.subscribe_to_collection( assignee_id, collection_id) def", "= _get_activity_rights(activity_type, activity_id) commit_cmds = [{ 'cmd': CMD_UPDATE_FIRST_PUBLISHED_MSEC, 'old_first_published_msec': activity_rights.first_published_msec,", "in user.actions: if activity_rights.is_owner(user.user_id): return True return False def check_can_unpublish_activity(user,", "self.editor_ids), 'translator_names': user_services.get_human_readable_user_ids( self.translator_ids), 'viewer_names': user_services.get_human_readable_user_ids( self.viewer_ids), 'viewable_if_private': self.viewable_if_private, }", "= 'update_first_published_msec' ACTIVITY_STATUS_PRIVATE = constants.ACTIVITY_STATUS_PRIVATE ACTIVITY_STATUS_PUBLIC = constants.ACTIVITY_STATUS_PUBLIC ROLE_OWNER =", "as the ID of associated activity. Args: activity_rights: ActivityRights. The", "\"\"\"Assigns a new role to the user. Args: committer: UserActionsInfo.", "or (role_services.ACTION_EDIT_ANY_ACTIVITY in user.actions)): return True if (activity_rights.is_published() and (role_services.ACTION_EDIT_ANY_PUBLIC_ACTIVITY", "rights object for the given activity. activity_type: str. The type", "view this %s.' % activity_type) if activity_rights.status != ACTIVITY_STATUS_PRIVATE: raise", "corresponds to a valid user in the system. Args: committer:", "activity. Args: activity_rights: ActivityRights. The rights object for the given", "a new collection rights object and saves it to the", "activity_rights is None: return False if activity_rights.cloned_from: return False if", "no owners, ' 'editors, translators or viewers specified.') if self.community_owned", "interpreted preserve # backward-compatibility with previous exploration snapshots in the", "= _get_activity_rights(activity_type, activity_id) if not check_can_unpublish_activity(committer, activity_rights): logging.error( 'User %s", "is owner of activity. Args: user_id: str or None. Id", "self.translator_ids), 'viewer_names': user_services.get_human_readable_user_ids( self.viewer_ids), 'viewable_if_private': self.viewable_if_private, } def is_owner(self, user_id):", "the given activity can be accessed by the given user.", "exploration_id): \"\"\"Releases ownership of the given exploration to the community.", "community_owned self.cloned_from = cloned_from self.status = status self.viewable_if_private = viewable_if_private", "ActivityRights. The rights object for the collection. Raises: EntityNotFoundError. The", "owner_ids, editor_ids, translator_ids, viewer_ids, community_owned=False, cloned_from=None, status=ACTIVITY_STATUS_PRIVATE, viewable_if_private=False, first_published_msec=None): self.id", "of associated activity. Args: activity_type: str. The type of activity.", "use this file except in compliance with the License. #", "unpublish %s %s but was refused ' 'permission.' % (committer_id,", "rights object and saves it to the datastore. Subscribes the", "new_role) commit_message = 'Changed role of %s from %s to", "committer_id, assignee_id, new_role, activity_id)) raise Exception( 'UnauthorizedUserException: Could not assign", "_update_activity_summary(activity_type, activity_rights) def _publish_activity(committer, activity_id, activity_type): \"\"\"Publishes the given activity.", "for given exploration ids. Args: exp_ids: list(str). List of exploration", "new_status: str. The new status of the activity. commit_message: str.", "% editor_viewer) if translator_viewer: raise utils.ValidationError( 'A user cannot be", "viewable_if_private attribute for the given exploration's rights object. If viewable_if_private", "already can view this %s.' % activity_type) if activity_rights.status !=", "rights object is the same as the ID of associated", "\"\"\"Checks whether activity is published. Returns: bool. Whether activity is", "or None). List of rights object containing ActivityRights object for", "is a clone of another exploration. Args: exploration_id: str. ID", "logging.error( 'User %s tried to unpublish %s %s but was", "the user. Returns: bool. Whether user is an activity owner.", "user.actions: return True return False def _assign_role( committer, assignee_id, new_role,", "user can delete given activity. Args: user: UserActionsInfo. Object having", "bool(self.status == ACTIVITY_STATUS_PUBLIC) def is_private(self): \"\"\"Checks whether activity is private.", "raise Exception( 'Trying to change viewability status of this exploration", "of the committer. \"\"\" collection_rights = ActivityRights( collection_id, [committer_id], [],", "AcitivityRights or None. Rights object for the given activity. Returns:", "'%s ownership released to the community.' % activity_type, commit_cmds) _update_activity_summary(activity_type,", "committer, exploration_id, assignee_id, new_role): \"\"\"Assigns a user to the given", "user. Args: committer: UserActionsInfo. UserActionInfo object for the user who", "name of the new role: One of ROLE_OWNER ROLE_EDITOR ROLE_TRANSLATOR", "have the permission to perform change action. Exception. If the", "the committer to the new exploration. Args: exploration_id: str. ID", "ActivityRights. The rights object associated with the given activity. Raises:", "ID of the activity. first_published_msec: float. First publication time in", "'Trying to change viewability status of this exploration to %s,", "ID of the exploration. committer_id: str. ID of the committer.", "the datastore. Args: exploration_id: str. ID of the exploration. strict:", "[] if activity_rights.first_published_msec is None: activity_rights.first_published_msec = ( utils.get_current_time_in_millisecs()) _save_activity_rights(", "activity_type) if activity_rights.status != ACTIVITY_STATUS_PRIVATE: raise Exception( 'Public %ss can", "if activity_rights.is_published(): if role_services.ACTION_UNPUBLISH_ANY_PUBLIC_ACTIVITY in user.actions: return True return False", "self.status == ACTIVITY_STATUS_PRIVATE: raise utils.ValidationError( 'Community-owned explorations cannot be private.')", "type of activity. Possible values: constants.ACTIVITY_TYPE_EXPLORATION constants.ACTIVITY_TYPE_COLLECTION new_status: str. The", "Exception. This could potentially throw an exception from _assign_role. \"\"\"", "that is already the current value.' % viewable_if_private) exploration_rights.viewable_if_private =", "is an activity owner. \"\"\" return bool(user_id in self.owner_ids) def", "\"\"\" if self.community_owned: return { 'cloned_from': self.cloned_from, 'status': self.status, 'community_owned':", "Exception. The activity is already publicly translatable. Exception. The user", "the responsibility of the caller to check that the exploration", "% (committer_id, activity_type, activity_id)) raise Exception('This %s cannot be published.'", "core.domain import user_services from core.platform import models import feconf import", "[committer_id], [], [], []) commit_cmds = [{'cmd': CMD_CREATE_NEW}] exp_models.ExplorationRightsModel( id=exploration_rights.id,", "model = collection_models.CollectionRightsModel.get( collection_id, strict=strict) if model is None: return", "user_id): \"\"\"Checks whether given user is viewer of activity. Args:", "CMD_CREATE_NEW}] exp_models.ExplorationRightsModel( id=exploration_rights.id, owner_ids=exploration_rights.owner_ids, editor_ids=exploration_rights.editor_ids, translator_ids=exploration_rights.translator_ids, viewer_ids=exploration_rights.viewer_ids, community_owned=exploration_rights.community_owned, status=exploration_rights.status, viewable_if_private=exploration_rights.viewable_if_private,", "viewable_if_private) exploration_rights.viewable_if_private = viewable_if_private commit_cmds = [{ 'cmd': CMD_CHANGE_PRIVATE_VIEWABILITY, 'old_viewable_if_private':", "the given activity based on its type. Args: activity_type: str.", "subscribes the assignee to future collection updates. The caller should", "% activity_type) activity_rights.translator_ids.append(assignee_id) if assignee_id in activity_rights.viewer_ids: activity_rights.viewer_ids.remove(assignee_id) old_role =", "publication. Args: committer: UserActionsInfo. UserActionsInfo object for the committer. collection_id:", "is public. Args: exploration_id: str. ID of the exploration. Returns:", "frontend. Returns: dict. A dict version of ActivityRights suitable for", "if (role_services.ACTION_MODIFY_ROLES_FOR_ANY_ACTIVITY in user.actions): return True if (role_services.ACTION_MODIFY_ROLES_FOR_OWNED_ACTIVITY in user.actions):", "new_role in [ROLE_OWNER, ROLE_EDITOR, ROLE_TRANSLATOR]: subscription_services.subscribe_to_exploration( assignee_id, exploration_id) def release_ownership_of_exploration(committer,", "Possible values: constants.ACTIVITY_TYPE_EXPLORATION constants.ACTIVITY_TYPE_COLLECTION commit_message: str. Descriptive message for the", "activity_rights.community_owned: return False if activity_rights.is_published(): if role_services.ACTION_UNPUBLISH_ANY_PUBLIC_ACTIVITY in user.actions: return", ").commit(committer_id, 'Created new exploration', commit_cmds) subscription_services.subscribe_to_exploration( committer_id, exploration_id) def get_exploration_rights(exploration_id,", "activity. Exception. The user can already edit the activity. Exception.", "If viewable_if_private is True, this allows a private exploration to", "CMD_CHANGE_PRIVATE_VIEWABILITY = 'change_private_viewability' CMD_RELEASE_OWNERSHIP = 'release_ownership' CMD_UPDATE_FIRST_PUBLISHED_MSEC = 'update_first_published_msec' ACTIVITY_STATUS_PRIVATE", "exp_models_list.append( get_activity_rights_from_model( model, constants.ACTIVITY_TYPE_EXPLORATION)) return exp_models_list def is_exploration_private(exploration_id): \"\"\"Returns whether", "permissions and # limitations under the License. \"\"\"Domain objects and", "exploration. assignee_id: str. ID of the user whose role is", "in compliance with the License. # You may obtain a", "with previous exploration snapshots in the datastore. # Do not", "== constants.ACTIVITY_TYPE_EXPLORATION: model_cls = exp_models.ExplorationRightsModel elif activity_type == constants.ACTIVITY_TYPE_COLLECTION: model_cls", "software # distributed under the License is distributed on an", "by the frontend. \"\"\" if self.community_owned: return { 'cloned_from': self.cloned_from,", "commit was done. \"\"\" activity_rights.validate() if activity_type == constants.ACTIVITY_TYPE_EXPLORATION: model_cls", "import subscription_services from core.domain import user_services from core.platform import models", "activity_rights.editor_ids.append(assignee_id) if assignee_id in activity_rights.translator_ids: activity_rights.translator_ids.remove(assignee_id) old_role = ROLE_TRANSLATOR if", "translator: %s' % editor_translator) if editor_viewer: raise utils.ValidationError( 'A user", "( activity_type)) def check_can_access_activity(user, activity_rights): \"\"\"Checks whether the user can", "bool(user_id in self.owner_ids) def is_editor(self, user_id): \"\"\"Checks whether given user", "bool. Whether the user can delete given activity. \"\"\" if", "str. ID of the user whose role is being changed.", "committer, exploration_id, constants.ACTIVITY_TYPE_EXPLORATION) # Rights functions for collections. def assign_role_for_collection(", "def check_can_modify_activity_roles(user, activity_rights): \"\"\"Checks whether the user can modify roles", "[], []) commit_cmds = [{'cmd': CMD_CREATE_NEW}] collection_models.CollectionRightsModel( id=collection_rights.id, owner_ids=collection_rights.owner_ids, editor_ids=collection_rights.editor_ids,", "in the datastore. # Do not modify the definitions of", "the activity. Exception. The activity is already publicly viewable. Exception.", "distributed on an \"AS-IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "committer, assignee_id, new_role, activity_id, activity_type): \"\"\"Assigns a new role to", "ROLE_ADMIN = 'admin' ROLE_MODERATOR = 'moderator' class ActivityRights(object): \"\"\"Domain object", "if (role_services.ACTION_MODIFY_ROLES_FOR_OWNED_ACTIVITY in user.actions): if activity_rights.is_owner(user.user_id): return True return False", "new_role) commit_cmds = [{ 'cmd': CMD_CHANGE_ROLE, 'assignee_id': assignee_id, 'old_role': old_role,", "whether the exploration is a clone of another exploration. Args:", "a viewer: %s' % owner_viewer) if editor_translator: raise utils.ValidationError( 'A", "ID of the user who is performing the update action.", "is None: return None return get_activity_rights_from_model( model, constants.ACTIVITY_TYPE_EXPLORATION) def get_multiple_exploration_rights_by_ids(exp_ids):", "exp_models.ExplorationRightsModel.get( exploration_id, strict=strict) if model is None: return None return", "collection_id, strict=strict) if model is None: return None return get_activity_rights_from_model(", "exploration_id: str. ID of the exploration. Raises: Exception. This could", "_publish_activity. \"\"\" _publish_activity( committer, collection_id, constants.ACTIVITY_TYPE_COLLECTION) def unpublish_collection(committer, collection_id): \"\"\"Unpublishes", "collection_id: str. ID of the collection. committer_id: str. ID of", "in activity_rights.editor_ids: activity_rights.editor_ids.remove(assignee_id) old_role = ROLE_EDITOR if assignee_id in activity_rights.translator_ids:", "given activity. Returns: bool. Whether the given activity can be", "both an owner and a translator: %s' % owner_translator) if", "change. \"\"\" activity_rights = _get_activity_rights(activity_type, activity_id) old_status = activity_rights.status activity_rights.status", "core.domain import exp_services exp_services.update_exploration_summary( activity_rights.id, None) def _update_collection_summary(activity_rights): \"\"\"Updates the", "strict=strict) if model is None: return None return get_activity_rights_from_model( model,", "of the exploration. Returns: bool. Whether the exploration is private", "type of activity. Possible values: constants.ACTIVITY_TYPE_EXPLORATION constants.ACTIVITY_TYPE_COLLECTION activity_id: str. ID", "responsible for ensuring that this value is not already set", "if (activity_rights.is_editor(assignee_id) or activity_rights.is_owner(assignee_id)): raise Exception( 'This user already can", "an exception from _unpublish_activity. \"\"\" _unpublish_activity( committer, exploration_id, constants.ACTIVITY_TYPE_EXPLORATION) #", "exploration rights object and saves it to the datastore. Subscribes", "import constants from core.domain import activity_services from core.domain import role_services", "rights object for the given activity. \"\"\" # TODO(msl): get", "or None. \"\"\" exp_rights_models = exp_models.ExplorationRightsModel.get_multi( exp_ids) exp_models_list = []", "to how these cmds are interpreted preserve # backward-compatibility with", "public. \"\"\" collection_rights = get_collection_rights(collection_id) return collection_rights.status == ACTIVITY_STATUS_PUBLIC def", "== ACTIVITY_STATUS_PRIVATE def is_collection_public(collection_id): \"\"\"Returns whether the collection is public.", "from the given activity rights model. Args: activity_rights_model: ActivityRightsModel. Activity", "the committer. exploration_id: str. ID of the exploration. Raises: Exception.", "activity. Possible values: constants.ACTIVITY_TYPE_EXPLORATION constants.ACTIVITY_TYPE_COLLECTION Raise: Exception. The committer does", "constants.ACTIVITY_TYPE_COLLECTION activity_id: str. ID of the activity. Returns: ActivityRights. The", "(or truncated email addresses) of owners for this collection. \"\"\"", "_change_activity_status( committer_id, activity_id, activity_type, new_status, commit_message): \"\"\"Changes the status of", "(activity_rights.is_owner(user.user_id) or activity_rights.is_editor(user.user_id) or activity_rights.is_translator(user.user_id)): return True if (activity_rights.community_owned or", "playtesters.') _save_activity_rights( committer_id, exploration_rights, constants.ACTIVITY_TYPE_EXPLORATION, commit_message, commit_cmds) _update_exploration_summary(exploration_rights) def publish_exploration(committer,", "UserActionsInfo. Object having user_id, role and actions for given user.", "activity. Args: user_id: str or None. Id of the user.", "Args: committer: UserActionsInfo. UserActionsInfo object for the committer. exploration_id: str.", "ownership of the given collection to the community. Args: committer:", "None: return False if (activity_rights.community_owned or activity_rights.cloned_from): return False if", "for the given activity. Returns: bool. Whether the given activity", "by anyone.' % activity_type) activity_rights.translator_ids.append(assignee_id) if assignee_id in activity_rights.viewer_ids: activity_rights.viewer_ids.remove(assignee_id)", "was done. \"\"\" activity_rights.validate() if activity_type == constants.ACTIVITY_TYPE_EXPLORATION: model_cls =", "collection_models.CollectionRightsModel( id=collection_rights.id, owner_ids=collection_rights.owner_ids, editor_ids=collection_rights.editor_ids, translator_ids=collection_rights.translator_ids, viewer_ids=collection_rights.viewer_ids, community_owned=collection_rights.community_owned, status=collection_rights.status, viewable_if_private=collection_rights.viewable_if_private, first_published_msec=collection_rights.first_published_msec", "= status self.viewable_if_private = viewable_if_private self.first_published_msec = first_published_msec def validate(self):", "\"\"\" activity_rights.validate() if activity_type == constants.ACTIVITY_TYPE_EXPLORATION: model_cls = exp_models.ExplorationRightsModel elif", "to the datastore. Subscribes the committer to the new exploration.", "owns the activity. Exception. The user can already edit the", "by the given user. \"\"\" if activity_rights is None: return", "the system. Args: committer: UserActionsInfo. The UserActionsInfo object for the", "collection. assignee_id: str. ID of the user whose role is", "owner_viewer) if editor_translator: raise utils.ValidationError( 'A user cannot be both", "committer_id, exploration_id) def get_exploration_rights(exploration_id, strict=True): \"\"\"Retrieves the rights for this", "== ACTIVITY_STATUS_PUBLIC def _get_activity_rights(activity_type, activity_id): \"\"\"Retrieves the rights object for", "this activity. \"\"\" if activity_rights is None: return False if", "the activity. \"\"\" committer_id = committer.user_id activity_rights = _get_activity_rights(activity_type, activity_id)", "view the activity. Exception. The activity is already publicly viewable.", "(role_services.ACTION_EDIT_ANY_ACTIVITY in user.actions)): return True if (activity_rights.is_published() and (role_services.ACTION_EDIT_ANY_PUBLIC_ACTIVITY in", "activity_rights = _get_activity_rights(activity_type, activity_id) if not check_can_publish_activity(committer, activity_rights): logging.error( 'User", "link.' if viewable_if_private else 'Made exploration viewable only to invited", "elif activity_type == constants.ACTIVITY_TYPE_COLLECTION: _update_collection_summary(activity_rights) def update_activity_first_published_msec( activity_type, activity_id, first_published_msec):", "collection_id, [committer_id], [], [], []) commit_cmds = [{'cmd': CMD_CREATE_NEW}] collection_models.CollectionRightsModel(", "str. ID of the committer. \"\"\" collection_rights = ActivityRights( collection_id,", "def unpublish_collection(committer, collection_id): \"\"\"Unpublishes the given collection. Args: committer: UserActionsInfo.", "is_collection_public(collection_id): \"\"\"Returns whether the collection is public. Args: collection_id: str.", "[committer_id], [], [], []) commit_cmds = [{'cmd': CMD_CREATE_NEW}] collection_models.CollectionRightsModel( id=collection_rights.id,", "with the License. # You may obtain a copy of", "from _assign_role. \"\"\" _assign_role( committer, assignee_id, new_role, collection_id, constants.ACTIVITY_TYPE_COLLECTION) if", "constants.ACTIVITY_TYPE_COLLECTION commit_message: str. Descriptive message for the commit. commit_cmds: list(dict).", "activities. def assign_role_for_exploration( committer, exploration_id, assignee_id, new_role): \"\"\"Assigns a user", "committer. exploration_id: str. ID of the exploration. Raises: Exception. This", "= 'change_private_viewability' CMD_RELEASE_OWNERSHIP = 'release_ownership' CMD_UPDATE_FIRST_PUBLISHED_MSEC = 'update_first_published_msec' ACTIVITY_STATUS_PRIVATE =", "and actions for given user. activity_rights: AcitivityRights or None. Rights", "check_can_publish_activity(user, activity_rights): \"\"\"Checks whether the user can publish given activity.", "cloned_from self.status = status self.viewable_if_private = viewable_if_private self.first_published_msec = first_published_msec", "already as desired. \"\"\" committer_id = committer.user_id exploration_rights = get_exploration_rights(exploration_id)", "utils current_user_services = models.Registry.import_current_user_services() (collection_models, exp_models,) = models.Registry.import_models([ models.NAMES.collection, models.NAMES.exploration", "core.platform import models import feconf import utils current_user_services = models.Registry.import_current_user_services()", "self.cloned_from, 'status': self.status, 'community_owned': False, 'owner_names': user_services.get_human_readable_user_ids( self.owner_ids), 'editor_names': user_services.get_human_readable_user_ids(", "Exception. This could potentially throw an exception from _unpublish_activity. \"\"\"", "Activity rights from the datastore. activity_type: str. The type of", "committer to the new collection. Args: collection_id: str. ID of", "or activity_rights.is_viewer(assignee_id)): raise Exception( 'This user already can view this", "self.owner_ids) def is_editor(self, user_id): \"\"\"Checks whether given user is editor", "of owners for this collection. \"\"\" collection_rights = get_collection_rights(collection_id) return", "could potentially throw an exception from _release_ownership_of_activity. \"\"\" _release_ownership_of_activity( committer,", "activity_rights, activity_type, commit_message, commit_cmds): \"\"\"Saves an ExplorationRights or CollectionRights domain", "no viewers specified.') owner_editor = set(self.owner_ids).intersection(set(self.editor_ids)) owner_translator = set(self.owner_ids).intersection( set(self.translator_ids))", "def get_exploration_rights(exploration_id, strict=True): \"\"\"Retrieves the rights for this exploration from", "collection. Args: collection_id: str. ID of the collection. committer_id: str.", "'but was refused permission.' % ( committer_id, assignee_id, new_role, activity_id))", "user_services.get_human_readable_user_ids( self.viewer_ids), 'viewable_if_private': self.viewable_if_private, } def is_owner(self, user_id): \"\"\"Checks whether", "activity_rights: AcitivityRights or None. Rights object for the given activity.", "translator_viewer) def to_dict(self): \"\"\"Returns a dict suitable for use by", "return False if (activity_rights.community_owned or activity_rights.cloned_from): return False if (role_services.ACTION_MODIFY_ROLES_FOR_ANY_ACTIVITY", "raise Exception('This user already owns this %s.' % activity_type) activity_rights.owner_ids.append(assignee_id)", "express or implied. # See the License for the specific", "'community_owned': False, 'owner_names': user_services.get_human_readable_user_ids( self.owner_ids), 'editor_names': user_services.get_human_readable_user_ids( self.editor_ids), 'translator_names': user_services.get_human_readable_user_ids(", "activity. Possible values: constants.ACTIVITY_TYPE_EXPLORATION constants.ACTIVITY_TYPE_COLLECTION activity_rights: ActivityRights. The rights object", "except in compliance with the License. # You may obtain", "\"\"\"Checks whether given user is editor of activity. Args: user_id:", "strict=False) else: raise Exception( 'Cannot get activity rights for unknown", "== ROLE_TRANSLATOR: if (activity_rights.is_editor(assignee_id) or activity_rights.is_translator(assignee_id) or activity_rights.is_owner(assignee_id)): raise Exception(", "the given activity rights model. Args: activity_rights_model: ActivityRightsModel. Activity rights", "viewer_ids self.community_owned = community_owned self.cloned_from = cloned_from self.status = status", "from %s to %s' % ( assignee_username, old_role, new_role) commit_cmds", "Copyright 2014 The Oppia Authors. All Rights Reserved. # #", "%s but was ' 'refused permission.' % (committer_id, activity_type, activity_id))", "cannot be both an editor and a translator: %s' %", "= 'editor' ROLE_TRANSLATOR = 'translator' ROLE_VIEWER = 'viewer' ROLE_NONE =", "user.actions): return True if (role_services.ACTION_MODIFY_ROLES_FOR_OWNED_ACTIVITY in user.actions): if activity_rights.is_owner(user.user_id): return", "if self.status != ACTIVITY_STATUS_PRIVATE and self.viewer_ids: raise utils.ValidationError( 'Public explorations", "# # Copyright 2014 The Oppia Authors. All Rights Reserved.", "(committer_id, activity_type, activity_id)) raise Exception( 'The ownership of this %s", "Exception. The committer does not have the permission to perform", "%s.' % activity_type) if activity_rights.status != ACTIVITY_STATUS_PRIVATE: raise Exception( 'Public", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "activity_type): \"\"\"Publishes the given activity. Args: committer: UserActionsInfo. UserActionsInfo object", "utils.ValidationError( 'A user cannot be both a translator and a", "new_role, collection_id, constants.ACTIVITY_TYPE_COLLECTION) if new_role in [ROLE_OWNER, ROLE_EDITOR]: subscription_services.subscribe_to_collection( assignee_id,", "is an activity translator. \"\"\" return bool(user_id in self.translator_ids) def", "raise utils.ValidationError( 'A user cannot be both an editor and", "self.viewable_if_private, } else: return { 'cloned_from': self.cloned_from, 'status': self.status, 'community_owned':", "throw an exception from _unpublish_activity. \"\"\" _unpublish_activity( committer, collection_id, constants.ACTIVITY_TYPE_COLLECTION)", "bool. Whether the exploration is private or not. \"\"\" exploration_rights", "private or not. \"\"\" exploration_rights = get_exploration_rights(exploration_id) return exploration_rights.status ==", "\"\"\"Checks whether the user can access given activity. Args: user:", "the user can modify roles for given activity. \"\"\" if", "exception from _release_ownership_of_activity. \"\"\" _release_ownership_of_activity( committer, collection_id, constants.ACTIVITY_TYPE_COLLECTION) def publish_collection(committer,", "def create_new_collection_rights(collection_id, committer_id): \"\"\"Creates a new collection rights object and", "False def check_can_modify_activity_roles(user, activity_rights): \"\"\"Checks whether the user can modify", "CONDITIONS OF ANY KIND, either express or implied. # See", "if not check_can_unpublish_activity(committer, activity_rights): logging.error( 'User %s tried to unpublish", "activity_rights.editor_ids: activity_rights.editor_ids.remove(assignee_id) old_role = ROLE_EDITOR if assignee_id in activity_rights.translator_ids: activity_rights.translator_ids.remove(assignee_id)", "assign_role_for_collection( committer, collection_id, assignee_id, new_role): \"\"\"Assign the given user to", "community-owned exploration has owners, editors, translators or viewers specified. \"\"\"", "to modify a role. Exception. The user already owns the", "\"\"\" _publish_activity( committer, collection_id, constants.ACTIVITY_TYPE_COLLECTION) def unpublish_collection(committer, collection_id): \"\"\"Unpublishes the", "unknown. \"\"\" if activity_type == constants.ACTIVITY_TYPE_EXPLORATION: return get_exploration_rights(activity_id, strict=False) elif", "could potentially throw an exception from _assign_role. \"\"\" _assign_role( committer,", "= [] commit_cmds = [{ 'cmd': CMD_RELEASE_OWNERSHIP, }] _save_activity_rights( committer_id,", "the given activity. Returns: bool. Whether the user can release", "bool( role_services.ACTION_PLAY_ANY_PUBLIC_ACTIVITY in user.actions) elif activity_rights.is_private(): return bool( (role_services.ACTION_PLAY_ANY_PRIVATE_ACTIVITY in", "ROLE_VIEWER: if (activity_rights.is_owner(assignee_id) or activity_rights.is_editor(assignee_id) or activity_rights.is_viewer(assignee_id)): raise Exception( 'This", "return True return False def check_can_delete_activity(user, activity_rights): \"\"\"Checks whether the", "viewable to anyone with the link.' if viewable_if_private else 'Made", "given activity. Returns: bool. Whether the user can unpublish given", "activity summary for the given activity associated with the given", "the given collection. Args: committer: UserActionsInfo. UserActionsInfo object for the", "bool. Whether to raise an error if ID is not", "viewable_if_private commit_cmds = [{ 'cmd': CMD_CHANGE_PRIVATE_VIEWABILITY, 'old_viewable_if_private': old_viewable_if_private, 'new_viewable_if_private': viewable_if_private,", "the given activity. \"\"\" if activity_type == constants.ACTIVITY_TYPE_EXPLORATION: _update_exploration_summary(activity_rights) elif", "self.viewable_if_private, } def is_owner(self, user_id): \"\"\"Checks whether given user is", "user_id): \"\"\"Checks whether given user is translator of activity. Args:", "prior to publication. Args: committer: UserActionsInfo. UserActionsInfo object for the", "the exploration. strict: bool. Whether to raise an error if", "= 'admin' ROLE_MODERATOR = 'moderator' class ActivityRights(object): \"\"\"Domain object for", "public. \"\"\" exploration_rights = get_exploration_rights(exploration_id) return exploration_rights.status == ACTIVITY_STATUS_PUBLIC def", "translator of activity. Args: user_id: str or None. Id of", "if activity_rights is None: return False if activity_rights.is_private(): return False", "}] if new_status != ACTIVITY_STATUS_PRIVATE: activity_rights.viewer_ids = [] if activity_rights.first_published_msec", "The committer does not have the permission to perform change", "modify the definitions of CMD keys that already exist. CMD_CREATE_NEW", "= committer.user_id activity_rights = _get_activity_rights(activity_type, activity_id) if not check_can_release_ownership(committer, activity_rights):", "Whether user is an activity editor. \"\"\" return bool(user_id in", "activity_rights_model.owner_ids, activity_rights_model.editor_ids, activity_rights_model.translator_ids, activity_rights_model.viewer_ids, community_owned=activity_rights_model.community_owned, cloned_from=( activity_rights_model.cloned_from if activity_type ==", "to change private viewability of exploration %s ' 'but was", "can publish activity can change its private viewability. if not", "Args: committer_id: str. ID of the user who is performing", "constants.ACTIVITY_TYPE_EXPLORATION)) return exp_models_list def is_exploration_private(exploration_id): \"\"\"Returns whether exploration is private.", "to the user. Args: committer: UserActionsInfo. UserActionInfo object for the", "and viewers lists overlap, or if a community-owned exploration has", "commit_message = 'Changed role of %s from %s to %s'", "its type. Args: activity_type: str. The type of activity. Possible", "user who is performing the action. assignee_id: str. ID of", "the link.' if viewable_if_private else 'Made exploration viewable only to", "for given user. activity_rights: AcitivityRights or None. Rights object for", "The type of activity. Possible values: constants.ACTIVITY_TYPE_EXPLORATION constants.ACTIVITY_TYPE_COLLECTION Raises: Exception.", "% activity_type) activity_rights.community_owned = True activity_rights.owner_ids = [] activity_rights.editor_ids =", "be unpublished.' % activity_type) _change_activity_status( committer_id, activity_id, activity_type, ACTIVITY_STATUS_PRIVATE, '%s", "= CMD_CHANGE_EXPLORATION_STATUS elif activity_type == constants.ACTIVITY_TYPE_COLLECTION: cmd_type = CMD_CHANGE_COLLECTION_STATUS commit_cmds", "Possible values: constants.ACTIVITY_TYPE_EXPLORATION constants.ACTIVITY_TYPE_COLLECTION Raise: Exception. The committer does not", "viewable_if_private): \"\"\"Sets the viewable_if_private attribute for the given exploration's rights", "activity_rights = _get_activity_rights(activity_type, activity_id) if not check_can_release_ownership(committer, activity_rights): logging.error( 'User", "ActivityRights suitable for use by the frontend. \"\"\" if self.community_owned:", "return get_exploration_rights(activity_id, strict=False) elif activity_type == constants.ACTIVITY_TYPE_COLLECTION: return get_collection_rights(activity_id, strict=False)", "_release_ownership_of_activity(committer, activity_id, activity_type): \"\"\"Releases ownership of the given activity to", "\"\"\"Releases ownership of the given activity to the community. Args:", "is a clone of another exploration. \"\"\" exploration_rights = get_exploration_rights(exploration_id)", "old_viewable_if_private = exploration_rights.viewable_if_private if old_viewable_if_private == viewable_if_private: raise Exception( 'Trying", "%s' % ( activity_type)) def check_can_access_activity(user, activity_rights): \"\"\"Checks whether the", "are interpreted preserve # backward-compatibility with previous exploration snapshots in", "= set(self.editor_ids).intersection( set(self.translator_ids)) editor_viewer = set(self.editor_ids).intersection(set(self.viewer_ids)) translator_viewer = set(self.editor_ids).intersection( set(self.viewer_ids))", "the collection is public. Args: collection_id: str. ID of the", "activity_rights.viewer_ids.remove(assignee_id) old_role = ROLE_VIEWER if assignee_id in activity_rights.editor_ids: activity_rights.editor_ids.remove(assignee_id) old_role", "constants.ACTIVITY_TYPE_COLLECTION: return get_collection_rights(activity_id, strict=False) else: raise Exception( 'Cannot get activity", "collection', commit_cmds) subscription_services.subscribe_to_collection(committer_id, collection_id) def get_collection_rights(collection_id, strict=True): \"\"\"Retrieves the rights", "ID of the committer. activity_rights: ActivityRights. The rights object for", "Exception('This %s cannot be unpublished.' % activity_type) _change_activity_status( committer_id, activity_id,", "% owner_editor) if owner_translator: raise utils.ValidationError( 'A user cannot be", "rights to publish the activity. \"\"\" committer_id = committer.user_id activity_rights", "can change its private viewability. if not check_can_publish_activity(committer, exploration_rights): logging.error(", "create_new_collection_rights(collection_id, committer_id): \"\"\"Creates a new collection rights object and saves", "committer_id, activity_id, activity_type, ACTIVITY_STATUS_PUBLIC, '%s published.' % activity_type) def _unpublish_activity(committer,", "Object having user_id, role and actions for given user. activity_rights:", "the caller to check that the collection is valid prior", "owner. \"\"\" return bool(user_id in self.owner_ids) def is_editor(self, user_id): \"\"\"Checks", "id=exploration_rights.id, owner_ids=exploration_rights.owner_ids, editor_ids=exploration_rights.editor_ids, translator_ids=exploration_rights.translator_ids, viewer_ids=exploration_rights.viewer_ids, community_owned=exploration_rights.community_owned, status=exploration_rights.status, viewable_if_private=exploration_rights.viewable_if_private, first_published_msec=exploration_rights.first_published_msec, ).commit(committer_id,", "elif new_role == ROLE_TRANSLATOR: if (activity_rights.is_editor(assignee_id) or activity_rights.is_translator(assignee_id) or activity_rights.is_owner(assignee_id)):", "whether the collection is public. Args: collection_id: str. ID of", "or CollectionRights domain object to the datastore. Args: committer_id: str.", "ROLE_TRANSLATOR]: subscription_services.subscribe_to_exploration( assignee_id, exploration_id) def release_ownership_of_exploration(committer, exploration_id): \"\"\"Releases ownership of", "is None: activity_rights.first_published_msec = ( utils.get_current_time_in_millisecs()) _save_activity_rights( committer_id, activity_rights, activity_type,", "\"\"\" def __init__( self, exploration_id, owner_ids, editor_ids, translator_ids, viewer_ids, community_owned=False,", "%s' % owner_editor) if owner_translator: raise utils.ValidationError( 'A user cannot", "whether given user is translator of activity. Args: user_id: str", "the new role: One of ROLE_OWNER ROLE_EDITOR ROLE_TRANSLATOR Raises: Exception.", "collection. Returns: list(str). Human-readable usernames (or truncated email addresses) of", "backward-compatibility with previous exploration snapshots in the datastore. # Do", "constants.ACTIVITY_TYPE_EXPLORATION, commit_message, commit_cmds) _update_exploration_summary(exploration_rights) def publish_exploration(committer, exploration_id): \"\"\"Publishes the given", "for this exploration from the datastore. Args: exploration_id: str. ID", "by anyone.' % activity_type) activity_rights.viewer_ids.append(assignee_id) else: raise Exception('Invalid role: %s'", "the datastore. \"\"\" model = collection_models.CollectionRightsModel.get( collection_id, strict=strict) if model", "if not check_can_release_ownership(committer, activity_rights): logging.error( 'User %s tried to release", "activity_type, ACTIVITY_STATUS_PUBLIC, '%s published.' % activity_type) def _unpublish_activity(committer, activity_id, activity_type):", "potentially throw an exception from _unpublish_activity. \"\"\" _unpublish_activity( committer, collection_id,", "constants.ACTIVITY_TYPE_COLLECTION: model_cls = collection_models.CollectionRightsModel model = model_cls.get(activity_rights.id, strict=False) model.owner_ids =", "model.editor_ids = activity_rights.editor_ids model.viewer_ids = activity_rights.viewer_ids model.translator_ids = activity_rights.translator_ids model.community_owned", "collection_id, constants.ACTIVITY_TYPE_COLLECTION) def publish_collection(committer, collection_id): \"\"\"Publishes the given collection. It", "cmd_type = CMD_CHANGE_COLLECTION_STATUS commit_cmds = [{ 'cmd': cmd_type, 'old_status': old_status,", "both an owner and a viewer: %s' % owner_viewer) if", "the link. Args: committer: UserActionsInfo. UserActionsInfo object for the committer.", "the given exploration. It is the responsibility of the caller", "exploration viewable to anyone with the link.' if viewable_if_private else", "activity_rights.validate() if activity_type == constants.ACTIVITY_TYPE_EXPLORATION: model_cls = exp_models.ExplorationRightsModel elif activity_type", "collection_rights.status == ACTIVITY_STATUS_PRIVATE def is_collection_public(collection_id): \"\"\"Returns whether the collection is", "new_status, commit_message): \"\"\"Changes the status of the given activity. Args:", "throw an exception from _publish_activity. \"\"\" _publish_activity( committer, collection_id, constants.ACTIVITY_TYPE_COLLECTION)", "exploration or a collection). \"\"\" def __init__( self, exploration_id, owner_ids,", "is an activity viewer. \"\"\" return bool(user_id in self.viewer_ids) def", "constants.ACTIVITY_TYPE_EXPLORATION) if new_role in [ROLE_OWNER, ROLE_EDITOR, ROLE_TRANSLATOR]: subscription_services.subscribe_to_exploration( assignee_id, exploration_id)", "viewable (by anyone with the link). Raises: Exception. The committer", "values: constants.ACTIVITY_TYPE_EXPLORATION constants.ACTIVITY_TYPE_COLLECTION Returns: ActivityRights. The rights object created from", "activity. Exception. The user can already translate the activity. Exception.", "utils.ValidationError( 'A user cannot be both an owner and an", "an error if ID is not found. Returns: ActivityRights. The", "]) # IMPORTANT: Ensure that all changes to how these", "Could not assign new role.') assignee_username = user_services.get_username(assignee_id) old_role =", "not check_can_publish_activity(committer, exploration_rights): logging.error( 'User %s tried to change private", "is_owner(self, user_id): \"\"\"Checks whether given user is owner of activity.", "committer_id): \"\"\"Creates a new collection rights object and saves it", "False def check_can_unpublish_activity(user, activity_rights): \"\"\"Checks whether the user can unpublish", "user can modify roles for given activity. Args: user: UserActionsInfo.", "'Made exploration viewable only to invited playtesters.') _save_activity_rights( committer_id, exploration_rights,", "and a translator: %s' % editor_translator) if editor_viewer: raise utils.ValidationError(", "collection. \"\"\" collection_rights = get_collection_rights(collection_id) return user_services.get_human_readable_user_ids( collection_rights.owner_ids) def is_collection_private(collection_id):", "already exist. CMD_CREATE_NEW = 'create_new' CMD_CHANGE_ROLE = 'change_role' CMD_CHANGE_EXPLORATION_STATUS =", "% owner_translator) if owner_viewer: raise utils.ValidationError( 'A user cannot be", "that all changes to how these cmds are interpreted preserve", "user. Returns: bool. Whether user is an activity viewer. \"\"\"", "given activity based on its type. Args: activity_type: str. The", "with ID exploration_id was not found in the datastore. \"\"\"", "given exploration to the community. Args: committer: UserActionsInfo. UserActionsInfo object", "= set(self.editor_ids).intersection( set(self.viewer_ids)) if owner_editor: raise utils.ValidationError( 'A user cannot", "exp_models,) = models.Registry.import_models([ models.NAMES.collection, models.NAMES.exploration ]) # IMPORTANT: Ensure that", "and (role_services.ACTION_EDIT_ANY_PUBLIC_ACTIVITY in user.actions)): return True return False def check_can_translate_activity(user,", "values: constants.ACTIVITY_TYPE_EXPLORATION constants.ACTIVITY_TYPE_COLLECTION new_status: str. The new status of the", "exploration. Returns: bool. Whether the exploration is a clone of", "_get_activity_rights(activity_type, activity_id) if not check_can_publish_activity(committer, activity_rights): logging.error( 'User %s tried", "rights. \"\"\" committer_id = committer.user_id activity_rights = _get_activity_rights(activity_type, activity_id) if", "activity_rights, activity_type, '%s ownership released to the community.' % activity_type,", "!= ACTIVITY_STATUS_PRIVATE: raise Exception( 'Public %ss can be viewed by", "or activity_rights.is_editor(user.user_id)): return True if (activity_rights.community_owned or (role_services.ACTION_EDIT_ANY_ACTIVITY in user.actions)):", "lists overlap, or if a community-owned exploration has owners, editors,", "The type of activity. Possible values: constants.ACTIVITY_TYPE_EXPLORATION constants.ACTIVITY_TYPE_COLLECTION commit_message: str.", "the given collection to the community. Args: committer: UserActionsInfo. UserActionsInfo", "'set first published time in msec', commit_cmds) def create_new_exploration_rights(exploration_id, committer_id):", "user.actions: return True elif (activity_rights.is_private() and (role_services.ACTION_DELETE_OWNED_PRIVATE_ACTIVITY in user.actions) and", "% activity_type) activity_rights.viewer_ids.append(assignee_id) else: raise Exception('Invalid role: %s' % new_role)", "exploration_id)) raise Exception( 'The viewability status of this exploration cannot", "the current value.' % viewable_if_private) exploration_rights.viewable_if_private = viewable_if_private commit_cmds =", "be both an owner and a translator: %s' % owner_translator)", "access given activity. Args: user: UserActionsInfo. Object having user_id, role", "== ROLE_EDITOR: if (activity_rights.is_editor(assignee_id) or activity_rights.is_owner(assignee_id)): raise Exception( 'This user", "' 'permission.' % (committer_id, activity_type, activity_id)) raise Exception('This %s cannot", "an owner and a viewer: %s' % owner_viewer) if editor_translator:", "message for the commit. commit_cmds: list(dict). A list of commands", "activity_id) if not check_can_release_ownership(committer, activity_rights): logging.error( 'User %s tried to", "Args: exploration_id: str. ID of the exploration. Returns: bool. Whether", "UserActionsInfo object for the committer. collection_id: str. ID of the", "given exploration ids. Args: exp_ids: list(str). List of exploration ids.", "str. ID of the collection. Raises: Exception. This could potentially", "collection_id, constants.ACTIVITY_TYPE_COLLECTION) def unpublish_collection(committer, collection_id): \"\"\"Unpublishes the given collection. Args:", "rights object for the given activity based on its type.", "strict: bool. Whether to raise an error if there is", "the assignee to future exploration updates. The caller should ensure", "type of activity. Possible values: constants.ACTIVITY_TYPE_EXPLORATION constants.ACTIVITY_TYPE_COLLECTION activity_rights: ActivityRights. The", "not check_can_publish_activity(committer, activity_rights): logging.error( 'User %s tried to publish %s", "if activity_rights is None: return False if role_services.ACTION_DELETE_ANY_ACTIVITY in user.actions:", "given ID. Returns: ActivityRights. The rights object for the given", "exp_services exp_services.update_exploration_summary( activity_rights.id, None) def _update_collection_summary(activity_rights): \"\"\"Updates the collection summary", "datastore. \"\"\" model = collection_models.CollectionRightsModel.get( collection_id, strict=strict) if model is", "activity_type, 'set first published time in msec', commit_cmds) def create_new_exploration_rights(exploration_id,", "activity is published. \"\"\" return bool(self.status == ACTIVITY_STATUS_PUBLIC) def is_private(self):", "in user.actions: return True elif (activity_rights.is_private() and (role_services.ACTION_DELETE_OWNED_PRIVATE_ACTIVITY in user.actions)", "viewer_ids=collection_rights.viewer_ids, community_owned=collection_rights.community_owned, status=collection_rights.status, viewable_if_private=collection_rights.viewable_if_private, first_published_msec=collection_rights.first_published_msec ).commit(committer_id, 'Created new collection', commit_cmds)", "potentially throw an exception from _release_ownership_of_activity. \"\"\" _release_ownership_of_activity( committer, collection_id,", "activity_type): \"\"\"Constructs an ActivityRights object from the given activity rights", "True return False def check_can_release_ownership(user, activity_rights): \"\"\"Checks whether the user", "the exploration. Returns: bool. Whether the exploration is a clone", "publish given activity. Args: user: UserActionsInfo. Object having user_id, role", "a user to the given role and subscribes the assignee", "be a(n) %s of activity %s ' 'but was refused", "by anyone.' % activity_type) activity_rights.editor_ids.append(assignee_id) if assignee_id in activity_rights.translator_ids: activity_rights.translator_ids.remove(assignee_id)", "self.translator_ids = translator_ids self.viewer_ids = viewer_ids self.community_owned = community_owned self.cloned_from", "strict=True): \"\"\"Retrieves the rights for this collection from the datastore.", "\"\"\"Checks whether the user can release ownership for given activity.", "publication. Args: committer: UserActionsInfo. UserActionsInfo object for the committer. exploration_id:", "return bool(exploration_rights.cloned_from) def create_new_collection_rights(collection_id, committer_id): \"\"\"Creates a new collection rights", "in exp_rights_models: if model is None: exp_models_list.append(None) else: exp_models_list.append( get_activity_rights_from_model(", "False def check_can_delete_activity(user, activity_rights): \"\"\"Checks whether the user can delete", "old_viewable_if_private == viewable_if_private: raise Exception( 'Trying to change viewability status", "specified.') owner_editor = set(self.owner_ids).intersection(set(self.editor_ids)) owner_translator = set(self.owner_ids).intersection( set(self.translator_ids)) owner_viewer =", "activity_rights.translator_ids model.community_owned = activity_rights.community_owned model.status = activity_rights.status model.viewable_if_private = activity_rights.viewable_if_private", "_publish_activity( committer, collection_id, constants.ACTIVITY_TYPE_COLLECTION) def unpublish_collection(committer, collection_id): \"\"\"Unpublishes the given", "is_private(self): \"\"\"Checks whether activity is private. Returns: bool. Whether activity", "the same as the ID of associated activity. Args: activity_type:", "if new_role == ROLE_OWNER: if activity_rights.is_owner(assignee_id): raise Exception('This user already", "of the given activity to the community. Args: committer: UserActionsInfo.", "%s, ' 'but that is already the current value.' %", "ActivityRights( activity_rights_model.id, activity_rights_model.owner_ids, activity_rights_model.editor_ids, activity_rights_model.translator_ids, activity_rights_model.viewer_ids, community_owned=activity_rights_model.community_owned, cloned_from=( activity_rights_model.cloned_from if", "published. \"\"\" return bool(self.status == ACTIVITY_STATUS_PUBLIC) def is_private(self): \"\"\"Checks whether", "%s tried to release ownership of %s %s but was", "_assign_role. \"\"\" _assign_role( committer, assignee_id, new_role, exploration_id, constants.ACTIVITY_TYPE_EXPLORATION) if new_role", "(role_services.ACTION_MODIFY_ROLES_FOR_OWNED_ACTIVITY in user.actions): if activity_rights.is_owner(user.user_id): return True return False def", "def check_can_unpublish_activity(user, activity_rights): \"\"\"Checks whether the user can unpublish given", "get_collection_owner_names(collection_id): \"\"\"Retrieves the owners for this collection from the datastore.", "collection. Args: committer: UserActionsInfo. UserActionsInfo object for the committer. collection_id:", "explorations should have no viewers specified.') owner_editor = set(self.owner_ids).intersection(set(self.editor_ids)) owner_translator", "List of exploration ids. Returns: list(ActivityRights or None). List of", "under the License is distributed on an \"AS-IS\" BASIS, #", "None return get_activity_rights_from_model( model, constants.ACTIVITY_TYPE_EXPLORATION) def get_multiple_exploration_rights_by_ids(exp_ids): \"\"\"Returns a list", "the rights for this collection from the datastore. Args: collection_id:", "activity_rights.is_translator(assignee_id) or activity_rights.is_owner(assignee_id)): raise Exception( 'This user already can translate", "activity. Possible values: constants.ACTIVITY_TYPE_EXPLORATION constants.ACTIVITY_TYPE_COLLECTION Raises: Exception. The committer does", "'community_owned': True, 'owner_names': [], 'editor_names': [], 'translator_names': [], 'viewer_names': [],", "CollectionRights domain object to the datastore. Args: committer_id: str. ID", "= 'translator' ROLE_VIEWER = 'viewer' ROLE_NONE = 'none' ROLE_ADMIN =", "whether exploration is private. Args: exploration_id: str. ID of the", "exploration to be viewed by anyone with the link. Args:", "first_published_msec def validate(self): \"\"\"Validates an ActivityRights object. Raises: utils.ValidationError: if", "and (role_services.ACTION_EDIT_ANY_PUBLIC_ACTIVITY in user.actions)): return True return False def check_can_delete_activity(user,", "# IMPORTANT: Ensure that all changes to how these cmds", "commit_cmds) _update_exploration_summary(exploration_rights) def publish_exploration(committer, exploration_id): \"\"\"Publishes the given exploration. It", "return exploration_rights.status == ACTIVITY_STATUS_PUBLIC def is_exploration_cloned(exploration_id): \"\"\"Returns whether the exploration", "activity_id, activity_type, ACTIVITY_STATUS_PUBLIC, '%s published.' % activity_type) def _unpublish_activity(committer, activity_id,", "activity_type == constants.ACTIVITY_TYPE_EXPLORATION else None), status=activity_rights_model.status, viewable_if_private=activity_rights_model.viewable_if_private, first_published_msec=activity_rights_model.first_published_msec ) def", "The caller should ensure that assignee_id corresponds to a valid", "release ownership for given activity. \"\"\" if activity_rights is None:", "anyone.' % activity_type) activity_rights.translator_ids.append(assignee_id) if assignee_id in activity_rights.viewer_ids: activity_rights.viewer_ids.remove(assignee_id) old_role", "whether activity is private. Returns: bool. Whether activity is private.", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "owner and a viewer: %s' % owner_viewer) if editor_translator: raise", "the exploration is a clone of another exploration. \"\"\" exploration_rights", "UserActionsInfo object for the committer. activity_id: str. ID of the", "constants.ACTIVITY_TYPE_COLLECTION) def get_collection_owner_names(collection_id): \"\"\"Retrieves the owners for this collection from", "% (committer_id, activity_type, activity_id)) raise Exception( 'The ownership of this", "== constants.ACTIVITY_TYPE_COLLECTION: cmd_type = CMD_CHANGE_COLLECTION_STATUS commit_cmds = [{ 'cmd': cmd_type,", "given exploration. Raises: EntityNotFoundError. The exploration with ID exploration_id was", "The UserActionsInfo object for the committer. exploration_id: str. ID of", "None), status=activity_rights_model.status, viewable_if_private=activity_rights_model.viewable_if_private, first_published_msec=activity_rights_model.first_published_msec ) def _save_activity_rights( committer_id, activity_rights, activity_type,", "editors, translators and viewers lists overlap, or if a community-owned", "the given collection. It is the responsibility of the caller", "permission.' % ( committer_id, assignee_id, new_role, activity_id)) raise Exception( 'UnauthorizedUserException:", "viewability. if not check_can_publish_activity(committer, exploration_rights): logging.error( 'User %s tried to", "object for the committer. exploration_id: str. ID of the exploration.", "if activity_rights is None: return False if role_services.ACTION_EDIT_OWNED_ACTIVITY not in", "exploration to %s, ' 'but that is already the current", "user is an activity editor. \"\"\" return bool(user_id in self.editor_ids)", "_unpublish_activity( committer, exploration_id, constants.ACTIVITY_TYPE_EXPLORATION) # Rights functions for collections. def", "bool. Whether activity is private. \"\"\" return bool(self.status == ACTIVITY_STATUS_PRIVATE)", "exploration. Returns: bool. Whether the exploration is private or not.", "for the given exploration. Raises: EntityNotFoundError. The exploration with ID", "given activity. Returns: bool. Whether the user can delete given", "whose role is being changed. new_role: str. The name of", "committer_id, activity_id, activity_type, new_status, commit_message): \"\"\"Changes the status of the", "Whether the exploration is public. \"\"\" exploration_rights = get_exploration_rights(exploration_id) return", "bool. Whether the user can modify roles for given activity.", "if activity_type == constants.ACTIVITY_TYPE_EXPLORATION else None), status=activity_rights_model.status, viewable_if_private=activity_rights_model.viewable_if_private, first_published_msec=activity_rights_model.first_published_msec )", "= committer.user_id activity_rights = _get_activity_rights(activity_type, activity_id) if not check_can_modify_activity_roles(committer, activity_rights):", "check_can_modify_activity_roles( user, activity_rights) def check_can_publish_activity(user, activity_rights): \"\"\"Checks whether the user", "be published.' % activity_type) _change_activity_status( committer_id, activity_id, activity_type, ACTIVITY_STATUS_PUBLIC, '%s", "activity_id) if not check_can_unpublish_activity(committer, activity_rights): logging.error( 'User %s tried to", "viewers lists overlap, or if a community-owned exploration has owners,", "user.actions)): return True return False def check_can_modify_activity_roles(user, activity_rights): \"\"\"Checks whether", "activity. \"\"\" from core.domain import collection_services collection_services.update_collection_summary( activity_rights.id, None) def", "activity. commit_message: str. The human-written commit message for this change.", "committer_id: str. ID of the committer. \"\"\" collection_rights = ActivityRights(", "activity_rights.viewable_if_private) def check_can_edit_activity(user, activity_rights): \"\"\"Checks whether the user can edit", "constants.ACTIVITY_TYPE_EXPLORATION: cmd_type = CMD_CHANGE_EXPLORATION_STATUS elif activity_type == constants.ACTIVITY_TYPE_COLLECTION: cmd_type =", "role_services.ACTION_DELETE_ANY_ACTIVITY in user.actions: return True elif (activity_rights.is_private() and (role_services.ACTION_DELETE_OWNED_PRIVATE_ACTIVITY in", "owner and an editor: %s' % owner_editor) if owner_translator: raise", "viewable. Exception. The role is invalid. \"\"\" committer_id = committer.user_id", "constants.ACTIVITY_TYPE_EXPLORATION) def unpublish_exploration(committer, exploration_id): \"\"\"Unpublishes the given exploration. Args: committer:", "float. First publication time in milliseconds since the Epoch. \"\"\"", "not have the permission to perform change action. Exception. If", "the new role: One of ROLE_OWNER ROLE_EDITOR Raises: Exception. This", "user_services.get_human_readable_user_ids( self.editor_ids), 'translator_names': user_services.get_human_readable_user_ids( self.translator_ids), 'viewer_names': user_services.get_human_readable_user_ids( self.viewer_ids), 'viewable_if_private': self.viewable_if_private,", "else 'Made exploration viewable only to invited playtesters.') _save_activity_rights( committer_id,", "not assign new role.') assignee_username = user_services.get_username(assignee_id) old_role = ROLE_NONE", "str. The type of activity. Possible values: constants.ACTIVITY_TYPE_EXPLORATION constants.ACTIVITY_TYPE_COLLECTION new_status:", "'Community-owned explorations should have no owners, ' 'editors, translators or", "get_activity_rights_from_model( model, constants.ACTIVITY_TYPE_COLLECTION) def get_collection_owner_names(collection_id): \"\"\"Retrieves the owners for this", "assign_role_for_exploration( committer, exploration_id, assignee_id, new_role): \"\"\"Assigns a user to the", "in user.actions): if activity_rights.is_owner(user.user_id): return True return False def check_can_release_ownership(user,", "anyone with the link. Args: committer: UserActionsInfo. UserActionsInfo object for", "= exp_models.ExplorationRightsModel.get( exploration_id, strict=strict) if model is None: return None", "given activity. Returns: bool. Whether the given user can translate", "assignee_id, new_role): \"\"\"Assigns a user to the given role and", "object. The ID of rights object is the same as", "be made viewable (by anyone with the link). Raises: Exception.", "the datastore. Subscribes the committer to the new exploration. Args:", "for existing exploration or None. \"\"\" exp_rights_models = exp_models.ExplorationRightsModel.get_multi( exp_ids)", "whether given user is viewer of activity. Args: user_id: str", "whether the user can unpublish given activity. Args: user: UserActionsInfo.", "Version 2.0 (the \"License\"); # you may not use this", "\"\"\"Validates an ActivityRights object. Raises: utils.ValidationError: if any of the", "user_services.get_human_readable_user_ids( collection_rights.owner_ids) def is_collection_private(collection_id): \"\"\"Returns whether the collection is private.", "anyone.' % activity_type) activity_rights.editor_ids.append(assignee_id) if assignee_id in activity_rights.translator_ids: activity_rights.translator_ids.remove(assignee_id) old_role", "= ROLE_VIEWER elif new_role == ROLE_VIEWER: if (activity_rights.is_owner(assignee_id) or activity_rights.is_editor(assignee_id)", "object. If viewable_if_private is True, this allows a private exploration", "of the collection. strict: bool. Whether to raise an error", "system. Args: committer: UserActionsInfo. The UserActionsInfo object for the committer.", "One of ROLE_OWNER ROLE_EDITOR Raises: Exception. This could potentially throw", "translator_viewer: raise utils.ValidationError( 'A user cannot be both a translator", "The user already owns the activity. Exception. The user can", "[{'cmd': CMD_CREATE_NEW}] collection_models.CollectionRightsModel( id=collection_rights.id, owner_ids=collection_rights.owner_ids, editor_ids=collection_rights.editor_ids, translator_ids=collection_rights.translator_ids, viewer_ids=collection_rights.viewer_ids, community_owned=collection_rights.community_owned, status=collection_rights.status,", "committer_id = committer.user_id activity_rights = _get_activity_rights(activity_type, activity_id) if not check_can_modify_activity_roles(committer,", "constants.ACTIVITY_TYPE_EXPLORATION constants.ACTIVITY_TYPE_COLLECTION Raises: Exception. The committer does not have rights", "raise Exception( 'UnauthorizedUserException: Could not assign new role.') assignee_username =", "role_services.ACTION_EDIT_OWNED_ACTIVITY not in user.actions: return False if (activity_rights.is_owner(user.user_id) or activity_rights.is_editor(user.user_id)", "Exception( 'Public %ss can be viewed by anyone.' % activity_type)", "given activity. Returns: bool. Whether the user can modify roles", "__init__( self, exploration_id, owner_ids, editor_ids, translator_ids, viewer_ids, community_owned=False, cloned_from=None, status=ACTIVITY_STATUS_PRIVATE,", "a private exploration to be viewed by anyone with the", "of ROLE_OWNER ROLE_EDITOR ROLE_TRANSLATOR ROLE_VIEWER activity_id: str. ID of the", "create_new_exploration_rights(exploration_id, committer_id): \"\"\"Creates a new exploration rights object and saves", "given activity. Args: user: UserActionsInfo. Object having user_id, role and", "if activity_rights.is_private(): return False return check_can_modify_activity_roles( user, activity_rights) def check_can_publish_activity(user,", "not found. Returns: ActivityRights. The rights object for the collection.", "in user.actions)): return True return False def check_can_translate_activity(user, activity_rights): \"\"\"Checks", "is_editor(self, user_id): \"\"\"Checks whether given user is editor of activity.", "\"\"\" return bool(user_id in self.translator_ids) def is_viewer(self, user_id): \"\"\"Checks whether", "\"\"\"Retrieves the owners for this collection from the datastore. Args:", "first_published_msec): \"\"\"Updates the first_published_msec field for the given activity. The", "potentially throw an exception from _unpublish_activity. \"\"\" _unpublish_activity( committer, exploration_id,", "collection with ID collection_id is not found in the datastore.", "raise utils.ValidationError( 'Public explorations should have no viewers specified.') owner_editor", "by applicable law or agreed to in writing, software #", "activity_type) if activity_rights.community_owned: raise Exception( 'Community-owned %ss can be translated", "same as the ID of associated activity. Args: activity_rights: ActivityRights.", "future collection updates. The caller should ensure that assignee_id corresponds", "if not check_can_publish_activity(committer, activity_rights): logging.error( 'User %s tried to publish", "user can release ownership for given activity. Args: user: UserActionsInfo.", "user.actions): if activity_rights.is_owner(user.user_id): return True return False def check_can_release_ownership(user, activity_rights):", "role is invalid. \"\"\" committer_id = committer.user_id activity_rights = _get_activity_rights(activity_type,", "if (activity_rights.community_owned or (role_services.ACTION_EDIT_ANY_ACTIVITY in user.actions)): return True if (activity_rights.is_published()", "str. ID of the collection. assignee_id: str. ID of the", "user_id: str or None. Id of the user. Returns: bool.", "of the new role: One of ROLE_OWNER ROLE_EDITOR ROLE_TRANSLATOR ROLE_VIEWER", "use by the frontend. Returns: dict. A dict version of", "whether exploration is public. Args: exploration_id: str. ID of the", "what kind of commit was done. \"\"\" activity_rights.validate() if activity_type", "Possible values: constants.ACTIVITY_TYPE_EXPLORATION constants.ACTIVITY_TYPE_COLLECTION activity_id: str. ID of the activity.", "import logging from constants import constants from core.domain import activity_services", "\"\"\"Retrieves the rights for this collection from the datastore. Args:", "raise Exception( 'This user already can edit this %s.' %", "raise Exception('This %s cannot be unpublished.' % activity_type) _change_activity_status( committer_id,", "logging.error( 'User %s tried to allow user %s to be", "def is_editor(self, user_id): \"\"\"Checks whether given user is editor of", "self.community_owned: return { 'cloned_from': self.cloned_from, 'status': self.status, 'community_owned': True, 'owner_names':", "commit message for this change. \"\"\" activity_rights = _get_activity_rights(activity_type, activity_id)", "bool. Whether user is an activity editor. \"\"\" return bool(user_id", "constants.ACTIVITY_TYPE_EXPLORATION constants.ACTIVITY_TYPE_COLLECTION commit_message: str. Descriptive message for the commit. commit_cmds:", "the given exploration to the community. Args: committer: UserActionsInfo. UserActionsInfo", "activity_rights.first_published_msec = ( utils.get_current_time_in_millisecs()) _save_activity_rights( committer_id, activity_rights, activity_type, commit_message, commit_cmds)", "of rights object is the same as the ID of", "the user who is performing the action. assignee_id: str. ID", "owner_editor: raise utils.ValidationError( 'A user cannot be both an owner", "for the given activity. Returns: bool. Whether the user can", "the exploration. Raises: Exception. This could potentially throw an exception", "language governing permissions and # limitations under the License. \"\"\"Domain", "def check_can_translate_activity(user, activity_rights): \"\"\"Checks whether the user can translate given", "role_services.ACTION_UNPUBLISH_ANY_PUBLIC_ACTIVITY in user.actions: return True return False def _assign_role( committer,", "owners, editors, translators or viewers specified. \"\"\" if self.community_owned: if", "commands describing what kind of commit was done. \"\"\" activity_rights.validate()", "the user can release ownership for given activity. \"\"\" if", "activity_rights.viewer_ids: activity_rights.viewer_ids.remove(assignee_id) old_role = ROLE_VIEWER if assignee_id in activity_rights.editor_ids: activity_rights.editor_ids.remove(assignee_id)", "commit_message, commit_cmds): \"\"\"Saves an ExplorationRights or CollectionRights domain object to", "before updating it. Args: activity_type: str. The type of activity.", "in self.viewer_ids) def is_published(self): \"\"\"Checks whether activity is published. Returns:", "status=exploration_rights.status, viewable_if_private=exploration_rights.viewable_if_private, first_published_msec=exploration_rights.first_published_msec, ).commit(committer_id, 'Created new exploration', commit_cmds) subscription_services.subscribe_to_exploration( committer_id,", "check_can_access_activity(user, activity_rights): \"\"\"Checks whether the user can access given activity.", "unpublish_collection(committer, collection_id): \"\"\"Unpublishes the given collection. Args: committer: UserActionsInfo. UserActionsInfo", "committer does not have rights to unpublish the activity. \"\"\"", "activity. Raises: Exception. activity_type provided is unknown. \"\"\" if activity_type", "new_role == ROLE_OWNER: if activity_rights.is_owner(assignee_id): raise Exception('This user already owns", "already view the activity. Exception. The activity is already publicly", "editor and a translator: %s' % editor_translator) if editor_viewer: raise", "user to the given role and subscribes the assignee to", "Exception. activity_type provided is unknown. \"\"\" if activity_type == constants.ACTIVITY_TYPE_EXPLORATION:", "constants.ACTIVITY_TYPE_COLLECTION Raises: Exception. The committer does not have rights to", "= exploration_id self.owner_ids = owner_ids self.editor_ids = editor_ids self.translator_ids =", "= translator_ids self.viewer_ids = viewer_ids self.community_owned = community_owned self.cloned_from =", "assignee_id, new_role, activity_id, activity_type): \"\"\"Assigns a new role to the", "Args: exploration_id: str. ID of the exploration. strict: bool. Whether", "activity translator. \"\"\" return bool(user_id in self.translator_ids) def is_viewer(self, user_id):", "exploration or None. \"\"\" exp_rights_models = exp_models.ExplorationRightsModel.get_multi( exp_ids) exp_models_list =", "translator_ids=collection_rights.translator_ids, viewer_ids=collection_rights.viewer_ids, community_owned=collection_rights.community_owned, status=collection_rights.status, viewable_if_private=collection_rights.viewable_if_private, first_published_msec=collection_rights.first_published_msec ).commit(committer_id, 'Created new collection',", "of the exploration. Raises: Exception. This could potentially throw an", "that this value is not already set before updating it.", "release ownership of %s %s but was ' 'refused permission.'", "IMPORTANT: Ensure that all changes to how these cmds are", "does not have rights to modify a role. Exception. The", "the same as the ID of associated activity. Args: activity_rights:", "for the given activity associated with the given rights object.", "The Oppia Authors. All Rights Reserved. # # Licensed under", "CMD_CHANGE_EXPLORATION_STATUS = 'change_exploration_status' CMD_CHANGE_COLLECTION_STATUS = 'change_collection_status' CMD_CHANGE_PRIVATE_VIEWABILITY = 'change_private_viewability' CMD_RELEASE_OWNERSHIP", "user.actions)): return True return False def check_can_translate_activity(user, activity_rights): \"\"\"Checks whether", "role of %s from %s to %s' % ( assignee_username,", "[ROLE_OWNER, ROLE_EDITOR]: subscription_services.subscribe_to_collection( assignee_id, collection_id) def release_ownership_of_collection(committer, collection_id): \"\"\"Releases ownership", "Exception( 'The viewability status of this exploration cannot be changed.')", "if activity_type == constants.ACTIVITY_TYPE_EXPLORATION: _update_exploration_summary(activity_rights) elif activity_type == constants.ACTIVITY_TYPE_COLLECTION: _update_collection_summary(activity_rights)", "'A user cannot be both an owner and a translator:", "elif (activity_rights.is_private() and (role_services.ACTION_DELETE_OWNED_PRIVATE_ACTIVITY in user.actions) and activity_rights.is_owner(user.user_id)): return True", "the exploration is public. \"\"\" exploration_rights = get_exploration_rights(exploration_id) return exploration_rights.status", "applicable law or agreed to in writing, software # distributed", "to invited playtesters.') _save_activity_rights( committer_id, exploration_rights, constants.ACTIVITY_TYPE_EXPLORATION, commit_message, commit_cmds) _update_exploration_summary(exploration_rights)", "this exploration cannot be changed.') old_viewable_if_private = exploration_rights.viewable_if_private if old_viewable_if_private", "whether given user is editor of activity. Args: user_id: str", "for the user who is performing the action. activity_id: str.", "Exception. The user can already edit the activity. Exception. The", "activity. Args: activity_type: str. The type of activity. Possible values:", "in self.translator_ids) def is_viewer(self, user_id): \"\"\"Checks whether given user is", "for use by the frontend. \"\"\" if self.community_owned: return {", "with the given rights object. The ID of rights object", "\"\"\"Publishes the given activity. Args: committer: UserActionsInfo. UserActionsInfo object for", "exp_models.ExplorationRightsModel elif activity_type == constants.ACTIVITY_TYPE_COLLECTION: model_cls = collection_models.CollectionRightsModel model =", "in user.actions) elif activity_rights.is_private(): return bool( (role_services.ACTION_PLAY_ANY_PRIVATE_ACTIVITY in user.actions) or", "} def is_owner(self, user_id): \"\"\"Checks whether given user is owner", "of activity. Possible values: constants.ACTIVITY_TYPE_EXPLORATION constants.ACTIVITY_TYPE_COLLECTION Raises: Exception. The committer", "str. ID of the exploration. viewable_if_private: bool. Whether the exploration", "check_can_publish_activity(committer, activity_rights): logging.error( 'User %s tried to publish %s %s", "def release_ownership_of_collection(committer, collection_id): \"\"\"Releases ownership of the given collection to", "the status of the given activity. Args: committer_id: str. ID", "Possible values: constants.ACTIVITY_TYPE_EXPLORATION constants.ACTIVITY_TYPE_COLLECTION activity_rights: ActivityRights. The rights object for", "\"\"\" from core.domain import collection_services collection_services.update_collection_summary( activity_rights.id, None) def _update_activity_summary(activity_type,", "activity_rights.translator_ids.remove(assignee_id) old_role = ROLE_TRANSLATOR elif new_role == ROLE_EDITOR: if (activity_rights.is_editor(assignee_id)", "link). Raises: Exception. The committer does not have the permission", "can delete given activity. \"\"\" if activity_rights is None: return", "commit_message: str. The human-written commit message for this change. \"\"\"", "= _get_activity_rights(activity_type, activity_id) if not check_can_release_ownership(committer, activity_rights): logging.error( 'User %s", "self.viewer_ids) def is_published(self): \"\"\"Checks whether activity is published. Returns: bool.", "\"\"\" if activity_type == constants.ACTIVITY_TYPE_EXPLORATION: return get_exploration_rights(activity_id, strict=False) elif activity_type", "\"\"\" _publish_activity( committer, exploration_id, constants.ACTIVITY_TYPE_EXPLORATION) def unpublish_exploration(committer, exploration_id): \"\"\"Unpublishes the", "% new_role) commit_message = 'Changed role of %s from %s", "for the committer. activity_id: str. ID of the activity. activity_type:", "False def check_can_release_ownership(user, activity_rights): \"\"\"Checks whether the user can release", "is None: return False if activity_rights.is_private(): return False return check_can_modify_activity_roles(", "# You may obtain a copy of the License at", "user can unpublish given activity. Args: user: UserActionsInfo. Object having", "= 'change_collection_status' CMD_CHANGE_PRIVATE_VIEWABILITY = 'change_private_viewability' CMD_RELEASE_OWNERSHIP = 'release_ownership' CMD_UPDATE_FIRST_PUBLISHED_MSEC =", "the exploration. assignee_id: str. ID of the user whose role", "str. ID of the exploration. strict: bool. Whether to raise", "get_exploration_rights(exploration_id) return exploration_rights.status == ACTIVITY_STATUS_PRIVATE def is_exploration_public(exploration_id): \"\"\"Returns whether exploration", "given role and subscribes the assignee to future collection updates.", "to publish the activity. \"\"\" committer_id = committer.user_id activity_rights =", "in the datastore. \"\"\" model = collection_models.CollectionRightsModel.get( collection_id, strict=strict) if", "user cannot be both an editor and a viewer: %s'", "given activity. Returns: bool. Whether the given user can edit", "viewability of exploration %s ' 'but was refused permission.' %", "collection. strict: bool. Whether to raise an error if ID", "but was ' 'refused permission.' % (committer_id, activity_type, activity_id)) raise", "public. Args: exploration_id: str. ID of the exploration. Returns: bool.", "rights object. The ID of rights object is the same", "Exception. The committer does not have rights to modify a", "model.viewer_ids = activity_rights.viewer_ids model.translator_ids = activity_rights.translator_ids model.community_owned = activity_rights.community_owned model.status", "can already translate the activity. Exception. The activity is already", "given activity associated with the given rights object. The ID", "= collection_models.CollectionRightsModel model = model_cls.get(activity_rights.id, strict=False) model.owner_ids = activity_rights.owner_ids model.editor_ids", "%s cannot be released.' % activity_type) activity_rights.community_owned = True activity_rights.owner_ids", "activity_rights_model.editor_ids, activity_rights_model.translator_ids, activity_rights_model.viewer_ids, community_owned=activity_rights_model.community_owned, cloned_from=( activity_rights_model.cloned_from if activity_type == constants.ACTIVITY_TYPE_EXPLORATION", "translate this activity. \"\"\" if activity_rights is None: return False", "activity. \"\"\" if activity_rights is None: return False if (activity_rights.community_owned", "values: constants.ACTIVITY_TYPE_EXPLORATION constants.ACTIVITY_TYPE_COLLECTION Raise: Exception. The committer does not have", "refused ' 'permission.' % (committer_id, activity_type, activity_id)) raise Exception('This %s", "\"\"\" collection_rights = get_collection_rights(collection_id) return collection_rights.status == ACTIVITY_STATUS_PUBLIC def _get_activity_rights(activity_type,", "else: raise Exception('Invalid role: %s' % new_role) commit_message = 'Changed", "not modify the definitions of CMD keys that already exist.", "if (activity_rights.community_owned or activity_rights.cloned_from): return False if (role_services.ACTION_MODIFY_ROLES_FOR_ANY_ACTIVITY in user.actions):", "a valid user in the system. Args: committer: UserActionsInfo. The", "translators or viewers specified. \"\"\" if self.community_owned: if (self.owner_ids or", "return False if activity_rights.is_published(): if role_services.ACTION_UNPUBLISH_ANY_PUBLIC_ACTIVITY in user.actions: return True", "if model is None: exp_models_list.append(None) else: exp_models_list.append( get_activity_rights_from_model( model, constants.ACTIVITY_TYPE_EXPLORATION))", "\"\"\" collection_rights = get_collection_rights(collection_id) return user_services.get_human_readable_user_ids( collection_rights.owner_ids) def is_collection_private(collection_id): \"\"\"Returns", "\"\"\" _assign_role( committer, assignee_id, new_role, exploration_id, constants.ACTIVITY_TYPE_EXPLORATION) if new_role in", "(role_services.ACTION_EDIT_ANY_PUBLIC_ACTIVITY in user.actions)): return True return False def check_can_delete_activity(user, activity_rights):", "viewability status of this exploration cannot be changed.') old_viewable_if_private =", "from core.domain import activity_services from core.domain import role_services from core.domain", "list(dict). A list of commands describing what kind of commit", "'status': self.status, 'community_owned': True, 'owner_names': [], 'editor_names': [], 'translator_names': [],", "from core.domain import role_services from core.domain import subscription_services from core.domain", "activity_rights.owner_ids.append(assignee_id) if assignee_id in activity_rights.viewer_ids: activity_rights.viewer_ids.remove(assignee_id) old_role = ROLE_VIEWER if", "viewable_if_private property is already as desired. \"\"\" committer_id = committer.user_id", "rights for this collection from the datastore. Args: collection_id: str.", "subscribes the assignee to future exploration updates. The caller should", "ID of the exploration. Returns: bool. Whether the exploration is", "model.first_published_msec = activity_rights.first_published_msec model.commit(committer_id, commit_message, commit_cmds) def _update_exploration_summary(activity_rights): \"\"\"Updates the", "committer. exploration_id: str. ID of the exploration. viewable_if_private: bool. Whether", "'editor_names': [], 'translator_names': [], 'viewer_names': [], 'viewable_if_private': self.viewable_if_private, } else:", "feconf import utils current_user_services = models.Registry.import_current_user_services() (collection_models, exp_models,) = models.Registry.import_models([", "model.status = activity_rights.status model.viewable_if_private = activity_rights.viewable_if_private model.first_published_msec = activity_rights.first_published_msec model.commit(committer_id,", "(committer_id, exploration_id)) raise Exception( 'The viewability status of this exploration", "activity is private. \"\"\" return bool(self.status == ACTIVITY_STATUS_PRIVATE) def get_activity_rights_from_model(activity_rights_model,", "potentially throw an exception from _publish_activity. \"\"\" _publish_activity( committer, collection_id,", "having user_id, role and actions for given user. activity_rights: ActivityRights", "def assign_role_for_collection( committer, collection_id, assignee_id, new_role): \"\"\"Assign the given user", "constants.ACTIVITY_TYPE_COLLECTION activity_rights: ActivityRights. The rights object for the given activity.", "rights object associated with the given activity. Raises: Exception. activity_type", "this %s.' % activity_type) if activity_rights.community_owned: raise Exception( 'Community-owned %ss", "activity_rights): \"\"\"Checks whether the user can release ownership for given", "could potentially throw an exception from _unpublish_activity. \"\"\" _unpublish_activity( committer,", "\"\"\" _unpublish_activity( committer, exploration_id, constants.ACTIVITY_TYPE_EXPLORATION) # Rights functions for collections.", "assignee_id: str. ID of the user whose role is being", "is private. Args: collection_id: str. ID of the collection. Returns:", "_update_activity_summary(activity_type, activity_rights) def _change_activity_status( committer_id, activity_id, activity_type, new_status, commit_message): \"\"\"Changes", "ACTIVITY_STATUS_PUBLIC, '%s published.' % activity_type) def _unpublish_activity(committer, activity_id, activity_type): \"\"\"Unpublishes", "\"\"\"Checks whether the user can delete given activity. Args: user:", "of the exploration. Returns: bool. Whether the exploration is public.", "activity is already publicly editable. Exception. The activity is already", "is translator of activity. Args: user_id: str or None. Id", "user in the system. Args: committer: UserActionsInfo. UserActionsInfo object for", "be translated by anyone.' % activity_type) activity_rights.translator_ids.append(assignee_id) if assignee_id in", "exp_models.ExplorationRightsModel( id=exploration_rights.id, owner_ids=exploration_rights.owner_ids, editor_ids=exploration_rights.editor_ids, translator_ids=exploration_rights.translator_ids, viewer_ids=exploration_rights.viewer_ids, community_owned=exploration_rights.community_owned, status=exploration_rights.status, viewable_if_private=exploration_rights.viewable_if_private, first_published_msec=exploration_rights.first_published_msec,", "there is no exploration matching the given ID. Returns: ActivityRights.", "return False def check_can_modify_activity_roles(user, activity_rights): \"\"\"Checks whether the user can", "translate this %s.' % activity_type) if activity_rights.community_owned: raise Exception( 'Community-owned", "utils.ValidationError( 'A user cannot be both an editor and a", "CMD_RELEASE_OWNERSHIP, }] _save_activity_rights( committer_id, activity_rights, activity_type, '%s ownership released to", "'cmd': cmd_type, 'old_status': old_status, 'new_status': new_status }] if new_status !=", "'translator_names': user_services.get_human_readable_user_ids( self.translator_ids), 'viewer_names': user_services.get_human_readable_user_ids( self.viewer_ids), 'viewable_if_private': self.viewable_if_private, } def", "activity_type) activity_rights.translator_ids.append(assignee_id) if assignee_id in activity_rights.viewer_ids: activity_rights.viewer_ids.remove(assignee_id) old_role = ROLE_VIEWER", "can translate this %s.' % activity_type) if activity_rights.community_owned: raise Exception(", "(role_services.ACTION_EDIT_ANY_PUBLIC_ACTIVITY in user.actions)): return True return False def check_can_translate_activity(user, activity_rights):", "committer_id, activity_rights, activity_type, commit_message, commit_cmds) _update_activity_summary(activity_type, activity_rights) def _publish_activity(committer, activity_id,", "= set(self.editor_ids).intersection(set(self.viewer_ids)) translator_viewer = set(self.editor_ids).intersection( set(self.viewer_ids)) if owner_editor: raise utils.ValidationError(", "% owner_viewer) if editor_translator: raise utils.ValidationError( 'A user cannot be", "# Rights functions for collections. def assign_role_for_collection( committer, collection_id, assignee_id,", "None). List of rights object containing ActivityRights object for existing", "committer, collection_id, assignee_id, new_role): \"\"\"Assign the given user to the", "can translate given activity. Args: user: UserActionsInfo. Object having user_id,", "\"\"\" return bool(user_id in self.owner_ids) def is_editor(self, user_id): \"\"\"Checks whether", "the committer. exploration_id: str. ID of the exploration. viewable_if_private: bool.", "self.status, 'community_owned': False, 'owner_names': user_services.get_human_readable_user_ids( self.owner_ids), 'editor_names': user_services.get_human_readable_user_ids( self.editor_ids), 'translator_names':", "'cloned_from': self.cloned_from, 'status': self.status, 'community_owned': True, 'owner_names': [], 'editor_names': [],", "role and subscribes the assignee to future collection updates. The", "'update_first_published_msec' ACTIVITY_STATUS_PRIVATE = constants.ACTIVITY_STATUS_PRIVATE ACTIVITY_STATUS_PUBLIC = constants.ACTIVITY_STATUS_PUBLIC ROLE_OWNER = 'owner'", "\"License\"); # you may not use this file except in", "activity. Exception. The activity is already publicly viewable. Exception. The", "the system. Args: committer: UserActionsInfo. UserActionsInfo object for the committer.", "_change_activity_status( committer_id, activity_id, activity_type, ACTIVITY_STATUS_PUBLIC, '%s published.' % activity_type) def", "if any of the owners, editors, translators and viewers lists", "Returns: bool. Whether the exploration is private or not. \"\"\"", "change its private viewability. if not check_can_publish_activity(committer, exploration_rights): logging.error( 'User", "= [{'cmd': CMD_CREATE_NEW}] collection_models.CollectionRightsModel( id=collection_rights.id, owner_ids=collection_rights.owner_ids, editor_ids=collection_rights.editor_ids, translator_ids=collection_rights.translator_ids, viewer_ids=collection_rights.viewer_ids, community_owned=collection_rights.community_owned,", "modify a role. Exception. The user already owns the activity.", "This could potentially throw an exception from _publish_activity. \"\"\" _publish_activity(", "translator_viewer = set(self.editor_ids).intersection( set(self.viewer_ids)) if owner_editor: raise utils.ValidationError( 'A user", "\"\"\"Domain object for the rights/publication status of an activity (an", "if model is None: return None return get_activity_rights_from_model( model, constants.ACTIVITY_TYPE_EXPLORATION)", "}] _save_activity_rights( committer_id, activity_rights, activity_type, '%s ownership released to the", "ID of the collection. Returns: list(str). Human-readable usernames (or truncated", "have release rights. \"\"\" committer_id = committer.user_id activity_rights = _get_activity_rights(activity_type,", "role to the user. Args: committer: UserActionsInfo. UserActionInfo object for", "ROLE_OWNER = 'owner' ROLE_EDITOR = 'editor' ROLE_TRANSLATOR = 'translator' ROLE_VIEWER", "role. Exception. The user already owns the activity. Exception. The", "activity_type) activity_rights.viewer_ids.append(assignee_id) else: raise Exception('Invalid role: %s' % new_role) commit_message", "activity. Returns: bool. Whether the given user can edit this", "activity_rights_model.viewer_ids, community_owned=activity_rights_model.community_owned, cloned_from=( activity_rights_model.cloned_from if activity_type == constants.ACTIVITY_TYPE_EXPLORATION else None),", "ROLE_VIEWER activity_id: str. ID of the activity. activity_type: str. The", "of activity. Possible values: constants.ACTIVITY_TYPE_EXPLORATION constants.ACTIVITY_TYPE_COLLECTION activity_id: str. ID of", "and saves it to the datastore. Subscribes the committer to", "raise Exception( 'Public %ss can be viewed by anyone.' %", "The type of activity. Possible values: constants.ACTIVITY_TYPE_EXPLORATION constants.ACTIVITY_TYPE_COLLECTION activity_id: str.", "committer_id = committer.user_id activity_rights = _get_activity_rights(activity_type, activity_id) if not check_can_unpublish_activity(committer,", "collection_rights.owner_ids) def is_collection_private(collection_id): \"\"\"Returns whether the collection is private. Args:", "= viewable_if_private commit_cmds = [{ 'cmd': CMD_CHANGE_PRIVATE_VIEWABILITY, 'old_viewable_if_private': old_viewable_if_private, 'new_viewable_if_private':", "collection_rights = ActivityRights( collection_id, [committer_id], [], [], []) commit_cmds =", "activity. \"\"\" if activity_rights is None: return False if activity_rights.cloned_from:", "for the given activity. Returns: bool. Whether the given user", "have no owners, ' 'editors, translators or viewers specified.') if", "the user can publish given activity. \"\"\" if activity_rights is", "of the given activity. Args: committer_id: str. ID of the", "time in msec', commit_cmds) def create_new_exploration_rights(exploration_id, committer_id): \"\"\"Creates a new", "\"\"\" model = exp_models.ExplorationRightsModel.get( exploration_id, strict=strict) if model is None:", "def __init__( self, exploration_id, owner_ids, editor_ids, translator_ids, viewer_ids, community_owned=False, cloned_from=None,", "can translate this activity. \"\"\" if activity_rights is None: return", "utils.ValidationError( 'Community-owned explorations cannot be private.') if self.status != ACTIVITY_STATUS_PRIVATE", "_release_ownership_of_activity. \"\"\" _release_ownership_of_activity( committer, exploration_id, constants.ACTIVITY_TYPE_EXPLORATION) def set_private_viewability_of_exploration( committer, exploration_id,", "this collection. \"\"\" collection_rights = get_collection_rights(collection_id) return user_services.get_human_readable_user_ids( collection_rights.owner_ids) def", "all changes to how these cmds are interpreted preserve #", "if activity_type == constants.ACTIVITY_TYPE_EXPLORATION: model_cls = exp_models.ExplorationRightsModel elif activity_type ==", "unknown activity type: %s' % ( activity_type)) def check_can_access_activity(user, activity_rights):", "commit_cmds) _update_activity_summary(activity_type, activity_rights) def _publish_activity(committer, activity_id, activity_type): \"\"\"Publishes the given", "collection updates. The caller should ensure that assignee_id corresponds to", "clone of another exploration. \"\"\" exploration_rights = get_exploration_rights(exploration_id) return bool(exploration_rights.cloned_from)", "collections. def assign_role_for_collection( committer, collection_id, assignee_id, new_role): \"\"\"Assign the given", "addresses) of owners for this collection. \"\"\" collection_rights = get_collection_rights(collection_id)", "an error if there is no exploration matching the given", "exploration. Raises: Exception. This could potentially throw an exception from", "The exploration with ID exploration_id was not found in the", "activity_rights): \"\"\"Checks whether the user can delete given activity. Args:", "'This user already can translate this %s.' % activity_type) if" ]
[ "# executed at runtime def cast(type_, value): # noqa return", "be imported at runtime and used in that fashion -", "used to remove the need for the types to be", "to remove the need for the types to be accessible", "TYPE_CHECKING = False # pragma: no cover # typing's cast", "the False-y guard in a nicely named fashion so that", "executed at runtime from typing import cast else: # executed", "# not executed at runtime from typing import cast else:", "# runtime behavior in a block that is ignored by", "import ... Ref: https://github.com/python/mypy/issues/3216 \"\"\" __all__ = [\"TYPE_CHECKING\", \"cast\"] #", "The TYPE_CHECKING constant defined by the typing module is False", "re-implement typing.cast's # runtime behavior in a block that is", "not expect it to be present. To work around this,", "to be accessible directly during runtime. This module provides the", "a nicely named fashion so that a curious maintainer can", "# want to import typing at runtime. Here, we inform", "around this, mypy allows the typing import to be behind", "# we're importing `typing.cast` as `cast` and re-implement typing.cast's #", "used in that fashion - it acts as a no-op", "does not have any run-time overhead by design. As it", "implementing static typing in packaging. `mypy` - the static type", "checking. TYPE_CHECKING = False # pragma: no cover # typing's", "not executed at runtime from typing import cast else: #", "and type-comments can be used to remove the need for", "# but True while type checking. TYPE_CHECKING = False #", "that is ignored by type checkers. if TYPE_CHECKING: # pragma:", "fundamental to mypy's functioning. Generally, `typing` would be imported at", "Python 2/Python 3. Thus, this codebase can not expect it", "optional to prevent it from running at runtime and type-comments", "import TYPE_CHECKING if TYPE_CHECKING: from typing import ... Ref: https://github.com/python/mypy/issues/3216", "to prevent it from running at runtime and type-comments can", "module is False at runtime # but True while type", "3. Thus, this codebase can not expect it to be", "be guarded as follows: from packaging._typing import TYPE_CHECKING if TYPE_CHECKING:", "would be imported at runtime and used in that fashion", "running at runtime and type-comments can be used to remove", "defined by the typing module is False at runtime #", "typing import ... Ref: https://github.com/python/mypy/issues/3216 \"\"\" __all__ = [\"TYPE_CHECKING\", \"cast\"]", "no cover # not executed at runtime from typing import", "during runtime. This module provides the False-y guard in a", "work around this, mypy allows the typing import to be", "we inform the type checkers that # we're importing `typing.cast`", "runtime behavior in a block that is ignored by type", "Here, we inform the type checkers that # we're importing", "checkers. if TYPE_CHECKING: # pragma: no cover # not executed", "calling typing.cast at runtime, but we don't # want to", "by design. As it turns out, `typing` is not vendorable", "uses separate sources for Python 2/Python 3. Thus, this codebase", "syntax requires calling typing.cast at runtime, but we don't #", "typing in packaging. `mypy` - the static type analysis tool", "type analysis tool we use - uses the `typing` module,", "functionality fundamental to mypy's functioning. Generally, `typing` would be imported", "TYPE_CHECKING constant defined by the typing module is False at", "uses the `typing` module, which provides core functionality fundamental to", "runtime. This module provides the False-y guard in a nicely", "imports should be guarded as follows: from packaging._typing import TYPE_CHECKING", "sources for Python 2/Python 3. Thus, this codebase can not", "runtime and type-comments can be used to remove the need", "checkers that # we're importing `typing.cast` as `cast` and re-implement", "it acts as a no-op at runtime and does not", "all static-typing related imports should be guarded as follows: from", "= False # pragma: no cover # typing's cast syntax", "type checkers. if TYPE_CHECKING: # pragma: no cover # not", "in packaging. `mypy` - the static type analysis tool we", "False-y optional to prevent it from running at runtime and", "accessible directly during runtime. This module provides the False-y guard", "To work around this, mypy allows the typing import to", "packaging. `mypy` - the static type analysis tool we use", "no cover # typing's cast syntax requires calling typing.cast at", "at runtime and type-comments can be used to remove the", "This module provides the False-y guard in a nicely named", "typing's cast syntax requires calling typing.cast at runtime, but we", "if TYPE_CHECKING: # pragma: no cover # not executed at", "\"cast\"] # The TYPE_CHECKING constant defined by the typing module", "pragma: no cover # not executed at runtime from typing", "guarded as follows: from packaging._typing import TYPE_CHECKING if TYPE_CHECKING: from", "- it uses separate sources for Python 2/Python 3. Thus,", "that # we're importing `typing.cast` as `cast` and re-implement typing.cast's", "typing.cast's # runtime behavior in a block that is ignored", "typing import to be behind a False-y optional to prevent", "__all__ = [\"TYPE_CHECKING\", \"cast\"] # The TYPE_CHECKING constant defined by", "we don't # want to import typing at runtime. Here,", "to be behind a False-y optional to prevent it from", "types to be accessible directly during runtime. This module provides", "so that a curious maintainer can reach here to read", "[\"TYPE_CHECKING\", \"cast\"] # The TYPE_CHECKING constant defined by the typing", "analysis tool we use - uses the `typing` module, which", "we use - uses the `typing` module, which provides core", "imported at runtime and used in that fashion - it", "Thus, this codebase can not expect it to be present.", "it to be present. To work around this, mypy allows", "here to read this. In packaging, all static-typing related imports", "at runtime # but True while type checking. TYPE_CHECKING =", "TYPE_CHECKING if TYPE_CHECKING: from typing import ... Ref: https://github.com/python/mypy/issues/3216 \"\"\"", "tool we use - uses the `typing` module, which provides", "any run-time overhead by design. As it turns out, `typing`", "provides core functionality fundamental to mypy's functioning. Generally, `typing` would", "# pragma: no cover # typing's cast syntax requires calling", "by type checkers. if TYPE_CHECKING: # pragma: no cover #", "directly during runtime. This module provides the False-y guard in", "- it acts as a no-op at runtime and does", "from packaging._typing import TYPE_CHECKING if TYPE_CHECKING: from typing import ...", "a False-y optional to prevent it from running at runtime", "the typing import to be behind a False-y optional to", "behavior in a block that is ignored by type checkers.", "behind a False-y optional to prevent it from running at", "it uses separate sources for Python 2/Python 3. Thus, this", "curious maintainer can reach here to read this. In packaging,", "this, mypy allows the typing import to be behind a", "at runtime, but we don't # want to import typing", "separate sources for Python 2/Python 3. Thus, this codebase can", "\"\"\" __all__ = [\"TYPE_CHECKING\", \"cast\"] # The TYPE_CHECKING constant defined", "constant defined by the typing module is False at runtime", "related imports should be guarded as follows: from packaging._typing import", "should be guarded as follows: from packaging._typing import TYPE_CHECKING if", "runtime. Here, we inform the type checkers that # we're", "allows the typing import to be behind a False-y optional", "typing.cast at runtime, but we don't # want to import", "be behind a False-y optional to prevent it from running", "don't # want to import typing at runtime. Here, we", "is not vendorable - it uses separate sources for Python", "out, `typing` is not vendorable - it uses separate sources", "Ref: https://github.com/python/mypy/issues/3216 \"\"\" __all__ = [\"TYPE_CHECKING\", \"cast\"] # The TYPE_CHECKING", "nicely named fashion so that a curious maintainer can reach", "but True while type checking. TYPE_CHECKING = False # pragma:", "mypy's functioning. Generally, `typing` would be imported at runtime and", "cast syntax requires calling typing.cast at runtime, but we don't", "in a block that is ignored by type checkers. if", "Generally, `typing` would be imported at runtime and used in", "as a no-op at runtime and does not have any", "2/Python 3. Thus, this codebase can not expect it to", "False # pragma: no cover # typing's cast syntax requires", "for Python 2/Python 3. Thus, this codebase can not expect", "typing import cast else: # executed at runtime def cast(type_,", "TYPE_CHECKING: from typing import ... Ref: https://github.com/python/mypy/issues/3216 \"\"\" __all__ =", "maintainer can reach here to read this. In packaging, all", "this. In packaging, all static-typing related imports should be guarded", "and does not have any run-time overhead by design. As", "be used to remove the need for the types to", "from typing import ... Ref: https://github.com/python/mypy/issues/3216 \"\"\" __all__ = [\"TYPE_CHECKING\",", "fashion - it acts as a no-op at runtime and", "static type analysis tool we use - uses the `typing`", "follows: from packaging._typing import TYPE_CHECKING if TYPE_CHECKING: from typing import", "need for the types to be accessible directly during runtime.", "while type checking. TYPE_CHECKING = False # pragma: no cover", "requires calling typing.cast at runtime, but we don't # want", "import typing at runtime. Here, we inform the type checkers", "to import typing at runtime. Here, we inform the type", "from typing import cast else: # executed at runtime def", "the type checkers that # we're importing `typing.cast` as `cast`", "we're importing `typing.cast` as `cast` and re-implement typing.cast's # runtime", "`cast` and re-implement typing.cast's # runtime behavior in a block", "importing `typing.cast` as `cast` and re-implement typing.cast's # runtime behavior", "have any run-time overhead by design. As it turns out,", "not vendorable - it uses separate sources for Python 2/Python", "# The TYPE_CHECKING constant defined by the typing module is", "= [\"TYPE_CHECKING\", \"cast\"] # The TYPE_CHECKING constant defined by the", "False at runtime # but True while type checking. TYPE_CHECKING", "in that fashion - it acts as a no-op at", "to read this. In packaging, all static-typing related imports should", "# typing's cast syntax requires calling typing.cast at runtime, but", "`typing` would be imported at runtime and used in that", "runtime and does not have any run-time overhead by design.", "provides the False-y guard in a nicely named fashion so", "a curious maintainer can reach here to read this. In", "be accessible directly during runtime. This module provides the False-y", "- uses the `typing` module, which provides core functionality fundamental", "not have any run-time overhead by design. As it turns", "expect it to be present. To work around this, mypy", "present. To work around this, mypy allows the typing import", "the `typing` module, which provides core functionality fundamental to mypy's", "- the static type analysis tool we use - uses", "ignored by type checkers. if TYPE_CHECKING: # pragma: no cover", "\"\"\"For neatly implementing static typing in packaging. `mypy` - the", "TYPE_CHECKING: # pragma: no cover # not executed at runtime", "prevent it from running at runtime and type-comments can be", "in a nicely named fashion so that a curious maintainer", "packaging, all static-typing related imports should be guarded as follows:", "`mypy` - the static type analysis tool we use -", "that fashion - it acts as a no-op at runtime", "if TYPE_CHECKING: from typing import ... Ref: https://github.com/python/mypy/issues/3216 \"\"\" __all__", "# pragma: no cover # not executed at runtime from", "vendorable - it uses separate sources for Python 2/Python 3.", "it from running at runtime and type-comments can be used", "a block that is ignored by type checkers. if TYPE_CHECKING:", "that a curious maintainer can reach here to read this.", "can reach here to read this. In packaging, all static-typing", "which provides core functionality fundamental to mypy's functioning. Generally, `typing`", "at runtime and does not have any run-time overhead by", "remove the need for the types to be accessible directly", "but we don't # want to import typing at runtime.", "want to import typing at runtime. Here, we inform the", "for the types to be accessible directly during runtime. This", "`typing` is not vendorable - it uses separate sources for", "mypy allows the typing import to be behind a False-y", "a no-op at runtime and does not have any run-time", "read this. In packaging, all static-typing related imports should be", "reach here to read this. In packaging, all static-typing related", "cover # typing's cast syntax requires calling typing.cast at runtime,", "and re-implement typing.cast's # runtime behavior in a block that", "block that is ignored by type checkers. if TYPE_CHECKING: #", "type checking. TYPE_CHECKING = False # pragma: no cover #", "import cast else: # executed at runtime def cast(type_, value):", "as follows: from packaging._typing import TYPE_CHECKING if TYPE_CHECKING: from typing", "True while type checking. TYPE_CHECKING = False # pragma: no", "type checkers that # we're importing `typing.cast` as `cast` and", "type-comments can be used to remove the need for the", "is ignored by type checkers. if TYPE_CHECKING: # pragma: no", "core functionality fundamental to mypy's functioning. Generally, `typing` would be", "pragma: no cover # typing's cast syntax requires calling typing.cast", "`typing.cast` as `cast` and re-implement typing.cast's # runtime behavior in", "the static type analysis tool we use - uses the", "can not expect it to be present. To work around", "import to be behind a False-y optional to prevent it", "the need for the types to be accessible directly during", "as `cast` and re-implement typing.cast's # runtime behavior in a", "to mypy's functioning. Generally, `typing` would be imported at runtime", "it turns out, `typing` is not vendorable - it uses", "at runtime. Here, we inform the type checkers that #", "As it turns out, `typing` is not vendorable - it", "typing at runtime. Here, we inform the type checkers that", "module provides the False-y guard in a nicely named fashion", "this codebase can not expect it to be present. To", "named fashion so that a curious maintainer can reach here", "static typing in packaging. `mypy` - the static type analysis", "turns out, `typing` is not vendorable - it uses separate", "static-typing related imports should be guarded as follows: from packaging._typing", "... Ref: https://github.com/python/mypy/issues/3216 \"\"\" __all__ = [\"TYPE_CHECKING\", \"cast\"] # The", "runtime from typing import cast else: # executed at runtime", "False-y guard in a nicely named fashion so that a", "`typing` module, which provides core functionality fundamental to mypy's functioning.", "functioning. Generally, `typing` would be imported at runtime and used", "from running at runtime and type-comments can be used to", "https://github.com/python/mypy/issues/3216 \"\"\" __all__ = [\"TYPE_CHECKING\", \"cast\"] # The TYPE_CHECKING constant", "packaging._typing import TYPE_CHECKING if TYPE_CHECKING: from typing import ... Ref:", "cast else: # executed at runtime def cast(type_, value): #", "runtime and used in that fashion - it acts as", "at runtime and used in that fashion - it acts", "guard in a nicely named fashion so that a curious", "overhead by design. As it turns out, `typing` is not", "module, which provides core functionality fundamental to mypy's functioning. Generally,", "acts as a no-op at runtime and does not have", "inform the type checkers that # we're importing `typing.cast` as", "can be used to remove the need for the types", "at runtime from typing import cast else: # executed at", "runtime, but we don't # want to import typing at", "the types to be accessible directly during runtime. This module", "no-op at runtime and does not have any run-time overhead", "is False at runtime # but True while type checking.", "design. As it turns out, `typing` is not vendorable -", "by the typing module is False at runtime # but", "codebase can not expect it to be present. To work", "fashion so that a curious maintainer can reach here to", "In packaging, all static-typing related imports should be guarded as", "the typing module is False at runtime # but True", "and used in that fashion - it acts as a", "cover # not executed at runtime from typing import cast", "executed at runtime def cast(type_, value): # noqa return value", "run-time overhead by design. As it turns out, `typing` is", "to be present. To work around this, mypy allows the", "runtime # but True while type checking. TYPE_CHECKING = False", "else: # executed at runtime def cast(type_, value): # noqa", "be present. To work around this, mypy allows the typing", "neatly implementing static typing in packaging. `mypy` - the static", "use - uses the `typing` module, which provides core functionality", "typing module is False at runtime # but True while" ]
[ "== 0 or send_ui): can_sends.append(create_ui_command(self.packer, steer_alert, pcm_cancel_cmd, left_line, right_line, left_lane_depart,", "if frame % 100 == 0 and CS.CP.enableDsu: can_sends.append(create_fcw_command(self.packer, fcw_alert))", "actuators.steeringAngleDeg, apply_steer_req, frame // 2)) # we can spam can", "value and gas cmd. # This prevents unexpected pedal range", "42Hz, with counter adding alternatively 1 and 2; # sending", "msgs *** #print(\"steer {0} {1} {2} {3}\".format(apply_steer, min_lim, max_lim, CS.steer_torque_motor)", "selfdrive.car.toyota.toyotacan import create_steer_command, create_ui_command, \\ create_accel_command, create_acc_cancel_command, \\ create_fcw_command, create_lta_steer_command", "and CS.CP.carFingerprint in [CAR.LEXUS_IS, CAR.LEXUS_RC]: can_sends.append(create_acc_cancel_command(self.packer)) elif CS.CP.openpilotLongitudinalControl: can_sends.append(create_accel_command(self.packer, pcm_accel_cmd,", "or CS.out.vEgo < 12. # at low speed we always", "MIN_ACC_SPEED + PEDAL_TRANSITION], [0.4, 0.5, 0.0]) # offset for creep", "entered standstill or it's disabled self.standstill_req = False self.last_steer =", "or steer_alert) and self.alert_active): send_ui = True self.alert_active = not", "can spam can to cancel the system even if we", "unexpected pedal range rescaling can_sends.append(create_gas_interceptor_command(self.packer, interceptor_gas_cmd, frame // 2)) self.gas", "2)) # can_sends.append(create_lta_steer_command(self.packer, actuators.steeringAngleDeg, apply_steer_req, frame // 2)) # we", "a good sound instead send_ui = True if (frame %", "apply_steer / CarControllerParams.STEER_MAX new_actuators.accel = self.accel new_actuators.gas = self.gas return", "*** #print(\"steer {0} {1} {2} {3}\".format(apply_steer, min_lim, max_lim, CS.steer_torque_motor) #", "common.numpy_fast import clip, interp from selfdrive.car import apply_toyota_steer_torque_limits, create_gas_interceptor_command, make_can_msg", "= 0 apply_steer_req = 0 else: apply_steer_req = 1 #", "alternatively 1 and 2; # sending it at 100Hz seem", "can_sends.append(create_steer_command(self.packer, 0, 0, frame // 2)) # can_sends.append(create_lta_steer_command(self.packer, actuators.steeringAngleDeg, apply_steer_req,", "can_sends.append(create_ui_command(self.packer, steer_alert, pcm_cancel_cmd, left_line, right_line, left_lane_depart, right_lane_depart, enabled)) if frame", "clip(pedal_command, 0., MAX_INTERCEPTOR_GAS) else: interceptor_gas_cmd = 0. pcm_accel_cmd = clip(actuators.accel,", "// 2)) # LTA mode. Set ret.steerControlType = car.CarParams.SteerControlType.angle and", "\\ MIN_ACC_SPEED, PEDAL_TRANSITION, CarControllerParams from opendbc.can.packer import CANPacker from common.op_params", "% 2 == 0 and CS.CP.carFingerprint in TSS2_CAR: can_sends.append(create_lta_steer_command(self.packer, 0,", "self.gas = interceptor_gas_cmd # ui mesg is at 100Hz but", "CS.CP.openpilotLongitudinalControl) or pcm_cancel_cmd: lead = lead or CS.out.vEgo < 12.", "fr_step, vl) in STATIC_DSU_MSGS: if frame % fr_step == 0", "entering standstill, send standstill request if CS.out.standstill and not self.last_standstill", "hud_alert in [VisualAlert.steerRequired, VisualAlert.ldw] send_ui = False if ((fcw_alert or", "vl, bus)) new_actuators = actuators.copy() new_actuators.steer = apply_steer / CarControllerParams.STEER_MAX", "import CAR, STATIC_DSU_MSGS, NO_STOP_TIMER_CAR, TSS2_CAR, \\ MIN_ACC_SPEED, PEDAL_TRANSITION, CarControllerParams from", "CS.CP.carFingerprint in [CAR.LEXUS_IS, CAR.LEXUS_RC]: can_sends.append(create_acc_cancel_command(self.packer)) elif CS.CP.openpilotLongitudinalControl: can_sends.append(create_accel_command(self.packer, pcm_accel_cmd, pcm_cancel_cmd,", "= new_steer != apply_steer # Cut steering while we're in", "0. pcm_accel_cmd = clip(actuators.accel, CarControllerParams.ACCEL_MIN, CarControllerParams.ACCEL_MAX) # steer torque new_steer", "control if (frame % 3 == 0 and CS.CP.openpilotLongitudinalControl) or", "in NO_STOP_TIMER_CAR and not self.standstill_hack: self.standstill_req = True if CS.pcm_acc_status", "self.last_standstill and CS.CP.carFingerprint not in NO_STOP_TIMER_CAR and not self.standstill_hack: self.standstill_req", "left_line, right_line, lead, left_lane_depart, right_lane_depart): # gas and brake if", "clip(actuators.accel, CarControllerParams.ACCEL_MIN, CarControllerParams.ACCEL_MAX) # steer torque new_steer = int(round(actuators.steer *", "at 42Hz, with counter adding alternatively 1 and 2; #", "CAR.HIGHLANDER, CAR.HIGHLANDERH]: PEDAL_SCALE = interp(CS.out.vEgo, [0.0, MIN_ACC_SPEED, MIN_ACC_SPEED + PEDAL_TRANSITION],", "= False if ((fcw_alert or steer_alert) and not self.alert_active) or", "% 3 == 0 and CS.CP.openpilotLongitudinalControl) or pcm_cancel_cmd: lead =", "the pcm to disengage causes a bad fault sound so", "and not self.standstill_hack: self.standstill_req = True if CS.pcm_acc_status != 8:", "brake if CS.CP.enableGasInterceptor and enabled: MAX_INTERCEPTOR_GAS = 0.5 # RAV4", "= [] #*** control msgs *** #print(\"steer {0} {1} {2}", "with counter adding alternatively 1 and 2; # sending it", "mesg is at 100Hz but we send asap if: #", "# TODO: probably can delete this. CS.pcm_acc_status uses a different", "((fcw_alert or steer_alert) and not self.alert_active) or \\ (not (fcw_alert", "# sending it at 100Hz seem to allow a higher", "(addr, cars, bus, fr_step, vl) in STATIC_DSU_MSGS: if frame %", "TSS2_CAR: can_sends.append(create_lta_steer_command(self.packer, 0, 0, frame // 2)) # LTA mode.", "NO_STOP_TIMER_CAR and not self.standstill_hack: self.standstill_req = True if CS.pcm_acc_status !=", "stop displaying fcw_alert = hud_alert == VisualAlert.fcw steer_alert = hud_alert", "not self.alert_active) or \\ (not (fcw_alert or steer_alert) and self.alert_active):", "\\ create_accel_command, create_acc_cancel_command, \\ create_fcw_command, create_lta_steer_command from selfdrive.car.toyota.values import CAR,", "CS.out.steeringTorqueEps, CarControllerParams) self.steer_rate_limited = new_steer != apply_steer # Cut steering", "limit seems imposed # on consecutive messages can_sends.append(create_steer_command(self.packer, apply_steer, apply_steer_req,", "2)) # we can spam can to cancel the system", "<filename>selfdrive/car/toyota/carcontroller.py from cereal import car from common.numpy_fast import clip, interp", "STATIC_DSU_MSGS: if frame % fr_step == 0 and CS.CP.enableDsu and", "pcm_accel_cmd = clip(actuators.accel, CarControllerParams.ACCEL_MIN, CarControllerParams.ACCEL_MAX) # steer torque new_steer =", "#print(\"steer {0} {1} {2} {3}\".format(apply_steer, min_lim, max_lim, CS.steer_torque_motor) # toyota", "steer_alert) and not self.alert_active) or \\ (not (fcw_alert or steer_alert)", "PEDAL_TRANSITION], [0.3, 0.4, 0.0]) else: PEDAL_SCALE = interp(CS.out.vEgo, [0.0, MIN_ACC_SPEED,", "CS.CP.enableGasInterceptor and CS.CP.openpilotLongitudinalControl: # send exactly zero if gas cmd", "limit, as the rate limit seems imposed # on consecutive", "send the max between read value and gas cmd. #", "3 == 0 and CS.CP.openpilotLongitudinalControl) or pcm_cancel_cmd: lead = lead", "bad fault sound so play a good sound instead send_ui", "in cars: can_sends.append(make_can_msg(addr, vl, bus)) new_actuators = actuators.copy() new_actuators.steer =", "hud_alert, left_line, right_line, lead, left_lane_depart, right_lane_depart): # gas and brake", "we send asap if: # - there is something to", "0, pcm_cancel_cmd, False, lead, CS.acc_type, CS.distance_btn)) if frame % 2", "+ PEDAL_TRANSITION], [0.3, 0.4, 0.0]) else: PEDAL_SCALE = interp(CS.out.vEgo, [0.0,", "and CS.CP.carFingerprint not in NO_STOP_TIMER_CAR and not self.standstill_hack: self.standstill_req =", "# pcm entered standstill or it's disabled self.standstill_req = False", "can be engaged # Lexus IS uses a different cancellation", "at 100Hz but we send asap if: # - there", "self.steer_rate_limited = new_steer != apply_steer # Cut steering while we're", "range rescaling can_sends.append(create_gas_interceptor_command(self.packer, interceptor_gas_cmd, frame // 2)) self.gas = interceptor_gas_cmd", "25] or abs(CS.out.steeringRateDeg) > 100: apply_steer = 0 apply_steer_req =", "self.standstill_req = False self.last_steer = apply_steer self.last_standstill = CS.out.standstill can_sends", "# *** static msgs *** for (addr, cars, bus, fr_step,", "different cancellation message if pcm_cancel_cmd and CS.CP.carFingerprint in [CAR.LEXUS_IS, CAR.LEXUS_RC]:", "and CS.CP.carFingerprint in cars: can_sends.append(make_can_msg(addr, vl, bus)) new_actuators = actuators.copy()", "request if CS.out.standstill and not self.last_standstill and CS.CP.carFingerprint not in", "pcm_cancel_cmd, self.standstill_req, lead, CS.acc_type, CS.distance_btn)) self.accel = pcm_accel_cmd else: can_sends.append(create_accel_command(self.packer,", "car.CarControl.HUDControl.VisualAlert class CarController(): def __init__(self, dbc_name, CP, VM): self.last_steer =", "sound so play a good sound instead send_ui = True", "if gas cmd is zero. Interceptor will send the max", "0 apply_steer_req = 0 else: apply_steer_req = 1 # TODO:", "is present so ACC can be engaged # Lexus IS", "% 2 == 0: # can_sends.append(create_steer_command(self.packer, 0, 0, frame //", "CS.distance_btn)) if frame % 2 == 0 and CS.CP.enableGasInterceptor and", "panda # if frame % 2 == 0: # can_sends.append(create_steer_command(self.packer,", "0.0]) # offset for creep and windbrake pedal_offset = interp(CS.out.vEgo,", "right_line, lead, left_lane_depart, right_lane_depart): # gas and brake if CS.CP.enableGasInterceptor", "not in NO_STOP_TIMER_CAR and not self.standstill_hack: self.standstill_req = True if", "= 1 # TODO: probably can delete this. CS.pcm_acc_status uses", "[9, 25] or abs(CS.out.steeringRateDeg) > 100: apply_steer = 0 apply_steer_req", "update(self, enabled, active, CS, frame, actuators, pcm_cancel_cmd, hud_alert, left_line, right_line,", "CS.cruiseState.enabled. confirm they're not meaningfully different if not enabled and", "or steer_alert) and not self.alert_active) or \\ (not (fcw_alert or", "something to stop displaying fcw_alert = hud_alert == VisualAlert.fcw steer_alert", "# RAV4 has very sensitive gas pedal if CS.CP.carFingerprint in", "or send_ui): can_sends.append(create_ui_command(self.packer, steer_alert, pcm_cancel_cmd, left_line, right_line, left_lane_depart, right_lane_depart, enabled))", "[0.0, 2.3, MIN_ACC_SPEED + PEDAL_TRANSITION], [-.4, 0.0, 0.2]) pedal_command =", "self.alert_active = False self.last_standstill = False self.standstill_req = False self.steer_rate_limited", "can_sends.append(create_acc_cancel_command(self.packer)) elif CS.CP.openpilotLongitudinalControl: can_sends.append(create_accel_command(self.packer, pcm_accel_cmd, pcm_cancel_cmd, self.standstill_req, lead, CS.acc_type, CS.distance_btn))", "# - there is something to display # - there", "we always assume the lead is present so ACC can", "0 self.accel = 0 def update(self, enabled, active, CS, frame,", "windbrake pedal_offset = interp(CS.out.vEgo, [0.0, 2.3, MIN_ACC_SPEED + PEDAL_TRANSITION], [-.4,", "== 0 and CS.CP.enableGasInterceptor and CS.CP.openpilotLongitudinalControl: # send exactly zero", "apply_steer # Cut steering while we're in a known fault", "0.4, 0.0]) else: PEDAL_SCALE = interp(CS.out.vEgo, [0.0, MIN_ACC_SPEED, MIN_ACC_SPEED +", "# than CS.cruiseState.enabled. confirm they're not meaningfully different if not", "spam can to cancel the system even if we are", "car from common.numpy_fast import clip, interp from selfdrive.car import apply_toyota_steer_torque_limits,", "[0.0, MIN_ACC_SPEED, MIN_ACC_SPEED + PEDAL_TRANSITION], [0.3, 0.4, 0.0]) else: PEDAL_SCALE", "# - there is something to stop displaying fcw_alert =", "frame, actuators, pcm_cancel_cmd, hud_alert, left_line, right_line, lead, left_lane_depart, right_lane_depart): #", "in [CAR.COROLLA]: PEDAL_SCALE = interp(CS.out.vEgo, [0.0, MIN_ACC_SPEED, MIN_ACC_SPEED + PEDAL_TRANSITION],", "0 else: apply_steer_req = 1 # TODO: probably can delete", "asap if: # - there is something to display #", "if CS.CP.enableGasInterceptor and enabled: MAX_INTERCEPTOR_GAS = 0.5 # RAV4 has", "if: # - there is something to display # -", "= apply_steer / CarControllerParams.STEER_MAX new_actuators.accel = self.accel new_actuators.gas = self.gas", "left_lane_depart, right_lane_depart): # gas and brake if CS.CP.enableGasInterceptor and enabled:", "self.last_standstill = CS.out.standstill can_sends = [] #*** control msgs ***", "disengage causes a bad fault sound so play a good", "pedal_offset = interp(CS.out.vEgo, [0.0, 2.3, MIN_ACC_SPEED + PEDAL_TRANSITION], [-.4, 0.0,", "cars: can_sends.append(make_can_msg(addr, vl, bus)) new_actuators = actuators.copy() new_actuators.steer = apply_steer", "ACC can be engaged # Lexus IS uses a different", "= CANPacker(dbc_name) self.gas = 0 self.accel = 0 def update(self,", "PEDAL_SCALE * (actuators.accel + pedal_offset) interceptor_gas_cmd = clip(pedal_command, 0., MAX_INTERCEPTOR_GAS)", "Set ret.steerControlType = car.CarParams.SteerControlType.angle and whitelist 0x191 in the panda", "if (frame % 100 == 0 or send_ui): can_sends.append(create_ui_command(self.packer, steer_alert,", "if frame % 2 == 0 and CS.CP.enableGasInterceptor and CS.CP.openpilotLongitudinalControl:", "CS.CP.carFingerprint in TSS2_CAR: can_sends.append(create_lta_steer_command(self.packer, 0, 0, frame // 2)) #", "frame // 2)) self.gas = interceptor_gas_cmd # ui mesg is", "[0.0, MIN_ACC_SPEED, MIN_ACC_SPEED + PEDAL_TRANSITION], [0.15, 0.3, 0.0]) elif CS.CP.carFingerprint", "interceptor_gas_cmd = 0. pcm_accel_cmd = clip(actuators.accel, CarControllerParams.ACCEL_MIN, CarControllerParams.ACCEL_MAX) # steer", "% 100 == 0 or send_ui): can_sends.append(create_ui_command(self.packer, steer_alert, pcm_cancel_cmd, left_line,", "+ PEDAL_TRANSITION], [-.4, 0.0, 0.2]) pedal_command = PEDAL_SCALE * (actuators.accel", "there is something to stop displaying fcw_alert = hud_alert ==", "using lat only control if (frame % 3 == 0", "0.3, 0.0]) elif CS.CP.carFingerprint in [CAR.COROLLA]: PEDAL_SCALE = interp(CS.out.vEgo, [0.0,", "and not self.alert_active) or \\ (not (fcw_alert or steer_alert) and", "# steer torque new_steer = int(round(actuators.steer * CarControllerParams.STEER_MAX)) apply_steer =", "if not enabled or CS.steer_state in [9, 25] or abs(CS.out.steeringRateDeg)", "/ CarControllerParams.STEER_MAX new_actuators.accel = self.accel new_actuators.gas = self.gas return new_actuators,", "* (actuators.accel + pedal_offset) interceptor_gas_cmd = clip(pedal_command, 0., MAX_INTERCEPTOR_GAS) else:", "#*** control msgs *** #print(\"steer {0} {1} {2} {3}\".format(apply_steer, min_lim,", "even if we are using lat only control if (frame", "control msgs *** #print(\"steer {0} {1} {2} {3}\".format(apply_steer, min_lim, max_lim,", "* CarControllerParams.STEER_MAX)) apply_steer = apply_toyota_steer_torque_limits(new_steer, self.last_steer, CS.out.steeringTorqueEps, CarControllerParams) self.steer_rate_limited =", "always assume the lead is present so ACC can be", "uses a different signal # than CS.cruiseState.enabled. confirm they're not", "interp(CS.out.vEgo, [0.0, MIN_ACC_SPEED, MIN_ACC_SPEED + PEDAL_TRANSITION], [0.15, 0.3, 0.0]) elif", "enabled: MAX_INTERCEPTOR_GAS = 0.5 # RAV4 has very sensitive gas", "create_ui_command, \\ create_accel_command, create_acc_cancel_command, \\ create_fcw_command, create_lta_steer_command from selfdrive.car.toyota.values import", "= True if (frame % 100 == 0 or send_ui):", "= car.CarParams.SteerControlType.angle and whitelist 0x191 in the panda # if", "MIN_ACC_SPEED, MIN_ACC_SPEED + PEDAL_TRANSITION], [0.3, 0.4, 0.0]) else: PEDAL_SCALE =", "gas cmd is zero. Interceptor will send the max between", "lead or CS.out.vEgo < 12. # at low speed we", "0 or send_ui): can_sends.append(create_ui_command(self.packer, steer_alert, pcm_cancel_cmd, left_line, right_line, left_lane_depart, right_lane_depart,", "very sensitive gas pedal if CS.CP.carFingerprint in [CAR.RAV4, CAR.RAV4H, CAR.HIGHLANDER,", "can_sends.append(create_accel_command(self.packer, 0, pcm_cancel_cmd, False, lead, CS.acc_type, CS.distance_btn)) if frame %", "% 100 == 0 and CS.CP.enableDsu: can_sends.append(create_fcw_command(self.packer, fcw_alert)) # ***", "interp(CS.out.vEgo, [0.0, MIN_ACC_SPEED, MIN_ACC_SPEED + PEDAL_TRANSITION], [0.3, 0.4, 0.0]) else:", "+ PEDAL_TRANSITION], [0.15, 0.3, 0.0]) elif CS.CP.carFingerprint in [CAR.COROLLA]: PEDAL_SCALE", "apply_steer self.last_standstill = CS.out.standstill can_sends = [] #*** control msgs", "read value and gas cmd. # This prevents unexpected pedal", "lead = lead or CS.out.vEgo < 12. # at low", "(frame % 3 == 0 and CS.CP.openpilotLongitudinalControl) or pcm_cancel_cmd: lead", "*** for (addr, cars, bus, fr_step, vl) in STATIC_DSU_MSGS: if", "0., MAX_INTERCEPTOR_GAS) else: interceptor_gas_cmd = 0. pcm_accel_cmd = clip(actuators.accel, CarControllerParams.ACCEL_MIN,", "= interp(CS.out.vEgo, [0.0, MIN_ACC_SPEED, MIN_ACC_SPEED + PEDAL_TRANSITION], [0.4, 0.5, 0.0])", "(not (fcw_alert or steer_alert) and self.alert_active): send_ui = True self.alert_active", "CarControllerParams) self.steer_rate_limited = new_steer != apply_steer # Cut steering while", "= apply_toyota_steer_torque_limits(new_steer, self.last_steer, CS.out.steeringTorqueEps, CarControllerParams) self.steer_rate_limited = new_steer != apply_steer", "not enabled and CS.pcm_acc_status: pcm_cancel_cmd = 1 # on entering", "(fcw_alert or steer_alert) and self.alert_active): send_ui = True self.alert_active =", "0.5 # RAV4 has very sensitive gas pedal if CS.CP.carFingerprint", "= interp(CS.out.vEgo, [0.0, 2.3, MIN_ACC_SPEED + PEDAL_TRANSITION], [-.4, 0.0, 0.2])", "{3}\".format(apply_steer, min_lim, max_lim, CS.steer_torque_motor) # toyota can trace shows this", "This prevents unexpected pedal range rescaling can_sends.append(create_gas_interceptor_command(self.packer, interceptor_gas_cmd, frame //", "= 0 else: apply_steer_req = 1 # TODO: probably can", "seem to allow a higher rate limit, as the rate", "PEDAL_SCALE = interp(CS.out.vEgo, [0.0, MIN_ACC_SPEED, MIN_ACC_SPEED + PEDAL_TRANSITION], [0.15, 0.3,", "adding alternatively 1 and 2; # sending it at 100Hz", "Lexus IS uses a different cancellation message if pcm_cancel_cmd and", "in [9, 25] or abs(CS.out.steeringRateDeg) > 100: apply_steer = 0", "= hud_alert == VisualAlert.fcw steer_alert = hud_alert in [VisualAlert.steerRequired, VisualAlert.ldw]", "dbc_name, CP, VM): self.last_steer = 0 self.alert_active = False self.last_standstill", "CAR.RAV4H, CAR.HIGHLANDER, CAR.HIGHLANDERH]: PEDAL_SCALE = interp(CS.out.vEgo, [0.0, MIN_ACC_SPEED, MIN_ACC_SPEED +", "low speed we always assume the lead is present so", "sound instead send_ui = True if (frame % 100 ==", "rate limit seems imposed # on consecutive messages can_sends.append(create_steer_command(self.packer, apply_steer,", "the system even if we are using lat only control", "False, lead, CS.acc_type, CS.distance_btn)) if frame % 2 == 0", "CS.CP.openpilotLongitudinalControl: # send exactly zero if gas cmd is zero.", "or CS.steer_state in [9, 25] or abs(CS.out.steeringRateDeg) > 100: apply_steer", "from opendbc.can.packer import CANPacker from common.op_params import opParams VisualAlert =", "state (2s) if not enabled or CS.steer_state in [9, 25]", "and CS.CP.enableDsu and CS.CP.carFingerprint in cars: can_sends.append(make_can_msg(addr, vl, bus)) new_actuators", "# Cut steering while we're in a known fault state", "= pcm_accel_cmd else: can_sends.append(create_accel_command(self.packer, 0, pcm_cancel_cmd, False, lead, CS.acc_type, CS.distance_btn))", "self.standstill_hack = opParams().get('standstill_hack') self.packer = CANPacker(dbc_name) self.gas = 0 self.accel", "= car.CarControl.HUDControl.VisualAlert class CarController(): def __init__(self, dbc_name, CP, VM): self.last_steer", "there is something to display # - there is something", "actuators.copy() new_actuators.steer = apply_steer / CarControllerParams.STEER_MAX new_actuators.accel = self.accel new_actuators.gas", "[CAR.RAV4, CAR.RAV4H, CAR.HIGHLANDER, CAR.HIGHLANDERH]: PEDAL_SCALE = interp(CS.out.vEgo, [0.0, MIN_ACC_SPEED, MIN_ACC_SPEED", "shows this message at 42Hz, with counter adding alternatively 1", "can to cancel the system even if we are using", "common.op_params import opParams VisualAlert = car.CarControl.HUDControl.VisualAlert class CarController(): def __init__(self,", "right_lane_depart): # gas and brake if CS.CP.enableGasInterceptor and enabled: MAX_INTERCEPTOR_GAS", "on consecutive messages can_sends.append(create_steer_command(self.packer, apply_steer, apply_steer_req, frame)) if frame %", "= 0.5 # RAV4 has very sensitive gas pedal if", "MIN_ACC_SPEED, MIN_ACC_SPEED + PEDAL_TRANSITION], [0.4, 0.5, 0.0]) # offset for", "play a good sound instead send_ui = True if (frame", "apply_steer, apply_steer_req, frame)) if frame % 2 == 0 and", "CS.CP.enableGasInterceptor and enabled: MAX_INTERCEPTOR_GAS = 0.5 # RAV4 has very", "// 2)) # we can spam can to cancel the", "MIN_ACC_SPEED + PEDAL_TRANSITION], [0.15, 0.3, 0.0]) elif CS.CP.carFingerprint in [CAR.COROLLA]:", "than CS.cruiseState.enabled. confirm they're not meaningfully different if not enabled", "MIN_ACC_SPEED + PEDAL_TRANSITION], [-.4, 0.0, 0.2]) pedal_command = PEDAL_SCALE *", "# if frame % 2 == 0: # can_sends.append(create_steer_command(self.packer, 0,", "2; # sending it at 100Hz seem to allow a", "CS.steer_torque_motor) # toyota can trace shows this message at 42Hz,", "a bad fault sound so play a good sound instead", "0 def update(self, enabled, active, CS, frame, actuators, pcm_cancel_cmd, hud_alert,", "frame % 100 == 0 and CS.CP.enableDsu: can_sends.append(create_fcw_command(self.packer, fcw_alert)) #", "self.gas = 0 self.accel = 0 def update(self, enabled, active,", "# can_sends.append(create_lta_steer_command(self.packer, actuators.steeringAngleDeg, apply_steer_req, frame // 2)) # we can", "gas pedal if CS.CP.carFingerprint in [CAR.RAV4, CAR.RAV4H, CAR.HIGHLANDER, CAR.HIGHLANDERH]: PEDAL_SCALE", "False if ((fcw_alert or steer_alert) and not self.alert_active) or \\", "standstill request if CS.out.standstill and not self.last_standstill and CS.CP.carFingerprint not", "{2} {3}\".format(apply_steer, min_lim, max_lim, CS.steer_torque_motor) # toyota can trace shows", "instead send_ui = True if (frame % 100 == 0", "CS.acc_type, CS.distance_btn)) self.accel = pcm_accel_cmd else: can_sends.append(create_accel_command(self.packer, 0, pcm_cancel_cmd, False,", "2 == 0 and CS.CP.carFingerprint in TSS2_CAR: can_sends.append(create_lta_steer_command(self.packer, 0, 0,", "abs(CS.out.steeringRateDeg) > 100: apply_steer = 0 apply_steer_req = 0 else:", "cancel the system even if we are using lat only", "True if CS.pcm_acc_status != 8: # pcm entered standstill or", "is zero. Interceptor will send the max between read value", "create_acc_cancel_command, \\ create_fcw_command, create_lta_steer_command from selfdrive.car.toyota.values import CAR, STATIC_DSU_MSGS, NO_STOP_TIMER_CAR,", "in STATIC_DSU_MSGS: if frame % fr_step == 0 and CS.CP.enableDsu", "cereal import car from common.numpy_fast import clip, interp from selfdrive.car", "fcw_alert = hud_alert == VisualAlert.fcw steer_alert = hud_alert in [VisualAlert.steerRequired,", "# send exactly zero if gas cmd is zero. Interceptor", "pcm_cancel_cmd, left_line, right_line, left_lane_depart, right_lane_depart, enabled)) if frame % 100", "trace shows this message at 42Hz, with counter adding alternatively", "enabled, active, CS, frame, actuators, pcm_cancel_cmd, hud_alert, left_line, right_line, lead,", "- there is something to stop displaying fcw_alert = hud_alert", "but we send asap if: # - there is something", "frame)) if frame % 2 == 0 and CS.CP.carFingerprint in", "== VisualAlert.fcw steer_alert = hud_alert in [VisualAlert.steerRequired, VisualAlert.ldw] send_ui =", "new_steer = int(round(actuators.steer * CarControllerParams.STEER_MAX)) apply_steer = apply_toyota_steer_torque_limits(new_steer, self.last_steer, CS.out.steeringTorqueEps,", "lat only control if (frame % 3 == 0 and", "import apply_toyota_steer_torque_limits, create_gas_interceptor_command, make_can_msg from selfdrive.car.toyota.toyotacan import create_steer_command, create_ui_command, \\", "2 == 0: # can_sends.append(create_steer_command(self.packer, 0, 0, frame // 2))", "CS.out.standstill can_sends = [] #*** control msgs *** #print(\"steer {0}", "create_lta_steer_command from selfdrive.car.toyota.values import CAR, STATIC_DSU_MSGS, NO_STOP_TIMER_CAR, TSS2_CAR, \\ MIN_ACC_SPEED,", "pcm_cancel_cmd, hud_alert, left_line, right_line, lead, left_lane_depart, right_lane_depart): # gas and", "pedal if CS.CP.carFingerprint in [CAR.RAV4, CAR.RAV4H, CAR.HIGHLANDER, CAR.HIGHLANDERH]: PEDAL_SCALE =", "CS.CP.enableDsu: can_sends.append(create_fcw_command(self.packer, fcw_alert)) # *** static msgs *** for (addr,", "it's disabled self.standstill_req = False self.last_steer = apply_steer self.last_standstill =", "100Hz seem to allow a higher rate limit, as the", "CP, VM): self.last_steer = 0 self.alert_active = False self.last_standstill =", "2.3, MIN_ACC_SPEED + PEDAL_TRANSITION], [-.4, 0.0, 0.2]) pedal_command = PEDAL_SCALE", "CAR, STATIC_DSU_MSGS, NO_STOP_TIMER_CAR, TSS2_CAR, \\ MIN_ACC_SPEED, PEDAL_TRANSITION, CarControllerParams from opendbc.can.packer", "= opParams().get('standstill_hack') self.packer = CANPacker(dbc_name) self.gas = 0 self.accel =", "or abs(CS.out.steeringRateDeg) > 100: apply_steer = 0 apply_steer_req = 0", "pcm_cancel_cmd, False, lead, CS.acc_type, CS.distance_btn)) if frame % 2 ==", "in TSS2_CAR: can_sends.append(create_lta_steer_command(self.packer, 0, 0, frame // 2)) # LTA", "elif pcm_cancel_cmd: # forcing the pcm to disengage causes a", "bus, fr_step, vl) in STATIC_DSU_MSGS: if frame % fr_step ==", "steer torque new_steer = int(round(actuators.steer * CarControllerParams.STEER_MAX)) apply_steer = apply_toyota_steer_torque_limits(new_steer,", "self.last_steer, CS.out.steeringTorqueEps, CarControllerParams) self.steer_rate_limited = new_steer != apply_steer # Cut", "fault state (2s) if not enabled or CS.steer_state in [9,", "= False self.last_standstill = False self.standstill_req = False self.steer_rate_limited =", "can_sends.append(create_fcw_command(self.packer, fcw_alert)) # *** static msgs *** for (addr, cars,", "from cereal import car from common.numpy_fast import clip, interp from", "+ PEDAL_TRANSITION], [0.4, 0.5, 0.0]) # offset for creep and", "if CS.CP.carFingerprint in [CAR.RAV4, CAR.RAV4H, CAR.HIGHLANDER, CAR.HIGHLANDERH]: PEDAL_SCALE = interp(CS.out.vEgo,", "[0.4, 0.5, 0.0]) # offset for creep and windbrake pedal_offset", "= False self.standstill_req = False self.steer_rate_limited = False self.standstill_hack =", "in [CAR.LEXUS_IS, CAR.LEXUS_RC]: can_sends.append(create_acc_cancel_command(self.packer)) elif CS.CP.openpilotLongitudinalControl: can_sends.append(create_accel_command(self.packer, pcm_accel_cmd, pcm_cancel_cmd, self.standstill_req,", "VisualAlert.fcw steer_alert = hud_alert in [VisualAlert.steerRequired, VisualAlert.ldw] send_ui = False", "= True self.alert_active = not self.alert_active elif pcm_cancel_cmd: # forcing", "rescaling can_sends.append(create_gas_interceptor_command(self.packer, interceptor_gas_cmd, frame // 2)) self.gas = interceptor_gas_cmd #", "if not enabled and CS.pcm_acc_status: pcm_cancel_cmd = 1 # on", "and 2; # sending it at 100Hz seem to allow", "make_can_msg from selfdrive.car.toyota.toyotacan import create_steer_command, create_ui_command, \\ create_accel_command, create_acc_cancel_command, \\", "== 0 and CS.CP.enableDsu: can_sends.append(create_fcw_command(self.packer, fcw_alert)) # *** static msgs", "speed we always assume the lead is present so ACC", "CarControllerParams.STEER_MAX)) apply_steer = apply_toyota_steer_torque_limits(new_steer, self.last_steer, CS.out.steeringTorqueEps, CarControllerParams) self.steer_rate_limited = new_steer", "self.accel = pcm_accel_cmd else: can_sends.append(create_accel_command(self.packer, 0, pcm_cancel_cmd, False, lead, CS.acc_type,", "TSS2_CAR, \\ MIN_ACC_SPEED, PEDAL_TRANSITION, CarControllerParams from opendbc.can.packer import CANPacker from", "create_gas_interceptor_command, make_can_msg from selfdrive.car.toyota.toyotacan import create_steer_command, create_ui_command, \\ create_accel_command, create_acc_cancel_command,", "# offset for creep and windbrake pedal_offset = interp(CS.out.vEgo, [0.0,", "send_ui = True if (frame % 100 == 0 or", "a different signal # than CS.cruiseState.enabled. confirm they're not meaningfully", "MIN_ACC_SPEED + PEDAL_TRANSITION], [0.3, 0.4, 0.0]) else: PEDAL_SCALE = interp(CS.out.vEgo,", "\\ (not (fcw_alert or steer_alert) and self.alert_active): send_ui = True", "steer_alert, pcm_cancel_cmd, left_line, right_line, left_lane_depart, right_lane_depart, enabled)) if frame %", "and self.alert_active): send_ui = True self.alert_active = not self.alert_active elif", "apply_steer_req = 0 else: apply_steer_req = 1 # TODO: probably", "zero if gas cmd is zero. Interceptor will send the", "it at 100Hz seem to allow a higher rate limit,", "for creep and windbrake pedal_offset = interp(CS.out.vEgo, [0.0, 2.3, MIN_ACC_SPEED", "= 0 self.accel = 0 def update(self, enabled, active, CS,", "enabled or CS.steer_state in [9, 25] or abs(CS.out.steeringRateDeg) > 100:", "// 2)) self.gas = interceptor_gas_cmd # ui mesg is at", "hud_alert == VisualAlert.fcw steer_alert = hud_alert in [VisualAlert.steerRequired, VisualAlert.ldw] send_ui", "!= apply_steer # Cut steering while we're in a known", "a higher rate limit, as the rate limit seems imposed", "lead, left_lane_depart, right_lane_depart): # gas and brake if CS.CP.enableGasInterceptor and", "CarController(): def __init__(self, dbc_name, CP, VM): self.last_steer = 0 self.alert_active", "and enabled: MAX_INTERCEPTOR_GAS = 0.5 # RAV4 has very sensitive", "not enabled or CS.steer_state in [9, 25] or abs(CS.out.steeringRateDeg) >", "[CAR.LEXUS_IS, CAR.LEXUS_RC]: can_sends.append(create_acc_cancel_command(self.packer)) elif CS.CP.openpilotLongitudinalControl: can_sends.append(create_accel_command(self.packer, pcm_accel_cmd, pcm_cancel_cmd, self.standstill_req, lead,", "standstill or it's disabled self.standstill_req = False self.last_steer = apply_steer", "pcm_accel_cmd else: can_sends.append(create_accel_command(self.packer, 0, pcm_cancel_cmd, False, lead, CS.acc_type, CS.distance_btn)) if", "CANPacker(dbc_name) self.gas = 0 self.accel = 0 def update(self, enabled,", "assume the lead is present so ACC can be engaged", "if frame % fr_step == 0 and CS.CP.enableDsu and CS.CP.carFingerprint", "toyota can trace shows this message at 42Hz, with counter", "steer_alert) and self.alert_active): send_ui = True self.alert_active = not self.alert_active", "2 == 0 and CS.CP.enableGasInterceptor and CS.CP.openpilotLongitudinalControl: # send exactly", "in the panda # if frame % 2 == 0:", "message at 42Hz, with counter adding alternatively 1 and 2;", "lead, CS.acc_type, CS.distance_btn)) if frame % 2 == 0 and", "self.alert_active): send_ui = True self.alert_active = not self.alert_active elif pcm_cancel_cmd:", "pcm_accel_cmd, pcm_cancel_cmd, self.standstill_req, lead, CS.acc_type, CS.distance_btn)) self.accel = pcm_accel_cmd else:", "interceptor_gas_cmd # ui mesg is at 100Hz but we send", "apply_steer = 0 apply_steer_req = 0 else: apply_steer_req = 1", "if pcm_cancel_cmd and CS.CP.carFingerprint in [CAR.LEXUS_IS, CAR.LEXUS_RC]: can_sends.append(create_acc_cancel_command(self.packer)) elif CS.CP.openpilotLongitudinalControl:", "the max between read value and gas cmd. # This", "is something to stop displaying fcw_alert = hud_alert == VisualAlert.fcw", "displaying fcw_alert = hud_alert == VisualAlert.fcw steer_alert = hud_alert in", "CANPacker from common.op_params import opParams VisualAlert = car.CarControl.HUDControl.VisualAlert class CarController():", "from selfdrive.car.toyota.toyotacan import create_steer_command, create_ui_command, \\ create_accel_command, create_acc_cancel_command, \\ create_fcw_command,", "from selfdrive.car import apply_toyota_steer_torque_limits, create_gas_interceptor_command, make_can_msg from selfdrive.car.toyota.toyotacan import create_steer_command,", "counter adding alternatively 1 and 2; # sending it at", "exactly zero if gas cmd is zero. Interceptor will send", "msgs *** for (addr, cars, bus, fr_step, vl) in STATIC_DSU_MSGS:", "steer_alert = hud_alert in [VisualAlert.steerRequired, VisualAlert.ldw] send_ui = False if", "if ((fcw_alert or steer_alert) and not self.alert_active) or \\ (not", "from common.op_params import opParams VisualAlert = car.CarControl.HUDControl.VisualAlert class CarController(): def", "while we're in a known fault state (2s) if not", "interceptor_gas_cmd = clip(pedal_command, 0., MAX_INTERCEPTOR_GAS) else: interceptor_gas_cmd = 0. pcm_accel_cmd", "uses a different cancellation message if pcm_cancel_cmd and CS.CP.carFingerprint in", "to disengage causes a bad fault sound so play a", "allow a higher rate limit, as the rate limit seems", "left_lane_depart, right_lane_depart, enabled)) if frame % 100 == 0 and", "0, frame // 2)) # LTA mode. Set ret.steerControlType =", "2)) self.gas = interceptor_gas_cmd # ui mesg is at 100Hz", "MAX_INTERCEPTOR_GAS) else: interceptor_gas_cmd = 0. pcm_accel_cmd = clip(actuators.accel, CarControllerParams.ACCEL_MIN, CarControllerParams.ACCEL_MAX)", "= interp(CS.out.vEgo, [0.0, MIN_ACC_SPEED, MIN_ACC_SPEED + PEDAL_TRANSITION], [0.15, 0.3, 0.0])", "send exactly zero if gas cmd is zero. Interceptor will", "enabled)) if frame % 100 == 0 and CS.CP.enableDsu: can_sends.append(create_fcw_command(self.packer,", "[0.3, 0.4, 0.0]) else: PEDAL_SCALE = interp(CS.out.vEgo, [0.0, MIN_ACC_SPEED, MIN_ACC_SPEED", "something to display # - there is something to stop", "= interceptor_gas_cmd # ui mesg is at 100Hz but we", "left_line, right_line, left_lane_depart, right_lane_depart, enabled)) if frame % 100 ==", "the panda # if frame % 2 == 0: #", "= int(round(actuators.steer * CarControllerParams.STEER_MAX)) apply_steer = apply_toyota_steer_torque_limits(new_steer, self.last_steer, CS.out.steeringTorqueEps, CarControllerParams)", "CS.CP.openpilotLongitudinalControl: can_sends.append(create_accel_command(self.packer, pcm_accel_cmd, pcm_cancel_cmd, self.standstill_req, lead, CS.acc_type, CS.distance_btn)) self.accel =", "interp(CS.out.vEgo, [0.0, MIN_ACC_SPEED, MIN_ACC_SPEED + PEDAL_TRANSITION], [0.4, 0.5, 0.0]) #", "meaningfully different if not enabled and CS.pcm_acc_status: pcm_cancel_cmd = 1", "self.standstill_req = False self.steer_rate_limited = False self.standstill_hack = opParams().get('standstill_hack') self.packer", "CS, frame, actuators, pcm_cancel_cmd, hud_alert, left_line, right_line, lead, left_lane_depart, right_lane_depart):", "we're in a known fault state (2s) if not enabled", "sensitive gas pedal if CS.CP.carFingerprint in [CAR.RAV4, CAR.RAV4H, CAR.HIGHLANDER, CAR.HIGHLANDERH]:", "if frame % 2 == 0: # can_sends.append(create_steer_command(self.packer, 0, 0,", "torque new_steer = int(round(actuators.steer * CarControllerParams.STEER_MAX)) apply_steer = apply_toyota_steer_torque_limits(new_steer, self.last_steer,", "pedal_command = PEDAL_SCALE * (actuators.accel + pedal_offset) interceptor_gas_cmd = clip(pedal_command,", "else: can_sends.append(create_accel_command(self.packer, 0, pcm_cancel_cmd, False, lead, CS.acc_type, CS.distance_btn)) if frame", "self.last_steer = 0 self.alert_active = False self.last_standstill = False self.standstill_req", "PEDAL_TRANSITION], [0.4, 0.5, 0.0]) # offset for creep and windbrake", "steering while we're in a known fault state (2s) if", "CS.CP.carFingerprint in cars: can_sends.append(make_can_msg(addr, vl, bus)) new_actuators = actuators.copy() new_actuators.steer", "0, 0, frame // 2)) # can_sends.append(create_lta_steer_command(self.packer, actuators.steeringAngleDeg, apply_steer_req, frame", "so ACC can be engaged # Lexus IS uses a", "[] #*** control msgs *** #print(\"steer {0} {1} {2} {3}\".format(apply_steer,", "== 0 and CS.CP.enableDsu and CS.CP.carFingerprint in cars: can_sends.append(make_can_msg(addr, vl,", "= PEDAL_SCALE * (actuators.accel + pedal_offset) interceptor_gas_cmd = clip(pedal_command, 0.,", "# Lexus IS uses a different cancellation message if pcm_cancel_cmd", "new_actuators.steer = apply_steer / CarControllerParams.STEER_MAX new_actuators.accel = self.accel new_actuators.gas =", "seems imposed # on consecutive messages can_sends.append(create_steer_command(self.packer, apply_steer, apply_steer_req, frame))", "offset for creep and windbrake pedal_offset = interp(CS.out.vEgo, [0.0, 2.3,", "opendbc.can.packer import CANPacker from common.op_params import opParams VisualAlert = car.CarControl.HUDControl.VisualAlert", "different if not enabled and CS.pcm_acc_status: pcm_cancel_cmd = 1 #", "+ pedal_offset) interceptor_gas_cmd = clip(pedal_command, 0., MAX_INTERCEPTOR_GAS) else: interceptor_gas_cmd =", "CS.CP.carFingerprint in [CAR.RAV4, CAR.RAV4H, CAR.HIGHLANDER, CAR.HIGHLANDERH]: PEDAL_SCALE = interp(CS.out.vEgo, [0.0,", "(frame % 100 == 0 or send_ui): can_sends.append(create_ui_command(self.packer, steer_alert, pcm_cancel_cmd,", "to cancel the system even if we are using lat", "0 and CS.CP.carFingerprint in TSS2_CAR: can_sends.append(create_lta_steer_command(self.packer, 0, 0, frame //", "higher rate limit, as the rate limit seems imposed #", "[0.0, MIN_ACC_SPEED, MIN_ACC_SPEED + PEDAL_TRANSITION], [0.4, 0.5, 0.0]) # offset", "STATIC_DSU_MSGS, NO_STOP_TIMER_CAR, TSS2_CAR, \\ MIN_ACC_SPEED, PEDAL_TRANSITION, CarControllerParams from opendbc.can.packer import", "int(round(actuators.steer * CarControllerParams.STEER_MAX)) apply_steer = apply_toyota_steer_torque_limits(new_steer, self.last_steer, CS.out.steeringTorqueEps, CarControllerParams) self.steer_rate_limited", "# ui mesg is at 100Hz but we send asap", "gas cmd. # This prevents unexpected pedal range rescaling can_sends.append(create_gas_interceptor_command(self.packer,", "MAX_INTERCEPTOR_GAS = 0.5 # RAV4 has very sensitive gas pedal", "0 and CS.CP.openpilotLongitudinalControl) or pcm_cancel_cmd: lead = lead or CS.out.vEgo", "TODO: probably can delete this. CS.pcm_acc_status uses a different signal", "False self.standstill_req = False self.steer_rate_limited = False self.standstill_hack = opParams().get('standstill_hack')", "= clip(pedal_command, 0., MAX_INTERCEPTOR_GAS) else: interceptor_gas_cmd = 0. pcm_accel_cmd =", "CarControllerParams.ACCEL_MAX) # steer torque new_steer = int(round(actuators.steer * CarControllerParams.STEER_MAX)) apply_steer", "max_lim, CS.steer_torque_motor) # toyota can trace shows this message at", "CS.acc_type, CS.distance_btn)) if frame % 2 == 0 and CS.CP.enableGasInterceptor", "def __init__(self, dbc_name, CP, VM): self.last_steer = 0 self.alert_active =", "0, frame // 2)) # can_sends.append(create_lta_steer_command(self.packer, actuators.steeringAngleDeg, apply_steer_req, frame //", "PEDAL_TRANSITION], [-.4, 0.0, 0.2]) pedal_command = PEDAL_SCALE * (actuators.accel +", "if CS.out.standstill and not self.last_standstill and CS.CP.carFingerprint not in NO_STOP_TIMER_CAR", "__init__(self, dbc_name, CP, VM): self.last_steer = 0 self.alert_active = False", "= interp(CS.out.vEgo, [0.0, MIN_ACC_SPEED, MIN_ACC_SPEED + PEDAL_TRANSITION], [0.3, 0.4, 0.0])", "frame % fr_step == 0 and CS.CP.enableDsu and CS.CP.carFingerprint in", "confirm they're not meaningfully different if not enabled and CS.pcm_acc_status:", "# LTA mode. Set ret.steerControlType = car.CarParams.SteerControlType.angle and whitelist 0x191", "can_sends.append(create_steer_command(self.packer, apply_steer, apply_steer_req, frame)) if frame % 2 == 0", "= 0 def update(self, enabled, active, CS, frame, actuators, pcm_cancel_cmd,", "self.standstill_req = True if CS.pcm_acc_status != 8: # pcm entered", "False self.last_steer = apply_steer self.last_standstill = CS.out.standstill can_sends = []", "consecutive messages can_sends.append(create_steer_command(self.packer, apply_steer, apply_steer_req, frame)) if frame % 2", "% fr_step == 0 and CS.CP.enableDsu and CS.CP.carFingerprint in cars:", "can_sends.append(make_can_msg(addr, vl, bus)) new_actuators = actuators.copy() new_actuators.steer = apply_steer /", "has very sensitive gas pedal if CS.CP.carFingerprint in [CAR.RAV4, CAR.RAV4H,", "CS.distance_btn)) self.accel = pcm_accel_cmd else: can_sends.append(create_accel_command(self.packer, 0, pcm_cancel_cmd, False, lead,", "imposed # on consecutive messages can_sends.append(create_steer_command(self.packer, apply_steer, apply_steer_req, frame)) if", "frame // 2)) # we can spam can to cancel", "= True if CS.pcm_acc_status != 8: # pcm entered standstill", "so play a good sound instead send_ui = True if", "or it's disabled self.standstill_req = False self.last_steer = apply_steer self.last_standstill", "frame // 2)) # LTA mode. Set ret.steerControlType = car.CarParams.SteerControlType.angle", "# gas and brake if CS.CP.enableGasInterceptor and enabled: MAX_INTERCEPTOR_GAS =", "actuators, pcm_cancel_cmd, hud_alert, left_line, right_line, lead, left_lane_depart, right_lane_depart): # gas", "0, 0, frame // 2)) # LTA mode. Set ret.steerControlType", "if (frame % 3 == 0 and CS.CP.openpilotLongitudinalControl) or pcm_cancel_cmd:", "self.alert_active) or \\ (not (fcw_alert or steer_alert) and self.alert_active): send_ui", "and gas cmd. # This prevents unexpected pedal range rescaling", "PEDAL_TRANSITION], [0.15, 0.3, 0.0]) elif CS.CP.carFingerprint in [CAR.COROLLA]: PEDAL_SCALE =", "CS.pcm_acc_status: pcm_cancel_cmd = 1 # on entering standstill, send standstill", "send_ui): can_sends.append(create_ui_command(self.packer, steer_alert, pcm_cancel_cmd, left_line, right_line, left_lane_depart, right_lane_depart, enabled)) if", "!= 8: # pcm entered standstill or it's disabled self.standstill_req", "and windbrake pedal_offset = interp(CS.out.vEgo, [0.0, 2.3, MIN_ACC_SPEED + PEDAL_TRANSITION],", "frame % 2 == 0: # can_sends.append(create_steer_command(self.packer, 0, 0, frame", "== 0: # can_sends.append(create_steer_command(self.packer, 0, 0, frame // 2)) #", "fault sound so play a good sound instead send_ui =", "0.0]) else: PEDAL_SCALE = interp(CS.out.vEgo, [0.0, MIN_ACC_SPEED, MIN_ACC_SPEED + PEDAL_TRANSITION],", "are using lat only control if (frame % 3 ==", "= False self.standstill_hack = opParams().get('standstill_hack') self.packer = CANPacker(dbc_name) self.gas =", "opParams VisualAlert = car.CarControl.HUDControl.VisualAlert class CarController(): def __init__(self, dbc_name, CP,", "= CS.out.standstill can_sends = [] #*** control msgs *** #print(\"steer", "send_ui = False if ((fcw_alert or steer_alert) and not self.alert_active)", "engaged # Lexus IS uses a different cancellation message if", "CS.pcm_acc_status != 8: # pcm entered standstill or it's disabled", "apply_toyota_steer_torque_limits, create_gas_interceptor_command, make_can_msg from selfdrive.car.toyota.toyotacan import create_steer_command, create_ui_command, \\ create_accel_command,", "12. # at low speed we always assume the lead", "0 and CS.CP.enableDsu: can_sends.append(create_fcw_command(self.packer, fcw_alert)) # *** static msgs ***", "{0} {1} {2} {3}\".format(apply_steer, min_lim, max_lim, CS.steer_torque_motor) # toyota can", "apply_steer = apply_toyota_steer_torque_limits(new_steer, self.last_steer, CS.out.steeringTorqueEps, CarControllerParams) self.steer_rate_limited = new_steer !=", "CS.CP.carFingerprint not in NO_STOP_TIMER_CAR and not self.standstill_hack: self.standstill_req = True", "not self.standstill_hack: self.standstill_req = True if CS.pcm_acc_status != 8: #", "{1} {2} {3}\".format(apply_steer, min_lim, max_lim, CS.steer_torque_motor) # toyota can trace", "forcing the pcm to disengage causes a bad fault sound", "known fault state (2s) if not enabled or CS.steer_state in", "interp from selfdrive.car import apply_toyota_steer_torque_limits, create_gas_interceptor_command, make_can_msg from selfdrive.car.toyota.toyotacan import", "import create_steer_command, create_ui_command, \\ create_accel_command, create_acc_cancel_command, \\ create_fcw_command, create_lta_steer_command from", "and not self.last_standstill and CS.CP.carFingerprint not in NO_STOP_TIMER_CAR and not", "NO_STOP_TIMER_CAR, TSS2_CAR, \\ MIN_ACC_SPEED, PEDAL_TRANSITION, CarControllerParams from opendbc.can.packer import CANPacker", "in a known fault state (2s) if not enabled or", "creep and windbrake pedal_offset = interp(CS.out.vEgo, [0.0, 2.3, MIN_ACC_SPEED +", "lead is present so ACC can be engaged # Lexus", "- there is something to display # - there is", "RAV4 has very sensitive gas pedal if CS.CP.carFingerprint in [CAR.RAV4,", "rate limit, as the rate limit seems imposed # on", "only control if (frame % 3 == 0 and CS.CP.openpilotLongitudinalControl)", "disabled self.standstill_req = False self.last_steer = apply_steer self.last_standstill = CS.out.standstill", "cancellation message if pcm_cancel_cmd and CS.CP.carFingerprint in [CAR.LEXUS_IS, CAR.LEXUS_RC]: can_sends.append(create_acc_cancel_command(self.packer))", "# toyota can trace shows this message at 42Hz, with", "2)) # LTA mode. Set ret.steerControlType = car.CarParams.SteerControlType.angle and whitelist", "static msgs *** for (addr, cars, bus, fr_step, vl) in", "not self.last_standstill and CS.CP.carFingerprint not in NO_STOP_TIMER_CAR and not self.standstill_hack:", "from selfdrive.car.toyota.values import CAR, STATIC_DSU_MSGS, NO_STOP_TIMER_CAR, TSS2_CAR, \\ MIN_ACC_SPEED, PEDAL_TRANSITION,", "apply_steer_req = 1 # TODO: probably can delete this. CS.pcm_acc_status", "else: PEDAL_SCALE = interp(CS.out.vEgo, [0.0, MIN_ACC_SPEED, MIN_ACC_SPEED + PEDAL_TRANSITION], [0.4,", "CarControllerParams.ACCEL_MIN, CarControllerParams.ACCEL_MAX) # steer torque new_steer = int(round(actuators.steer * CarControllerParams.STEER_MAX))", "can_sends.append(create_lta_steer_command(self.packer, actuators.steeringAngleDeg, apply_steer_req, frame // 2)) # we can spam", "is at 100Hz but we send asap if: # -", "can_sends.append(create_lta_steer_command(self.packer, 0, 0, frame // 2)) # LTA mode. Set", "pcm entered standstill or it's disabled self.standstill_req = False self.last_steer", "= False self.steer_rate_limited = False self.standstill_hack = opParams().get('standstill_hack') self.packer =", "to allow a higher rate limit, as the rate limit", "frame // 2)) # can_sends.append(create_lta_steer_command(self.packer, actuators.steeringAngleDeg, apply_steer_req, frame // 2))", "# can_sends.append(create_steer_command(self.packer, 0, 0, frame // 2)) # can_sends.append(create_lta_steer_command(self.packer, actuators.steeringAngleDeg,", "= clip(actuators.accel, CarControllerParams.ACCEL_MIN, CarControllerParams.ACCEL_MAX) # steer torque new_steer = int(round(actuators.steer", "[0.15, 0.3, 0.0]) elif CS.CP.carFingerprint in [CAR.COROLLA]: PEDAL_SCALE = interp(CS.out.vEgo,", "and CS.pcm_acc_status: pcm_cancel_cmd = 1 # on entering standstill, send", "in [CAR.RAV4, CAR.RAV4H, CAR.HIGHLANDER, CAR.HIGHLANDERH]: PEDAL_SCALE = interp(CS.out.vEgo, [0.0, MIN_ACC_SPEED,", "[CAR.COROLLA]: PEDAL_SCALE = interp(CS.out.vEgo, [0.0, MIN_ACC_SPEED, MIN_ACC_SPEED + PEDAL_TRANSITION], [0.3,", "elif CS.CP.carFingerprint in [CAR.COROLLA]: PEDAL_SCALE = interp(CS.out.vEgo, [0.0, MIN_ACC_SPEED, MIN_ACC_SPEED", "== 0 and CS.CP.carFingerprint in TSS2_CAR: can_sends.append(create_lta_steer_command(self.packer, 0, 0, frame", "create_steer_command, create_ui_command, \\ create_accel_command, create_acc_cancel_command, \\ create_fcw_command, create_lta_steer_command from selfdrive.car.toyota.values", "self.alert_active elif pcm_cancel_cmd: # forcing the pcm to disengage causes", "elif CS.CP.openpilotLongitudinalControl: can_sends.append(create_accel_command(self.packer, pcm_accel_cmd, pcm_cancel_cmd, self.standstill_req, lead, CS.acc_type, CS.distance_btn)) self.accel", "pedal range rescaling can_sends.append(create_gas_interceptor_command(self.packer, interceptor_gas_cmd, frame // 2)) self.gas =", "and CS.CP.openpilotLongitudinalControl) or pcm_cancel_cmd: lead = lead or CS.out.vEgo <", "fr_step == 0 and CS.CP.enableDsu and CS.CP.carFingerprint in cars: can_sends.append(make_can_msg(addr,", "PEDAL_SCALE = interp(CS.out.vEgo, [0.0, MIN_ACC_SPEED, MIN_ACC_SPEED + PEDAL_TRANSITION], [0.3, 0.4,", "will send the max between read value and gas cmd.", "True if (frame % 100 == 0 or send_ui): can_sends.append(create_ui_command(self.packer,", "car.CarParams.SteerControlType.angle and whitelist 0x191 in the panda # if frame", "False self.last_standstill = False self.standstill_req = False self.steer_rate_limited = False", "and brake if CS.CP.enableGasInterceptor and enabled: MAX_INTERCEPTOR_GAS = 0.5 #", "CS.CP.carFingerprint in [CAR.COROLLA]: PEDAL_SCALE = interp(CS.out.vEgo, [0.0, MIN_ACC_SPEED, MIN_ACC_SPEED +", "send standstill request if CS.out.standstill and not self.last_standstill and CS.CP.carFingerprint", "= 0 self.alert_active = False self.last_standstill = False self.standstill_req =", "0 and CS.CP.enableDsu and CS.CP.carFingerprint in cars: can_sends.append(make_can_msg(addr, vl, bus))", "message if pcm_cancel_cmd and CS.CP.carFingerprint in [CAR.LEXUS_IS, CAR.LEXUS_RC]: can_sends.append(create_acc_cancel_command(self.packer)) elif", "the lead is present so ACC can be engaged #", "0.0, 0.2]) pedal_command = PEDAL_SCALE * (actuators.accel + pedal_offset) interceptor_gas_cmd", "(2s) if not enabled or CS.steer_state in [9, 25] or", "opParams().get('standstill_hack') self.packer = CANPacker(dbc_name) self.gas = 0 self.accel = 0", "# forcing the pcm to disengage causes a bad fault", "can delete this. CS.pcm_acc_status uses a different signal # than", "for (addr, cars, bus, fr_step, vl) in STATIC_DSU_MSGS: if frame", "fcw_alert)) # *** static msgs *** for (addr, cars, bus,", "prevents unexpected pedal range rescaling can_sends.append(create_gas_interceptor_command(self.packer, interceptor_gas_cmd, frame // 2))", "\\ create_fcw_command, create_lta_steer_command from selfdrive.car.toyota.values import CAR, STATIC_DSU_MSGS, NO_STOP_TIMER_CAR, TSS2_CAR,", "PEDAL_TRANSITION, CarControllerParams from opendbc.can.packer import CANPacker from common.op_params import opParams", "they're not meaningfully different if not enabled and CS.pcm_acc_status: pcm_cancel_cmd", "= 0. pcm_accel_cmd = clip(actuators.accel, CarControllerParams.ACCEL_MIN, CarControllerParams.ACCEL_MAX) # steer torque", "VisualAlert.ldw] send_ui = False if ((fcw_alert or steer_alert) and not", "CAR.HIGHLANDERH]: PEDAL_SCALE = interp(CS.out.vEgo, [0.0, MIN_ACC_SPEED, MIN_ACC_SPEED + PEDAL_TRANSITION], [0.15,", "ret.steerControlType = car.CarParams.SteerControlType.angle and whitelist 0x191 in the panda #", "standstill, send standstill request if CS.out.standstill and not self.last_standstill and", "pcm_cancel_cmd: lead = lead or CS.out.vEgo < 12. # at", "is something to display # - there is something to", "CAR.LEXUS_RC]: can_sends.append(create_acc_cancel_command(self.packer)) elif CS.CP.openpilotLongitudinalControl: can_sends.append(create_accel_command(self.packer, pcm_accel_cmd, pcm_cancel_cmd, self.standstill_req, lead, CS.acc_type,", "vl) in STATIC_DSU_MSGS: if frame % fr_step == 0 and", "MIN_ACC_SPEED, PEDAL_TRANSITION, CarControllerParams from opendbc.can.packer import CANPacker from common.op_params import", "100 == 0 and CS.CP.enableDsu: can_sends.append(create_fcw_command(self.packer, fcw_alert)) # *** static", "else: interceptor_gas_cmd = 0. pcm_accel_cmd = clip(actuators.accel, CarControllerParams.ACCEL_MIN, CarControllerParams.ACCEL_MAX) #", "= not self.alert_active elif pcm_cancel_cmd: # forcing the pcm to", "and CS.CP.enableGasInterceptor and CS.CP.openpilotLongitudinalControl: # send exactly zero if gas", "self.standstill_hack: self.standstill_req = True if CS.pcm_acc_status != 8: # pcm", "max between read value and gas cmd. # This prevents", "== 0 and CS.CP.openpilotLongitudinalControl) or pcm_cancel_cmd: lead = lead or", "new_steer != apply_steer # Cut steering while we're in a", "if CS.pcm_acc_status != 8: # pcm entered standstill or it's", "# on entering standstill, send standstill request if CS.out.standstill and", "% 2 == 0 and CS.CP.enableGasInterceptor and CS.CP.openpilotLongitudinalControl: # send", "100Hz but we send asap if: # - there is", "0x191 in the panda # if frame % 2 ==", "can trace shows this message at 42Hz, with counter adding", "signal # than CS.cruiseState.enabled. confirm they're not meaningfully different if", "pcm_cancel_cmd = 1 # on entering standstill, send standstill request", "= apply_steer self.last_standstill = CS.out.standstill can_sends = [] #*** control", "mode. Set ret.steerControlType = car.CarParams.SteerControlType.angle and whitelist 0x191 in the", "this message at 42Hz, with counter adding alternatively 1 and", "send asap if: # - there is something to display", "not meaningfully different if not enabled and CS.pcm_acc_status: pcm_cancel_cmd =", "VisualAlert = car.CarControl.HUDControl.VisualAlert class CarController(): def __init__(self, dbc_name, CP, VM):", "enabled and CS.pcm_acc_status: pcm_cancel_cmd = 1 # on entering standstill,", "CS.steer_state in [9, 25] or abs(CS.out.steeringRateDeg) > 100: apply_steer =", "as the rate limit seems imposed # on consecutive messages", "right_lane_depart, enabled)) if frame % 100 == 0 and CS.CP.enableDsu:", "> 100: apply_steer = 0 apply_steer_req = 0 else: apply_steer_req", "else: apply_steer_req = 1 # TODO: probably can delete this.", "1 and 2; # sending it at 100Hz seem to", "selfdrive.car.toyota.values import CAR, STATIC_DSU_MSGS, NO_STOP_TIMER_CAR, TSS2_CAR, \\ MIN_ACC_SPEED, PEDAL_TRANSITION, CarControllerParams", "0 self.alert_active = False self.last_standstill = False self.standstill_req = False", "messages can_sends.append(create_steer_command(self.packer, apply_steer, apply_steer_req, frame)) if frame % 2 ==", "a different cancellation message if pcm_cancel_cmd and CS.CP.carFingerprint in [CAR.LEXUS_IS,", "# This prevents unexpected pedal range rescaling can_sends.append(create_gas_interceptor_command(self.packer, interceptor_gas_cmd, frame", "Interceptor will send the max between read value and gas", "interp(CS.out.vEgo, [0.0, 2.3, MIN_ACC_SPEED + PEDAL_TRANSITION], [-.4, 0.0, 0.2]) pedal_command", "cmd is zero. Interceptor will send the max between read", "pcm to disengage causes a bad fault sound so play", "CS.out.vEgo < 12. # at low speed we always assume", "not self.alert_active elif pcm_cancel_cmd: # forcing the pcm to disengage", "0.2]) pedal_command = PEDAL_SCALE * (actuators.accel + pedal_offset) interceptor_gas_cmd =", "CS.pcm_acc_status uses a different signal # than CS.cruiseState.enabled. confirm they're", "< 12. # at low speed we always assume the", "in [VisualAlert.steerRequired, VisualAlert.ldw] send_ui = False if ((fcw_alert or steer_alert)", "cars, bus, fr_step, vl) in STATIC_DSU_MSGS: if frame % fr_step", "zero. Interceptor will send the max between read value and", "if we are using lat only control if (frame %", "(actuators.accel + pedal_offset) interceptor_gas_cmd = clip(pedal_command, 0., MAX_INTERCEPTOR_GAS) else: interceptor_gas_cmd", "Cut steering while we're in a known fault state (2s)", "send_ui = True self.alert_active = not self.alert_active elif pcm_cancel_cmd: #", "# on consecutive messages can_sends.append(create_steer_command(self.packer, apply_steer, apply_steer_req, frame)) if frame", "1 # TODO: probably can delete this. CS.pcm_acc_status uses a", "apply_steer_req, frame)) if frame % 2 == 0 and CS.CP.carFingerprint", "display # - there is something to stop displaying fcw_alert", "or \\ (not (fcw_alert or steer_alert) and self.alert_active): send_ui =", "self.alert_active = not self.alert_active elif pcm_cancel_cmd: # forcing the pcm", "we are using lat only control if (frame % 3", "whitelist 0x191 in the panda # if frame % 2", "pcm_cancel_cmd: # forcing the pcm to disengage causes a bad", "and CS.CP.enableDsu: can_sends.append(create_fcw_command(self.packer, fcw_alert)) # *** static msgs *** for", "frame % 2 == 0 and CS.CP.enableGasInterceptor and CS.CP.openpilotLongitudinalControl: #", "import opParams VisualAlert = car.CarControl.HUDControl.VisualAlert class CarController(): def __init__(self, dbc_name,", "self.standstill_req, lead, CS.acc_type, CS.distance_btn)) self.accel = pcm_accel_cmd else: can_sends.append(create_accel_command(self.packer, 0,", "a known fault state (2s) if not enabled or CS.steer_state", "clip, interp from selfdrive.car import apply_toyota_steer_torque_limits, create_gas_interceptor_command, make_can_msg from selfdrive.car.toyota.toyotacan", "lead, CS.acc_type, CS.distance_btn)) self.accel = pcm_accel_cmd else: can_sends.append(create_accel_command(self.packer, 0, pcm_cancel_cmd,", "can_sends.append(create_gas_interceptor_command(self.packer, interceptor_gas_cmd, frame // 2)) self.gas = interceptor_gas_cmd # ui", "selfdrive.car import apply_toyota_steer_torque_limits, create_gas_interceptor_command, make_can_msg from selfdrive.car.toyota.toyotacan import create_steer_command, create_ui_command,", "# we can spam can to cancel the system even", "delete this. CS.pcm_acc_status uses a different signal # than CS.cruiseState.enabled.", "import CANPacker from common.op_params import opParams VisualAlert = car.CarControl.HUDControl.VisualAlert class", "PEDAL_SCALE = interp(CS.out.vEgo, [0.0, MIN_ACC_SPEED, MIN_ACC_SPEED + PEDAL_TRANSITION], [0.4, 0.5,", "we can spam can to cancel the system even if", "[VisualAlert.steerRequired, VisualAlert.ldw] send_ui = False if ((fcw_alert or steer_alert) and", "and CS.CP.openpilotLongitudinalControl: # send exactly zero if gas cmd is", "100 == 0 or send_ui): can_sends.append(create_ui_command(self.packer, steer_alert, pcm_cancel_cmd, left_line, right_line,", "causes a bad fault sound so play a good sound", "create_accel_command, create_acc_cancel_command, \\ create_fcw_command, create_lta_steer_command from selfdrive.car.toyota.values import CAR, STATIC_DSU_MSGS,", "ui mesg is at 100Hz but we send asap if:", "self.packer = CANPacker(dbc_name) self.gas = 0 self.accel = 0 def", "pcm_cancel_cmd and CS.CP.carFingerprint in [CAR.LEXUS_IS, CAR.LEXUS_RC]: can_sends.append(create_acc_cancel_command(self.packer)) elif CS.CP.openpilotLongitudinalControl: can_sends.append(create_accel_command(self.packer,", "= 1 # on entering standstill, send standstill request if", "between read value and gas cmd. # This prevents unexpected", "LTA mode. Set ret.steerControlType = car.CarParams.SteerControlType.angle and whitelist 0x191 in", "right_line, left_lane_depart, right_lane_depart, enabled)) if frame % 100 == 0", "from common.numpy_fast import clip, interp from selfdrive.car import apply_toyota_steer_torque_limits, create_gas_interceptor_command,", "100: apply_steer = 0 apply_steer_req = 0 else: apply_steer_req =", "False self.steer_rate_limited = False self.standstill_hack = opParams().get('standstill_hack') self.packer = CANPacker(dbc_name)", "and whitelist 0x191 in the panda # if frame %", "frame % 2 == 0 and CS.CP.carFingerprint in TSS2_CAR: can_sends.append(create_lta_steer_command(self.packer,", "0 and CS.CP.enableGasInterceptor and CS.CP.openpilotLongitudinalControl: # send exactly zero if", "probably can delete this. CS.pcm_acc_status uses a different signal #", "this. CS.pcm_acc_status uses a different signal # than CS.cruiseState.enabled. confirm", "at 100Hz seem to allow a higher rate limit, as", "apply_toyota_steer_torque_limits(new_steer, self.last_steer, CS.out.steeringTorqueEps, CarControllerParams) self.steer_rate_limited = new_steer != apply_steer #", "# at low speed we always assume the lead is", "import clip, interp from selfdrive.car import apply_toyota_steer_torque_limits, create_gas_interceptor_command, make_can_msg from", "0.5, 0.0]) # offset for creep and windbrake pedal_offset =", "if frame % 2 == 0 and CS.CP.carFingerprint in TSS2_CAR:", "CS.CP.enableDsu and CS.CP.carFingerprint in cars: can_sends.append(make_can_msg(addr, vl, bus)) new_actuators =", "def update(self, enabled, active, CS, frame, actuators, pcm_cancel_cmd, hud_alert, left_line,", "8: # pcm entered standstill or it's disabled self.standstill_req =", "be engaged # Lexus IS uses a different cancellation message", "False self.standstill_hack = opParams().get('standstill_hack') self.packer = CANPacker(dbc_name) self.gas = 0", "present so ACC can be engaged # Lexus IS uses", "can_sends.append(create_accel_command(self.packer, pcm_accel_cmd, pcm_cancel_cmd, self.standstill_req, lead, CS.acc_type, CS.distance_btn)) self.accel = pcm_accel_cmd", "min_lim, max_lim, CS.steer_torque_motor) # toyota can trace shows this message", "can_sends = [] #*** control msgs *** #print(\"steer {0} {1}", "*** static msgs *** for (addr, cars, bus, fr_step, vl)", "0: # can_sends.append(create_steer_command(self.packer, 0, 0, frame // 2)) # can_sends.append(create_lta_steer_command(self.packer,", "CarControllerParams from opendbc.can.packer import CANPacker from common.op_params import opParams VisualAlert", "self.accel = 0 def update(self, enabled, active, CS, frame, actuators,", "CS.out.standstill and not self.last_standstill and CS.CP.carFingerprint not in NO_STOP_TIMER_CAR and", "the rate limit seems imposed # on consecutive messages can_sends.append(create_steer_command(self.packer,", "self.steer_rate_limited = False self.standstill_hack = opParams().get('standstill_hack') self.packer = CANPacker(dbc_name) self.gas", "True self.alert_active = not self.alert_active elif pcm_cancel_cmd: # forcing the", "pedal_offset) interceptor_gas_cmd = clip(pedal_command, 0., MAX_INTERCEPTOR_GAS) else: interceptor_gas_cmd = 0.", "good sound instead send_ui = True if (frame % 100", "IS uses a different cancellation message if pcm_cancel_cmd and CS.CP.carFingerprint", "bus)) new_actuators = actuators.copy() new_actuators.steer = apply_steer / CarControllerParams.STEER_MAX new_actuators.accel", "different signal # than CS.cruiseState.enabled. confirm they're not meaningfully different", "to display # - there is something to stop displaying", "and CS.CP.carFingerprint in TSS2_CAR: can_sends.append(create_lta_steer_command(self.packer, 0, 0, frame // 2))", "or pcm_cancel_cmd: lead = lead or CS.out.vEgo < 12. #", "gas and brake if CS.CP.enableGasInterceptor and enabled: MAX_INTERCEPTOR_GAS = 0.5", "on entering standstill, send standstill request if CS.out.standstill and not", "= actuators.copy() new_actuators.steer = apply_steer / CarControllerParams.STEER_MAX new_actuators.accel = self.accel", "VM): self.last_steer = 0 self.alert_active = False self.last_standstill = False", "interceptor_gas_cmd, frame // 2)) self.gas = interceptor_gas_cmd # ui mesg", "self.last_steer = apply_steer self.last_standstill = CS.out.standstill can_sends = [] #***", "MIN_ACC_SPEED, MIN_ACC_SPEED + PEDAL_TRANSITION], [0.15, 0.3, 0.0]) elif CS.CP.carFingerprint in", "CarControllerParams.STEER_MAX new_actuators.accel = self.accel new_actuators.gas = self.gas return new_actuators, can_sends", "active, CS, frame, actuators, pcm_cancel_cmd, hud_alert, left_line, right_line, lead, left_lane_depart,", "// 2)) # can_sends.append(create_lta_steer_command(self.packer, actuators.steeringAngleDeg, apply_steer_req, frame // 2)) #", "create_fcw_command, create_lta_steer_command from selfdrive.car.toyota.values import CAR, STATIC_DSU_MSGS, NO_STOP_TIMER_CAR, TSS2_CAR, \\", "cmd. # This prevents unexpected pedal range rescaling can_sends.append(create_gas_interceptor_command(self.packer, interceptor_gas_cmd,", "system even if we are using lat only control if", "to stop displaying fcw_alert = hud_alert == VisualAlert.fcw steer_alert =", "= hud_alert in [VisualAlert.steerRequired, VisualAlert.ldw] send_ui = False if ((fcw_alert", "0.0]) elif CS.CP.carFingerprint in [CAR.COROLLA]: PEDAL_SCALE = interp(CS.out.vEgo, [0.0, MIN_ACC_SPEED,", "apply_steer_req, frame // 2)) # we can spam can to", "= lead or CS.out.vEgo < 12. # at low speed", "[-.4, 0.0, 0.2]) pedal_command = PEDAL_SCALE * (actuators.accel + pedal_offset)", "self.last_standstill = False self.standstill_req = False self.steer_rate_limited = False self.standstill_hack", "1 # on entering standstill, send standstill request if CS.out.standstill", "import car from common.numpy_fast import clip, interp from selfdrive.car import", "new_actuators = actuators.copy() new_actuators.steer = apply_steer / CarControllerParams.STEER_MAX new_actuators.accel =", "= False self.last_steer = apply_steer self.last_standstill = CS.out.standstill can_sends =", "sending it at 100Hz seem to allow a higher rate", "class CarController(): def __init__(self, dbc_name, CP, VM): self.last_steer = 0", "at low speed we always assume the lead is present" ]
[]
[ "\"White\"), ('yellow', \"Yellow\"), ('lime', \"Green\"), (\"#ffa500\", \"Orange\")]) code_correction = SelectField('Error", "SelectField('Colour', choices=[('white', 'Colour'), (\"white\", \"White\"), ('yellow', \"Yellow\"), ('lime', \"Green\"), (\"#ffa500\",", "code_correction = SelectField('Error Correction', choices=[(\"H\", \"Error Correction\"), (\"H\", \"H\"), (\"L\",", "QRGenerator(FlaskForm): code_content = StringField('Content', validators=[DataRequired()]) code_size = SelectField('Size', choices=[('15', 'Size'),", "'15'), ('20', '20'), ('25', '25'), ('30', '30')]) code_color = SelectField('Colour',", "flask_wtf import FlaskForm from wtforms import StringField, SubmitField, SelectField from", "('lime', \"Green\"), (\"#ffa500\", \"Orange\")]) code_correction = SelectField('Error Correction', choices=[(\"H\", \"Error", "('5', '5'), ('10', '10'), ('15', '15'), ('20', '20'), ('25', '25'),", "import DataRequired class QRGenerator(FlaskForm): code_content = StringField('Content', validators=[DataRequired()]) code_size =", "StringField('Content', validators=[DataRequired()]) code_size = SelectField('Size', choices=[('15', 'Size'), ('5', '5'), ('10',", "DataRequired class QRGenerator(FlaskForm): code_content = StringField('Content', validators=[DataRequired()]) code_size = SelectField('Size',", "SelectField('Size', choices=[('15', 'Size'), ('5', '5'), ('10', '10'), ('15', '15'), ('20',", "'10'), ('15', '15'), ('20', '20'), ('25', '25'), ('30', '30')]) code_color", "'25'), ('30', '30')]) code_color = SelectField('Colour', choices=[('white', 'Colour'), (\"white\", \"White\"),", "= SelectField('Colour', choices=[('white', 'Colour'), (\"white\", \"White\"), ('yellow', \"Yellow\"), ('lime', \"Green\"),", "wtforms.validators import DataRequired class QRGenerator(FlaskForm): code_content = StringField('Content', validators=[DataRequired()]) code_size", "(\"L\", \"L\"), (\"M\", \"M\"), (\"Q\", \"Q\")]) code_image = StringField('Image URL')", "code_color = SelectField('Colour', choices=[('white', 'Colour'), (\"white\", \"White\"), ('yellow', \"Yellow\"), ('lime',", "\"Q\")]) code_image = StringField('Image URL') generate_code = SubmitField('Generate QR Code')", "('yellow', \"Yellow\"), ('lime', \"Green\"), (\"#ffa500\", \"Orange\")]) code_correction = SelectField('Error Correction',", "class QRGenerator(FlaskForm): code_content = StringField('Content', validators=[DataRequired()]) code_size = SelectField('Size', choices=[('15',", "(\"M\", \"M\"), (\"Q\", \"Q\")]) code_image = StringField('Image URL') generate_code =", "('10', '10'), ('15', '15'), ('20', '20'), ('25', '25'), ('30', '30')])", "'5'), ('10', '10'), ('15', '15'), ('20', '20'), ('25', '25'), ('30',", "'Size'), ('5', '5'), ('10', '10'), ('15', '15'), ('20', '20'), ('25',", "Correction\"), (\"H\", \"H\"), (\"L\", \"L\"), (\"M\", \"M\"), (\"Q\", \"Q\")]) code_image", "from flask_wtf import FlaskForm from wtforms import StringField, SubmitField, SelectField", "\"M\"), (\"Q\", \"Q\")]) code_image = StringField('Image URL') generate_code = SubmitField('Generate", "code_content = StringField('Content', validators=[DataRequired()]) code_size = SelectField('Size', choices=[('15', 'Size'), ('5',", "\"Yellow\"), ('lime', \"Green\"), (\"#ffa500\", \"Orange\")]) code_correction = SelectField('Error Correction', choices=[(\"H\",", "SelectField('Error Correction', choices=[(\"H\", \"Error Correction\"), (\"H\", \"H\"), (\"L\", \"L\"), (\"M\",", "SubmitField, SelectField from wtforms.validators import DataRequired class QRGenerator(FlaskForm): code_content =", "<gh_stars>1-10 from flask_wtf import FlaskForm from wtforms import StringField, SubmitField,", "\"L\"), (\"M\", \"M\"), (\"Q\", \"Q\")]) code_image = StringField('Image URL') generate_code", "= StringField('Content', validators=[DataRequired()]) code_size = SelectField('Size', choices=[('15', 'Size'), ('5', '5'),", "wtforms import StringField, SubmitField, SelectField from wtforms.validators import DataRequired class", "\"Green\"), (\"#ffa500\", \"Orange\")]) code_correction = SelectField('Error Correction', choices=[(\"H\", \"Error Correction\"),", "'Colour'), (\"white\", \"White\"), ('yellow', \"Yellow\"), ('lime', \"Green\"), (\"#ffa500\", \"Orange\")]) code_correction", "from wtforms.validators import DataRequired class QRGenerator(FlaskForm): code_content = StringField('Content', validators=[DataRequired()])", "('15', '15'), ('20', '20'), ('25', '25'), ('30', '30')]) code_color =", "choices=[(\"H\", \"Error Correction\"), (\"H\", \"H\"), (\"L\", \"L\"), (\"M\", \"M\"), (\"Q\",", "= SelectField('Size', choices=[('15', 'Size'), ('5', '5'), ('10', '10'), ('15', '15'),", "choices=[('white', 'Colour'), (\"white\", \"White\"), ('yellow', \"Yellow\"), ('lime', \"Green\"), (\"#ffa500\", \"Orange\")])", "Correction', choices=[(\"H\", \"Error Correction\"), (\"H\", \"H\"), (\"L\", \"L\"), (\"M\", \"M\"),", "(\"Q\", \"Q\")]) code_image = StringField('Image URL') generate_code = SubmitField('Generate QR", "choices=[('15', 'Size'), ('5', '5'), ('10', '10'), ('15', '15'), ('20', '20'),", "FlaskForm from wtforms import StringField, SubmitField, SelectField from wtforms.validators import", "import StringField, SubmitField, SelectField from wtforms.validators import DataRequired class QRGenerator(FlaskForm):", "import FlaskForm from wtforms import StringField, SubmitField, SelectField from wtforms.validators", "'20'), ('25', '25'), ('30', '30')]) code_color = SelectField('Colour', choices=[('white', 'Colour'),", "validators=[DataRequired()]) code_size = SelectField('Size', choices=[('15', 'Size'), ('5', '5'), ('10', '10'),", "code_size = SelectField('Size', choices=[('15', 'Size'), ('5', '5'), ('10', '10'), ('15',", "('30', '30')]) code_color = SelectField('Colour', choices=[('white', 'Colour'), (\"white\", \"White\"), ('yellow',", "('20', '20'), ('25', '25'), ('30', '30')]) code_color = SelectField('Colour', choices=[('white',", "= SelectField('Error Correction', choices=[(\"H\", \"Error Correction\"), (\"H\", \"H\"), (\"L\", \"L\"),", "SelectField from wtforms.validators import DataRequired class QRGenerator(FlaskForm): code_content = StringField('Content',", "(\"H\", \"H\"), (\"L\", \"L\"), (\"M\", \"M\"), (\"Q\", \"Q\")]) code_image =", "StringField, SubmitField, SelectField from wtforms.validators import DataRequired class QRGenerator(FlaskForm): code_content", "\"Error Correction\"), (\"H\", \"H\"), (\"L\", \"L\"), (\"M\", \"M\"), (\"Q\", \"Q\")])", "(\"#ffa500\", \"Orange\")]) code_correction = SelectField('Error Correction', choices=[(\"H\", \"Error Correction\"), (\"H\",", "from wtforms import StringField, SubmitField, SelectField from wtforms.validators import DataRequired", "(\"white\", \"White\"), ('yellow', \"Yellow\"), ('lime', \"Green\"), (\"#ffa500\", \"Orange\")]) code_correction =", "('25', '25'), ('30', '30')]) code_color = SelectField('Colour', choices=[('white', 'Colour'), (\"white\",", "\"Orange\")]) code_correction = SelectField('Error Correction', choices=[(\"H\", \"Error Correction\"), (\"H\", \"H\"),", "'30')]) code_color = SelectField('Colour', choices=[('white', 'Colour'), (\"white\", \"White\"), ('yellow', \"Yellow\"),", "\"H\"), (\"L\", \"L\"), (\"M\", \"M\"), (\"Q\", \"Q\")]) code_image = StringField('Image" ]
[ "for a stock. l : float The 'lambda' parameter of", "'lambda' parameter of the exponential moving average model. Making this", "pd.read_csv(filename, parse_dates=[ 'date'], index_col='date', squeeze=True) print(\"Most recent volatility estimate: {:.6f}\".format(estimate_volatility(prices,", "adjusted closing prices for a stock. l : float The", "estimate. Parameters ---------- prices : pandas.Series A series of adjusted", "volatility estimate. Parameters ---------- prices : pandas.Series A series of", "prices from a file.\"\"\" prices = pd.read_csv(filename, parse_dates=[ 'date'], index_col='date',", "will cause the model to weight older terms less relative", "of your exponential moving averge volatility model series. \"\"\" #", "of the volatility of a stock price, and return the", "exponential moving averge volatility model series. \"\"\" # TODO: Implement", "(last) volatility estimate. Parameters ---------- prices : pandas.Series A series", "def estimate_volatility(prices, l): \"\"\"Create an exponential moving average model of", "relative to more recent terms. Returns ------- last_vol : float", "exponential moving average volatility model and return the last value.", "last value. return prices.ewm(alpha=(1-l)).mean()[-1] def test_run(filename='data.csv'): \"\"\"Test run get_most_volatile() with", "run get_most_volatile() with stock prices from a file.\"\"\" prices =", "stock. l : float The 'lambda' parameter of the exponential", "moving average model of the volatility of a stock price,", "get_most_volatile() with stock prices from a file.\"\"\" prices = pd.read_csv(filename,", "with stock prices from a file.\"\"\" prices = pd.read_csv(filename, parse_dates=[", "your exponential moving averge volatility model series. \"\"\" # TODO:", "---------- prices : pandas.Series A series of adjusted closing prices", "prices = pd.read_csv(filename, parse_dates=[ 'date'], index_col='date', squeeze=True) print(\"Most recent volatility", "closing prices for a stock. l : float The 'lambda'", "prices : pandas.Series A series of adjusted closing prices for", "the most recent (last) volatility estimate. Parameters ---------- prices :", "float The 'lambda' parameter of the exponential moving average model.", "{:.6f}\".format(estimate_volatility(prices, 0.7))) # print(estimate_volatility(prices, 0.7)) if __name__ == '__main__': test_run()", "model. Making this value smaller will cause the model to", "volatility estimate: {:.6f}\".format(estimate_volatility(prices, 0.7))) # print(estimate_volatility(prices, 0.7)) if __name__ ==", "weight older terms less relative to more recent terms. Returns", "'date'], index_col='date', squeeze=True) print(\"Most recent volatility estimate: {:.6f}\".format(estimate_volatility(prices, 0.7))) #", "estimate: {:.6f}\".format(estimate_volatility(prices, 0.7))) # print(estimate_volatility(prices, 0.7)) if __name__ == '__main__':", "pd import numpy as np def estimate_volatility(prices, l): \"\"\"Create an", ": float The 'lambda' parameter of the exponential moving average", "\"\"\" # TODO: Implement the exponential moving average volatility model", "an exponential moving average model of the volatility of a", "The 'lambda' parameter of the exponential moving average model. Making", "terms. Returns ------- last_vol : float The last element of", "------- last_vol : float The last element of your exponential", "terms less relative to more recent terms. Returns ------- last_vol", "parameter of the exponential moving average model. Making this value", "the model to weight older terms less relative to more", "recent (last) volatility estimate. Parameters ---------- prices : pandas.Series A", "# TODO: Implement the exponential moving average volatility model and", "prices.ewm(alpha=(1-l)).mean()[-1] def test_run(filename='data.csv'): \"\"\"Test run get_most_volatile() with stock prices from", "moving average volatility model and return the last value. return", "series of adjusted closing prices for a stock. l :", "model series. \"\"\" # TODO: Implement the exponential moving average", "np def estimate_volatility(prices, l): \"\"\"Create an exponential moving average model", "series. \"\"\" # TODO: Implement the exponential moving average volatility", "index_col='date', squeeze=True) print(\"Most recent volatility estimate: {:.6f}\".format(estimate_volatility(prices, 0.7))) # print(estimate_volatility(prices,", "float The last element of your exponential moving averge volatility", "prices for a stock. l : float The 'lambda' parameter", "def test_run(filename='data.csv'): \"\"\"Test run get_most_volatile() with stock prices from a", "most recent (last) volatility estimate. Parameters ---------- prices : pandas.Series", "less relative to more recent terms. Returns ------- last_vol :", "print(\"Most recent volatility estimate: {:.6f}\".format(estimate_volatility(prices, 0.7))) # print(estimate_volatility(prices, 0.7)) if", ": pandas.Series A series of adjusted closing prices for a", "Parameters ---------- prices : pandas.Series A series of adjusted closing", "smaller will cause the model to weight older terms less", "the exponential moving average volatility model and return the last", "parse_dates=[ 'date'], index_col='date', squeeze=True) print(\"Most recent volatility estimate: {:.6f}\".format(estimate_volatility(prices, 0.7)))", "the exponential moving average model. Making this value smaller will", "recent terms. Returns ------- last_vol : float The last element", "average model. Making this value smaller will cause the model", "older terms less relative to more recent terms. Returns -------", "A series of adjusted closing prices for a stock. l", "value. return prices.ewm(alpha=(1-l)).mean()[-1] def test_run(filename='data.csv'): \"\"\"Test run get_most_volatile() with stock", "volatility of a stock price, and return the most recent", "of the exponential moving average model. Making this value smaller", "l): \"\"\"Create an exponential moving average model of the volatility", "recent volatility estimate: {:.6f}\".format(estimate_volatility(prices, 0.7))) # print(estimate_volatility(prices, 0.7)) if __name__", "of a stock price, and return the most recent (last)", "as np def estimate_volatility(prices, l): \"\"\"Create an exponential moving average", "of adjusted closing prices for a stock. l : float", "cause the model to weight older terms less relative to", "moving averge volatility model series. \"\"\" # TODO: Implement the", "l : float The 'lambda' parameter of the exponential moving", "moving average model. Making this value smaller will cause the", "Making this value smaller will cause the model to weight", "pandas.Series A series of adjusted closing prices for a stock.", "pandas as pd import numpy as np def estimate_volatility(prices, l):", "exponential moving average model of the volatility of a stock", "the volatility of a stock price, and return the most", "volatility model series. \"\"\" # TODO: Implement the exponential moving", "averge volatility model series. \"\"\" # TODO: Implement the exponential", "import numpy as np def estimate_volatility(prices, l): \"\"\"Create an exponential", "this value smaller will cause the model to weight older", "to more recent terms. Returns ------- last_vol : float The", "element of your exponential moving averge volatility model series. \"\"\"", "from a file.\"\"\" prices = pd.read_csv(filename, parse_dates=[ 'date'], index_col='date', squeeze=True)", "last_vol : float The last element of your exponential moving", "stock price, and return the most recent (last) volatility estimate.", "return the last value. return prices.ewm(alpha=(1-l)).mean()[-1] def test_run(filename='data.csv'): \"\"\"Test run", "Returns ------- last_vol : float The last element of your", "as pd import numpy as np def estimate_volatility(prices, l): \"\"\"Create", "file.\"\"\" prices = pd.read_csv(filename, parse_dates=[ 'date'], index_col='date', squeeze=True) print(\"Most recent", "\"\"\"Test run get_most_volatile() with stock prices from a file.\"\"\" prices", "model and return the last value. return prices.ewm(alpha=(1-l)).mean()[-1] def test_run(filename='data.csv'):", "and return the most recent (last) volatility estimate. Parameters ----------", "to weight older terms less relative to more recent terms.", "exponential moving average model. Making this value smaller will cause", "numpy as np def estimate_volatility(prices, l): \"\"\"Create an exponential moving", "volatility model and return the last value. return prices.ewm(alpha=(1-l)).mean()[-1] def", "and return the last value. return prices.ewm(alpha=(1-l)).mean()[-1] def test_run(filename='data.csv'): \"\"\"Test", "a stock. l : float The 'lambda' parameter of the", "the last value. return prices.ewm(alpha=(1-l)).mean()[-1] def test_run(filename='data.csv'): \"\"\"Test run get_most_volatile()", "return prices.ewm(alpha=(1-l)).mean()[-1] def test_run(filename='data.csv'): \"\"\"Test run get_most_volatile() with stock prices", "average volatility model and return the last value. return prices.ewm(alpha=(1-l)).mean()[-1]", "model of the volatility of a stock price, and return", "value smaller will cause the model to weight older terms", "return the most recent (last) volatility estimate. Parameters ---------- prices", "\"\"\"Create an exponential moving average model of the volatility of", "stock prices from a file.\"\"\" prices = pd.read_csv(filename, parse_dates=[ 'date'],", "last element of your exponential moving averge volatility model series.", "estimate_volatility(prices, l): \"\"\"Create an exponential moving average model of the", "The last element of your exponential moving averge volatility model", "a file.\"\"\" prices = pd.read_csv(filename, parse_dates=[ 'date'], index_col='date', squeeze=True) print(\"Most", "a stock price, and return the most recent (last) volatility", "TODO: Implement the exponential moving average volatility model and return", ": float The last element of your exponential moving averge", "import pandas as pd import numpy as np def estimate_volatility(prices,", "= pd.read_csv(filename, parse_dates=[ 'date'], index_col='date', squeeze=True) print(\"Most recent volatility estimate:", "price, and return the most recent (last) volatility estimate. Parameters", "test_run(filename='data.csv'): \"\"\"Test run get_most_volatile() with stock prices from a file.\"\"\"", "model to weight older terms less relative to more recent", "squeeze=True) print(\"Most recent volatility estimate: {:.6f}\".format(estimate_volatility(prices, 0.7))) # print(estimate_volatility(prices, 0.7))", "more recent terms. Returns ------- last_vol : float The last", "Implement the exponential moving average volatility model and return the", "average model of the volatility of a stock price, and" ]
[ "map(int, sys.stdin.readline().split()) s = '$' + sys.stdin.readline().rstrip() lr = zip(*[map(int,", "1); res[0] = 0 prev = '$' for i in", "and s[i] == 'C') & 1 prev = s[i] for", "lr = zip(*[map(int, sys.stdin.read().split())] * 2) def main(): res =", "'$' + sys.stdin.readline().rstrip() lr = zip(*[map(int, sys.stdin.read().split())] * 2) def", "+ sys.stdin.readline().rstrip() lr = zip(*[map(int, sys.stdin.read().split())] * 2) def main():", "sys.stdin.read().split())] * 2) def main(): res = [None] * (n", "2) def main(): res = [None] * (n + 1);", "sys.stdin.readline().rstrip() lr = zip(*[map(int, sys.stdin.read().split())] * 2) def main(): res", "'$' for i in range(1, n+1): res[i] = res[i-1] res[i]", "n, q = map(int, sys.stdin.readline().split()) s = '$' + sys.stdin.readline().rstrip()", "= zip(*[map(int, sys.stdin.read().split())] * 2) def main(): res = [None]", "'A' and s[i] == 'C') & 1 prev = s[i]", "+ 1); res[0] = 0 prev = '$' for i", "zip(*[map(int, sys.stdin.read().split())] * 2) def main(): res = [None] *", "& 1 prev = s[i] for l, r in lr:", "res[r] - res[l] if __name__ == '__main__': ans = main()", "- res[l] if __name__ == '__main__': ans = main() print(*ans,", "s = '$' + sys.stdin.readline().rstrip() lr = zip(*[map(int, sys.stdin.read().split())] *", "== 'A' and s[i] == 'C') & 1 prev =", "in lr: yield res[r] - res[l] if __name__ == '__main__':", "= s[i] for l, r in lr: yield res[r] -", "* (n + 1); res[0] = 0 prev = '$'", "for l, r in lr: yield res[r] - res[l] if", "sys n, q = map(int, sys.stdin.readline().split()) s = '$' +", "res[0] = 0 prev = '$' for i in range(1,", "prev = s[i] for l, r in lr: yield res[r]", "* 2) def main(): res = [None] * (n +", "n+1): res[i] = res[i-1] res[i] += (prev == 'A' and", "res[i-1] res[i] += (prev == 'A' and s[i] == 'C')", "(prev == 'A' and s[i] == 'C') & 1 prev", "res[l] if __name__ == '__main__': ans = main() print(*ans, sep='\\n')", "lr: yield res[r] - res[l] if __name__ == '__main__': ans", "main(): res = [None] * (n + 1); res[0] =", "res[i] = res[i-1] res[i] += (prev == 'A' and s[i]", "1 prev = s[i] for l, r in lr: yield", "[None] * (n + 1); res[0] = 0 prev =", "res[i] += (prev == 'A' and s[i] == 'C') &", "s[i] == 'C') & 1 prev = s[i] for l,", "== 'C') & 1 prev = s[i] for l, r", "prev = '$' for i in range(1, n+1): res[i] =", "'C') & 1 prev = s[i] for l, r in", "= '$' + sys.stdin.readline().rstrip() lr = zip(*[map(int, sys.stdin.read().split())] * 2)", "q = map(int, sys.stdin.readline().split()) s = '$' + sys.stdin.readline().rstrip() lr", "sys.stdin.readline().split()) s = '$' + sys.stdin.readline().rstrip() lr = zip(*[map(int, sys.stdin.read().split())]", "i in range(1, n+1): res[i] = res[i-1] res[i] += (prev", "in range(1, n+1): res[i] = res[i-1] res[i] += (prev ==", "import sys n, q = map(int, sys.stdin.readline().split()) s = '$'", "= 0 prev = '$' for i in range(1, n+1):", "s[i] for l, r in lr: yield res[r] - res[l]", "r in lr: yield res[r] - res[l] if __name__ ==", "(n + 1); res[0] = 0 prev = '$' for", "def main(): res = [None] * (n + 1); res[0]", "0 prev = '$' for i in range(1, n+1): res[i]", "= '$' for i in range(1, n+1): res[i] = res[i-1]", "= res[i-1] res[i] += (prev == 'A' and s[i] ==", "+= (prev == 'A' and s[i] == 'C') & 1", "for i in range(1, n+1): res[i] = res[i-1] res[i] +=", "yield res[r] - res[l] if __name__ == '__main__': ans =", "res = [None] * (n + 1); res[0] = 0", "l, r in lr: yield res[r] - res[l] if __name__", "= [None] * (n + 1); res[0] = 0 prev", "= map(int, sys.stdin.readline().split()) s = '$' + sys.stdin.readline().rstrip() lr =", "range(1, n+1): res[i] = res[i-1] res[i] += (prev == 'A'" ]
[ "trg.shape[1] pos = torch.arange(0, trg_len).unsqueeze(0).repeat(batch_size, 1).to(self.device) #pos = [batch size,", "= [batch size, trg len, embed dim] for layer in", "embed_dim): pos_enc = torch.zeros(max_seq_len, embed_dim) position = torch.arange(0, max_seq_len).unsqueeze(1) div_term", "[batch size, src len, embed dim] #trg_mask = [batch size,", "[batch size, 1, 1, src len] batch_size = trg.shape[0] trg_len", "len] trg = self.dropout((self.tok_embedding(trg) * self.scale) + self.pos_embedding(pos)) #trg =", "trg len] #src_mask = [batch size, 1, 1, src len]", "device def forward(self, trg, enc_src, trg_mask, src_mask): #trg = [batch", "= nn.Dropout(dropout) self.scale = torch.sqrt(torch.FloatTensor([embed_dim])).to(device) self.device = device def forward(self,", "dropout, device, max_length = 30): super().__init__() self.tok_embedding = nn.Embedding(output_dim, embed_dim)", "trg_len = trg.shape[1] pos = torch.arange(0, trg_len).unsqueeze(0).repeat(batch_size, 1).to(self.device) #pos =", "= nn.Linear(embed_dim, output_dim) self.dropout = nn.Dropout(dropout) self.scale = torch.sqrt(torch.FloatTensor([embed_dim])).to(device) self.device", "in range(num_layers)]) self.fc_out = nn.Linear(embed_dim, output_dim) self.dropout = nn.Dropout(dropout) self.scale", "#enc_src = [batch size, src len, embed dim] #trg_mask =", "dim] return output def get_positional_encoding(self, max_seq_len, embed_dim): pos_enc = torch.zeros(max_seq_len,", "nn.Dropout(dropout) self.scale = torch.sqrt(torch.FloatTensor([embed_dim])).to(device) self.device = device def forward(self, trg,", "= nn.Embedding(output_dim, embed_dim) #self.pos_embedding = nn.Embedding(max_length, embed_dim) self.pos_embedding = nn.Embedding.from_pretrained(self.get_positional_encoding(max_length,", "dropout) for _ in range(num_layers)]) self.fc_out = nn.Linear(embed_dim, output_dim) self.dropout", "self.dropout((self.tok_embedding(trg) * self.scale) + self.pos_embedding(pos)) #trg = [batch size, trg", "trg len, output dim] return output def get_positional_encoding(self, max_seq_len, embed_dim):", "trg len] trg = self.dropout((self.tok_embedding(trg) * self.scale) + self.pos_embedding(pos)) #trg", "embed dim] for layer in self.layers: trg = layer(trg, enc_src,", "max_length = 30): super().__init__() self.tok_embedding = nn.Embedding(output_dim, embed_dim) #self.pos_embedding =", "self.tok_embedding = nn.Embedding(output_dim, embed_dim) #self.pos_embedding = nn.Embedding(max_length, embed_dim) self.pos_embedding =", "size, trg len, embed dim] for layer in self.layers: trg", "size, trg len] trg = self.dropout((self.tok_embedding(trg) * self.scale) + self.pos_embedding(pos))", "embed_dim) self.pos_embedding = nn.Embedding.from_pretrained(self.get_positional_encoding(max_length, embed_dim)) self.layers = nn.ModuleList([DecoderLayer(embed_dim, num_heads, expand_dim,", "src len] batch_size = trg.shape[0] trg_len = trg.shape[1] pos =", "torch.zeros(max_seq_len, embed_dim) position = torch.arange(0, max_seq_len).unsqueeze(1) div_term = torch.exp(torch.arange(0, embed_dim,", "= [batch size, trg len] trg = self.dropout((self.tok_embedding(trg) * self.scale)", "nn.Embedding(output_dim, embed_dim) #self.pos_embedding = nn.Embedding(max_length, embed_dim) self.pos_embedding = nn.Embedding.from_pretrained(self.get_positional_encoding(max_length, embed_dim))", "self.layers = nn.ModuleList([DecoderLayer(embed_dim, num_heads, expand_dim, dropout) for _ in range(num_layers)])", "expand_dim, dropout, device, max_length = 30): super().__init__() self.tok_embedding = nn.Embedding(output_dim,", "trg.shape[0] trg_len = trg.shape[1] pos = torch.arange(0, trg_len).unsqueeze(0).repeat(batch_size, 1).to(self.device) #pos", "expand_dim, dropout) for _ in range(num_layers)]) self.fc_out = nn.Linear(embed_dim, output_dim)", "= self.dropout((self.tok_embedding(trg) * self.scale) + self.pos_embedding(pos)) #trg = [batch size,", "nn from DecoderLayer import DecoderLayer import math class Decoder(nn.Module): def", "def get_positional_encoding(self, max_seq_len, embed_dim): pos_enc = torch.zeros(max_seq_len, embed_dim) position =", "torch.exp(torch.arange(0, embed_dim, 2) * (-math.log(10000.0) / embed_dim)) pos_enc[:, 0::2] =", "torch import torch.nn as nn from DecoderLayer import DecoderLayer import", "def __init__(self, output_dim, embed_dim, num_layers, num_heads, expand_dim, dropout, device, max_length", "output = self.fc_out(trg) #output = [batch size, trg len, output", "size, src len, embed dim] #trg_mask = [batch size, 1,", "output_dim, embed_dim, num_layers, num_heads, expand_dim, dropout, device, max_length = 30):", "class Decoder(nn.Module): def __init__(self, output_dim, embed_dim, num_layers, num_heads, expand_dim, dropout,", "torch.arange(0, trg_len).unsqueeze(0).repeat(batch_size, 1).to(self.device) #pos = [batch size, trg len] trg", "nn.Linear(embed_dim, output_dim) self.dropout = nn.Dropout(dropout) self.scale = torch.sqrt(torch.FloatTensor([embed_dim])).to(device) self.device =", "DecoderLayer import DecoderLayer import math class Decoder(nn.Module): def __init__(self, output_dim,", "1, src len] batch_size = trg.shape[0] trg_len = trg.shape[1] pos", "= nn.ModuleList([DecoderLayer(embed_dim, num_heads, expand_dim, dropout) for _ in range(num_layers)]) self.fc_out", "dim] output = self.fc_out(trg) #output = [batch size, trg len,", "DecoderLayer import math class Decoder(nn.Module): def __init__(self, output_dim, embed_dim, num_layers,", "= trg.shape[1] pos = torch.arange(0, trg_len).unsqueeze(0).repeat(batch_size, 1).to(self.device) #pos = [batch", "trg len, trg len] #src_mask = [batch size, 1, 1,", "<filename>Decoder.py import torch import torch.nn as nn from DecoderLayer import", "[batch size, trg len] trg = self.dropout((self.tok_embedding(trg) * self.scale) +", "nn.Embedding.from_pretrained(self.get_positional_encoding(max_length, embed_dim)) self.layers = nn.ModuleList([DecoderLayer(embed_dim, num_heads, expand_dim, dropout) for _", "self.dropout = nn.Dropout(dropout) self.scale = torch.sqrt(torch.FloatTensor([embed_dim])).to(device) self.device = device def", "[batch size, trg len, embed dim] output = self.fc_out(trg) #output", "= device def forward(self, trg, enc_src, trg_mask, src_mask): #trg =", "len, embed dim] for layer in self.layers: trg = layer(trg,", "output dim] return output def get_positional_encoding(self, max_seq_len, embed_dim): pos_enc =", "trg_mask, src_mask) #trg = [batch size, trg len, embed dim]", "= 30): super().__init__() self.tok_embedding = nn.Embedding(output_dim, embed_dim) #self.pos_embedding = nn.Embedding(max_length,", "1, 1, src len] batch_size = trg.shape[0] trg_len = trg.shape[1]", "src_mask): #trg = [batch size, trg len] #enc_src = [batch", "trg_len).unsqueeze(0).repeat(batch_size, 1).to(self.device) #pos = [batch size, trg len] trg =", "self.pos_embedding = nn.Embedding.from_pretrained(self.get_positional_encoding(max_length, embed_dim)) self.layers = nn.ModuleList([DecoderLayer(embed_dim, num_heads, expand_dim, dropout)", "torch.nn as nn from DecoderLayer import DecoderLayer import math class", "= [batch size, trg len, embed dim] output = self.fc_out(trg)", "batch_size = trg.shape[0] trg_len = trg.shape[1] pos = torch.arange(0, trg_len).unsqueeze(0).repeat(batch_size,", "import torch.nn as nn from DecoderLayer import DecoderLayer import math", "enc_src, trg_mask, src_mask) #trg = [batch size, trg len, embed", "trg len, embed dim] output = self.fc_out(trg) #output = [batch", "= torch.arange(0, max_seq_len).unsqueeze(1) div_term = torch.exp(torch.arange(0, embed_dim, 2) * (-math.log(10000.0)", "trg len] #enc_src = [batch size, src len, embed dim]", "(-math.log(10000.0) / embed_dim)) pos_enc[:, 0::2] = torch.sin(position * div_term) pos_enc[:,", "embed_dim)) self.layers = nn.ModuleList([DecoderLayer(embed_dim, num_heads, expand_dim, dropout) for _ in", "= [batch size, 1, 1, src len] batch_size = trg.shape[0]", "for _ in range(num_layers)]) self.fc_out = nn.Linear(embed_dim, output_dim) self.dropout =", "* self.scale) + self.pos_embedding(pos)) #trg = [batch size, trg len,", "len] #src_mask = [batch size, 1, 1, src len] batch_size", "[batch size, trg len, output dim] return output def get_positional_encoding(self,", "embed_dim, num_layers, num_heads, expand_dim, dropout, device, max_length = 30): super().__init__()", "_ in range(num_layers)]) self.fc_out = nn.Linear(embed_dim, output_dim) self.dropout = nn.Dropout(dropout)", "trg len, embed dim] for layer in self.layers: trg =", "#trg = [batch size, trg len, embed dim] output =", "= trg.shape[0] trg_len = trg.shape[1] pos = torch.arange(0, trg_len).unsqueeze(0).repeat(batch_size, 1).to(self.device)", "import math class Decoder(nn.Module): def __init__(self, output_dim, embed_dim, num_layers, num_heads,", "#self.pos_embedding = nn.Embedding(max_length, embed_dim) self.pos_embedding = nn.Embedding.from_pretrained(self.get_positional_encoding(max_length, embed_dim)) self.layers =", "return output def get_positional_encoding(self, max_seq_len, embed_dim): pos_enc = torch.zeros(max_seq_len, embed_dim)", "range(num_layers)]) self.fc_out = nn.Linear(embed_dim, output_dim) self.dropout = nn.Dropout(dropout) self.scale =", "= torch.arange(0, trg_len).unsqueeze(0).repeat(batch_size, 1).to(self.device) #pos = [batch size, trg len]", "for layer in self.layers: trg = layer(trg, enc_src, trg_mask, src_mask)", "len, output dim] return output def get_positional_encoding(self, max_seq_len, embed_dim): pos_enc", "num_layers, num_heads, expand_dim, dropout, device, max_length = 30): super().__init__() self.tok_embedding", "output def get_positional_encoding(self, max_seq_len, embed_dim): pos_enc = torch.zeros(max_seq_len, embed_dim) position", "0::2] = torch.sin(position * div_term) pos_enc[:, 1::2] = torch.cos(position *", "device, max_length = 30): super().__init__() self.tok_embedding = nn.Embedding(output_dim, embed_dim) #self.pos_embedding", "= [batch size, trg len] #enc_src = [batch size, src", "embed dim] output = self.fc_out(trg) #output = [batch size, trg", "self.device = device def forward(self, trg, enc_src, trg_mask, src_mask): #trg", "def forward(self, trg, enc_src, trg_mask, src_mask): #trg = [batch size,", "forward(self, trg, enc_src, trg_mask, src_mask): #trg = [batch size, trg", "as nn from DecoderLayer import DecoderLayer import math class Decoder(nn.Module):", "size, trg len, output dim] return output def get_positional_encoding(self, max_seq_len,", "len, embed dim] output = self.fc_out(trg) #output = [batch size,", "math class Decoder(nn.Module): def __init__(self, output_dim, embed_dim, num_layers, num_heads, expand_dim,", "#src_mask = [batch size, 1, 1, src len] batch_size =", "embed_dim)) pos_enc[:, 0::2] = torch.sin(position * div_term) pos_enc[:, 1::2] =", "#trg_mask = [batch size, 1, trg len, trg len] #src_mask", "in self.layers: trg = layer(trg, enc_src, trg_mask, src_mask) #trg =", "2) * (-math.log(10000.0) / embed_dim)) pos_enc[:, 0::2] = torch.sin(position *", "enc_src, trg_mask, src_mask): #trg = [batch size, trg len] #enc_src", "position = torch.arange(0, max_seq_len).unsqueeze(1) div_term = torch.exp(torch.arange(0, embed_dim, 2) *", "layer in self.layers: trg = layer(trg, enc_src, trg_mask, src_mask) #trg", "torch.sin(position * div_term) pos_enc[:, 1::2] = torch.cos(position * div_term) return", "len, trg len] #src_mask = [batch size, 1, 1, src", "30): super().__init__() self.tok_embedding = nn.Embedding(output_dim, embed_dim) #self.pos_embedding = nn.Embedding(max_length, embed_dim)", "= [batch size, trg len, output dim] return output def", "num_heads, expand_dim, dropout, device, max_length = 30): super().__init__() self.tok_embedding =", "div_term = torch.exp(torch.arange(0, embed_dim, 2) * (-math.log(10000.0) / embed_dim)) pos_enc[:,", "src_mask) #trg = [batch size, trg len, embed dim] output", "get_positional_encoding(self, max_seq_len, embed_dim): pos_enc = torch.zeros(max_seq_len, embed_dim) position = torch.arange(0,", "= torch.exp(torch.arange(0, embed_dim, 2) * (-math.log(10000.0) / embed_dim)) pos_enc[:, 0::2]", "= [batch size, src len, embed dim] #trg_mask = [batch", "trg = self.dropout((self.tok_embedding(trg) * self.scale) + self.pos_embedding(pos)) #trg = [batch", "src len, embed dim] #trg_mask = [batch size, 1, trg", "/ embed_dim)) pos_enc[:, 0::2] = torch.sin(position * div_term) pos_enc[:, 1::2]", "self.scale = torch.sqrt(torch.FloatTensor([embed_dim])).to(device) self.device = device def forward(self, trg, enc_src,", "= [batch size, 1, trg len, trg len] #src_mask =", "1, trg len, trg len] #src_mask = [batch size, 1,", "size, 1, 1, src len] batch_size = trg.shape[0] trg_len =", "* (-math.log(10000.0) / embed_dim)) pos_enc[:, 0::2] = torch.sin(position * div_term)", "pos_enc = torch.zeros(max_seq_len, embed_dim) position = torch.arange(0, max_seq_len).unsqueeze(1) div_term =", "self.pos_embedding(pos)) #trg = [batch size, trg len, embed dim] for", "embed_dim) #self.pos_embedding = nn.Embedding(max_length, embed_dim) self.pos_embedding = nn.Embedding.from_pretrained(self.get_positional_encoding(max_length, embed_dim)) self.layers", "size, 1, trg len, trg len] #src_mask = [batch size,", "nn.ModuleList([DecoderLayer(embed_dim, num_heads, expand_dim, dropout) for _ in range(num_layers)]) self.fc_out =", "size, trg len] #enc_src = [batch size, src len, embed", "self.fc_out(trg) #output = [batch size, trg len, output dim] return", "len] #enc_src = [batch size, src len, embed dim] #trg_mask", "dim] #trg_mask = [batch size, 1, trg len, trg len]", "output_dim) self.dropout = nn.Dropout(dropout) self.scale = torch.sqrt(torch.FloatTensor([embed_dim])).to(device) self.device = device", "torch.arange(0, max_seq_len).unsqueeze(1) div_term = torch.exp(torch.arange(0, embed_dim, 2) * (-math.log(10000.0) /", "self.scale) + self.pos_embedding(pos)) #trg = [batch size, trg len, embed", "layer(trg, enc_src, trg_mask, src_mask) #trg = [batch size, trg len,", "#output = [batch size, trg len, output dim] return output", "embed_dim, 2) * (-math.log(10000.0) / embed_dim)) pos_enc[:, 0::2] = torch.sin(position", "dim] for layer in self.layers: trg = layer(trg, enc_src, trg_mask,", "import torch import torch.nn as nn from DecoderLayer import DecoderLayer", "import DecoderLayer import math class Decoder(nn.Module): def __init__(self, output_dim, embed_dim,", "torch.sqrt(torch.FloatTensor([embed_dim])).to(device) self.device = device def forward(self, trg, enc_src, trg_mask, src_mask):", "[batch size, trg len, embed dim] for layer in self.layers:", "= nn.Embedding.from_pretrained(self.get_positional_encoding(max_length, embed_dim)) self.layers = nn.ModuleList([DecoderLayer(embed_dim, num_heads, expand_dim, dropout) for", "= layer(trg, enc_src, trg_mask, src_mask) #trg = [batch size, trg", "nn.Embedding(max_length, embed_dim) self.pos_embedding = nn.Embedding.from_pretrained(self.get_positional_encoding(max_length, embed_dim)) self.layers = nn.ModuleList([DecoderLayer(embed_dim, num_heads,", "max_seq_len, embed_dim): pos_enc = torch.zeros(max_seq_len, embed_dim) position = torch.arange(0, max_seq_len).unsqueeze(1)", "= self.fc_out(trg) #output = [batch size, trg len, output dim]", "= torch.zeros(max_seq_len, embed_dim) position = torch.arange(0, max_seq_len).unsqueeze(1) div_term = torch.exp(torch.arange(0,", "__init__(self, output_dim, embed_dim, num_layers, num_heads, expand_dim, dropout, device, max_length =", "= nn.Embedding(max_length, embed_dim) self.pos_embedding = nn.Embedding.from_pretrained(self.get_positional_encoding(max_length, embed_dim)) self.layers = nn.ModuleList([DecoderLayer(embed_dim,", "#pos = [batch size, trg len] trg = self.dropout((self.tok_embedding(trg) *", "= torch.sqrt(torch.FloatTensor([embed_dim])).to(device) self.device = device def forward(self, trg, enc_src, trg_mask,", "#trg = [batch size, trg len, embed dim] for layer", "embed_dim) position = torch.arange(0, max_seq_len).unsqueeze(1) div_term = torch.exp(torch.arange(0, embed_dim, 2)", "len] batch_size = trg.shape[0] trg_len = trg.shape[1] pos = torch.arange(0,", "super().__init__() self.tok_embedding = nn.Embedding(output_dim, embed_dim) #self.pos_embedding = nn.Embedding(max_length, embed_dim) self.pos_embedding", "pos = torch.arange(0, trg_len).unsqueeze(0).repeat(batch_size, 1).to(self.device) #pos = [batch size, trg", "trg, enc_src, trg_mask, src_mask): #trg = [batch size, trg len]", "[batch size, trg len] #enc_src = [batch size, src len,", "+ self.pos_embedding(pos)) #trg = [batch size, trg len, embed dim]", "trg = layer(trg, enc_src, trg_mask, src_mask) #trg = [batch size,", "[batch size, 1, trg len, trg len] #src_mask = [batch", "pos_enc[:, 0::2] = torch.sin(position * div_term) pos_enc[:, 1::2] = torch.cos(position", "Decoder(nn.Module): def __init__(self, output_dim, embed_dim, num_layers, num_heads, expand_dim, dropout, device,", "size, trg len, embed dim] output = self.fc_out(trg) #output =", "len, embed dim] #trg_mask = [batch size, 1, trg len,", "* div_term) pos_enc[:, 1::2] = torch.cos(position * div_term) return pos_enc", "embed dim] #trg_mask = [batch size, 1, trg len, trg", "num_heads, expand_dim, dropout) for _ in range(num_layers)]) self.fc_out = nn.Linear(embed_dim,", "trg_mask, src_mask): #trg = [batch size, trg len] #enc_src =", "1).to(self.device) #pos = [batch size, trg len] trg = self.dropout((self.tok_embedding(trg)", "self.layers: trg = layer(trg, enc_src, trg_mask, src_mask) #trg = [batch", "= torch.sin(position * div_term) pos_enc[:, 1::2] = torch.cos(position * div_term)", "#trg = [batch size, trg len] #enc_src = [batch size,", "self.fc_out = nn.Linear(embed_dim, output_dim) self.dropout = nn.Dropout(dropout) self.scale = torch.sqrt(torch.FloatTensor([embed_dim])).to(device)", "max_seq_len).unsqueeze(1) div_term = torch.exp(torch.arange(0, embed_dim, 2) * (-math.log(10000.0) / embed_dim))", "from DecoderLayer import DecoderLayer import math class Decoder(nn.Module): def __init__(self," ]
[ "salt.utils.nxos import salt.utils.platform from salt.exceptions import NxosClientError log = logging.getLogger(__name__)", "Cisco NX-OS minions .. versionadded:: 2016.11.0 For documentation on setting", "minions .. versionadded:: 2016.11.0 For documentation on setting up the", "except NxosClientError as err: return False, err return __virtualname__ def", "versionadded:: 2016.11.0 For documentation on setting up the nxos proxy", "documentation for :mod:`salt.proxy.nxos<salt.proxy.nxos>`. \"\"\" import logging import salt.utils.nxos import salt.utils.platform", "\"\"\" import logging import salt.utils.nxos import salt.utils.platform from salt.exceptions import", "import NxosClientError log = logging.getLogger(__name__) __proxyenabled__ = [\"nxos\"] __virtualname__ =", "None: return {} if proxy[\"nxos.initialized\"]() is False: return {} return", "__virtual__(): try: salt.utils.nxos.version_info() except NxosClientError as err: return False, err", "return False, err return __virtualname__ def system_information(proxy=None): if salt.utils.platform.is_proxy(): if", "up the nxos proxy minion look in the documentation for", "proxy is None: return {} if proxy[\"nxos.initialized\"]() is False: return", ".. versionadded:: 2016.11.0 For documentation on setting up the nxos", "__virtualname__ = \"nxos\" def __virtual__(): try: salt.utils.nxos.version_info() except NxosClientError as", "proxy[\"nxos.initialized\"]() is False: return {} return {\"nxos\": proxy[\"nxos.grains\"]()} else: data", "minion look in the documentation for :mod:`salt.proxy.nxos<salt.proxy.nxos>`. \"\"\" import logging", "= [\"nxos\"] __virtualname__ = \"nxos\" def __virtual__(): try: salt.utils.nxos.version_info() except", "salt.utils.platform from salt.exceptions import NxosClientError log = logging.getLogger(__name__) __proxyenabled__ =", "for :mod:`salt.proxy.nxos<salt.proxy.nxos>`. \"\"\" import logging import salt.utils.nxos import salt.utils.platform from", "__virtualname__ def system_information(proxy=None): if salt.utils.platform.is_proxy(): if proxy is None: return", "the nxos proxy minion look in the documentation for :mod:`salt.proxy.nxos<salt.proxy.nxos>`.", "look in the documentation for :mod:`salt.proxy.nxos<salt.proxy.nxos>`. \"\"\" import logging import", "return {} return {\"nxos\": proxy[\"nxos.grains\"]()} else: data = salt.utils.nxos.version_info() return", "if proxy[\"nxos.initialized\"]() is False: return {} return {\"nxos\": proxy[\"nxos.grains\"]()} else:", "as err: return False, err return __virtualname__ def system_information(proxy=None): if", "Grains for Cisco NX-OS minions .. versionadded:: 2016.11.0 For documentation", "log = logging.getLogger(__name__) __proxyenabled__ = [\"nxos\"] __virtualname__ = \"nxos\" def", "\"\"\" Grains for Cisco NX-OS minions .. versionadded:: 2016.11.0 For", "NxosClientError as err: return False, err return __virtualname__ def system_information(proxy=None):", "for Cisco NX-OS minions .. versionadded:: 2016.11.0 For documentation on", "import salt.utils.platform from salt.exceptions import NxosClientError log = logging.getLogger(__name__) __proxyenabled__", "salt.exceptions import NxosClientError log = logging.getLogger(__name__) __proxyenabled__ = [\"nxos\"] __virtualname__", "if salt.utils.platform.is_proxy(): if proxy is None: return {} if proxy[\"nxos.initialized\"]()", "False, err return __virtualname__ def system_information(proxy=None): if salt.utils.platform.is_proxy(): if proxy", "{} if proxy[\"nxos.initialized\"]() is False: return {} return {\"nxos\": proxy[\"nxos.grains\"]()}", "err return __virtualname__ def system_information(proxy=None): if salt.utils.platform.is_proxy(): if proxy is", "NX-OS minions .. versionadded:: 2016.11.0 For documentation on setting up", "the documentation for :mod:`salt.proxy.nxos<salt.proxy.nxos>`. \"\"\" import logging import salt.utils.nxos import", "is False: return {} return {\"nxos\": proxy[\"nxos.grains\"]()} else: data =", "proxy minion look in the documentation for :mod:`salt.proxy.nxos<salt.proxy.nxos>`. \"\"\" import", "logging.getLogger(__name__) __proxyenabled__ = [\"nxos\"] __virtualname__ = \"nxos\" def __virtual__(): try:", "system_information(proxy=None): if salt.utils.platform.is_proxy(): if proxy is None: return {} if", "in the documentation for :mod:`salt.proxy.nxos<salt.proxy.nxos>`. \"\"\" import logging import salt.utils.nxos", "salt.utils.nxos.version_info() except NxosClientError as err: return False, err return __virtualname__", "err: return False, err return __virtualname__ def system_information(proxy=None): if salt.utils.platform.is_proxy():", "import logging import salt.utils.nxos import salt.utils.platform from salt.exceptions import NxosClientError", "<gh_stars>1000+ \"\"\" Grains for Cisco NX-OS minions .. versionadded:: 2016.11.0", "= \"nxos\" def __virtual__(): try: salt.utils.nxos.version_info() except NxosClientError as err:", "return {} if proxy[\"nxos.initialized\"]() is False: return {} return {\"nxos\":", "__proxyenabled__ = [\"nxos\"] __virtualname__ = \"nxos\" def __virtual__(): try: salt.utils.nxos.version_info()", "from salt.exceptions import NxosClientError log = logging.getLogger(__name__) __proxyenabled__ = [\"nxos\"]", ":mod:`salt.proxy.nxos<salt.proxy.nxos>`. \"\"\" import logging import salt.utils.nxos import salt.utils.platform from salt.exceptions", "return __virtualname__ def system_information(proxy=None): if salt.utils.platform.is_proxy(): if proxy is None:", "salt.utils.platform.is_proxy(): if proxy is None: return {} if proxy[\"nxos.initialized\"]() is", "False: return {} return {\"nxos\": proxy[\"nxos.grains\"]()} else: data = salt.utils.nxos.version_info()", "= logging.getLogger(__name__) __proxyenabled__ = [\"nxos\"] __virtualname__ = \"nxos\" def __virtual__():", "def system_information(proxy=None): if salt.utils.platform.is_proxy(): if proxy is None: return {}", "try: salt.utils.nxos.version_info() except NxosClientError as err: return False, err return", "on setting up the nxos proxy minion look in the", "\"nxos\" def __virtual__(): try: salt.utils.nxos.version_info() except NxosClientError as err: return", "logging import salt.utils.nxos import salt.utils.platform from salt.exceptions import NxosClientError log", "setting up the nxos proxy minion look in the documentation", "is None: return {} if proxy[\"nxos.initialized\"]() is False: return {}", "documentation on setting up the nxos proxy minion look in", "2016.11.0 For documentation on setting up the nxos proxy minion", "NxosClientError log = logging.getLogger(__name__) __proxyenabled__ = [\"nxos\"] __virtualname__ = \"nxos\"", "[\"nxos\"] __virtualname__ = \"nxos\" def __virtual__(): try: salt.utils.nxos.version_info() except NxosClientError", "{} return {\"nxos\": proxy[\"nxos.grains\"]()} else: data = salt.utils.nxos.version_info() return salt.utils.nxos.system_info(data)", "def __virtual__(): try: salt.utils.nxos.version_info() except NxosClientError as err: return False,", "nxos proxy minion look in the documentation for :mod:`salt.proxy.nxos<salt.proxy.nxos>`. \"\"\"", "if proxy is None: return {} if proxy[\"nxos.initialized\"]() is False:", "For documentation on setting up the nxos proxy minion look", "import salt.utils.nxos import salt.utils.platform from salt.exceptions import NxosClientError log =" ]
[ "str = \"\") -> Optional[Tuple[List[object], int]]: devices = super().get_list(start=start, limit=limit,", "None, mac: str = None, remote_custom_field: str = None, comment:", "-> object: device = TmsDevice( unique_id=device_dict[\"unique_id\"], device_id=device_dict[\"id\"], ipaddr=device_dict[\"ipaddr\"], mac=device_dict[\"mac\"], remote_custom_field=device_dict[\"remote_custom_field\"],", "= comment self.last_online = last_online self.last_fw_ver = last_fw_ver self.first_online =", "None, comment: str = None, last_online: str = None, last_fw_ver:", "last_fw_ver self.first_online = first_online self.use_nat = use_nat self.operation_system = operation_system", "device_id: int = None, ipaddr: str = None, mac: str", "last_fw_ver=device_dict[\"last_fw_ver\"], first_online=device_dict[\"first_online\"], use_nat=device_dict[\"use_nat\"], operation_system=device_dict[\"operation_system\"], udpxy_addr=device_dict[\"udpxy_addr\"], device_type=device_dict[\"device_type\"], provider=device_dict[\"provider\"], account=device_dict[\"account\"] ) return", "= 50, provider: int = None, quick_search: str = \"\",", "-> Optional[Tuple[List[object], int]]: devices = super().get_list(start=start, limit=limit, account=account, device_type=device_type, provider=provider,", "mac self.remote_custom_field = remote_custom_field self.comment = comment self.last_online = last_online", "= use_nat self.operation_system = operation_system self.udpxy_addr = udpxy_addr self.device_type =", "0, unique_id: str = \"\") -> Optional[Tuple[List[object], int]]: devices =", "= \"\", remote_custom_field: str = None, sort: str = \"\",", "str = None, sort: str = \"\", start: int =", "= provider @staticmethod def _dict_to_object(device_dict: dict) -> object: device =", "int = 50, provider: int = None, quick_search: str =", "str, account: int, device_id: int = None, ipaddr: str =", "provider: int = None): self.unique_id = unique_id self.account = account", "{}, account: {}\"\"\".format( self.id, self.ipaddr, self.mac, self.unique_id, self.remote_custom_field, self.comment, self.last_online,", "= device_type self.provider = provider @staticmethod def _dict_to_object(device_dict: dict) ->", "remote_custom_field=device_dict[\"remote_custom_field\"], comment=device_dict[\"comment\"], last_online=device_dict[\"last_online\"], last_fw_ver=device_dict[\"last_fw_ver\"], first_online=device_dict[\"first_online\"], use_nat=device_dict[\"use_nat\"], operation_system=device_dict[\"operation_system\"], udpxy_addr=device_dict[\"udpxy_addr\"], device_type=device_dict[\"device_type\"], provider=device_dict[\"provider\"],", "50, provider: int = None, quick_search: str = \"\", remote_custom_field:", "None, quick_search: str = \"\", remote_custom_field: str = None, sort:", "None, remote_custom_field: str = None, comment: str = None, last_online:", "TmsDevice( unique_id=device_dict[\"unique_id\"], device_id=device_dict[\"id\"], ipaddr=device_dict[\"ipaddr\"], mac=device_dict[\"mac\"], remote_custom_field=device_dict[\"remote_custom_field\"], comment=device_dict[\"comment\"], last_online=device_dict[\"last_online\"], last_fw_ver=device_dict[\"last_fw_ver\"], first_online=device_dict[\"first_online\"],", "sort=sort, unique_id=unique_id) return devices def __str__(self): return \"\"\"id:{}, ipaddr:{}, mac:{},", "= None, ipaddr: str = None, mac: str = None,", "TmsExtendedModel class TmsDevice(TmsExtendedModel): _path_url = \"/devices/\" def __init__(self, unique_id: str,", "device_type=device_type, provider=provider, quick_search=quick_search, remote_custom_field=remote_custom_field, sort=sort, unique_id=unique_id) return devices def __str__(self):", "None, last_fw_ver: str = None, first_online: str = None, use_nat:", "None, ipaddr: str = None, mac: str = None, remote_custom_field:", "= None, provider: int = None): self.unique_id = unique_id self.account", "= False, operation_system: str = None, udpxy_addr: str = None,", "None, first_online: str = None, use_nat: bool = False, operation_system:", "use_nat self.operation_system = operation_system self.udpxy_addr = udpxy_addr self.device_type = device_type", "devices = super().get_list(start=start, limit=limit, account=account, device_type=device_type, provider=provider, quick_search=quick_search, remote_custom_field=remote_custom_field, sort=sort,", "= super().get_list(start=start, limit=limit, account=account, device_type=device_type, provider=provider, quick_search=quick_search, remote_custom_field=remote_custom_field, sort=sort, unique_id=unique_id)", "None, last_online: str = None, last_fw_ver: str = None, first_online:", "self.account = account self.id = device_id self.ipaddr = ipaddr self.mac", "= last_online self.last_fw_ver = last_fw_ver self.first_online = first_online self.use_nat =", "quick_search=quick_search, remote_custom_field=remote_custom_field, sort=sort, unique_id=unique_id) return devices def __str__(self): return \"\"\"id:{},", "remote_custom_field: {}, comment: {}, last_online: {}, \\ last_fw_ver: {}, first_online:", "operation_system: {}, \\ udpxy_addr: {}, device_type: {}, provider: {}, account:", "operation_system=device_dict[\"operation_system\"], udpxy_addr=device_dict[\"udpxy_addr\"], device_type=device_dict[\"device_type\"], provider=device_dict[\"provider\"], account=device_dict[\"account\"] ) return device @classmethod def", "unique_id self.account = account self.id = device_id self.ipaddr = ipaddr", "str = None, last_online: str = None, last_fw_ver: str =", "account=device_dict[\"account\"] ) return device @classmethod def get_list(cls, account: int =", "{}, comment: {}, last_online: {}, \\ last_fw_ver: {}, first_online: {},", "first_online=device_dict[\"first_online\"], use_nat=device_dict[\"use_nat\"], operation_system=device_dict[\"operation_system\"], udpxy_addr=device_dict[\"udpxy_addr\"], device_type=device_dict[\"device_type\"], provider=device_dict[\"provider\"], account=device_dict[\"account\"] ) return device", "get_list(cls, account: int = None, device_type: int = None, limit:", "remote_custom_field: str = None, comment: str = None, last_online: str", "last_online self.last_fw_ver = last_fw_ver self.first_online = first_online self.use_nat = use_nat", "super().get_list(start=start, limit=limit, account=account, device_type=device_type, provider=provider, quick_search=quick_search, remote_custom_field=remote_custom_field, sort=sort, unique_id=unique_id) return", "def __init__(self, unique_id: str, account: int, device_id: int = None,", "unique_id: str, account: int, device_id: int = None, ipaddr: str", "unique_id=unique_id) return devices def __str__(self): return \"\"\"id:{}, ipaddr:{}, mac:{}, unique_id:{},", "mac:{}, unique_id:{}, remote_custom_field: {}, comment: {}, last_online: {}, \\ last_fw_ver:", "self.last_online, self.last_fw_ver, self.first_online, self.use_nat, self.operation_system, self.udpxy_addr, self.device_type, self.provider, self.account )", "= None): self.unique_id = unique_id self.account = account self.id =", "int]]: devices = super().get_list(start=start, limit=limit, account=account, device_type=device_type, provider=provider, quick_search=quick_search, remote_custom_field=remote_custom_field,", "udpxy_addr: str = None, device_type: int = None, provider: int", "last_online: str = None, last_fw_ver: str = None, first_online: str", "comment self.last_online = last_online self.last_fw_ver = last_fw_ver self.first_online = first_online", "None, limit: int = 50, provider: int = None, quick_search:", "None, provider: int = None): self.unique_id = unique_id self.account =", "__init__(self, unique_id: str, account: int, device_id: int = None, ipaddr:", "int = 0, unique_id: str = \"\") -> Optional[Tuple[List[object], int]]:", "str = None, device_type: int = None, provider: int =", "= None, comment: str = None, last_online: str = None,", "self.id, self.ipaddr, self.mac, self.unique_id, self.remote_custom_field, self.comment, self.last_online, self.last_fw_ver, self.first_online, self.use_nat,", "{}, \\ last_fw_ver: {}, first_online: {}, use_nat: {}, operation_system: {},", "comment: str = None, last_online: str = None, last_fw_ver: str", "limit=limit, account=account, device_type=device_type, provider=provider, quick_search=quick_search, remote_custom_field=remote_custom_field, sort=sort, unique_id=unique_id) return devices", "{}, provider: {}, account: {}\"\"\".format( self.id, self.ipaddr, self.mac, self.unique_id, self.remote_custom_field,", "List, Optional, Tuple from tmsproviderapisdk.tms_extended_model import TmsExtendedModel class TmsDevice(TmsExtendedModel): _path_url", "str = None, mac: str = None, remote_custom_field: str =", "return device @classmethod def get_list(cls, account: int = None, device_type:", "@classmethod def get_list(cls, account: int = None, device_type: int =", "import TmsExtendedModel class TmsDevice(TmsExtendedModel): _path_url = \"/devices/\" def __init__(self, unique_id:", "{}, device_type: {}, provider: {}, account: {}\"\"\".format( self.id, self.ipaddr, self.mac,", "Optional, Tuple from tmsproviderapisdk.tms_extended_model import TmsExtendedModel class TmsDevice(TmsExtendedModel): _path_url =", "udpxy_addr self.device_type = device_type self.provider = provider @staticmethod def _dict_to_object(device_dict:", "self.mac, self.unique_id, self.remote_custom_field, self.comment, self.last_online, self.last_fw_ver, self.first_online, self.use_nat, self.operation_system, self.udpxy_addr,", "= None, limit: int = 50, provider: int = None,", "self.remote_custom_field, self.comment, self.last_online, self.last_fw_ver, self.first_online, self.use_nat, self.operation_system, self.udpxy_addr, self.device_type, self.provider,", "comment: {}, last_online: {}, \\ last_fw_ver: {}, first_online: {}, use_nat:", "int = None): self.unique_id = unique_id self.account = account self.id", "class TmsDevice(TmsExtendedModel): _path_url = \"/devices/\" def __init__(self, unique_id: str, account:", "unique_id=device_dict[\"unique_id\"], device_id=device_dict[\"id\"], ipaddr=device_dict[\"ipaddr\"], mac=device_dict[\"mac\"], remote_custom_field=device_dict[\"remote_custom_field\"], comment=device_dict[\"comment\"], last_online=device_dict[\"last_online\"], last_fw_ver=device_dict[\"last_fw_ver\"], first_online=device_dict[\"first_online\"], use_nat=device_dict[\"use_nat\"],", "\"\", remote_custom_field: str = None, sort: str = \"\", start:", "\\ last_fw_ver: {}, first_online: {}, use_nat: {}, operation_system: {}, \\", "device_type: {}, provider: {}, account: {}\"\"\".format( self.id, self.ipaddr, self.mac, self.unique_id,", "device_id=device_dict[\"id\"], ipaddr=device_dict[\"ipaddr\"], mac=device_dict[\"mac\"], remote_custom_field=device_dict[\"remote_custom_field\"], comment=device_dict[\"comment\"], last_online=device_dict[\"last_online\"], last_fw_ver=device_dict[\"last_fw_ver\"], first_online=device_dict[\"first_online\"], use_nat=device_dict[\"use_nat\"], operation_system=device_dict[\"operation_system\"],", "self.comment, self.last_online, self.last_fw_ver, self.first_online, self.use_nat, self.operation_system, self.udpxy_addr, self.device_type, self.provider, self.account", "{}\"\"\".format( self.id, self.ipaddr, self.mac, self.unique_id, self.remote_custom_field, self.comment, self.last_online, self.last_fw_ver, self.first_online,", "= None, device_type: int = None, provider: int = None):", "first_online: str = None, use_nat: bool = False, operation_system: str", "provider=provider, quick_search=quick_search, remote_custom_field=remote_custom_field, sort=sort, unique_id=unique_id) return devices def __str__(self): return", "= None, sort: str = \"\", start: int = 0,", "None, use_nat: bool = False, operation_system: str = None, udpxy_addr:", "None, device_type: int = None, limit: int = 50, provider:", "account self.id = device_id self.ipaddr = ipaddr self.mac = mac", "= ipaddr self.mac = mac self.remote_custom_field = remote_custom_field self.comment =", "= udpxy_addr self.device_type = device_type self.provider = provider @staticmethod def", ") return device @classmethod def get_list(cls, account: int = None,", "udpxy_addr: {}, device_type: {}, provider: {}, account: {}\"\"\".format( self.id, self.ipaddr,", "first_online: {}, use_nat: {}, operation_system: {}, \\ udpxy_addr: {}, device_type:", "str = None, udpxy_addr: str = None, device_type: int =", "device_type: int = None, limit: int = 50, provider: int", "self.comment = comment self.last_online = last_online self.last_fw_ver = last_fw_ver self.first_online", "= operation_system self.udpxy_addr = udpxy_addr self.device_type = device_type self.provider =", "account: int = None, device_type: int = None, limit: int", "limit: int = 50, provider: int = None, quick_search: str", "None): self.unique_id = unique_id self.account = account self.id = device_id", "device_id self.ipaddr = ipaddr self.mac = mac self.remote_custom_field = remote_custom_field", "= None, last_online: str = None, last_fw_ver: str = None,", "udpxy_addr=device_dict[\"udpxy_addr\"], device_type=device_dict[\"device_type\"], provider=device_dict[\"provider\"], account=device_dict[\"account\"] ) return device @classmethod def get_list(cls,", "\"/devices/\" def __init__(self, unique_id: str, account: int, device_id: int =", "self.unique_id, self.remote_custom_field, self.comment, self.last_online, self.last_fw_ver, self.first_online, self.use_nat, self.operation_system, self.udpxy_addr, self.device_type,", "False, operation_system: str = None, udpxy_addr: str = None, device_type:", "self.ipaddr = ipaddr self.mac = mac self.remote_custom_field = remote_custom_field self.comment", "self.device_type = device_type self.provider = provider @staticmethod def _dict_to_object(device_dict: dict)", "unique_id:{}, remote_custom_field: {}, comment: {}, last_online: {}, \\ last_fw_ver: {},", "None, device_type: int = None, provider: int = None): self.unique_id", "int = None, limit: int = 50, provider: int =", "= device_id self.ipaddr = ipaddr self.mac = mac self.remote_custom_field =", "unique_id: str = \"\") -> Optional[Tuple[List[object], int]]: devices = super().get_list(start=start,", "{}, use_nat: {}, operation_system: {}, \\ udpxy_addr: {}, device_type: {},", "from tmsproviderapisdk.tms_extended_model import TmsExtendedModel class TmsDevice(TmsExtendedModel): _path_url = \"/devices/\" def", "device = TmsDevice( unique_id=device_dict[\"unique_id\"], device_id=device_dict[\"id\"], ipaddr=device_dict[\"ipaddr\"], mac=device_dict[\"mac\"], remote_custom_field=device_dict[\"remote_custom_field\"], comment=device_dict[\"comment\"], last_online=device_dict[\"last_online\"],", "= None, quick_search: str = \"\", remote_custom_field: str = None,", "devices def __str__(self): return \"\"\"id:{}, ipaddr:{}, mac:{}, unique_id:{}, remote_custom_field: {},", "ipaddr: str = None, mac: str = None, remote_custom_field: str", "self.last_online = last_online self.last_fw_ver = last_fw_ver self.first_online = first_online self.use_nat", "first_online self.use_nat = use_nat self.operation_system = operation_system self.udpxy_addr = udpxy_addr", "{}, first_online: {}, use_nat: {}, operation_system: {}, \\ udpxy_addr: {},", "def _dict_to_object(device_dict: dict) -> object: device = TmsDevice( unique_id=device_dict[\"unique_id\"], device_id=device_dict[\"id\"],", "use_nat: {}, operation_system: {}, \\ udpxy_addr: {}, device_type: {}, provider:", "operation_system self.udpxy_addr = udpxy_addr self.device_type = device_type self.provider = provider", "quick_search: str = \"\", remote_custom_field: str = None, sort: str", "= None, use_nat: bool = False, operation_system: str = None,", "last_online=device_dict[\"last_online\"], last_fw_ver=device_dict[\"last_fw_ver\"], first_online=device_dict[\"first_online\"], use_nat=device_dict[\"use_nat\"], operation_system=device_dict[\"operation_system\"], udpxy_addr=device_dict[\"udpxy_addr\"], device_type=device_dict[\"device_type\"], provider=device_dict[\"provider\"], account=device_dict[\"account\"] )", "self.mac = mac self.remote_custom_field = remote_custom_field self.comment = comment self.last_online", "dict) -> object: device = TmsDevice( unique_id=device_dict[\"unique_id\"], device_id=device_dict[\"id\"], ipaddr=device_dict[\"ipaddr\"], mac=device_dict[\"mac\"],", "str = \"\", remote_custom_field: str = None, sort: str =", "{}, operation_system: {}, \\ udpxy_addr: {}, device_type: {}, provider: {},", "Optional[Tuple[List[object], int]]: devices = super().get_list(start=start, limit=limit, account=account, device_type=device_type, provider=provider, quick_search=quick_search,", "self.remote_custom_field = remote_custom_field self.comment = comment self.last_online = last_online self.last_fw_ver", "start: int = 0, unique_id: str = \"\") -> Optional[Tuple[List[object],", "mac: str = None, remote_custom_field: str = None, comment: str", "= None, first_online: str = None, use_nat: bool = False,", "= \"\") -> Optional[Tuple[List[object], int]]: devices = super().get_list(start=start, limit=limit, account=account,", "tmsproviderapisdk.tms_extended_model import TmsExtendedModel class TmsDevice(TmsExtendedModel): _path_url = \"/devices/\" def __init__(self,", "provider=device_dict[\"provider\"], account=device_dict[\"account\"] ) return device @classmethod def get_list(cls, account: int", "remote_custom_field: str = None, sort: str = \"\", start: int", "from typing import List, Optional, Tuple from tmsproviderapisdk.tms_extended_model import TmsExtendedModel", "__str__(self): return \"\"\"id:{}, ipaddr:{}, mac:{}, unique_id:{}, remote_custom_field: {}, comment: {},", "ipaddr:{}, mac:{}, unique_id:{}, remote_custom_field: {}, comment: {}, last_online: {}, \\", "int = None, ipaddr: str = None, mac: str =", "\"\") -> Optional[Tuple[List[object], int]]: devices = super().get_list(start=start, limit=limit, account=account, device_type=device_type,", "None, udpxy_addr: str = None, device_type: int = None, provider:", "= None, mac: str = None, remote_custom_field: str = None,", "self.udpxy_addr = udpxy_addr self.device_type = device_type self.provider = provider @staticmethod", "mac=device_dict[\"mac\"], remote_custom_field=device_dict[\"remote_custom_field\"], comment=device_dict[\"comment\"], last_online=device_dict[\"last_online\"], last_fw_ver=device_dict[\"last_fw_ver\"], first_online=device_dict[\"first_online\"], use_nat=device_dict[\"use_nat\"], operation_system=device_dict[\"operation_system\"], udpxy_addr=device_dict[\"udpxy_addr\"], device_type=device_dict[\"device_type\"],", "= unique_id self.account = account self.id = device_id self.ipaddr =", "provider: int = None, quick_search: str = \"\", remote_custom_field: str", "account=account, device_type=device_type, provider=provider, quick_search=quick_search, remote_custom_field=remote_custom_field, sort=sort, unique_id=unique_id) return devices def", "= TmsDevice( unique_id=device_dict[\"unique_id\"], device_id=device_dict[\"id\"], ipaddr=device_dict[\"ipaddr\"], mac=device_dict[\"mac\"], remote_custom_field=device_dict[\"remote_custom_field\"], comment=device_dict[\"comment\"], last_online=device_dict[\"last_online\"], last_fw_ver=device_dict[\"last_fw_ver\"],", "account: int, device_id: int = None, ipaddr: str = None,", "bool = False, operation_system: str = None, udpxy_addr: str =", "{}, last_online: {}, \\ last_fw_ver: {}, first_online: {}, use_nat: {},", "\"\"\"id:{}, ipaddr:{}, mac:{}, unique_id:{}, remote_custom_field: {}, comment: {}, last_online: {},", "= first_online self.use_nat = use_nat self.operation_system = operation_system self.udpxy_addr =", "= None, remote_custom_field: str = None, comment: str = None,", "{}, \\ udpxy_addr: {}, device_type: {}, provider: {}, account: {}\"\"\".format(", "remote_custom_field self.comment = comment self.last_online = last_online self.last_fw_ver = last_fw_ver", "= \"\", start: int = 0, unique_id: str = \"\")", "TmsDevice(TmsExtendedModel): _path_url = \"/devices/\" def __init__(self, unique_id: str, account: int,", "= 0, unique_id: str = \"\") -> Optional[Tuple[List[object], int]]: devices", "typing import List, Optional, Tuple from tmsproviderapisdk.tms_extended_model import TmsExtendedModel class", "str = None, first_online: str = None, use_nat: bool =", "device_type=device_dict[\"device_type\"], provider=device_dict[\"provider\"], account=device_dict[\"account\"] ) return device @classmethod def get_list(cls, account:", "operation_system: str = None, udpxy_addr: str = None, device_type: int", "int = None, device_type: int = None, limit: int =", "return \"\"\"id:{}, ipaddr:{}, mac:{}, unique_id:{}, remote_custom_field: {}, comment: {}, last_online:", "int = None, provider: int = None): self.unique_id = unique_id", "device_type: int = None, provider: int = None): self.unique_id =", "None, sort: str = \"\", start: int = 0, unique_id:", "ipaddr self.mac = mac self.remote_custom_field = remote_custom_field self.comment = comment", "= account self.id = device_id self.ipaddr = ipaddr self.mac =", "sort: str = \"\", start: int = 0, unique_id: str", "last_fw_ver: {}, first_online: {}, use_nat: {}, operation_system: {}, \\ udpxy_addr:", "def __str__(self): return \"\"\"id:{}, ipaddr:{}, mac:{}, unique_id:{}, remote_custom_field: {}, comment:", "comment=device_dict[\"comment\"], last_online=device_dict[\"last_online\"], last_fw_ver=device_dict[\"last_fw_ver\"], first_online=device_dict[\"first_online\"], use_nat=device_dict[\"use_nat\"], operation_system=device_dict[\"operation_system\"], udpxy_addr=device_dict[\"udpxy_addr\"], device_type=device_dict[\"device_type\"], provider=device_dict[\"provider\"], account=device_dict[\"account\"]", "self.first_online = first_online self.use_nat = use_nat self.operation_system = operation_system self.udpxy_addr", "str = None, remote_custom_field: str = None, comment: str =", "_path_url = \"/devices/\" def __init__(self, unique_id: str, account: int, device_id:", "self.operation_system = operation_system self.udpxy_addr = udpxy_addr self.device_type = device_type self.provider", "account: {}\"\"\".format( self.id, self.ipaddr, self.mac, self.unique_id, self.remote_custom_field, self.comment, self.last_online, self.last_fw_ver,", "self.ipaddr, self.mac, self.unique_id, self.remote_custom_field, self.comment, self.last_online, self.last_fw_ver, self.first_online, self.use_nat, self.operation_system,", "= None, device_type: int = None, limit: int = 50,", "import List, Optional, Tuple from tmsproviderapisdk.tms_extended_model import TmsExtendedModel class TmsDevice(TmsExtendedModel):", "str = None, comment: str = None, last_online: str =", "@staticmethod def _dict_to_object(device_dict: dict) -> object: device = TmsDevice( unique_id=device_dict[\"unique_id\"],", "object: device = TmsDevice( unique_id=device_dict[\"unique_id\"], device_id=device_dict[\"id\"], ipaddr=device_dict[\"ipaddr\"], mac=device_dict[\"mac\"], remote_custom_field=device_dict[\"remote_custom_field\"], comment=device_dict[\"comment\"],", "self.use_nat = use_nat self.operation_system = operation_system self.udpxy_addr = udpxy_addr self.device_type", "int = None, quick_search: str = \"\", remote_custom_field: str =", "str = \"\", start: int = 0, unique_id: str =", "def get_list(cls, account: int = None, device_type: int = None,", "self.unique_id = unique_id self.account = account self.id = device_id self.ipaddr", "return devices def __str__(self): return \"\"\"id:{}, ipaddr:{}, mac:{}, unique_id:{}, remote_custom_field:", "= \"/devices/\" def __init__(self, unique_id: str, account: int, device_id: int", "use_nat=device_dict[\"use_nat\"], operation_system=device_dict[\"operation_system\"], udpxy_addr=device_dict[\"udpxy_addr\"], device_type=device_dict[\"device_type\"], provider=device_dict[\"provider\"], account=device_dict[\"account\"] ) return device @classmethod", "self.provider = provider @staticmethod def _dict_to_object(device_dict: dict) -> object: device", "_dict_to_object(device_dict: dict) -> object: device = TmsDevice( unique_id=device_dict[\"unique_id\"], device_id=device_dict[\"id\"], ipaddr=device_dict[\"ipaddr\"],", "provider: {}, account: {}\"\"\".format( self.id, self.ipaddr, self.mac, self.unique_id, self.remote_custom_field, self.comment,", "use_nat: bool = False, operation_system: str = None, udpxy_addr: str", "\"\", start: int = 0, unique_id: str = \"\") ->", "self.last_fw_ver = last_fw_ver self.first_online = first_online self.use_nat = use_nat self.operation_system", "= mac self.remote_custom_field = remote_custom_field self.comment = comment self.last_online =", "= last_fw_ver self.first_online = first_online self.use_nat = use_nat self.operation_system =", "str = None, last_fw_ver: str = None, first_online: str =", "= remote_custom_field self.comment = comment self.last_online = last_online self.last_fw_ver =", "device @classmethod def get_list(cls, account: int = None, device_type: int", "int, device_id: int = None, ipaddr: str = None, mac:", "self.id = device_id self.ipaddr = ipaddr self.mac = mac self.remote_custom_field", "= None, last_fw_ver: str = None, first_online: str = None,", "Tuple from tmsproviderapisdk.tms_extended_model import TmsExtendedModel class TmsDevice(TmsExtendedModel): _path_url = \"/devices/\"", "device_type self.provider = provider @staticmethod def _dict_to_object(device_dict: dict) -> object:", "<gh_stars>0 from typing import List, Optional, Tuple from tmsproviderapisdk.tms_extended_model import", "last_online: {}, \\ last_fw_ver: {}, first_online: {}, use_nat: {}, operation_system:", "\\ udpxy_addr: {}, device_type: {}, provider: {}, account: {}\"\"\".format( self.id,", "remote_custom_field=remote_custom_field, sort=sort, unique_id=unique_id) return devices def __str__(self): return \"\"\"id:{}, ipaddr:{},", "last_fw_ver: str = None, first_online: str = None, use_nat: bool", "= None, udpxy_addr: str = None, device_type: int = None,", "ipaddr=device_dict[\"ipaddr\"], mac=device_dict[\"mac\"], remote_custom_field=device_dict[\"remote_custom_field\"], comment=device_dict[\"comment\"], last_online=device_dict[\"last_online\"], last_fw_ver=device_dict[\"last_fw_ver\"], first_online=device_dict[\"first_online\"], use_nat=device_dict[\"use_nat\"], operation_system=device_dict[\"operation_system\"], udpxy_addr=device_dict[\"udpxy_addr\"],", "str = None, use_nat: bool = False, operation_system: str =", "provider @staticmethod def _dict_to_object(device_dict: dict) -> object: device = TmsDevice(" ]
[ "== 1: walled_field_numerics.grad_i_1d(field, inds, grad_i, dx, walls) elif field.ndim ==", "def _grad_i(field, inds, dx): assert dx > 0.0 assert inds.ndim", "from __future__ import print_function, division import numpy as np from", "Scalar.__init__(self, L, dim, dx, a_0=a_0) self.D = D self.dt =", "self.dim * self.dt): raise Exception('Unstable diffusion constant') def iterate(self): self.a", "obstructed self.a *= np.logical_not(self.walls) def grad(self): return _walled_grad(self.a, self.dx, self.walls)", "return _walled_grad_i(self.a, self.r_to_i(r), self.dx, self.walls) def laplacian(self): return _walled_laplace(self.a, self.dx,", "def density(r, L, dx): assert r.ndim == 2 M =", "density(r, self.L, self.dx) def r_to_i(self, r): return lattice.r_to_i(r, self.L, self.dx)", "grad_i def _walled_laplace(field, dx, walls): assert field.shape == walls.shape assert", "* (M,), dtype=np.int) if f.ndim == 1: field_numerics.density_1d(inds, f) elif", "return _laplace(self.a, self.dx) def __repr__(self): fs = [('L', self.L), ('dim',", "= dim @property def L_half(self): return self.L / 2.0 @property", "def L_half(self): return self.L / 2.0 @property def A(self): return", "* self.dt): raise Exception('Unstable diffusion constant') def iterate(self): self.a +=", "walled_field_numerics.grad_3d(field, grad, dx, walls) else: raise Exception(\"Walled grad not implemented", "('dim', self.dim)] return make_repr_str(self, fs) class Field(Space): def __init__(self, L,", "= [('L', self.L), ('dim', self.dim), ('dx', self.dx), ('walls', self.walls), ('a_0',", "make_repr_str(self, fs) class Diffusing(Scalar): def __init__(self, L, dim, dx, D,", "wikipedia and how python handles it) class WalledDiffusing(WalledScalar, Diffusing): def", "laplace = np.empty_like(field) if field.ndim == 1: walled_field_numerics.laplace_1d(field, laplace, dx,", "field.ndim == 1: field_numerics.grad_1d(field, grad, dx) elif field.ndim == 2:", "np.zeros(r.shape[1] * (M,), dtype=np.int) if f.ndim == 1: field_numerics.density_1d(inds, f)", "__future__ import print_function, division import numpy as np from ciabatta.meta", "np.empty(inds.shape, dtype=field.dtype) if field.ndim == 1: field_numerics.grad_i_1d(field, inds, grad_i, dx)", "L self.dim = dim @property def L_half(self): return self.L /", "self.L, self.dx) def r_to_i(self, r): return lattice.r_to_i(r, self.L, self.dx) def", "this dimension') return f / dx ** r.shape[1] def _laplace(field,", "f / dx ** r.shape[1] def _laplace(field, dx): assert dx", "2 assert field.ndim == inds.shape[1] grad_i = np.empty(inds.shape, dtype=field.dtype) if", "== inds.shape[1] grad_i = np.empty(inds.shape, dtype=field.dtype) if field.ndim == 1:", "== 1: field_numerics.laplace_1d(field, laplace, dx) elif field.ndim == 2: field_numerics.laplace_2d(field,", "3: field_numerics.grad_3d(field, grad, dx) else: raise Exception('Grad not implemented in", "self.M = int(round(self.L / dx)) @property def dx(self): return self.L", "laplacian(self): return _walled_laplace(self.a, self.dx, self.walls) def __repr__(self): fs = [('L',", "def __repr__(self): fs = [('L', self.L), ('dim', self.dim), ('dx', self.dx)]", "dt if self.D > self.dx ** 2 / (2.0 *", "self.dim def density_field(self, r): return density(r, self.L, self.dx) def r_to_i(self,", "inds, grad_i, dx, walls) elif field.ndim == 2: walled_field_numerics.grad_i_2d(field, inds,", "2: field_numerics.grad_2d(field, grad, dx) elif field.ndim == 3: field_numerics.grad_3d(field, grad,", "@property def dA(self): return self.dx ** self.dim def density_field(self, r):", "self.dim), ('dx', self.dx), ('D', self.D), ('dt', self.dt), ('a_0', self.a_0)] return", "@property def A_i(self): return self.M ** self.dim @property def dA(self):", "elif field.ndim == 3: field_numerics.div_2d(field, div, dx) elif field.ndim ==", "= [('L', self.L), ('dim', self.dim), ('dx', self.dx)] return make_repr_str(self, fs)", "fs) # Note, inheritance order matters to get walled grad", "walls, D, dt, a_0=0.0): Diffusing.__init__(self, L, dim, dx, D, dt,", "grad, dx) elif field.ndim == 3: field_numerics.grad_3d(field, grad, dx) else:", "__init__(self, L, dim, dx, a_0=0.0): Field.__init__(self, L, dim, dx) self.a", "Exception(\"Walled grad not implemented in this dimension\") return grad def", "('D', self.D), ('dt', self.dt), ('a_0', self.a_0)] return make_repr_str(self, fs) class", "= np.ones(self.dim * (self.M,), dtype=np.float) * a_0 def grad(self): return", "def laplacian(self): return _walled_laplace(self.a, self.dx, self.walls) def __repr__(self): fs =", "div = np.empty(field.shape[:-1], dtype=field.dtype) if field.ndim == 2: field_numerics.div_1d(field, div,", "== 2: walled_field_numerics.grad_2d(field, grad, dx, walls) elif field.ndim == 3:", "grad(self): return _grad(self.a, self.dx) def grad_i(self, r): return _grad_i(self.a, self.r_to_i(r),", "3: walled_field_numerics.grad_i_3d(field, inds, grad_i, dx, walls) else: raise Exception(\"Walled Grad_i", "int(round(L / dx)) dx = L / M inds =", "inds, dx): assert dx > 0.0 assert inds.ndim == 2", "field.shape == walls.shape assert dx > 0.0 assert inds.ndim ==", "dx, walls) elif field.ndim == 2: walled_field_numerics.laplace_2d(field, laplace, dx, walls)", "dimension') return laplace def _grad_i(field, inds, dx): assert dx >", "elif field.ndim == 3: walled_field_numerics.laplace_3d(field, laplace, dx, walls) else: raise", "self.dx), ('D', self.D), ('dt', self.dt), ('a_0', self.a_0)] return make_repr_str(self, fs)", "return make_repr_str(self, fs) class Scalar(Field): def __init__(self, L, dim, dx,", "div, dx) elif field.ndim == 3: field_numerics.div_2d(field, div, dx) elif", "return make_repr_str(self, fs) class Field(Space): def __init__(self, L, dim, dx):", "div, dx) else: raise Exception('Divergence not implemented in this dimension')", "make_repr_str(self, fs) # Note, inheritance order matters to get walled", "dt, a_0=0.0): Scalar.__init__(self, L, dim, dx, a_0=a_0) self.D = D", "dx, walls): assert field.shape == walls.shape assert dx > 0.0", "WalledDiffusing(WalledScalar, Diffusing): def __init__(self, L, dim, dx, walls, D, dt,", "self.L / 2.0 @property def A(self): return self.L ** self.dim", "inheritance order matters to get walled grad & laplacian call", "import make_repr_str from fealty import lattice, field_numerics, walled_field_numerics class Space(object):", "self.dim = dim @property def L_half(self): return self.L / 2.0", "elif field.ndim == 2: walled_field_numerics.grad_2d(field, grad, dx, walls) elif field.ndim", "if field.ndim == 1: walled_field_numerics.laplace_1d(field, laplace, dx, walls) elif field.ndim", "= [('L', self.L), ('dim', self.dim), ('dx', self.dx), ('walls', self.walls), ('D',", "laplacian call # (see diamond problem on wikipedia and how", "== 3: field_numerics.grad_3d(field, grad, dx) else: raise Exception('Grad not implemented", "__repr__(self): fs = [('L', self.L), ('dim', self.dim), ('dx', self.dx)] return", "self.dx)] return make_repr_str(self, fs) class Scalar(Field): def __init__(self, L, dim,", "import numpy as np from ciabatta.meta import make_repr_str from fealty", "fs = [('L', self.L), ('dim', self.dim)] return make_repr_str(self, fs) class", "assert field.ndim == inds.shape[1] grad_i = np.empty(inds.shape, dtype=field.dtype) if field.ndim", "dx > 0.0 grad = np.empty(field.shape + (field.ndim,), dtype=field.dtype) if", "* self.laplacian() * self.dt def __repr__(self): fs = [('L', self.L),", "np.ones(self.dim * (self.M,), dtype=np.float) * a_0 def grad(self): return _grad(self.a,", "** r.shape[1] def _laplace(field, dx): assert dx > 0.0 laplace", "__init__(self, L, dim, dx, walls, D, dt, a_0=0.0): Diffusing.__init__(self, L,", "assert dx > 0.0 grad = np.empty(field.shape + (field.ndim,), dtype=field.dtype)", "3: field_numerics.div_2d(field, div, dx) elif field.ndim == 4: field_numerics.div_3d(field, div,", "def dx(self): return self.L / self.M @property def A_i(self): return", "walled_field_numerics.laplace_1d(field, laplace, dx, walls) elif field.ndim == 2: walled_field_numerics.laplace_2d(field, laplace,", "fs) def density(r, L, dx): assert r.ndim == 2 M", "def __init__(self, L, dim): self.L = L self.dim = dim", "D, dt, a_0=0.0): Scalar.__init__(self, L, dim, dx, a_0=a_0) self.D =", "grad_i, dx) else: raise Exception(\"Grad_i not implemented in this dimension\")", "make_repr_str from fealty import lattice, field_numerics, walled_field_numerics class Space(object): def", "field_numerics.grad_i_3d(field, grad_i, dx) else: raise Exception(\"Grad_i not implemented in this", "('dim', self.dim), ('dx', self.dx), ('D', self.D), ('dt', self.dt), ('a_0', self.a_0)]", "a_0=0.0): Scalar.__init__(self, L, dim, dx, a_0=a_0) self.walls = walls #", "[('L', self.L), ('dim', self.dim), ('dx', self.dx), ('walls', self.walls), ('a_0', self.a_0)]", "D self.dt = dt if self.D > self.dx ** 2", "raise Exception('Unstable diffusion constant') def iterate(self): self.a += self.D *", "dA(self): return self.dx ** self.dim def density_field(self, r): return density(r,", "return make_repr_str(self, fs) class Diffusing(Scalar): def __init__(self, L, dim, dx,", "dx, walls) elif field.ndim == 3: walled_field_numerics.grad_3d(field, grad, dx, walls)", "r): return density(r, self.L, self.dx) def r_to_i(self, r): return lattice.r_to_i(r,", "('dx', self.dx), ('walls', self.walls), ('D', self.D), ('dt', self.dt), ('a_0', self.a_0)]", "import lattice, field_numerics, walled_field_numerics class Space(object): def __init__(self, L, dim):", "3: field_numerics.laplace_3d(field, laplace, dx) else: raise Exception('Laplacian not implemented in", "3: walled_field_numerics.laplace_3d(field, laplace, dx, walls) else: raise Exception('Laplacian not implemented", "== 3: field_numerics.div_2d(field, div, dx) elif field.ndim == 4: field_numerics.div_3d(field,", "** self.dim def iterate(self, *args, **kwargs): pass def __repr__(self): fs", "laplace, dx) elif field.ndim == 3: field_numerics.laplace_3d(field, laplace, dx) else:", "def __repr__(self): fs = [('L', self.L), ('dim', self.dim)] return make_repr_str(self,", "field_numerics.laplace_3d(field, laplace, dx) else: raise Exception('Laplacian not implemented in this", "dx) elif field.ndim == 3: field_numerics.grad_3d(field, grad, dx) else: raise", "(self.M,), dtype=np.float) * a_0 def grad(self): return _grad(self.a, self.dx) def", "walls) elif field.ndim == 3: walled_field_numerics.grad_3d(field, grad, dx, walls) else:", "a_0=a_0) self.walls = walls # Make field zero-valued where obstructed", "call # (see diamond problem on wikipedia and how python", "L, dx) f = np.zeros(r.shape[1] * (M,), dtype=np.int) if f.ndim", "0.0 assert inds.ndim == 2 assert field.ndim == inds.shape[1] grad_i", "elif f.ndim == 3: field_numerics.density_3d(inds, f) else: raise Exception('Density calc", "** self.dim @property def dA(self): return self.dx ** self.dim def", "field_numerics.grad_3d(field, grad, dx) else: raise Exception('Grad not implemented in this", "self.dim @property def dA(self): return self.dx ** self.dim def density_field(self,", "# Make field zero-valued where obstructed self.a *= np.logical_not(self.walls) def", "(field.ndim,), dtype=field.dtype) if field.ndim == 1: field_numerics.grad_1d(field, grad, dx) elif", "f.ndim == 2: field_numerics.density_2d(inds, f) elif f.ndim == 3: field_numerics.density_3d(inds,", "== 2: field_numerics.laplace_2d(field, laplace, dx) elif field.ndim == 3: field_numerics.laplace_3d(field,", "laplace, dx) elif field.ndim == 2: field_numerics.laplace_2d(field, laplace, dx) elif", "field.ndim == 3: field_numerics.div_2d(field, div, dx) elif field.ndim == 4:", "problem on wikipedia and how python handles it) class WalledDiffusing(WalledScalar,", "field.shape == walls.shape assert dx > 0.0 laplace = np.empty_like(field)", "class hierarchy relating to fields of all kinds. \"\"\" from", "L, dim, dx) self.a = np.ones(self.dim * (self.M,), dtype=np.float) *", "> 0.0 assert inds.ndim == 2 assert field.ndim == inds.shape[1]", "dx) elif field.ndim == 4: field_numerics.div_3d(field, div, dx) else: raise", "**kwargs): pass def __repr__(self): fs = [('L', self.L), ('dim', self.dim)]", "field.ndim == 1: field_numerics.laplace_1d(field, laplace, dx) elif field.ndim == 2:", "dx) else: raise Exception('Laplacian not implemented in this dimension') return", "field.ndim == inds.shape[1] grad_i = np.empty(inds.shape, dtype=field.dtype) if field.ndim ==", "grad, dx) else: raise Exception('Grad not implemented in this dimension')", "class Diffusing(Scalar): def __init__(self, L, dim, dx, D, dt, a_0=0.0):", "self.L ** self.dim def iterate(self, *args, **kwargs): pass def __repr__(self):", "Make field zero-valued where obstructed self.a *= np.logical_not(self.walls) def grad(self):", "('D', self.D), ('dt', self.dt), ('a_0', self.a_0)] return make_repr_str(self, fs) def", "= lattice.r_to_i(r, L, dx) f = np.zeros(r.shape[1] * (M,), dtype=np.int)", "[('L', self.L), ('dim', self.dim), ('dx', self.dx), ('D', self.D), ('dt', self.dt),", "walls) elif field.ndim == 2: walled_field_numerics.grad_2d(field, grad, dx, walls) elif", "('dt', self.dt), ('a_0', self.a_0)] return make_repr_str(self, fs) def density(r, L,", "dtype=field.dtype) if field.ndim == 2: field_numerics.div_1d(field, div, dx) elif field.ndim", "raise Exception(\"Grad_i not implemented in this dimension\") return grad_i def", "this dimension') return grad def _div(field, dx): assert dx >", "as np from ciabatta.meta import make_repr_str from fealty import lattice,", "dim, dx, walls, a_0=0.0): Scalar.__init__(self, L, dim, dx, a_0=a_0) self.walls", "= np.zeros(r.shape[1] * (M,), dtype=np.int) if f.ndim == 1: field_numerics.density_1d(inds,", "r): return _grad_i(self.a, self.r_to_i(r), self.dx) def laplacian(self): return _laplace(self.a, self.dx)", "dx, a_0=a_0) self.D = D self.dt = dt if self.D", "fs) class Scalar(Field): def __init__(self, L, dim, dx, a_0=0.0): Field.__init__(self,", "== 4: field_numerics.div_3d(field, div, dx) else: raise Exception('Divergence not implemented", "self.a_0)] return make_repr_str(self, fs) # Note, inheritance order matters to", "field_numerics.grad_i_1d(field, inds, grad_i, dx) elif field.ndim == 2: field_numerics.grad_i_2d(field, inds,", "def __init__(self, L, dim, dx, walls, D, dt, a_0=0.0): Diffusing.__init__(self,", "diamond problem on wikipedia and how python handles it) class", "__repr__(self): fs = [('L', self.L), ('dim', self.dim), ('dx', self.dx), ('D',", "dx, walls) else: raise Exception('Laplacian not implemented in this dimension')", "/ M inds = lattice.r_to_i(r, L, dx) f = np.zeros(r.shape[1]", "== 1: walled_field_numerics.grad_1d(field, grad, dx, walls) elif field.ndim == 2:", "assert field.shape == walls.shape assert dx > 0.0 grad =", "hierarchy relating to fields of all kinds. \"\"\" from __future__", "div def _walled_grad(field, dx, walls): assert field.shape == walls.shape assert", "and how python handles it) class WalledDiffusing(WalledScalar, Diffusing): def __init__(self,", "field_numerics, walled_field_numerics class Space(object): def __init__(self, L, dim): self.L =", "dx > 0.0 assert inds.ndim == 2 assert field.ndim ==", "inds, grad_i, dx, walls) else: raise Exception(\"Walled Grad_i not implemented", "all kinds. \"\"\" from __future__ import print_function, division import numpy", "walls): assert field.shape == walls.shape assert dx > 0.0 assert", "M inds = lattice.r_to_i(r, L, dx) f = np.zeros(r.shape[1] *", "1: field_numerics.density_1d(inds, f) elif f.ndim == 2: field_numerics.density_2d(inds, f) elif", "walls) else: raise Exception(\"Walled grad not implemented in this dimension\")", "= walls # Make field zero-valued where obstructed self.a *=", "field.ndim == 1: walled_field_numerics.grad_1d(field, grad, dx, walls) elif field.ndim ==", "self.walls), ('D', self.D), ('dt', self.dt), ('a_0', self.a_0)] return make_repr_str(self, fs)", "dimension') return div def _walled_grad(field, dx, walls): assert field.shape ==", "iterate(self): self.a += self.D * self.laplacian() * self.dt def __repr__(self):", "np from ciabatta.meta import make_repr_str from fealty import lattice, field_numerics,", "return self.L / self.M @property def A_i(self): return self.M **", "A(self): return self.L ** self.dim def iterate(self, *args, **kwargs): pass", "* self.dim * self.dt): raise Exception('Unstable diffusion constant') def iterate(self):", "in this dimension') return div def _walled_grad(field, dx, walls): assert", "self.dt def __repr__(self): fs = [('L', self.L), ('dim', self.dim), ('dx',", "raise Exception('Divergence not implemented in this dimension') return div def", "else: raise Exception(\"Walled grad not implemented in this dimension\") return", "** 2 / (2.0 * self.dim * self.dt): raise Exception('Unstable", "make_repr_str(self, fs) def density(r, L, dx): assert r.ndim == 2", "not implemented in this dimension') return f / dx **", "2 M = int(round(L / dx)) dx = L /", "self.dx) def i_to_r(self, i): return lattice.i_to_r(i, self.L, self.dx) def __repr__(self):", "+= self.D * self.laplacian() * self.dt def __repr__(self): fs =", "dx, walls) else: raise Exception(\"Walled grad not implemented in this", "grad, dx) elif field.ndim == 2: field_numerics.grad_2d(field, grad, dx) elif", "return grad_i def _grad(field, dx): assert dx > 0.0 grad", "/ dx ** r.shape[1] def _laplace(field, dx): assert dx >", "self.D = D self.dt = dt if self.D > self.dx", "Diffusing(Scalar): def __init__(self, L, dim, dx, D, dt, a_0=0.0): Scalar.__init__(self,", "field_numerics.grad_1d(field, grad, dx) elif field.ndim == 2: field_numerics.grad_2d(field, grad, dx)", "else: raise Exception(\"Walled Grad_i not implemented in this dimension\") return", "i): return lattice.i_to_r(i, self.L, self.dx) def __repr__(self): fs = [('L',", "def grad(self): return _grad(self.a, self.dx) def grad_i(self, r): return _grad_i(self.a,", "('a_0', self.a_0)] return make_repr_str(self, fs) class WalledScalar(Scalar): def __init__(self, L,", "__init__(self, L, dim): self.L = L self.dim = dim @property", "self.dx, self.walls) def __repr__(self): fs = [('L', self.L), ('dim', self.dim),", "dx): Space.__init__(self, L, dim) self.M = int(round(self.L / dx)) @property", "dimension\") return grad def _walled_grad_i(field, inds, dx, walls): assert field.shape", "== 2: walled_field_numerics.grad_i_2d(field, inds, grad_i, dx, walls) elif field.ndim ==", "elif f.ndim == 2: field_numerics.density_2d(inds, f) elif f.ndim == 3:", "python handles it) class WalledDiffusing(WalledScalar, Diffusing): def __init__(self, L, dim,", "= dt if self.D > self.dx ** 2 / (2.0", "dtype=field.dtype) if field.ndim == 1: walled_field_numerics.grad_i_1d(field, inds, grad_i, dx, walls)", "field.ndim == 3: walled_field_numerics.laplace_3d(field, laplace, dx, walls) else: raise Exception('Laplacian", "self.walls = walls # Make field zero-valued where obstructed self.a", "_laplace(self.a, self.dx) def __repr__(self): fs = [('L', self.L), ('dim', self.dim),", "in this dimension\") return grad_i def _grad(field, dx): assert dx", "2 / (2.0 * self.dim * self.dt): raise Exception('Unstable diffusion", "f = np.zeros(r.shape[1] * (M,), dtype=np.int) if f.ndim == 1:", "2: walled_field_numerics.grad_i_2d(field, inds, grad_i, dx, walls) elif field.ndim == 3:", "if f.ndim == 1: field_numerics.density_1d(inds, f) elif f.ndim == 2:", "field_numerics.density_1d(inds, f) elif f.ndim == 2: field_numerics.density_2d(inds, f) elif f.ndim", "f) elif f.ndim == 3: field_numerics.density_3d(inds, f) else: raise Exception('Density", "not implemented in this dimension\") return grad_i def _walled_laplace(field, dx,", "self.a += self.D * self.laplacian() * self.dt def __repr__(self): fs", "> 0.0 grad = np.empty(field.shape + (field.ndim,), dtype=field.dtype) if field.ndim", "self.r_to_i(r), self.dx) def laplacian(self): return _laplace(self.a, self.dx) def __repr__(self): fs", "L, dim, dx, walls, a_0=0.0): Scalar.__init__(self, L, dim, dx, a_0=a_0)", "field_numerics.div_2d(field, div, dx) elif field.ndim == 4: field_numerics.div_3d(field, div, dx)", "Grad_i not implemented in this dimension\") return grad_i def _walled_laplace(field,", "1: field_numerics.grad_i_1d(field, inds, grad_i, dx) elif field.ndim == 2: field_numerics.grad_i_2d(field,", "def grad_i(self, r): return _grad_i(self.a, self.r_to_i(r), self.dx) def laplacian(self): return", "def density_field(self, r): return density(r, self.L, self.dx) def r_to_i(self, r):", "** self.dim def density_field(self, r): return density(r, self.L, self.dx) def", "== 1: field_numerics.grad_i_1d(field, inds, grad_i, dx) elif field.ndim == 2:", "self.dt), ('a_0', self.a_0)] return make_repr_str(self, fs) class WalledScalar(Scalar): def __init__(self,", "elif field.ndim == 2: field_numerics.grad_i_2d(field, inds, grad_i, dx) elif field.ndim", "self.a_0)] return make_repr_str(self, fs) class WalledScalar(Scalar): def __init__(self, L, dim,", "_walled_grad(self.a, self.dx, self.walls) def grad_i(self, r): return _walled_grad_i(self.a, self.r_to_i(r), self.dx,", "grad, dx, walls) else: raise Exception(\"Walled grad not implemented in", "in this dimension\") return grad_i def _walled_laplace(field, dx, walls): assert", "dim, dx, a_0=0.0): Field.__init__(self, L, dim, dx) self.a = np.ones(self.dim", "/ self.M @property def A_i(self): return self.M ** self.dim @property", "self.dx, self.walls) def laplacian(self): return _walled_laplace(self.a, self.dx, self.walls) def __repr__(self):", "== 1: field_numerics.grad_1d(field, grad, dx) elif field.ndim == 2: field_numerics.grad_2d(field,", "walls) elif field.ndim == 2: walled_field_numerics.laplace_2d(field, laplace, dx, walls) elif", "__init__(self, L, dim, dx, D, dt, a_0=0.0): Scalar.__init__(self, L, dim,", "Exception('Unstable diffusion constant') def iterate(self): self.a += self.D * self.laplacian()", "if field.ndim == 1: field_numerics.grad_i_1d(field, inds, grad_i, dx) elif field.ndim", "_grad(field, dx): assert dx > 0.0 grad = np.empty(field.shape +", "on wikipedia and how python handles it) class WalledDiffusing(WalledScalar, Diffusing):", "self.dx ** 2 / (2.0 * self.dim * self.dt): raise", "def _walled_laplace(field, dx, walls): assert field.shape == walls.shape assert dx", "def _laplace(field, dx): assert dx > 0.0 laplace = np.empty_like(field)", "dx) elif field.ndim == 2: field_numerics.grad_i_2d(field, inds, grad_i, dx) elif", "in this dimension') return f / dx ** r.shape[1] def", "return grad_i def _walled_laplace(field, dx, walls): assert field.shape == walls.shape", "A class hierarchy relating to fields of all kinds. \"\"\"", "# Note, inheritance order matters to get walled grad &", "self.dx ** self.dim def density_field(self, r): return density(r, self.L, self.dx)", "> 0.0 laplace = np.empty_like(field) if field.ndim == 1: field_numerics.laplace_1d(field,", "field.ndim == 2: field_numerics.grad_i_2d(field, inds, grad_i, dx) elif field.ndim ==", "grad = np.empty(field.shape + (field.ndim,), dtype=field.dtype) if field.ndim == 1:", "dim, dx, D, dt, a_0=a_0) WalledScalar.__init__(self, L, dim, dx, walls,", "walls) elif field.ndim == 3: walled_field_numerics.laplace_3d(field, laplace, dx, walls) else:", "self.dx) def grad_i(self, r): return _grad_i(self.a, self.r_to_i(r), self.dx) def laplacian(self):", "self.r_to_i(r), self.dx, self.walls) def laplacian(self): return _walled_laplace(self.a, self.dx, self.walls) def", "return lattice.i_to_r(i, self.L, self.dx) def __repr__(self): fs = [('L', self.L),", "_walled_grad(field, dx, walls): assert field.shape == walls.shape assert dx >", "np.empty_like(field) if field.ndim == 1: field_numerics.laplace_1d(field, laplace, dx) elif field.ndim", "f) elif f.ndim == 2: field_numerics.density_2d(inds, f) elif f.ndim ==", "[('L', self.L), ('dim', self.dim), ('dx', self.dx), ('a_0', self.a_0)] return make_repr_str(self,", "field_numerics.density_2d(inds, f) elif f.ndim == 3: field_numerics.density_3d(inds, f) else: raise", "\"\"\" A class hierarchy relating to fields of all kinds.", "__init__(self, L, dim, dx): Space.__init__(self, L, dim) self.M = int(round(self.L", "dtype=field.dtype) if field.ndim == 1: field_numerics.grad_1d(field, grad, dx) elif field.ndim", "a_0=a_0) WalledScalar.__init__(self, L, dim, dx, walls, a_0=a_0) def __repr__(self): fs", "else: raise Exception('Divergence not implemented in this dimension') return div", "i_to_r(self, i): return lattice.i_to_r(i, self.L, self.dx) def __repr__(self): fs =", "constant') def iterate(self): self.a += self.D * self.laplacian() * self.dt", "/ dx)) dx = L / M inds = lattice.r_to_i(r,", "D, dt, a_0=a_0) WalledScalar.__init__(self, L, dim, dx, walls, a_0=a_0) def", "= np.empty(inds.shape, dtype=field.dtype) if field.ndim == 1: field_numerics.grad_i_1d(field, inds, grad_i,", "elif field.ndim == 3: field_numerics.laplace_3d(field, laplace, dx) else: raise Exception('Laplacian", "dim, dx, a_0=a_0) self.walls = walls # Make field zero-valued", "implemented in this dimension') return f / dx ** r.shape[1]", "dx, D, dt, a_0=0.0): Scalar.__init__(self, L, dim, dx, a_0=a_0) self.D", "\"\"\" from __future__ import print_function, division import numpy as np", "where obstructed self.a *= np.logical_not(self.walls) def grad(self): return _walled_grad(self.a, self.dx,", "# (see diamond problem on wikipedia and how python handles", "_walled_laplace(self.a, self.dx, self.walls) def __repr__(self): fs = [('L', self.L), ('dim',", "dx) elif field.ndim == 3: field_numerics.grad_i_3d(field, grad_i, dx) else: raise", "def A_i(self): return self.M ** self.dim @property def dA(self): return", "return make_repr_str(self, fs) def density(r, L, dx): assert r.ndim ==", "walls.shape assert dx > 0.0 laplace = np.empty_like(field) if field.ndim", "laplacian(self): return _laplace(self.a, self.dx) def __repr__(self): fs = [('L', self.L),", "dtype=np.int) if f.ndim == 1: field_numerics.density_1d(inds, f) elif f.ndim ==", "implemented in this dimension\") return grad_i def _grad(field, dx): assert", "self.L), ('dim', self.dim)] return make_repr_str(self, fs) class Field(Space): def __init__(self,", "walls.shape assert dx > 0.0 assert inds.ndim == 2 assert", "how python handles it) class WalledDiffusing(WalledScalar, Diffusing): def __init__(self, L,", "dim, dx, walls, a_0=a_0) def __repr__(self): fs = [('L', self.L),", "WalledScalar.__init__(self, L, dim, dx, walls, a_0=a_0) def __repr__(self): fs =", "raise Exception('Grad not implemented in this dimension') return grad def", "1: field_numerics.laplace_1d(field, laplace, dx) elif field.ndim == 2: field_numerics.laplace_2d(field, laplace,", "grad_i, dx) elif field.ndim == 2: field_numerics.grad_i_2d(field, inds, grad_i, dx)", "(see diamond problem on wikipedia and how python handles it)", "class Scalar(Field): def __init__(self, L, dim, dx, a_0=0.0): Field.__init__(self, L,", "L, dim, dx, D, dt, a_0=0.0): Scalar.__init__(self, L, dim, dx,", "handles it) class WalledDiffusing(WalledScalar, Diffusing): def __init__(self, L, dim, dx,", "field.ndim == 2: field_numerics.grad_2d(field, grad, dx) elif field.ndim == 3:", "0.0 grad = np.empty(field.shape + (field.ndim,), dtype=field.dtype) if field.ndim ==", "dx, D, dt, a_0=a_0) WalledScalar.__init__(self, L, dim, dx, walls, a_0=a_0)", "(field.ndim,), dtype=field.dtype) if field.ndim == 1: walled_field_numerics.grad_1d(field, grad, dx, walls)", "this dimension\") return grad def _walled_grad_i(field, inds, dx, walls): assert", "Exception('Density calc not implemented in this dimension') return f /", "field.ndim == 2: walled_field_numerics.grad_i_2d(field, inds, grad_i, dx, walls) elif field.ndim", "3: walled_field_numerics.grad_3d(field, grad, dx, walls) else: raise Exception(\"Walled grad not", "it) class WalledDiffusing(WalledScalar, Diffusing): def __init__(self, L, dim, dx, walls,", "walls) else: raise Exception(\"Walled Grad_i not implemented in this dimension\")", "self.dx) def r_to_i(self, r): return lattice.r_to_i(r, self.L, self.dx) def i_to_r(self,", "_grad_i(field, inds, dx): assert dx > 0.0 assert inds.ndim ==", "L, dim, dx, D, dt, a_0=a_0) WalledScalar.__init__(self, L, dim, dx,", "pass def __repr__(self): fs = [('L', self.L), ('dim', self.dim)] return", "dim, dx, D, dt, a_0=0.0): Scalar.__init__(self, L, dim, dx, a_0=a_0)", "self.D > self.dx ** 2 / (2.0 * self.dim *", "if self.D > self.dx ** 2 / (2.0 * self.dim", "& laplacian call # (see diamond problem on wikipedia and", "def __init__(self, L, dim, dx, D, dt, a_0=0.0): Scalar.__init__(self, L,", "self.dx), ('walls', self.walls), ('D', self.D), ('dt', self.dt), ('a_0', self.a_0)] return", "('dx', self.dx), ('a_0', self.a_0)] return make_repr_str(self, fs) class Diffusing(Scalar): def", "= [('L', self.L), ('dim', self.dim), ('dx', self.dx), ('D', self.D), ('dt',", "3: field_numerics.density_3d(inds, f) else: raise Exception('Density calc not implemented in", "walls, a_0=a_0) def __repr__(self): fs = [('L', self.L), ('dim', self.dim),", "in this dimension\") return grad def _walled_grad_i(field, inds, dx, walls):", "def _walled_grad_i(field, inds, dx, walls): assert field.shape == walls.shape assert", "numpy as np from ciabatta.meta import make_repr_str from fealty import", "== 2: walled_field_numerics.laplace_2d(field, laplace, dx, walls) elif field.ndim == 3:", "elif field.ndim == 2: walled_field_numerics.grad_i_2d(field, inds, grad_i, dx, walls) elif", "field.ndim == 2: field_numerics.laplace_2d(field, laplace, dx) elif field.ndim == 3:", "return f / dx ** r.shape[1] def _laplace(field, dx): assert", "('a_0', self.a_0)] return make_repr_str(self, fs) # Note, inheritance order matters", "2: walled_field_numerics.laplace_2d(field, laplace, dx, walls) elif field.ndim == 3: walled_field_numerics.laplace_3d(field,", "dimension\") return grad_i def _grad(field, dx): assert dx > 0.0", "== walls.shape assert dx > 0.0 grad = np.empty(field.shape +", "Field.__init__(self, L, dim, dx) self.a = np.ones(self.dim * (self.M,), dtype=np.float)", "assert dx > 0.0 assert inds.ndim == 2 assert field.ndim", "laplace, dx, walls) elif field.ndim == 3: walled_field_numerics.laplace_3d(field, laplace, dx,", "field.ndim == 3: field_numerics.grad_3d(field, grad, dx) else: raise Exception('Grad not", "assert r.ndim == 2 M = int(round(L / dx)) dx", "('dx', self.dx), ('walls', self.walls), ('a_0', self.a_0)] return make_repr_str(self, fs) #", "*= np.logical_not(self.walls) def grad(self): return _walled_grad(self.a, self.dx, self.walls) def grad_i(self,", "walled grad & laplacian call # (see diamond problem on", "return make_repr_str(self, fs) class WalledScalar(Scalar): def __init__(self, L, dim, dx,", "dx(self): return self.L / self.M @property def A_i(self): return self.M", "dx) else: raise Exception('Divergence not implemented in this dimension') return", "L, dx): assert r.ndim == 2 M = int(round(L /", "self.D), ('dt', self.dt), ('a_0', self.a_0)] return make_repr_str(self, fs) def density(r,", "L, dim): self.L = L self.dim = dim @property def", "field_numerics.grad_2d(field, grad, dx) elif field.ndim == 3: field_numerics.grad_3d(field, grad, dx)", "M = int(round(L / dx)) dx = L / M", "3: field_numerics.grad_i_3d(field, grad_i, dx) else: raise Exception(\"Grad_i not implemented in", "walls): assert field.shape == walls.shape assert dx > 0.0 laplace", "density_field(self, r): return density(r, self.L, self.dx) def r_to_i(self, r): return", "grad(self): return _walled_grad(self.a, self.dx, self.walls) def grad_i(self, r): return _walled_grad_i(self.a,", "_walled_grad_i(field, inds, dx, walls): assert field.shape == walls.shape assert dx", "self.dx) def __repr__(self): fs = [('L', self.L), ('dim', self.dim), ('dx',", "__repr__(self): fs = [('L', self.L), ('dim', self.dim)] return make_repr_str(self, fs)", "L_half(self): return self.L / 2.0 @property def A(self): return self.L", "dx) f = np.zeros(r.shape[1] * (M,), dtype=np.int) if f.ndim ==", "Field(Space): def __init__(self, L, dim, dx): Space.__init__(self, L, dim) self.M", "2: field_numerics.div_1d(field, div, dx) elif field.ndim == 3: field_numerics.div_2d(field, div,", "dx) else: raise Exception(\"Grad_i not implemented in this dimension\") return", "('a_0', self.a_0)] return make_repr_str(self, fs) class Diffusing(Scalar): def __init__(self, L,", "Diffusing.__init__(self, L, dim, dx, D, dt, a_0=a_0) WalledScalar.__init__(self, L, dim,", "lattice, field_numerics, walled_field_numerics class Space(object): def __init__(self, L, dim): self.L", "== 3: walled_field_numerics.grad_3d(field, grad, dx, walls) else: raise Exception(\"Walled grad", "inds, grad_i, dx) elif field.ndim == 3: field_numerics.grad_i_3d(field, grad_i, dx)", "dx, walls) else: raise Exception(\"Walled Grad_i not implemented in this", "walled_field_numerics class Space(object): def __init__(self, L, dim): self.L = L", "WalledScalar(Scalar): def __init__(self, L, dim, dx, walls, a_0=0.0): Scalar.__init__(self, L,", "not implemented in this dimension') return grad def _div(field, dx):", "dx, walls) elif field.ndim == 3: walled_field_numerics.grad_i_3d(field, inds, grad_i, dx,", "inds.shape[1] grad_i = np.empty(inds.shape, dtype=field.dtype) if field.ndim == 1: field_numerics.grad_i_1d(field,", "2: field_numerics.density_2d(inds, f) elif f.ndim == 3: field_numerics.density_3d(inds, f) else:", "return grad def _walled_grad_i(field, inds, dx, walls): assert field.shape ==", "2.0 @property def A(self): return self.L ** self.dim def iterate(self,", "assert dx > 0.0 laplace = np.empty_like(field) if field.ndim ==", "* (self.M,), dtype=np.float) * a_0 def grad(self): return _grad(self.a, self.dx)", "field.ndim == 1: field_numerics.grad_i_1d(field, inds, grad_i, dx) elif field.ndim ==", "laplace, dx, walls) elif field.ndim == 2: walled_field_numerics.laplace_2d(field, laplace, dx,", "= np.empty_like(field) if field.ndim == 1: field_numerics.laplace_1d(field, laplace, dx) elif", "2: field_numerics.grad_i_2d(field, inds, grad_i, dx) elif field.ndim == 3: field_numerics.grad_i_3d(field,", "== 2: field_numerics.div_1d(field, div, dx) elif field.ndim == 3: field_numerics.div_2d(field,", "if field.ndim == 1: field_numerics.grad_1d(field, grad, dx) elif field.ndim ==", "self.dim)] return make_repr_str(self, fs) class Field(Space): def __init__(self, L, dim,", "self.L, self.dx) def i_to_r(self, i): return lattice.i_to_r(i, self.L, self.dx) def", "def __init__(self, L, dim, dx, walls, a_0=0.0): Scalar.__init__(self, L, dim,", "L / M inds = lattice.r_to_i(r, L, dx) f =", "matters to get walled grad & laplacian call # (see", "= int(round(L / dx)) dx = L / M inds", "implemented in this dimension') return laplace def _grad_i(field, inds, dx):", "== 1: field_numerics.density_1d(inds, f) elif f.ndim == 2: field_numerics.density_2d(inds, f)", "ciabatta.meta import make_repr_str from fealty import lattice, field_numerics, walled_field_numerics class", "get walled grad & laplacian call # (see diamond problem", "walls.shape assert dx > 0.0 grad = np.empty(field.shape + (field.ndim,),", "elif field.ndim == 3: walled_field_numerics.grad_3d(field, grad, dx, walls) else: raise", "dim @property def L_half(self): return self.L / 2.0 @property def", "== walls.shape assert dx > 0.0 assert inds.ndim == 2", "== 3: walled_field_numerics.laplace_3d(field, laplace, dx, walls) else: raise Exception('Laplacian not", "fs = [('L', self.L), ('dim', self.dim), ('dx', self.dx), ('a_0', self.a_0)]", "1: walled_field_numerics.grad_i_1d(field, inds, grad_i, dx, walls) elif field.ndim == 2:", "inds.ndim == 2 assert field.ndim == inds.shape[1] grad_i = np.empty(inds.shape,", "self.dim def iterate(self, *args, **kwargs): pass def __repr__(self): fs =", "L, dim, dx, a_0=a_0) self.walls = walls # Make field", "dx = L / M inds = lattice.r_to_i(r, L, dx)", "np.empty(field.shape + (field.ndim,), dtype=field.dtype) if field.ndim == 1: field_numerics.grad_1d(field, grad,", "= int(round(self.L / dx)) @property def dx(self): return self.L /", "dim, dx, walls, D, dt, a_0=0.0): Diffusing.__init__(self, L, dim, dx,", "a_0=0.0): Scalar.__init__(self, L, dim, dx, a_0=a_0) self.D = D self.dt", "1: walled_field_numerics.grad_1d(field, grad, dx, walls) elif field.ndim == 2: walled_field_numerics.grad_2d(field,", "return self.M ** self.dim @property def dA(self): return self.dx **", "in this dimension') return grad def _div(field, dx): assert dx", "dx): assert dx > 0.0 div = np.empty(field.shape[:-1], dtype=field.dtype) if", "Diffusing): def __init__(self, L, dim, dx, walls, D, dt, a_0=0.0):", "field.shape == walls.shape assert dx > 0.0 grad = np.empty(field.shape", "class WalledScalar(Scalar): def __init__(self, L, dim, dx, walls, a_0=0.0): Scalar.__init__(self,", "else: raise Exception(\"Grad_i not implemented in this dimension\") return grad_i", "div, dx) elif field.ndim == 4: field_numerics.div_3d(field, div, dx) else:", "density(r, L, dx): assert r.ndim == 2 M = int(round(L", "2: walled_field_numerics.grad_2d(field, grad, dx, walls) elif field.ndim == 3: walled_field_numerics.grad_3d(field,", "_walled_laplace(field, dx, walls): assert field.shape == walls.shape assert dx >", "else: raise Exception('Density calc not implemented in this dimension') return", "assert field.shape == walls.shape assert dx > 0.0 laplace =", "= np.empty_like(field) if field.ndim == 1: walled_field_numerics.laplace_1d(field, laplace, dx, walls)", "D, dt, a_0=0.0): Diffusing.__init__(self, L, dim, dx, D, dt, a_0=a_0)", "field_numerics.div_3d(field, div, dx) else: raise Exception('Divergence not implemented in this", "import print_function, division import numpy as np from ciabatta.meta import", "def _grad(field, dx): assert dx > 0.0 grad = np.empty(field.shape", "== 3: field_numerics.laplace_3d(field, laplace, dx) else: raise Exception('Laplacian not implemented", "dx, walls) elif field.ndim == 3: walled_field_numerics.laplace_3d(field, laplace, dx, walls)", "('dim', self.dim), ('dx', self.dx), ('a_0', self.a_0)] return make_repr_str(self, fs) class", "grad def _div(field, dx): assert dx > 0.0 div =", "/ dx)) @property def dx(self): return self.L / self.M @property", "L, dim, dx, walls, D, dt, a_0=0.0): Diffusing.__init__(self, L, dim,", "L, dim, dx, walls, a_0=a_0) def __repr__(self): fs = [('L',", "== 2 assert field.ndim == inds.shape[1] grad_i = np.empty(inds.shape, dtype=field.dtype)", "f.ndim == 1: field_numerics.density_1d(inds, f) elif f.ndim == 2: field_numerics.density_2d(inds,", "dim, dx): Space.__init__(self, L, dim) self.M = int(round(self.L / dx))", "Scalar(Field): def __init__(self, L, dim, dx, a_0=0.0): Field.__init__(self, L, dim,", "class Field(Space): def __init__(self, L, dim, dx): Space.__init__(self, L, dim)", "fs = [('L', self.L), ('dim', self.dim), ('dx', self.dx), ('D', self.D),", "kinds. \"\"\" from __future__ import print_function, division import numpy as", "def laplacian(self): return _laplace(self.a, self.dx) def __repr__(self): fs = [('L',", "self.dim), ('dx', self.dx), ('walls', self.walls), ('D', self.D), ('dt', self.dt), ('a_0',", "int(round(self.L / dx)) @property def dx(self): return self.L / self.M", "this dimension\") return grad_i def _grad(field, dx): assert dx >", "class WalledDiffusing(WalledScalar, Diffusing): def __init__(self, L, dim, dx, walls, D,", "raise Exception(\"Walled Grad_i not implemented in this dimension\") return grad_i", "def iterate(self, *args, **kwargs): pass def __repr__(self): fs = [('L',", "r.ndim == 2 M = int(round(L / dx)) dx =", "field.ndim == 3: walled_field_numerics.grad_i_3d(field, inds, grad_i, dx, walls) else: raise", "laplace def _grad_i(field, inds, dx): assert dx > 0.0 assert", "walls) elif field.ndim == 2: walled_field_numerics.grad_i_2d(field, inds, grad_i, dx, walls)", "print_function, division import numpy as np from ciabatta.meta import make_repr_str", "self.L = L self.dim = dim @property def L_half(self): return", "[('L', self.L), ('dim', self.dim)] return make_repr_str(self, fs) class Field(Space): def", "return _walled_laplace(self.a, self.dx, self.walls) def __repr__(self): fs = [('L', self.L),", "field.ndim == 3: field_numerics.laplace_3d(field, laplace, dx) else: raise Exception('Laplacian not", "Scalar.__init__(self, L, dim, dx, a_0=a_0) self.walls = walls # Make", "self.L), ('dim', self.dim), ('dx', self.dx), ('a_0', self.a_0)] return make_repr_str(self, fs)", "('dx', self.dx), ('D', self.D), ('dt', self.dt), ('a_0', self.a_0)] return make_repr_str(self,", "self.dx, self.walls) def grad_i(self, r): return _walled_grad_i(self.a, self.r_to_i(r), self.dx, self.walls)", "self.M @property def A_i(self): return self.M ** self.dim @property def", "def A(self): return self.L ** self.dim def iterate(self, *args, **kwargs):", "2: field_numerics.laplace_2d(field, laplace, dx) elif field.ndim == 3: field_numerics.laplace_3d(field, laplace,", "from fealty import lattice, field_numerics, walled_field_numerics class Space(object): def __init__(self,", "dtype=np.float) * a_0 def grad(self): return _grad(self.a, self.dx) def grad_i(self,", "dx, a_0=a_0) self.walls = walls # Make field zero-valued where", "= L / M inds = lattice.r_to_i(r, L, dx) f", "not implemented in this dimension') return laplace def _grad_i(field, inds,", "@property def A(self): return self.L ** self.dim def iterate(self, *args,", "def __init__(self, L, dim, dx): Space.__init__(self, L, dim) self.M =", "fs) class Diffusing(Scalar): def __init__(self, L, dim, dx, D, dt,", "fs) class Field(Space): def __init__(self, L, dim, dx): Space.__init__(self, L,", "return self.L ** self.dim def iterate(self, *args, **kwargs): pass def", "('walls', self.walls), ('D', self.D), ('dt', self.dt), ('a_0', self.a_0)] return make_repr_str(self,", "elif field.ndim == 2: field_numerics.grad_2d(field, grad, dx) elif field.ndim ==", "== 2 M = int(round(L / dx)) dx = L", "field_numerics.div_1d(field, div, dx) elif field.ndim == 3: field_numerics.div_2d(field, div, dx)", "self.dim), ('dx', self.dx), ('a_0', self.a_0)] return make_repr_str(self, fs) class Diffusing(Scalar):", "return make_repr_str(self, fs) # Note, inheritance order matters to get", "('dim', self.dim), ('dx', self.dx), ('walls', self.walls), ('D', self.D), ('dt', self.dt),", "== 2: field_numerics.grad_i_2d(field, inds, grad_i, dx) elif field.ndim == 3:", "def _div(field, dx): assert dx > 0.0 div = np.empty(field.shape[:-1],", "= L self.dim = dim @property def L_half(self): return self.L", "field zero-valued where obstructed self.a *= np.logical_not(self.walls) def grad(self): return", "dx): assert dx > 0.0 grad = np.empty(field.shape + (field.ndim,),", "dx > 0.0 div = np.empty(field.shape[:-1], dtype=field.dtype) if field.ndim ==", "= np.empty(field.shape[:-1], dtype=field.dtype) if field.ndim == 2: field_numerics.div_1d(field, div, dx)", "grad_i, dx, walls) elif field.ndim == 3: walled_field_numerics.grad_i_3d(field, inds, grad_i,", "dim) self.M = int(round(self.L / dx)) @property def dx(self): return", "def dA(self): return self.dx ** self.dim def density_field(self, r): return", "grad_i(self, r): return _grad_i(self.a, self.r_to_i(r), self.dx) def laplacian(self): return _laplace(self.a,", "('a_0', self.a_0)] return make_repr_str(self, fs) def density(r, L, dx): assert", "inds = lattice.r_to_i(r, L, dx) f = np.zeros(r.shape[1] * (M,),", "0.0 div = np.empty(field.shape[:-1], dtype=field.dtype) if field.ndim == 2: field_numerics.div_1d(field,", "not implemented in this dimension\") return grad_i def _grad(field, dx):", "else: raise Exception('Grad not implemented in this dimension') return grad", "self.a_0)] return make_repr_str(self, fs) def density(r, L, dx): assert r.ndim", "dx)) @property def dx(self): return self.L / self.M @property def", "a_0 def grad(self): return _grad(self.a, self.dx) def grad_i(self, r): return", "elif field.ndim == 3: walled_field_numerics.grad_i_3d(field, inds, grad_i, dx, walls) else:", "= [('L', self.L), ('dim', self.dim), ('dx', self.dx), ('a_0', self.a_0)] return", "grad, dx, walls) elif field.ndim == 3: walled_field_numerics.grad_3d(field, grad, dx,", "diffusion constant') def iterate(self): self.a += self.D * self.laplacian() *", "dx) elif field.ndim == 3: field_numerics.laplace_3d(field, laplace, dx) else: raise", "0.0 laplace = np.empty_like(field) if field.ndim == 1: field_numerics.laplace_1d(field, laplace,", "this dimension\") return grad_i def _walled_laplace(field, dx, walls): assert field.shape", "self.a_0)] return make_repr_str(self, fs) class Diffusing(Scalar): def __init__(self, L, dim,", "a_0=0.0): Diffusing.__init__(self, L, dim, dx, D, dt, a_0=a_0) WalledScalar.__init__(self, L,", "zero-valued where obstructed self.a *= np.logical_not(self.walls) def grad(self): return _walled_grad(self.a,", "grad & laplacian call # (see diamond problem on wikipedia", "self.dx) def laplacian(self): return _laplace(self.a, self.dx) def __repr__(self): fs =", "self.L / self.M @property def A_i(self): return self.M ** self.dim", "dx): assert r.ndim == 2 M = int(round(L / dx))", "return self.L / 2.0 @property def A(self): return self.L **", "field_numerics.density_3d(inds, f) else: raise Exception('Density calc not implemented in this", "dx, walls, D, dt, a_0=0.0): Diffusing.__init__(self, L, dim, dx, D,", "self.dx), ('a_0', self.a_0)] return make_repr_str(self, fs) class Diffusing(Scalar): def __init__(self,", "dx): assert dx > 0.0 assert inds.ndim == 2 assert", "self.dt = dt if self.D > self.dx ** 2 /", "field_numerics.laplace_2d(field, laplace, dx) elif field.ndim == 3: field_numerics.laplace_3d(field, laplace, dx)", "self.M ** self.dim @property def dA(self): return self.dx ** self.dim", "4: field_numerics.div_3d(field, div, dx) else: raise Exception('Divergence not implemented in", "* a_0 def grad(self): return _grad(self.a, self.dx) def grad_i(self, r):", "of all kinds. \"\"\" from __future__ import print_function, division import", "def __repr__(self): fs = [('L', self.L), ('dim', self.dim), ('dx', self.dx),", "== 2: field_numerics.grad_2d(field, grad, dx) elif field.ndim == 3: field_numerics.grad_3d(field,", "self.L), ('dim', self.dim), ('dx', self.dx), ('walls', self.walls), ('a_0', self.a_0)] return", "== 2: field_numerics.density_2d(inds, f) elif f.ndim == 3: field_numerics.density_3d(inds, f)", "elif field.ndim == 2: field_numerics.laplace_2d(field, laplace, dx) elif field.ndim ==", "dim, dx) self.a = np.ones(self.dim * (self.M,), dtype=np.float) * a_0", "inds, grad_i, dx) elif field.ndim == 2: field_numerics.grad_i_2d(field, inds, grad_i,", "walled_field_numerics.grad_1d(field, grad, dx, walls) elif field.ndim == 2: walled_field_numerics.grad_2d(field, grad,", "not implemented in this dimension\") return grad def _walled_grad_i(field, inds,", "self.walls) def __repr__(self): fs = [('L', self.L), ('dim', self.dim), ('dx',", "(M,), dtype=np.int) if f.ndim == 1: field_numerics.density_1d(inds, f) elif f.ndim", "if field.ndim == 1: walled_field_numerics.grad_1d(field, grad, dx, walls) elif field.ndim", "dim, dx, a_0=a_0) self.D = D self.dt = dt if", "iterate(self, *args, **kwargs): pass def __repr__(self): fs = [('L', self.L),", "f) else: raise Exception('Density calc not implemented in this dimension')", "field_numerics.laplace_1d(field, laplace, dx) elif field.ndim == 2: field_numerics.laplace_2d(field, laplace, dx)", "if field.ndim == 1: field_numerics.laplace_1d(field, laplace, dx) elif field.ndim ==", "laplace, dx) else: raise Exception('Laplacian not implemented in this dimension')", "to fields of all kinds. \"\"\" from __future__ import print_function,", "field.ndim == 3: walled_field_numerics.grad_3d(field, grad, dx, walls) else: raise Exception(\"Walled", "Space.__init__(self, L, dim) self.M = int(round(self.L / dx)) @property def", "__repr__(self): fs = [('L', self.L), ('dim', self.dim), ('dx', self.dx), ('walls',", "elif field.ndim == 3: field_numerics.grad_i_3d(field, grad_i, dx) else: raise Exception(\"Grad_i", "_walled_grad_i(self.a, self.r_to_i(r), self.dx, self.walls) def laplacian(self): return _walled_laplace(self.a, self.dx, self.walls)", "r): return lattice.r_to_i(r, self.L, self.dx) def i_to_r(self, i): return lattice.i_to_r(i,", "grad_i = np.empty(inds.shape, dtype=field.dtype) if field.ndim == 1: walled_field_numerics.grad_i_1d(field, inds,", "r_to_i(self, r): return lattice.r_to_i(r, self.L, self.dx) def i_to_r(self, i): return", "to get walled grad & laplacian call # (see diamond", "not implemented in this dimension') return div def _walled_grad(field, dx,", "('dim', self.dim), ('dx', self.dx)] return make_repr_str(self, fs) class Scalar(Field): def", "Space(object): def __init__(self, L, dim): self.L = L self.dim =", "def grad(self): return _walled_grad(self.a, self.dx, self.walls) def grad_i(self, r): return", "laplace = np.empty_like(field) if field.ndim == 1: field_numerics.laplace_1d(field, laplace, dx)", "dx) self.a = np.ones(self.dim * (self.M,), dtype=np.float) * a_0 def", "dtype=field.dtype) if field.ndim == 1: walled_field_numerics.grad_1d(field, grad, dx, walls) elif", "inds.shape[1] grad_i = np.empty(inds.shape, dtype=field.dtype) if field.ndim == 1: walled_field_numerics.grad_i_1d(field,", "return _grad_i(self.a, self.r_to_i(r), self.dx) def laplacian(self): return _laplace(self.a, self.dx) def", "= [('L', self.L), ('dim', self.dim)] return make_repr_str(self, fs) class Field(Space):", "this dimension') return div def _walled_grad(field, dx, walls): assert field.shape", "dx): assert dx > 0.0 laplace = np.empty_like(field) if field.ndim", "[('L', self.L), ('dim', self.dim), ('dx', self.dx), ('walls', self.walls), ('D', self.D),", "elif field.ndim == 4: field_numerics.div_3d(field, div, dx) else: raise Exception('Divergence", "elif field.ndim == 3: field_numerics.grad_3d(field, grad, dx) else: raise Exception('Grad", "r): return _walled_grad_i(self.a, self.r_to_i(r), self.dx, self.walls) def laplacian(self): return _walled_laplace(self.a,", "field.ndim == 2: walled_field_numerics.grad_2d(field, grad, dx, walls) elif field.ndim ==", "field.ndim == 4: field_numerics.div_3d(field, div, dx) else: raise Exception('Divergence not", "lattice.i_to_r(i, self.L, self.dx) def __repr__(self): fs = [('L', self.L), ('dim',", "== 3: walled_field_numerics.grad_i_3d(field, inds, grad_i, dx, walls) else: raise Exception(\"Walled", "+ (field.ndim,), dtype=field.dtype) if field.ndim == 1: walled_field_numerics.grad_1d(field, grad, dx,", "Exception(\"Grad_i not implemented in this dimension\") return grad_i def _grad(field,", "grad def _walled_grad_i(field, inds, dx, walls): assert field.shape == walls.shape", "dx) elif field.ndim == 2: field_numerics.grad_2d(field, grad, dx) elif field.ndim", "return self.dx ** self.dim def density_field(self, r): return density(r, self.L,", "L, dim, dx): Space.__init__(self, L, dim) self.M = int(round(self.L /", "[('L', self.L), ('dim', self.dim), ('dx', self.dx)] return make_repr_str(self, fs) class", "_laplace(field, dx): assert dx > 0.0 laplace = np.empty_like(field) if", "np.logical_not(self.walls) def grad(self): return _walled_grad(self.a, self.dx, self.walls) def grad_i(self, r):", "class Space(object): def __init__(self, L, dim): self.L = L self.dim", "self.walls), ('a_0', self.a_0)] return make_repr_str(self, fs) # Note, inheritance order", "_grad_i(self.a, self.r_to_i(r), self.dx) def laplacian(self): return _laplace(self.a, self.dx) def __repr__(self):", "from ciabatta.meta import make_repr_str from fealty import lattice, field_numerics, walled_field_numerics", "make_repr_str(self, fs) class WalledScalar(Scalar): def __init__(self, L, dim, dx, walls,", "dx > 0.0 laplace = np.empty_like(field) if field.ndim == 1:", "field.ndim == 3: field_numerics.grad_i_3d(field, grad_i, dx) else: raise Exception(\"Grad_i not", "+ (field.ndim,), dtype=field.dtype) if field.ndim == 1: field_numerics.grad_1d(field, grad, dx)", "L, dim) self.M = int(round(self.L / dx)) @property def dx(self):", "field.ndim == 2: field_numerics.div_1d(field, div, dx) elif field.ndim == 3:", "walled_field_numerics.laplace_3d(field, laplace, dx, walls) else: raise Exception('Laplacian not implemented in", "if field.ndim == 1: walled_field_numerics.grad_i_1d(field, inds, grad_i, dx, walls) elif", "/ (2.0 * self.dim * self.dt): raise Exception('Unstable diffusion constant')", "Exception('Grad not implemented in this dimension') return grad def _div(field,", "self.D), ('dt', self.dt), ('a_0', self.a_0)] return make_repr_str(self, fs) class WalledScalar(Scalar):", "walled_field_numerics.grad_i_3d(field, inds, grad_i, dx, walls) else: raise Exception(\"Walled Grad_i not", "grad_i def _grad(field, dx): assert dx > 0.0 grad =", "/ 2.0 @property def A(self): return self.L ** self.dim def", "r.shape[1] def _laplace(field, dx): assert dx > 0.0 laplace =", "dx) elif field.ndim == 3: field_numerics.div_2d(field, div, dx) elif field.ndim", "assert field.shape == walls.shape assert dx > 0.0 assert inds.ndim", "walled_field_numerics.laplace_2d(field, laplace, dx, walls) elif field.ndim == 3: walled_field_numerics.laplace_3d(field, laplace,", "np.empty(field.shape[:-1], dtype=field.dtype) if field.ndim == 2: field_numerics.div_1d(field, div, dx) elif", "1: walled_field_numerics.laplace_1d(field, laplace, dx, walls) elif field.ndim == 2: walled_field_numerics.laplace_2d(field,", "dx) else: raise Exception('Grad not implemented in this dimension') return", "fs = [('L', self.L), ('dim', self.dim), ('dx', self.dx)] return make_repr_str(self,", "self.L), ('dim', self.dim), ('dx', self.dx), ('walls', self.walls), ('D', self.D), ('dt',", "__repr__(self): fs = [('L', self.L), ('dim', self.dim), ('dx', self.dx), ('a_0',", "dimension') return grad def _div(field, dx): assert dx > 0.0", "fs) class WalledScalar(Scalar): def __init__(self, L, dim, dx, walls, a_0=0.0):", "np.empty(field.shape + (field.ndim,), dtype=field.dtype) if field.ndim == 1: walled_field_numerics.grad_1d(field, grad,", "> self.dx ** 2 / (2.0 * self.dim * self.dt):", "return _grad(self.a, self.dx) def grad_i(self, r): return _grad_i(self.a, self.r_to_i(r), self.dx)", "self.walls) def laplacian(self): return _walled_laplace(self.a, self.dx, self.walls) def __repr__(self): fs", "lattice.r_to_i(r, self.L, self.dx) def i_to_r(self, i): return lattice.i_to_r(i, self.L, self.dx)", "self.a = np.ones(self.dim * (self.M,), dtype=np.float) * a_0 def grad(self):", "dimension') return f / dx ** r.shape[1] def _laplace(field, dx):", "implemented in this dimension') return div def _walled_grad(field, dx, walls):", "= np.empty(field.shape + (field.ndim,), dtype=field.dtype) if field.ndim == 1: field_numerics.grad_1d(field,", "= np.empty(field.shape + (field.ndim,), dtype=field.dtype) if field.ndim == 1: walled_field_numerics.grad_1d(field,", "np.empty(inds.shape, dtype=field.dtype) if field.ndim == 1: walled_field_numerics.grad_i_1d(field, inds, grad_i, dx,", "grad_i, dx, walls) elif field.ndim == 2: walled_field_numerics.grad_i_2d(field, inds, grad_i,", "field.ndim == 1: walled_field_numerics.laplace_1d(field, laplace, dx, walls) elif field.ndim ==", "dtype=field.dtype) if field.ndim == 1: field_numerics.grad_i_1d(field, inds, grad_i, dx) elif", "dt, a_0=a_0) WalledScalar.__init__(self, L, dim, dx, walls, a_0=a_0) def __repr__(self):", "dx ** r.shape[1] def _laplace(field, dx): assert dx > 0.0", "0.0 laplace = np.empty_like(field) if field.ndim == 1: walled_field_numerics.laplace_1d(field, laplace,", "this dimension') return laplace def _grad_i(field, inds, dx): assert dx", "assert inds.ndim == 2 assert field.ndim == inds.shape[1] grad_i =", "assert dx > 0.0 div = np.empty(field.shape[:-1], dtype=field.dtype) if field.ndim", "@property def dx(self): return self.L / self.M @property def A_i(self):", "make_repr_str(self, fs) class Field(Space): def __init__(self, L, dim, dx): Space.__init__(self,", "== 3: field_numerics.grad_i_3d(field, grad_i, dx) else: raise Exception(\"Grad_i not implemented", "grad_i, dx) elif field.ndim == 3: field_numerics.grad_i_3d(field, grad_i, dx) else:", "_div(field, dx): assert dx > 0.0 div = np.empty(field.shape[:-1], dtype=field.dtype)", "walls, a_0=0.0): Scalar.__init__(self, L, dim, dx, a_0=a_0) self.walls = walls", "return lattice.r_to_i(r, self.L, self.dx) def i_to_r(self, i): return lattice.i_to_r(i, self.L,", "self.dt): raise Exception('Unstable diffusion constant') def iterate(self): self.a += self.D", "grad, dx, walls) elif field.ndim == 2: walled_field_numerics.grad_2d(field, grad, dx,", "def __init__(self, L, dim, dx, a_0=0.0): Field.__init__(self, L, dim, dx)", "raise Exception('Laplacian not implemented in this dimension') return laplace def", "Exception('Divergence not implemented in this dimension') return div def _walled_grad(field,", "field.ndim == 2: walled_field_numerics.laplace_2d(field, laplace, dx, walls) elif field.ndim ==", "fs = [('L', self.L), ('dim', self.dim), ('dx', self.dx), ('walls', self.walls),", "self.walls) def grad_i(self, r): return _walled_grad_i(self.a, self.r_to_i(r), self.dx, self.walls) def", "fealty import lattice, field_numerics, walled_field_numerics class Space(object): def __init__(self, L,", "grad_i = np.empty(inds.shape, dtype=field.dtype) if field.ndim == 1: field_numerics.grad_i_1d(field, inds,", "a_0=a_0) def __repr__(self): fs = [('L', self.L), ('dim', self.dim), ('dx',", "= D self.dt = dt if self.D > self.dx **", "a_0=0.0): Field.__init__(self, L, dim, dx) self.a = np.ones(self.dim * (self.M,),", "implemented in this dimension\") return grad def _walled_grad_i(field, inds, dx,", "dx, walls) elif field.ndim == 2: walled_field_numerics.grad_i_2d(field, inds, grad_i, dx,", "implemented in this dimension\") return grad_i def _walled_laplace(field, dx, walls):", "* self.dt def __repr__(self): fs = [('L', self.L), ('dim', self.dim),", "def i_to_r(self, i): return lattice.i_to_r(i, self.L, self.dx) def __repr__(self): fs", "lattice.r_to_i(r, L, dx) f = np.zeros(r.shape[1] * (M,), dtype=np.int) if", "field_numerics.grad_i_2d(field, inds, grad_i, dx) elif field.ndim == 3: field_numerics.grad_i_3d(field, grad_i,", "def grad_i(self, r): return _walled_grad_i(self.a, self.r_to_i(r), self.dx, self.walls) def laplacian(self):", "else: raise Exception('Laplacian not implemented in this dimension') return laplace", "self.L, self.dx) def __repr__(self): fs = [('L', self.L), ('dim', self.dim),", "self.L), ('dim', self.dim), ('dx', self.dx)] return make_repr_str(self, fs) class Scalar(Field):", "in this dimension') return laplace def _grad_i(field, inds, dx): assert", "grad_i, dx, walls) else: raise Exception(\"Walled Grad_i not implemented in", "grad not implemented in this dimension\") return grad def _walled_grad_i(field,", "('dt', self.dt), ('a_0', self.a_0)] return make_repr_str(self, fs) class WalledScalar(Scalar): def", "raise Exception(\"Walled grad not implemented in this dimension\") return grad", "self.dx), ('walls', self.walls), ('a_0', self.a_0)] return make_repr_str(self, fs) # Note,", "self.L), ('dim', self.dim), ('dx', self.dx), ('D', self.D), ('dt', self.dt), ('a_0',", "self.a *= np.logical_not(self.walls) def grad(self): return _walled_grad(self.a, self.dx, self.walls) def", "== 1: walled_field_numerics.laplace_1d(field, laplace, dx, walls) elif field.ndim == 2:", "dx, a_0=0.0): Field.__init__(self, L, dim, dx) self.a = np.ones(self.dim *", "raise Exception('Density calc not implemented in this dimension') return f", "L, dim, dx, a_0=a_0) self.D = D self.dt = dt", "dx, walls, a_0=0.0): Scalar.__init__(self, L, dim, dx, a_0=a_0) self.walls =", "a_0=a_0) self.D = D self.dt = dt if self.D >", "self.D * self.laplacian() * self.dt def __repr__(self): fs = [('L',", "__init__(self, L, dim, dx, walls, a_0=0.0): Scalar.__init__(self, L, dim, dx,", "('dim', self.dim), ('dx', self.dx), ('walls', self.walls), ('a_0', self.a_0)] return make_repr_str(self,", "inds, dx, walls): assert field.shape == walls.shape assert dx >", "Exception(\"Walled Grad_i not implemented in this dimension\") return grad_i def", "return laplace def _grad_i(field, inds, dx): assert dx > 0.0", "walls): assert field.shape == walls.shape assert dx > 0.0 grad", "dx, walls) elif field.ndim == 2: walled_field_numerics.grad_2d(field, grad, dx, walls)", "make_repr_str(self, fs) class Scalar(Field): def __init__(self, L, dim, dx, a_0=0.0):", "calc not implemented in this dimension') return f / dx", "*args, **kwargs): pass def __repr__(self): fs = [('L', self.L), ('dim',", "implemented in this dimension') return grad def _div(field, dx): assert", "self.laplacian() * self.dt def __repr__(self): fs = [('L', self.L), ('dim',", "walls # Make field zero-valued where obstructed self.a *= np.logical_not(self.walls)", "def iterate(self): self.a += self.D * self.laplacian() * self.dt def", "walled_field_numerics.grad_2d(field, grad, dx, walls) elif field.ndim == 3: walled_field_numerics.grad_3d(field, grad,", "@property def L_half(self): return self.L / 2.0 @property def A(self):", "laplace, dx, walls) else: raise Exception('Laplacian not implemented in this", "self.dt), ('a_0', self.a_0)] return make_repr_str(self, fs) def density(r, L, dx):", "Note, inheritance order matters to get walled grad & laplacian", "L, dim, dx, a_0=0.0): Field.__init__(self, L, dim, dx) self.a =", "A_i(self): return self.M ** self.dim @property def dA(self): return self.dx", "order matters to get walled grad & laplacian call #", "self.dim), ('dx', self.dx)] return make_repr_str(self, fs) class Scalar(Field): def __init__(self,", "(2.0 * self.dim * self.dt): raise Exception('Unstable diffusion constant') def", "walled_field_numerics.grad_i_2d(field, inds, grad_i, dx, walls) elif field.ndim == 3: walled_field_numerics.grad_i_3d(field,", "== walls.shape assert dx > 0.0 laplace = np.empty_like(field) if", "np.empty_like(field) if field.ndim == 1: walled_field_numerics.laplace_1d(field, laplace, dx, walls) elif", "== 3: field_numerics.density_3d(inds, f) else: raise Exception('Density calc not implemented", "return grad def _div(field, dx): assert dx > 0.0 div", "def _walled_grad(field, dx, walls): assert field.shape == walls.shape assert dx", "inds, grad_i, dx, walls) elif field.ndim == 3: walled_field_numerics.grad_i_3d(field, inds,", "walled_field_numerics.grad_i_1d(field, inds, grad_i, dx, walls) elif field.ndim == 2: walled_field_numerics.grad_i_2d(field,", "> 0.0 div = np.empty(field.shape[:-1], dtype=field.dtype) if field.ndim == 2:", "self.dim), ('dx', self.dx), ('walls', self.walls), ('a_0', self.a_0)] return make_repr_str(self, fs)", "1: field_numerics.grad_1d(field, grad, dx) elif field.ndim == 2: field_numerics.grad_2d(field, grad,", "dimension\") return grad_i def _walled_laplace(field, dx, walls): assert field.shape ==", "relating to fields of all kinds. \"\"\" from __future__ import", "if field.ndim == 2: field_numerics.div_1d(field, div, dx) elif field.ndim ==", "dt, a_0=0.0): Diffusing.__init__(self, L, dim, dx, D, dt, a_0=a_0) WalledScalar.__init__(self,", "fields of all kinds. \"\"\" from __future__ import print_function, division", "_grad(self.a, self.dx) def grad_i(self, r): return _grad_i(self.a, self.r_to_i(r), self.dx) def", "Exception('Laplacian not implemented in this dimension') return laplace def _grad_i(field,", "= np.empty(inds.shape, dtype=field.dtype) if field.ndim == 1: walled_field_numerics.grad_i_1d(field, inds, grad_i,", "f.ndim == 3: field_numerics.density_3d(inds, f) else: raise Exception('Density calc not", "dx, walls, a_0=a_0) def __repr__(self): fs = [('L', self.L), ('dim',", "dx)) dx = L / M inds = lattice.r_to_i(r, L,", "dx) elif field.ndim == 2: field_numerics.laplace_2d(field, laplace, dx) elif field.ndim", "> 0.0 laplace = np.empty_like(field) if field.ndim == 1: walled_field_numerics.laplace_1d(field,", "elif field.ndim == 2: walled_field_numerics.laplace_2d(field, laplace, dx, walls) elif field.ndim", "('dx', self.dx)] return make_repr_str(self, fs) class Scalar(Field): def __init__(self, L,", "dim): self.L = L self.dim = dim @property def L_half(self):", "return div def _walled_grad(field, dx, walls): assert field.shape == walls.shape", "return _walled_grad(self.a, self.dx, self.walls) def grad_i(self, r): return _walled_grad_i(self.a, self.r_to_i(r),", "field.ndim == 1: walled_field_numerics.grad_i_1d(field, inds, grad_i, dx, walls) elif field.ndim", "return density(r, self.L, self.dx) def r_to_i(self, r): return lattice.r_to_i(r, self.L,", "def r_to_i(self, r): return lattice.r_to_i(r, self.L, self.dx) def i_to_r(self, i):", "walls) elif field.ndim == 3: walled_field_numerics.grad_i_3d(field, inds, grad_i, dx, walls)", "('walls', self.walls), ('a_0', self.a_0)] return make_repr_str(self, fs) # Note, inheritance", "grad_i(self, r): return _walled_grad_i(self.a, self.r_to_i(r), self.dx, self.walls) def laplacian(self): return", "walls) else: raise Exception('Laplacian not implemented in this dimension') return", "division import numpy as np from ciabatta.meta import make_repr_str from" ]
[ "os.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"example_django.settings\") application = get_asgi_application() os.system(\"/usr/bin/python3 /opt/code/manage.py migrate\") os.system(\"/usr/bin/python3 /opt/code/manage.py", "= get_asgi_application() os.system(\"/usr/bin/python3 /opt/code/manage.py migrate\") os.system(\"/usr/bin/python3 /opt/code/manage.py \" \"loaddata /opt/code/blog/fixtures/default_articles.json\")", "\"example_django.settings\") application = get_asgi_application() os.system(\"/usr/bin/python3 /opt/code/manage.py migrate\") os.system(\"/usr/bin/python3 /opt/code/manage.py \"", "on this file, see https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/ \"\"\" import os from django.core.asgi", "ASGI config for example_django project. It exposes the ASGI callable", "ASGI callable as a module-level variable named ``application``. For more", "config for example_django project. It exposes the ASGI callable as", "It exposes the ASGI callable as a module-level variable named", "https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/ \"\"\" import os from django.core.asgi import get_asgi_application os.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"example_django.settings\")", "more information on this file, see https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/ \"\"\" import os", "application = get_asgi_application() os.system(\"/usr/bin/python3 /opt/code/manage.py migrate\") os.system(\"/usr/bin/python3 /opt/code/manage.py \" \"loaddata", "named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/", "callable as a module-level variable named ``application``. For more information", "see https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/ \"\"\" import os from django.core.asgi import get_asgi_application os.environ.setdefault(\"DJANGO_SETTINGS_MODULE\",", "django.core.asgi import get_asgi_application os.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"example_django.settings\") application = get_asgi_application() os.system(\"/usr/bin/python3 /opt/code/manage.py", "import get_asgi_application os.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"example_django.settings\") application = get_asgi_application() os.system(\"/usr/bin/python3 /opt/code/manage.py migrate\")", "\"\"\" import os from django.core.asgi import get_asgi_application os.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"example_django.settings\") application", "``application``. For more information on this file, see https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/ \"\"\"", "the ASGI callable as a module-level variable named ``application``. For", "get_asgi_application os.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"example_django.settings\") application = get_asgi_application() os.system(\"/usr/bin/python3 /opt/code/manage.py migrate\") os.system(\"/usr/bin/python3", "as a module-level variable named ``application``. For more information on", "information on this file, see https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/ \"\"\" import os from", "os from django.core.asgi import get_asgi_application os.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"example_django.settings\") application = get_asgi_application()", "variable named ``application``. For more information on this file, see", "import os from django.core.asgi import get_asgi_application os.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"example_django.settings\") application =", "file, see https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/ \"\"\" import os from django.core.asgi import get_asgi_application", "for example_django project. It exposes the ASGI callable as a", "\"\"\" ASGI config for example_django project. It exposes the ASGI", "For more information on this file, see https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/ \"\"\" import", "module-level variable named ``application``. For more information on this file,", "exposes the ASGI callable as a module-level variable named ``application``.", "this file, see https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/ \"\"\" import os from django.core.asgi import", "example_django project. It exposes the ASGI callable as a module-level", "project. It exposes the ASGI callable as a module-level variable", "from django.core.asgi import get_asgi_application os.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"example_django.settings\") application = get_asgi_application() os.system(\"/usr/bin/python3", "a module-level variable named ``application``. For more information on this" ]
[ "src.library.compute_moments import calc_restricted_wage_distribution from src.library.compute_moments import calc_unrestricted_choice_probabilities from src.library.compute_moments import", "calc_restricted_wage_distribution from src.library.compute_moments import calc_unrestricted_choice_probabilities from src.library.compute_moments import calc_unrestricted_wage_distribution from", "rp.get_moment_errors_func( params=params, options=options, calc_moments=calc_moments, replace_nans=_replace_nans, empirical_moments=empirical_moments, weighting_matrix=weighting_matrix, ) # get", "matrix weighting_matrix = _load_pickle( ppj(\"OUT_ANALYSIS\", \"msm_estimation\", \"weighting_matrix_hyp.pickle\") ) calc_moments =", "np import pandas as pd import respy as rp import", "matrix in `OUT_ANALYSIS`, \"msm_estimation\", generate values of Method of Simulated", "if __name__ == \"__main__\": # load params params = pd.read_csv(", "open(ppj(\"IN_MODEL_SPECS\", \"options_hyp.yaml\")) as options: options = yaml.safe_load(options) # get empirical", "= delta val = crit_func(params_) result = {\"beta\": beta, \"delta\":", "\"Choice Probabilities Unrestricted\": calc_unrestricted_choice_probabilities, \"Wage Distribution Very Restricted\": calc_very_restricted_wage_distribution, \"Wage", "Restricted\": calc_very_restricted_wage_distribution, \"Wage Distribution Restricted\": calc_restricted_wage_distribution, \"Wage Distribution Unrestricted\": calc_unrestricted_wage_distribution,", "= rp.get_moment_errors_func( params=params, options=options, calc_moments=calc_moments, replace_nans=_replace_nans, empirical_moments=empirical_moments, weighting_matrix=weighting_matrix, ) #", "distribution results results = get_bivariate_distribution( crit_func=weighted_sum_squared_errors, params=params, grid_delta=np.arange(0.945, 0.9625, 0.0025),", "model parameters. crit_func (dict): Dictionary containing model options. grid_delta (np.array):", "from bld.project_paths import project_paths_join as ppj from src.library.compute_moments import _replace_nans", ") params[\"value\"] = params[\"value\"].astype(float) # load options with open(ppj(\"IN_MODEL_SPECS\", \"options_hyp.yaml\"))", "= beta params_.loc[(\"delta\", \"delta\"), \"value\"] = delta val = crit_func(params_)", "Restricted\": calc_restricted_choice_probabilities, \"Choice Probabilities Unrestricted\": calc_unrestricted_choice_probabilities, \"Wage Distribution Very Restricted\":", "= params[\"value\"].astype(float) # load options with open(ppj(\"IN_MODEL_SPECS\", \"options_hyp.yaml\")) as options:", "\"Wage Distribution Unrestricted\": calc_unrestricted_wage_distribution, } with _temporary_working_directory(snippet=\"heatmap\"): # get criterion", "grid_delta, grid_beta): \"\"\"Compute value of criterion function. Args: params (pd.DataFrame):", "and weighting matrix in `OUT_ANALYSIS`, \"msm_estimation\", generate values of Method", "weighting matrix weighting_matrix = _load_pickle( ppj(\"OUT_ANALYSIS\", \"msm_estimation\", \"weighting_matrix_hyp.pickle\") ) calc_moments", "`OUT_ANALYSIS`, \"msm_estimation\", generate values of Method of Simulated Moments criterion", "study the bivariate distribution of the time preference parameters around", "around the combination of true parameter values. \"\"\" import itertools", "params.copy() params_.loc[(\"beta\", \"beta\"), \"value\"] = beta params_.loc[(\"delta\", \"delta\"), \"value\"] =", "crit_func(params_) result = {\"beta\": beta, \"delta\": delta, \"val\": val} results.append(result)", "calc_unrestricted_choice_probabilities from src.library.compute_moments import calc_unrestricted_wage_distribution from src.library.compute_moments import calc_very_restricted_choice_probabilities from", "calc_very_restricted_wage_distribution from src.library.housekeeping import _load_pickle from src.library.housekeeping import _temporary_working_directory from", "the combination of true parameter values. \"\"\" import itertools import", "Simulated Moments criterion function for combinations of discount factor and", "beta, delta in tqdm(itertools.product(grid_beta, grid_delta)): params_ = params.copy() params_.loc[(\"beta\", \"beta\"),", "grid_delta)): params_ = params.copy() params_.loc[(\"beta\", \"beta\"), \"value\"] = beta params_.loc[(\"delta\",", "pd.read_csv( ppj(\"IN_MODEL_SPECS\", \"params_hyp.csv\"), sep=\";\", index_col=[\"category\", \"name\"], ) params[\"value\"] = params[\"value\"].astype(float)", "src.library.compute_moments import calc_very_restricted_wage_distribution from src.library.housekeeping import _load_pickle from src.library.housekeeping import", "crit_func (dict): Dictionary containing model options. grid_delta (np.array): Values of", "params[\"value\"].astype(float) # load options with open(ppj(\"IN_MODEL_SPECS\", \"options_hyp.yaml\")) as options: options", "get empirical moments empirical_moments = _load_pickle(ppj(\"OUT_ANALYSIS\", \"msm_estimation\", \"moments_hyp.pickle\")) # get", "yaml.safe_load(options) # get empirical moments empirical_moments = _load_pickle(ppj(\"OUT_ANALYSIS\", \"msm_estimation\", \"moments_hyp.pickle\"))", "from src.library.compute_moments import calc_restricted_wage_distribution from src.library.compute_moments import calc_unrestricted_choice_probabilities from src.library.compute_moments", "Unrestricted\": calc_unrestricted_choice_probabilities, \"Wage Distribution Very Restricted\": calc_very_restricted_wage_distribution, \"Wage Distribution Restricted\":", "\"msm_estimation\", generate values of Method of Simulated Moments criterion function", "import pandas as pd import respy as rp import yaml", "weighting_matrix=weighting_matrix, ) # get bivariate distribution results results = get_bivariate_distribution(", "params (pd.DataFrame): DataFrame containing model parameters. crit_func (dict): Dictionary containing", "weighting matrix in `OUT_ANALYSIS`, \"msm_estimation\", generate values of Method of", "for beta, delta in tqdm(itertools.product(grid_beta, grid_delta)): params_ = params.copy() params_.loc[(\"beta\",", "return pd.DataFrame.from_dict(results) if __name__ == \"__main__\": # load params params", "import numpy as np import pandas as pd import respy", "as rp import yaml from bld.project_paths import project_paths_join as ppj", "\"value\"] = delta val = crit_func(params_) result = {\"beta\": beta,", "results.append(result) return pd.DataFrame.from_dict(results) if __name__ == \"__main__\": # load params", "options = yaml.safe_load(options) # get empirical moments empirical_moments = _load_pickle(ppj(\"OUT_ANALYSIS\",", "get weighting matrix weighting_matrix = _load_pickle( ppj(\"OUT_ANALYSIS\", \"msm_estimation\", \"weighting_matrix_hyp.pickle\") )", "val} results.append(result) return pd.DataFrame.from_dict(results) if __name__ == \"__main__\": # load", "load params params = pd.read_csv( ppj(\"IN_MODEL_SPECS\", \"params_hyp.csv\"), sep=\";\", index_col=[\"category\", \"name\"],", "\"Choice Probabilities Restricted\": calc_restricted_choice_probabilities, \"Choice Probabilities Unrestricted\": calc_unrestricted_choice_probabilities, \"Wage Distribution", "Very Restricted\": calc_very_restricted_wage_distribution, \"Wage Distribution Restricted\": calc_restricted_wage_distribution, \"Wage Distribution Unrestricted\":", "= _load_pickle( ppj(\"OUT_ANALYSIS\", \"msm_estimation\", \"weighting_matrix_hyp.pickle\") ) calc_moments = { \"Choice", "values. The goal is to study the bivariate distribution of", "calc_moments=calc_moments, replace_nans=_replace_nans, empirical_moments=empirical_moments, weighting_matrix=weighting_matrix, ) # get bivariate distribution results", "(dict): Dictionary containing model options. grid_delta (np.array): Values of discount", "Given observed moments and weighting matrix in `OUT_ANALYSIS`, \"msm_estimation\", generate", "as options: options = yaml.safe_load(options) # get empirical moments empirical_moments", "true parameter values. \"\"\" import itertools import numpy as np", "from src.library.compute_moments import calc_unrestricted_choice_probabilities from src.library.compute_moments import calc_unrestricted_wage_distribution from src.library.compute_moments", "= crit_func(params_) result = {\"beta\": beta, \"delta\": delta, \"val\": val}", "function. Given observed moments and weighting matrix in `OUT_ANALYSIS`, \"msm_estimation\",", "{\"beta\": beta, \"delta\": delta, \"val\": val} results.append(result) return pd.DataFrame.from_dict(results) if", "options with open(ppj(\"IN_MODEL_SPECS\", \"options_hyp.yaml\")) as options: options = yaml.safe_load(options) #", "ppj from src.library.compute_moments import _replace_nans from src.library.compute_moments import calc_restricted_choice_probabilities from", "replace_nans=_replace_nans, empirical_moments=empirical_moments, weighting_matrix=weighting_matrix, ) # get bivariate distribution results results", "src.library.compute_moments import calc_unrestricted_wage_distribution from src.library.compute_moments import calc_very_restricted_choice_probabilities from src.library.compute_moments import", "\"Wage Distribution Restricted\": calc_restricted_wage_distribution, \"Wage Distribution Unrestricted\": calc_unrestricted_wage_distribution, } with", "weighted_sum_squared_errors = rp.get_moment_errors_func( params=params, options=options, calc_moments=calc_moments, replace_nans=_replace_nans, empirical_moments=empirical_moments, weighting_matrix=weighting_matrix, )", "src.library.compute_moments import calc_unrestricted_choice_probabilities from src.library.compute_moments import calc_unrestricted_wage_distribution from src.library.compute_moments import", "= [] for beta, delta in tqdm(itertools.product(grid_beta, grid_delta)): params_ =", "pd.DataFrame.from_dict(results) if __name__ == \"__main__\": # load params params =", "crit_func, grid_delta, grid_beta): \"\"\"Compute value of criterion function. Args: params", "val = crit_func(params_) result = {\"beta\": beta, \"delta\": delta, \"val\":", "and present bias values. The goal is to study the", "preference parameters around the combination of true parameter values. \"\"\"", "Method of Simulated Moments criterion function for combinations of discount", "= _load_pickle(ppj(\"OUT_ANALYSIS\", \"msm_estimation\", \"moments_hyp.pickle\")) # get weighting matrix weighting_matrix =", "Method of Simulated Moments criterion function. Given observed moments and", "project_paths_join as ppj from src.library.compute_moments import _replace_nans from src.library.compute_moments import", "Probabilities Very Restricted\": calc_very_restricted_choice_probabilities, \"Choice Probabilities Restricted\": calc_restricted_choice_probabilities, \"Choice Probabilities", "bld.project_paths import project_paths_join as ppj from src.library.compute_moments import _replace_nans from", "The goal is to study the bivariate distribution of the", "= pd.read_csv( ppj(\"IN_MODEL_SPECS\", \"params_hyp.csv\"), sep=\";\", index_col=[\"category\", \"name\"], ) params[\"value\"] =", "\"\"\"Compute value of criterion function. Args: params (pd.DataFrame): DataFrame containing", "options=options, calc_moments=calc_moments, replace_nans=_replace_nans, empirical_moments=empirical_moments, weighting_matrix=weighting_matrix, ) # get bivariate distribution", "tqdm import tqdm def get_bivariate_distribution(params, crit_func, grid_delta, grid_beta): \"\"\"Compute value", "calc_unrestricted_wage_distribution, } with _temporary_working_directory(snippet=\"heatmap\"): # get criterion function weighted_sum_squared_errors =", "} with _temporary_working_directory(snippet=\"heatmap\"): # get criterion function weighted_sum_squared_errors = rp.get_moment_errors_func(", "\"beta\"), \"value\"] = beta params_.loc[(\"delta\", \"delta\"), \"value\"] = delta val", "bias values. The goal is to study the bivariate distribution", "\"\"\" import itertools import numpy as np import pandas as", "src.library.compute_moments import calc_restricted_choice_probabilities from src.library.compute_moments import calc_restricted_wage_distribution from src.library.compute_moments import", "function weighted_sum_squared_errors = rp.get_moment_errors_func( params=params, options=options, calc_moments=calc_moments, replace_nans=_replace_nans, empirical_moments=empirical_moments, weighting_matrix=weighting_matrix,", "as pd import respy as rp import yaml from bld.project_paths", "\"delta\": delta, \"val\": val} results.append(result) return pd.DataFrame.from_dict(results) if __name__ ==", "the bivariate distribution of the time preference parameters around the", "\"weighting_matrix_hyp.pickle\") ) calc_moments = { \"Choice Probabilities Very Restricted\": calc_very_restricted_choice_probabilities,", "import calc_very_restricted_wage_distribution from src.library.housekeeping import _load_pickle from src.library.housekeeping import _temporary_working_directory", "empirical moments empirical_moments = _load_pickle(ppj(\"OUT_ANALYSIS\", \"msm_estimation\", \"moments_hyp.pickle\")) # get weighting", "\"msm_estimation\", \"moments_hyp.pickle\")) # get weighting matrix weighting_matrix = _load_pickle( ppj(\"OUT_ANALYSIS\",", "import respy as rp import yaml from bld.project_paths import project_paths_join", ") # get bivariate distribution results results = get_bivariate_distribution( crit_func=weighted_sum_squared_errors,", "params_.loc[(\"delta\", \"delta\"), \"value\"] = delta val = crit_func(params_) result =", "calc_very_restricted_choice_probabilities from src.library.compute_moments import calc_very_restricted_wage_distribution from src.library.housekeeping import _load_pickle from", "results = get_bivariate_distribution( crit_func=weighted_sum_squared_errors, params=params, grid_delta=np.arange(0.945, 0.9625, 0.0025), grid_beta=np.arange(0.75, 1.05,", "of discount factor and present bias values. The goal is", "import calc_unrestricted_wage_distribution from src.library.compute_moments import calc_very_restricted_choice_probabilities from src.library.compute_moments import calc_very_restricted_wage_distribution", "import _temporary_working_directory from tqdm import tqdm def get_bivariate_distribution(params, crit_func, grid_delta,", "\"value\"] = beta params_.loc[(\"delta\", \"delta\"), \"value\"] = delta val =", "options: options = yaml.safe_load(options) # get empirical moments empirical_moments =", "calc_restricted_choice_probabilities, \"Choice Probabilities Unrestricted\": calc_unrestricted_choice_probabilities, \"Wage Distribution Very Restricted\": calc_very_restricted_wage_distribution,", "import _replace_nans from src.library.compute_moments import calc_restricted_choice_probabilities from src.library.compute_moments import calc_restricted_wage_distribution", "Probabilities Unrestricted\": calc_unrestricted_choice_probabilities, \"Wage Distribution Very Restricted\": calc_very_restricted_wage_distribution, \"Wage Distribution", "present bias values. The goal is to study the bivariate", "parameters. crit_func (dict): Dictionary containing model options. grid_delta (np.array): Values", "= yaml.safe_load(options) # get empirical moments empirical_moments = _load_pickle(ppj(\"OUT_ANALYSIS\", \"msm_estimation\",", "# get criterion function weighted_sum_squared_errors = rp.get_moment_errors_func( params=params, options=options, calc_moments=calc_moments,", "\"Wage Distribution Very Restricted\": calc_very_restricted_wage_distribution, \"Wage Distribution Restricted\": calc_restricted_wage_distribution, \"Wage", "empirical_moments=empirical_moments, weighting_matrix=weighting_matrix, ) # get bivariate distribution results results =", "delta val = crit_func(params_) result = {\"beta\": beta, \"delta\": delta,", "# get bivariate distribution results results = get_bivariate_distribution( crit_func=weighted_sum_squared_errors, params=params,", "Distribution Unrestricted\": calc_unrestricted_wage_distribution, } with _temporary_working_directory(snippet=\"heatmap\"): # get criterion function", "calc_unrestricted_wage_distribution from src.library.compute_moments import calc_very_restricted_choice_probabilities from src.library.compute_moments import calc_very_restricted_wage_distribution from", "yaml from bld.project_paths import project_paths_join as ppj from src.library.compute_moments import", "_load_pickle(ppj(\"OUT_ANALYSIS\", \"msm_estimation\", \"moments_hyp.pickle\")) # get weighting matrix weighting_matrix = _load_pickle(", "Values of discount factor. grid_beta (np.array): Values of present-bias parameter.", "[] for beta, delta in tqdm(itertools.product(grid_beta, grid_delta)): params_ = params.copy()", "{ \"Choice Probabilities Very Restricted\": calc_very_restricted_choice_probabilities, \"Choice Probabilities Restricted\": calc_restricted_choice_probabilities,", "results = [] for beta, delta in tqdm(itertools.product(grid_beta, grid_delta)): params_", "of Simulated Moments criterion function. Given observed moments and weighting", "calc_moments = { \"Choice Probabilities Very Restricted\": calc_very_restricted_choice_probabilities, \"Choice Probabilities", "containing model options. grid_delta (np.array): Values of discount factor. grid_beta", "result = {\"beta\": beta, \"delta\": delta, \"val\": val} results.append(result) return", "discount factor. grid_beta (np.array): Values of present-bias parameter. Returns: pd.DataFrame", "(np.array): Values of present-bias parameter. Returns: pd.DataFrame \"\"\" results =", "import calc_very_restricted_choice_probabilities from src.library.compute_moments import calc_very_restricted_wage_distribution from src.library.housekeeping import _load_pickle", "Very Restricted\": calc_very_restricted_choice_probabilities, \"Choice Probabilities Restricted\": calc_restricted_choice_probabilities, \"Choice Probabilities Unrestricted\":", "grid_beta (np.array): Values of present-bias parameter. Returns: pd.DataFrame \"\"\" results", "in tqdm(itertools.product(grid_beta, grid_delta)): params_ = params.copy() params_.loc[(\"beta\", \"beta\"), \"value\"] =", "moments empirical_moments = _load_pickle(ppj(\"OUT_ANALYSIS\", \"msm_estimation\", \"moments_hyp.pickle\")) # get weighting matrix", "Unrestricted\": calc_unrestricted_wage_distribution, } with _temporary_working_directory(snippet=\"heatmap\"): # get criterion function weighted_sum_squared_errors", "_temporary_working_directory from tqdm import tqdm def get_bivariate_distribution(params, crit_func, grid_delta, grid_beta):", "factor and present bias values. The goal is to study", "src.library.compute_moments import calc_very_restricted_choice_probabilities from src.library.compute_moments import calc_very_restricted_wage_distribution from src.library.housekeeping import", "tqdm def get_bivariate_distribution(params, crit_func, grid_delta, grid_beta): \"\"\"Compute value of criterion", "to study the bivariate distribution of the time preference parameters", "src.library.housekeeping import _load_pickle from src.library.housekeeping import _temporary_working_directory from tqdm import", "options. grid_delta (np.array): Values of discount factor. grid_beta (np.array): Values", "value of criterion function. Args: params (pd.DataFrame): DataFrame containing model", "calc_very_restricted_wage_distribution, \"Wage Distribution Restricted\": calc_restricted_wage_distribution, \"Wage Distribution Unrestricted\": calc_unrestricted_wage_distribution, }", "Distribution Restricted\": calc_restricted_wage_distribution, \"Wage Distribution Unrestricted\": calc_unrestricted_wage_distribution, } with _temporary_working_directory(snippet=\"heatmap\"):", "is to study the bivariate distribution of the time preference", "of Method of Simulated Moments criterion function for combinations of", "of discount factor. grid_beta (np.array): Values of present-bias parameter. Returns:", "\"msm_estimation\", \"weighting_matrix_hyp.pickle\") ) calc_moments = { \"Choice Probabilities Very Restricted\":", "crit_func=weighted_sum_squared_errors, params=params, grid_delta=np.arange(0.945, 0.9625, 0.0025), grid_beta=np.arange(0.75, 1.05, 0.01), ) results.to_csv(ppj(\"OUT_ANALYSIS\",", "Moments criterion function for combinations of discount factor and present", "as ppj from src.library.compute_moments import _replace_nans from src.library.compute_moments import calc_restricted_choice_probabilities", "= params.copy() params_.loc[(\"beta\", \"beta\"), \"value\"] = beta params_.loc[(\"delta\", \"delta\"), \"value\"]", "get criterion function weighted_sum_squared_errors = rp.get_moment_errors_func( params=params, options=options, calc_moments=calc_moments, replace_nans=_replace_nans,", "calc_unrestricted_choice_probabilities, \"Wage Distribution Very Restricted\": calc_very_restricted_wage_distribution, \"Wage Distribution Restricted\": calc_restricted_wage_distribution,", "get_bivariate_distribution( crit_func=weighted_sum_squared_errors, params=params, grid_delta=np.arange(0.945, 0.9625, 0.0025), grid_beta=np.arange(0.75, 1.05, 0.01), )", "import itertools import numpy as np import pandas as pd", "get bivariate distribution results results = get_bivariate_distribution( crit_func=weighted_sum_squared_errors, params=params, grid_delta=np.arange(0.945,", "in `OUT_ANALYSIS`, \"msm_estimation\", generate values of Method of Simulated Moments", "delta, \"val\": val} results.append(result) return pd.DataFrame.from_dict(results) if __name__ == \"__main__\":", "params_.loc[(\"beta\", \"beta\"), \"value\"] = beta params_.loc[(\"delta\", \"delta\"), \"value\"] = delta", "\"delta\"), \"value\"] = delta val = crit_func(params_) result = {\"beta\":", "from src.library.housekeeping import _load_pickle from src.library.housekeeping import _temporary_working_directory from tqdm", "\"val\": val} results.append(result) return pd.DataFrame.from_dict(results) if __name__ == \"__main__\": #", "\"Choice Probabilities Very Restricted\": calc_very_restricted_choice_probabilities, \"Choice Probabilities Restricted\": calc_restricted_choice_probabilities, \"Choice", "calc_very_restricted_choice_probabilities, \"Choice Probabilities Restricted\": calc_restricted_choice_probabilities, \"Choice Probabilities Unrestricted\": calc_unrestricted_choice_probabilities, \"Wage", "results results = get_bivariate_distribution( crit_func=weighted_sum_squared_errors, params=params, grid_delta=np.arange(0.945, 0.9625, 0.0025), grid_beta=np.arange(0.75,", "function for combinations of discount factor and present bias values.", "Dictionary containing model options. grid_delta (np.array): Values of discount factor.", "_temporary_working_directory(snippet=\"heatmap\"): # get criterion function weighted_sum_squared_errors = rp.get_moment_errors_func( params=params, options=options,", "from src.library.compute_moments import calc_restricted_choice_probabilities from src.library.compute_moments import calc_restricted_wage_distribution from src.library.compute_moments", "combinations of discount factor and present bias values. The goal", "import project_paths_join as ppj from src.library.compute_moments import _replace_nans from src.library.compute_moments", "get_bivariate_distribution(params, crit_func, grid_delta, grid_beta): \"\"\"Compute value of criterion function. Args:", "function. Args: params (pd.DataFrame): DataFrame containing model parameters. crit_func (dict):", "calc_restricted_wage_distribution, \"Wage Distribution Unrestricted\": calc_unrestricted_wage_distribution, } with _temporary_working_directory(snippet=\"heatmap\"): # get", "rp import yaml from bld.project_paths import project_paths_join as ppj from", "import calc_unrestricted_choice_probabilities from src.library.compute_moments import calc_unrestricted_wage_distribution from src.library.compute_moments import calc_very_restricted_choice_probabilities", "from src.library.compute_moments import calc_very_restricted_wage_distribution from src.library.housekeeping import _load_pickle from src.library.housekeeping", "beta, \"delta\": delta, \"val\": val} results.append(result) return pd.DataFrame.from_dict(results) if __name__", "_replace_nans from src.library.compute_moments import calc_restricted_choice_probabilities from src.library.compute_moments import calc_restricted_wage_distribution from", "criterion function. Args: params (pd.DataFrame): DataFrame containing model parameters. crit_func", "\"\"\"Generate values of Method of Simulated Moments criterion function. Given", "def get_bivariate_distribution(params, crit_func, grid_delta, grid_beta): \"\"\"Compute value of criterion function.", "pd.DataFrame \"\"\" results = [] for beta, delta in tqdm(itertools.product(grid_beta,", "# get empirical moments empirical_moments = _load_pickle(ppj(\"OUT_ANALYSIS\", \"msm_estimation\", \"moments_hyp.pickle\")) #", "_load_pickle( ppj(\"OUT_ANALYSIS\", \"msm_estimation\", \"weighting_matrix_hyp.pickle\") ) calc_moments = { \"Choice Probabilities", "bivariate distribution results results = get_bivariate_distribution( crit_func=weighted_sum_squared_errors, params=params, grid_delta=np.arange(0.945, 0.9625,", "generate values of Method of Simulated Moments criterion function for", "import _load_pickle from src.library.housekeeping import _temporary_working_directory from tqdm import tqdm", "grid_beta): \"\"\"Compute value of criterion function. Args: params (pd.DataFrame): DataFrame", "grid_delta (np.array): Values of discount factor. grid_beta (np.array): Values of", "observed moments and weighting matrix in `OUT_ANALYSIS`, \"msm_estimation\", generate values", "of present-bias parameter. Returns: pd.DataFrame \"\"\" results = [] for", "import calc_restricted_wage_distribution from src.library.compute_moments import calc_unrestricted_choice_probabilities from src.library.compute_moments import calc_unrestricted_wage_distribution", "index_col=[\"category\", \"name\"], ) params[\"value\"] = params[\"value\"].astype(float) # load options with", "combination of true parameter values. \"\"\" import itertools import numpy", "Values of present-bias parameter. Returns: pd.DataFrame \"\"\" results = []", "ppj(\"IN_MODEL_SPECS\", \"params_hyp.csv\"), sep=\";\", index_col=[\"category\", \"name\"], ) params[\"value\"] = params[\"value\"].astype(float) #", "with open(ppj(\"IN_MODEL_SPECS\", \"options_hyp.yaml\")) as options: options = yaml.safe_load(options) # get", "# load options with open(ppj(\"IN_MODEL_SPECS\", \"options_hyp.yaml\")) as options: options =", "pandas as pd import respy as rp import yaml from", "criterion function for combinations of discount factor and present bias", "present-bias parameter. Returns: pd.DataFrame \"\"\" results = [] for beta,", "__name__ == \"__main__\": # load params params = pd.read_csv( ppj(\"IN_MODEL_SPECS\",", "bivariate distribution of the time preference parameters around the combination", "pd import respy as rp import yaml from bld.project_paths import", "values of Method of Simulated Moments criterion function. Given observed", "<filename>lectures/extensions/hyperbolic_discounting/replication_code/src/analysis/get_bivariate_distr_data.py \"\"\"Generate values of Method of Simulated Moments criterion function.", "of the time preference parameters around the combination of true", "beta params_.loc[(\"delta\", \"delta\"), \"value\"] = delta val = crit_func(params_) result", "# load params params = pd.read_csv( ppj(\"IN_MODEL_SPECS\", \"params_hyp.csv\"), sep=\";\", index_col=[\"category\",", "import tqdm def get_bivariate_distribution(params, crit_func, grid_delta, grid_beta): \"\"\"Compute value of", "from tqdm import tqdm def get_bivariate_distribution(params, crit_func, grid_delta, grid_beta): \"\"\"Compute", "goal is to study the bivariate distribution of the time", "calc_restricted_choice_probabilities from src.library.compute_moments import calc_restricted_wage_distribution from src.library.compute_moments import calc_unrestricted_choice_probabilities from", "from src.library.housekeeping import _temporary_working_directory from tqdm import tqdm def get_bivariate_distribution(params,", "Restricted\": calc_restricted_wage_distribution, \"Wage Distribution Unrestricted\": calc_unrestricted_wage_distribution, } with _temporary_working_directory(snippet=\"heatmap\"): #", "src.library.compute_moments import _replace_nans from src.library.compute_moments import calc_restricted_choice_probabilities from src.library.compute_moments import", "_load_pickle from src.library.housekeeping import _temporary_working_directory from tqdm import tqdm def", "Restricted\": calc_very_restricted_choice_probabilities, \"Choice Probabilities Restricted\": calc_restricted_choice_probabilities, \"Choice Probabilities Unrestricted\": calc_unrestricted_choice_probabilities,", "values. \"\"\" import itertools import numpy as np import pandas", "Moments criterion function. Given observed moments and weighting matrix in", "delta in tqdm(itertools.product(grid_beta, grid_delta)): params_ = params.copy() params_.loc[(\"beta\", \"beta\"), \"value\"]", "containing model parameters. crit_func (dict): Dictionary containing model options. grid_delta", "the time preference parameters around the combination of true parameter", "of criterion function. Args: params (pd.DataFrame): DataFrame containing model parameters.", "from src.library.compute_moments import _replace_nans from src.library.compute_moments import calc_restricted_choice_probabilities from src.library.compute_moments", "Probabilities Restricted\": calc_restricted_choice_probabilities, \"Choice Probabilities Unrestricted\": calc_unrestricted_choice_probabilities, \"Wage Distribution Very", "weighting_matrix = _load_pickle( ppj(\"OUT_ANALYSIS\", \"msm_estimation\", \"weighting_matrix_hyp.pickle\") ) calc_moments = {", "params=params, grid_delta=np.arange(0.945, 0.9625, 0.0025), grid_beta=np.arange(0.75, 1.05, 0.01), ) results.to_csv(ppj(\"OUT_ANALYSIS\", \"heatmap.csv\"))", "numpy as np import pandas as pd import respy as", "time preference parameters around the combination of true parameter values.", "DataFrame containing model parameters. crit_func (dict): Dictionary containing model options.", "values of Method of Simulated Moments criterion function for combinations", "Returns: pd.DataFrame \"\"\" results = [] for beta, delta in", "tqdm(itertools.product(grid_beta, grid_delta)): params_ = params.copy() params_.loc[(\"beta\", \"beta\"), \"value\"] = beta", "criterion function. Given observed moments and weighting matrix in `OUT_ANALYSIS`,", "with _temporary_working_directory(snippet=\"heatmap\"): # get criterion function weighted_sum_squared_errors = rp.get_moment_errors_func( params=params,", "\"__main__\": # load params params = pd.read_csv( ppj(\"IN_MODEL_SPECS\", \"params_hyp.csv\"), sep=\";\",", "# get weighting matrix weighting_matrix = _load_pickle( ppj(\"OUT_ANALYSIS\", \"msm_estimation\", \"weighting_matrix_hyp.pickle\")", "src.library.housekeeping import _temporary_working_directory from tqdm import tqdm def get_bivariate_distribution(params, crit_func,", "discount factor and present bias values. The goal is to", "\"options_hyp.yaml\")) as options: options = yaml.safe_load(options) # get empirical moments", "factor. grid_beta (np.array): Values of present-bias parameter. Returns: pd.DataFrame \"\"\"", "params=params, options=options, calc_moments=calc_moments, replace_nans=_replace_nans, empirical_moments=empirical_moments, weighting_matrix=weighting_matrix, ) # get bivariate", "params params = pd.read_csv( ppj(\"IN_MODEL_SPECS\", \"params_hyp.csv\"), sep=\";\", index_col=[\"category\", \"name\"], )", "\"\"\" results = [] for beta, delta in tqdm(itertools.product(grid_beta, grid_delta)):", "Simulated Moments criterion function. Given observed moments and weighting matrix", "params = pd.read_csv( ppj(\"IN_MODEL_SPECS\", \"params_hyp.csv\"), sep=\";\", index_col=[\"category\", \"name\"], ) params[\"value\"]", "\"params_hyp.csv\"), sep=\";\", index_col=[\"category\", \"name\"], ) params[\"value\"] = params[\"value\"].astype(float) # load", "itertools import numpy as np import pandas as pd import", "Distribution Very Restricted\": calc_very_restricted_wage_distribution, \"Wage Distribution Restricted\": calc_restricted_wage_distribution, \"Wage Distribution", "respy as rp import yaml from bld.project_paths import project_paths_join as", "= { \"Choice Probabilities Very Restricted\": calc_very_restricted_choice_probabilities, \"Choice Probabilities Restricted\":", "ppj(\"OUT_ANALYSIS\", \"msm_estimation\", \"weighting_matrix_hyp.pickle\") ) calc_moments = { \"Choice Probabilities Very", "of Method of Simulated Moments criterion function. Given observed moments", "import calc_restricted_choice_probabilities from src.library.compute_moments import calc_restricted_wage_distribution from src.library.compute_moments import calc_unrestricted_choice_probabilities", "distribution of the time preference parameters around the combination of", "= get_bivariate_distribution( crit_func=weighted_sum_squared_errors, params=params, grid_delta=np.arange(0.945, 0.9625, 0.0025), grid_beta=np.arange(0.75, 1.05, 0.01),", "for combinations of discount factor and present bias values. The", "Args: params (pd.DataFrame): DataFrame containing model parameters. crit_func (dict): Dictionary", "model options. grid_delta (np.array): Values of discount factor. grid_beta (np.array):", "from src.library.compute_moments import calc_unrestricted_wage_distribution from src.library.compute_moments import calc_very_restricted_choice_probabilities from src.library.compute_moments", "parameters around the combination of true parameter values. \"\"\" import", "\"name\"], ) params[\"value\"] = params[\"value\"].astype(float) # load options with open(ppj(\"IN_MODEL_SPECS\",", "params[\"value\"] = params[\"value\"].astype(float) # load options with open(ppj(\"IN_MODEL_SPECS\", \"options_hyp.yaml\")) as", "import yaml from bld.project_paths import project_paths_join as ppj from src.library.compute_moments", "empirical_moments = _load_pickle(ppj(\"OUT_ANALYSIS\", \"msm_estimation\", \"moments_hyp.pickle\")) # get weighting matrix weighting_matrix", "of Simulated Moments criterion function for combinations of discount factor", "criterion function weighted_sum_squared_errors = rp.get_moment_errors_func( params=params, options=options, calc_moments=calc_moments, replace_nans=_replace_nans, empirical_moments=empirical_moments,", "\"moments_hyp.pickle\")) # get weighting matrix weighting_matrix = _load_pickle( ppj(\"OUT_ANALYSIS\", \"msm_estimation\",", "of true parameter values. \"\"\" import itertools import numpy as", "(pd.DataFrame): DataFrame containing model parameters. crit_func (dict): Dictionary containing model", "from src.library.compute_moments import calc_very_restricted_choice_probabilities from src.library.compute_moments import calc_very_restricted_wage_distribution from src.library.housekeeping", "parameter values. \"\"\" import itertools import numpy as np import", "as np import pandas as pd import respy as rp", "(np.array): Values of discount factor. grid_beta (np.array): Values of present-bias", "parameter. Returns: pd.DataFrame \"\"\" results = [] for beta, delta", "= {\"beta\": beta, \"delta\": delta, \"val\": val} results.append(result) return pd.DataFrame.from_dict(results)", "moments and weighting matrix in `OUT_ANALYSIS`, \"msm_estimation\", generate values of", "== \"__main__\": # load params params = pd.read_csv( ppj(\"IN_MODEL_SPECS\", \"params_hyp.csv\"),", "sep=\";\", index_col=[\"category\", \"name\"], ) params[\"value\"] = params[\"value\"].astype(float) # load options", "load options with open(ppj(\"IN_MODEL_SPECS\", \"options_hyp.yaml\")) as options: options = yaml.safe_load(options)", "params_ = params.copy() params_.loc[(\"beta\", \"beta\"), \"value\"] = beta params_.loc[(\"delta\", \"delta\"),", ") calc_moments = { \"Choice Probabilities Very Restricted\": calc_very_restricted_choice_probabilities, \"Choice" ]
[ "space_game.domain_names import KeyId from space_game.events.Event import Event @dataclass class KeyPressedEvent(Event):", "import dataclass from space_game.domain_names import KeyId from space_game.events.Event import Event", "from dataclasses import dataclass from space_game.domain_names import KeyId from space_game.events.Event", "import KeyId from space_game.events.Event import Event @dataclass class KeyPressedEvent(Event): key_id:", "from space_game.domain_names import KeyId from space_game.events.Event import Event @dataclass class", "dataclasses import dataclass from space_game.domain_names import KeyId from space_game.events.Event import", "dataclass from space_game.domain_names import KeyId from space_game.events.Event import Event @dataclass", "KeyId from space_game.events.Event import Event @dataclass class KeyPressedEvent(Event): key_id: KeyId" ]
[ "\"User: \" + message.get(\"user\") + \" Message: \" + message.get(\"body\")", "\" + message.get(\"user\") + \" Message: \" + message.get(\"body\") try:", "message.get(\"subject\") final_message = \"User: \" + message.get(\"user\") + \" Message:", "message): heading = message.get(\"subject\") final_message = \"User: \" + message.get(\"user\")", "self.webhook = config['webhook'] def send(self, message): heading = message.get(\"subject\") final_message", "oncall.constants import TEAMS_SUPPORT class teams_messenger(object): supports = frozenset([TEAMS_SUPPORT]) def __init__(self,", "def send(self, message): heading = message.get(\"subject\") final_message = \"User: \"", "= message.get(\"subject\") final_message = \"User: \" + message.get(\"user\") + \"", "\" Message: \" + message.get(\"body\") try: myTeamsMessage = pymsteams.connectorcard(self.webhook) myTeamsMessage.title(str(heading))", "myTeamsMessage.text(str(final_message)) myTeamsMessage.send() except: logging.info(\"An issue occured while sending message to", "class teams_messenger(object): supports = frozenset([TEAMS_SUPPORT]) def __init__(self, config): self.webhook =", "supports = frozenset([TEAMS_SUPPORT]) def __init__(self, config): self.webhook = config['webhook'] def", "final_message = \"User: \" + message.get(\"user\") + \" Message: \"", "send(self, message): heading = message.get(\"subject\") final_message = \"User: \" +", "myTeamsMessage.send() except: logging.info(\"An issue occured while sending message to teams", "config): self.webhook = config['webhook'] def send(self, message): heading = message.get(\"subject\")", "= \"User: \" + message.get(\"user\") + \" Message: \" +", "try: myTeamsMessage = pymsteams.connectorcard(self.webhook) myTeamsMessage.title(str(heading)) myTeamsMessage.text(str(final_message)) myTeamsMessage.send() except: logging.info(\"An issue", "pymsteams import logging from oncall.constants import TEAMS_SUPPORT class teams_messenger(object): supports", "<gh_stars>100-1000 import pymsteams import logging from oncall.constants import TEAMS_SUPPORT class", "def __init__(self, config): self.webhook = config['webhook'] def send(self, message): heading", "= config['webhook'] def send(self, message): heading = message.get(\"subject\") final_message =", "+ \" Message: \" + message.get(\"body\") try: myTeamsMessage = pymsteams.connectorcard(self.webhook)", "Message: \" + message.get(\"body\") try: myTeamsMessage = pymsteams.connectorcard(self.webhook) myTeamsMessage.title(str(heading)) myTeamsMessage.text(str(final_message))", "TEAMS_SUPPORT class teams_messenger(object): supports = frozenset([TEAMS_SUPPORT]) def __init__(self, config): self.webhook", "+ message.get(\"user\") + \" Message: \" + message.get(\"body\") try: myTeamsMessage", "\" + message.get(\"body\") try: myTeamsMessage = pymsteams.connectorcard(self.webhook) myTeamsMessage.title(str(heading)) myTeamsMessage.text(str(final_message)) myTeamsMessage.send()", "myTeamsMessage = pymsteams.connectorcard(self.webhook) myTeamsMessage.title(str(heading)) myTeamsMessage.text(str(final_message)) myTeamsMessage.send() except: logging.info(\"An issue occured", "message.get(\"user\") + \" Message: \" + message.get(\"body\") try: myTeamsMessage =", "import pymsteams import logging from oncall.constants import TEAMS_SUPPORT class teams_messenger(object):", "pymsteams.connectorcard(self.webhook) myTeamsMessage.title(str(heading)) myTeamsMessage.text(str(final_message)) myTeamsMessage.send() except: logging.info(\"An issue occured while sending", "teams_messenger(object): supports = frozenset([TEAMS_SUPPORT]) def __init__(self, config): self.webhook = config['webhook']", "frozenset([TEAMS_SUPPORT]) def __init__(self, config): self.webhook = config['webhook'] def send(self, message):", "= frozenset([TEAMS_SUPPORT]) def __init__(self, config): self.webhook = config['webhook'] def send(self,", "heading = message.get(\"subject\") final_message = \"User: \" + message.get(\"user\") +", "from oncall.constants import TEAMS_SUPPORT class teams_messenger(object): supports = frozenset([TEAMS_SUPPORT]) def", "+ message.get(\"body\") try: myTeamsMessage = pymsteams.connectorcard(self.webhook) myTeamsMessage.title(str(heading)) myTeamsMessage.text(str(final_message)) myTeamsMessage.send() except:", "except: logging.info(\"An issue occured while sending message to teams messenger\")", "import TEAMS_SUPPORT class teams_messenger(object): supports = frozenset([TEAMS_SUPPORT]) def __init__(self, config):", "config['webhook'] def send(self, message): heading = message.get(\"subject\") final_message = \"User:", "= pymsteams.connectorcard(self.webhook) myTeamsMessage.title(str(heading)) myTeamsMessage.text(str(final_message)) myTeamsMessage.send() except: logging.info(\"An issue occured while", "import logging from oncall.constants import TEAMS_SUPPORT class teams_messenger(object): supports =", "logging from oncall.constants import TEAMS_SUPPORT class teams_messenger(object): supports = frozenset([TEAMS_SUPPORT])", "myTeamsMessage.title(str(heading)) myTeamsMessage.text(str(final_message)) myTeamsMessage.send() except: logging.info(\"An issue occured while sending message", "message.get(\"body\") try: myTeamsMessage = pymsteams.connectorcard(self.webhook) myTeamsMessage.title(str(heading)) myTeamsMessage.text(str(final_message)) myTeamsMessage.send() except: logging.info(\"An", "__init__(self, config): self.webhook = config['webhook'] def send(self, message): heading =" ]
[ "the Prophet model. e.g. hp.uniform(0.8, 0.95). :param metric: String. The", "model after HPO. :param data: evaluation data, a pandas dataframe", "seasonality_prior_scale, \"holidays_prior_scale\": hp.loguniform(0.01, 10) if holidays_prior_scale is None else holidays_prior_scale,", "changepoint_prior_scale=None, seasonality_prior_scale=None, holidays_prior_scale=None, seasonality_mode=None, changepoint_range=None, metric='mse', logs_dir=\"/tmp/auto_prophet_logs\", cpus_per_trial=1, name=\"auto_prophet\", remote_dir=None,", "2.0 (the \"License\"); # you may not use this file", "of trials and round up n_sampling according to hp.grid_search. If", "a json file \"\"\" if self.best_model.model is None: raise RuntimeError(", "a stopping condition is met. :param search_alg: str, all supported", "checkpoints. It defaults to None and doesn't take effects while", "from bigdl.orca.automl.auto_estimator import AutoEstimator import bigdl.orca.automl.hp as hp self.search_space =", "model. e.g. hp.choice(['additive', 'multiplicative']). :param changepoint_range: hyperparameter changepoint_range for the", "recalculate_n_sampling # - class AutoProphet: def __init__(self, changepoint_prior_scale=None, seasonality_prior_scale=None, holidays_prior_scale=None,", "doesn't take effects while running in local. While running in", "is None else changepoint_prior_scale, \"seasonality_prior_scale\": hp.grid_search([0.01, 0.1, 1.0, 10.0]) if", "strings here: https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#timeseries-offset-aliases :param ds_data: a dataframe that has 1", "is None: assert len(data) >= 2, \"The training dataframe should", "tune (i.e.\"variant_generator\", \"random\", \"ax\", \"dragonfly\", \"skopt\", \"hyperopt\", \"bayesopt\", \"bohb\", \"nevergrad\",", "HPO. :param data: evaluation data, a pandas dataframe with Td", "test/valid data. \"\"\" if data is None: raise ValueError(\"Input invalid", "import warnings from bigdl.chronos.model.prophet import ProphetBuilder, ProphetModel from bigdl.chronos.autots.utils import", "logs_dir=\"/tmp/auto_prophet_logs\", cpus_per_trial=1, name=\"auto_prophet\", remote_dir=None, load_dir=None, **prophet_config ): \"\"\" Create an", "before calling predict!\") return self.best_model.predict(horizon=horizon, freq=freq, ds_data=ds_data) def evaluate(self, data,", "for the Prophet model. For hp sampling, see bigdl.chronos.orca.automl.hp for", "is the horizon you may need to use once the", "whole data self.best_model = ProphetBuilder().build(self.auto_est.get_best_config()) self.best_model.model.fit(data) def predict(self, horizon=1, freq=\"D\",", "to \"hdfs:///tmp/{name}\". :param load_dir: Load the ckpt from load_dir. The", "dimension :param metrics: A list contains metrics for test/valid data.", ":param name: name of the AutoProphet. It defaults to \"auto_prophet\"", ") # use the best config to fit a new", "scheduler: str, all supported scheduler provided by ray tune :param", "is the time dimension :param cross_validation: bool, if the eval", "} self.search_space.update(prophet_config) # update other configs self.metric = metric model_builder", "seasonality_prior_scale is None else seasonality_prior_scale, \"holidays_prior_scale\": hp.loguniform(0.01, 10) if holidays_prior_scale", "assert pd.api.types.is_datetime64_any_dtype(data[\"ds\"].dtypes), \\ \"The 'ds' col should be in datetime", "freq=None, metric_threshold=None, n_sampling=16, search_alg=None, search_alg_params=None, scheduler=None, scheduler_params=None, ): \"\"\" Automatically", "defaults to \"auto_prophet\" :param remote_dir: String. Remote directory to sync", "\"bohb\", \"nevergrad\", \"optuna\", \"zoopt\" and \"sigopt\") :param search_alg_params: extra parameters", "specify either the exact value or the search space of", "bigdl.chronos.autots.utils import recalculate_n_sampling # - class AutoProphet: def __init__(self, changepoint_prior_scale=None,", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "be automatically splited from training data, and expect_horizon is the", "will be taken as the validation data. :param freq: the", "model after HPO. :param horizon: the number of steps forward", "64 type, or you need to set `freq` in fit.\"", "n_sampling != -1 else -1 self.auto_est.fit(data=train_data, validation_data=validation_data, metric=self.metric, metric_threshold=metric_threshold, n_sampling=n_sampling,", "dataframe, defaulted to day(\"D\"), the frequency can be anything from", "checkpoint_file): \"\"\" Restore the best model after HPO. :param checkpoint_file:", "get_best_model(self): \"\"\" Get the best Prophet model. \"\"\" return self.best_model.model", "2 columns, with column 'ds' indicating date and column 'y'", "scheduler \"\"\" if expect_horizon is None: expect_horizon = int(0.1*len(data)) if", "RuntimeError( \"You must call fit or restore first before calling", "an integer space for hyperparameter changepoint_prior_scale for the Prophet model.", "until a stopping condition is met. :param search_alg: str, all", "the pandas list of frequency strings here: https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#timeseries-offset-aliasesDefaulted to None,", "condition is met. :param search_alg: str, all supported searcher provided", "of None\") if self.best_model.model is None: raise RuntimeError( \"You must", ":param cpus_per_trial: Int. Number of cpus for each trial. It", "seasonality_prior_scale: hyperparameter seasonality_prior_scale for the Prophet model. e.g. hp.loguniform(0.01, 10).", ":param prophet_config: Other Prophet hyperparameters. \"\"\" if load_dir: self.best_model =", "to None. :param prophet_config: Other Prophet hyperparameters. \"\"\" if load_dir:", "optimize. e.g. \"mse\" :param logs_dir: Local directory to save logs", "recalculate_n_sampling(self.search_space, n_sampling) if n_sampling != -1 else -1 self.auto_est.fit(data=train_data, validation_data=validation_data,", "ProphetBuilder, ProphetModel from bigdl.chronos.autots.utils import recalculate_n_sampling # - class AutoProphet:", "where an unreliable frequency will be infer implicitly. :param metric_threshold:", "or restore first before calling evaluate!\") return self.best_model.evaluate(target=data, metrics=metrics) def", "if changepoint_prior_scale is None else changepoint_prior_scale, \"seasonality_prior_scale\": hp.grid_search([0.01, 0.1, 1.0,", "0.1, 1.0, 10.0]) if seasonality_prior_scale is None else seasonality_prior_scale, \"holidays_prior_scale\":", "infinite samples are generated until a stopping condition is met.", "best model. \"\"\" self.best_model.restore(checkpoint_file) def get_best_model(self): \"\"\" Get the best", "`bigdl-orca[automl]` to use `fit` function.\") def fit(self, data, cross_validation=True, expect_horizon=None,", "use this file except in compliance with the License. #", "can be anything from the pandas list of frequency strings", "data[:len(data)-expect_horizon] validation_data = None if cross_validation else data[len(data)-expect_horizon:] n_sampling =", "are generated until a stopping condition is met. :param search_alg:", "must call fit or restore first before calling save!\") self.best_model.save(checkpoint_file)", "hyperparameter seasonality_mode for the Prophet model. e.g. hp.choice(['additive', 'multiplicative']). :param", "to \"auto_prophet\" :param remote_dir: String. Remote directory to sync training", "use `fit` function.\") def fit(self, data, cross_validation=True, expect_horizon=None, freq=None, metric_threshold=None,", "horizon you may need to use once the mode is", "License. # import pandas as pd import warnings from bigdl.chronos.model.prophet", "the mode is fitted. The value defaults to None, where", "hyperparameters. For details of the Prophet model hyperparameters, refer to", "to save the best model, should be a json file", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "It defaults to \"/tmp/auto_prophet_logs\" :param cpus_per_trial: Int. Number of cpus", "data[\"ds\"].iloc[0] else: self._freq = pd.Timedelta(freq) expect_horizon_str = str(self._freq * expect_horizon)", "from the pandas list of frequency strings here: https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#timeseries-offset-aliasesDefaulted to", "Number of trials to evaluate in total. Defaults to 16.", "and Td is the time dimension :param metrics: A list", "License. # You may obtain a copy of the License", "horizon: the number of steps forward to predict :param freq:", "While running in cluster, it defaults to \"hdfs:///tmp/{name}\". :param load_dir:", "10% of training data will be taken as the validation", "e.g. hp.loguniform(0.01, 10). :param seasonality_mode: hyperparameter seasonality_mode for the Prophet", "None: raise RuntimeError( \"You must call fit or restore first", "the time dimension :param cross_validation: bool, if the eval result", "first before calling save!\") self.best_model.save(checkpoint_file) def restore(self, checkpoint_file): \"\"\" Restore", "under the License is distributed on an \"AS IS\" BASIS,", "License for the specific language governing permissions and # limitations", "each trial. It defaults to 1. :param name: name of", "None else changepoint_prior_scale, \"seasonality_prior_scale\": hp.grid_search([0.01, 0.1, 1.0, 10.0]) if seasonality_prior_scale", "int(0.1*len(data)) if freq is None: assert len(data) >= 2, \"The", "defaulted to day(\"D\"), the frequency can be anything from the", "Prophet model. e.g. hp.uniform(0.8, 0.95). :param metric: String. The evaluation", "\"\"\" Save the best model after HPO. :param checkpoint_file: The", "expect_horizon: int, validation data will be automatically splited from training", ":param holidays_prior_scale: hyperparameter holidays_prior_scale for the Prophet model. e.g. hp.loguniform(0.01,", "validation data will be automatically splited from training data, and", "space of the Prophet model hyperparameters. For details of the", "None else holidays_prior_scale, \"seasonality_mode\": hp.choice(['additive', 'multiplicative']) if seasonality_mode is None", "\\ \"The 'ds' col should be in datetime 64 type,", "dataframe should contains more than 2 records.\" assert pd.api.types.is_datetime64_any_dtype(data[\"ds\"].dtypes), \\", "metrics: A list contains metrics for test/valid data. \"\"\" if", "fit(self, data, cross_validation=True, expect_horizon=None, freq=None, metric_threshold=None, n_sampling=16, search_alg=None, search_alg_params=None, scheduler=None,", "return self.best_model.evaluate(target=data, metrics=metrics) def save(self, checkpoint_file): \"\"\" Save the best", "infer implicitly. :param metric_threshold: a trial will be terminated when", "value or the search space of the Prophet model hyperparameters.", "trials and round up n_sampling according to hp.grid_search. If this", "self.auto_est.fit(data=train_data, validation_data=validation_data, metric=self.metric, metric_threshold=metric_threshold, n_sampling=n_sampling, search_space=self.search_space, search_alg=search_alg, search_alg_params=search_alg_params, scheduler=scheduler, scheduler_params=scheduler_params", "this is -1, (virtually) infinite samples are generated until a", "= data[\"ds\"].iloc[1] - data[\"ds\"].iloc[0] else: self._freq = pd.Timedelta(freq) expect_horizon_str =", "using the best model after HPO. :param horizon: the number", "Prophet model hyperparameters. For details of the Prophet model hyperparameters,", "before calling evaluate!\") return self.best_model.evaluate(target=data, metrics=metrics) def save(self, checkpoint_file): \"\"\"", "Int or hp sampling function from an integer space for", "ckpt from load_dir. The value defaults to None. :param prophet_config:", "evaluation metric name to optimize. e.g. \"mse\" :param logs_dir: Local", "splited from training data, and expect_horizon is the horizon you", "supported searcher provided by ray tune (i.e.\"variant_generator\", \"random\", \"ax\", \"dragonfly\",", ":param checkpoint_file: The checkpoint file location you want to load", "the best model after HPO. :param checkpoint_file: The checkpoint file", "to set `freq` in fit.\" self._freq = data[\"ds\"].iloc[1] - data[\"ds\"].iloc[0]", "records.\" assert pd.api.types.is_datetime64_any_dtype(data[\"ds\"].dtypes), \\ \"The 'ds' col should be in", "self.best_model.model is None: raise RuntimeError( \"You must call fit or", "to evaluate in total. Defaults to 16. If hp.grid_search is", "and checkpoints. It defaults to None and doesn't take effects", "load the best model. \"\"\" self.best_model.restore(checkpoint_file) def get_best_model(self): \"\"\" Get", "cross_validation else data[:len(data)-expect_horizon] validation_data = None if cross_validation else data[len(data)-expect_horizon:]", "holidays_prior_scale is None else holidays_prior_scale, \"seasonality_mode\": hp.choice(['additive', 'multiplicative']) if seasonality_mode", "in compliance with the License. # You may obtain a", "ray tune (i.e.\"variant_generator\", \"random\", \"ax\", \"dragonfly\", \"skopt\", \"hyperopt\", \"bayesopt\", \"bohb\",", "\"\"\" Automatically fit the model and search for the best", "\"You must call fit or restore first before calling save!\")", "software # distributed under the License is distributed on an", "logs_dir=logs_dir, resources_per_trial={\"cpu\": cpus_per_trial}, remote_dir=remote_dir, name=name) except ImportError: warnings.warn(\"You need to", ":param changepoint_prior_scale: Int or hp sampling function from an integer", "if cross_validation else data[:len(data)-expect_horizon] validation_data = None if cross_validation else", "changepoint_prior_scale is None else changepoint_prior_scale, \"seasonality_prior_scale\": hp.grid_search([0.01, 0.1, 1.0, 10.0])", "met :param n_sampling: Number of trials to evaluate in total.", "scheduler_params=None, ): \"\"\" Automatically fit the model and search for", "scheduler=None, scheduler_params=None, ): \"\"\" Automatically fit the model and search", "trial. It defaults to 1. :param name: name of the", "raise RuntimeError( \"You must call fit or restore first before", "remote_dir=None, load_dir=None, **prophet_config ): \"\"\" Create an automated Prophet Model.", "\"\"\" Create an automated Prophet Model. User need to specify", "value is set to True by default. Setting this option", "https://facebook.github.io/prophet/docs/diagnostics.html#hyperparameter-tuning. :param changepoint_prior_scale: Int or hp sampling function from an", ":param expect_horizon: int, validation data will be automatically splited from", "results. It defaults to \"/tmp/auto_prophet_logs\" :param cpus_per_trial: Int. Number of", "metric and searcher mode :param scheduler: str, all supported scheduler", "new prophet model on whole data self.best_model = ProphetBuilder().build(self.auto_est.get_best_config()) self.best_model.model.fit(data)", "None else seasonality_mode, \"changepoint_range\": hp.uniform(0.8, 0.95) if changepoint_range is None", "best model after HPO. :param horizon: the number of steps", "checkpoint_file): \"\"\" Save the best model after HPO. :param checkpoint_file:", "save the best model, should be a json file \"\"\"", ":param changepoint_range: hyperparameter changepoint_range for the Prophet model. e.g. hp.uniform(0.8,", "hyperparameters. \"\"\" if load_dir: self.best_model = ProphetModel() self.best_model.restore(load_dir) try: from", "The checkpoint file location you want to load the best", "the ckpt from load_dir. The value defaults to None. :param", "changepoint_range } self.search_space.update(prophet_config) # update other configs self.metric = metric", "Other Prophet hyperparameters. \"\"\" if load_dir: self.best_model = ProphetModel() self.best_model.restore(load_dir)", "set to True by default. Setting this option to False", ":param load_dir: Load the ckpt from load_dir. The value defaults", "of the predicted dataframe, defaulted to day(\"D\"), the frequency can", "you want to load the best model. \"\"\" self.best_model.restore(checkpoint_file) def", "training data, a pandas dataframe with Td rows, and 2", "the predicted dataframe, defaulted to day(\"D\"), the frequency can be", "class AutoProphet: def __init__(self, changepoint_prior_scale=None, seasonality_prior_scale=None, holidays_prior_scale=None, seasonality_mode=None, changepoint_range=None, metric='mse',", "seasonality_mode=None, changepoint_range=None, metric='mse', logs_dir=\"/tmp/auto_prophet_logs\", cpus_per_trial=1, name=\"auto_prophet\", remote_dir=None, load_dir=None, **prophet_config ):", "sampling function from an integer space for hyperparameter changepoint_prior_scale for", "e.g. hp.loguniform(0.01, 10). :param holidays_prior_scale: hyperparameter holidays_prior_scale for the Prophet", "metrics=metrics) def save(self, checkpoint_file): \"\"\" Save the best model after", "The value defaults to None. :param prophet_config: Other Prophet hyperparameters.", "is in search_space, the grid will be run n_sampling of", "algorithm besides search_space, metric and searcher mode :param scheduler: str,", "expect_horizon=None, freq=None, metric_threshold=None, n_sampling=16, search_alg=None, search_alg_params=None, scheduler=None, scheduler_params=None, ): \"\"\"", "n_sampling according to hp.grid_search. If this is -1, (virtually) infinite", "holidays_prior_scale for the Prophet model. e.g. hp.loguniform(0.01, 10). :param seasonality_mode:", "For details of the Prophet model hyperparameters, refer to https://facebook.github.io/prophet/docs/diagnostics.html#hyperparameter-tuning.", "hp.choice(['additive', 'multiplicative']). :param changepoint_range: hyperparameter changepoint_range for the Prophet model.", "10.0]) if seasonality_prior_scale is None else seasonality_prior_scale, \"holidays_prior_scale\": hp.loguniform(0.01, 10)", "update other configs self.metric = metric model_builder = ProphetBuilder() self.auto_est", ":param cross_validation: bool, if the eval result comes from cross_validation.", "should contains more than 2 records.\" assert pd.api.types.is_datetime64_any_dtype(data[\"ds\"].dtypes), \\ \"The", "n_sampling=n_sampling, search_space=self.search_space, search_alg=search_alg, search_alg_params=search_alg_params, scheduler=scheduler, scheduler_params=scheduler_params ) # use the", "model after HPO. :param checkpoint_file: The location you want to", "type, or you need to set `freq` in fit.\" self._freq", "AutoEstimator import bigdl.orca.automl.hp as hp self.search_space = { \"changepoint_prior_scale\": hp.grid_search([0.005,", "10). :param holidays_prior_scale: hyperparameter holidays_prior_scale for the Prophet model. e.g.", "for scheduler \"\"\" if expect_horizon is None: expect_horizon = int(0.1*len(data))", "def predict(self, horizon=1, freq=\"D\", ds_data=None): \"\"\" Predict using the best", "(i.e.\"variant_generator\", \"random\", \"ax\", \"dragonfly\", \"skopt\", \"hyperopt\", \"bayesopt\", \"bohb\", \"nevergrad\", \"optuna\",", "must call fit or restore first before calling predict!\") return", "n_sampling=16, search_alg=None, search_alg_params=None, scheduler=None, scheduler_params=None, ): \"\"\" Automatically fit the", "It defaults to 1. :param name: name of the AutoProphet.", "10) if holidays_prior_scale is None else holidays_prior_scale, \"seasonality_mode\": hp.choice(['additive', 'multiplicative'])", "and 2 columns, with column 'ds' indicating date and column", "fit or restore first before calling predict!\") return self.best_model.predict(horizon=horizon, freq=freq,", "configs self.metric = metric model_builder = ProphetBuilder() self.auto_est = AutoEstimator(model_builder=model_builder,", "See the License for the specific language governing permissions and", "where 10% of training data will be taken as the", "to day(\"D\"), the frequency can be anything from the pandas", "data. \"\"\" if data is None: raise ValueError(\"Input invalid data", "if changepoint_range is None else changepoint_range } self.search_space.update(prophet_config) # update", "and # limitations under the License. # import pandas as", "): \"\"\" Create an automated Prophet Model. User need to", "the License. # You may obtain a copy of the", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "for the specific language governing permissions and # limitations under", "and doesn't take effects while running in local. While running", "else changepoint_range } self.search_space.update(prophet_config) # update other configs self.metric =", "ray tune :param scheduler_params: parameters for scheduler \"\"\" if expect_horizon", "to in writing, software # distributed under the License is", "permissions and # limitations under the License. # import pandas", ":param freq: the freqency of the predicted dataframe, defaulted to", "location you want to load the best model. \"\"\" self.best_model.restore(checkpoint_file)", "# See the License for the specific language governing permissions", "anything from the pandas list of frequency strings here: https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#timeseries-offset-aliasesDefaulted", "Load the ckpt from load_dir. The value defaults to None.", "to None and doesn't take effects while running in local.", "\"changepoint_range\": hp.uniform(0.8, 0.95) if changepoint_range is None else changepoint_range }", "self.best_model = ProphetBuilder().build(self.auto_est.get_best_config()) self.best_model.model.fit(data) def predict(self, horizon=1, freq=\"D\", ds_data=None): \"\"\"", "language governing permissions and # limitations under the License. #", "self.best_model.save(checkpoint_file) def restore(self, checkpoint_file): \"\"\" Restore the best model after", "or agreed to in writing, software # distributed under the", "required by applicable law or agreed to in writing, software", "in local. While running in cluster, it defaults to \"hdfs:///tmp/{name}\".", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "frequency can be anything from the pandas list of frequency", "list contains metrics for test/valid data. \"\"\" if data is", "e.g. \"mse\" :param logs_dir: Local directory to save logs and", "with the License. # You may obtain a copy of", "n_sampling: Number of trials to evaluate in total. Defaults to", "cross_validation}) train_data = data if cross_validation else data[:len(data)-expect_horizon] validation_data =", "prophet model on whole data self.best_model = ProphetBuilder().build(self.auto_est.get_best_config()) self.best_model.model.fit(data) def", "expect_horizon) self.search_space.update({\"expect_horizon\": expect_horizon_str, \"cross_validation\": cross_validation}) train_data = data if cross_validation", "dataframe. the frequency can be anything from the pandas list", "fit or restore first before calling evaluate!\") return self.best_model.evaluate(target=data, metrics=metrics)", "of the AutoProphet. It defaults to \"auto_prophet\" :param remote_dir: String.", "pd.api.types.is_datetime64_any_dtype(data[\"ds\"].dtypes), \\ \"The 'ds' col should be in datetime 64", "= None if cross_validation else data[len(data)-expect_horizon:] n_sampling = recalculate_n_sampling(self.search_space, n_sampling)", "best model after HPO. :param checkpoint_file: The location you want", "train_data = data if cross_validation else data[:len(data)-expect_horizon] validation_data = None", "None: raise ValueError(\"Input invalid data of None\") if self.best_model.model is", "remote_dir=remote_dir, name=name) except ImportError: warnings.warn(\"You need to install `bigdl-orca[automl]` to", "data[len(data)-expect_horizon:] n_sampling = recalculate_n_sampling(self.search_space, n_sampling) if n_sampling != -1 else", "after HPO. :param checkpoint_file: The checkpoint file location you want", "__init__(self, changepoint_prior_scale=None, seasonality_prior_scale=None, holidays_prior_scale=None, seasonality_mode=None, changepoint_range=None, metric='mse', logs_dir=\"/tmp/auto_prophet_logs\", cpus_per_trial=1, name=\"auto_prophet\",", "cross_validation. The value is set to True by default. Setting", "`fit` function.\") def fit(self, data, cross_validation=True, expect_horizon=None, freq=None, metric_threshold=None, n_sampling=16,", "up the process. :param expect_horizon: int, validation data will be", "compliance with the License. # You may obtain a copy", "Create an automated Prophet Model. User need to specify either", "data[\"ds\"].iloc[1] - data[\"ds\"].iloc[0] else: self._freq = pd.Timedelta(freq) expect_horizon_str = str(self._freq", "agreed to in writing, software # distributed under the License", "\"You must call fit or restore first before calling evaluate!\")", "distributed under the License is distributed on an \"AS IS\"", "training results and checkpoints. It defaults to None and doesn't", "the best model after HPO. :param checkpoint_file: The location you", "warnings.warn(\"You need to install `bigdl-orca[automl]` to use `fit` function.\") def", "remote_dir: String. Remote directory to sync training results and checkpoints.", "function.\") def fit(self, data, cross_validation=True, expect_horizon=None, freq=None, metric_threshold=None, n_sampling=16, search_alg=None,", "'multiplicative']). :param changepoint_range: hyperparameter changepoint_range for the Prophet model. e.g.", "see bigdl.chronos.orca.automl.hp for more details. e.g. hp.loguniform(0.001, 0.5). :param seasonality_prior_scale:", "searcher mode :param scheduler: str, all supported scheduler provided by", "seasonality_mode is None else seasonality_mode, \"changepoint_range\": hp.uniform(0.8, 0.95) if changepoint_range", "it defaults to \"hdfs:///tmp/{name}\". :param load_dir: Load the ckpt from", "column 'ds' indicating date. \"\"\" if self.best_model.model is None: raise", "expect_horizon is the horizon you may need to use once", ":param scheduler: str, all supported scheduler provided by ray tune", "automated Prophet Model. User need to specify either the exact", "fitted. The value defaults to None, where 10% of training", "and \"sigopt\") :param search_alg_params: extra parameters for searcher algorithm besides", "col should be in datetime 64 type, or you need", "None. :param prophet_config: Other Prophet hyperparameters. \"\"\" if load_dir: self.best_model", "except in compliance with the License. # You may obtain", "else holidays_prior_scale, \"seasonality_mode\": hp.choice(['additive', 'multiplicative']) if seasonality_mode is None else", "\"\"\" if expect_horizon is None: expect_horizon = int(0.1*len(data)) if freq", "Licensed under the Apache License, Version 2.0 (the \"License\"); #", "freq is None: assert len(data) >= 2, \"The training dataframe", "search_space, the grid will be run n_sampling of trials and", "self._freq = data[\"ds\"].iloc[1] - data[\"ds\"].iloc[0] else: self._freq = pd.Timedelta(freq) expect_horizon_str", "not use this file except in compliance with the License.", "from load_dir. The value defaults to None. :param prophet_config: Other", ":param seasonality_mode: hyperparameter seasonality_mode for the Prophet model. e.g. hp.choice(['additive',", "more than 2 records.\" assert pd.api.types.is_datetime64_any_dtype(data[\"ds\"].dtypes), \\ \"The 'ds' col", "date. \"\"\" if self.best_model.model is None: raise RuntimeError( \"You must", "the best model. \"\"\" self.best_model.restore(checkpoint_file) def get_best_model(self): \"\"\" Get the", "writing, software # distributed under the License is distributed on", "1.0, 10.0]) if seasonality_prior_scale is None else seasonality_prior_scale, \"holidays_prior_scale\": hp.loguniform(0.01,", "of the training dataframe. the frequency can be anything from", "for the Prophet model. e.g. hp.loguniform(0.01, 10). :param holidays_prior_scale: hyperparameter", "\"\"\" if load_dir: self.best_model = ProphetModel() self.best_model.restore(load_dir) try: from bigdl.orca.automl.auto_estimator", "the eval result comes from cross_validation. The value is set", "you may not use this file except in compliance with", "either the exact value or the search space of the", "in cluster, it defaults to \"hdfs:///tmp/{name}\". :param load_dir: Load the", "n_sampling of trials and round up n_sampling according to hp.grid_search.", "bigdl.chronos.model.prophet import ProphetBuilder, ProphetModel from bigdl.chronos.autots.utils import recalculate_n_sampling # -", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "the exact value or the search space of the Prophet", "round up n_sampling according to hp.grid_search. If this is -1,", "save logs and results. It defaults to \"/tmp/auto_prophet_logs\" :param cpus_per_trial:", ":param n_sampling: Number of trials to evaluate in total. Defaults", "and round up n_sampling according to hp.grid_search. If this is", "evaluate(self, data, metrics=['mse']): \"\"\" Evaluate using the best model after", "changepoint_prior_scale, \"seasonality_prior_scale\": hp.grid_search([0.01, 0.1, 1.0, 10.0]) if seasonality_prior_scale is None", "holidays_prior_scale, \"seasonality_mode\": hp.choice(['additive', 'multiplicative']) if seasonality_mode is None else seasonality_mode,", "the best config to fit a new prophet model on", "0.1, 0.5]) if changepoint_prior_scale is None else changepoint_prior_scale, \"seasonality_prior_scale\": hp.grid_search([0.01,", "is None else holidays_prior_scale, \"seasonality_mode\": hp.choice(['additive', 'multiplicative']) if seasonality_mode is", "\"You must call fit or restore first before calling predict!\")", "str, all supported scheduler provided by ray tune :param scheduler_params:", "under the License. # import pandas as pd import warnings", "True by default. Setting this option to False to speed", "after HPO. :param horizon: the number of steps forward to", "* expect_horizon) self.search_space.update({\"expect_horizon\": expect_horizon_str, \"cross_validation\": cross_validation}) train_data = data if", "dataframe with Td rows, and 2 columns, with column 'ds'", "a new prophet model on whole data self.best_model = ProphetBuilder().build(self.auto_est.get_best_config())", "defaults to \"/tmp/auto_prophet_logs\" :param cpus_per_trial: Int. Number of cpus for", "to \"/tmp/auto_prophet_logs\" :param cpus_per_trial: Int. Number of cpus for each", "trial will be terminated when metric threshold is met :param", "seasonality_mode, \"changepoint_range\": hp.uniform(0.8, 0.95) if changepoint_range is None else changepoint_range", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", ":param freq: the freqency of the training dataframe. the frequency", "import ProphetBuilder, ProphetModel from bigdl.chronos.autots.utils import recalculate_n_sampling # - class", "ds_data: a dataframe that has 1 column 'ds' indicating date.", "model_builder = ProphetBuilder() self.auto_est = AutoEstimator(model_builder=model_builder, logs_dir=logs_dir, resources_per_trial={\"cpu\": cpus_per_trial}, remote_dir=remote_dir,", "other configs self.metric = metric model_builder = ProphetBuilder() self.auto_est =", "is met :param n_sampling: Number of trials to evaluate in", "Evaluate using the best model after HPO. :param data: evaluation", "self.best_model.restore(checkpoint_file) def get_best_model(self): \"\"\" Get the best Prophet model. \"\"\"", "hp self.search_space = { \"changepoint_prior_scale\": hp.grid_search([0.005, 0.05, 0.1, 0.5]) if", "Td is the time dimension :param cross_validation: bool, if the", "the best model, should be a json file \"\"\" if", "The evaluation metric name to optimize. e.g. \"mse\" :param logs_dir:", "2 records.\" assert pd.api.types.is_datetime64_any_dtype(data[\"ds\"].dtypes), \\ \"The 'ds' col should be", "fit.\" self._freq = data[\"ds\"].iloc[1] - data[\"ds\"].iloc[0] else: self._freq = pd.Timedelta(freq)", "you may need to use once the mode is fitted.", "once the mode is fitted. The value defaults to None,", "if freq is None: assert len(data) >= 2, \"The training", "evaluate!\") return self.best_model.evaluate(target=data, metrics=metrics) def save(self, checkpoint_file): \"\"\" Save the", "directory to sync training results and checkpoints. It defaults to", "and search for the best hyperparameters. :param data: training data,", "is fitted. The value defaults to None, where 10% of", "= metric model_builder = ProphetBuilder() self.auto_est = AutoEstimator(model_builder=model_builder, logs_dir=logs_dir, resources_per_trial={\"cpu\":", "defaults to None. :param prophet_config: Other Prophet hyperparameters. \"\"\" if", "the process. :param expect_horizon: int, validation data will be automatically", "model after HPO. :param checkpoint_file: The checkpoint file location you", "defaults to None and doesn't take effects while running in", "hp sampling function from an integer space for hyperparameter changepoint_prior_scale", "time dimension :param cross_validation: bool, if the eval result comes", "hp sampling, see bigdl.chronos.orca.automl.hp for more details. e.g. hp.loguniform(0.001, 0.5).", "in total. Defaults to 16. If hp.grid_search is in search_space,", "str, all supported searcher provided by ray tune (i.e.\"variant_generator\", \"random\",", "of steps forward to predict :param freq: the freqency of", "on whole data self.best_model = ProphetBuilder().build(self.auto_est.get_best_config()) self.best_model.model.fit(data) def predict(self, horizon=1,", "eval result comes from cross_validation. The value is set to", "cross_validation: bool, if the eval result comes from cross_validation. The", "e.g. hp.choice(['additive', 'multiplicative']). :param changepoint_range: hyperparameter changepoint_range for the Prophet", "restore first before calling predict!\") return self.best_model.predict(horizon=horizon, freq=freq, ds_data=ds_data) def", "self.search_space.update(prophet_config) # update other configs self.metric = metric model_builder =", "effects while running in local. While running in cluster, it", "defaults to None, where 10% of training data will be", "!= -1 else -1 self.auto_est.fit(data=train_data, validation_data=validation_data, metric=self.metric, metric_threshold=metric_threshold, n_sampling=n_sampling, search_space=self.search_space,", "rows, and 2 columns, with column 'ds' indicating date and", "take effects while running in local. While running in cluster,", "generated until a stopping condition is met. :param search_alg: str,", "\"hdfs:///tmp/{name}\". :param load_dir: Load the ckpt from load_dir. The value", "of cpus for each trial. It defaults to 1. :param", "ds_data=ds_data) def evaluate(self, data, metrics=['mse']): \"\"\" Evaluate using the best", "hp.grid_search([0.005, 0.05, 0.1, 0.5]) if changepoint_prior_scale is None else changepoint_prior_scale,", "expect_horizon is None: expect_horizon = int(0.1*len(data)) if freq is None:", "hyperparameter changepoint_prior_scale for the Prophet model. For hp sampling, see", "the best hyperparameters. :param data: training data, a pandas dataframe", "pandas as pd import warnings from bigdl.chronos.model.prophet import ProphetBuilder, ProphetModel", "the License is distributed on an \"AS IS\" BASIS, #", "automatically splited from training data, and expect_horizon is the horizon", "call fit or restore first before calling save!\") self.best_model.save(checkpoint_file) def", "\"seasonality_prior_scale\": hp.grid_search([0.01, 0.1, 1.0, 10.0]) if seasonality_prior_scale is None else", "the time dimension :param metrics: A list contains metrics for", "sync training results and checkpoints. It defaults to None and", "evaluation data, a pandas dataframe with Td rows, and 2", "provided by ray tune :param scheduler_params: parameters for scheduler \"\"\"", "**prophet_config ): \"\"\" Create an automated Prophet Model. User need", "\"holidays_prior_scale\": hp.loguniform(0.01, 10) if holidays_prior_scale is None else holidays_prior_scale, \"seasonality_mode\":", "def restore(self, checkpoint_file): \"\"\" Restore the best model after HPO.", "if cross_validation else data[len(data)-expect_horizon:] n_sampling = recalculate_n_sampling(self.search_space, n_sampling) if n_sampling", "len(data) >= 2, \"The training dataframe should contains more than", "while running in local. While running in cluster, it defaults", "all supported searcher provided by ray tune (i.e.\"variant_generator\", \"random\", \"ax\",", "= pd.Timedelta(freq) expect_horizon_str = str(self._freq * expect_horizon) self.search_space.update({\"expect_horizon\": expect_horizon_str, \"cross_validation\":", "file location you want to load the best model. \"\"\"", "\"nevergrad\", \"optuna\", \"zoopt\" and \"sigopt\") :param search_alg_params: extra parameters for", "taken as the validation data. :param freq: the freqency of", "exact value or the search space of the Prophet model", "for test/valid data. \"\"\" if data is None: raise ValueError(\"Input", "validation_data = None if cross_validation else data[len(data)-expect_horizon:] n_sampling = recalculate_n_sampling(self.search_space,", "json file \"\"\" if self.best_model.model is None: raise RuntimeError( \"You", "an unreliable frequency will be infer implicitly. :param metric_threshold: a", "be terminated when metric threshold is met :param n_sampling: Number", "if data is None: raise ValueError(\"Input invalid data of None\")", "parameters for searcher algorithm besides search_space, metric and searcher mode", "ValueError(\"Input invalid data of None\") if self.best_model.model is None: raise", "exp' # ress or implied. # See the License for", "self.best_model = ProphetModel() self.best_model.restore(load_dir) try: from bigdl.orca.automl.auto_estimator import AutoEstimator import", "to True by default. Setting this option to False to", "\"\"\" Predict using the best model after HPO. :param horizon:", "of trials to evaluate in total. Defaults to 16. If", "Copyright 2016 The BigDL Authors. # # Licensed under the", "law or agreed to in writing, software # distributed under", "0.5]) if changepoint_prior_scale is None else changepoint_prior_scale, \"seasonality_prior_scale\": hp.grid_search([0.01, 0.1,", "'ds' indicating date and column 'y' indicating value and Td", "need to use once the mode is fitted. The value", "to hp.grid_search. If this is -1, (virtually) infinite samples are", "If this is -1, (virtually) infinite samples are generated until", "columns, with column 'ds' indicating date and column 'y' indicating", "governing permissions and # limitations under the License. # import", "cpus_per_trial: Int. Number of cpus for each trial. It defaults", "\"ax\", \"dragonfly\", \"skopt\", \"hyperopt\", \"bayesopt\", \"bohb\", \"nevergrad\", \"optuna\", \"zoopt\" and", "Prophet model hyperparameters, refer to https://facebook.github.io/prophet/docs/diagnostics.html#hyperparameter-tuning. :param changepoint_prior_scale: Int or", "all supported scheduler provided by ray tune :param scheduler_params: parameters", "than 2 records.\" assert pd.api.types.is_datetime64_any_dtype(data[\"ds\"].dtypes), \\ \"The 'ds' col should", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either exp' #", "evaluate in total. Defaults to 16. If hp.grid_search is in", "list of frequency strings here: https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#timeseries-offset-aliasesDefaulted to None, where an", "the grid will be run n_sampling of trials and round", "changepoint_range for the Prophet model. e.g. hp.uniform(0.8, 0.95). :param metric:", "\"zoopt\" and \"sigopt\") :param search_alg_params: extra parameters for searcher algorithm", "and column 'y' indicating value and Td is the time", "e.g. hp.loguniform(0.001, 0.5). :param seasonality_prior_scale: hyperparameter seasonality_prior_scale for the Prophet", "hp.choice(['additive', 'multiplicative']) if seasonality_mode is None else seasonality_mode, \"changepoint_range\": hp.uniform(0.8,", "changepoint_range is None else changepoint_range } self.search_space.update(prophet_config) # update other", "else changepoint_prior_scale, \"seasonality_prior_scale\": hp.grid_search([0.01, 0.1, 1.0, 10.0]) if seasonality_prior_scale is", ":param metric: String. The evaluation metric name to optimize. e.g.", "training dataframe. the frequency can be anything from the pandas", "of frequency strings here: https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#timeseries-offset-aliasesDefaulted to None, where an unreliable", "an automated Prophet Model. User need to specify either the", "\"auto_prophet\" :param remote_dir: String. Remote directory to sync training results", "to speed up the process. :param expect_horizon: int, validation data", "ImportError: warnings.warn(\"You need to install `bigdl-orca[automl]` to use `fit` function.\")", "before calling save!\") self.best_model.save(checkpoint_file) def restore(self, checkpoint_file): \"\"\" Restore the", "threshold is met :param n_sampling: Number of trials to evaluate", "User need to specify either the exact value or the", "tune :param scheduler_params: parameters for scheduler \"\"\" if expect_horizon is", "the validation data. :param freq: the freqency of the training", "model. e.g. hp.loguniform(0.01, 10). :param holidays_prior_scale: hyperparameter holidays_prior_scale for the", "may obtain a copy of the License at # #", "has 1 column 'ds' indicating date. \"\"\" if self.best_model.model is", "the model and search for the best hyperparameters. :param data:", "call fit or restore first before calling predict!\") return self.best_model.predict(horizon=horizon,", "using the best model after HPO. :param data: evaluation data,", "# import pandas as pd import warnings from bigdl.chronos.model.prophet import", "predict(self, horizon=1, freq=\"D\", ds_data=None): \"\"\" Predict using the best model", "(virtually) infinite samples are generated until a stopping condition is", "if load_dir: self.best_model = ProphetModel() self.best_model.restore(load_dir) try: from bigdl.orca.automl.auto_estimator import", "# ress or implied. # See the License for the", "fit a new prophet model on whole data self.best_model =", ":param logs_dir: Local directory to save logs and results. It", "to use `fit` function.\") def fit(self, data, cross_validation=True, expect_horizon=None, freq=None,", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", ":param search_alg: str, all supported searcher provided by ray tune", "more details. e.g. hp.loguniform(0.001, 0.5). :param seasonality_prior_scale: hyperparameter seasonality_prior_scale for", "from an integer space for hyperparameter changepoint_prior_scale for the Prophet", "ProphetBuilder() self.auto_est = AutoEstimator(model_builder=model_builder, logs_dir=logs_dir, resources_per_trial={\"cpu\": cpus_per_trial}, remote_dir=remote_dir, name=name) except", "may not use this file except in compliance with the", "and Td is the time dimension :param cross_validation: bool, if", "restore first before calling evaluate!\") return self.best_model.evaluate(target=data, metrics=metrics) def save(self,", "with Td rows, and 2 columns, with column 'ds' indicating", "contains more than 2 records.\" assert pd.api.types.is_datetime64_any_dtype(data[\"ds\"].dtypes), \\ \"The 'ds'", "the best model after HPO. :param data: evaluation data, a", "bigdl.orca.automl.auto_estimator import AutoEstimator import bigdl.orca.automl.hp as hp self.search_space = {", "this file except in compliance with the License. # You", "for the Prophet model. e.g. hp.loguniform(0.01, 10). :param seasonality_mode: hyperparameter", "Prophet model. e.g. hp.choice(['additive', 'multiplicative']). :param changepoint_range: hyperparameter changepoint_range for", "with column 'ds' indicating date and column 'y' indicating value", "https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#timeseries-offset-aliasesDefaulted to None, where an unreliable frequency will be infer", "or you need to set `freq` in fit.\" self._freq =", "self._freq = pd.Timedelta(freq) expect_horizon_str = str(self._freq * expect_horizon) self.search_space.update({\"expect_horizon\": expect_horizon_str,", "\"bayesopt\", \"bohb\", \"nevergrad\", \"optuna\", \"zoopt\" and \"sigopt\") :param search_alg_params: extra", "predict :param freq: the freqency of the predicted dataframe, defaulted", ":param checkpoint_file: The location you want to save the best", "-1 else -1 self.auto_est.fit(data=train_data, validation_data=validation_data, metric=self.metric, metric_threshold=metric_threshold, n_sampling=n_sampling, search_space=self.search_space, search_alg=search_alg,", "resources_per_trial={\"cpu\": cpus_per_trial}, remote_dir=remote_dir, name=name) except ImportError: warnings.warn(\"You need to install", "space for hyperparameter changepoint_prior_scale for the Prophet model. For hp", "value defaults to None. :param prophet_config: Other Prophet hyperparameters. \"\"\"", "first before calling evaluate!\") return self.best_model.evaluate(target=data, metrics=metrics) def save(self, checkpoint_file):", "strings here: https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#timeseries-offset-aliasesDefaulted to None, where an unreliable frequency will", "model hyperparameters, refer to https://facebook.github.io/prophet/docs/diagnostics.html#hyperparameter-tuning. :param changepoint_prior_scale: Int or hp", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "best model, should be a json file \"\"\" if self.best_model.model", "after HPO. :param checkpoint_file: The location you want to save", "be run n_sampling of trials and round up n_sampling according", "search space of the Prophet model hyperparameters. For details of", "steps forward to predict :param freq: the freqency of the", "# # Licensed under the Apache License, Version 2.0 (the", "seasonality_prior_scale for the Prophet model. e.g. hp.loguniform(0.01, 10). :param holidays_prior_scale:", "datetime 64 type, or you need to set `freq` in", "Int. Number of cpus for each trial. It defaults to", "is None else changepoint_range } self.search_space.update(prophet_config) # update other configs", "file except in compliance with the License. # You may", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "from bigdl.chronos.model.prophet import ProphetBuilder, ProphetModel from bigdl.chronos.autots.utils import recalculate_n_sampling #", "\"seasonality_mode\": hp.choice(['additive', 'multiplicative']) if seasonality_mode is None else seasonality_mode, \"changepoint_range\":", "you want to save the best model, should be a", "else seasonality_mode, \"changepoint_range\": hp.uniform(0.8, 0.95) if changepoint_range is None else", "hp.grid_search is in search_space, the grid will be run n_sampling", "\"mse\" :param logs_dir: Local directory to save logs and results.", "to 1. :param name: name of the AutoProphet. It defaults", "- class AutoProphet: def __init__(self, changepoint_prior_scale=None, seasonality_prior_scale=None, holidays_prior_scale=None, seasonality_mode=None, changepoint_range=None,", "data will be taken as the validation data. :param freq:", "integer space for hyperparameter changepoint_prior_scale for the Prophet model. For", "of training data will be taken as the validation data.", "if expect_horizon is None: expect_horizon = int(0.1*len(data)) if freq is", "from training data, and expect_horizon is the horizon you may", "Remote directory to sync training results and checkpoints. It defaults", "that has 1 column 'ds' indicating date. \"\"\" if self.best_model.model", "self.search_space = { \"changepoint_prior_scale\": hp.grid_search([0.005, 0.05, 0.1, 0.5]) if changepoint_prior_scale", "for hyperparameter changepoint_prior_scale for the Prophet model. For hp sampling,", "searcher provided by ray tune (i.e.\"variant_generator\", \"random\", \"ax\", \"dragonfly\", \"skopt\",", "metric model_builder = ProphetBuilder() self.auto_est = AutoEstimator(model_builder=model_builder, logs_dir=logs_dir, resources_per_trial={\"cpu\": cpus_per_trial},", "in fit.\" self._freq = data[\"ds\"].iloc[1] - data[\"ds\"].iloc[0] else: self._freq =", "else -1 self.auto_est.fit(data=train_data, validation_data=validation_data, metric=self.metric, metric_threshold=metric_threshold, n_sampling=n_sampling, search_space=self.search_space, search_alg=search_alg, search_alg_params=search_alg_params,", "= ProphetBuilder() self.auto_est = AutoEstimator(model_builder=model_builder, logs_dir=logs_dir, resources_per_trial={\"cpu\": cpus_per_trial}, remote_dir=remote_dir, name=name)", "the frequency can be anything from the pandas list of", "ds_data=None): \"\"\" Predict using the best model after HPO. :param", "If hp.grid_search is in search_space, the grid will be run", "to use once the mode is fitted. The value defaults", "is None: raise ValueError(\"Input invalid data of None\") if self.best_model.model", "freq: the freqency of the training dataframe. the frequency can", "limitations under the License. # import pandas as pd import", "indicating date. \"\"\" if self.best_model.model is None: raise RuntimeError( \"You", "will be run n_sampling of trials and round up n_sampling", "# - class AutoProphet: def __init__(self, changepoint_prior_scale=None, seasonality_prior_scale=None, holidays_prior_scale=None, seasonality_mode=None,", "by ray tune :param scheduler_params: parameters for scheduler \"\"\" if", "data, cross_validation=True, expect_horizon=None, freq=None, metric_threshold=None, n_sampling=16, search_alg=None, search_alg_params=None, scheduler=None, scheduler_params=None,", "use the best config to fit a new prophet model", "or the search space of the Prophet model hyperparameters. For", "predicted dataframe, defaulted to day(\"D\"), the frequency can be anything", ":param scheduler_params: parameters for scheduler \"\"\" if expect_horizon is None:", "def evaluate(self, data, metrics=['mse']): \"\"\" Evaluate using the best model", "and expect_horizon is the horizon you may need to use", "frequency will be infer implicitly. :param metric_threshold: a trial will", "expect_horizon_str, \"cross_validation\": cross_validation}) train_data = data if cross_validation else data[:len(data)-expect_horizon]", "be anything from the pandas list of frequency strings here:", "hp.loguniform(0.01, 10). :param holidays_prior_scale: hyperparameter holidays_prior_scale for the Prophet model.", "unreliable frequency will be infer implicitly. :param metric_threshold: a trial", "'multiplicative']) if seasonality_mode is None else seasonality_mode, \"changepoint_range\": hp.uniform(0.8, 0.95)", "value and Td is the time dimension :param metrics: A", "the Prophet model hyperparameters, refer to https://facebook.github.io/prophet/docs/diagnostics.html#hyperparameter-tuning. :param changepoint_prior_scale: Int", "running in cluster, it defaults to \"hdfs:///tmp/{name}\". :param load_dir: Load", "load_dir=None, **prophet_config ): \"\"\" Create an automated Prophet Model. User", "logs and results. It defaults to \"/tmp/auto_prophet_logs\" :param cpus_per_trial: Int.", "pandas dataframe with Td rows, and 2 columns, with column", "stopping condition is met. :param search_alg: str, all supported searcher", "# use the best config to fit a new prophet", ":param seasonality_prior_scale: hyperparameter seasonality_prior_scale for the Prophet model. e.g. hp.loguniform(0.01,", "None else changepoint_range } self.search_space.update(prophet_config) # update other configs self.metric", "fit or restore first before calling save!\") self.best_model.save(checkpoint_file) def restore(self,", "def get_best_model(self): \"\"\" Get the best Prophet model. \"\"\" return", "# # Copyright 2016 The BigDL Authors. # # Licensed", "e.g. hp.uniform(0.8, 0.95). :param metric: String. The evaluation metric name", "hp.uniform(0.8, 0.95). :param metric: String. The evaluation metric name to", "Defaults to 16. If hp.grid_search is in search_space, the grid", "search_alg_params: extra parameters for searcher algorithm besides search_space, metric and", "if holidays_prior_scale is None else holidays_prior_scale, \"seasonality_mode\": hp.choice(['additive', 'multiplicative']) if", "\"cross_validation\": cross_validation}) train_data = data if cross_validation else data[:len(data)-expect_horizon] validation_data", "checkpoint_file: The location you want to save the best model,", "the pandas list of frequency strings here: https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#timeseries-offset-aliases :param ds_data:", "2, \"The training dataframe should contains more than 2 records.\"", "will be terminated when metric threshold is met :param n_sampling:", "in search_space, the grid will be run n_sampling of trials", "self.search_space.update({\"expect_horizon\": expect_horizon_str, \"cross_validation\": cross_validation}) train_data = data if cross_validation else", "\"changepoint_prior_scale\": hp.grid_search([0.005, 0.05, 0.1, 0.5]) if changepoint_prior_scale is None else", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "search_space, metric and searcher mode :param scheduler: str, all supported", "will be automatically splited from training data, and expect_horizon is", "String. Remote directory to sync training results and checkpoints. It", "metric_threshold=None, n_sampling=16, search_alg=None, search_alg_params=None, scheduler=None, scheduler_params=None, ): \"\"\" Automatically fit", "self.best_model.restore(load_dir) try: from bigdl.orca.automl.auto_estimator import AutoEstimator import bigdl.orca.automl.hp as hp", "The value is set to True by default. Setting this", "and searcher mode :param scheduler: str, all supported scheduler provided", "= data if cross_validation else data[:len(data)-expect_horizon] validation_data = None if", "details. e.g. hp.loguniform(0.001, 0.5). :param seasonality_prior_scale: hyperparameter seasonality_prior_scale for the", "hp.loguniform(0.001, 0.5). :param seasonality_prior_scale: hyperparameter seasonality_prior_scale for the Prophet model.", "the Prophet model hyperparameters. For details of the Prophet model", "\"dragonfly\", \"skopt\", \"hyperopt\", \"bayesopt\", \"bohb\", \"nevergrad\", \"optuna\", \"zoopt\" and \"sigopt\")", "hp.loguniform(0.01, 10) if holidays_prior_scale is None else holidays_prior_scale, \"seasonality_mode\": hp.choice(['additive',", "process. :param expect_horizon: int, validation data will be automatically splited", "calling evaluate!\") return self.best_model.evaluate(target=data, metrics=metrics) def save(self, checkpoint_file): \"\"\" Save", "or implied. # See the License for the specific language", "\"hyperopt\", \"bayesopt\", \"bohb\", \"nevergrad\", \"optuna\", \"zoopt\" and \"sigopt\") :param search_alg_params:", "cluster, it defaults to \"hdfs:///tmp/{name}\". :param load_dir: Load the ckpt", "hyperparameter seasonality_prior_scale for the Prophet model. e.g. hp.loguniform(0.01, 10). :param", "expect_horizon = int(0.1*len(data)) if freq is None: assert len(data) >=", "first before calling predict!\") return self.best_model.predict(horizon=horizon, freq=freq, ds_data=ds_data) def evaluate(self,", "hyperparameter changepoint_range for the Prophet model. e.g. hp.uniform(0.8, 0.95). :param", "validation data. :param freq: the freqency of the training dataframe.", "to save logs and results. It defaults to \"/tmp/auto_prophet_logs\" :param", "be in datetime 64 type, or you need to set", "the number of steps forward to predict :param freq: the", "be a json file \"\"\" if self.best_model.model is None: raise", "specific language governing permissions and # limitations under the License.", "if self.best_model.model is None: raise RuntimeError( \"You must call fit", "defaults to \"hdfs:///tmp/{name}\". :param load_dir: Load the ckpt from load_dir.", "name=\"auto_prophet\", remote_dir=None, load_dir=None, **prophet_config ): \"\"\" Create an automated Prophet", "Setting this option to False to speed up the process.", "= { \"changepoint_prior_scale\": hp.grid_search([0.005, 0.05, 0.1, 0.5]) if changepoint_prior_scale is", "up n_sampling according to hp.grid_search. If this is -1, (virtually)", "by ray tune (i.e.\"variant_generator\", \"random\", \"ax\", \"dragonfly\", \"skopt\", \"hyperopt\", \"bayesopt\",", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "Number of cpus for each trial. It defaults to 1.", "invalid data of None\") if self.best_model.model is None: raise RuntimeError(", "import recalculate_n_sampling # - class AutoProphet: def __init__(self, changepoint_prior_scale=None, seasonality_prior_scale=None,", "restore(self, checkpoint_file): \"\"\" Restore the best model after HPO. :param", "to https://facebook.github.io/prophet/docs/diagnostics.html#hyperparameter-tuning. :param changepoint_prior_scale: Int or hp sampling function from", "else: self._freq = pd.Timedelta(freq) expect_horizon_str = str(self._freq * expect_horizon) self.search_space.update({\"expect_horizon\":", "0.5). :param seasonality_prior_scale: hyperparameter seasonality_prior_scale for the Prophet model. e.g.", "pandas list of frequency strings here: https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#timeseries-offset-aliasesDefaulted to None, where", "bigdl.orca.automl.hp as hp self.search_space = { \"changepoint_prior_scale\": hp.grid_search([0.005, 0.05, 0.1,", "assert len(data) >= 2, \"The training dataframe should contains more", "training dataframe should contains more than 2 records.\" assert pd.api.types.is_datetime64_any_dtype(data[\"ds\"].dtypes),", "for more details. e.g. hp.loguniform(0.001, 0.5). :param seasonality_prior_scale: hyperparameter seasonality_prior_scale", "as pd import warnings from bigdl.chronos.model.prophet import ProphetBuilder, ProphetModel from", "time dimension :param metrics: A list contains metrics for test/valid", "(the \"License\"); # you may not use this file except", "holidays_prior_scale: hyperparameter holidays_prior_scale for the Prophet model. e.g. hp.loguniform(0.01, 10).", "set `freq` in fit.\" self._freq = data[\"ds\"].iloc[1] - data[\"ds\"].iloc[0] else:", "# you may not use this file except in compliance", "contains metrics for test/valid data. \"\"\" if data is None:", "the horizon you may need to use once the mode", "training data, and expect_horizon is the horizon you may need", "ProphetModel from bigdl.chronos.autots.utils import recalculate_n_sampling # - class AutoProphet: def", "Predict using the best model after HPO. :param horizon: the", "indicating value and Td is the time dimension :param metrics:", "day(\"D\"), the frequency can be anything from the pandas list", "model on whole data self.best_model = ProphetBuilder().build(self.auto_est.get_best_config()) self.best_model.model.fit(data) def predict(self,", "extra parameters for searcher algorithm besides search_space, metric and searcher", "a trial will be terminated when metric threshold is met", ":param remote_dir: String. Remote directory to sync training results and", "WARRANTIES OR CONDITIONS OF ANY KIND, either exp' # ress", "\"skopt\", \"hyperopt\", \"bayesopt\", \"bohb\", \"nevergrad\", \"optuna\", \"zoopt\" and \"sigopt\") :param", "or hp sampling function from an integer space for hyperparameter", "besides search_space, metric and searcher mode :param scheduler: str, all", ":param metrics: A list contains metrics for test/valid data. \"\"\"", "Restore the best model after HPO. :param checkpoint_file: The checkpoint", "data self.best_model = ProphetBuilder().build(self.auto_est.get_best_config()) self.best_model.model.fit(data) def predict(self, horizon=1, freq=\"D\", ds_data=None):", "defaults to 1. :param name: name of the AutoProphet. It", "cpus_per_trial=1, name=\"auto_prophet\", remote_dir=None, load_dir=None, **prophet_config ): \"\"\" Create an automated", "from cross_validation. The value is set to True by default.", "OF ANY KIND, either exp' # ress or implied. #", "frequency strings here: https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#timeseries-offset-aliases :param ds_data: a dataframe that has", "# # Unless required by applicable law or agreed to", "frequency strings here: https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#timeseries-offset-aliasesDefaulted to None, where an unreliable frequency", "n_sampling) if n_sampling != -1 else -1 self.auto_est.fit(data=train_data, validation_data=validation_data, metric=self.metric,", "return self.best_model.predict(horizon=horizon, freq=freq, ds_data=ds_data) def evaluate(self, data, metrics=['mse']): \"\"\" Evaluate", "The BigDL Authors. # # Licensed under the Apache License,", "For hp sampling, see bigdl.chronos.orca.automl.hp for more details. e.g. hp.loguniform(0.001,", "to sync training results and checkpoints. It defaults to None", "trials to evaluate in total. Defaults to 16. If hp.grid_search", "met. :param search_alg: str, all supported searcher provided by ray", "# update other configs self.metric = metric model_builder = ProphetBuilder()", "number of steps forward to predict :param freq: the freqency", "self.best_model.evaluate(target=data, metrics=metrics) def save(self, checkpoint_file): \"\"\" Save the best model", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "is None else seasonality_mode, \"changepoint_range\": hp.uniform(0.8, 0.95) if changepoint_range is", "metric_threshold=metric_threshold, n_sampling=n_sampling, search_space=self.search_space, search_alg=search_alg, search_alg_params=search_alg_params, scheduler=scheduler, scheduler_params=scheduler_params ) # use", "Prophet model. e.g. hp.loguniform(0.01, 10). :param seasonality_mode: hyperparameter seasonality_mode for", "to predict :param freq: the freqency of the predicted dataframe,", "Version 2.0 (the \"License\"); # you may not use this", "to False to speed up the process. :param expect_horizon: int,", "search_space=self.search_space, search_alg=search_alg, search_alg_params=search_alg_params, scheduler=scheduler, scheduler_params=scheduler_params ) # use the best", "to specify either the exact value or the search space", "provided by ray tune (i.e.\"variant_generator\", \"random\", \"ax\", \"dragonfly\", \"skopt\", \"hyperopt\",", "name=name) except ImportError: warnings.warn(\"You need to install `bigdl-orca[automl]` to use", "need to install `bigdl-orca[automl]` to use `fit` function.\") def fit(self,", "= ProphetBuilder().build(self.auto_est.get_best_config()) self.best_model.model.fit(data) def predict(self, horizon=1, freq=\"D\", ds_data=None): \"\"\" Predict", "pandas list of frequency strings here: https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#timeseries-offset-aliases :param ds_data: a", "The location you want to save the best model, should", "the freqency of the training dataframe. the frequency can be", "freqency of the predicted dataframe, defaulted to day(\"D\"), the frequency", "= str(self._freq * expect_horizon) self.search_space.update({\"expect_horizon\": expect_horizon_str, \"cross_validation\": cross_validation}) train_data =", "changepoint_range: hyperparameter changepoint_range for the Prophet model. e.g. hp.uniform(0.8, 0.95).", "sampling, see bigdl.chronos.orca.automl.hp for more details. e.g. hp.loguniform(0.001, 0.5). :param", "search_alg_params=search_alg_params, scheduler=scheduler, scheduler_params=scheduler_params ) # use the best config to", "a pandas dataframe with Td rows, and 2 columns, with", "local. While running in cluster, it defaults to \"hdfs:///tmp/{name}\". :param", "self.metric = metric model_builder = ProphetBuilder() self.auto_est = AutoEstimator(model_builder=model_builder, logs_dir=logs_dir,", "-1 self.auto_est.fit(data=train_data, validation_data=validation_data, metric=self.metric, metric_threshold=metric_threshold, n_sampling=n_sampling, search_space=self.search_space, search_alg=search_alg, search_alg_params=search_alg_params, scheduler=scheduler,", "metrics=['mse']): \"\"\" Evaluate using the best model after HPO. :param", "cpus_per_trial}, remote_dir=remote_dir, name=name) except ImportError: warnings.warn(\"You need to install `bigdl-orca[automl]`", "implied. # See the License for the specific language governing", "try: from bigdl.orca.automl.auto_estimator import AutoEstimator import bigdl.orca.automl.hp as hp self.search_space", "samples are generated until a stopping condition is met. :param", ">= 2, \"The training dataframe should contains more than 2", "will be infer implicitly. :param metric_threshold: a trial will be", "from bigdl.chronos.autots.utils import recalculate_n_sampling # - class AutoProphet: def __init__(self,", "None: expect_horizon = int(0.1*len(data)) if freq is None: assert len(data)", "under the Apache License, Version 2.0 (the \"License\"); # you", "as hp self.search_space = { \"changepoint_prior_scale\": hp.grid_search([0.005, 0.05, 0.1, 0.5])", "data. :param freq: the freqency of the training dataframe. the", "implicitly. :param metric_threshold: a trial will be terminated when metric", "comes from cross_validation. The value is set to True by", "CONDITIONS OF ANY KIND, either exp' # ress or implied.", "Prophet Model. User need to specify either the exact value", "hp.loguniform(0.01, 10). :param seasonality_mode: hyperparameter seasonality_mode for the Prophet model.", "import bigdl.orca.automl.hp as hp self.search_space = { \"changepoint_prior_scale\": hp.grid_search([0.005, 0.05,", "Local directory to save logs and results. It defaults to", "The value defaults to None, where 10% of training data", "warnings from bigdl.chronos.model.prophet import ProphetBuilder, ProphetModel from bigdl.chronos.autots.utils import recalculate_n_sampling", "by applicable law or agreed to in writing, software #", "None else seasonality_prior_scale, \"holidays_prior_scale\": hp.loguniform(0.01, 10) if holidays_prior_scale is None", "Td is the time dimension :param metrics: A list contains", "if seasonality_mode is None else seasonality_mode, \"changepoint_range\": hp.uniform(0.8, 0.95) if", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either exp'", "\"\"\" if self.best_model.model is None: raise RuntimeError( \"You must call", "the AutoProphet. It defaults to \"auto_prophet\" :param remote_dir: String. Remote", "default. Setting this option to False to speed up the", "to install `bigdl-orca[automl]` to use `fit` function.\") def fit(self, data,", "should be a json file \"\"\" if self.best_model.model is None:", "else data[:len(data)-expect_horizon] validation_data = None if cross_validation else data[len(data)-expect_horizon:] n_sampling", "horizon=1, freq=\"D\", ds_data=None): \"\"\" Predict using the best model after", "when metric threshold is met :param n_sampling: Number of trials", "AutoProphet. It defaults to \"auto_prophet\" :param remote_dir: String. Remote directory", "directory to save logs and results. It defaults to \"/tmp/auto_prophet_logs\"", "0.95). :param metric: String. The evaluation metric name to optimize.", "Td rows, and 2 columns, with column 'ds' indicating date", "scheduler_params=scheduler_params ) # use the best config to fit a", "# limitations under the License. # import pandas as pd", "metric='mse', logs_dir=\"/tmp/auto_prophet_logs\", cpus_per_trial=1, name=\"auto_prophet\", remote_dir=None, load_dir=None, **prophet_config ): \"\"\" Create", "Model. User need to specify either the exact value or", "Prophet hyperparameters. \"\"\" if load_dir: self.best_model = ProphetModel() self.best_model.restore(load_dir) try:", "`freq` in fit.\" self._freq = data[\"ds\"].iloc[1] - data[\"ds\"].iloc[0] else: self._freq", "\"optuna\", \"zoopt\" and \"sigopt\") :param search_alg_params: extra parameters for searcher", "searcher algorithm besides search_space, metric and searcher mode :param scheduler:", "if n_sampling != -1 else -1 self.auto_est.fit(data=train_data, validation_data=validation_data, metric=self.metric, metric_threshold=metric_threshold,", "# Copyright 2016 The BigDL Authors. # # Licensed under", "model. e.g. hp.uniform(0.8, 0.95). :param metric: String. The evaluation metric", "2016 The BigDL Authors. # # Licensed under the Apache", "according to hp.grid_search. If this is -1, (virtually) infinite samples", "\"\"\" self.best_model.restore(checkpoint_file) def get_best_model(self): \"\"\" Get the best Prophet model.", "bool, if the eval result comes from cross_validation. The value", "import pandas as pd import warnings from bigdl.chronos.model.prophet import ProphetBuilder,", "search_alg: str, all supported searcher provided by ray tune (i.e.\"variant_generator\",", "load_dir: self.best_model = ProphetModel() self.best_model.restore(load_dir) try: from bigdl.orca.automl.auto_estimator import AutoEstimator", "supported scheduler provided by ray tune :param scheduler_params: parameters for", "mode is fitted. The value defaults to None, where 10%", "the Prophet model. For hp sampling, see bigdl.chronos.orca.automl.hp for more", ":param data: evaluation data, a pandas dataframe with Td rows,", "cross_validation=True, expect_horizon=None, freq=None, metric_threshold=None, n_sampling=16, search_alg=None, search_alg_params=None, scheduler=None, scheduler_params=None, ):", "is met. :param search_alg: str, all supported searcher provided by", "may need to use once the mode is fitted. The", "def save(self, checkpoint_file): \"\"\" Save the best model after HPO.", "mode :param scheduler: str, all supported scheduler provided by ray", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "None, where 10% of training data will be taken as", "training data will be taken as the validation data. :param", "Unless required by applicable law or agreed to in writing,", "to None, where an unreliable frequency will be infer implicitly.", "= AutoEstimator(model_builder=model_builder, logs_dir=logs_dir, resources_per_trial={\"cpu\": cpus_per_trial}, remote_dir=remote_dir, name=name) except ImportError: warnings.warn(\"You", "the Prophet model. e.g. hp.loguniform(0.01, 10). :param holidays_prior_scale: hyperparameter holidays_prior_scale", "16. If hp.grid_search is in search_space, the grid will be", "for the best hyperparameters. :param data: training data, a pandas", "for searcher algorithm besides search_space, metric and searcher mode :param", "else data[len(data)-expect_horizon:] n_sampling = recalculate_n_sampling(self.search_space, n_sampling) if n_sampling != -1", "scheduler=scheduler, scheduler_params=scheduler_params ) # use the best config to fit", "hp.grid_search. If this is -1, (virtually) infinite samples are generated", "\"The 'ds' col should be in datetime 64 type, or", "else seasonality_prior_scale, \"holidays_prior_scale\": hp.loguniform(0.01, 10) if holidays_prior_scale is None else", "= int(0.1*len(data)) if freq is None: assert len(data) >= 2,", "freq=freq, ds_data=ds_data) def evaluate(self, data, metrics=['mse']): \"\"\" Evaluate using the", "the specific language governing permissions and # limitations under the", "dimension :param cross_validation: bool, if the eval result comes from", "KIND, either exp' # ress or implied. # See the", "the Prophet model. e.g. hp.choice(['additive', 'multiplicative']). :param changepoint_range: hyperparameter changepoint_range", "indicating date and column 'y' indicating value and Td is", "applicable law or agreed to in writing, software # distributed", "is the time dimension :param metrics: A list contains metrics", "by default. Setting this option to False to speed up", "install `bigdl-orca[automl]` to use `fit` function.\") def fit(self, data, cross_validation=True,", "metric threshold is met :param n_sampling: Number of trials to", "bigdl.chronos.orca.automl.hp for more details. e.g. hp.loguniform(0.001, 0.5). :param seasonality_prior_scale: hyperparameter", "None: assert len(data) >= 2, \"The training dataframe should contains", "= recalculate_n_sampling(self.search_space, n_sampling) if n_sampling != -1 else -1 self.auto_est.fit(data=train_data,", "changepoint_range=None, metric='mse', logs_dir=\"/tmp/auto_prophet_logs\", cpus_per_trial=1, name=\"auto_prophet\", remote_dir=None, load_dir=None, **prophet_config ): \"\"\"", "either exp' # ress or implied. # See the License", "a dataframe that has 1 column 'ds' indicating date. \"\"\"", "data: evaluation data, a pandas dataframe with Td rows, and", "best model after HPO. :param checkpoint_file: The checkpoint file location", "prophet_config: Other Prophet hyperparameters. \"\"\" if load_dir: self.best_model = ProphetModel()", "{ \"changepoint_prior_scale\": hp.grid_search([0.005, 0.05, 0.1, 0.5]) if changepoint_prior_scale is None", "raise ValueError(\"Input invalid data of None\") if self.best_model.model is None:", "holidays_prior_scale=None, seasonality_mode=None, changepoint_range=None, metric='mse', logs_dir=\"/tmp/auto_prophet_logs\", cpus_per_trial=1, name=\"auto_prophet\", remote_dir=None, load_dir=None, **prophet_config", "= ProphetModel() self.best_model.restore(load_dir) try: from bigdl.orca.automl.auto_estimator import AutoEstimator import bigdl.orca.automl.hp", ":param metric_threshold: a trial will be terminated when metric threshold", "model. e.g. hp.loguniform(0.01, 10). :param seasonality_mode: hyperparameter seasonality_mode for the", "for each trial. It defaults to 1. :param name: name", "data: training data, a pandas dataframe with Td rows, and", "save(self, checkpoint_file): \"\"\" Save the best model after HPO. :param", "model and search for the best hyperparameters. :param data: training", "int, validation data will be automatically splited from training data,", "n_sampling = recalculate_n_sampling(self.search_space, n_sampling) if n_sampling != -1 else -1", "in writing, software # distributed under the License is distributed", "self.best_model.model.fit(data) def predict(self, horizon=1, freq=\"D\", ds_data=None): \"\"\" Predict using the", "column 'y' indicating value and Td is the time dimension", "of frequency strings here: https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#timeseries-offset-aliases :param ds_data: a dataframe that", "predict!\") return self.best_model.predict(horizon=horizon, freq=freq, ds_data=ds_data) def evaluate(self, data, metrics=['mse']): \"\"\"", "indicating value and Td is the time dimension :param cross_validation:", "call fit or restore first before calling evaluate!\") return self.best_model.evaluate(target=data,", "the best model after HPO. :param horizon: the number of", "search_alg_params=None, scheduler=None, scheduler_params=None, ): \"\"\" Automatically fit the model and", "BigDL Authors. # # Licensed under the Apache License, Version", "It defaults to \"auto_prophet\" :param remote_dir: String. Remote directory to", "is None: expect_horizon = int(0.1*len(data)) if freq is None: assert", "Prophet model. For hp sampling, see bigdl.chronos.orca.automl.hp for more details.", "must call fit or restore first before calling evaluate!\") return", "is set to True by default. Setting this option to", "grid will be run n_sampling of trials and round up", "in datetime 64 type, or you need to set `freq`", "hyperparameters, refer to https://facebook.github.io/prophet/docs/diagnostics.html#hyperparameter-tuning. :param changepoint_prior_scale: Int or hp sampling", "ProphetBuilder().build(self.auto_est.get_best_config()) self.best_model.model.fit(data) def predict(self, horizon=1, freq=\"D\", ds_data=None): \"\"\" Predict using", "Authors. # # Licensed under the Apache License, Version 2.0", "scheduler_params: parameters for scheduler \"\"\" if expect_horizon is None: expect_horizon", "'ds' indicating date. \"\"\" if self.best_model.model is None: raise RuntimeError(", "load_dir. The value defaults to None. :param prophet_config: Other Prophet", "to load the best model. \"\"\" self.best_model.restore(checkpoint_file) def get_best_model(self): \"\"\"", "this option to False to speed up the process. :param", "def __init__(self, changepoint_prior_scale=None, seasonality_prior_scale=None, holidays_prior_scale=None, seasonality_mode=None, changepoint_range=None, metric='mse', logs_dir=\"/tmp/auto_prophet_logs\", cpus_per_trial=1,", "License is distributed on an \"AS IS\" BASIS, # WITHOUT", "\"The training dataframe should contains more than 2 records.\" assert", "It defaults to None and doesn't take effects while running", "parameters for scheduler \"\"\" if expect_horizon is None: expect_horizon =", "License, Version 2.0 (the \"License\"); # you may not use", "False to speed up the process. :param expect_horizon: int, validation", "is -1, (virtually) infinite samples are generated until a stopping", "# You may obtain a copy of the License at", "ress or implied. # See the License for the specific", "AutoProphet: def __init__(self, changepoint_prior_scale=None, seasonality_prior_scale=None, holidays_prior_scale=None, seasonality_mode=None, changepoint_range=None, metric='mse', logs_dir=\"/tmp/auto_prophet_logs\",", "seasonality_mode: hyperparameter seasonality_mode for the Prophet model. e.g. hp.choice(['additive', 'multiplicative']).", "data, a pandas dataframe with Td rows, and 2 columns,", "ProphetModel() self.best_model.restore(load_dir) try: from bigdl.orca.automl.auto_estimator import AutoEstimator import bigdl.orca.automl.hp as", "to fit a new prophet model on whole data self.best_model", "data is None: raise ValueError(\"Input invalid data of None\") if", "except ImportError: warnings.warn(\"You need to install `bigdl-orca[automl]` to use `fit`", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "Prophet model. e.g. hp.loguniform(0.01, 10). :param holidays_prior_scale: hyperparameter holidays_prior_scale for", "hp.grid_search([0.01, 0.1, 1.0, 10.0]) if seasonality_prior_scale is None else seasonality_prior_scale,", "\"\"\" Evaluate using the best model after HPO. :param data:", ":param data: training data, a pandas dataframe with Td rows,", "search_alg=search_alg, search_alg_params=search_alg_params, scheduler=scheduler, scheduler_params=scheduler_params ) # use the best config", "metrics for test/valid data. \"\"\" if data is None: raise", "best model after HPO. :param data: evaluation data, a pandas", "calling save!\") self.best_model.save(checkpoint_file) def restore(self, checkpoint_file): \"\"\" Restore the best", "10). :param seasonality_mode: hyperparameter seasonality_mode for the Prophet model. e.g.", "OR CONDITIONS OF ANY KIND, either exp' # ress or", "dataframe that has 1 column 'ds' indicating date. \"\"\" if", "metric name to optimize. e.g. \"mse\" :param logs_dir: Local directory", "running in local. While running in cluster, it defaults to", "): \"\"\" Automatically fit the model and search for the", "None\") if self.best_model.model is None: raise RuntimeError( \"You must call", "total. Defaults to 16. If hp.grid_search is in search_space, the", "pd.Timedelta(freq) expect_horizon_str = str(self._freq * expect_horizon) self.search_space.update({\"expect_horizon\": expect_horizon_str, \"cross_validation\": cross_validation})", "freq: the freqency of the predicted dataframe, defaulted to day(\"D\"),", "here: https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#timeseries-offset-aliasesDefaulted to None, where an unreliable frequency will be", "the License for the specific language governing permissions and #", "seasonality_mode for the Prophet model. e.g. hp.choice(['additive', 'multiplicative']). :param changepoint_range:", "value defaults to None, where 10% of training data will", "str(self._freq * expect_horizon) self.search_space.update({\"expect_horizon\": expect_horizon_str, \"cross_validation\": cross_validation}) train_data = data", "name: name of the AutoProphet. It defaults to \"auto_prophet\" :param", "freq=\"D\", ds_data=None): \"\"\" Predict using the best model after HPO.", "Apache License, Version 2.0 (the \"License\"); # you may not", "cpus for each trial. It defaults to 1. :param name:", "- data[\"ds\"].iloc[0] else: self._freq = pd.Timedelta(freq) expect_horizon_str = str(self._freq *", "need to set `freq` in fit.\" self._freq = data[\"ds\"].iloc[1] -", "forward to predict :param freq: the freqency of the predicted", "self.best_model.predict(horizon=horizon, freq=freq, ds_data=ds_data) def evaluate(self, data, metrics=['mse']): \"\"\" Evaluate using", "HPO. :param horizon: the number of steps forward to predict", "column 'ds' indicating date and column 'y' indicating value and", ":param ds_data: a dataframe that has 1 column 'ds' indicating", "\"\"\" if data is None: raise ValueError(\"Input invalid data of", "self.auto_est = AutoEstimator(model_builder=model_builder, logs_dir=logs_dir, resources_per_trial={\"cpu\": cpus_per_trial}, remote_dir=remote_dir, name=name) except ImportError:", "file \"\"\" if self.best_model.model is None: raise RuntimeError( \"You must", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "refer to https://facebook.github.io/prophet/docs/diagnostics.html#hyperparameter-tuning. :param changepoint_prior_scale: Int or hp sampling function", "def fit(self, data, cross_validation=True, expect_horizon=None, freq=None, metric_threshold=None, n_sampling=16, search_alg=None, search_alg_params=None,", "Save the best model after HPO. :param checkpoint_file: The location", "restore first before calling save!\") self.best_model.save(checkpoint_file) def restore(self, checkpoint_file): \"\"\"", "HPO. :param checkpoint_file: The checkpoint file location you want to", "checkpoint_file: The checkpoint file location you want to load the", "1. :param name: name of the AutoProphet. It defaults to", "Automatically fit the model and search for the best hyperparameters.", "value and Td is the time dimension :param cross_validation: bool,", "and results. It defaults to \"/tmp/auto_prophet_logs\" :param cpus_per_trial: Int. Number", "or restore first before calling save!\") self.best_model.save(checkpoint_file) def restore(self, checkpoint_file):", "freqency of the training dataframe. the frequency can be anything", "name of the AutoProphet. It defaults to \"auto_prophet\" :param remote_dir:", "None if cross_validation else data[len(data)-expect_horizon:] n_sampling = recalculate_n_sampling(self.search_space, n_sampling) if", "1 column 'ds' indicating date. \"\"\" if self.best_model.model is None:", "you need to set `freq` in fit.\" self._freq = data[\"ds\"].iloc[1]", "want to save the best model, should be a json", "validation_data=validation_data, metric=self.metric, metric_threshold=metric_threshold, n_sampling=n_sampling, search_space=self.search_space, search_alg=search_alg, search_alg_params=search_alg_params, scheduler=scheduler, scheduler_params=scheduler_params )", "0.95) if changepoint_range is None else changepoint_range } self.search_space.update(prophet_config) #", "of the Prophet model hyperparameters, refer to https://facebook.github.io/prophet/docs/diagnostics.html#hyperparameter-tuning. :param changepoint_prior_scale:", "should be in datetime 64 type, or you need to", "data if cross_validation else data[:len(data)-expect_horizon] validation_data = None if cross_validation", "want to load the best model. \"\"\" self.best_model.restore(checkpoint_file) def get_best_model(self):", "for the Prophet model. e.g. hp.uniform(0.8, 0.95). :param metric: String.", "if seasonality_prior_scale is None else seasonality_prior_scale, \"holidays_prior_scale\": hp.loguniform(0.01, 10) if", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "the License. # import pandas as pd import warnings from", "here: https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#timeseries-offset-aliases :param ds_data: a dataframe that has 1 column", "be taken as the validation data. :param freq: the freqency", "-1, (virtually) infinite samples are generated until a stopping condition", "HPO. :param checkpoint_file: The location you want to save the", "pd import warnings from bigdl.chronos.model.prophet import ProphetBuilder, ProphetModel from bigdl.chronos.autots.utils", "'ds' col should be in datetime 64 type, or you", "scheduler provided by ray tune :param scheduler_params: parameters for scheduler", "best config to fit a new prophet model on whole", "the freqency of the predicted dataframe, defaulted to day(\"D\"), the", "if the eval result comes from cross_validation. The value is", "the search space of the Prophet model hyperparameters. For details", "option to False to speed up the process. :param expect_horizon:", "logs_dir: Local directory to save logs and results. It defaults", "to optimize. e.g. \"mse\" :param logs_dir: Local directory to save", "# + # # Copyright 2016 The BigDL Authors. #", "after HPO. :param data: evaluation data, a pandas dataframe with", "model hyperparameters. For details of the Prophet model hyperparameters, refer", "is None else seasonality_prior_scale, \"holidays_prior_scale\": hp.loguniform(0.01, 10) if holidays_prior_scale is", "function from an integer space for hyperparameter changepoint_prior_scale for the", "search for the best hyperparameters. :param data: training data, a", "+ # # Copyright 2016 The BigDL Authors. # #", "cross_validation else data[len(data)-expect_horizon:] n_sampling = recalculate_n_sampling(self.search_space, n_sampling) if n_sampling !=", "to 16. If hp.grid_search is in search_space, the grid will", "best hyperparameters. :param data: training data, a pandas dataframe with", ":param search_alg_params: extra parameters for searcher algorithm besides search_space, metric", "\"License\"); # you may not use this file except in", "anything from the pandas list of frequency strings here: https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#timeseries-offset-aliases", "metric_threshold: a trial will be terminated when metric threshold is", "model. For hp sampling, see bigdl.chronos.orca.automl.hp for more details. e.g.", "the Prophet model. e.g. hp.loguniform(0.01, 10). :param seasonality_mode: hyperparameter seasonality_mode", "None, where an unreliable frequency will be infer implicitly. :param", "\"\"\" Restore the best model after HPO. :param checkpoint_file: The", "hyperparameter holidays_prior_scale for the Prophet model. e.g. hp.loguniform(0.01, 10). :param", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "model, should be a json file \"\"\" if self.best_model.model is", "0.05, 0.1, 0.5]) if changepoint_prior_scale is None else changepoint_prior_scale, \"seasonality_prior_scale\":", "search_alg=None, search_alg_params=None, scheduler=None, scheduler_params=None, ): \"\"\" Automatically fit the model", "checkpoint file location you want to load the best model.", "\"random\", \"ax\", \"dragonfly\", \"skopt\", \"hyperopt\", \"bayesopt\", \"bohb\", \"nevergrad\", \"optuna\", \"zoopt\"", "list of frequency strings here: https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#timeseries-offset-aliases :param ds_data: a dataframe", "data of None\") if self.best_model.model is None: raise RuntimeError( \"You", "None and doesn't take effects while running in local. While", "# distributed under the License is distributed on an \"AS", "String. The evaluation metric name to optimize. e.g. \"mse\" :param", "AutoEstimator(model_builder=model_builder, logs_dir=logs_dir, resources_per_trial={\"cpu\": cpus_per_trial}, remote_dir=remote_dir, name=name) except ImportError: warnings.warn(\"You need", "\"sigopt\") :param search_alg_params: extra parameters for searcher algorithm besides search_space,", "hp.uniform(0.8, 0.95) if changepoint_range is None else changepoint_range } self.search_space.update(prophet_config)", "use once the mode is fitted. The value defaults to", "# Unless required by applicable law or agreed to in", "A list contains metrics for test/valid data. \"\"\" if data", "import AutoEstimator import bigdl.orca.automl.hp as hp self.search_space = { \"changepoint_prior_scale\":", "data, and expect_horizon is the horizon you may need to", "result comes from cross_validation. The value is set to True", "\"/tmp/auto_prophet_logs\" :param cpus_per_trial: Int. Number of cpus for each trial.", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "load_dir: Load the ckpt from load_dir. The value defaults to", "expect_horizon_str = str(self._freq * expect_horizon) self.search_space.update({\"expect_horizon\": expect_horizon_str, \"cross_validation\": cross_validation}) train_data", "seasonality_prior_scale=None, holidays_prior_scale=None, seasonality_mode=None, changepoint_range=None, metric='mse', logs_dir=\"/tmp/auto_prophet_logs\", cpus_per_trial=1, name=\"auto_prophet\", remote_dir=None, load_dir=None,", "https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#timeseries-offset-aliases :param ds_data: a dataframe that has 1 column 'ds'", "metric: String. The evaluation metric name to optimize. e.g. \"mse\"", "save!\") self.best_model.save(checkpoint_file) def restore(self, checkpoint_file): \"\"\" Restore the best model", "need to specify either the exact value or the search", "You may obtain a copy of the License at #", "to None, where 10% of training data will be taken", "for the Prophet model. e.g. hp.choice(['additive', 'multiplicative']). :param changepoint_range: hyperparameter", "ANY KIND, either exp' # ress or implied. # See", "date and column 'y' indicating value and Td is the", "data will be automatically splited from training data, and expect_horizon", "run n_sampling of trials and round up n_sampling according to", "from the pandas list of frequency strings here: https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#timeseries-offset-aliases :param", "hyperparameters. :param data: training data, a pandas dataframe with Td", "is None: raise RuntimeError( \"You must call fit or restore", ":param horizon: the number of steps forward to predict :param", "or restore first before calling predict!\") return self.best_model.predict(horizon=horizon, freq=freq, ds_data=ds_data)", "calling predict!\") return self.best_model.predict(horizon=horizon, freq=freq, ds_data=ds_data) def evaluate(self, data, metrics=['mse']):", "speed up the process. :param expect_horizon: int, validation data will", "results and checkpoints. It defaults to None and doesn't take", "as the validation data. :param freq: the freqency of the", "data, metrics=['mse']): \"\"\" Evaluate using the best model after HPO.", "model. \"\"\" self.best_model.restore(checkpoint_file) def get_best_model(self): \"\"\" Get the best Prophet", "name to optimize. e.g. \"mse\" :param logs_dir: Local directory to", "location you want to save the best model, should be", "the training dataframe. the frequency can be anything from the", "the Apache License, Version 2.0 (the \"License\"); # you may", "be infer implicitly. :param metric_threshold: a trial will be terminated", "metric=self.metric, metric_threshold=metric_threshold, n_sampling=n_sampling, search_space=self.search_space, search_alg=search_alg, search_alg_params=search_alg_params, scheduler=scheduler, scheduler_params=scheduler_params ) #", "of the Prophet model hyperparameters. For details of the Prophet", "fit the model and search for the best hyperparameters. :param", "changepoint_prior_scale: Int or hp sampling function from an integer space", "details of the Prophet model hyperparameters, refer to https://facebook.github.io/prophet/docs/diagnostics.html#hyperparameter-tuning. :param", "'y' indicating value and Td is the time dimension :param", "terminated when metric threshold is met :param n_sampling: Number of", "changepoint_prior_scale for the Prophet model. For hp sampling, see bigdl.chronos.orca.automl.hp", "config to fit a new prophet model on whole data" ]
[ "diagonal = -1) + \\ torch.diag(torch.ones(self.dim)) U = torch.triu(self.U, diagonal", "if i == 0: mu, alpha = self.initial_param[0], self.initial_param[1] else:", "= base_network(dim // 2, dim // 2, hidden_dim) self.s2 =", "s1_transformed = self.s1(lower) upper = t1_transformed + upper * torch.exp(s1_transformed)", "(torch.exp(self.log_alpha) + r) ** 2) return z, log_det class FCNN(nn.Module):", "init.uniform_(self.w, -math.sqrt(1/dim), math.sqrt(1/dim)) init.uniform_(self.u, -math.sqrt(1/dim), math.sqrt(1/dim)) init.uniform_(self.b, -math.sqrt(1/dim), math.sqrt(1/dim)) def", "-torch.sum(torch.log(torch.abs(self.S))) return x, log_det class NSF_AR(nn.Module): \"\"\" Neural spline flow,", "log_det += torch.sum(ld, dim = 1) out = self.f2(upper).reshape(-1, self.dim", "- 1 u = self.u + scal * self.w /", "lower, ld = unconstrained_RQS( lower, W, H, D, inverse=False, tail_bound=self.B)", "log_det = torch.zeros(x.shape[0]) for i in range(self.dim): if i ==", "torch.exp(self.log_sigma) log_det = -torch.sum(self.log_sigma) return x, log_det class OneByOneConv(nn.Module): \"\"\"", "sp.linalg.lu(W) self.P = torch.tensor(P, dtype = torch.float) self.L = nn.Parameter(torch.tensor(L,", "= 1), torch.softmax(H, dim = 1) W, H = 2", "= = x + β h(α, r)(z − z0) [Rezende", "nn.Tanh(), nn.Linear(hidden_dim, out_dim), ) def forward(self, x): return self.network(x) class", "z = x @ self.P @ L @ (U +", "ld = unconstrained_RQS( upper, W, H, D, inverse = True,", "self.B * H D = F.softplus(D) x[:, i], ld =", "2, 3 * self.K - 1) W, H, D =", "// 2, hidden_dim) self.f2 = base_network(dim // 2, (3 *", "= nn.ModuleList() self.init_param = nn.Parameter(torch.Tensor(3 * K - 1)) for", "- 1 / 2, 1 / 2) def forward(self, x):", "z = f(x) = = x + β h(α, r)(z", "0).type(torch.FloatTensor) + \\ (x < 0).type(torch.FloatTensor) * torch.exp(x) } class", "log|df/dx|. Returns ------- \"\"\" if self.h in (F.elu, F.leaky_relu): u", "backward(self, z): lower, upper = z[:,:self.dim // 2], z[:,self.dim //", "F.softplus(D) z[:, i], ld = unconstrained_RQS( x[:, i], W, H,", "K self.B = B self.layers = nn.ModuleList() self.init_param = nn.Parameter(torch.Tensor(3", "+ torch.log(1 + torch.exp(self.beta)) z = x + beta *", "hidden_dim)] self.reset_parameters() def reset_parameters(self): init.uniform_(self.init_param, - 1 / 2, 1", "i] log_det += alpha return x, log_det class ActNorm(nn.Module): \"\"\"", "x + beta * h * (x - self.x0) log_det", "torch.exp(-s1_transformed) x = torch.cat([lower, upper], dim=1) log_det = torch.sum(-s1_transformed, dim=1)", "log_det = torch.zeros(z.shape[0]) for i in range(self.dim): if i ==", "base_network(dim // 2, dim // 2, hidden_dim) def forward(self, x):", "dim = 1) return torch.cat([lower, upper], dim = 1), log_det", "log-determinant log|df/dx|. \"\"\" m, n = x.shape r = torch.norm(x", "= 1) return torch.cat([lower, upper], dim = 1), log_det def", "beta * h) + \\ torch.log(1 + beta * h", "= functional_derivatives[self.h](lin) * self.w log_det = torch.log(torch.abs(1 + phi @", "torch.diag(self.S)) log_det = torch.sum(torch.log(torch.abs(self.S))) return z, log_det def backward(self, z):", "hidden_dim = 8, base_network=FCNN): super().__init__() self.dim = dim self.layers =", "the function must be invertible functional_derivatives = { torch.tanh: lambda", "@ self.W_inv log_det = -torch.sum(torch.log(torch.abs(self.S))) return x, log_det class NSF_AR(nn.Module):", "dim=1) log_det = torch.sum(-s1_transformed, dim=1) + \\ torch.sum(-s2_transformed, dim=1) return", "in range(1, dim): self.layers += [base_network(i, 2, hidden_dim)] self.reset_parameters() def", "0).type(torch.FloatTensor) + \\ (x < 0).type(torch.FloatTensor) * -0.01, F.elu: lambda", "nn.Linear(in_dim, hidden_dim), nn.Tanh(), nn.Linear(hidden_dim, hidden_dim), nn.Tanh(), nn.Linear(hidden_dim, out_dim), ) def", "W, _ = sp.linalg.qr(np.random.randn(dim, dim)) P, L, U = sp.linalg.lu(W)", "* torch.exp(-s1_transformed) x = torch.cat([lower, upper], dim=1) log_det = torch.sum(-s1_transformed,", "forward(self, x): z = x * torch.exp(self.log_sigma) + self.mu log_det", "log_det class MAF(nn.Module): \"\"\" Masked auto-regressive flow. [Papamakarios et al.", "torch.nn.functional as F from nf.utils import unconstrained_RQS # supported non-linearities:", "@ self.u)) - self.w @ self.u - 1 u =", "/ torch.exp(self.log_sigma) log_det = -torch.sum(self.log_sigma) return x, log_det class OneByOneConv(nn.Module):", "self.B * H D = F.softplus(D) upper, ld = unconstrained_RQS(", "self.initial_param = nn.Parameter(torch.Tensor(2)) for i in range(1, dim): self.layers +=", "= 1 / (torch.exp(self.log_alpha) + r) beta = -torch.exp(self.log_alpha) +", "import torch.nn.init as init import torch.nn.functional as F from nf.utils", "[base_network(i, 2, hidden_dim)] self.reset_parameters() def reset_parameters(self): init.uniform_(self.initial_param, -math.sqrt(0.5), math.sqrt(0.5)) def", "* dim // 2, hidden_dim) def forward(self, x): log_det =", "= x.shape r = torch.norm(x - self.x0) h = 1", "* H D = F.softplus(D) lower, ld = unconstrained_RQS( lower,", "hidden_dim) def forward(self, x): log_det = torch.zeros(x.shape[0]) lower, upper =", "self.b = nn.Parameter(torch.Tensor(1)) self.reset_parameters(dim) def reset_parameters(self, dim): init.uniform_(self.w, -math.sqrt(1/dim), math.sqrt(1/dim))", "log_det def backward(self, z): log_det = torch.zeros(z.shape[0]) lower, upper =", "+ lower * torch.exp(s2_transformed) z = torch.cat([lower, upper], dim=1) log_det", "self.reset_parameters() def reset_parameters(self): init.uniform_(self.initial_param, -math.sqrt(0.5), math.sqrt(0.5)) def forward(self, x): z", "+= ld return x, log_det class NSF_CL(nn.Module): \"\"\" Neural spline", "< 0).type(torch.FloatTensor) * -0.01, F.elu: lambda x: (x > 0).type(torch.FloatTensor)", "= 1) W = self.P @ L @ (U +", "x: 1 - torch.pow(torch.tanh(x), 2), F.leaky_relu: lambda x: (x >", "self.layers += [base_network(i, 2, hidden_dim)] self.reset_parameters() def reset_parameters(self): init.uniform_(self.initial_param, -math.sqrt(0.5),", "dim = 2) W, H = 2 * self.B *", "z, log_det def backward(self, z): x = (z - self.mu)", "nn.Parameter(torch.Tensor(1)) def reset_parameters(dim): init.uniform_(self.z0, -math.sqrt(1/dim), math.sqrt(1/dim)) init.uniform_(self.log_alpha, -math.sqrt(1/dim), math.sqrt(1/dim)) init.uniform_(self.beta,", "h = 1 / (torch.exp(self.log_alpha) + r) beta = -torch.exp(self.log_alpha)", "(3 * K - 1) * dim // 2, hidden_dim)", "init.uniform_(self.z0, -math.sqrt(1/dim), math.sqrt(1/dim)) init.uniform_(self.log_alpha, -math.sqrt(1/dim), math.sqrt(1/dim)) init.uniform_(self.beta, -math.sqrt(1/dim), math.sqrt(1/dim)) def", "+ r) beta = -torch.exp(self.log_alpha) + torch.log(1 + torch.exp(self.beta)) z", "super().__init__() self.network = nn.Sequential( nn.Linear(in_dim, hidden_dim), nn.Tanh(), nn.Linear(hidden_dim, hidden_dim), nn.Tanh(),", "dtype = torch.float), diagonal = 1)) self.W_inv = None def", "{ torch.tanh: lambda x: 1 - torch.pow(torch.tanh(x), 2), F.leaky_relu: lambda", "preserving flow. [Dinh et. al. 2017] \"\"\" def __init__(self, dim,", "== 0: init_param = self.init_param.expand(x.shape[0], 3 * self.K - 1)", "= unconstrained_RQS( lower, W, H, D, inverse=True, tail_bound=self.B) log_det +=", "in_dim, out_dim, hidden_dim): super().__init__() self.network = nn.Sequential( nn.Linear(in_dim, hidden_dim), nn.Tanh(),", "W, 2 * self.B * H D = F.softplus(D) x[:,", "lower, upper = z[:, :self.dim // 2], z[:, self.dim //", "upper, ld = unconstrained_RQS( upper, W, H, D, inverse =", "auto-regressive flow. [Papamakarios et al. 2018] \"\"\" def __init__(self, dim,", "backward(self, z): log_det = torch.zeros(z.shape[0]) lower, upper = z[:, :self.dim", "z, log_det def backward(self, z): lower, upper = z[:,:self.dim //", "= 2) W, H = torch.softmax(W, dim = 2), torch.softmax(H,", "u) + 1e-4) return z, log_det def backward(self, z): raise", "alpha = out[:, 0], out[:, 1] z[:, i] = (x[:,", "z0) [Rezende and Mohamed 2015] \"\"\" def __init__(self, dim): super().__init__()", "= (x[:, i] - mu) / torch.exp(alpha) log_det -= alpha", "def __init__(self, in_dim, out_dim, hidden_dim): super().__init__() self.network = nn.Sequential( nn.Linear(in_dim,", "base_network = FCNN): super().__init__() self.dim = dim self.K = K", "r / (torch.exp(self.log_alpha) + r) ** 2) return z, log_det", "out[:, 0], out[:, 1] x[:, i] = mu + torch.exp(alpha)", "nn.Parameter(torch.Tensor(dim)) self.u = nn.Parameter(torch.Tensor(dim)) self.b = nn.Parameter(torch.Tensor(1)) self.reset_parameters(dim) def reset_parameters(self,", "+ r) ** 2) return z, log_det class FCNN(nn.Module): \"\"\"", "torch.sum(ld, dim = 1) out = self.f1(lower).reshape(-1, self.dim // 2,", "self.u elif self.h == torch.tanh: scal = torch.log(1+torch.exp(self.w @ self.u))", "8, base_network=FCNN): super().__init__() self.dim = dim self.layers = nn.ModuleList() self.initial_param", "} class Planar(nn.Module): \"\"\" Planar flow. z = f(x) =", "NSF_AR(nn.Module): \"\"\" Neural spline flow, auto-regressive. [Durkan et al. 2019]", "Dhariwal, 2018.] \"\"\" def __init__(self, dim): super().__init__() self.dim = dim", "* self.B * H D = F.softplus(D) upper, ld =", "= nn.Parameter(torch.Tensor(2)) for i in range(1, dim): self.layers += [base_network(i,", "= torch.float) self.L = nn.Parameter(torch.tensor(L, dtype = torch.float)) self.S =", "spline flow, coupling layer. [Durkan et al. 2019] \"\"\" def", "i] - mu) / torch.exp(alpha) log_det -= alpha return z.flip(dims=(1,)),", "// 2, dim // 2, hidden_dim) def forward(self, x): lower,", "1) + self.b z = x + u * self.h(lin)", "z[:, i] log_det += alpha return x, log_det class ActNorm(nn.Module):", "__init__(self, dim): super().__init__() self.x0 = nn.Parameter(torch.Tensor(dim)) self.log_alpha = nn.Parameter(torch.Tensor(1)) self.beta", "F.softplus(D) upper, ld = unconstrained_RQS( upper, W, H, D, inverse", "self.f2 = base_network(dim // 2, (3 * K - 1)", "self.K, dim = 2) W, H = torch.softmax(W, dim =", "import unconstrained_RQS # supported non-linearities: note that the function must", "-1) + torch.diag(torch.ones(self.dim)) U = torch.triu(self.U, diagonal = 1) z", "[base_network(i, 3 * K - 1, hidden_dim)] self.reset_parameters() def reset_parameters(self):", "nn.ModuleList() self.init_param = nn.Parameter(torch.Tensor(3 * K - 1)) for i", "0: mu, alpha = self.initial_param[0], self.initial_param[1] else: out = self.layers[i", "self.x0) h = 1 / (torch.exp(self.log_alpha) + r) beta =", "= x * torch.exp(self.log_sigma) + self.mu log_det = torch.sum(self.log_sigma) return", "- 1](x[:, :i]) W, H, D = torch.split(out, self.K, dim", "// 2:] t2_transformed = self.t2(upper) s2_transformed = self.s2(upper) lower =", "W, H, D, inverse=True, tail_bound=self.B) log_det += torch.sum(ld, dim =", "hidden_dim) def forward(self, x): lower, upper = x[:,:self.dim // 2],", "self.h(lin) phi = functional_derivatives[self.h](lin) * self.w log_det = torch.log(torch.abs(1 +", "torch.log(1 + beta * h - \\ beta * r", "m, n = x.shape r = torch.norm(x - self.x0) h", "3 * K - 1, hidden_dim)] self.reset_parameters() def reset_parameters(self): init.uniform_(self.init_param,", "else: out = self.layers[i - 1](x[:, :i]) mu, alpha =", "H, D, inverse = True, tail_bound = self.B) log_det +=", "(F.elu, F.leaky_relu): u = self.u elif self.h == torch.tanh: scal", "def reset_parameters(self, dim): init.uniform_(self.w, -math.sqrt(1/dim), math.sqrt(1/dim)) init.uniform_(self.u, -math.sqrt(1/dim), math.sqrt(1/dim)) init.uniform_(self.b,", "F.softplus(D) lower, ld = unconstrained_RQS( lower, W, H, D, inverse=True,", "- torch.pow(torch.tanh(x), 2), F.leaky_relu: lambda x: (x > 0).type(torch.FloatTensor) +", "x, log_det class NSF_AR(nn.Module): \"\"\" Neural spline flow, auto-regressive. [Durkan", "/ 2) def forward(self, x): z = torch.zeros_like(x) log_det =", "= torch.triu(self.U, diagonal = 1) z = x @ self.P", "RealNVP(nn.Module): \"\"\" Non-volume preserving flow. [Dinh et. al. 2017] \"\"\"", "\"\"\" ActNorm layer. [Kingma and Dhariwal, 2018.] \"\"\" def __init__(self,", "self.t1(lower) s1_transformed = self.s1(lower) upper = (upper - t1_transformed) *", "2, hidden_dim) self.t2 = base_network(dim // 2, dim // 2,", "dim, hidden_dim = 8, base_network=FCNN): super().__init__() self.dim = dim self.layers", "def backward(self, z): x = torch.zeros_like(z) log_det = torch.zeros(x.shape[0]) for", "+ \\ torch.sum(s2_transformed, dim=1) return z, log_det def backward(self, z):", "= self.s2(upper) lower = t2_transformed + lower * torch.exp(s2_transformed) z", "fully connected neural network. \"\"\" def __init__(self, in_dim, out_dim, hidden_dim):", "al. 2018] \"\"\" def __init__(self, dim, hidden_dim = 8, base_network=FCNN):", "s2_transformed = self.s2(upper) lower = t2_transformed + lower * torch.exp(s2_transformed)", "[Kingma and Dhariwal, 2018.] \"\"\" def __init__(self, dim): super().__init__() self.dim", "def reset_parameters(self): init.uniform_(self.initial_param, -math.sqrt(0.5), math.sqrt(0.5)) def forward(self, x): z =", "init.uniform_(self.initial_param, -math.sqrt(0.5), math.sqrt(0.5)) def forward(self, x): z = torch.zeros_like(x) log_det", "= self.layers[i - 1](x[:, :i]) W, H, D = torch.split(out,", "- 1) W, H, D = torch.split(out, self.K, dim =", "is not supported.\") lin = torch.unsqueeze(x @ self.w, 1) +", "= torch.tril(self.L, diagonal = -1) + \\ torch.diag(torch.ones(self.dim)) U =", "= nn.ModuleList() self.initial_param = nn.Parameter(torch.Tensor(2)) for i in range(1, dim):", "upper], dim=1) log_det = torch.sum(s1_transformed, dim=1) + \\ torch.sum(s2_transformed, dim=1)", "0: init_param = self.init_param.expand(x.shape[0], 3 * self.K - 1) W,", "x): z = x * torch.exp(self.log_sigma) + self.mu log_det =", "F.softplus(D) x[:, i], ld = unconstrained_RQS( z[:, i], W, H,", "ld = unconstrained_RQS( lower, W, H, D, inverse=True, tail_bound=self.B) log_det", "convolution. [Kingma and Dhariwal, 2018.] \"\"\" def __init__(self, dim): super().__init__()", "returns z and the log-determinant log|df/dx|. Returns ------- \"\"\" if", "torch.inverse(W) x = z @ self.W_inv log_det = -torch.sum(torch.log(torch.abs(self.S))) return", "import scipy.linalg import torch import torch.nn as nn import torch.nn.init", "upper = t1_transformed + upper * torch.exp(s1_transformed) t2_transformed = self.t2(upper)", "F.leaky_relu): u = self.u elif self.h == torch.tanh: scal =", "1, hidden_dim)] self.reset_parameters() def reset_parameters(self): init.uniform_(self.init_param, - 1 / 2,", "flow. [Dinh et. al. 2017] \"\"\" def __init__(self, dim, hidden_dim", "1 - torch.pow(torch.tanh(x), 2), F.leaky_relu: lambda x: (x > 0).type(torch.FloatTensor)", "inverse=True, tail_bound=self.B) log_det += torch.sum(ld, dim = 1) out =", "z, log_det class FCNN(nn.Module): \"\"\" Simple fully connected neural network.", "i == 0: mu, alpha = self.initial_param[0], self.initial_param[1] else: out", "2015] \"\"\" def __init__(self, dim, nonlinearity=torch.tanh): super().__init__() self.h = nonlinearity", "W, 2 * self.B * H D = F.softplus(D) lower,", "forward(self, x): z = torch.zeros_like(x) log_det = torch.zeros(z.shape[0]) for i", "out = self.f1(lower).reshape(-1, self.dim // 2, 3 * self.K -", "dim): super().__init__() self.dim = dim W, _ = sp.linalg.qr(np.random.randn(dim, dim))", "self.t2(upper) s2_transformed = self.s2(upper) lower = (lower - t2_transformed) *", "- self.x0) h = 1 / (torch.exp(self.log_alpha) + r) beta", "* self.B * H D = F.softplus(D) z[:, i], ld", "= nonlinearity self.w = nn.Parameter(torch.Tensor(dim)) self.u = nn.Parameter(torch.Tensor(dim)) self.b =", "dim = 2), torch.softmax(H, dim = 2) W, H =", "log_det += torch.sum(ld, dim = 1) return torch.cat([lower, upper], dim", "Non-volume preserving flow. [Dinh et. al. 2017] \"\"\" def __init__(self,", "self.beta = nn.Parameter(torch.Tensor(1)) def reset_parameters(dim): init.uniform_(self.z0, -math.sqrt(1/dim), math.sqrt(1/dim)) init.uniform_(self.log_alpha, -math.sqrt(1/dim),", "self.log_alpha = nn.Parameter(torch.Tensor(1)) self.beta = nn.Parameter(torch.Tensor(1)) def reset_parameters(dim): init.uniform_(self.z0, -math.sqrt(1/dim),", "(lower - t2_transformed) * torch.exp(-s2_transformed) t1_transformed = self.t1(lower) s1_transformed =", "nonlinearity=torch.tanh): super().__init__() self.h = nonlinearity self.w = nn.Parameter(torch.Tensor(dim)) self.u =", ") def forward(self, x): return self.network(x) class RealNVP(nn.Module): \"\"\" Non-volume", "2, dim // 2, hidden_dim) self.s2 = base_network(dim // 2,", "= torch.zeros(x.shape[0]) for i in range(self.dim): if i == 0:", "sp.linalg.qr(np.random.randn(dim, dim)) P, L, U = sp.linalg.lu(W) self.P = torch.tensor(P,", "out[:, 1] x[:, i] = mu + torch.exp(alpha) * z[:,", "1) * dim // 2, hidden_dim) def forward(self, x): log_det", "class OneByOneConv(nn.Module): \"\"\" Invertible 1x1 convolution. [Kingma and Dhariwal, 2018.]", "* torch.exp(x) } class Planar(nn.Module): \"\"\" Planar flow. z =", "1 / (torch.exp(self.log_alpha) + r) beta = -torch.exp(self.log_alpha) + torch.log(1", "upper, ld = unconstrained_RQS( upper, W, H, D, inverse=False, tail_bound=self.B)", "= 1) W, H = 2 * self.B * W,", "self.t2 = base_network(dim // 2, dim // 2, hidden_dim) self.s2", "/ (torch.exp(self.log_alpha) + r) beta = -torch.exp(self.log_alpha) + torch.log(1 +", "x, returns z and the log-determinant log|df/dx|. \"\"\" m, n", "dim): init.uniform_(self.w, -math.sqrt(1/dim), math.sqrt(1/dim)) init.uniform_(self.u, -math.sqrt(1/dim), math.sqrt(1/dim)) init.uniform_(self.b, -math.sqrt(1/dim), math.sqrt(1/dim))", "3, hidden_dim = 8, base_network = FCNN): super().__init__() self.dim =", "returns z and the log-determinant log|df/dx|. \"\"\" m, n =", "3 * self.K - 1) W, H, D = torch.split(out,", "layer. [Durkan et al. 2019] \"\"\" def __init__(self, dim, K", "unconstrained_RQS( upper, W, H, D, inverse = True, tail_bound =", "MAF(nn.Module): \"\"\" Masked auto-regressive flow. [Papamakarios et al. 2018] \"\"\"", "backward(self, z): x = (z - self.mu) / torch.exp(self.log_sigma) log_det", "torch.pow(torch.tanh(x), 2), F.leaky_relu: lambda x: (x > 0).type(torch.FloatTensor) + \\", "invertible functional_derivatives = { torch.tanh: lambda x: 1 - torch.pow(torch.tanh(x),", "dim=1) return z, log_det def backward(self, z): lower, upper =", "unconstrained_RQS( lower, W, H, D, inverse=False, tail_bound=self.B) log_det += torch.sum(ld,", "/ torch.norm(self.w) else: raise NotImplementedError(\"Non-linearity is not supported.\") lin =", "mu, alpha = out[:, 0], out[:, 1] x[:, i] =", "= None def forward(self, x): L = torch.tril(self.L, diagonal =", "* W, 2 * self.B * H D = F.softplus(D)", "i in range(self.dim): if i == 0: mu, alpha =", "return x, log_det class NSF_AR(nn.Module): \"\"\" Neural spline flow, auto-regressive.", "* torch.exp(self.log_sigma) + self.mu log_det = torch.sum(self.log_sigma) return z, log_det", "torch.sum(ld, dim = 1) return torch.cat([lower, upper], dim = 1),", "@ L @ (U + torch.diag(self.S)) self.W_inv = torch.inverse(W) x", "W, H = 2 * self.B * W, 2 *", "torch.zeros(z.shape[0]) lower, upper = z[:, :self.dim // 2], z[:, self.dim", "1 / 2) def forward(self, x): z = torch.zeros_like(x) log_det", "nn.Parameter(torch.triu(torch.tensor(U, dtype = torch.float), diagonal = 1)) self.W_inv = None", "hidden_dim), nn.Tanh(), nn.Linear(hidden_dim, out_dim), ) def forward(self, x): return self.network(x)", "P, L, U = sp.linalg.lu(W) self.P = torch.tensor(P, dtype =", "self.x0) log_det = (n - 1) * torch.log(1 + beta", "def __init__(self, dim): super().__init__() self.dim = dim W, _ =", "dim = 1) out = self.f2(upper).reshape(-1, self.dim // 2, 3", "D, inverse=False, tail_bound=self.B) log_det += ld return z, log_det def", "lower, ld = unconstrained_RQS( lower, W, H, D, inverse=True, tail_bound=self.B)", "raise NotImplementedError(\"Planar flow has no algebraic inverse.\") class Radial(nn.Module): \"\"\"", "= z[:, :self.dim // 2], z[:, self.dim // 2:] out", "= z.flip(dims=(1,)) for i in range(self.dim): if i == 0:", "tail_bound = self.B) log_det += ld return x, log_det class", "x[:, :self.dim // 2], x[:, self.dim // 2:] out =", "self.s1(lower) upper = (upper - t1_transformed) * torch.exp(-s1_transformed) x =", "x[:, i], W, H, D, inverse=False, tail_bound=self.B) log_det += ld", "= unconstrained_RQS( z[:, i], W, H, D, inverse = True,", "* torch.exp(s2_transformed) z = torch.cat([lower, upper], dim=1) log_det = torch.sum(s1_transformed,", "- mu) / torch.exp(alpha) log_det -= alpha return z.flip(dims=(1,)), log_det", "def forward(self, x): z = x * torch.exp(self.log_sigma) + self.mu", "ActNorm layer. [Kingma and Dhariwal, 2018.] \"\"\" def __init__(self, dim):", "1) z = x @ self.P @ L @ (U", "base_network(dim // 2, dim // 2, hidden_dim) self.s1 = base_network(dim", "= self.t2(upper) s2_transformed = self.s2(upper) lower = t2_transformed + lower", "torch.norm(self.w) else: raise NotImplementedError(\"Non-linearity is not supported.\") lin = torch.unsqueeze(x", "in range(1, dim): self.layers += [base_network(i, 3 * K -", "i], ld = unconstrained_RQS( x[:, i], W, H, D, inverse=False,", "forward(self, x): L = torch.tril(self.L, diagonal = -1) + torch.diag(torch.ones(self.dim))", ":i]) mu, alpha = out[:, 0], out[:, 1] x[:, i]", "\\ torch.diag(torch.ones(self.dim)) U = torch.triu(self.U, diagonal = 1) W =", "dim self.mu = nn.Parameter(torch.zeros(dim, dtype = torch.float)) self.log_sigma = nn.Parameter(torch.zeros(dim,", "@ self.u - 1 u = self.u + scal *", "2:] out = self.f2(upper).reshape(-1, self.dim // 2, 3 * self.K", "** 2) return z, log_det class FCNN(nn.Module): \"\"\" Simple fully", "= torch.log(1+torch.exp(self.w @ self.u)) - self.w @ self.u - 1", "* torch.exp(s1_transformed) t2_transformed = self.t2(upper) s2_transformed = self.s2(upper) lower =", "dim): super().__init__() self.dim = dim self.mu = nn.Parameter(torch.zeros(dim, dtype =", "as sp import scipy.linalg import torch import torch.nn as nn", "def __init__(self, dim, K = 5, B = 3, hidden_dim", "Returns ------- \"\"\" if self.h in (F.elu, F.leaky_relu): u =", "self.log_sigma = nn.Parameter(torch.zeros(dim, dtype = torch.float)) def forward(self, x): z", "nn.Parameter(torch.Tensor(1)) self.reset_parameters(dim) def reset_parameters(self, dim): init.uniform_(self.w, -math.sqrt(1/dim), math.sqrt(1/dim)) init.uniform_(self.u, -math.sqrt(1/dim),", "* self.B * H D = F.softplus(D) x[:, i], ld", "no algebraic inverse.\") class Radial(nn.Module): \"\"\" Radial flow. z =", "= self.u + scal * self.w / torch.norm(self.w) else: raise", "for i in range(1, dim): self.layers += [base_network(i, 3 *", "// 2, dim // 2, hidden_dim) self.s1 = base_network(dim //", "2), torch.softmax(H, dim = 2) W, H = 2 *", "= torch.tensor(P, dtype = torch.float) self.L = nn.Parameter(torch.tensor(L, dtype =", "dim = 2) W, H = torch.softmax(W, dim = 2),", "= mu + torch.exp(alpha) * z[:, i] log_det += alpha", "-math.sqrt(1/dim), math.sqrt(1/dim)) init.uniform_(self.beta, -math.sqrt(1/dim), math.sqrt(1/dim)) def forward(self, x): \"\"\" Given", "= nn.Parameter(torch.zeros(dim, dtype = torch.float)) def forward(self, x): z =", "= out[:, 0], out[:, 1] x[:, i] = mu +", "z): raise NotImplementedError(\"Planar flow has no algebraic inverse.\") class Radial(nn.Module):", "torch.tanh: lambda x: 1 - torch.pow(torch.tanh(x), 2), F.leaky_relu: lambda x:", "2, dim // 2, hidden_dim) self.s1 = base_network(dim // 2,", "nn.Linear(hidden_dim, hidden_dim), nn.Tanh(), nn.Linear(hidden_dim, out_dim), ) def forward(self, x): return", "// 2, 3 * self.K - 1) W, H, D", "dim // 2, hidden_dim) def forward(self, x): log_det = torch.zeros(x.shape[0])", "diagonal = 1)) self.W_inv = None def forward(self, x): L", "i] = (x[:, i] - mu) / torch.exp(alpha) log_det -=", "- \\ beta * r / (torch.exp(self.log_alpha) + r) **", "upper], dim = 1), log_det def backward(self, z): log_det =", "self.layers += [base_network(i, 3 * K - 1, hidden_dim)] self.reset_parameters()", "log_det def backward(self, z): x = torch.zeros_like(z) log_det = torch.zeros(x.shape[0])", "forward(self, x): log_det = torch.zeros(x.shape[0]) lower, upper = x[:, :self.dim", "= 8, base_network=FCNN): super().__init__() self.dim = dim self.t1 = base_network(dim", "torch.float), diagonal = 1)) self.W_inv = None def forward(self, x):", "// 2, dim // 2, hidden_dim) self.t2 = base_network(dim //", "= sp.linalg.lu(W) self.P = torch.tensor(P, dtype = torch.float) self.L =", "self.network = nn.Sequential( nn.Linear(in_dim, hidden_dim), nn.Tanh(), nn.Linear(hidden_dim, hidden_dim), nn.Tanh(), nn.Linear(hidden_dim,", "hidden_dim): super().__init__() self.network = nn.Sequential( nn.Linear(in_dim, hidden_dim), nn.Tanh(), nn.Linear(hidden_dim, hidden_dim),", "log_det += ld return x, log_det class NSF_CL(nn.Module): \"\"\" Neural", "upper = z[:, :self.dim // 2], z[:, self.dim // 2:]", "W, H, D = torch.split(init_param, self.K, dim = 1) else:", "log-determinant log|df/dx|. Returns ------- \"\"\" if self.h in (F.elu, F.leaky_relu):", "nn.Parameter(torch.Tensor(dim)) self.log_alpha = nn.Parameter(torch.Tensor(1)) self.beta = nn.Parameter(torch.Tensor(1)) def reset_parameters(dim): init.uniform_(self.z0,", "flow. [Papamakarios et al. 2018] \"\"\" def __init__(self, dim, hidden_dim", "0], out[:, 1] x[:, i] = mu + torch.exp(alpha) *", "torch.exp(-s2_transformed) t1_transformed = self.t1(lower) s1_transformed = self.s1(lower) upper = (upper", "s2_transformed = self.s2(upper) lower = (lower - t2_transformed) * torch.exp(-s2_transformed)", "self.P = torch.tensor(P, dtype = torch.float) self.L = nn.Parameter(torch.tensor(L, dtype", "log_det = torch.sum(-s1_transformed, dim=1) + \\ torch.sum(-s2_transformed, dim=1) return x,", "+ self.mu log_det = torch.sum(self.log_sigma) return z, log_det def backward(self,", "algebraic inverse.\") class Radial(nn.Module): \"\"\" Radial flow. z = f(x)", "supported.\") lin = torch.unsqueeze(x @ self.w, 1) + self.b z", "nonlinearity self.w = nn.Parameter(torch.Tensor(dim)) self.u = nn.Parameter(torch.Tensor(dim)) self.b = nn.Parameter(torch.Tensor(1))", "def forward(self, x): lower, upper = x[:,:self.dim // 2], x[:,self.dim", "as F from nf.utils import unconstrained_RQS # supported non-linearities: note", "1x1 convolution. [Kingma and Dhariwal, 2018.] \"\"\" def __init__(self, dim):", "\"\"\" def __init__(self, dim, K = 5, B = 3,", "torch.log(torch.abs(1 + phi @ u) + 1e-4) return z, log_det", "\"\"\" Given x, returns z and the log-determinant log|df/dx|. Returns", "H, D = torch.split(out, self.K, dim = 1) W, H", "= nn.Parameter(torch.Tensor(dim)) self.log_alpha = nn.Parameter(torch.Tensor(1)) self.beta = nn.Parameter(torch.Tensor(1)) def reset_parameters(dim):", "x[:, i], ld = unconstrained_RQS( z[:, i], W, H, D,", "i], W, H, D, inverse=False, tail_bound=self.B) log_det += ld return", "log_det = torch.sum(s1_transformed, dim=1) + \\ torch.sum(s2_transformed, dim=1) return z,", "= out[:, 0], out[:, 1] z[:, i] = (x[:, i]", "= B self.layers = nn.ModuleList() self.init_param = nn.Parameter(torch.Tensor(3 * K", "= nn.Parameter(torch.Tensor(dim)) self.u = nn.Parameter(torch.Tensor(dim)) self.b = nn.Parameter(torch.Tensor(1)) self.reset_parameters(dim) def", "0).type(torch.FloatTensor) * torch.exp(x) } class Planar(nn.Module): \"\"\" Planar flow. z", "\"\"\" m, n = x.shape r = torch.norm(x - self.x0)", "F from nf.utils import unconstrained_RQS # supported non-linearities: note that", "= x + u h(wᵀx + b) [<NAME> Mohamed, 2015]", "class Planar(nn.Module): \"\"\" Planar flow. z = f(x) = x", "= torch.zeros(z.shape[0]) z = z.flip(dims=(1,)) for i in range(self.dim): if", "= nn.Parameter(torch.tensor(L, dtype = torch.float)) self.S = nn.Parameter(torch.tensor(np.diag(U), dtype =", "torch.cat([lower, upper], dim=1) log_det = torch.sum(-s1_transformed, dim=1) + \\ torch.sum(-s2_transformed,", "= 1) W, H = torch.softmax(W, dim = 1), torch.softmax(H,", "upper, W, H, D, inverse=False, tail_bound=self.B) log_det += torch.sum(ld, dim", "def __init__(self, dim, nonlinearity=torch.tanh): super().__init__() self.h = nonlinearity self.w =", "= -torch.exp(self.log_alpha) + torch.log(1 + torch.exp(self.beta)) z = x +", "+= ld return z, log_det def backward(self, z): x =", "x[:, i] = mu + torch.exp(alpha) * z[:, i] log_det", "torch.tanh: scal = torch.log(1+torch.exp(self.w @ self.u)) - self.w @ self.u", "2 * self.B * H D = F.softplus(D) z[:, i],", "self.K = K self.B = B self.layers = nn.ModuleList() self.init_param", "2:] t1_transformed = self.t1(lower) s1_transformed = self.s1(lower) upper = t1_transformed", "x = torch.cat([lower, upper], dim=1) log_det = torch.sum(-s1_transformed, dim=1) +", "= torch.sum(s1_transformed, dim=1) + \\ torch.sum(s2_transformed, dim=1) return z, log_det", "_ = sp.linalg.qr(np.random.randn(dim, dim)) P, L, U = sp.linalg.lu(W) self.P", "nn.Tanh(), nn.Linear(hidden_dim, hidden_dim), nn.Tanh(), nn.Linear(hidden_dim, out_dim), ) def forward(self, x):", "@ u) + 1e-4) return z, log_det def backward(self, z):", "x): log_det = torch.zeros(x.shape[0]) lower, upper = x[:, :self.dim //", "h * (x - self.x0) log_det = (n - 1)", "t1_transformed) * torch.exp(-s1_transformed) x = torch.cat([lower, upper], dim=1) log_det =", "class ActNorm(nn.Module): \"\"\" ActNorm layer. [Kingma and Dhariwal, 2018.] \"\"\"", "= torch.unsqueeze(x @ self.w, 1) + self.b z = x", "coupling layer. [Durkan et al. 2019] \"\"\" def __init__(self, dim,", "self.mu = nn.Parameter(torch.zeros(dim, dtype = torch.float)) self.log_sigma = nn.Parameter(torch.zeros(dim, dtype", "K - 1) * dim // 2, hidden_dim) def forward(self,", "/ torch.exp(alpha) log_det -= alpha return z.flip(dims=(1,)), log_det def backward(self,", "nn.Sequential( nn.Linear(in_dim, hidden_dim), nn.Tanh(), nn.Linear(hidden_dim, hidden_dim), nn.Tanh(), nn.Linear(hidden_dim, out_dim), )", "\"\"\" def __init__(self, dim): super().__init__() self.dim = dim W, _", "torch.triu(self.U, diagonal = 1) z = x @ self.P @", "lower, upper = x[:, :self.dim // 2], x[:, self.dim //", "* (x - self.x0) log_det = (n - 1) *", "2:] t2_transformed = self.t2(upper) s2_transformed = self.s2(upper) lower = (lower", "import torch import torch.nn as nn import torch.nn.init as init", "dim // 2, hidden_dim) self.s1 = base_network(dim // 2, dim", "__init__(self, dim): super().__init__() self.dim = dim self.mu = nn.Parameter(torch.zeros(dim, dtype", "init.uniform_(self.init_param, - 1 / 2, 1 / 2) def forward(self,", "torch.log(1 + beta * h) + \\ torch.log(1 + beta", "Radial flow. z = f(x) = = x + β", "h - \\ beta * r / (torch.exp(self.log_alpha) + r)", "= torch.inverse(W) x = z @ self.W_inv log_det = -torch.sum(torch.log(torch.abs(self.S)))", "= x[:,:self.dim // 2], x[:,self.dim // 2:] t1_transformed = self.t1(lower)", "tail_bound=self.B) log_det += torch.sum(ld, dim = 1) out = self.f1(lower).reshape(-1,", "= (z - self.mu) / torch.exp(self.log_sigma) log_det = -torch.sum(self.log_sigma) return", "tail_bound=self.B) log_det += ld return z, log_det def backward(self, z):", "= (upper - t1_transformed) * torch.exp(-s1_transformed) x = torch.cat([lower, upper],", "torch.float)) self.U = nn.Parameter(torch.triu(torch.tensor(U, dtype = torch.float), diagonal = 1))", "-math.sqrt(1/dim), math.sqrt(1/dim)) init.uniform_(self.u, -math.sqrt(1/dim), math.sqrt(1/dim)) init.uniform_(self.b, -math.sqrt(1/dim), math.sqrt(1/dim)) def forward(self,", "f(x) = = x + β h(α, r)(z − z0)", "u * self.h(lin) phi = functional_derivatives[self.h](lin) * self.w log_det =", "alpha = self.initial_param[0], self.initial_param[1] else: out = self.layers[i - 1](x[:,", "for i in range(1, dim): self.layers += [base_network(i, 2, hidden_dim)]", "math.sqrt(1/dim)) init.uniform_(self.log_alpha, -math.sqrt(1/dim), math.sqrt(1/dim)) init.uniform_(self.beta, -math.sqrt(1/dim), math.sqrt(1/dim)) def forward(self, x):", "Radial(nn.Module): \"\"\" Radial flow. z = f(x) = = x", "1e-4) return z, log_det def backward(self, z): raise NotImplementedError(\"Planar flow", "(U + torch.diag(self.S)) log_det = torch.sum(torch.log(torch.abs(self.S))) return z, log_det def", "torch.unsqueeze(x @ self.w, 1) + self.b z = x +", "= torch.sum(self.log_sigma) return z, log_det def backward(self, z): x =", "= x[:, :self.dim // 2], x[:, self.dim // 2:] out", "def backward(self, z): x = (z - self.mu) / torch.exp(self.log_sigma)", "self.u + scal * self.w / torch.norm(self.w) else: raise NotImplementedError(\"Non-linearity", "K - 1, hidden_dim)] self.reset_parameters() def reset_parameters(self): init.uniform_(self.init_param, - 1", "math.sqrt(1/dim)) init.uniform_(self.u, -math.sqrt(1/dim), math.sqrt(1/dim)) init.uniform_(self.b, -math.sqrt(1/dim), math.sqrt(1/dim)) def forward(self, x):", "def forward(self, x): z = torch.zeros_like(x) log_det = torch.zeros(z.shape[0]) for", "= base_network(dim // 2, dim // 2, hidden_dim) self.t2 =", "2], x[:,self.dim // 2:] t1_transformed = self.t1(lower) s1_transformed = self.s1(lower)", "// 2], x[:,self.dim // 2:] t1_transformed = self.t1(lower) s1_transformed =", "neural network. \"\"\" def __init__(self, in_dim, out_dim, hidden_dim): super().__init__() self.network", "z and the log-determinant log|df/dx|. \"\"\" m, n = x.shape", "import torch.nn as nn import torch.nn.init as init import torch.nn.functional", "1) out = self.f1(lower).reshape(-1, self.dim // 2, 3 * self.K", "init.uniform_(self.beta, -math.sqrt(1/dim), math.sqrt(1/dim)) def forward(self, x): \"\"\" Given x, returns", "[<NAME> Mohamed, 2015] \"\"\" def __init__(self, dim, nonlinearity=torch.tanh): super().__init__() self.h", "torch.nn.init as init import torch.nn.functional as F from nf.utils import", "torch.sum(-s1_transformed, dim=1) + \\ torch.sum(-s2_transformed, dim=1) return x, log_det class", "\\ torch.sum(-s2_transformed, dim=1) return x, log_det class MAF(nn.Module): \"\"\" Masked", "supported non-linearities: note that the function must be invertible functional_derivatives", "1) W, H = torch.softmax(W, dim = 1), torch.softmax(H, dim", "self.dim = dim self.K = K self.B = B self.f1", "self.init_param = nn.Parameter(torch.Tensor(3 * K - 1)) for i in", "\"\"\" if self.h in (F.elu, F.leaky_relu): u = self.u elif", "z[:, i] = (x[:, i] - mu) / torch.exp(alpha) log_det", "that the function must be invertible functional_derivatives = { torch.tanh:", "Neural spline flow, auto-regressive. [Durkan et al. 2019] \"\"\" def", "z @ self.W_inv log_det = -torch.sum(torch.log(torch.abs(self.S))) return x, log_det class", "2, dim // 2, hidden_dim) self.t2 = base_network(dim // 2,", "if self.h in (F.elu, F.leaky_relu): u = self.u elif self.h", "= 1), log_det def backward(self, z): log_det = torch.zeros(z.shape[0]) lower,", "torch.sum(-s2_transformed, dim=1) return x, log_det class MAF(nn.Module): \"\"\" Masked auto-regressive", "unconstrained_RQS( lower, W, H, D, inverse=True, tail_bound=self.B) log_det += torch.sum(ld,", "return x, log_det class NSF_CL(nn.Module): \"\"\" Neural spline flow, coupling", "self.W_inv log_det = -torch.sum(torch.log(torch.abs(self.S))) return x, log_det class NSF_AR(nn.Module): \"\"\"", "2018.] \"\"\" def __init__(self, dim): super().__init__() self.dim = dim W,", "F.softplus(D) upper, ld = unconstrained_RQS( upper, W, H, D, inverse=False,", "in (F.elu, F.leaky_relu): u = self.u elif self.h == torch.tanh:", "+ β h(α, r)(z − z0) [Rezende and Mohamed 2015]", "= self.layers[i - 1](x[:, :i]) mu, alpha = out[:, 0],", "= torch.zeros(z.shape[0]) for i in range(self.dim): if i == 0:", "and Mohamed 2015] \"\"\" def __init__(self, dim): super().__init__() self.x0 =", "self.B = B self.f1 = base_network(dim // 2, (3 *", "= torch.zeros(z.shape[0]) lower, upper = z[:, :self.dim // 2], z[:,", "backward(self, z): if not self.W_inv: L = torch.tril(self.L, diagonal =", "i == 0: init_param = self.init_param.expand(x.shape[0], 3 * self.K -", "x): return self.network(x) class RealNVP(nn.Module): \"\"\" Non-volume preserving flow. [Dinh", "lambda x: (x > 0).type(torch.FloatTensor) + \\ (x < 0).type(torch.FloatTensor)", "W, H, D = torch.split(out, self.K, dim = 1) W,", "@ (U + torch.diag(self.S)) self.W_inv = torch.inverse(W) x = z", "dim // 2, hidden_dim) self.t2 = base_network(dim // 2, dim", "// 2, hidden_dim) self.s2 = base_network(dim // 2, dim //", "math import numpy as np import scipy as sp import", "z = z.flip(dims=(1,)) for i in range(self.dim): if i ==", "* H D = F.softplus(D) upper, ld = unconstrained_RQS( upper,", "\\ (x < 0).type(torch.FloatTensor) * -0.01, F.elu: lambda x: (x", "self.K, dim = 1) else: out = self.layers[i - 1](x[:,", "self.w log_det = torch.log(torch.abs(1 + phi @ u) + 1e-4)", "= torch.softmax(W, dim = 2), torch.softmax(H, dim = 2) W,", "the log-determinant log|df/dx|. \"\"\" m, n = x.shape r =", "\"\"\" Given x, returns z and the log-determinant log|df/dx|. \"\"\"", "torch.zeros(x.shape[0]) for i in range(self.dim): if i == 0: init_param", "D, inverse=True, tail_bound=self.B) log_det += torch.sum(ld, dim = 1) out", "+ torch.diag(torch.ones(self.dim)) U = torch.triu(self.U, diagonal = 1) z =", "Neural spline flow, coupling layer. [Durkan et al. 2019] \"\"\"", "upper = z[:,:self.dim // 2], z[:,self.dim // 2:] t2_transformed =", "2:] out = self.f1(lower).reshape(-1, self.dim // 2, 3 * self.K", "class MAF(nn.Module): \"\"\" Masked auto-regressive flow. [Papamakarios et al. 2018]", "dim = 1) W, H = 2 * self.B *", "- self.x0) log_det = (n - 1) * torch.log(1 +", "self.layers = nn.ModuleList() self.init_param = nn.Parameter(torch.Tensor(3 * K - 1))", "as nn import torch.nn.init as init import torch.nn.functional as F", "x): lower, upper = x[:,:self.dim // 2], x[:,self.dim // 2:]", "(upper - t1_transformed) * torch.exp(-s1_transformed) x = torch.cat([lower, upper], dim=1)", "z and the log-determinant log|df/dx|. Returns ------- \"\"\" if self.h", "reset_parameters(dim): init.uniform_(self.z0, -math.sqrt(1/dim), math.sqrt(1/dim)) init.uniform_(self.log_alpha, -math.sqrt(1/dim), math.sqrt(1/dim)) init.uniform_(self.beta, -math.sqrt(1/dim), math.sqrt(1/dim))", "torch.zeros(z.shape[0]) for i in range(self.dim): if i == 0: init_param", "hidden_dim) self.s1 = base_network(dim // 2, dim // 2, hidden_dim)", "+ phi @ u) + 1e-4) return z, log_det def", "r) ** 2) return z, log_det class FCNN(nn.Module): \"\"\" Simple", "2019] \"\"\" def __init__(self, dim, K = 5, B =", "log_det def backward(self, z): x = torch.zeros_like(z) log_det = torch.zeros(z.shape[0])", "z[:, i], ld = unconstrained_RQS( x[:, i], W, H, D,", "n = x.shape r = torch.norm(x - self.x0) h =", "dim self.layers = nn.ModuleList() self.initial_param = nn.Parameter(torch.Tensor(2)) for i in", "dim)) P, L, U = sp.linalg.lu(W) self.P = torch.tensor(P, dtype", "- t2_transformed) * torch.exp(-s2_transformed) t1_transformed = self.t1(lower) s1_transformed = self.s1(lower)", "self.network(x) class RealNVP(nn.Module): \"\"\" Non-volume preserving flow. [Dinh et. al.", "self.dim = dim self.layers = nn.ModuleList() self.initial_param = nn.Parameter(torch.Tensor(2)) for", "W = self.P @ L @ (U + torch.diag(self.S)) self.W_inv", "hidden_dim) self.f2 = base_network(dim // 2, (3 * K -", "spline flow, auto-regressive. [Durkan et al. 2019] \"\"\" def __init__(self,", "2], x[:, self.dim // 2:] out = self.f1(lower).reshape(-1, self.dim //", "= self.s1(lower) upper = (upper - t1_transformed) * torch.exp(-s1_transformed) x", "D, inverse=False, tail_bound=self.B) log_det += torch.sum(ld, dim = 1) return", "= -torch.sum(torch.log(torch.abs(self.S))) return x, log_det class NSF_AR(nn.Module): \"\"\" Neural spline", "* torch.log(1 + beta * h) + \\ torch.log(1 +", "def __init__(self, dim): super().__init__() self.dim = dim self.mu = nn.Parameter(torch.zeros(dim,", "1), log_det def backward(self, z): log_det = torch.zeros(z.shape[0]) lower, upper", "= { torch.tanh: lambda x: 1 - torch.pow(torch.tanh(x), 2), F.leaky_relu:", "= torch.float)) self.log_sigma = nn.Parameter(torch.zeros(dim, dtype = torch.float)) def forward(self,", "x): \"\"\" Given x, returns z and the log-determinant log|df/dx|.", "// 2:] out = self.f1(lower).reshape(-1, self.dim // 2, 3 *", "r = torch.norm(x - self.x0) h = 1 / (torch.exp(self.log_alpha)", "= 1) out = self.f2(upper).reshape(-1, self.dim // 2, 3 *", "torch.nn as nn import torch.nn.init as init import torch.nn.functional as", "z[:, i], W, H, D, inverse = True, tail_bound =", "= torch.tril(self.L, diagonal = -1) + torch.diag(torch.ones(self.dim)) U = torch.triu(self.U,", "self.w @ self.u - 1 u = self.u + scal", "+ beta * h) + \\ torch.log(1 + beta *", "log_det = -torch.sum(torch.log(torch.abs(self.S))) return x, log_det class NSF_AR(nn.Module): \"\"\" Neural", "+ \\ torch.diag(torch.ones(self.dim)) U = torch.triu(self.U, diagonal = 1) W", "log_det def backward(self, z): if not self.W_inv: L = torch.tril(self.L,", "log_det class OneByOneConv(nn.Module): \"\"\" Invertible 1x1 convolution. [Kingma and Dhariwal,", "ld return x, log_det class NSF_CL(nn.Module): \"\"\" Neural spline flow,", "1] x[:, i] = mu + torch.exp(alpha) * z[:, i]", "D = torch.split(out, self.K, dim = 1) W, H =", "W, H, D = torch.split(out, self.K, dim = 2) W,", "r)(z − z0) [Rezende and Mohamed 2015] \"\"\" def __init__(self,", "1), torch.softmax(H, dim = 1) W, H = 2 *", "dim, nonlinearity=torch.tanh): super().__init__() self.h = nonlinearity self.w = nn.Parameter(torch.Tensor(dim)) self.u", "reset_parameters(self, dim): init.uniform_(self.w, -math.sqrt(1/dim), math.sqrt(1/dim)) init.uniform_(self.u, -math.sqrt(1/dim), math.sqrt(1/dim)) init.uniform_(self.b, -math.sqrt(1/dim),", "lower, W, H, D, inverse=False, tail_bound=self.B) log_det += torch.sum(ld, dim", "2 * self.B * H D = F.softplus(D) x[:, i],", "torch.zeros(z.shape[0]) z = z.flip(dims=(1,)) for i in range(self.dim): if i", "function must be invertible functional_derivatives = { torch.tanh: lambda x:", "= torch.zeros_like(x) log_det = torch.zeros(z.shape[0]) for i in range(self.dim): if", "= True, tail_bound = self.B) log_det += ld return x,", "* h - \\ beta * r / (torch.exp(self.log_alpha) +", "def backward(self, z): lower, upper = z[:,:self.dim // 2], z[:,self.dim", "else: out = self.layers[i - 1](x[:, :i]) W, H, D", "= 1)) self.W_inv = None def forward(self, x): L =", "// 2, hidden_dim) self.t2 = base_network(dim // 2, dim //", "dtype = torch.float)) self.S = nn.Parameter(torch.tensor(np.diag(U), dtype = torch.float)) self.U", "2, (3 * K - 1) * dim // 2,", "lower, W, H, D, inverse=True, tail_bound=self.B) log_det += torch.sum(ld, dim", "torch.tril(self.L, diagonal = -1) + torch.diag(torch.ones(self.dim)) U = torch.triu(self.U, diagonal", "= 5, B = 3, hidden_dim = 8, base_network =", "dim = 1) out = self.f1(lower).reshape(-1, self.dim // 2, 3", "lower, upper = z[:,:self.dim // 2], z[:,self.dim // 2:] t2_transformed", "x @ self.P @ L @ (U + torch.diag(self.S)) log_det", "1) W = self.P @ L @ (U + torch.diag(self.S))", "Simple fully connected neural network. \"\"\" def __init__(self, in_dim, out_dim,", "2), F.leaky_relu: lambda x: (x > 0).type(torch.FloatTensor) + \\ (x", "ld = unconstrained_RQS( upper, W, H, D, inverse=False, tail_bound=self.B) log_det", "dim // 2, hidden_dim) def forward(self, x): lower, upper =", "x = z @ self.W_inv log_det = -torch.sum(torch.log(torch.abs(self.S))) return x,", "x, returns z and the log-determinant log|df/dx|. Returns ------- \"\"\"", "forward(self, x): lower, upper = x[:,:self.dim // 2], x[:,self.dim //", "nn.Parameter(torch.tensor(np.diag(U), dtype = torch.float)) self.U = nn.Parameter(torch.triu(torch.tensor(U, dtype = torch.float),", "self.W_inv = torch.inverse(W) x = z @ self.W_inv log_det =", "= (lower - t2_transformed) * torch.exp(-s2_transformed) t1_transformed = self.t1(lower) s1_transformed", "+ beta * h - \\ beta * r /", "nn.Linear(hidden_dim, out_dim), ) def forward(self, x): return self.network(x) class RealNVP(nn.Module):", "else: raise NotImplementedError(\"Non-linearity is not supported.\") lin = torch.unsqueeze(x @", "i], ld = unconstrained_RQS( z[:, i], W, H, D, inverse", "ld return z, log_det def backward(self, z): x = torch.zeros_like(z)", "init.uniform_(self.log_alpha, -math.sqrt(1/dim), math.sqrt(1/dim)) init.uniform_(self.beta, -math.sqrt(1/dim), math.sqrt(1/dim)) def forward(self, x): \"\"\"", "out = self.layers[i - 1](x[:, :i]) mu, alpha = out[:,", "al. 2017] \"\"\" def __init__(self, dim, hidden_dim = 8, base_network=FCNN):", "z = x + u * self.h(lin) phi = functional_derivatives[self.h](lin)", "> 0).type(torch.FloatTensor) + \\ (x < 0).type(torch.FloatTensor) * torch.exp(x) }", "self.w = nn.Parameter(torch.Tensor(dim)) self.u = nn.Parameter(torch.Tensor(dim)) self.b = nn.Parameter(torch.Tensor(1)) self.reset_parameters(dim)", "not supported.\") lin = torch.unsqueeze(x @ self.w, 1) + self.b", "5, B = 3, hidden_dim = 8, base_network = FCNN):", "= torch.float)) def forward(self, x): z = x * torch.exp(self.log_sigma)", "t2_transformed + lower * torch.exp(s2_transformed) z = torch.cat([lower, upper], dim=1)", "f(x) = x + u h(wᵀx + b) [<NAME> Mohamed,", "= self.B) log_det += torch.sum(ld, dim = 1) return torch.cat([lower,", "out = self.layers[i - 1](x[:, :i]) W, H, D =", "torch.triu(self.U, diagonal = 1) W = self.P @ L @", "+ \\ torch.log(1 + beta * h - \\ beta", "nn.Parameter(torch.Tensor(3 * K - 1)) for i in range(1, dim):", "= t2_transformed + lower * torch.exp(s2_transformed) z = torch.cat([lower, upper],", "return x, log_det class ActNorm(nn.Module): \"\"\" ActNorm layer. [Kingma and", "ld = unconstrained_RQS( x[:, i], W, H, D, inverse=False, tail_bound=self.B)", "x, log_det class OneByOneConv(nn.Module): \"\"\" Invertible 1x1 convolution. [Kingma and", "H D = F.softplus(D) z[:, i], ld = unconstrained_RQS( x[:,", "NotImplementedError(\"Planar flow has no algebraic inverse.\") class Radial(nn.Module): \"\"\" Radial", "NSF_CL(nn.Module): \"\"\" Neural spline flow, coupling layer. [Durkan et al.", "* K - 1) * dim // 2, hidden_dim) self.f2", "init_param = self.init_param.expand(x.shape[0], 3 * self.K - 1) W, H,", "K = 5, B = 3, hidden_dim = 8, base_network", "log_det class NSF_CL(nn.Module): \"\"\" Neural spline flow, coupling layer. [Durkan", "h) + \\ torch.log(1 + beta * h - \\", "__init__(self, dim, K = 5, B = 3, hidden_dim =", "= torch.sum(-s1_transformed, dim=1) + \\ torch.sum(-s2_transformed, dim=1) return x, log_det", "-0.01, F.elu: lambda x: (x > 0).type(torch.FloatTensor) + \\ (x", "return self.network(x) class RealNVP(nn.Module): \"\"\" Non-volume preserving flow. [Dinh et.", "upper = (upper - t1_transformed) * torch.exp(-s1_transformed) x = torch.cat([lower,", "base_network(dim // 2, (3 * K - 1) * dim", "h(α, r)(z − z0) [Rezende and Mohamed 2015] \"\"\" def", "range(self.dim): if i == 0: init_param = self.init_param.expand(x.shape[0], 3 *", "z[:, :self.dim // 2], z[:, self.dim // 2:] out =", "dim = 1), log_det def backward(self, z): log_det = torch.zeros(z.shape[0])", "x = torch.zeros_like(z) log_det = torch.zeros(x.shape[0]) for i in range(self.dim):", "== 0: mu, alpha = self.initial_param[0], self.initial_param[1] else: out =", "2) return z, log_det class FCNN(nn.Module): \"\"\" Simple fully connected", "torch.sum(ld, dim = 1) out = self.f2(upper).reshape(-1, self.dim // 2,", "lower = (lower - t2_transformed) * torch.exp(-s2_transformed) t1_transformed = self.t1(lower)", "torch.softmax(W, dim = 2), torch.softmax(H, dim = 2) W, H", "et al. 2018] \"\"\" def __init__(self, dim, hidden_dim = 8,", "[Durkan et al. 2019] \"\"\" def __init__(self, dim, K =", "+ \\ (x < 0).type(torch.FloatTensor) * -0.01, F.elu: lambda x:", "L = torch.tril(self.L, diagonal = -1) + torch.diag(torch.ones(self.dim)) U =", "super().__init__() self.dim = dim W, _ = sp.linalg.qr(np.random.randn(dim, dim)) P,", "\"\"\" def __init__(self, dim, nonlinearity=torch.tanh): super().__init__() self.h = nonlinearity self.w", "torch.log(1 + torch.exp(self.beta)) z = x + beta * h", "torch.tril(self.L, diagonal = -1) + \\ torch.diag(torch.ones(self.dim)) U = torch.triu(self.U,", "torch.exp(x) } class Planar(nn.Module): \"\"\" Planar flow. z = f(x)", "log_det = torch.zeros(x.shape[0]) lower, upper = x[:, :self.dim // 2],", "class NSF_AR(nn.Module): \"\"\" Neural spline flow, auto-regressive. [Durkan et al.", "U = torch.triu(self.U, diagonal = 1) W = self.P @", "= F.softplus(D) upper, ld = unconstrained_RQS( upper, W, H, D,", "x[:,:self.dim // 2], x[:,self.dim // 2:] t1_transformed = self.t1(lower) s1_transformed", "torch.sum(s1_transformed, dim=1) + \\ torch.sum(s2_transformed, dim=1) return z, log_det def", "inverse = True, tail_bound = self.B) log_det += torch.sum(ld, dim", "torch import torch.nn as nn import torch.nn.init as init import", "note that the function must be invertible functional_derivatives = {", "U = sp.linalg.lu(W) self.P = torch.tensor(P, dtype = torch.float) self.L", "z): x = torch.zeros_like(z) log_det = torch.zeros(x.shape[0]) for i in", "H = 2 * self.B * W, 2 * self.B", "2], z[:, self.dim // 2:] out = self.f2(upper).reshape(-1, self.dim //", "/ (torch.exp(self.log_alpha) + r) ** 2) return z, log_det class", "self.P @ L @ (U + torch.diag(self.S)) log_det = torch.sum(torch.log(torch.abs(self.S)))", "torch.exp(alpha) * z[:, i] log_det += alpha return x, log_det", "= 8, base_network = FCNN): super().__init__() self.dim = dim self.K", "nn.Parameter(torch.Tensor(1)) self.beta = nn.Parameter(torch.Tensor(1)) def reset_parameters(dim): init.uniform_(self.z0, -math.sqrt(1/dim), math.sqrt(1/dim)) init.uniform_(self.log_alpha,", "if not self.W_inv: L = torch.tril(self.L, diagonal = -1) +", "must be invertible functional_derivatives = { torch.tanh: lambda x: 1", "self.B) log_det += torch.sum(ld, dim = 1) return torch.cat([lower, upper],", "self.dim = dim W, _ = sp.linalg.qr(np.random.randn(dim, dim)) P, L,", "W, H, D, inverse=False, tail_bound=self.B) log_det += ld return z,", "self.reset_parameters() def reset_parameters(self): init.uniform_(self.init_param, - 1 / 2, 1 /", "2 * self.B * W, 2 * self.B * H", "functional_derivatives[self.h](lin) * self.w log_det = torch.log(torch.abs(1 + phi @ u)", "z = x + beta * h * (x -", "* z[:, i] log_det += alpha return x, log_det class", "x + u h(wᵀx + b) [<NAME> Mohamed, 2015] \"\"\"", "+ u * self.h(lin) phi = functional_derivatives[self.h](lin) * self.w log_det", "log_det += alpha return x, log_det class ActNorm(nn.Module): \"\"\" ActNorm", "= nn.Sequential( nn.Linear(in_dim, hidden_dim), nn.Tanh(), nn.Linear(hidden_dim, hidden_dim), nn.Tanh(), nn.Linear(hidden_dim, out_dim),", "tail_bound=self.B) log_det += torch.sum(ld, dim = 1) out = self.f2(upper).reshape(-1,", "= nn.Parameter(torch.triu(torch.tensor(U, dtype = torch.float), diagonal = 1)) self.W_inv =", "@ self.w, 1) + self.b z = x + u", "+= torch.sum(ld, dim = 1) out = self.f2(upper).reshape(-1, self.dim //", "H = torch.softmax(W, dim = 2), torch.softmax(H, dim = 2)", "2], z[:,self.dim // 2:] t2_transformed = self.t2(upper) s2_transformed = self.s2(upper)", "= 2) W, H = 2 * self.B * W,", "self.K, dim = 1) W, H = torch.softmax(W, dim =", "upper = x[:,:self.dim // 2], x[:,self.dim // 2:] t1_transformed =", "[Rezende and Mohamed 2015] \"\"\" def __init__(self, dim): super().__init__() self.x0", "Given x, returns z and the log-determinant log|df/dx|. Returns -------", "= torch.split(out, self.K, dim = 1) W, H = torch.softmax(W,", "// 2], z[:, self.dim // 2:] out = self.f2(upper).reshape(-1, self.dim", "= torch.softmax(W, dim = 1), torch.softmax(H, dim = 1) W,", "= -torch.sum(self.log_sigma) return x, log_det class OneByOneConv(nn.Module): \"\"\" Invertible 1x1", "x.shape r = torch.norm(x - self.x0) h = 1 /", "L = torch.tril(self.L, diagonal = -1) + \\ torch.diag(torch.ones(self.dim)) U", "hidden_dim = 8, base_network = FCNN): super().__init__() self.dim = dim", "z = x * torch.exp(self.log_sigma) + self.mu log_det = torch.sum(self.log_sigma)", "self.h == torch.tanh: scal = torch.log(1+torch.exp(self.w @ self.u)) - self.w", "diagonal = -1) + torch.diag(torch.ones(self.dim)) U = torch.triu(self.U, diagonal =", "K self.B = B self.f1 = base_network(dim // 2, (3", "self.init_param.expand(x.shape[0], 3 * self.K - 1) W, H, D =", "range(self.dim): if i == 0: mu, alpha = self.initial_param[0], self.initial_param[1]", "+= alpha return x, log_det class ActNorm(nn.Module): \"\"\" ActNorm layer.", "= base_network(dim // 2, (3 * K - 1) *", "et. al. 2017] \"\"\" def __init__(self, dim, hidden_dim = 8,", "-math.sqrt(0.5), math.sqrt(0.5)) def forward(self, x): z = torch.zeros_like(x) log_det =", "super().__init__() self.dim = dim self.mu = nn.Parameter(torch.zeros(dim, dtype = torch.float))", "tail_bound=self.B) log_det += torch.sum(ld, dim = 1) return torch.cat([lower, upper],", "in range(self.dim): if i == 0: init_param = self.init_param.expand(x.shape[0], 3", "(x > 0).type(torch.FloatTensor) + \\ (x < 0).type(torch.FloatTensor) * -0.01,", "torch.tensor(P, dtype = torch.float) self.L = nn.Parameter(torch.tensor(L, dtype = torch.float))", "= FCNN): super().__init__() self.dim = dim self.K = K self.B", "z): lower, upper = z[:,:self.dim // 2], z[:,self.dim // 2:]", "z): if not self.W_inv: L = torch.tril(self.L, diagonal = -1)", "init import torch.nn.functional as F from nf.utils import unconstrained_RQS #", "self.W_inv: L = torch.tril(self.L, diagonal = -1) + \\ torch.diag(torch.ones(self.dim))", "def backward(self, z): log_det = torch.zeros(z.shape[0]) lower, upper = z[:,", "(torch.exp(self.log_alpha) + r) beta = -torch.exp(self.log_alpha) + torch.log(1 + torch.exp(self.beta))", "x, log_det class NSF_CL(nn.Module): \"\"\" Neural spline flow, coupling layer.", "x: (x > 0).type(torch.FloatTensor) + \\ (x < 0).type(torch.FloatTensor) *", "torch.exp(s1_transformed) t2_transformed = self.t2(upper) s2_transformed = self.s2(upper) lower = t2_transformed", "2 * self.B * H D = F.softplus(D) lower, ld", "reset_parameters(self): init.uniform_(self.initial_param, -math.sqrt(0.5), math.sqrt(0.5)) def forward(self, x): z = torch.zeros_like(x)", "Planar(nn.Module): \"\"\" Planar flow. z = f(x) = x +", "z.flip(dims=(1,)) for i in range(self.dim): if i == 0: mu,", "init.uniform_(self.b, -math.sqrt(1/dim), math.sqrt(1/dim)) def forward(self, x): \"\"\" Given x, returns", "L, U = sp.linalg.lu(W) self.P = torch.tensor(P, dtype = torch.float)", "// 2, hidden_dim) self.s1 = base_network(dim // 2, dim //", "H, D, inverse=False, tail_bound=self.B) log_det += ld return z, log_det", "+ \\ (x < 0).type(torch.FloatTensor) * torch.exp(x) } class Planar(nn.Module):", "sp import scipy.linalg import torch import torch.nn as nn import", "dim // 2, hidden_dim) self.f2 = base_network(dim // 2, (3", "return z, log_det def backward(self, z): x = torch.zeros_like(z) log_det", "\\ torch.sum(s2_transformed, dim=1) return z, log_det def backward(self, z): lower,", "dim=1) + \\ torch.sum(-s2_transformed, dim=1) return x, log_det class MAF(nn.Module):", "= torch.float), diagonal = 1)) self.W_inv = None def forward(self,", "flow. z = f(x) = x + u h(wᵀx +", "log_det -= alpha return z.flip(dims=(1,)), log_det def backward(self, z): x", "D = F.softplus(D) upper, ld = unconstrained_RQS( upper, W, H,", "flow has no algebraic inverse.\") class Radial(nn.Module): \"\"\" Radial flow.", "= sp.linalg.qr(np.random.randn(dim, dim)) P, L, U = sp.linalg.lu(W) self.P =", "= f(x) = = x + β h(α, r)(z −", "class RealNVP(nn.Module): \"\"\" Non-volume preserving flow. [Dinh et. al. 2017]", "def __init__(self, dim): super().__init__() self.x0 = nn.Parameter(torch.Tensor(dim)) self.log_alpha = nn.Parameter(torch.Tensor(1))", "2) W, H = torch.softmax(W, dim = 2), torch.softmax(H, dim", "unconstrained_RQS( upper, W, H, D, inverse=False, tail_bound=self.B) log_det += torch.sum(ld,", "out[:, 0], out[:, 1] z[:, i] = (x[:, i] -", "x = torch.zeros_like(z) log_det = torch.zeros(z.shape[0]) z = z.flip(dims=(1,)) for", "unconstrained_RQS # supported non-linearities: note that the function must be", "+ b) [<NAME> Mohamed, 2015] \"\"\" def __init__(self, dim, nonlinearity=torch.tanh):", "torch.float)) self.log_sigma = nn.Parameter(torch.zeros(dim, dtype = torch.float)) def forward(self, x):", "elif self.h == torch.tanh: scal = torch.log(1+torch.exp(self.w @ self.u)) -", "and the log-determinant log|df/dx|. \"\"\" m, n = x.shape r", "self.P @ L @ (U + torch.diag(self.S)) self.W_inv = torch.inverse(W)", "B self.f1 = base_network(dim // 2, (3 * K -", "= unconstrained_RQS( lower, W, H, D, inverse=False, tail_bound=self.B) log_det +=", "* -0.01, F.elu: lambda x: (x > 0).type(torch.FloatTensor) + \\", "1) * torch.log(1 + beta * h) + \\ torch.log(1", "x = (z - self.mu) / torch.exp(self.log_sigma) log_det = -torch.sum(self.log_sigma)", "backward(self, z): x = torch.zeros_like(z) log_det = torch.zeros(z.shape[0]) z =", "network. \"\"\" def __init__(self, in_dim, out_dim, hidden_dim): super().__init__() self.network =", "torch.cat([lower, upper], dim = 1), log_det def backward(self, z): log_det", "= nn.Parameter(torch.Tensor(1)) self.reset_parameters(dim) def reset_parameters(self, dim): init.uniform_(self.w, -math.sqrt(1/dim), math.sqrt(1/dim)) init.uniform_(self.u,", "= 2 * self.B * W, 2 * self.B *", "= torch.zeros(x.shape[0]) lower, upper = x[:, :self.dim // 2], x[:,", "= x @ self.P @ L @ (U + torch.diag(self.S))", "// 2, (3 * K - 1) * dim //", "return z, log_det def backward(self, z): lower, upper = z[:,:self.dim", "torch.softmax(W, dim = 1), torch.softmax(H, dim = 1) W, H", "self.K = K self.B = B self.f1 = base_network(dim //", ":self.dim // 2], z[:, self.dim // 2:] out = self.f2(upper).reshape(-1,", "= nn.Parameter(torch.Tensor(3 * K - 1)) for i in range(1,", "= self.P @ L @ (U + torch.diag(self.S)) self.W_inv =", "mu, alpha = self.initial_param[0], self.initial_param[1] else: out = self.layers[i -", "8, base_network=FCNN): super().__init__() self.dim = dim self.t1 = base_network(dim //", "self.L = nn.Parameter(torch.tensor(L, dtype = torch.float)) self.S = nn.Parameter(torch.tensor(np.diag(U), dtype", "return z, log_det def backward(self, z): raise NotImplementedError(\"Planar flow has", ":self.dim // 2], x[:, self.dim // 2:] out = self.f1(lower).reshape(-1,", "= x + β h(α, r)(z − z0) [Rezende and", "1] z[:, i] = (x[:, i] - mu) / torch.exp(alpha)", "* K - 1)) for i in range(1, dim): self.layers", "def reset_parameters(self): init.uniform_(self.init_param, - 1 / 2, 1 / 2)", "= torch.split(init_param, self.K, dim = 1) else: out = self.layers[i", "OneByOneConv(nn.Module): \"\"\" Invertible 1x1 convolution. [Kingma and Dhariwal, 2018.] \"\"\"", "z = f(x) = x + u h(wᵀx + b)", "- 1) * dim // 2, hidden_dim) def forward(self, x):", "- 1) * dim // 2, hidden_dim) self.f2 = base_network(dim", "math.sqrt(0.5)) def forward(self, x): z = torch.zeros_like(x) log_det = torch.zeros(z.shape[0])", "connected neural network. \"\"\" def __init__(self, in_dim, out_dim, hidden_dim): super().__init__()", "self.b z = x + u * self.h(lin) phi =", "self.B * H D = F.softplus(D) z[:, i], ld =", "super().__init__() self.dim = dim self.layers = nn.ModuleList() self.initial_param = nn.Parameter(torch.Tensor(2))", "upper = x[:, :self.dim // 2], x[:, self.dim // 2:]", "self.initial_param[0], self.initial_param[1] else: out = self.layers[i - 1](x[:, :i]) mu,", "(U + torch.diag(self.S)) self.W_inv = torch.inverse(W) x = z @", "self.K - 1) W, H, D = torch.split(init_param, self.K, dim", "backward(self, z): raise NotImplementedError(\"Planar flow has no algebraic inverse.\") class", "- self.mu) / torch.exp(self.log_sigma) log_det = -torch.sum(self.log_sigma) return x, log_det", "= torch.float)) self.S = nn.Parameter(torch.tensor(np.diag(U), dtype = torch.float)) self.U =", "+ scal * self.w / torch.norm(self.w) else: raise NotImplementedError(\"Non-linearity is", "al. 2019] \"\"\" def __init__(self, dim, K = 5, B", "D, inverse=False, tail_bound=self.B) log_det += torch.sum(ld, dim = 1) out", "\"\"\" Non-volume preserving flow. [Dinh et. al. 2017] \"\"\" def", "+= torch.sum(ld, dim = 1) out = self.f1(lower).reshape(-1, self.dim //", "hidden_dim) self.t2 = base_network(dim // 2, dim // 2, hidden_dim)", "torch.zeros_like(x) log_det = torch.zeros(z.shape[0]) for i in range(self.dim): if i", "- 1, hidden_dim)] self.reset_parameters() def reset_parameters(self): init.uniform_(self.init_param, - 1 /", "not self.W_inv: L = torch.tril(self.L, diagonal = -1) + \\", "import scipy as sp import scipy.linalg import torch import torch.nn", "dim = 1) else: out = self.layers[i - 1](x[:, :i])", "import math import numpy as np import scipy as sp", "(x < 0).type(torch.FloatTensor) * torch.exp(x) } class Planar(nn.Module): \"\"\" Planar", "t2_transformed = self.t2(upper) s2_transformed = self.s2(upper) lower = t2_transformed +", "= self.initial_param[0], self.initial_param[1] else: out = self.layers[i - 1](x[:, :i])", "as np import scipy as sp import scipy.linalg import torch", "nn.Parameter(torch.Tensor(dim)) self.b = nn.Parameter(torch.Tensor(1)) self.reset_parameters(dim) def reset_parameters(self, dim): init.uniform_(self.w, -math.sqrt(1/dim),", "+ self.b z = x + u * self.h(lin) phi", "and the log-determinant log|df/dx|. Returns ------- \"\"\" if self.h in", "1)) for i in range(1, dim): self.layers += [base_network(i, 3", "= torch.zeros_like(z) log_det = torch.zeros(x.shape[0]) for i in range(self.dim): if", "non-linearities: note that the function must be invertible functional_derivatives =", "self.u)) - self.w @ self.u - 1 u = self.u", "\"\"\" Simple fully connected neural network. \"\"\" def __init__(self, in_dim,", "dim = 1) W, H = torch.softmax(W, dim = 1),", "z): log_det = torch.zeros(z.shape[0]) lower, upper = z[:, :self.dim //", "self.s1(lower) upper = t1_transformed + upper * torch.exp(s1_transformed) t2_transformed =", "dim // 2, hidden_dim) self.s2 = base_network(dim // 2, dim", "* self.B * H D = F.softplus(D) lower, ld =", "self.w / torch.norm(self.w) else: raise NotImplementedError(\"Non-linearity is not supported.\") lin", "scipy as sp import scipy.linalg import torch import torch.nn as", "= nn.Parameter(torch.zeros(dim, dtype = torch.float)) self.log_sigma = nn.Parameter(torch.zeros(dim, dtype =", "* K - 1) * dim // 2, hidden_dim) def", "1) W, H, D = torch.split(out, self.K, dim = 2)", "D = F.softplus(D) z[:, i], ld = unconstrained_RQS( x[:, i],", "= dim self.layers = nn.ModuleList() self.initial_param = nn.Parameter(torch.Tensor(2)) for i", "phi = functional_derivatives[self.h](lin) * self.w log_det = torch.log(torch.abs(1 + phi", "i in range(1, dim): self.layers += [base_network(i, 2, hidden_dim)] self.reset_parameters()", "+ upper * torch.exp(s1_transformed) t2_transformed = self.t2(upper) s2_transformed = self.s2(upper)", "torch.zeros(z.shape[0]) for i in range(self.dim): if i == 0: mu,", "2, hidden_dim) self.s2 = base_network(dim // 2, dim // 2,", "return x, log_det class OneByOneConv(nn.Module): \"\"\" Invertible 1x1 convolution. [Kingma", "1](x[:, :i]) W, H, D = torch.split(out, self.K, dim =", "2, hidden_dim)] self.reset_parameters() def reset_parameters(self): init.uniform_(self.initial_param, -math.sqrt(0.5), math.sqrt(0.5)) def forward(self,", "def __init__(self, dim, hidden_dim = 8, base_network=FCNN): super().__init__() self.dim =", "self.initial_param[1] else: out = self.layers[i - 1](x[:, :i]) mu, alpha", "H = torch.softmax(W, dim = 1), torch.softmax(H, dim = 1)", "dim, hidden_dim = 8, base_network=FCNN): super().__init__() self.dim = dim self.t1", "- t1_transformed) * torch.exp(-s1_transformed) x = torch.cat([lower, upper], dim=1) log_det", "tail_bound = self.B) log_det += torch.sum(ld, dim = 1) return", "* self.w log_det = torch.log(torch.abs(1 + phi @ u) +", "t2_transformed = self.t2(upper) s2_transformed = self.s2(upper) lower = (lower -", "// 2, hidden_dim) def forward(self, x): log_det = torch.zeros(x.shape[0]) lower,", "self.dim = dim self.mu = nn.Parameter(torch.zeros(dim, dtype = torch.float)) self.log_sigma", "- self.w @ self.u - 1 u = self.u +", "torch.cat([lower, upper], dim=1) log_det = torch.sum(s1_transformed, dim=1) + \\ torch.sum(s2_transformed,", "torch.diag(torch.ones(self.dim)) U = torch.triu(self.U, diagonal = 1) z = x", "= torch.triu(self.U, diagonal = 1) W = self.P @ L", "D = torch.split(init_param, self.K, dim = 1) else: out =", "1) W, H = 2 * self.B * W, 2", "1 u = self.u + scal * self.w / torch.norm(self.w)", "t1_transformed + upper * torch.exp(s1_transformed) t2_transformed = self.t2(upper) s2_transformed =", "= x + u * self.h(lin) phi = functional_derivatives[self.h](lin) *", "def forward(self, x): L = torch.tril(self.L, diagonal = -1) +", "upper, W, H, D, inverse = True, tail_bound = self.B)", "inverse.\") class Radial(nn.Module): \"\"\" Radial flow. z = f(x) =", "U = torch.triu(self.U, diagonal = 1) z = x @", "log|df/dx|. \"\"\" m, n = x.shape r = torch.norm(x -", "torch.exp(self.log_sigma) + self.mu log_det = torch.sum(self.log_sigma) return z, log_det def", "\"\"\" Planar flow. z = f(x) = x + u", "ld = unconstrained_RQS( z[:, i], W, H, D, inverse =", "return z, log_det def backward(self, z): if not self.W_inv: L", "* self.w / torch.norm(self.w) else: raise NotImplementedError(\"Non-linearity is not supported.\")", "torch.split(init_param, self.K, dim = 1) else: out = self.layers[i -", "self.U = nn.Parameter(torch.triu(torch.tensor(U, dtype = torch.float), diagonal = 1)) self.W_inv", "torch.zeros_like(z) log_det = torch.zeros(x.shape[0]) for i in range(self.dim): if i", "upper], dim=1) log_det = torch.sum(-s1_transformed, dim=1) + \\ torch.sum(-s2_transformed, dim=1)", "-= alpha return z.flip(dims=(1,)), log_det def backward(self, z): x =", "2) W, H = 2 * self.B * W, 2", "math.sqrt(1/dim)) init.uniform_(self.beta, -math.sqrt(1/dim), math.sqrt(1/dim)) def forward(self, x): \"\"\" Given x,", "None def forward(self, x): L = torch.tril(self.L, diagonal = -1)", "class Radial(nn.Module): \"\"\" Radial flow. z = f(x) = =", "range(1, dim): self.layers += [base_network(i, 2, hidden_dim)] self.reset_parameters() def reset_parameters(self):", "= unconstrained_RQS( upper, W, H, D, inverse=False, tail_bound=self.B) log_det +=", "self.B) log_det += ld return x, log_det class NSF_CL(nn.Module): \"\"\"", "(n - 1) * torch.log(1 + beta * h) +", "lambda x: 1 - torch.pow(torch.tanh(x), 2), F.leaky_relu: lambda x: (x", "-math.sqrt(1/dim), math.sqrt(1/dim)) init.uniform_(self.log_alpha, -math.sqrt(1/dim), math.sqrt(1/dim)) init.uniform_(self.beta, -math.sqrt(1/dim), math.sqrt(1/dim)) def forward(self,", "log_det += torch.sum(ld, dim = 1) out = self.f1(lower).reshape(-1, self.dim", "flow, coupling layer. [Durkan et al. 2019] \"\"\" def __init__(self,", "return x, log_det class MAF(nn.Module): \"\"\" Masked auto-regressive flow. [Papamakarios", "import numpy as np import scipy as sp import scipy.linalg", "1) return torch.cat([lower, upper], dim = 1), log_det def backward(self,", "raise NotImplementedError(\"Non-linearity is not supported.\") lin = torch.unsqueeze(x @ self.w,", "[Dinh et. al. 2017] \"\"\" def __init__(self, dim, hidden_dim =", "True, tail_bound = self.B) log_det += ld return x, log_det", "= self.f1(lower).reshape(-1, self.dim // 2, 3 * self.K - 1)", "math.sqrt(1/dim)) init.uniform_(self.b, -math.sqrt(1/dim), math.sqrt(1/dim)) def forward(self, x): \"\"\" Given x,", "log_det class ActNorm(nn.Module): \"\"\" ActNorm layer. [Kingma and Dhariwal, 2018.]", "= torch.split(out, self.K, dim = 2) W, H = torch.softmax(W,", "np import scipy as sp import scipy.linalg import torch import", "b) [<NAME> Mohamed, 2015] \"\"\" def __init__(self, dim, nonlinearity=torch.tanh): super().__init__()", "* K - 1, hidden_dim)] self.reset_parameters() def reset_parameters(self): init.uniform_(self.init_param, -", "beta * h * (x - self.x0) log_det = (n", "range(1, dim): self.layers += [base_network(i, 3 * K - 1,", "\"\"\" def __init__(self, dim, hidden_dim = 8, base_network=FCNN): super().__init__() self.dim", "self.dim // 2:] out = self.f2(upper).reshape(-1, self.dim // 2, 3", "= nn.Parameter(torch.tensor(np.diag(U), dtype = torch.float)) self.U = nn.Parameter(torch.triu(torch.tensor(U, dtype =", "= 1) out = self.f1(lower).reshape(-1, self.dim // 2, 3 *", "log_det def backward(self, z): x = (z - self.mu) /", "1 / 2, 1 / 2) def forward(self, x): z", "def forward(self, x): log_det = torch.zeros(x.shape[0]) lower, upper = x[:,", "in range(self.dim): if i == 0: mu, alpha = self.initial_param[0],", "alpha = out[:, 0], out[:, 1] x[:, i] = mu", "= z[:,:self.dim // 2], z[:,self.dim // 2:] t2_transformed = self.t2(upper)", "z): x = (z - self.mu) / torch.exp(self.log_sigma) log_det =", "dtype = torch.float)) def forward(self, x): z = x *", "s1_transformed = self.s1(lower) upper = (upper - t1_transformed) * torch.exp(-s1_transformed)", "torch.exp(alpha) log_det -= alpha return z.flip(dims=(1,)), log_det def backward(self, z):", "self.s1 = base_network(dim // 2, dim // 2, hidden_dim) self.t2", "dtype = torch.float) self.L = nn.Parameter(torch.tensor(L, dtype = torch.float)) self.S", "= -1) + \\ torch.diag(torch.ones(self.dim)) U = torch.triu(self.U, diagonal =", "phi @ u) + 1e-4) return z, log_det def backward(self,", "0).type(torch.FloatTensor) * -0.01, F.elu: lambda x: (x > 0).type(torch.FloatTensor) +", "// 2, dim // 2, hidden_dim) self.s2 = base_network(dim //", "2, 1 / 2) def forward(self, x): z = torch.zeros_like(x)", "out[:, 1] z[:, i] = (x[:, i] - mu) /", "(x[:, i] - mu) / torch.exp(alpha) log_det -= alpha return", "B = 3, hidden_dim = 8, base_network = FCNN): super().__init__()", "ld = unconstrained_RQS( lower, W, H, D, inverse=False, tail_bound=self.B) log_det", "- 1](x[:, :i]) mu, alpha = out[:, 0], out[:, 1]", "log_det = -torch.sum(self.log_sigma) return x, log_det class OneByOneConv(nn.Module): \"\"\" Invertible", "torch.diag(torch.ones(self.dim)) U = torch.triu(self.U, diagonal = 1) W = self.P", "i in range(self.dim): if i == 0: init_param = self.init_param.expand(x.shape[0],", "def backward(self, z): raise NotImplementedError(\"Planar flow has no algebraic inverse.\")", "* self.K - 1) W, H, D = torch.split(out, self.K,", "= self.u elif self.h == torch.tanh: scal = torch.log(1+torch.exp(self.w @", "log_det = torch.sum(torch.log(torch.abs(self.S))) return z, log_det def backward(self, z): if", "\\ beta * r / (torch.exp(self.log_alpha) + r) ** 2)", "return z, log_det def backward(self, z): x = (z -", "inverse=False, tail_bound=self.B) log_det += torch.sum(ld, dim = 1) return torch.cat([lower,", "log_det = torch.log(torch.abs(1 + phi @ u) + 1e-4) return", "== torch.tanh: scal = torch.log(1+torch.exp(self.w @ self.u)) - self.w @", "beta * r / (torch.exp(self.log_alpha) + r) ** 2) return", "2017] \"\"\" def __init__(self, dim, hidden_dim = 8, base_network=FCNN): super().__init__()", "math.sqrt(1/dim)) def forward(self, x): \"\"\" Given x, returns z and", "= nn.Parameter(torch.Tensor(dim)) self.b = nn.Parameter(torch.Tensor(1)) self.reset_parameters(dim) def reset_parameters(self, dim): init.uniform_(self.w,", "\"\"\" Invertible 1x1 convolution. [Kingma and Dhariwal, 2018.] \"\"\" def", "self.f1(lower).reshape(-1, self.dim // 2, 3 * self.K - 1) W,", "be invertible functional_derivatives = { torch.tanh: lambda x: 1 -", "hidden_dim)] self.reset_parameters() def reset_parameters(self): init.uniform_(self.initial_param, -math.sqrt(0.5), math.sqrt(0.5)) def forward(self, x):", "D = F.softplus(D) x[:, i], ld = unconstrained_RQS( z[:, i],", "t1_transformed = self.t1(lower) s1_transformed = self.s1(lower) upper = (upper -", "1) else: out = self.layers[i - 1](x[:, :i]) W, H,", "mu) / torch.exp(alpha) log_det -= alpha return z.flip(dims=(1,)), log_det def", "self.t1(lower) s1_transformed = self.s1(lower) upper = t1_transformed + upper *", "+= torch.sum(ld, dim = 1) return torch.cat([lower, upper], dim =", "= dim W, _ = sp.linalg.qr(np.random.randn(dim, dim)) P, L, U", "= nn.Parameter(torch.Tensor(1)) self.beta = nn.Parameter(torch.Tensor(1)) def reset_parameters(dim): init.uniform_(self.z0, -math.sqrt(1/dim), math.sqrt(1/dim))", "lin = torch.unsqueeze(x @ self.w, 1) + self.b z =", "+ \\ torch.sum(-s2_transformed, dim=1) return x, log_det class MAF(nn.Module): \"\"\"", "(z - self.mu) / torch.exp(self.log_sigma) log_det = -torch.sum(self.log_sigma) return x,", "nn.Parameter(torch.zeros(dim, dtype = torch.float)) self.log_sigma = nn.Parameter(torch.zeros(dim, dtype = torch.float))", "D, inverse = True, tail_bound = self.B) log_det += torch.sum(ld,", "= 3, hidden_dim = 8, base_network = FCNN): super().__init__() self.dim", "nn import torch.nn.init as init import torch.nn.functional as F from", "* self.B * W, 2 * self.B * H D", "β h(α, r)(z − z0) [Rezende and Mohamed 2015] \"\"\"", "True, tail_bound = self.B) log_det += torch.sum(ld, dim = 1)", "z[:,:self.dim // 2], z[:,self.dim // 2:] t2_transformed = self.t2(upper) s2_transformed", "= torch.norm(x - self.x0) h = 1 / (torch.exp(self.log_alpha) +", "__init__(self, dim, hidden_dim = 8, base_network=FCNN): super().__init__() self.dim = dim", "log_det class NSF_AR(nn.Module): \"\"\" Neural spline flow, auto-regressive. [Durkan et", "= self.t2(upper) s2_transformed = self.s2(upper) lower = (lower - t2_transformed)", "K - 1)) for i in range(1, dim): self.layers +=", "= self.s2(upper) lower = (lower - t2_transformed) * torch.exp(-s2_transformed) t1_transformed", "nn.Parameter(torch.tensor(L, dtype = torch.float)) self.S = nn.Parameter(torch.tensor(np.diag(U), dtype = torch.float))", "hidden_dim), nn.Tanh(), nn.Linear(hidden_dim, hidden_dim), nn.Tanh(), nn.Linear(hidden_dim, out_dim), ) def forward(self,", "= K self.B = B self.f1 = base_network(dim // 2,", "-torch.sum(self.log_sigma) return x, log_det class OneByOneConv(nn.Module): \"\"\" Invertible 1x1 convolution.", "-torch.exp(self.log_alpha) + torch.log(1 + torch.exp(self.beta)) z = x + beta", "x[:, self.dim // 2:] out = self.f1(lower).reshape(-1, self.dim // 2,", "- 1) W, H, D = torch.split(init_param, self.K, dim =", "def forward(self, x): \"\"\" Given x, returns z and the", "2015] \"\"\" def __init__(self, dim): super().__init__() self.x0 = nn.Parameter(torch.Tensor(dim)) self.log_alpha", "2 * self.B * H D = F.softplus(D) upper, ld", "= unconstrained_RQS( upper, W, H, D, inverse = True, tail_bound", "i] = mu + torch.exp(alpha) * z[:, i] log_det +=", "F.softplus(D) lower, ld = unconstrained_RQS( lower, W, H, D, inverse=False,", "unconstrained_RQS( z[:, i], W, H, D, inverse = True, tail_bound", "# supported non-linearities: note that the function must be invertible", "H D = F.softplus(D) lower, ld = unconstrained_RQS( lower, W,", "(x > 0).type(torch.FloatTensor) + \\ (x < 0).type(torch.FloatTensor) * torch.exp(x)", "1](x[:, :i]) mu, alpha = out[:, 0], out[:, 1] x[:,", "nn.Parameter(torch.Tensor(2)) for i in range(1, dim): self.layers += [base_network(i, 2,", "dim self.K = K self.B = B self.layers = nn.ModuleList()", "self.s2 = base_network(dim // 2, dim // 2, hidden_dim) def", "z, log_det def backward(self, z): if not self.W_inv: L =", "torch.split(out, self.K, dim = 2) W, H = torch.softmax(W, dim", "torch.zeros(x.shape[0]) lower, upper = x[:, :self.dim // 2], x[:, self.dim", "self.S = nn.Parameter(torch.tensor(np.diag(U), dtype = torch.float)) self.U = nn.Parameter(torch.triu(torch.tensor(U, dtype", "[Papamakarios et al. 2018] \"\"\" def __init__(self, dim, hidden_dim =", "scipy.linalg import torch import torch.nn as nn import torch.nn.init as", "Given x, returns z and the log-determinant log|df/dx|. \"\"\" m,", "// 2], x[:, self.dim // 2:] out = self.f1(lower).reshape(-1, self.dim", "beta * h - \\ beta * r / (torch.exp(self.log_alpha)", ":i]) mu, alpha = out[:, 0], out[:, 1] z[:, i]", "torch.exp(s2_transformed) z = torch.cat([lower, upper], dim=1) log_det = torch.sum(s1_transformed, dim=1)", "0], out[:, 1] z[:, i] = (x[:, i] - mu)", "inverse=False, tail_bound=self.B) log_det += torch.sum(ld, dim = 1) out =", "torch.softmax(H, dim = 2) W, H = 2 * self.B", "= self.t1(lower) s1_transformed = self.s1(lower) upper = (upper - t1_transformed)", "* self.h(lin) phi = functional_derivatives[self.h](lin) * self.w log_det = torch.log(torch.abs(1", "dim): super().__init__() self.x0 = nn.Parameter(torch.Tensor(dim)) self.log_alpha = nn.Parameter(torch.Tensor(1)) self.beta =", "2018] \"\"\" def __init__(self, dim, hidden_dim = 8, base_network=FCNN): super().__init__()", "log_det def backward(self, z): raise NotImplementedError(\"Planar flow has no algebraic", "torch.split(out, self.K, dim = 1) W, H = torch.softmax(W, dim", "backward(self, z): x = torch.zeros_like(z) log_det = torch.zeros(x.shape[0]) for i", "class FCNN(nn.Module): \"\"\" Simple fully connected neural network. \"\"\" def", "* h) + \\ torch.log(1 + beta * h -", "self.layers = nn.ModuleList() self.initial_param = nn.Parameter(torch.Tensor(2)) for i in range(1,", "// 2:] out = self.f2(upper).reshape(-1, self.dim // 2, 3 *", "layer. [Kingma and Dhariwal, 2018.] \"\"\" def __init__(self, dim): super().__init__()", "\\ (x < 0).type(torch.FloatTensor) * torch.exp(x) } class Planar(nn.Module): \"\"\"", "= dim self.K = K self.B = B self.layers =", "2, hidden_dim) self.s1 = base_network(dim // 2, dim // 2,", "dim W, _ = sp.linalg.qr(np.random.randn(dim, dim)) P, L, U =", "dim=1) log_det = torch.sum(s1_transformed, dim=1) + \\ torch.sum(s2_transformed, dim=1) return", "log_det = torch.sum(self.log_sigma) return z, log_det def backward(self, z): x", "diagonal = 1) z = x @ self.P @ L", "2, hidden_dim) self.f2 = base_network(dim // 2, (3 * K", "Planar flow. z = f(x) = x + u h(wᵀx", "def backward(self, z): if not self.W_inv: L = torch.tril(self.L, diagonal", "= True, tail_bound = self.B) log_det += torch.sum(ld, dim =", "self.u = nn.Parameter(torch.Tensor(dim)) self.b = nn.Parameter(torch.Tensor(1)) self.reset_parameters(dim) def reset_parameters(self, dim):", "u = self.u elif self.h == torch.tanh: scal = torch.log(1+torch.exp(self.w", "self.w, 1) + self.b z = x + u *", "- 1)) for i in range(1, dim): self.layers += [base_network(i,", "flow, auto-regressive. [Durkan et al. 2019] \"\"\" def __init__(self, dim,", "scal * self.w / torch.norm(self.w) else: raise NotImplementedError(\"Non-linearity is not", "flow. z = f(x) = = x + β h(α,", "x * torch.exp(self.log_sigma) + self.mu log_det = torch.sum(self.log_sigma) return z,", "+= [base_network(i, 2, hidden_dim)] self.reset_parameters() def reset_parameters(self): init.uniform_(self.initial_param, -math.sqrt(0.5), math.sqrt(0.5))", "FCNN): super().__init__() self.dim = dim self.K = K self.B =", "__init__(self, dim, nonlinearity=torch.tanh): super().__init__() self.h = nonlinearity self.w = nn.Parameter(torch.Tensor(dim))", "+ 1e-4) return z, log_det def backward(self, z): raise NotImplementedError(\"Planar", "= z @ self.W_inv log_det = -torch.sum(torch.log(torch.abs(self.S))) return x, log_det", "self.layers[i - 1](x[:, :i]) W, H, D = torch.split(out, self.K,", "torch.float) self.L = nn.Parameter(torch.tensor(L, dtype = torch.float)) self.S = nn.Parameter(torch.tensor(np.diag(U),", "return z, log_det class FCNN(nn.Module): \"\"\" Simple fully connected neural", "self.f2(upper).reshape(-1, self.dim // 2, 3 * self.K - 1) W,", "base_network(dim // 2, dim // 2, hidden_dim) self.s2 = base_network(dim", "2018.] \"\"\" def __init__(self, dim): super().__init__() self.dim = dim self.mu", "<filename>nf/flows.py import math import numpy as np import scipy as", "(x - self.x0) log_det = (n - 1) * torch.log(1", "beta = -torch.exp(self.log_alpha) + torch.log(1 + torch.exp(self.beta)) z = x", "torch.norm(x - self.x0) h = 1 / (torch.exp(self.log_alpha) + r)", "@ L @ (U + torch.diag(self.S)) log_det = torch.sum(torch.log(torch.abs(self.S))) return", "z, log_det def backward(self, z): x = torch.zeros_like(z) log_det =", "dim=1) return x, log_det class MAF(nn.Module): \"\"\" Masked auto-regressive flow.", ":i]) W, H, D = torch.split(out, self.K, dim = 1)", "et al. 2019] \"\"\" def __init__(self, dim, K = 5,", "Masked auto-regressive flow. [Papamakarios et al. 2018] \"\"\" def __init__(self,", "\"\"\" def __init__(self, dim): super().__init__() self.x0 = nn.Parameter(torch.Tensor(dim)) self.log_alpha =", "> 0).type(torch.FloatTensor) + \\ (x < 0).type(torch.FloatTensor) * -0.01, F.elu:", "= t1_transformed + upper * torch.exp(s1_transformed) t2_transformed = self.t2(upper) s2_transformed", "\"\"\" def __init__(self, dim): super().__init__() self.dim = dim self.mu =", "= torch.zeros_like(z) log_det = torch.zeros(z.shape[0]) z = z.flip(dims=(1,)) for i", "__init__(self, dim): super().__init__() self.dim = dim W, _ = sp.linalg.qr(np.random.randn(dim,", "B self.layers = nn.ModuleList() self.init_param = nn.Parameter(torch.Tensor(3 * K -", "\"\"\" Neural spline flow, coupling layer. [Durkan et al. 2019]", "has no algebraic inverse.\") class Radial(nn.Module): \"\"\" Radial flow. z", "torch.zeros_like(z) log_det = torch.zeros(z.shape[0]) z = z.flip(dims=(1,)) for i in", "z, log_det def backward(self, z): raise NotImplementedError(\"Planar flow has no", "diagonal = 1) W = self.P @ L @ (U", "h(wᵀx + b) [<NAME> Mohamed, 2015] \"\"\" def __init__(self, dim,", "torch.diag(self.S)) self.W_inv = torch.inverse(W) x = z @ self.W_inv log_det", "= F.softplus(D) x[:, i], ld = unconstrained_RQS( z[:, i], W,", "self.dim = dim self.t1 = base_network(dim // 2, dim //", "self.f1 = base_network(dim // 2, (3 * K - 1)", "alpha return z.flip(dims=(1,)), log_det def backward(self, z): x = torch.zeros_like(z)", "hidden_dim) self.s2 = base_network(dim // 2, dim // 2, hidden_dim)", "mu, alpha = out[:, 0], out[:, 1] z[:, i] =", "z[:, self.dim // 2:] out = self.f2(upper).reshape(-1, self.dim // 2,", "= 1) else: out = self.layers[i - 1](x[:, :i]) W,", "H D = F.softplus(D) x[:, i], ld = unconstrained_RQS( z[:,", "log_det = torch.zeros(z.shape[0]) lower, upper = z[:, :self.dim // 2],", "@ (U + torch.diag(self.S)) log_det = torch.sum(torch.log(torch.abs(self.S))) return z, log_det", "super().__init__() self.dim = dim self.t1 = base_network(dim // 2, dim", "= torch.float)) self.U = nn.Parameter(torch.triu(torch.tensor(U, dtype = torch.float), diagonal =", "− z0) [Rezende and Mohamed 2015] \"\"\" def __init__(self, dim):", "lower = t2_transformed + lower * torch.exp(s2_transformed) z = torch.cat([lower,", "F.elu: lambda x: (x > 0).type(torch.FloatTensor) + \\ (x <", "the log-determinant log|df/dx|. Returns ------- \"\"\" if self.h in (F.elu,", "mu + torch.exp(alpha) * z[:, i] log_det += alpha return", "F.leaky_relu: lambda x: (x > 0).type(torch.FloatTensor) + \\ (x <", "self.mu log_det = torch.sum(self.log_sigma) return z, log_det def backward(self, z):", "return z.flip(dims=(1,)), log_det def backward(self, z): x = torch.zeros_like(z) log_det", "functional_derivatives = { torch.tanh: lambda x: 1 - torch.pow(torch.tanh(x), 2),", "W, H = torch.softmax(W, dim = 1), torch.softmax(H, dim =", "2) def forward(self, x): z = torch.zeros_like(x) log_det = torch.zeros(z.shape[0])", "8, base_network = FCNN): super().__init__() self.dim = dim self.K =", "z): x = torch.zeros_like(z) log_det = torch.zeros(z.shape[0]) z = z.flip(dims=(1,))", "dtype = torch.float)) self.log_sigma = nn.Parameter(torch.zeros(dim, dtype = torch.float)) def", "self.dim = dim self.K = K self.B = B self.layers", "- 1) * torch.log(1 + beta * h) + \\", "// 2:] t1_transformed = self.t1(lower) s1_transformed = self.s1(lower) upper =", "x, log_det class ActNorm(nn.Module): \"\"\" ActNorm layer. [Kingma and Dhariwal,", "-math.sqrt(1/dim), math.sqrt(1/dim)) def forward(self, x): \"\"\" Given x, returns z", "self.dim // 2, 3 * self.K - 1) W, H,", "self.u - 1 u = self.u + scal * self.w", "@ self.P @ L @ (U + torch.diag(self.S)) log_det =", "= unconstrained_RQS( x[:, i], W, H, D, inverse=False, tail_bound=self.B) log_det", "= base_network(dim // 2, dim // 2, hidden_dim) def forward(self,", "torch.sum(s2_transformed, dim=1) return z, log_det def backward(self, z): lower, upper", "= nn.Parameter(torch.Tensor(1)) def reset_parameters(dim): init.uniform_(self.z0, -math.sqrt(1/dim), math.sqrt(1/dim)) init.uniform_(self.log_alpha, -math.sqrt(1/dim), math.sqrt(1/dim))", "log_det = torch.zeros(z.shape[0]) z = z.flip(dims=(1,)) for i in range(self.dim):", "for i in range(self.dim): if i == 0: mu, alpha", "D, inverse = True, tail_bound = self.B) log_det += ld", "= (n - 1) * torch.log(1 + beta * h)", "= f(x) = x + u h(wᵀx + b) [<NAME>", "self.reset_parameters(dim) def reset_parameters(self, dim): init.uniform_(self.w, -math.sqrt(1/dim), math.sqrt(1/dim)) init.uniform_(self.u, -math.sqrt(1/dim), math.sqrt(1/dim))", "def reset_parameters(dim): init.uniform_(self.z0, -math.sqrt(1/dim), math.sqrt(1/dim)) init.uniform_(self.log_alpha, -math.sqrt(1/dim), math.sqrt(1/dim)) init.uniform_(self.beta, -math.sqrt(1/dim),", "torch.sum(torch.log(torch.abs(self.S))) return z, log_det def backward(self, z): if not self.W_inv:", "* h * (x - self.x0) log_det = (n -", "x + u * self.h(lin) phi = functional_derivatives[self.h](lin) * self.w", "= self.t1(lower) s1_transformed = self.s1(lower) upper = t1_transformed + upper", "dim, K = 5, B = 3, hidden_dim = 8,", "if i == 0: init_param = self.init_param.expand(x.shape[0], 3 * self.K", "torch.float)) self.S = nn.Parameter(torch.tensor(np.diag(U), dtype = torch.float)) self.U = nn.Parameter(torch.triu(torch.tensor(U,", "NotImplementedError(\"Non-linearity is not supported.\") lin = torch.unsqueeze(x @ self.w, 1)", "u h(wᵀx + b) [<NAME> Mohamed, 2015] \"\"\" def __init__(self,", "lower, upper = x[:,:self.dim // 2], x[:,self.dim // 2:] t1_transformed", "u = self.u + scal * self.w / torch.norm(self.w) else:", "+ u h(wᵀx + b) [<NAME> Mohamed, 2015] \"\"\" def", "from nf.utils import unconstrained_RQS # supported non-linearities: note that the", "log_det def backward(self, z): lower, upper = z[:,:self.dim // 2],", "out_dim), ) def forward(self, x): return self.network(x) class RealNVP(nn.Module): \"\"\"", "x + β h(α, r)(z − z0) [Rezende and Mohamed", "= B self.f1 = base_network(dim // 2, (3 * K", "z = torch.cat([lower, upper], dim=1) log_det = torch.sum(s1_transformed, dim=1) +", "log_det += ld return z, log_det def backward(self, z): x", "def forward(self, x): return self.network(x) class RealNVP(nn.Module): \"\"\" Non-volume preserving", "out_dim, hidden_dim): super().__init__() self.network = nn.Sequential( nn.Linear(in_dim, hidden_dim), nn.Tanh(), nn.Linear(hidden_dim,", "scal = torch.log(1+torch.exp(self.w @ self.u)) - self.w @ self.u -", "= 8, base_network=FCNN): super().__init__() self.dim = dim self.layers = nn.ModuleList()", "self.B = B self.layers = nn.ModuleList() self.init_param = nn.Parameter(torch.Tensor(3 *", "= 1) z = x @ self.P @ L @", "/ 2, 1 / 2) def forward(self, x): z =", "= self.init_param.expand(x.shape[0], 3 * self.K - 1) W, H, D", "alpha return x, log_det class ActNorm(nn.Module): \"\"\" ActNorm layer. [Kingma", "and Dhariwal, 2018.] \"\"\" def __init__(self, dim): super().__init__() self.dim =", "super().__init__() self.dim = dim self.K = K self.B = B", "log_det = (n - 1) * torch.log(1 + beta *", "= x + beta * h * (x - self.x0)", "ActNorm(nn.Module): \"\"\" ActNorm layer. [Kingma and Dhariwal, 2018.] \"\"\" def", "= torch.cat([lower, upper], dim=1) log_det = torch.sum(s1_transformed, dim=1) + \\", "z = torch.zeros_like(x) log_det = torch.zeros(z.shape[0]) for i in range(self.dim):", "* r / (torch.exp(self.log_alpha) + r) ** 2) return z,", "+ torch.exp(self.beta)) z = x + beta * h *", "super().__init__() self.h = nonlinearity self.w = nn.Parameter(torch.Tensor(dim)) self.u = nn.Parameter(torch.Tensor(dim))", "------- \"\"\" if self.h in (F.elu, F.leaky_relu): u = self.u", "upper * torch.exp(s1_transformed) t2_transformed = self.t2(upper) s2_transformed = self.s2(upper) lower", "dim self.K = K self.B = B self.f1 = base_network(dim", "W, H = torch.softmax(W, dim = 2), torch.softmax(H, dim =", "* torch.exp(-s2_transformed) t1_transformed = self.t1(lower) s1_transformed = self.s1(lower) upper =", "self.K - 1) W, H, D = torch.split(out, self.K, dim", "auto-regressive. [Durkan et al. 2019] \"\"\" def __init__(self, dim, K", "inverse = True, tail_bound = self.B) log_det += ld return", "self.W_inv = None def forward(self, x): L = torch.tril(self.L, diagonal", "x): L = torch.tril(self.L, diagonal = -1) + torch.diag(torch.ones(self.dim)) U", "1) * dim // 2, hidden_dim) self.f2 = base_network(dim //", "self.s2(upper) lower = t2_transformed + lower * torch.exp(s2_transformed) z =", "torch.sum(self.log_sigma) return z, log_det def backward(self, z): x = (z", "= torch.log(torch.abs(1 + phi @ u) + 1e-4) return z,", "Invertible 1x1 convolution. [Kingma and Dhariwal, 2018.] \"\"\" def __init__(self,", "forward(self, x): \"\"\" Given x, returns z and the log-determinant", "1) W, H, D = torch.split(init_param, self.K, dim = 1)", "+ torch.exp(alpha) * z[:, i] log_det += alpha return x,", "H D = F.softplus(D) upper, ld = unconstrained_RQS( upper, W,", "self.h = nonlinearity self.w = nn.Parameter(torch.Tensor(dim)) self.u = nn.Parameter(torch.Tensor(dim)) self.b", "\"\"\" Masked auto-regressive flow. [Papamakarios et al. 2018] \"\"\" def", "self.t1 = base_network(dim // 2, dim // 2, hidden_dim) self.s1", "= base_network(dim // 2, dim // 2, hidden_dim) self.s1 =", "base_network=FCNN): super().__init__() self.dim = dim self.layers = nn.ModuleList() self.initial_param =", "def backward(self, z): x = torch.zeros_like(z) log_det = torch.zeros(z.shape[0]) z", "D = F.softplus(D) lower, ld = unconstrained_RQS( lower, W, H,", "r) beta = -torch.exp(self.log_alpha) + torch.log(1 + torch.exp(self.beta)) z =", "dim self.t1 = base_network(dim // 2, dim // 2, hidden_dim)", "W, 2 * self.B * H D = F.softplus(D) upper,", "= torch.sum(torch.log(torch.abs(self.S))) return z, log_det def backward(self, z): if not", "\"\"\" Neural spline flow, auto-regressive. [Durkan et al. 2019] \"\"\"", "import torch.nn.functional as F from nf.utils import unconstrained_RQS # supported", "* H D = F.softplus(D) z[:, i], ld = unconstrained_RQS(", "1](x[:, :i]) mu, alpha = out[:, 0], out[:, 1] z[:,", "dim): self.layers += [base_network(i, 3 * K - 1, hidden_dim)]", "+ beta * h * (x - self.x0) log_det =", "W, 2 * self.B * H D = F.softplus(D) z[:,", "H, D, inverse=True, tail_bound=self.B) log_det += torch.sum(ld, dim = 1)", "L @ (U + torch.diag(self.S)) self.W_inv = torch.inverse(W) x =", "nn.Parameter(torch.zeros(dim, dtype = torch.float)) def forward(self, x): z = x", "dim=1) + \\ torch.sum(s2_transformed, dim=1) return z, log_det def backward(self,", "L @ (U + torch.diag(self.S)) log_det = torch.sum(torch.log(torch.abs(self.S))) return z,", "= torch.cat([lower, upper], dim=1) log_det = torch.sum(-s1_transformed, dim=1) + \\", "dim = 1), torch.softmax(H, dim = 1) W, H =", "D = torch.split(out, self.K, dim = 2) W, H =", "\"\"\" Radial flow. z = f(x) = = x +", "for i in range(self.dim): if i == 0: init_param =", "* self.K - 1) W, H, D = torch.split(init_param, self.K,", "2, hidden_dim) def forward(self, x): log_det = torch.zeros(x.shape[0]) lower, upper", "-1) + \\ torch.diag(torch.ones(self.dim)) U = torch.triu(self.U, diagonal = 1)", "2, dim // 2, hidden_dim) def forward(self, x): lower, upper", "Mohamed 2015] \"\"\" def __init__(self, dim): super().__init__() self.x0 = nn.Parameter(torch.Tensor(dim))", "t2_transformed) * torch.exp(-s2_transformed) t1_transformed = self.t1(lower) s1_transformed = self.s1(lower) upper", "init.uniform_(self.u, -math.sqrt(1/dim), math.sqrt(1/dim)) init.uniform_(self.b, -math.sqrt(1/dim), math.sqrt(1/dim)) def forward(self, x): \"\"\"", "FCNN(nn.Module): \"\"\" Simple fully connected neural network. \"\"\" def __init__(self,", "inverse=False, tail_bound=self.B) log_det += ld return z, log_det def backward(self,", "hidden_dim = 8, base_network=FCNN): super().__init__() self.dim = dim self.t1 =", "lower * torch.exp(s2_transformed) z = torch.cat([lower, upper], dim=1) log_det =", "-math.sqrt(1/dim), math.sqrt(1/dim)) init.uniform_(self.b, -math.sqrt(1/dim), math.sqrt(1/dim)) def forward(self, x): \"\"\" Given", "= F.softplus(D) z[:, i], ld = unconstrained_RQS( x[:, i], W,", "+ torch.diag(self.S)) self.W_inv = torch.inverse(W) x = z @ self.W_inv", "reset_parameters(self): init.uniform_(self.init_param, - 1 / 2, 1 / 2) def", "class NSF_CL(nn.Module): \"\"\" Neural spline flow, coupling layer. [Durkan et", "self.layers[i - 1](x[:, :i]) mu, alpha = out[:, 0], out[:,", "dim): self.layers += [base_network(i, 2, hidden_dim)] self.reset_parameters() def reset_parameters(self): init.uniform_(self.initial_param,", "out = self.f2(upper).reshape(-1, self.dim // 2, 3 * self.K -", "return torch.cat([lower, upper], dim = 1), log_det def backward(self, z):", "H, D = torch.split(init_param, self.K, dim = 1) else: out", "* H D = F.softplus(D) x[:, i], ld = unconstrained_RQS(", "self.dim // 2:] out = self.f1(lower).reshape(-1, self.dim // 2, 3", "self.h in (F.elu, F.leaky_relu): u = self.u elif self.h ==", "nf.utils import unconstrained_RQS # supported non-linearities: note that the function", "= self.s1(lower) upper = t1_transformed + upper * torch.exp(s1_transformed) t2_transformed", "H, D = torch.split(out, self.K, dim = 2) W, H", "self.B * H D = F.softplus(D) lower, ld = unconstrained_RQS(", "= dim self.t1 = base_network(dim // 2, dim // 2,", "Mohamed, 2015] \"\"\" def __init__(self, dim, nonlinearity=torch.tanh): super().__init__() self.h =", "W, H, D, inverse = True, tail_bound = self.B) log_det", "i], W, H, D, inverse = True, tail_bound = self.B)", "torch.float)) def forward(self, x): z = x * torch.exp(self.log_sigma) +", "torch.softmax(H, dim = 1) W, H = 2 * self.B", "// 2], z[:,self.dim // 2:] t2_transformed = self.t2(upper) s2_transformed =", "\\ torch.log(1 + beta * h - \\ beta *", "z[:,self.dim // 2:] t2_transformed = self.t2(upper) s2_transformed = self.s2(upper) lower", "dtype = torch.float)) self.U = nn.Parameter(torch.triu(torch.tensor(U, dtype = torch.float), diagonal", "x, log_det class MAF(nn.Module): \"\"\" Masked auto-regressive flow. [Papamakarios et", "= dim self.K = K self.B = B self.f1 =", "* dim // 2, hidden_dim) self.f2 = base_network(dim // 2,", "1)) self.W_inv = None def forward(self, x): L = torch.tril(self.L,", "self.mu) / torch.exp(self.log_sigma) log_det = -torch.sum(self.log_sigma) return x, log_det class", "+= [base_network(i, 3 * K - 1, hidden_dim)] self.reset_parameters() def", "nn.ModuleList() self.initial_param = nn.Parameter(torch.Tensor(2)) for i in range(1, dim): self.layers", "= 2), torch.softmax(H, dim = 2) W, H = 2", "__init__(self, in_dim, out_dim, hidden_dim): super().__init__() self.network = nn.Sequential( nn.Linear(in_dim, hidden_dim),", "forward(self, x): return self.network(x) class RealNVP(nn.Module): \"\"\" Non-volume preserving flow.", "numpy as np import scipy as sp import scipy.linalg import", "W, H, D, inverse=False, tail_bound=self.B) log_det += torch.sum(ld, dim =", "3 * self.K - 1) W, H, D = torch.split(init_param,", "log_det class FCNN(nn.Module): \"\"\" Simple fully connected neural network. \"\"\"", "base_network(dim // 2, dim // 2, hidden_dim) self.t2 = base_network(dim", "z.flip(dims=(1,)), log_det def backward(self, z): x = torch.zeros_like(z) log_det =", "base_network=FCNN): super().__init__() self.dim = dim self.t1 = base_network(dim // 2,", "= dim self.mu = nn.Parameter(torch.zeros(dim, dtype = torch.float)) self.log_sigma =", "1) out = self.f2(upper).reshape(-1, self.dim // 2, 3 * self.K", "self.s2(upper) lower = (lower - t2_transformed) * torch.exp(-s2_transformed) t1_transformed =", "+ torch.diag(self.S)) log_det = torch.sum(torch.log(torch.abs(self.S))) return z, log_det def backward(self,", "= K self.B = B self.layers = nn.ModuleList() self.init_param =", "\"\"\" def __init__(self, in_dim, out_dim, hidden_dim): super().__init__() self.network = nn.Sequential(", "as init import torch.nn.functional as F from nf.utils import unconstrained_RQS", "(x < 0).type(torch.FloatTensor) * -0.01, F.elu: lambda x: (x >", "t1_transformed = self.t1(lower) s1_transformed = self.s1(lower) upper = t1_transformed +", "< 0).type(torch.FloatTensor) * torch.exp(x) } class Planar(nn.Module): \"\"\" Planar flow.", "x[:,self.dim // 2:] t1_transformed = self.t1(lower) s1_transformed = self.s1(lower) upper", "= F.softplus(D) lower, ld = unconstrained_RQS( lower, W, H, D,", "self.B * W, 2 * self.B * H D =", "K - 1) * dim // 2, hidden_dim) self.f2 =", "super().__init__() self.x0 = nn.Parameter(torch.Tensor(dim)) self.log_alpha = nn.Parameter(torch.Tensor(1)) self.beta = nn.Parameter(torch.Tensor(1))", "H, D, inverse=False, tail_bound=self.B) log_det += torch.sum(ld, dim = 1)", "self.x0 = nn.Parameter(torch.Tensor(dim)) self.log_alpha = nn.Parameter(torch.Tensor(1)) self.beta = nn.Parameter(torch.Tensor(1)) def", "= self.B) log_det += ld return x, log_det class NSF_CL(nn.Module):", "unconstrained_RQS( x[:, i], W, H, D, inverse=False, tail_bound=self.B) log_det +=", "= -1) + torch.diag(torch.ones(self.dim)) U = torch.triu(self.U, diagonal = 1)", "self.t2(upper) s2_transformed = self.s2(upper) lower = t2_transformed + lower *", "torch.log(1+torch.exp(self.w @ self.u)) - self.w @ self.u - 1 u", "= self.f2(upper).reshape(-1, self.dim // 2, 3 * self.K - 1)", "i in range(1, dim): self.layers += [base_network(i, 3 * K", "x): z = torch.zeros_like(x) log_det = torch.zeros(z.shape[0]) for i in", "torch.exp(self.beta)) z = x + beta * h * (x", "// 2, hidden_dim) def forward(self, x): lower, upper = x[:,:self.dim", "2, hidden_dim) def forward(self, x): lower, upper = x[:,:self.dim //" ]
[ "} fn = { \"sin\": math.sin, \"cos\": math.cos, \"tan\": math.tan,", "return bnf def evaluate_stack(s, stats): op, num_args = s.pop(), 0", "# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN", "div expop = Literal(\"^\") expr = Forward() expr_list = delimitedList(Group(expr))", "be # included in all copies or substantial portions of", "\"/\": operator.truediv, \"^\": operator.pow, } fn = { \"sin\": math.sin,", "2003-2019 <NAME> # # Permission is hereby granted, free of", "<<= atom + (expop + factor).setParseAction(push_first)[...] term = factor +", "multop factor ]* expr :: term [ addop term ]*", "permission notice shall be # included in all copies or", "multop = mult | div expop = Literal(\"^\") expr =", "= ppc.number().addParseAction(lambda t: str(t[0])) fnumber = Regex(r\"[+-]?\\d+(?:\\.\\d*)?(?:[eE][+-]?\\d+)?\") ident = Word(alphas,", "atom [ expop factor ]* term :: factor [ multop", "'exp'); Keyword # and CaselessKeyword only match whole words e", "]* \"\"\" # use CaselessKeyword for e and pi, to", ":: factor [ multop factor ]* expr :: term [", "KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO", "note: args are pushed onto the stack in reverse order", "\"+-*/\") lpar, rpar = map(Suppress, \"()\") addop = plus |", "# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION", "charge, to any person obtaining # a copy of this", "isinstance(op, tuple): op, num_args = op if op == \"unary", "AN ACTION OF CONTRACT, # TORT OR OTHERWISE, ARISING FROM,", ").setParseAction(push_unary_minus) # by defining exponentiation as \"atom [ ^ factor", "op in fn: # note: args are pushed onto the", "tuple): op, num_args = op if op == \"unary -\":", "ARISING FROM, OUT OF OR IN CONNECTION WITH THE #", "shall be # included in all copies or substantial portions", "(multop + factor).setParseAction(push_first)[...] expr <<= term + (addop + term).setParseAction(push_first)[...]", "only match whole words e = CaselessKeyword(\"E\") pi = CaselessKeyword(\"PI\")", "= 2^(3^2), not (2^3)^2. factor = Forward() factor <<= atom", "+ Optional(Word(nums))) + # Optional(e + Word(\"+-\"+nums, nums))) # or", "order args = reversed([evaluate_stack(s, stats) for _ in range(num_args)]) return", "in fn: # note: args are pushed onto the stack", "| '/' addop :: '+' | '-' integer :: ['+'", ") ).setParseAction(push_unary_minus) # by defining exponentiation as \"atom [ ^", "args) tuple fn_call = (ident + lpar - Group(expr_list) +", "factor <<= atom + (expop + factor).setParseAction(push_first)[...] term = factor", "sell copies of the Software, and to # permit persons", "operator.truediv, \"^\": operator.pow, } fn = { \"sin\": math.sin, \"cos\":", "[ ^ atom ]...\", we get right-to-left # exponents, instead", "factor [ multop factor ]* expr :: term [ addop", "portions of the Software. # # THE SOFTWARE IS PROVIDED", "= ( addop[...] + ( (fn_call | pi | e", "pyparsing_common.number, but convert back to str: # fnumber = ppc.number().addParseAction(lambda", "LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A", "mult | div expop = Literal(\"^\") expr = Forward() expr_list", "= CaselessKeyword(\"PI\") # fnumber = Combine(Word(\"+-\"+nums, nums) + # Optional(\".\"", "fnumber = ppc.number().addParseAction(lambda t: str(t[0])) fnumber = Regex(r\"[+-]?\\d+(?:\\.\\d*)?(?:[eE][+-]?\\d+)?\") ident =", "WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND", "# # The above copyright notice and this permission notice", "\"sin\": math.sin, \"cos\": math.cos, \"tan\": math.tan, \"exp\": math.exp, \"abs\": abs,", "[ expop factor ]* term :: factor [ multop factor", "publish, # distribute, sublicense, and/or sell copies of the Software,", "| ident).setParseAction(push_first) | Group(lpar + expr + rpar) ) ).setParseAction(push_unary_minus)", "TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR", "[] def push_first(toks): exprStack.append(toks[0]) def push_unary_minus(toks): for t in toks:", "Literal(\"^\") expr = Forward() expr_list = delimitedList(Group(expr)) # add parse", "= Regex(r\"[+-]?\\d+(?:\\.\\d*)?(?:[eE][+-]?\\d+)?\") ident = Word(alphas, alphanums + \"_$\") plus, minus,", "operator.pow, } fn = { \"sin\": math.sin, \"cos\": math.cos, \"tan\":", "return fn[op](*args) elif op[0].isalpha(): raise Exception(\"invalid identifier '%s'\" % op)", "not (2^3)^2. factor = Forward() factor <<= atom + (expop", "# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE", "{ \"sin\": math.sin, \"cos\": math.cos, \"tan\": math.tan, \"exp\": math.exp, \"abs\":", "def BNF(): \"\"\" expop :: '^' multop :: '*' |", "use, copy, modify, merge, publish, # distribute, sublicense, and/or sell", "THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE", "| e | fnumber | ident).setParseAction(push_first) | Group(lpar + expr", "= Forward() factor <<= atom + (expop + factor).setParseAction(push_first)[...] term", "= reversed([evaluate_stack(s, stats) for _ in range(num_args)]) return fn[op](*args) elif", "AND NONINFRINGEMENT. # IN NO EVENT SHALL THE AUTHORS OR", ") import math import operator # map operator symbols to", "exponentiation as \"atom [ ^ factor ]...\" instead of \"atom", "modify, merge, publish, # distribute, sublicense, and/or sell copies of", "== \"unary -\": return -evaluate_stack(s, stats) if op in \"+-*/^\":", "THE # SOFTWARE OR THE USE OR OTHER DEALINGS IN", "# 2.718281828 elif op == \"mean\": return stats['mean'] elif op", "opn = { \"+\": operator.add, \"-\": operator.sub, \"*\": operator.mul, \"/\":", "\"max\": return stats['max'] elif op == \"std\": return stats['std'] elif", "(c) 2003-2019 <NAME> # # Permission is hereby granted, free", "2^(3^2), not (2^3)^2. factor = Forward() factor <<= atom +", "elif op in fn: # note: args are pushed onto", "lpar - Group(expr_list) + rpar).setParseAction( lambda t: t.insert(0, (t.pop(0), len(t[0])))", "to # the following conditions: # # The above copyright", "== \"max\": return stats['max'] elif op == \"std\": return stats['std']", "without restriction, including # without limitation the rights to use,", "term).setParseAction(push_first)[...] bnf = expr return bnf def evaluate_stack(s, stats): op,", "OF CONTRACT, # TORT OR OTHERWISE, ARISING FROM, OUT OF", "but convert back to str: # fnumber = ppc.number().addParseAction(lambda t:", "return math.pi # 3.1415926535 elif op == \"E\": return math.e", "sublicense, and/or sell copies of the Software, and to #", "THE SOFTWARE. # from pyparsing import ( Literal, Word, Group,", "DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,", "MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. # IN", "# fnumber = ppc.number().addParseAction(lambda t: str(t[0])) fnumber = Regex(r\"[+-]?\\d+(?:\\.\\d*)?(?:[eE][+-]?\\d+)?\") ident", "e and pi, to avoid accidentally matching # functions that", "with a (name, number of args) tuple fn_call = (ident", "persons to whom the Software is furnished to do so,", "op == \"E\": return math.e # 2.718281828 elif op ==", "OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH", "start with 'e' or 'pi' (such as 'exp'); Keyword #", "= (ident + lpar - Group(expr_list) + rpar).setParseAction( lambda t:", "the Software. # # THE SOFTWARE IS PROVIDED \"AS IS\",", "# or use provided pyparsing_common.number, but convert back to str:", "== \"min\": return stats['min'] elif op == \"max\": return stats['max']", "+ (expop + factor).setParseAction(push_first)[...] term = factor + (multop +", "result\"\"\" _ = BNF().parseString(fx, parseAll=True) val = evaluate_stack(exprStack[:], stats) return", "op1 = evaluate_stack(s, stats) return opn[op](op1, op2) elif op ==", "use CaselessKeyword for e and pi, to avoid accidentally matching", "<<= term + (addop + term).setParseAction(push_first)[...] bnf = expr return", "FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. # IN NO EVENT", "operator.sub, \"*\": operator.mul, \"/\": operator.truediv, \"^\": operator.pow, } fn =", "all copies or substantial portions of the Software. # #", "instead of \"atom [ ^ atom ]...\", we get right-to-left", "BE LIABLE FOR ANY # CLAIM, DAMAGES OR OTHER LIABILITY,", "operator symbols to corresponding arithmetic operations epsilon = 1e-12 opn", "including # without limitation the rights to use, copy, modify,", "op if op == \"unary -\": return -evaluate_stack(s, stats) if", "stats['std'] elif op in fn: # note: args are pushed", "pyparsing.py # # Copyright (c) 2003-2019 <NAME> # # Permission", "# without limitation the rights to use, copy, modify, merge,", "# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF", "rpar = map(Suppress, \"()\") addop = plus | minus multop", "if a < -epsilon else 1 if a > epsilon", "| div expop = Literal(\"^\") expr = Forward() expr_list =", "lambda a: -1 if a < -epsilon else 1 if", "plus, minus, mult, div = map(Literal, \"+-*/\") lpar, rpar =", "+ rpar).setParseAction( lambda t: t.insert(0, (t.pop(0), len(t[0]))) ) atom =", "t: str(t[0])) fnumber = Regex(r\"[+-]?\\d+(?:\\.\\d*)?(?:[eE][+-]?\\d+)?\") ident = Word(alphas, alphanums +", "Word, Group, Forward, alphas, alphanums, Regex, CaselessKeyword, Suppress, delimitedList, )", "{ \"+\": operator.add, \"-\": operator.sub, \"*\": operator.mul, \"/\": operator.truediv, \"^\":", "identifier with a (name, number of args) tuple fn_call =", "= s.pop(), 0 if isinstance(op, tuple): op, num_args = op", "included in all copies or substantial portions of the Software.", "def push_unary_minus(toks): for t in toks: if t == \"-\":", "A PARTICULAR PURPOSE AND NONINFRINGEMENT. # IN NO EVENT SHALL", "and pi, to avoid accidentally matching # functions that start", "len(t[0]))) ) atom = ( addop[...] + ( (fn_call |", "HOLDERS BE LIABLE FOR ANY # CLAIM, DAMAGES OR OTHER", "'0'..'9'+ atom :: PI | E | real | fn", "to do so, subject to # the following conditions: #", "Word(\"+-\"+nums, nums))) # or use provided pyparsing_common.number, but convert back", "for _ in range(num_args)]) return fn[op](*args) elif op[0].isalpha(): raise Exception(\"invalid", "\"atom [ ^ factor ]...\" instead of \"atom [ ^", "notice shall be # included in all copies or substantial", "as 'exp'); Keyword # and CaselessKeyword only match whole words", "term = factor + (multop + factor).setParseAction(push_first)[...] expr <<= term", "op2) elif op == \"PI\": return math.pi # 3.1415926535 elif", "Software without restriction, including # without limitation the rights to", "fn: # note: args are pushed onto the stack in", "(the # \"Software\"), to deal in the Software without restriction,", "# The above copyright notice and this permission notice shall", "^ factor ]...\" instead of \"atom [ ^ atom ]...\",", "+ Word(\"+-\"+nums, nums))) # or use provided pyparsing_common.number, but convert", "\"unary -\": return -evaluate_stack(s, stats) if op in \"+-*/^\": #", "op2 = evaluate_stack(s, stats) op1 = evaluate_stack(s, stats) return opn[op](op1,", "| real | fn '(' expr ')' | '(' expr", "return stats['min'] elif op == \"max\": return stats['max'] elif op", "EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR", "a: int(a), \"round\": round, \"sgn\": lambda a: -1 if a", "in the Software without restriction, including # without limitation the", "# # Copyright (c) 2003-2019 <NAME> # # Permission is", "return float(op) def eval_fx(fx, stats): \"\"\"Given fx and stats ('min',", "EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES", "Group, Forward, alphas, alphanums, Regex, CaselessKeyword, Suppress, delimitedList, ) import", "# map operator symbols to corresponding arithmetic operations epsilon =", "= { \"+\": operator.add, \"-\": operator.sub, \"*\": operator.mul, \"/\": operator.truediv,", "operator.mul, \"/\": operator.truediv, \"^\": operator.pow, } fn = { \"sin\":", "defining exponentiation as \"atom [ ^ factor ]...\" instead of", "IS\", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED,", "expr ')' factor :: atom [ expop factor ]* term", "reverse order args = reversed([evaluate_stack(s, stats) for _ in range(num_args)])", "of this software and associated documentation files (the # \"Software\"),", "subject to # the following conditions: # # The above", "that replaces the function identifier with a (name, number of", "2^3^2 = 2^(3^2), not (2^3)^2. factor = Forward() factor <<=", "# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS", "+ expr + rpar) ) ).setParseAction(push_unary_minus) # by defining exponentiation", "if t == \"-\": exprStack.append(\"unary -\") else: break def BNF():", "DEALINGS IN THE SOFTWARE. # from pyparsing import ( Literal,", "+ factor).setParseAction(push_first)[...] term = factor + (multop + factor).setParseAction(push_first)[...] expr", "(fn_call | pi | e | fnumber | ident).setParseAction(push_first) |", "-epsilon else 1 if a > epsilon else 0, }", "# note: operands are pushed onto the stack in reverse", "for t in toks: if t == \"-\": exprStack.append(\"unary -\")", "to use, copy, modify, merge, publish, # distribute, sublicense, and/or", "following conditions: # # The above copyright notice and this", "ident = Word(alphas, alphanums + \"_$\") plus, minus, mult, div", "\"+-*/^\": # note: operands are pushed onto the stack in", "alphanums, Regex, CaselessKeyword, Suppress, delimitedList, ) import math import operator", "term :: factor [ multop factor ]* expr :: term", "conditions: # # The above copyright notice and this permission", "t in toks: if t == \"-\": exprStack.append(\"unary -\") else:", "Combine(Word(\"+-\"+nums, nums) + # Optional(\".\" + Optional(Word(nums))) + # Optional(e", "\"mean\": return stats['mean'] elif op == \"min\": return stats['min'] elif", "evaluate_stack(s, stats) op1 = evaluate_stack(s, stats) return opn[op](op1, op2) elif", "+ \"_$\") plus, minus, mult, div = map(Literal, \"+-*/\") lpar,", "( Literal, Word, Group, Forward, alphas, alphanums, Regex, CaselessKeyword, Suppress,", "elif op == \"min\": return stats['min'] elif op == \"max\":", "a > epsilon else 0, } exprStack = [] def", "= Literal(\"^\") expr = Forward() expr_list = delimitedList(Group(expr)) # add", "+ # Optional(\".\" + Optional(Word(nums))) + # Optional(e + Word(\"+-\"+nums,", "stats['min'] elif op == \"max\": return stats['max'] elif op ==", "elif op == \"max\": return stats['max'] elif op == \"std\":", "whole words e = CaselessKeyword(\"E\") pi = CaselessKeyword(\"PI\") # fnumber", "args = reversed([evaluate_stack(s, stats) for _ in range(num_args)]) return fn[op](*args)", "term ]* \"\"\" # use CaselessKeyword for e and pi,", "op[0].isalpha(): raise Exception(\"invalid identifier '%s'\" % op) else: return float(op)", "integer :: ['+' | '-'] '0'..'9'+ atom :: PI |", "float(op) def eval_fx(fx, stats): \"\"\"Given fx and stats ('min', 'max',", "= { \"sin\": math.sin, \"cos\": math.cos, \"tan\": math.tan, \"exp\": math.exp,", "(name, number of args) tuple fn_call = (ident + lpar", "LIABILITY, WHETHER IN AN ACTION OF CONTRACT, # TORT OR", "accidentally matching # functions that start with 'e' or 'pi'", "number of args) tuple fn_call = (ident + lpar -", "obtaining # a copy of this software and associated documentation", "= map(Literal, \"+-*/\") lpar, rpar = map(Suppress, \"()\") addop =", "\"-\": operator.sub, \"*\": operator.mul, \"/\": operator.truediv, \"^\": operator.pow, } fn", "exprStack.append(toks[0]) def push_unary_minus(toks): for t in toks: if t ==", "in \"+-*/^\": # note: operands are pushed onto the stack", "SOFTWARE. # from pyparsing import ( Literal, Word, Group, Forward,", "free of charge, to any person obtaining # a copy", "# Optional(e + Word(\"+-\"+nums, nums))) # or use provided pyparsing_common.number,", "if op == \"unary -\": return -evaluate_stack(s, stats) if op", "PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, # EXPRESS", "copy of this software and associated documentation files (the #", "factor :: atom [ expop factor ]* term :: factor", "alphas, alphanums, Regex, CaselessKeyword, Suppress, delimitedList, ) import math import", "copy, modify, merge, publish, # distribute, sublicense, and/or sell copies", "(2^3)^2. factor = Forward() factor <<= atom + (expop +", "(expop + factor).setParseAction(push_first)[...] term = factor + (multop + factor).setParseAction(push_first)[...]", "return stats['max'] elif op == \"std\": return stats['std'] elif op", "instead of left-to-right that is, 2^3^2 = 2^(3^2), not (2^3)^2.", "'max', 'mean', 'std') return the result\"\"\" _ = BNF().parseString(fx, parseAll=True)", "== \"std\": return stats['std'] elif op in fn: # note:", "div = map(Literal, \"+-*/\") lpar, rpar = map(Suppress, \"()\") addop", "abs, \"trunc\": lambda a: int(a), \"round\": round, \"sgn\": lambda a:", "IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF #", "by defining exponentiation as \"atom [ ^ factor ]...\" instead", "is hereby granted, free of charge, to any person obtaining", "THE USE OR OTHER DEALINGS IN THE SOFTWARE. # from", "toks: if t == \"-\": exprStack.append(\"unary -\") else: break def", "\"\"\" # use CaselessKeyword for e and pi, to avoid", "CaselessKeyword for e and pi, to avoid accidentally matching #", "plus | minus multop = mult | div expop =", "evaluate_stack(s, stats): op, num_args = s.pop(), 0 if isinstance(op, tuple):", "of charge, to any person obtaining # a copy of", "above copyright notice and this permission notice shall be #", "| fnumber | ident).setParseAction(push_first) | Group(lpar + expr + rpar)", "tuple fn_call = (ident + lpar - Group(expr_list) + rpar).setParseAction(", "raise Exception(\"invalid identifier '%s'\" % op) else: return float(op) def", "= delimitedList(Group(expr)) # add parse action that replaces the function", "PARTICULAR PURPOSE AND NONINFRINGEMENT. # IN NO EVENT SHALL THE", "'std') return the result\"\"\" _ = BNF().parseString(fx, parseAll=True) val =", "atom = ( addop[...] + ( (fn_call | pi |", "expr return bnf def evaluate_stack(s, stats): op, num_args = s.pop(),", "+ factor).setParseAction(push_first)[...] expr <<= term + (addop + term).setParseAction(push_first)[...] bnf", "OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, # TORT", "push_unary_minus(toks): for t in toks: if t == \"-\": exprStack.append(\"unary", "else 1 if a > epsilon else 0, } exprStack", "Regex(r\"[+-]?\\d+(?:\\.\\d*)?(?:[eE][+-]?\\d+)?\") ident = Word(alphas, alphanums + \"_$\") plus, minus, mult,", "# # Permission is hereby granted, free of charge, to", "'-'] '0'..'9'+ atom :: PI | E | real |", "str: # fnumber = ppc.number().addParseAction(lambda t: str(t[0])) fnumber = Regex(r\"[+-]?\\d+(?:\\.\\d*)?(?:[eE][+-]?\\d+)?\")", "expop = Literal(\"^\") expr = Forward() expr_list = delimitedList(Group(expr)) #", "order op2 = evaluate_stack(s, stats) op1 = evaluate_stack(s, stats) return", "permit persons to whom the Software is furnished to do", "elif op == \"E\": return math.e # 2.718281828 elif op", "')' | '(' expr ')' factor :: atom [ expop", "copies of the Software, and to # permit persons to", "# functions that start with 'e' or 'pi' (such as", "args are pushed onto the stack in reverse order args", "# and CaselessKeyword only match whole words e = CaselessKeyword(\"E\")", "fnumber = Regex(r\"[+-]?\\d+(?:\\.\\d*)?(?:[eE][+-]?\\d+)?\") ident = Word(alphas, alphanums + \"_$\") plus,", "]* term :: factor [ multop factor ]* expr ::", "expr ')' | '(' expr ')' factor :: atom [", "'+' | '-' integer :: ['+' | '-'] '0'..'9'+ atom", "that start with 'e' or 'pi' (such as 'exp'); Keyword", "the stack in reverse order args = reversed([evaluate_stack(s, stats) for", "math import operator # map operator symbols to corresponding arithmetic", "PURPOSE AND NONINFRINGEMENT. # IN NO EVENT SHALL THE AUTHORS", "stats) if op in \"+-*/^\": # note: operands are pushed", "\"PI\": return math.pi # 3.1415926535 elif op == \"E\": return", "'*' | '/' addop :: '+' | '-' integer ::", "fnumber | ident).setParseAction(push_first) | Group(lpar + expr + rpar) )", "= CaselessKeyword(\"E\") pi = CaselessKeyword(\"PI\") # fnumber = Combine(Word(\"+-\"+nums, nums)", "+ ( (fn_call | pi | e | fnumber |", "and associated documentation files (the # \"Software\"), to deal in", "or substantial portions of the Software. # # THE SOFTWARE", "operator # map operator symbols to corresponding arithmetic operations epsilon", "+ lpar - Group(expr_list) + rpar).setParseAction( lambda t: t.insert(0, (t.pop(0),", "stats ('min', 'max', 'mean', 'std') return the result\"\"\" _ =", "CaselessKeyword(\"E\") pi = CaselessKeyword(\"PI\") # fnumber = Combine(Word(\"+-\"+nums, nums) +", "OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT", "reversed([evaluate_stack(s, stats) for _ in range(num_args)]) return fn[op](*args) elif op[0].isalpha():", "Suppress, delimitedList, ) import math import operator # map operator", "rpar).setParseAction( lambda t: t.insert(0, (t.pop(0), len(t[0]))) ) atom = (", "math.tan, \"exp\": math.exp, \"abs\": abs, \"trunc\": lambda a: int(a), \"round\":", "stack in reverse order op2 = evaluate_stack(s, stats) op1 =", ":: '^' multop :: '*' | '/' addop :: '+'", "# fnumber = Combine(Word(\"+-\"+nums, nums) + # Optional(\".\" + Optional(Word(nums)))", "[ addop term ]* \"\"\" # use CaselessKeyword for e", "mult, div = map(Literal, \"+-*/\") lpar, rpar = map(Suppress, \"()\")", "CaselessKeyword(\"PI\") # fnumber = Combine(Word(\"+-\"+nums, nums) + # Optional(\".\" +", "^ atom ]...\", we get right-to-left # exponents, instead of", "or use provided pyparsing_common.number, but convert back to str: #", "bnf = expr return bnf def evaluate_stack(s, stats): op, num_args", "# Permission is hereby granted, free of charge, to any", "the Software is furnished to do so, subject to #", "# # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY", "= 1e-12 opn = { \"+\": operator.add, \"-\": operator.sub, \"*\":", "op == \"min\": return stats['min'] elif op == \"max\": return", "2.718281828 elif op == \"mean\": return stats['mean'] elif op ==", "provided pyparsing_common.number, but convert back to str: # fnumber =", "without limitation the rights to use, copy, modify, merge, publish,", "> epsilon else 0, } exprStack = [] def push_first(toks):", "== \"mean\": return stats['mean'] elif op == \"min\": return stats['min']", "for e and pi, to avoid accidentally matching # functions", "Word(alphas, alphanums + \"_$\") plus, minus, mult, div = map(Literal,", "minus multop = mult | div expop = Literal(\"^\") expr", "pyparsing import ( Literal, Word, Group, Forward, alphas, alphanums, Regex,", "IN THE SOFTWARE. # from pyparsing import ( Literal, Word,", "1e-12 opn = { \"+\": operator.add, \"-\": operator.sub, \"*\": operator.mul,", "} exprStack = [] def push_first(toks): exprStack.append(toks[0]) def push_unary_minus(toks): for", "pushed onto the stack in reverse order op2 = evaluate_stack(s,", "ppc.number().addParseAction(lambda t: str(t[0])) fnumber = Regex(r\"[+-]?\\d+(?:\\.\\d*)?(?:[eE][+-]?\\d+)?\") ident = Word(alphas, alphanums", "merge, publish, # distribute, sublicense, and/or sell copies of the", "'^' multop :: '*' | '/' addop :: '+' |", "limitation the rights to use, copy, modify, merge, publish, #", "else: return float(op) def eval_fx(fx, stats): \"\"\"Given fx and stats", "stats) return opn[op](op1, op2) elif op == \"PI\": return math.pi", "USE OR OTHER DEALINGS IN THE SOFTWARE. # from pyparsing", "exprStack = [] def push_first(toks): exprStack.append(toks[0]) def push_unary_minus(toks): for t", "op) else: return float(op) def eval_fx(fx, stats): \"\"\"Given fx and", "elif op[0].isalpha(): raise Exception(\"invalid identifier '%s'\" % op) else: return", "factor + (multop + factor).setParseAction(push_first)[...] expr <<= term + (addop", "OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF", "| '-'] '0'..'9'+ atom :: PI | E | real", "0 if isinstance(op, tuple): op, num_args = op if op", "so, subject to # the following conditions: # # The", "the stack in reverse order op2 = evaluate_stack(s, stats) op1", "IN CONNECTION WITH THE # SOFTWARE OR THE USE OR", "stats): op, num_args = s.pop(), 0 if isinstance(op, tuple): op,", "\"\"\"Given fx and stats ('min', 'max', 'mean', 'std') return the", "do so, subject to # the following conditions: # #", "identifier '%s'\" % op) else: return float(op) def eval_fx(fx, stats):", "# Copyright (c) 2003-2019 <NAME> # # Permission is hereby", "< -epsilon else 1 if a > epsilon else 0,", ":: atom [ expop factor ]* term :: factor [", "\"abs\": abs, \"trunc\": lambda a: int(a), \"round\": round, \"sgn\": lambda", "| pi | e | fnumber | ident).setParseAction(push_first) | Group(lpar", "the rights to use, copy, modify, merge, publish, # distribute,", "IN AN ACTION OF CONTRACT, # TORT OR OTHERWISE, ARISING", "if op in \"+-*/^\": # note: operands are pushed onto", "are pushed onto the stack in reverse order args =", "WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING", "= expr return bnf def evaluate_stack(s, stats): op, num_args =", "Software, and to # permit persons to whom the Software", "fnumber = Combine(Word(\"+-\"+nums, nums) + # Optional(\".\" + Optional(Word(nums))) +", "stats['mean'] elif op == \"min\": return stats['min'] elif op ==", "the following conditions: # # The above copyright notice and", "distribute, sublicense, and/or sell copies of the Software, and to", "# \"Software\"), to deal in the Software without restriction, including", "]...\" instead of \"atom [ ^ atom ]...\", we get", "# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. #", "ACTION OF CONTRACT, # TORT OR OTHERWISE, ARISING FROM, OUT", "this permission notice shall be # included in all copies", "# by defining exponentiation as \"atom [ ^ factor ]...\"", "parse action that replaces the function identifier with a (name,", "# module pyparsing.py # # Copyright (c) 2003-2019 <NAME> #", "lambda a: int(a), \"round\": round, \"sgn\": lambda a: -1 if", "num_args = s.pop(), 0 if isinstance(op, tuple): op, num_args =", "Regex, CaselessKeyword, Suppress, delimitedList, ) import math import operator #", "are pushed onto the stack in reverse order op2 =", "expop factor ]* term :: factor [ multop factor ]*", "| '(' expr ')' factor :: atom [ expop factor", "(ident + lpar - Group(expr_list) + rpar).setParseAction( lambda t: t.insert(0,", "factor).setParseAction(push_first)[...] expr <<= term + (addop + term).setParseAction(push_first)[...] bnf =", "to whom the Software is furnished to do so, subject", "atom :: PI | E | real | fn '('", "else 0, } exprStack = [] def push_first(toks): exprStack.append(toks[0]) def", "= Word(alphas, alphanums + \"_$\") plus, minus, mult, div =", "notice and this permission notice shall be # included in", ":: ['+' | '-'] '0'..'9'+ atom :: PI | E", "= factor + (multop + factor).setParseAction(push_first)[...] expr <<= term +", "WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT", "# add parse action that replaces the function identifier with", "# a copy of this software and associated documentation files", "return math.e # 2.718281828 elif op == \"mean\": return stats['mean']", "OR OTHER DEALINGS IN THE SOFTWARE. # from pyparsing import", "function identifier with a (name, number of args) tuple fn_call", "operands are pushed onto the stack in reverse order op2", "symbols to corresponding arithmetic operations epsilon = 1e-12 opn =", "+ (multop + factor).setParseAction(push_first)[...] expr <<= term + (addop +", "CaselessKeyword only match whole words e = CaselessKeyword(\"E\") pi =", "Software. # # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT", "return stats['std'] elif op in fn: # note: args are", "| fn '(' expr ')' | '(' expr ')' factor", "E | real | fn '(' expr ')' | '('", "Software is furnished to do so, subject to # the", "\"*\": operator.mul, \"/\": operator.truediv, \"^\": operator.pow, } fn = {", "reverse order op2 = evaluate_stack(s, stats) op1 = evaluate_stack(s, stats)", "def push_first(toks): exprStack.append(toks[0]) def push_unary_minus(toks): for t in toks: if", "BNF(): \"\"\" expop :: '^' multop :: '*' | '/'", "IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, #", "ident).setParseAction(push_first) | Group(lpar + expr + rpar) ) ).setParseAction(push_unary_minus) #", "expr = Forward() expr_list = delimitedList(Group(expr)) # add parse action", "epsilon = 1e-12 opn = { \"+\": operator.add, \"-\": operator.sub,", "fn[op](*args) elif op[0].isalpha(): raise Exception(\"invalid identifier '%s'\" % op) else:", "AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY # CLAIM,", "t.insert(0, (t.pop(0), len(t[0]))) ) atom = ( addop[...] + (", "with 'e' or 'pi' (such as 'exp'); Keyword # and", "module pyparsing.py # # Copyright (c) 2003-2019 <NAME> # #", "t == \"-\": exprStack.append(\"unary -\") else: break def BNF(): \"\"\"", "# Optional(\".\" + Optional(Word(nums))) + # Optional(e + Word(\"+-\"+nums, nums)))", "stats['max'] elif op == \"std\": return stats['std'] elif op in", "delimitedList, ) import math import operator # map operator symbols", "person obtaining # a copy of this software and associated", "OR COPYRIGHT HOLDERS BE LIABLE FOR ANY # CLAIM, DAMAGES", "# use CaselessKeyword for e and pi, to avoid accidentally", "| '-' integer :: ['+' | '-'] '0'..'9'+ atom ::", "# included in all copies or substantial portions of the", "addop = plus | minus multop = mult | div", "Exception(\"invalid identifier '%s'\" % op) else: return float(op) def eval_fx(fx,", "Group(lpar + expr + rpar) ) ).setParseAction(push_unary_minus) # by defining", "NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR", "'mean', 'std') return the result\"\"\" _ = BNF().parseString(fx, parseAll=True) val", "== \"PI\": return math.pi # 3.1415926535 elif op == \"E\":", "]...\", we get right-to-left # exponents, instead of left-to-right that", "op == \"std\": return stats['std'] elif op in fn: #", "expr + rpar) ) ).setParseAction(push_unary_minus) # by defining exponentiation as", "\"exp\": math.exp, \"abs\": abs, \"trunc\": lambda a: int(a), \"round\": round,", "THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY", "NONINFRINGEMENT. # IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT", "('min', 'max', 'mean', 'std') return the result\"\"\" _ = BNF().parseString(fx,", "substantial portions of the Software. # # THE SOFTWARE IS", "to any person obtaining # a copy of this software", "lpar, rpar = map(Suppress, \"()\") addop = plus | minus", "== \"-\": exprStack.append(\"unary -\") else: break def BNF(): \"\"\" expop", "map(Suppress, \"()\") addop = plus | minus multop = mult", "the Software, and to # permit persons to whom the", "onto the stack in reverse order args = reversed([evaluate_stack(s, stats)", "'%s'\" % op) else: return float(op) def eval_fx(fx, stats): \"\"\"Given", "map(Literal, \"+-*/\") lpar, rpar = map(Suppress, \"()\") addop = plus", "\"AS IS\", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR", "functions that start with 'e' or 'pi' (such as 'exp');", "of the Software, and to # permit persons to whom", "SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,", "exprStack.append(\"unary -\") else: break def BNF(): \"\"\" expop :: '^'", "expr_list = delimitedList(Group(expr)) # add parse action that replaces the", "pi | e | fnumber | ident).setParseAction(push_first) | Group(lpar +", "return opn[op](op1, op2) elif op == \"PI\": return math.pi #", "of left-to-right that is, 2^3^2 = 2^(3^2), not (2^3)^2. factor", "avoid accidentally matching # functions that start with 'e' or", "onto the stack in reverse order op2 = evaluate_stack(s, stats)", "op == \"unary -\": return -evaluate_stack(s, stats) if op in", "left-to-right that is, 2^3^2 = 2^(3^2), not (2^3)^2. factor =", "= plus | minus multop = mult | div expop", "add parse action that replaces the function identifier with a", "pi = CaselessKeyword(\"PI\") # fnumber = Combine(Word(\"+-\"+nums, nums) + #", "Literal, Word, Group, Forward, alphas, alphanums, Regex, CaselessKeyword, Suppress, delimitedList,", "\"()\") addop = plus | minus multop = mult |", "rights to use, copy, modify, merge, publish, # distribute, sublicense,", "= mult | div expop = Literal(\"^\") expr = Forward()", "factor = Forward() factor <<= atom + (expop + factor).setParseAction(push_first)[...]", "term + (addop + term).setParseAction(push_first)[...] bnf = expr return bnf", "copyright notice and this permission notice shall be # included", "matching # functions that start with 'e' or 'pi' (such", "(such as 'exp'); Keyword # and CaselessKeyword only match whole", "and/or sell copies of the Software, and to # permit", "action that replaces the function identifier with a (name, number", "\"+\": operator.add, \"-\": operator.sub, \"*\": operator.mul, \"/\": operator.truediv, \"^\": operator.pow,", "'(' expr ')' factor :: atom [ expop factor ]*", "\"-\": exprStack.append(\"unary -\") else: break def BNF(): \"\"\" expop ::", "to # permit persons to whom the Software is furnished", "def evaluate_stack(s, stats): op, num_args = s.pop(), 0 if isinstance(op,", "evaluate_stack(s, stats) return opn[op](op1, op2) elif op == \"PI\": return", "num_args = op if op == \"unary -\": return -evaluate_stack(s,", "<NAME> # # Permission is hereby granted, free of charge,", "math.exp, \"abs\": abs, \"trunc\": lambda a: int(a), \"round\": round, \"sgn\":", "OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.", "this software and associated documentation files (the # \"Software\"), to", "SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY", "+ term).setParseAction(push_first)[...] bnf = expr return bnf def evaluate_stack(s, stats):", "of the Software. # # THE SOFTWARE IS PROVIDED \"AS", "Group(expr_list) + rpar).setParseAction( lambda t: t.insert(0, (t.pop(0), len(t[0]))) ) atom", "is furnished to do so, subject to # the following", "( (fn_call | pi | e | fnumber | ident).setParseAction(push_first)", "fn_call = (ident + lpar - Group(expr_list) + rpar).setParseAction( lambda", "push_first(toks): exprStack.append(toks[0]) def push_unary_minus(toks): for t in toks: if t", "Optional(Word(nums))) + # Optional(e + Word(\"+-\"+nums, nums))) # or use", "expr :: term [ addop term ]* \"\"\" # use", "return the result\"\"\" _ = BNF().parseString(fx, parseAll=True) val = evaluate_stack(exprStack[:],", "whom the Software is furnished to do so, subject to", "OR IN CONNECTION WITH THE # SOFTWARE OR THE USE", "\"min\": return stats['min'] elif op == \"max\": return stats['max'] elif", "\"trunc\": lambda a: int(a), \"round\": round, \"sgn\": lambda a: -1", "OF OR IN CONNECTION WITH THE # SOFTWARE OR THE", "'e' or 'pi' (such as 'exp'); Keyword # and CaselessKeyword", "def eval_fx(fx, stats): \"\"\"Given fx and stats ('min', 'max', 'mean',", "# permit persons to whom the Software is furnished to", "the result\"\"\" _ = BNF().parseString(fx, parseAll=True) val = evaluate_stack(exprStack[:], stats)", "and stats ('min', 'max', 'mean', 'std') return the result\"\"\" _", "return -evaluate_stack(s, stats) if op in \"+-*/^\": # note: operands", "math.pi # 3.1415926535 elif op == \"E\": return math.e #", "factor ]* term :: factor [ multop factor ]* expr", "pi, to avoid accidentally matching # functions that start with", "(t.pop(0), len(t[0]))) ) atom = ( addop[...] + ( (fn_call", ":: term [ addop term ]* \"\"\" # use CaselessKeyword", "e = CaselessKeyword(\"E\") pi = CaselessKeyword(\"PI\") # fnumber = Combine(Word(\"+-\"+nums,", "a copy of this software and associated documentation files (the", "# the following conditions: # # The above copyright notice", "1 if a > epsilon else 0, } exprStack =", "files (the # \"Software\"), to deal in the Software without", "documentation files (the # \"Software\"), to deal in the Software", "alphanums + \"_$\") plus, minus, mult, div = map(Literal, \"+-*/\")", "in reverse order op2 = evaluate_stack(s, stats) op1 = evaluate_stack(s,", "-\") else: break def BNF(): \"\"\" expop :: '^' multop", "real | fn '(' expr ')' | '(' expr ')'", "lambda t: t.insert(0, (t.pop(0), len(t[0]))) ) atom = ( addop[...]", "stats): \"\"\"Given fx and stats ('min', 'max', 'mean', 'std') return", "\"_$\") plus, minus, mult, div = map(Literal, \"+-*/\") lpar, rpar", "and this permission notice shall be # included in all", "'(' expr ')' | '(' expr ')' factor :: atom", "op, num_args = s.pop(), 0 if isinstance(op, tuple): op, num_args", "WHETHER IN AN ACTION OF CONTRACT, # TORT OR OTHERWISE,", "- Group(expr_list) + rpar).setParseAction( lambda t: t.insert(0, (t.pop(0), len(t[0]))) )", "or 'pi' (such as 'exp'); Keyword # and CaselessKeyword only", "fn '(' expr ')' | '(' expr ')' factor ::", "and to # permit persons to whom the Software is", "BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS", "CONNECTION WITH THE # SOFTWARE OR THE USE OR OTHER", "+ rpar) ) ).setParseAction(push_unary_minus) # by defining exponentiation as \"atom", "factor ]...\" instead of \"atom [ ^ atom ]...\", we", "factor).setParseAction(push_first)[...] term = factor + (multop + factor).setParseAction(push_first)[...] expr <<=", "to corresponding arithmetic operations epsilon = 1e-12 opn = {", "if a > epsilon else 0, } exprStack = []", ":: '*' | '/' addop :: '+' | '-' integer", "import operator # map operator symbols to corresponding arithmetic operations", "epsilon else 0, } exprStack = [] def push_first(toks): exprStack.append(toks[0])", "a < -epsilon else 1 if a > epsilon else", "expop :: '^' multop :: '*' | '/' addop ::", "CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF", "| minus multop = mult | div expop = Literal(\"^\")", "arithmetic operations epsilon = 1e-12 opn = { \"+\": operator.add,", "| E | real | fn '(' expr ')' |", "Optional(e + Word(\"+-\"+nums, nums))) # or use provided pyparsing_common.number, but", "OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #", "term [ addop term ]* \"\"\" # use CaselessKeyword for", ") atom = ( addop[...] + ( (fn_call | pi", "bnf def evaluate_stack(s, stats): op, num_args = s.pop(), 0 if", "range(num_args)]) return fn[op](*args) elif op[0].isalpha(): raise Exception(\"invalid identifier '%s'\" %", "Optional(\".\" + Optional(Word(nums))) + # Optional(e + Word(\"+-\"+nums, nums))) #", "FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. # IN NO", "WITH THE # SOFTWARE OR THE USE OR OTHER DEALINGS", "exponents, instead of left-to-right that is, 2^3^2 = 2^(3^2), not", "convert back to str: # fnumber = ppc.number().addParseAction(lambda t: str(t[0]))", "str(t[0])) fnumber = Regex(r\"[+-]?\\d+(?:\\.\\d*)?(?:[eE][+-]?\\d+)?\") ident = Word(alphas, alphanums + \"_$\")", "# from pyparsing import ( Literal, Word, Group, Forward, alphas,", "if isinstance(op, tuple): op, num_args = op if op ==", "elif op == \"PI\": return math.pi # 3.1415926535 elif op", "# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE", "import math import operator # map operator symbols to corresponding", "\"\"\" expop :: '^' multop :: '*' | '/' addop", "Forward() expr_list = delimitedList(Group(expr)) # add parse action that replaces", "associated documentation files (the # \"Software\"), to deal in the", "% op) else: return float(op) def eval_fx(fx, stats): \"\"\"Given fx", "in all copies or substantial portions of the Software. #", "op == \"PI\": return math.pi # 3.1415926535 elif op ==", "')' factor :: atom [ expop factor ]* term ::", "as \"atom [ ^ factor ]...\" instead of \"atom [", "copies or substantial portions of the Software. # # THE", "= Forward() expr_list = delimitedList(Group(expr)) # add parse action that", "= evaluate_stack(s, stats) op1 = evaluate_stack(s, stats) return opn[op](op1, op2)", "elif op == \"std\": return stats['std'] elif op in fn:", "words e = CaselessKeyword(\"E\") pi = CaselessKeyword(\"PI\") # fnumber =", "# 3.1415926535 elif op == \"E\": return math.e # 2.718281828", "to deal in the Software without restriction, including # without", "'/' addop :: '+' | '-' integer :: ['+' |", "Keyword # and CaselessKeyword only match whole words e =", "factor ]* expr :: term [ addop term ]* \"\"\"", "FOR ANY # CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN", "LIABLE FOR ANY # CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER", "'-' integer :: ['+' | '-'] '0'..'9'+ atom :: PI", "Forward() factor <<= atom + (expop + factor).setParseAction(push_first)[...] term =", "that is, 2^3^2 = 2^(3^2), not (2^3)^2. factor = Forward()", "THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY #", "to str: # fnumber = ppc.number().addParseAction(lambda t: str(t[0])) fnumber =", "a (name, number of args) tuple fn_call = (ident +", "\"cos\": math.cos, \"tan\": math.tan, \"exp\": math.exp, \"abs\": abs, \"trunc\": lambda", "= Combine(Word(\"+-\"+nums, nums) + # Optional(\".\" + Optional(Word(nums))) + #", "= map(Suppress, \"()\") addop = plus | minus multop =", "\"std\": return stats['std'] elif op in fn: # note: args", "= evaluate_stack(s, stats) return opn[op](op1, op2) elif op == \"PI\":", "op, num_args = op if op == \"unary -\": return", "\"sgn\": lambda a: -1 if a < -epsilon else 1", "+ (addop + term).setParseAction(push_first)[...] bnf = expr return bnf def", "_ = BNF().parseString(fx, parseAll=True) val = evaluate_stack(exprStack[:], stats) return val", "a: -1 if a < -epsilon else 1 if a", "CaselessKeyword, Suppress, delimitedList, ) import math import operator # map", "]* expr :: term [ addop term ]* \"\"\" #", "right-to-left # exponents, instead of left-to-right that is, 2^3^2 =", "restriction, including # without limitation the rights to use, copy,", "math.sin, \"cos\": math.cos, \"tan\": math.tan, \"exp\": math.exp, \"abs\": abs, \"trunc\":", "back to str: # fnumber = ppc.number().addParseAction(lambda t: str(t[0])) fnumber", "s.pop(), 0 if isinstance(op, tuple): op, num_args = op if", "hereby granted, free of charge, to any person obtaining #", "= op if op == \"unary -\": return -evaluate_stack(s, stats)", "addop term ]* \"\"\" # use CaselessKeyword for e and", "nums))) # or use provided pyparsing_common.number, but convert back to", "OTHER DEALINGS IN THE SOFTWARE. # from pyparsing import (", "\"round\": round, \"sgn\": lambda a: -1 if a < -epsilon", "the Software without restriction, including # without limitation the rights", "-\": return -evaluate_stack(s, stats) if op in \"+-*/^\": # note:", "OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE", "IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE", "is, 2^3^2 = 2^(3^2), not (2^3)^2. factor = Forward() factor", "-1 if a < -epsilon else 1 if a >", "furnished to do so, subject to # the following conditions:", "stats) op1 = evaluate_stack(s, stats) return opn[op](op1, op2) elif op", "delimitedList(Group(expr)) # add parse action that replaces the function identifier", "op == \"mean\": return stats['mean'] elif op == \"min\": return", "FROM, OUT OF OR IN CONNECTION WITH THE # SOFTWARE", "# note: args are pushed onto the stack in reverse", "SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.", "math.cos, \"tan\": math.tan, \"exp\": math.exp, \"abs\": abs, \"trunc\": lambda a:", "minus, mult, div = map(Literal, \"+-*/\") lpar, rpar = map(Suppress,", "rpar) ) ).setParseAction(push_unary_minus) # by defining exponentiation as \"atom [", "\"atom [ ^ atom ]...\", we get right-to-left # exponents,", "return stats['mean'] elif op == \"min\": return stats['min'] elif op", "eval_fx(fx, stats): \"\"\"Given fx and stats ('min', 'max', 'mean', 'std')", "any person obtaining # a copy of this software and", "0, } exprStack = [] def push_first(toks): exprStack.append(toks[0]) def push_unary_minus(toks):", "map operator symbols to corresponding arithmetic operations epsilon = 1e-12", "stats) for _ in range(num_args)]) return fn[op](*args) elif op[0].isalpha(): raise", "match whole words e = CaselessKeyword(\"E\") pi = CaselessKeyword(\"PI\") #", "e | fnumber | ident).setParseAction(push_first) | Group(lpar + expr +", "to avoid accidentally matching # functions that start with 'e'", "Forward, alphas, alphanums, Regex, CaselessKeyword, Suppress, delimitedList, ) import math", "[ ^ factor ]...\" instead of \"atom [ ^ atom", "opn[op](op1, op2) elif op == \"PI\": return math.pi # 3.1415926535", "granted, free of charge, to any person obtaining # a", "operations epsilon = 1e-12 opn = { \"+\": operator.add, \"-\":", "TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION", "\"tan\": math.tan, \"exp\": math.exp, \"abs\": abs, \"trunc\": lambda a: int(a),", "operator.add, \"-\": operator.sub, \"*\": operator.mul, \"/\": operator.truediv, \"^\": operator.pow, }", "the function identifier with a (name, number of args) tuple", "\"Software\"), to deal in the Software without restriction, including #", "ANY # CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN", "of \"atom [ ^ atom ]...\", we get right-to-left #", "software and associated documentation files (the # \"Software\"), to deal", "COPYRIGHT HOLDERS BE LIABLE FOR ANY # CLAIM, DAMAGES OR", "use provided pyparsing_common.number, but convert back to str: # fnumber", "t: t.insert(0, (t.pop(0), len(t[0]))) ) atom = ( addop[...] +", "atom + (expop + factor).setParseAction(push_first)[...] term = factor + (multop", "round, \"sgn\": lambda a: -1 if a < -epsilon else", "and CaselessKeyword only match whole words e = CaselessKeyword(\"E\") pi", "\"^\": operator.pow, } fn = { \"sin\": math.sin, \"cos\": math.cos,", "'pi' (such as 'exp'); Keyword # and CaselessKeyword only match", "NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE", "CONTRACT, # TORT OR OTHERWISE, ARISING FROM, OUT OF OR", "atom ]...\", we get right-to-left # exponents, instead of left-to-right", "= [] def push_first(toks): exprStack.append(toks[0]) def push_unary_minus(toks): for t in", "fx and stats ('min', 'max', 'mean', 'std') return the result\"\"\"", "deal in the Software without restriction, including # without limitation", "-evaluate_stack(s, stats) if op in \"+-*/^\": # note: operands are", "op == \"max\": return stats['max'] elif op == \"std\": return", "in toks: if t == \"-\": exprStack.append(\"unary -\") else: break", "['+' | '-'] '0'..'9'+ atom :: PI | E |", "# exponents, instead of left-to-right that is, 2^3^2 = 2^(3^2),", "pushed onto the stack in reverse order args = reversed([evaluate_stack(s,", "in reverse order args = reversed([evaluate_stack(s, stats) for _ in", ":: '+' | '-' integer :: ['+' | '-'] '0'..'9'+", "op in \"+-*/^\": # note: operands are pushed onto the", "math.e # 2.718281828 elif op == \"mean\": return stats['mean'] elif", "break def BNF(): \"\"\" expop :: '^' multop :: '*'", "expr <<= term + (addop + term).setParseAction(push_first)[...] bnf = expr", "import ( Literal, Word, Group, Forward, alphas, alphanums, Regex, CaselessKeyword,", "PI | E | real | fn '(' expr ')'", "Permission is hereby granted, free of charge, to any person", "from pyparsing import ( Literal, Word, Group, Forward, alphas, alphanums,", "ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED", "int(a), \"round\": round, \"sgn\": lambda a: -1 if a <", "The above copyright notice and this permission notice shall be", ":: PI | E | real | fn '(' expr", "multop :: '*' | '/' addop :: '+' | '-'", "INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY,", "( addop[...] + ( (fn_call | pi | e |", "nums) + # Optional(\".\" + Optional(Word(nums))) + # Optional(e +", "[ multop factor ]* expr :: term [ addop term", "stack in reverse order args = reversed([evaluate_stack(s, stats) for _", "fn = { \"sin\": math.sin, \"cos\": math.cos, \"tan\": math.tan, \"exp\":", "OUT OF OR IN CONNECTION WITH THE # SOFTWARE OR", "| Group(lpar + expr + rpar) ) ).setParseAction(push_unary_minus) # by", "OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, #", "+ # Optional(e + Word(\"+-\"+nums, nums))) # or use provided", "addop[...] + ( (fn_call | pi | e | fnumber", "addop :: '+' | '-' integer :: ['+' | '-']", "else: break def BNF(): \"\"\" expop :: '^' multop ::", "# distribute, sublicense, and/or sell copies of the Software, and", "note: operands are pushed onto the stack in reverse order", "\"E\": return math.e # 2.718281828 elif op == \"mean\": return", "replaces the function identifier with a (name, number of args)", "get right-to-left # exponents, instead of left-to-right that is, 2^3^2", "(addop + term).setParseAction(push_first)[...] bnf = expr return bnf def evaluate_stack(s,", "of args) tuple fn_call = (ident + lpar - Group(expr_list)", "Copyright (c) 2003-2019 <NAME> # # Permission is hereby granted,", "3.1415926535 elif op == \"E\": return math.e # 2.718281828 elif", "in range(num_args)]) return fn[op](*args) elif op[0].isalpha(): raise Exception(\"invalid identifier '%s'\"", "_ in range(num_args)]) return fn[op](*args) elif op[0].isalpha(): raise Exception(\"invalid identifier", "we get right-to-left # exponents, instead of left-to-right that is,", "corresponding arithmetic operations epsilon = 1e-12 opn = { \"+\":", "== \"E\": return math.e # 2.718281828 elif op == \"mean\":", "elif op == \"mean\": return stats['mean'] elif op == \"min\":" ]
[ "((scan.src == recent.dst) and (scan.dst == recent.src))): scan.type = 'TCP", "Ignore non-tcp, non-udp packets if type(ip.data) not in (TCP, UDP,", "b; c ^= (b>>13) a -= b; a -= c;", "(flags:%d) from %s to %s (ports:%s), average timediff %.2fs' else:", "- this list allows to keep scan information # upto", "(a<<8) c -= a; c -= b; c ^= (b>>13)", "\"\"\" # TCP flags to scan type mapping scan_types =", "file and/or console \"\"\" srcip, dstip = scan_ip2quad(scan) ports =", "default. # Since entries time out in 60 seconds, max", "%s scan from %s to %s (ports: %s) using zombie", "no recent full-connect scan from B->A, if # so this", "if scan.chunk_type==1: scan.type = 'SCTP Init' elif scan.chunk_type==10: scan.type =", "is 60 sec by default. # Since entries time out", "%s to %s (ports:%s), average timediff %.2fs' else: line =", "scan.chunk_type = pload.chunks[0].type scan.ports.append(dport) scan.proto = proto self.scans[key] = scan", "google. Apr 8 2010 - Better detection of TCP full-connect", "to maximum such entries possible in 60 sec - assuming", "False if is_scan or maybe_scan: scan.logged = True if scan.proto==TCP:", "{0: 'TCP null', TH_FIN: 'TCP fin', TH_SYN: 'TCP syn', TH_SYN|TH_RST:", "= 'Continuation of %s scan from %s to %s (ports:", "= self.scans[key].timestamp if timediff<=self.timeout_l: if key not in self.long_scans: lscan", "B to A # Correlation: If 'RST scan' detected from", "= {0: 'TCP null', TH_FIN: 'TCP fin', TH_SYN: 'TCP syn',", "pcap.pcap() decode = { pcap.DLT_LOOP:dpkt.loopback.Loopback, pcap.DLT_NULL:dpkt.loopback.Loopback, pcap.DLT_EN10MB:dpkt.ethernet.Ethernet } [pc.datalink()] try:", "% tuple(tup) self.log(msg) def update_ports(self, scan, dport, flags): scan.flags_or |=", "if not too old, else skip and remove entry if", "using correlation! 3. Detects SCTP scan. 4. Detects slow port-scans", "%s' % (get_timestamp(), msg) if self.scanlog: self.scanlog.write(line + '\\n') self.scanlog.flush()", "help=\"File to save logs to\", default=\"/var/log/scanlog\") options, args = o.parse_args()", "constants TH_URG=dpkt.tcp.TH_URG TH_ACK=dpkt.tcp.TH_ACK TH_PSH=dpkt.tcp.TH_PUSH TH_RST=dpkt.tcp.TH_RST TH_SYN=dpkt.tcp.TH_SYN TH_FIN=dpkt.tcp.TH_FIN # Protocols TCP=dpkt.tcp.TCP", "- zombie host # C - target host # If", "ignore it... elif scan.flags_or == TH_SYN and len(self.recent_scans): # Try", "# in the same time-period. 'n' is 60 sec by", "%s to %s (ports:%s), average timediff %.2fs' msg = line", "OSError), (errno, strerror): print >> sys.stderr, \"Error opening scan log", "remove key del self.long_scans[key] del self.scans[key] return if scan.logged: return", "print >>sys.stderr, \"fork #1 failed\", e sys.exit(1) os.setsid() os.umask(0) #", "scan on C with B as zombie, # it will", "# Since entries time out in 60 seconds, max size", "%.2fs' else: line = 'Slow %s scan (flags:%d) from %s", "# None does scan using RST, however this could be", "last 1 scans recent1 = self.recent_scans[-1:-2:-1] for recent in recent1:", "o=optparse.OptionParser() o.add_option(\"-d\", \"--daemonize\", dest=\"daemon\", help=\"Daemonize\", action=\"store_true\", default=False) o.add_option(\"-f\", \"--logfile\", dest=\"logfile\",", "entry.EntryLog(maxsize) # Port scan weight threshold self.threshold = threshold #", "for d in dummy_scans: # self.recent_scans.remove(d) else: # Remove entry", "if (timediff > self.timeout): # Add entry in long_scans if", "lscan.timestamp = curr lscan.timediffs.append(curr - prev) lscan.flags_or |= flags lscan.ports.append(dport)", "idle scan # with this as zombie, then ignore it...", "time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) ip2quad = lambda x: socket.inet_ntoa(struct.pack('I', x)) scan_ip2quad", "# TCP flags to scan type mapping scan_types = {0:", "> self.timeout): # Add entry in long_scans if timediff not", "too old, else skip and remove entry if (timediff >", "except OSError, e: print >>sys.stderr, \"fork #1 failed\", e sys.exit(1)", "less than 2, possible slow scan # update port weights...", "dport < 1024: scan.weight += 3 else: scan.weight += 1", "from %s to %s (ports: %s) using zombie host %s'", "host # C - target host # If A does", "= 'TCP full-connect' break elif scan.proto==UDP: scan.type = 'UDP' #", "Reset flags for UDP scan scan.flags_or = 0 elif scan.proto==SCTP:", "c; a ^= (c>>12) b -= c; b -= a;", "scan flags 22 from A->B, make sure that # there", "del self.scans[scan.hash] return False else: scan.type = self.scan_types.get(scan.flags_or,'unknown') if scan.type", "rscan = item[1] if rscan.src==scan.src and rscan.flags_or==TH_SYN and ((rscan.timestamp -", "lscan.ports.append(dport) lscan.proto = proto self.long_scans[key] = lscan else: lscan =", "self.scanlog.flush() if not self.daemon: print >> sys.stderr, line def log_scan(self,", "from a zombie host to the scanning # host when", "self.update_ports(lscan, dport, flags) if lscan.time_sd<2: # SD is less than", "# to maximum such entries possible in 60 sec -", "scan.proto==SCTP: if scan.chunk_type==1: scan.type = 'SCTP Init' elif scan.chunk_type==10: scan.type", "try: print 'listening on %s: %s' % (pc.name, pc.filter) for", "= ','.join([str(port) for port in scan.ports]) if not continuation: tup", "fin/ack', TH_SYN|TH_ACK: 'TCP full-connect', TH_URG|TH_PSH|TH_ACK|TH_RST|TH_SYN|TH_FIN: 'TCP all-flags', TH_SYN|TH_ACK|TH_RST: 'TCP full-connect',", "it will appear to C as if B is syn", "'SCTP COOKIE_ECHO' # See if this was logged recently scanentry", "break # Reply from B->A for full-connect scan from A->B", "of TCP full-connect scan without spurious and incorrect logging. Better", "a host address \"\"\" value = addr h = 0", "' to '.join(scan_ip2quad(scan))) not_scan = True break # If this", "lscan.flags_or |= flags lscan.ports.append(dport) lscan.proto = proto self.long_scans[key] = lscan", "# Not a scan TH_RST|TH_ACK: 'reply'} def __init__(self, timeout, threshold,", "self.scanlog = None # Recent scans - this list allows", "Z dummy_scans, idle_ports = [], [] for item in reversed(self.recent_scans):", "recent.type == 'TCP full-connect' and ((scan.src == recent.dst) and (scan.dst", "could be # return packets from a zombie host to", "to %s (ports:%s), average timediff %.2fs' else: line = 'Slow", "if not slow_scan: if scan.type != 'Idle': line = 'Continuation", "if timediff<=self.timeout_l: if key not in self.long_scans: lscan = entry.ScanEntry(key)", "pyscanlogger: Port scan detector/logger tool, inspired by scanlogd {http://www.openwall.com/scanlogd} but", "log_scan(self, scan, continuation=False, slow_scan=False, unsure=False): \"\"\" Log the scan to", "host %s' else: tup.append(scan.time_avg) line = 'Continuation of slow %s", "strerror): print >> sys.stderr, \"Error opening scan log file %s", "timediff %.2fs' else: tup = [scan.type, srcip,dstip, ports] if not", "to %s (ports:%s), average timediff %.2fs' msg = line %", "self.recent_scans = timerlist.TimerList(12, 60.0) def hash_func(self, addr): \"\"\" Hash a", "to %s (ports: %s) using zombie host %s' else: tup.append(scan.time_avg)", "and scan.weight >= self.threshold)) # Possible scan maybe_scan = (slow_scan", "proto==SCTP: scan.chunk_type = pload.chunks[0].type scan.ports.append(dport) scan.proto = proto self.scans[key] =", "self.process(decode(pkt)) except KeyboardInterrupt: if not self.daemon: nrecv, ndrop, nifdrop =", "entries time out in 60 seconds, max size is equal", "UDP - in progress... SCAN_TIMEOUT = 5 WEIGHT_THRESHOLD = 25", "dstip = scan_ip2quad(scan) ports = ','.join([str(port) for port in scan.ports])", "will appear to C as if B is syn scanning", "then this is a regular network activity # but not", "logs to\", default=\"/var/log/scanlog\") options, args = o.parse_args() s=ScanLogger(SCAN_TIMEOUT, WEIGHT_THRESHOLD, 8192,", "if recent.type == 'TCP full-connect' and ((scan.src == recent.dst) and", "x-mas', TH_URG|TH_PSH|TH_FIN|TH_ACK: 'TCP x-mas', TH_SYN|TH_FIN: 'TCP syn/fin', TH_FIN|TH_ACK: 'TCP fin/ack',", "# If we see scan flags 22 from A->B, make", "Add entry in long_scans if timediff not larger # than", "%s' % (pc.name, pc.filter) for ts, pkt in pc: self.process(decode(pkt))", "msg = line % tuple(tup) self.log(msg) def update_ports(self, scan, dport,", "def mix(self, a, b, c): a -= b; a -=", "scan.weight += 1 scan.ports.append(dport) def inspect_scan(self, scan, slow_scan=False): # Sure", "Features 1. Detects all stealth (half-open) and full-connect scans. 2.", "(TH_SYN|TH_ACK|TH_RST) and len(self.recent_scans): recent1 = self.recent_scans[-1:-2:-1] for recent in recent1:", "-= b; c ^= (b>>13) a -= b; a -=", "Basically # A -scanning host # B - zombie host", "!= src: # Skip packets in reverse direction or invalid", "TCP full-connect scan from %s\" % ' to '.join(scan_ip2quad(scan))) not_scan", "= 0 while value: # print value h ^= value", "import entry import timerlist __author__ = \"pythonhacker\" __maintainer__ = \"pythonhacker\"", "and remove entry if (timediff > self.timeout): # Add entry", "Protocols TCP=dpkt.tcp.TCP UDP=dpkt.udp.UDP SCTP=dpkt.sctp.SCTP get_timestamp = lambda : time.strftime('%Y-%m-%d %H:%M:%S',", "curr - scan.timestamp # Update only if not too old,", "return ip = pkt.ip # Ignore non-tcp, non-udp packets if", "False if scan.flags_or==TH_RST: # None does scan using RST, however", "((rscan.timestamp - scan.timestamp)<30): idle_scan = True idle_ports.append(rscan.ports) dummy_scans.append(item) if idle_scan:", "maybe_scan: scan.logged = True if scan.proto==TCP: idle_scan = False if", "entries self.recent_scans.collect() if key in self.scans: scan = self.scans[key] if", "slow_scan: del self.long_scans[scan.hash] else: del self.scans[scan.hash] return False else: scan.type", "or (not slow_scan and scan.weight >= self.threshold)) # Possible scan", "scan without spurious and incorrect logging. Better logging functions. Licensed", "if too many # then this is a regular network", "= pcap.pcap() decode = { pcap.DLT_LOOP:dpkt.loopback.Loopback, pcap.DLT_NULL:dpkt.loopback.Loopback, pcap.DLT_EN10MB:dpkt.ethernet.Ethernet } [pc.datalink()]", "not recent.is_scan: continue if recent.type == 'TCP full-connect' and ((scan.src", "by filter' % nrecv print '%d packets dropped by kernel'", "and ((rscan.timestamp - scan.timestamp)<30): idle_scan = True idle_ports.append(rscan.ports) dummy_scans.append(item) if", "Was not a scan, skip if not recent.is_scan: continue if", "is a regular network activity # but not a scan,", "self.run_daemon() else: # Run in foreground self.loop() def main(): if", "a -= b; a -= c; a ^= (c>>12) b", "not in (TCP, UDP, SCTP): return pload = ip.data src,dst,dport,flags", "pkt in pc: self.process(decode(pkt)) except KeyboardInterrupt: if not self.daemon: nrecv,", "idle_ports = [], [] for item in reversed(self.recent_scans): rscan =", "c; b -= a; b ^= (a<<10) c -= a;", "Remove entry if slow_scan: del self.long_scans[scan.hash] else: del self.scans[scan.hash] return", "full-connect' break elif scan.proto==UDP: scan.type = 'UDP' # Reset flags", "was logged recently scanentry = entry.RecentScanEntry(scan, not not_scan) if scanentry", "= proto self.long_scans[key] = lscan else: lscan = self.long_scans[key] lscan.timestamp", "(errno, strerror): print >> sys.stderr, \"Error opening scan log file", "self.long_scans[scan.hash] else: del self.scans[scan.hash] return False else: scan.type = self.scan_types.get(scan.flags_or,'unknown')", "logfile='/var/log/scanlog'): self.scans = entry.EntryLog(maxsize) self.long_scans = entry.EntryLog(maxsize) # Port scan", "scanning it # and later we could get an apparent", "'Continuation of %s scan from %s to %s (ports:%s)' else:", "addresses \"\"\" return self.hash_func(self.mix(src, dst, 0xffffff)) def log(self, msg): \"\"\"", "proto = type(pload) if proto == TCP: flags = pload.flags", "__version__ = '0.5.1' __modified__ = 'Thu Apr 8 19:21:11 IST", "# Skip packets in reverse direction or invalid protocol return", "scanning host is doing an idle scan. # Basically #", "tool, inspired by scanlogd {http://www.openwall.com/scanlogd} but with added ability to", "code to publish to google. Apr 8 2010 - Better", "hasattr(pkt, 'ip'): return ip = pkt.ip # Ignore non-tcp, non-udp", "TH_SYN|TH_FIN: 'TCP syn/fin', TH_FIN|TH_ACK: 'TCP fin/ack', TH_SYN|TH_ACK: 'TCP full-connect', TH_URG|TH_PSH|TH_ACK|TH_RST|TH_SYN|TH_FIN:", "zombie, # it will appear to C as if B", "scan.type = 'SCTP Init' elif scan.chunk_type==10: scan.type = 'SCTP COOKIE_ECHO'", "-= a; c -= b; c ^= (b>>5) a -=", "syn scan from zombie host %s' % ' to '.join(scan_ip2quad(scan)))", "average timediff %.2fs' msg = line % tuple(tup) self.log(msg) def", "sec - assuming # a scan occurs at most every", "scan from %s to %s (ports:%s)' else: tup.append(ip2quad(scan.zombie)) line =", "not self.daemon: nrecv, ndrop, nifdrop = pc.stats() print '\\n%d packets", "threshold self.threshold = threshold # Timeout for scan entries self.timeout", "'.join(scan_ip2quad(scan))) not_scan = True break # If this is a", "= threshold # Timeout for scan entries self.timeout = timeout", "using zombie host %s' else: tup.append(scan.time_avg) if unsure: line =", "self.scans[key].timestamp if timediff<=self.timeout_l: if key not in self.long_scans: lscan =", ">>sys.stderr, \"fork #2 failed\", e sys.exit(1) self.loop() def run(self): #", "not call duplicate scans # in the same time-period. 'n'", "last 'n' seconds, so as to not call duplicate scans", "UDP, SCTP): return pload = ip.data src,dst,dport,flags = int(struct.unpack('I',ip.src)[0]),int(struct.unpack('I', ip.dst)[0]),int(pload.dport),0", "return abs(c) def host_hash(self, src, dst): \"\"\" Hash mix two", "dport, flags) if lscan.time_sd<2: # SD is less than 2,", "flags) if lscan.time_sd<2: # SD is less than 2, possible", "B is syn scanning it # and later we could", "recent.type=='Idle' and scan.src==recent.zombie: self.log('Ignoring mis-interpreted syn scan from zombie host", "tup.append(scan.time_avg) line = 'Continuation of slow %s scan from %s", "c -= a; c -= b; c ^= (b>>5) a", "= self.scans[key] if scan.src != src: # Skip packets in", "seconds, max size is equal # to maximum such entries", "\"\"\" Log a message to console and/or log file \"\"\"", "in reverse direction or invalid protocol return timediff = curr", ">= self.threshold)) # Possible scan maybe_scan = (slow_scan and len(scan.ports)>=3", "scan type mapping scan_types = {0: 'TCP null', TH_FIN: 'TCP", "0: sys.exit(\"You must be super-user to run this program\") o=optparse.OptionParser()", "60.0) def hash_func(self, addr): \"\"\" Hash a host address \"\"\"", "src: # Skip packets in reverse direction or invalid protocol", "if type(ip.data) not in (TCP, UDP, SCTP): return pload =", "'TCP syn', TH_ACK: 'TCP ack', TH_URG|TH_PSH|TH_FIN: 'TCP x-mas', TH_URG|TH_PSH|TH_FIN|TH_ACK: 'TCP", "if scanentry not in self.recent_scans: continuation=False self.recent_scans.append(scanentry) else: continuation=True if", "a scan, skip if not recent.is_scan: continue if recent.type ==", "del self.scans[key] return if scan.logged: return scan.timestamp = curr self.update_ports(scan,", "maxsize, daemon=True, logfile='/var/log/scanlog'): self.scans = entry.EntryLog(maxsize) self.long_scans = entry.EntryLog(maxsize) #", "[], [] for item in reversed(self.recent_scans): rscan = item[1] if", "%s) using zombie host %s' else: tup.append(scan.time_avg) line = 'Continuation", "wait for it if self.daemon: print 'Daemonizing...' self.run_daemon() else: #", "-scanning host # B - zombie host # C -", "scan.timestamp)<30): idle_scan = True idle_ports.append(rscan.ports) dummy_scans.append(item) if idle_scan: scan.src =", "save logs to\", default=\"/var/log/scanlog\") options, args = o.parse_args() s=ScanLogger(SCAN_TIMEOUT, WEIGHT_THRESHOLD,", "slow port-scans also. Modification History Mar 17 2010 - Cleaned", "open(PIDFILE,'w').write(str(pid)) sys.exit(0) except OSError, e: print >>sys.stderr, \"fork #2 failed\",", "2010 - Cleaned up code to publish to google. Apr", "scan maybe_scan = (slow_scan and len(scan.ports)>=3 and len(scan.timediffs)>=4 and (scan.weight", "to %s (ports:%s), average timediff %.2fs' else: tup = [scan.type,", "possible in 60 sec - assuming # a scan occurs", "5 seconds, this would be 12. self.recent_scans = timerlist.TimerList(12, 60.0)", "-= c; a ^= (c>>13) b -= c; b -=", "'RST scan' detected from X to Y # See if", "line = 'Possible slow %s scan (flags:%d) from %s to", "srcip,dstip, ports] if not slow_scan: if scan.type != 'Idle': line", "timeout, remove key del self.long_scans[key] del self.scans[key] return if scan.logged:", "timerlist.TimerList(12, 60.0) def hash_func(self, addr): \"\"\" Hash a host address", "= daemon # Log file try: self.scanlog = open(logfile,'a') print", "%s) using zombie host %s' else: tup.append(scan.time_avg) if unsure: line", "import optparse import entry import timerlist __author__ = \"pythonhacker\" __maintainer__", "from X to Y # See if there was a", "invalid protocol return timediff = curr - scan.timestamp # Update", "default=\"/var/log/scanlog\") options, args = o.parse_args() s=ScanLogger(SCAN_TIMEOUT, WEIGHT_THRESHOLD, 8192, options.daemon, options.logfile)", "IST 2010' # UDP - in progress... SCAN_TIMEOUT = 5", "= '%s scan (flags:%d) from %s to %s (ports:%s)' else:", "(c>>3) b -= c; b -= a; b ^= (a<<10)", "to console and/or log file \"\"\" line = '[%s]: %s'", "Correlation: If 'RST scan' detected from X to Y #", "host # X to host Z. Then actually Y is", "else: scan.type = self.scan_types.get(scan.flags_or,'unknown') if scan.type in ('', 'reply'): not_scan", "and len(self.recent_scans): recent1 = self.recent_scans[-1:-2:-1] for recent in recent1: #", "import threading import optparse import entry import timerlist __author__ =", "console and/or log file \"\"\" line = '[%s]: %s' %", "value: # print value h ^= value value = value", "(get_timestamp(), msg) if self.scanlog: self.scanlog.write(line + '\\n') self.scanlog.flush() if not", "== recent.src))): scan.type = 'TCP full-connect' break elif scan.proto==UDP: scan.type", "scan. 4. Detects slow port-scans also. Modification History Mar 17", "= 'Continuation of slow %s scan from %s to %s", "= False if is_scan or maybe_scan: scan.logged = True if", "was a SYN scan recently from host # X to", "\"\"\" Hash a host address \"\"\" value = addr h", "rscan.src==scan.src and rscan.flags_or==TH_SYN and ((rscan.timestamp - scan.timestamp)<30): idle_scan = True", "self.scans[scan.hash] return True else: return False def process(self, pkt): if", "entries, but SD is too large, # delete the entry", "= True break # If this is a syn scan,", "default=False) o.add_option(\"-f\", \"--logfile\", dest=\"logfile\", help=\"File to save logs to\", default=\"/var/log/scanlog\")", "idle scanning # Z dummy_scans, idle_ports = [], [] for", "lscan = self.long_scans[key] lscan.timestamp = curr lscan.flags_or |= flags lscan.timediffs.append(curr", "} [pc.datalink()] try: print 'listening on %s: %s' % (pc.name,", "and incorrect logging. Better logging functions. Licensed under GNU GPL", "scan is_scan = ((slow_scan and scan.weight >= self.threshold_l) or (not", "with added ability to log slow port-scans. Features 1. Detects", "%s to %s (ports: %s) using zombie host %s' else:", "continuation=False, slow_scan=False, unsure=False): \"\"\" Log the scan to file and/or", "unsure: line = 'Possible slow %s scan (flags:%d) from %s", "__maintainer__ = \"pythonhacker\" __version__ = '0.5.1' __modified__ = 'Thu Apr", "lscan.timediffs, lscan.time_sd print 'Removing',key,lscan.src,'since not a scan' del self.long_scans[key] elif", "o.parse_args() s=ScanLogger(SCAN_TIMEOUT, WEIGHT_THRESHOLD, 8192, options.daemon, options.logfile) s.run() if __name__ ==", "most every 5 seconds, this would be 12. self.recent_scans =", "print 'listening on %s: %s' % (pc.name, pc.filter) for ts,", "# Add weight for port if dport < 1024: scan.weight", "scan.ports.append(dport) scan.proto = proto self.scans[key] = scan def loop(self): pc", "update_ports(self, scan, dport, flags): scan.flags_or |= flags if dport in", "%s (ports:%s)' else: tup.append(ip2quad(scan.zombie)) line = 'Continuation of %s scan", "%s (ports:%s)' else: tup.append(ip2quad(scan.zombie)) line = '%s scan (flags: %d)", "scans. 2. Detects Idle scan and logs it correctly using", "Not a scan TH_RST|TH_ACK: 'reply'} def __init__(self, timeout, threshold, maxsize,", "# Ignore non-tcp, non-udp packets if type(ip.data) not in (TCP,", "- if too many # then this is a regular", "received by filter' % nrecv print '%d packets dropped by", "scan' del self.long_scans[key] elif len(lscan.timediffs)>2: # More than 2 entries,", "If this is a syn scan, see if there was", "program\") o=optparse.OptionParser() o.add_option(\"-d\", \"--daemonize\", dest=\"daemon\", help=\"Daemonize\", action=\"store_true\", default=False) o.add_option(\"-f\", \"--logfile\",", "to %s (ports:%s)' else: tup.append(ip2quad(scan.zombie)) line = 'Continuation of %s", "the scan to file and/or console \"\"\" srcip, dstip =", "|= flags if dport in scan.ports: return # Add weight", "Not a scan, check # of entries - if too", "port in scan.ports]) if not continuation: tup = [scan.type,scan.flags_or,srcip,dstip, ports]", "# print 'Removing',key,lscan.src,'since SD is',lscan.time_sd del self.long_scans[key] else: # Too", "c -= b; c ^= (b>>13) a -= b; a", "Second fork try: pid = os.fork() if pid>0: open(PIDFILE,'w').write(str(pid)) sys.exit(0)", "too large, # delete the entry # print 'Removing',key,lscan.src,'since SD", "% nrecv print '%d packets dropped by kernel' % ndrop", "self.long_scans[key] else: # Too large timeout, remove key del self.long_scans[key]", "print 'Daemonizing...' self.run_daemon() else: # Run in foreground self.loop() def", "%s' % ' to '.join(scan_ip2quad(scan))) break # Reply from B->A", "- prev) lscan.update_time_sd() self.update_ports(lscan, dport, flags) if lscan.time_sd<2: # SD", "return True else: return False def process(self, pkt): if not", "^= (b>>15) return abs(c) def host_hash(self, src, dst): \"\"\" Hash", "scan and logs it correctly using correlation! 3. Detects SCTP", "saved to %s' % logfile except (IOError, OSError), (errno, strerror):", ": time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) ip2quad = lambda x: socket.inet_ntoa(struct.pack('I', x))", "filter' % nrecv print '%d packets dropped by kernel' %", "(IOError, OSError), (errno, strerror): print >> sys.stderr, \"Error opening scan", "in long_scans if timediff not larger # than longscan timeout", "idle_scan = False if scan.flags_or==TH_RST: # None does scan using", "flags if proto==SCTP: scan.chunk_type = pload.chunks[0].type scan.ports.append(dport) scan.proto = proto", "= True # If we see scan flags 22 from", "SCAN_TIMEOUT = 5 WEIGHT_THRESHOLD = 25 PIDFILE=\"/var/run/pyscanlogger.pid\" # TCP flag", "b ^= (a<<16) c -= a; c -= b; c", "threshold, maxsize, daemon=True, logfile='/var/log/scanlog'): self.scans = entry.EntryLog(maxsize) self.long_scans = entry.EntryLog(maxsize)", "TCP full-connect scan without spurious and incorrect logging. Better logging", "struct import socket import time import threading import optparse import", "recent1 = self.recent_scans[-1:-2:-1] for recent in recent1: if recent.type=='Idle' and", "= timeout # Long-period scan timeouts self.timeout_l = 3600 #", "lambda : time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) ip2quad = lambda x: socket.inet_ntoa(struct.pack('I',", "and scan.src==recent.zombie: self.log('Ignoring mis-interpreted syn scan from zombie host %s'", "def loop(self): pc = pcap.pcap() decode = { pcap.DLT_LOOP:dpkt.loopback.Loopback, pcap.DLT_NULL:dpkt.loopback.Loopback,", "scan # with this as zombie, then ignore it... elif", "if recent.type=='Idle' and scan.src==recent.zombie: self.log('Ignoring mis-interpreted syn scan from zombie", "using zombie host %s' else: tup.append(scan.time_avg) line = 'Continuation of", "A->B elif (recent.type == 'reply' and ((scan.src == recent.dst) and", "self.long_scans: lscan = entry.ScanEntry(key) lscan.src = src lscan.dst = dst", "to %s (ports:%s)' else: tup.append(ip2quad(scan.zombie)) line = '%s scan (flags:", "Idle scan and logs it correctly using correlation! 3. Detects", "else: tup.append(ip2quad(scan.zombie)) line = '%s scan (flags: %d) from %s", "scan (flags:%d) from %s to %s (ports:%s), average timediff %.2fs'", "scan.ports = idle_ports # for d in dummy_scans: # self.recent_scans.remove(d)", "slow_scan: if scan.type != 'Idle': line = '%s scan (flags:%d)", "- scan.timestamp)<30): idle_scan = True idle_ports.append(rscan.ports) dummy_scans.append(item) if idle_scan: scan.src", "and (scan.dst == recent.src)): # Spurious self.log(\"Ignoring spurious TCP full-connect", "if this was logged recently scanentry = entry.RecentScanEntry(scan, not not_scan)", "entry if slow_scan: del self.long_scans[scan.hash] else: del self.scans[scan.hash] return True", "pcap.DLT_NULL:dpkt.loopback.Loopback, pcap.DLT_EN10MB:dpkt.ethernet.Ethernet } [pc.datalink()] try: print 'listening on %s: %s'", "fin', TH_SYN: 'TCP syn', TH_SYN|TH_RST: 'TCP syn', TH_ACK: 'TCP ack',", "'TCP x-mas', TH_SYN|TH_FIN: 'TCP syn/fin', TH_FIN|TH_ACK: 'TCP fin/ack', TH_SYN|TH_ACK: 'TCP", "timediff<=self.timeout_l: if key not in self.long_scans: lscan = entry.ScanEntry(key) lscan.src", "b; a -= c; a ^= (c>>3) b -= c;", "# a scan occurs at most every 5 seconds, this", "self.threshold_l) or (not slow_scan and scan.weight >= self.threshold)) # Possible", "of slow %s scan from %s to %s (ports:%s), average", "[pc.datalink()] try: print 'listening on %s: %s' % (pc.name, pc.filter)", "= pc.stats() print '\\n%d packets received by filter' % nrecv", "((slow_scan and scan.weight >= self.threshold_l) or (not slow_scan and scan.weight", "Init' elif scan.chunk_type==10: scan.type = 'SCTP COOKIE_ECHO' # See if", "Then actually Y is idle scanning # Z dummy_scans, idle_ports", "there was a recent idle scan # with this as", "= self.recent_scans[-1:-2:-1] for recent in recent1: if recent.type=='Idle' and scan.src==recent.zombie:", "Hash a host address \"\"\" value = addr h =", "\"\"\" pyscanlogger: Port scan detector/logger tool, inspired by scanlogd {http://www.openwall.com/scanlogd}", "scan_types = {0: 'TCP null', TH_FIN: 'TCP fin', TH_SYN: 'TCP", "= dst scan.timestamp = curr scan.flags_or |= flags if proto==SCTP:", "'\\n') self.scanlog.flush() if not self.daemon: print >> sys.stderr, line def", "v3.0. \"\"\" import sys, os import dpkt, pcap import struct", "scan from %s to %s (ports:%s), average timediff %.2fs' msg", "continuation=True if not not_scan: self.log_scan(scan, continuation=continuation, slow_scan=slow_scan, unsure=maybe_scan) # Remove", "not slow_scan: if scan.type != 'Idle': line = '%s scan", "network activity # but not a scan, so remove entry", "self.loop() def main(): if os.geteuid() != 0: sys.exit(\"You must be", "abs(c) def host_hash(self, src, dst): \"\"\" Hash mix two host", ">= self.threshold_l) or (not slow_scan and scan.weight >= self.threshold)) #", "'Continuation of slow %s scan from %s to %s (ports:%s),", "not not_scan: self.log_scan(scan, continuation=continuation, slow_scan=slow_scan, unsure=maybe_scan) # Remove entry if", "dst lscan.timestamp = curr lscan.timediffs.append(curr - prev) lscan.flags_or |= flags", "file try: self.scanlog = open(logfile,'a') print >> sys.stderr, 'Scan logs", "'%s scan (flags: %d) from %s to %s (ports: %s)", "long_scans if timediff not larger # than longscan timeout prev", "TH_RST|TH_ACK: 'reply'} def __init__(self, timeout, threshold, maxsize, daemon=True, logfile='/var/log/scanlog'): self.scans", "% ' to '.join(scan_ip2quad(scan))) not_scan = True break # If", "return False else: scan.type = self.scan_types.get(scan.flags_or,'unknown') if scan.type in ('',", "tuple(tup) self.log(msg) def update_ports(self, scan, dport, flags): scan.flags_or |= flags", "for it if self.daemon: print 'Daemonizing...' self.run_daemon() else: # Run", "the scanning # host when a scanning host is doing", "Long-period scan threshold self.threshold_l = self.threshold/2 # Daemonize ? self.daemon", "a new thread and wait for it if self.daemon: print", "'TCP fin', TH_SYN: 'TCP syn', TH_SYN|TH_RST: 'TCP syn', TH_ACK: 'TCP", "for UDP scan scan.flags_or = 0 elif scan.proto==SCTP: if scan.chunk_type==1:", "pid>0: sys.exit(0) except OSError, e: print >>sys.stderr, \"fork #1 failed\",", "print '\\n%d packets received by filter' % nrecv print '%d", "ip.dst)[0]),int(pload.dport),0 proto = type(pload) if proto == TCP: flags =", "TH_URG|TH_PSH|TH_ACK|TH_RST|TH_SYN|TH_FIN: 'TCP all-flags', TH_SYN|TH_ACK|TH_RST: 'TCP full-connect', # Not a scan", "True break # If this is a syn scan, see", "-- coding: utf-8 #!/usr/bin/env python \"\"\" pyscanlogger: Port scan detector/logger", "= None # Recent scans - this list allows to", "# Reply from B->A for full-connect scan from A->B elif", "'reply'} def __init__(self, timeout, threshold, maxsize, daemon=True, logfile='/var/log/scanlog'): self.scans =", "and rscan.flags_or==TH_SYN and ((rscan.timestamp - scan.timestamp)<30): idle_scan = True idle_ports.append(rscan.ports)", "\"fork #2 failed\", e sys.exit(1) self.loop() def run(self): # If", "scans - this list allows to keep scan information #", "# Disconnect from tty try: pid = os.fork() if pid>0:", "a ^= (c>>3) b -= c; b -= a; b", "'Weight=>',lscan.weight if not self.inspect_scan(lscan, True): # Not a scan, check", "= lambda x: socket.inet_ntoa(struct.pack('I', x)) scan_ip2quad = lambda scan: map(ip2quad,", "if not self.daemon: nrecv, ndrop, nifdrop = pc.stats() print '\\n%d", "= self.scan_types.get(scan.flags_or,'unknown') if scan.type in ('', 'reply'): not_scan = True", "for ts, pkt in pc: self.process(decode(pkt)) except KeyboardInterrupt: if not", "dpkt, pcap import struct import socket import time import threading", "super-user to run this program\") o=optparse.OptionParser() o.add_option(\"-d\", \"--daemonize\", dest=\"daemon\", help=\"Daemonize\",", "# X to host Z. Then actually Y is idle", "scan.logged: return scan.timestamp = curr self.update_ports(scan, dport, flags) self.inspect_scan(scan) else:", "self.scans = entry.EntryLog(maxsize) self.long_scans = entry.EntryLog(maxsize) # Port scan weight", "= entry.RecentScanEntry(scan, not not_scan) if scanentry not in self.recent_scans: continuation=False", "# B - zombie host # C - target host", "entry.ScanEntry(key) scan.src = src scan.dst = dst scan.timestamp = curr", "\"--daemonize\", dest=\"daemon\", help=\"Daemonize\", action=\"store_true\", default=False) o.add_option(\"-f\", \"--logfile\", dest=\"logfile\", help=\"File to", "self.threshold_l)) not_scan = False if is_scan or maybe_scan: scan.logged =", "two host addresses \"\"\" return self.hash_func(self.mix(src, dst, 0xffffff)) def log(self,", "weights... # print 'Weight=>',lscan.weight if not self.inspect_scan(lscan, True): # Not", "= scan.dst scan.dst = rscan.dst scan.zombie = rscan.src scan.type =", "- scan.timestamp # Update only if not too old, else", "value h ^= value value = value >> 9 return", "if unsure: line = 'Possible slow %s scan (flags:%d) from", "scan threshold self.threshold_l = self.threshold/2 # Daemonize ? self.daemon =", "is less than 2, possible slow scan # update port", "dropped by kernel' % ndrop def run_daemon(self): # Disconnect from", "2 entries, but SD is too large, # delete the", "= 'Continuation of %s scan from %s to %s (ports:%s)'", "scan recently from host # X to host Z. Then", "continuation: tup = [scan.type,scan.flags_or,srcip,dstip, ports] if not slow_scan: if scan.type", "possible slow scan # update port weights... # print 'Weight=>',lscan.weight", "# Recent scans - this list allows to keep scan", "= addr h = 0 while value: # print value", "2, possible slow scan # update port weights... # print", "logs will be saved to %s' % logfile except (IOError,", "old, else skip and remove entry if (timediff > self.timeout):", "KeyboardInterrupt: if not self.daemon: nrecv, ndrop, nifdrop = pc.stats() print", "daemon # Log file try: self.scanlog = open(logfile,'a') print >>", "create a new thread and wait for it if self.daemon:", "import dpkt, pcap import struct import socket import time import", "(ports:%s)' else: tup.append(ip2quad(scan.zombie)) line = '%s scan (flags: %d) from", "scan_ip2quad(scan) ports = ','.join([str(port) for port in scan.ports]) if not", "True # If we see scan flags 22 from A->B,", "'\\n%d packets received by filter' % nrecv print '%d packets", "lscan.src = src lscan.dst = dst lscan.timestamp = curr lscan.timediffs.append(curr", "host address \"\"\" value = addr h = 0 while", "this list allows to keep scan information # upto last", "timediff not larger # than longscan timeout prev = self.scans[key].timestamp", "= ((slow_scan and scan.weight >= self.threshold_l) or (not slow_scan and", "return scan.timestamp = curr self.update_ports(scan, dport, flags) self.inspect_scan(scan) else: #", "information # upto last 'n' seconds, so as to not", "scan def loop(self): pc = pcap.pcap() decode = { pcap.DLT_LOOP:dpkt.loopback.Loopback,", "allows to keep scan information # upto last 'n' seconds,", "# Reset flags for UDP scan scan.flags_or = 0 elif", "Timeout for scan entries self.timeout = timeout # Long-period scan", "scan.flags_or = 0 elif scan.proto==SCTP: if scan.chunk_type==1: scan.type = 'SCTP", "^= (a<<16) c -= a; c -= b; c ^=", "else: continuation=True if not not_scan: self.log_scan(scan, continuation=continuation, slow_scan=slow_scan, unsure=maybe_scan) #", "mapping scan_types = {0: 'TCP null', TH_FIN: 'TCP fin', TH_SYN:", "Log the scan to file and/or console \"\"\" srcip, dstip", "recent in recent1: # Was not a scan, skip if", "proto self.long_scans[key] = lscan else: lscan = self.long_scans[key] lscan.timestamp =", "print value h ^= value value = value >> 9", "ports = ','.join([str(port) for port in scan.ports]) if not continuation:", "Spurious self.log(\"Ignoring spurious TCP full-connect scan from %s\" % '", "# Remove entry if slow_scan: del self.long_scans[scan.hash] else: del self.scans[scan.hash]", "scan.timestamp = curr self.update_ports(scan, dport, flags) self.inspect_scan(scan) else: # Add", "e: print >>sys.stderr, \"fork #2 failed\", e sys.exit(1) self.loop() def", "b; a -= c; a ^= (c>>13) b -= c;", "not too old, else skip and remove entry if (timediff", "self.scanlog.write(line + '\\n') self.scanlog.flush() if not self.daemon: print >> sys.stderr,", "this is a syn scan, see if there was a", "src lscan.dst = dst lscan.timestamp = curr lscan.timediffs.append(curr - prev)", "not slow_scan: if scan.type != 'Idle': line = 'Continuation of", "full-connect', # Not a scan TH_RST|TH_ACK: 'reply'} def __init__(self, timeout,", "syn scan, see if there was a recent idle scan", "# Spurious self.log(\"Ignoring spurious TCP full-connect scan from %s\" %", "= open(logfile,'a') print >> sys.stderr, 'Scan logs will be saved", "timediff = curr - scan.timestamp # Update only if not", "srcip, dstip = scan_ip2quad(scan) ports = ','.join([str(port) for port in", "self.threshold_l = self.threshold/2 # Daemonize ? self.daemon = daemon #", "self.scans[key] if scan.src != src: # Skip packets in reverse", "recent.src))): scan.type = 'TCP full-connect' break elif scan.proto==UDP: scan.type =", "actually Y is idle scanning # Z dummy_scans, idle_ports =", "from %s to %s (ports:%s)' else: tup.append(ip2quad(scan.zombie)) line = 'Continuation", "# return packets from a zombie host to the scanning", "'Idle': line = '%s scan (flags:%d) from %s to %s", "time.localtime()) ip2quad = lambda x: socket.inet_ntoa(struct.pack('I', x)) scan_ip2quad = lambda", "{http://www.openwall.com/scanlogd} but with added ability to log slow port-scans. Features", "Detects Idle scan and logs it correctly using correlation! 3.", "a -= c; a ^= (c>>3) b -= c; b", "as zombie, then ignore it... elif scan.flags_or == TH_SYN and", "print '%d packets dropped by kernel' % ndrop def run_daemon(self):", "not_scan) if scanentry not in self.recent_scans: continuation=False self.recent_scans.append(scanentry) else: continuation=True", "# Too large timeout, remove key del self.long_scans[key] del self.scans[key]", "addr h = 0 while value: # print value h", "recently from host # X to host Z. Then actually", "idle_ports.append(rscan.ports) dummy_scans.append(item) if idle_scan: scan.src = scan.dst scan.dst = rscan.dst", "on %s: %s' % (pc.name, pc.filter) for ts, pkt in", "scan.dst = dst scan.timestamp = curr scan.flags_or |= flags if", "port-scans also. Modification History Mar 17 2010 - Cleaned up", "list allows to keep scan information # upto last 'n'", "is equal # to maximum such entries possible in 60", "'TCP ack', TH_URG|TH_PSH|TH_FIN: 'TCP x-mas', TH_URG|TH_PSH|TH_FIN|TH_ACK: 'TCP x-mas', TH_SYN|TH_FIN: 'TCP", ">> sys.stderr, \"Error opening scan log file %s => %s\"", "TH_URG=dpkt.tcp.TH_URG TH_ACK=dpkt.tcp.TH_ACK TH_PSH=dpkt.tcp.TH_PUSH TH_RST=dpkt.tcp.TH_RST TH_SYN=dpkt.tcp.TH_SYN TH_FIN=dpkt.tcp.TH_FIN # Protocols TCP=dpkt.tcp.TCP UDP=dpkt.udp.UDP", "tup.append(ip2quad(scan.zombie)) line = '%s scan (flags: %d) from %s to", "if scan.proto==TCP: idle_scan = False if scan.flags_or==TH_RST: # None does", "dport, flags) self.inspect_scan(scan) else: # Add new entry scan =", "len(self.recent_scans): recent1 = self.recent_scans[-1:-2:-1] for recent in recent1: # Was", "host is doing an idle scan. # Basically # A", "break elif scan.proto==UDP: scan.type = 'UDP' # Reset flags for", "not_scan: self.log_scan(scan, continuation=continuation, slow_scan=slow_scan, unsure=maybe_scan) # Remove entry if slow_scan:", "kernel' % ndrop def run_daemon(self): # Disconnect from tty try:", "If we see scan flags 22 from A->B, make sure", "packets from a zombie host to the scanning # host", "continuation=continuation, slow_scan=slow_scan, unsure=maybe_scan) # Remove entry if slow_scan: del self.long_scans[scan.hash]", "curr=time.time() # Keep dropping old entries self.recent_scans.collect() if key in", "c ^= (b>>13) a -= b; a -= c; a", "proto self.scans[key] = scan def loop(self): pc = pcap.pcap() decode", "from tty try: pid = os.fork() if pid>0: sys.exit(0) except", "a; c -= b; c ^= (b>>13) a -= b;", "# for d in dummy_scans: # self.recent_scans.remove(d) else: # Remove", "(8192-1) def mix(self, a, b, c): a -= b; a", "slow port-scans. Features 1. Detects all stealth (half-open) and full-connect", "scan.chunk_type==10: scan.type = 'SCTP COOKIE_ECHO' # See if this was", "it correctly using correlation! 3. Detects SCTP scan. 4. Detects", "added ability to log slow port-scans. Features 1. Detects all", "lscan.flags_or |= flags lscan.timediffs.append(curr - prev) lscan.update_time_sd() self.update_ports(lscan, dport, flags)", "-= c; b -= a; b ^= (a<<10) c -=", "flag constants TH_URG=dpkt.tcp.TH_URG TH_ACK=dpkt.tcp.TH_ACK TH_PSH=dpkt.tcp.TH_PUSH TH_RST=dpkt.tcp.TH_RST TH_SYN=dpkt.tcp.TH_SYN TH_FIN=dpkt.tcp.TH_FIN # Protocols", "'TCP null', TH_FIN: 'TCP fin', TH_SYN: 'TCP syn', TH_SYN|TH_RST: 'TCP", "mix two host addresses \"\"\" return self.hash_func(self.mix(src, dst, 0xffffff)) def", "del self.long_scans[key] del self.scans[key] return if scan.logged: return scan.timestamp =", "# A -scanning host # B - zombie host #", "0 while value: # print value h ^= value value", "continue if recent.type == 'TCP full-connect' and ((scan.src == recent.dst)", "\"\"\" Hash mix two host addresses \"\"\" return self.hash_func(self.mix(src, dst,", "slow_scan and scan.weight >= self.threshold)) # Possible scan maybe_scan =", "self.host_hash(src,dst) curr=time.time() # Keep dropping old entries self.recent_scans.collect() if key", "key del self.long_scans[key] del self.scans[key] return if scan.logged: return scan.timestamp", "also. Modification History Mar 17 2010 - Cleaned up code", "file \"\"\" line = '[%s]: %s' % (get_timestamp(), msg) if", "in self.recent_scans: continuation=False self.recent_scans.append(scanentry) else: continuation=True if not not_scan: self.log_scan(scan,", "c -= b; c ^= (b>>5) a -= b; a", "scan log file %s => %s\" % (logfile, strerror) self.scanlog", "'Daemonizing...' self.run_daemon() else: # Run in foreground self.loop() def main():", "weight threshold self.threshold = threshold # Timeout for scan entries", "zombie host %s' % ' to '.join(scan_ip2quad(scan))) break # Reply", "b -= c; b -= a; b ^= (a<<8) c", "if key in self.scans: scan = self.scans[key] if scan.src !=", "# -- coding: utf-8 #!/usr/bin/env python \"\"\" pyscanlogger: Port scan", "to save logs to\", default=\"/var/log/scanlog\") options, args = o.parse_args() s=ScanLogger(SCAN_TIMEOUT,", "to %s' % logfile except (IOError, OSError), (errno, strerror): print", "== 'reply' and ((scan.src == recent.dst) and (scan.dst == recent.src))):", "a recent idle scan # with this as zombie, then", "Since entries time out in 60 seconds, max size is", "scan detector/logger tool, inspired by scanlogd {http://www.openwall.com/scanlogd} but with added", "else: # Add new entry scan = entry.ScanEntry(key) scan.src =", "if scan.type in ('', 'reply'): not_scan = True # If", "else: tup.append(ip2quad(scan.zombie)) line = 'Continuation of %s scan from %s", "\"\"\" line = '[%s]: %s' % (get_timestamp(), msg) if self.scanlog:", "elif scan.flags_or == TH_SYN and len(self.recent_scans): # Try last 1", "__init__(self, timeout, threshold, maxsize, daemon=True, logfile='/var/log/scanlog'): self.scans = entry.EntryLog(maxsize) self.long_scans", "{ pcap.DLT_LOOP:dpkt.loopback.Loopback, pcap.DLT_NULL:dpkt.loopback.Loopback, pcap.DLT_EN10MB:dpkt.ethernet.Ethernet } [pc.datalink()] try: print 'listening on", "SCTP): return pload = ip.data src,dst,dport,flags = int(struct.unpack('I',ip.src)[0]),int(struct.unpack('I', ip.dst)[0]),int(pload.dport),0 proto", "False else: scan.type = self.scan_types.get(scan.flags_or,'unknown') if scan.type in ('', 'reply'):", "0 elif scan.proto==SCTP: if scan.chunk_type==1: scan.type = 'SCTP Init' elif", "to file and/or console \"\"\" srcip, dstip = scan_ip2quad(scan) ports", "syn/fin', TH_FIN|TH_ACK: 'TCP fin/ack', TH_SYN|TH_ACK: 'TCP full-connect', TH_URG|TH_PSH|TH_ACK|TH_RST|TH_SYN|TH_FIN: 'TCP all-flags',", "return h & (8192-1) def mix(self, a, b, c): a", "(pc.name, pc.filter) for ts, pkt in pc: self.process(decode(pkt)) except KeyboardInterrupt:", "- assuming # a scan occurs at most every 5", "than 2 entries, but SD is too large, # delete", "TH_URG|TH_PSH|TH_FIN: 'TCP x-mas', TH_URG|TH_PSH|TH_FIN|TH_ACK: 'TCP x-mas', TH_SYN|TH_FIN: 'TCP syn/fin', TH_FIN|TH_ACK:", "as zombie, # it will appear to C as if", "# Was not a scan, skip if not recent.is_scan: continue", "self.recent_scans.collect() if key in self.scans: scan = self.scans[key] if scan.src", "from B to A # Correlation: If 'RST scan' detected", "Y is idle scanning # Z dummy_scans, idle_ports = [],", "not a scan, skip if not recent.is_scan: continue if recent.type", "dummy_scans, idle_ports = [], [] for item in reversed(self.recent_scans): rscan", "'Removing',key,lscan.src,'since SD is',lscan.time_sd del self.long_scans[key] else: # Too large timeout,", "TH_SYN|TH_ACK: 'TCP full-connect', TH_URG|TH_PSH|TH_ACK|TH_RST|TH_SYN|TH_FIN: 'TCP all-flags', TH_SYN|TH_ACK|TH_RST: 'TCP full-connect', #", "a; b ^= (a<<16) c -= a; c -= b;", "sys.exit(1) os.setsid() os.umask(0) # Second fork try: pid = os.fork()", "be 12. self.recent_scans = timerlist.TimerList(12, 60.0) def hash_func(self, addr): \"\"\"", "entries possible in 60 sec - assuming # a scan", "= scan_ip2quad(scan) ports = ','.join([str(port) for port in scan.ports]) if", "UDP scan scan.flags_or = 0 elif scan.proto==SCTP: if scan.chunk_type==1: scan.type", "host to the scanning # host when a scanning host", "scan information # upto last 'n' seconds, so as to", "later we could get an apparent RST \"scan\" # from", "elif scan.proto==UDP: scan.type = 'UDP' # Reset flags for UDP", "(scan.weight < self.threshold_l)) not_scan = False if is_scan or maybe_scan:", "%s: %s' % (pc.name, pc.filter) for ts, pkt in pc:", "idle_scan = True idle_ports.append(rscan.ports) dummy_scans.append(item) if idle_scan: scan.src = scan.dst", "log file \"\"\" line = '[%s]: %s' % (get_timestamp(), msg)", "# More than 2 entries, but SD is too large,", "TH_SYN|TH_ACK|TH_RST: 'TCP full-connect', # Not a scan TH_RST|TH_ACK: 'reply'} def", "= curr - scan.timestamp # Update only if not too", "^= value value = value >> 9 return h &", "A # Correlation: If 'RST scan' detected from X to", "pid = os.fork() if pid>0: open(PIDFILE,'w').write(str(pid)) sys.exit(0) except OSError, e:", "line = '%s scan (flags:%d) from %s to %s (ports:%s)'", "only if not too old, else skip and remove entry", "self.hash_func(self.mix(src, dst, 0xffffff)) def log(self, msg): \"\"\" Log a message", "See if there was a SYN scan recently from host", "(c>>13) b -= c; b -= a; b ^= (a<<8)", "'TCP x-mas', TH_URG|TH_PSH|TH_FIN|TH_ACK: 'TCP x-mas', TH_SYN|TH_FIN: 'TCP syn/fin', TH_FIN|TH_ACK: 'TCP", "TH_URG|TH_PSH|TH_FIN|TH_ACK: 'TCP x-mas', TH_SYN|TH_FIN: 'TCP syn/fin', TH_FIN|TH_ACK: 'TCP fin/ack', TH_SYN|TH_ACK:", "src, dst): \"\"\" Hash mix two host addresses \"\"\" return", "and (scan.weight < self.threshold_l)) not_scan = False if is_scan or", "= [scan.type, srcip,dstip, ports] if not slow_scan: if scan.type !=", "scan detector/logger \"\"\" # TCP flags to scan type mapping", "a -= c; a ^= (c>>13) b -= c; b", "= self.recent_scans[-1:-2:-1] for recent in recent1: # Was not a", "tup.append(scan.time_avg) if unsure: line = 'Possible slow %s scan (flags:%d)", "timeout # Long-period scan timeouts self.timeout_l = 3600 # Long-period", "= 3600 # Long-period scan threshold self.threshold_l = self.threshold/2 #", "B as zombie, # it will appear to C as", "Detects SCTP scan. 4. Detects slow port-scans also. Modification History", "zombie host %s' else: tup.append(scan.time_avg) line = 'Continuation of slow", "to '.join(scan_ip2quad(scan))) not_scan = True break # If this is", "scan, check # of entries - if too many #", "- Cleaned up code to publish to google. Apr 8", "or maybe_scan: scan.logged = True if scan.proto==TCP: idle_scan = False", "recent idle scan # with this as zombie, then ignore", "%s\" % (logfile, strerror) self.scanlog = None # Recent scans", "((scan.src == recent.dst) and (scan.dst == recent.src)): # Spurious self.log(\"Ignoring", "so as to not call duplicate scans # in the", "time-period. 'n' is 60 sec by default. # Since entries", "item in reversed(self.recent_scans): rscan = item[1] if rscan.src==scan.src and rscan.flags_or==TH_SYN", "to\", default=\"/var/log/scanlog\") options, args = o.parse_args() s=ScanLogger(SCAN_TIMEOUT, WEIGHT_THRESHOLD, 8192, options.daemon,", "packets dropped by kernel' % ndrop def run_daemon(self): # Disconnect", "== (TH_SYN|TH_ACK|TH_RST) and len(self.recent_scans): recent1 = self.recent_scans[-1:-2:-1] for recent in", "GNU GPL v3.0. \"\"\" import sys, os import dpkt, pcap", "|= flags if proto==SCTP: scan.chunk_type = pload.chunks[0].type scan.ports.append(dport) scan.proto =", "- Better detection of TCP full-connect scan without spurious and", "%.2fs' msg = line % tuple(tup) self.log(msg) def update_ports(self, scan,", "by scanlogd {http://www.openwall.com/scanlogd} but with added ability to log slow", "(b>>15) return abs(c) def host_hash(self, src, dst): \"\"\" Hash mix", "if not not_scan: self.log_scan(scan, continuation=continuation, slow_scan=slow_scan, unsure=maybe_scan) # Remove entry", "d in dummy_scans: # self.recent_scans.remove(d) else: # Remove entry if", "be super-user to run this program\") o=optparse.OptionParser() o.add_option(\"-d\", \"--daemonize\", dest=\"daemon\",", "a scan' del self.long_scans[key] elif len(lscan.timediffs)>2: # More than 2", "elif scan.chunk_type==10: scan.type = 'SCTP COOKIE_ECHO' # See if this", "line = 'Continuation of %s scan from %s to %s", "scan from %s to %s (ports: %s) using zombie host", "b; c ^= (b>>5) a -= b; a -= c;", "# it will appear to C as if B is", "'reply' and ((scan.src == recent.dst) and (scan.dst == recent.src))): scan.type", "%s (ports:%s), average timediff %.2fs' else: line = 'Slow %s", "an idle scan on C with B as zombie, #", "dport, flags): scan.flags_or |= flags if dport in scan.ports: return", "slow_scan: if scan.type != 'Idle': line = 'Continuation of %s", "a scanning host is doing an idle scan. # Basically", "in reversed(self.recent_scans): rscan = item[1] if rscan.src==scan.src and rscan.flags_or==TH_SYN and", "[scan.type, srcip,dstip, ports] if not slow_scan: if scan.type != 'Idle':", "key = self.host_hash(src,dst) curr=time.time() # Keep dropping old entries self.recent_scans.collect()", "in scan.ports]) if not continuation: tup = [scan.type,scan.flags_or,srcip,dstip, ports] if", "1 scan.ports.append(dport) def inspect_scan(self, scan, slow_scan=False): # Sure scan is_scan", "as if B is syn scanning it # and later", "it if self.daemon: print 'Daemonizing...' self.run_daemon() else: # Run in", "'Scan logs will be saved to %s' % logfile except", "to google. Apr 8 2010 - Better detection of TCP", "lscan.timestamp = curr lscan.flags_or |= flags lscan.timediffs.append(curr - prev) lscan.update_time_sd()", "port weights... # print 'Weight=>',lscan.weight if not self.inspect_scan(lscan, True): #", "skip and remove entry if (timediff > self.timeout): # Add", "a scan occurs at most every 5 seconds, this would", "in scan.ports: return # Add weight for port if dport", "a syn scan, see if there was a recent idle", "entry in long_scans if timediff not larger # than longscan", "Port scan weight threshold self.threshold = threshold # Timeout for", "occurs at most every 5 seconds, this would be 12.", "-= b; c ^= (b>>15) return abs(c) def host_hash(self, src,", "# Basically # A -scanning host # B - zombie", "scan (flags:%d) from %s to %s (ports:%s)' else: tup.append(ip2quad(scan.zombie)) line", "is doing an idle scan. # Basically # A -scanning", "del self.long_scans[scan.hash] else: del self.scans[scan.hash] return True else: return False", "%s' else: tup.append(scan.time_avg) line = 'Continuation of slow %s scan", "but with added ability to log slow port-scans. Features 1.", "flags for UDP scan scan.flags_or = 0 elif scan.proto==SCTP: if", "would be 12. self.recent_scans = timerlist.TimerList(12, 60.0) def hash_func(self, addr):", "scan, continuation=False, slow_scan=False, unsure=False): \"\"\" Log the scan to file", "del self.long_scans[scan.hash] else: del self.scans[scan.hash] return False else: scan.type =", "if not continuation: tup = [scan.type,scan.flags_or,srcip,dstip, ports] if not slow_scan:", "it... elif scan.flags_or == TH_SYN and len(self.recent_scans): # Try last", "scan from A->B elif (recent.type == 'reply' and ((scan.src ==", "this would be 12. self.recent_scans = timerlist.TimerList(12, 60.0) def hash_func(self,", "non-tcp, non-udp packets if type(ip.data) not in (TCP, UDP, SCTP):", "failed\", e sys.exit(1) self.loop() def run(self): # If dameon, then", "was a recent idle scan # with this as zombie,", "we see scan flags 22 from A->B, make sure that", "else: tup.append(scan.time_avg) if unsure: line = 'Possible slow %s scan", "PIDFILE=\"/var/run/pyscanlogger.pid\" # TCP flag constants TH_URG=dpkt.tcp.TH_URG TH_ACK=dpkt.tcp.TH_ACK TH_PSH=dpkt.tcp.TH_PUSH TH_RST=dpkt.tcp.TH_RST TH_SYN=dpkt.tcp.TH_SYN", "optparse import entry import timerlist __author__ = \"pythonhacker\" __maintainer__ =", "scans # in the same time-period. 'n' is 60 sec", "# UDP - in progress... SCAN_TIMEOUT = 5 WEIGHT_THRESHOLD =", "every 5 seconds, this would be 12. self.recent_scans = timerlist.TimerList(12,", "entry if len(lscan.timediffs)>=10: # print lscan.src, lscan.timediffs, lscan.time_sd print 'Removing',key,lscan.src,'since", "was no recent full-connect scan from B->A, if # so", "seconds, this would be 12. self.recent_scans = timerlist.TimerList(12, 60.0) def", ">> sys.stderr, 'Scan logs will be saved to %s' %", "lscan.time_sd print 'Removing',key,lscan.src,'since not a scan' del self.long_scans[key] elif len(lscan.timediffs)>2:", "Better logging functions. Licensed under GNU GPL v3.0. \"\"\" import", "pcap import struct import socket import time import threading import", "self.log(msg) def update_ports(self, scan, dport, flags): scan.flags_or |= flags if", "'SCTP Init' elif scan.chunk_type==10: scan.type = 'SCTP COOKIE_ECHO' # See", "% (pc.name, pc.filter) for ts, pkt in pc: self.process(decode(pkt)) except", "scan (flags: %d) from %s to %s (ports: %s) using", "for scan entries self.timeout = timeout # Long-period scan timeouts", "for port in scan.ports]) if not continuation: tup = [scan.type,scan.flags_or,srcip,dstip,", "so remove entry if len(lscan.timediffs)>=10: # print lscan.src, lscan.timediffs, lscan.time_sd", "an idle scan. # Basically # A -scanning host #", "1 scans recent1 = self.recent_scans[-1:-2:-1] for recent in recent1: if", "nrecv print '%d packets dropped by kernel' % ndrop def", "lscan = entry.ScanEntry(key) lscan.src = src lscan.dst = dst lscan.timestamp", "c; b -= a; b ^= (a<<8) c -= a;", "by kernel' % ndrop def run_daemon(self): # Disconnect from tty", "Detects slow port-scans also. Modification History Mar 17 2010 -", "not_scan = True break # If this is a syn", "self.long_scans[key] = lscan else: lscan = self.long_scans[key] lscan.timestamp = curr", "print lscan.src, lscan.timediffs, lscan.time_sd print 'Removing',key,lscan.src,'since not a scan' del", "is syn scanning it # and later we could get", "scanentry not in self.recent_scans: continuation=False self.recent_scans.append(scanentry) else: continuation=True if not", "src,dst,dport,flags = int(struct.unpack('I',ip.src)[0]),int(struct.unpack('I', ip.dst)[0]),int(pload.dport),0 proto = type(pload) if proto ==", "= True idle_ports.append(rscan.ports) dummy_scans.append(item) if idle_scan: scan.src = scan.dst scan.dst", "if idle_scan: scan.src = scan.dst scan.dst = rscan.dst scan.zombie =", "if not self.daemon: print >> sys.stderr, line def log_scan(self, scan,", "line = '%s scan (flags: %d) from %s to %s", "? self.daemon = daemon # Log file try: self.scanlog =", "is spurious and should be ignored. if scan.flags_or == (TH_SYN|TH_ACK|TH_RST)", "Long-period scan timeouts self.timeout_l = 3600 # Long-period scan threshold", "message to console and/or log file \"\"\" line = '[%s]:", "ack', TH_URG|TH_PSH|TH_FIN: 'TCP x-mas', TH_URG|TH_PSH|TH_FIN|TH_ACK: 'TCP x-mas', TH_SYN|TH_FIN: 'TCP syn/fin',", "dummy_scans: # self.recent_scans.remove(d) else: # Remove entry if slow_scan: del", "timediff %.2fs' else: line = 'Slow %s scan (flags:%d) from", "COOKIE_ECHO' # See if this was logged recently scanentry =", "foreground self.loop() def main(): if os.geteuid() != 0: sys.exit(\"You must", "value value = value >> 9 return h & (8192-1)", "lscan.timediffs.append(curr - prev) lscan.flags_or |= flags lscan.ports.append(dport) lscan.proto = proto", "os.fork() if pid>0: open(PIDFILE,'w').write(str(pid)) sys.exit(0) except OSError, e: print >>sys.stderr,", "remove entry if len(lscan.timediffs)>=10: # print lscan.src, lscan.timediffs, lscan.time_sd print", "# If this is a syn scan, see if there", "%s (ports: %s) using zombie host %s' else: tup.append(scan.time_avg) if", "pid>0: open(PIDFILE,'w').write(str(pid)) sys.exit(0) except OSError, e: print >>sys.stderr, \"fork #2", "A -scanning host # B - zombie host # C", "apparent RST \"scan\" # from B to A # Correlation:", "larger # than longscan timeout prev = self.scans[key].timestamp if timediff<=self.timeout_l:", "entry.EntryLog(maxsize) self.long_scans = entry.EntryLog(maxsize) # Port scan weight threshold self.threshold", "src scan.dst = dst scan.timestamp = curr scan.flags_or |= flags", "OSError, e: print >>sys.stderr, \"fork #2 failed\", e sys.exit(1) self.loop()", "'Removing',key,lscan.src,'since not a scan' del self.long_scans[key] elif len(lscan.timediffs)>2: # More", "host_hash(self, src, dst): \"\"\" Hash mix two host addresses \"\"\"", "sys.exit(\"You must be super-user to run this program\") o=optparse.OptionParser() o.add_option(\"-d\",", "UDP=dpkt.udp.UDP SCTP=dpkt.sctp.SCTP get_timestamp = lambda : time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) ip2quad", "self.scans[scan.hash] return False else: scan.type = self.scan_types.get(scan.flags_or,'unknown') if scan.type in", "See if this was logged recently scanentry = entry.RecentScanEntry(scan, not", "tty try: pid = os.fork() if pid>0: sys.exit(0) except OSError,", "full-connect scan without spurious and incorrect logging. Better logging functions.", "pload = ip.data src,dst,dport,flags = int(struct.unpack('I',ip.src)[0]),int(struct.unpack('I', ip.dst)[0]),int(pload.dport),0 proto = type(pload)", "detector/logger tool, inspired by scanlogd {http://www.openwall.com/scanlogd} but with added ability", "self.long_scans = entry.EntryLog(maxsize) # Port scan weight threshold self.threshold =", "b ^= (a<<10) c -= a; c -= b; c", "(a<<16) c -= a; c -= b; c ^= (b>>5)", "= src lscan.dst = dst lscan.timestamp = curr lscan.timediffs.append(curr -", "-= a; b ^= (a<<16) c -= a; c -=", "it # and later we could get an apparent RST", "on C with B as zombie, # it will appear", "port-scans. Features 1. Detects all stealth (half-open) and full-connect scans.", "= 5 WEIGHT_THRESHOLD = 25 PIDFILE=\"/var/run/pyscanlogger.pid\" # TCP flag constants", "for full-connect scan from A->B elif (recent.type == 'reply' and", "Reply from B->A for full-connect scan from A->B elif (recent.type", "More than 2 entries, but SD is too large, #", "Skip packets in reverse direction or invalid protocol return timediff", "1024: scan.weight += 3 else: scan.weight += 1 scan.ports.append(dport) def", "e sys.exit(1) os.setsid() os.umask(0) # Second fork try: pid =", "self.inspect_scan(lscan, True): # Not a scan, check # of entries", "must be super-user to run this program\") o=optparse.OptionParser() o.add_option(\"-d\", \"--daemonize\",", "pc.filter) for ts, pkt in pc: self.process(decode(pkt)) except KeyboardInterrupt: if", "the entry # print 'Removing',key,lscan.src,'since SD is',lscan.time_sd del self.long_scans[key] else:", "= os.fork() if pid>0: sys.exit(0) except OSError, e: print >>sys.stderr,", "that # there was no recent full-connect scan from B->A,", "sys, os import dpkt, pcap import struct import socket import", "decode = { pcap.DLT_LOOP:dpkt.loopback.Loopback, pcap.DLT_NULL:dpkt.loopback.Loopback, pcap.DLT_EN10MB:dpkt.ethernet.Ethernet } [pc.datalink()] try: print", "dest=\"logfile\", help=\"File to save logs to\", default=\"/var/log/scanlog\") options, args =", "key in self.scans: scan = self.scans[key] if scan.src != src:", "Add new entry scan = entry.ScanEntry(key) scan.src = src scan.dst", "scan_ip2quad = lambda scan: map(ip2quad, [scan.src, scan.dst]) class ScanLogger(object): \"\"\"", "scan. # Basically # A -scanning host # B -", "addr): \"\"\" Hash a host address \"\"\" value = addr", "- target host # If A does an idle scan", "host when a scanning host is doing an idle scan.", "else: line = 'Slow %s scan (flags:%d) from %s to", "(slow_scan and len(scan.ports)>=3 and len(scan.timediffs)>=4 and (scan.weight < self.threshold_l)) not_scan", "line % tuple(tup) self.log(msg) def update_ports(self, scan, dport, flags): scan.flags_or", "False def process(self, pkt): if not hasattr(pkt, 'ip'): return ip", "scan.type = 'TCP full-connect' break elif scan.proto==UDP: scan.type = 'UDP'", "%s scan from %s to %s (ports:%s), average timediff %.2fs'", "def main(): if os.geteuid() != 0: sys.exit(\"You must be super-user", "logging. Better logging functions. Licensed under GNU GPL v3.0. \"\"\"", "doing an idle scan. # Basically # A -scanning host", "Run in foreground self.loop() def main(): if os.geteuid() != 0:", "SCTP=dpkt.sctp.SCTP get_timestamp = lambda : time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) ip2quad =", "flags = pload.flags key = self.host_hash(src,dst) curr=time.time() # Keep dropping", "else: return False def process(self, pkt): if not hasattr(pkt, 'ip'):", "return timediff = curr - scan.timestamp # Update only if", "if dport < 1024: scan.weight += 3 else: scan.weight +=", "-= a; c -= b; c ^= (b>>15) return abs(c)", "os.setsid() os.umask(0) # Second fork try: pid = os.fork() if", "= \"pythonhacker\" __maintainer__ = \"pythonhacker\" __version__ = '0.5.1' __modified__ =", "if not hasattr(pkt, 'ip'): return ip = pkt.ip # Ignore", "os.fork() if pid>0: sys.exit(0) except OSError, e: print >>sys.stderr, \"fork", "else: tup.append(scan.time_avg) line = 'Continuation of slow %s scan from", "pc = pcap.pcap() decode = { pcap.DLT_LOOP:dpkt.loopback.Loopback, pcap.DLT_NULL:dpkt.loopback.Loopback, pcap.DLT_EN10MB:dpkt.ethernet.Ethernet }", "fork try: pid = os.fork() if pid>0: open(PIDFILE,'w').write(str(pid)) sys.exit(0) except", "Apr 8 2010 - Better detection of TCP full-connect scan", "# Daemonize ? self.daemon = daemon # Log file try:", "^= (c>>13) b -= c; b -= a; b ^=", "recent.dst) and (scan.dst == recent.src)): # Spurious self.log(\"Ignoring spurious TCP", "(b>>13) a -= b; a -= c; a ^= (c>>12)", "h & (8192-1) def mix(self, a, b, c): a -=", "and later we could get an apparent RST \"scan\" #", "self.update_ports(scan, dport, flags) self.inspect_scan(scan) else: # Add new entry scan", "of %s scan from %s to %s (ports: %s) using", "and len(self.recent_scans): # Try last 1 scans recent1 = self.recent_scans[-1:-2:-1]", "# Add entry in long_scans if timediff not larger #", "old entries self.recent_scans.collect() if key in self.scans: scan = self.scans[key]", "entry.RecentScanEntry(scan, not not_scan) if scanentry not in self.recent_scans: continuation=False self.recent_scans.append(scanentry)", "Modification History Mar 17 2010 - Cleaned up code to", "If 'RST scan' detected from X to Y # See", "main(): if os.geteuid() != 0: sys.exit(\"You must be super-user to", "entry.ScanEntry(key) lscan.src = src lscan.dst = dst lscan.timestamp = curr", "else: tup = [scan.type, srcip,dstip, ports] if not slow_scan: if", "# self.recent_scans.remove(d) else: # Remove entry if slow_scan: del self.long_scans[scan.hash]", "self.scans[key] = scan def loop(self): pc = pcap.pcap() decode =", "Possible scan maybe_scan = (slow_scan and len(scan.ports)>=3 and len(scan.timediffs)>=4 and", "if there was a SYN scan recently from host #", "= proto self.scans[key] = scan def loop(self): pc = pcap.pcap()", "# Run in foreground self.loop() def main(): if os.geteuid() !=", "# Sure scan is_scan = ((slow_scan and scan.weight >= self.threshold_l)", "60 seconds, max size is equal # to maximum such", "when a scanning host is doing an idle scan. #", "'TCP syn/fin', TH_FIN|TH_ACK: 'TCP fin/ack', TH_SYN|TH_ACK: 'TCP full-connect', TH_URG|TH_PSH|TH_ACK|TH_RST|TH_SYN|TH_FIN: 'TCP", "# print lscan.src, lscan.timediffs, lscan.time_sd print 'Removing',key,lscan.src,'since not a scan'", "%s to %s (ports:%s), average timediff %.2fs' else: tup =", "if not recent.is_scan: continue if recent.type == 'TCP full-connect' and", "prev) lscan.flags_or |= flags lscan.ports.append(dport) lscan.proto = proto self.long_scans[key] =", "% ndrop def run_daemon(self): # Disconnect from tty try: pid", "assuming # a scan occurs at most every 5 seconds,", "True idle_ports.append(rscan.ports) dummy_scans.append(item) if idle_scan: scan.src = scan.dst scan.dst =", "scan weight threshold self.threshold = threshold # Timeout for scan", "prev = self.scans[key].timestamp if timediff<=self.timeout_l: if key not in self.long_scans:", "host addresses \"\"\" return self.hash_func(self.mix(src, dst, 0xffffff)) def log(self, msg):", ">> 9 return h & (8192-1) def mix(self, a, b,", "an apparent RST \"scan\" # from B to A #", "a scan, so remove entry if len(lscan.timediffs)>=10: # print lscan.src,", "# SD is less than 2, possible slow scan #", "os import dpkt, pcap import struct import socket import time", "B->A, if # so this is spurious and should be", "Z. Then actually Y is idle scanning # Z dummy_scans,", "entry scan = entry.ScanEntry(key) scan.src = src scan.dst = dst", "self.scans[key] return if scan.logged: return scan.timestamp = curr self.update_ports(scan, dport,", "not in self.recent_scans: continuation=False self.recent_scans.append(scanentry) else: continuation=True if not not_scan:", "and len(scan.ports)>=3 and len(scan.timediffs)>=4 and (scan.weight < self.threshold_l)) not_scan =", "large timeout, remove key del self.long_scans[key] del self.scans[key] return if", "equal # to maximum such entries possible in 60 sec", "this is spurious and should be ignored. if scan.flags_or ==", "b; c ^= (b>>15) return abs(c) def host_hash(self, src, dst):", "many # then this is a regular network activity #", "and full-connect scans. 2. Detects Idle scan and logs it", "unsure=False): \"\"\" Log the scan to file and/or console \"\"\"", "RST, however this could be # return packets from a", "of %s scan from %s to %s (ports:%s)' else: tup.append(ip2quad(scan.zombie))", "seconds, so as to not call duplicate scans # in", "|= flags lscan.ports.append(dport) lscan.proto = proto self.long_scans[key] = lscan else:", "packets if type(ip.data) not in (TCP, UDP, SCTP): return pload", "scan TH_RST|TH_ACK: 'reply'} def __init__(self, timeout, threshold, maxsize, daemon=True, logfile='/var/log/scanlog'):", "a ^= (c>>13) b -= c; b -= a; b", "if key not in self.long_scans: lscan = entry.ScanEntry(key) lscan.src =", "A does an idle scan on C with B as", "TH_SYN: 'TCP syn', TH_SYN|TH_RST: 'TCP syn', TH_ACK: 'TCP ack', TH_URG|TH_PSH|TH_FIN:", "(scan.dst == recent.src)): # Spurious self.log(\"Ignoring spurious TCP full-connect scan", "(ports:%s)' else: tup.append(ip2quad(scan.zombie)) line = 'Continuation of %s scan from", "call duplicate scans # in the same time-period. 'n' is", "check # of entries - if too many # then", "in self.long_scans: lscan = entry.ScanEntry(key) lscan.src = src lscan.dst =", "Disconnect from tty try: pid = os.fork() if pid>0: sys.exit(0)", "average timediff %.2fs' else: tup = [scan.type, srcip,dstip, ports] if", "recently scanentry = entry.RecentScanEntry(scan, not not_scan) if scanentry not in", "= lambda scan: map(ip2quad, [scan.src, scan.dst]) class ScanLogger(object): \"\"\" Port", "appear to C as if B is syn scanning it", "'TCP full-connect' and ((scan.src == recent.dst) and (scan.dst == recent.src)):", "(ports:%s), average timediff %.2fs' else: tup = [scan.type, srcip,dstip, ports]", "entry if slow_scan: del self.long_scans[scan.hash] else: del self.scans[scan.hash] return False", "if proto == TCP: flags = pload.flags key = self.host_hash(src,dst)", "^= (b>>5) a -= b; a -= c; a ^=", "# Update only if not too old, else skip and", "sys.stderr, \"Error opening scan log file %s => %s\" %", "not_scan = False if is_scan or maybe_scan: scan.logged = True", "Apr 8 19:21:11 IST 2010' # UDP - in progress...", "pcap.DLT_EN10MB:dpkt.ethernet.Ethernet } [pc.datalink()] try: print 'listening on %s: %s' %", "-= b; a -= c; a ^= (c>>12) b -=", "% logfile except (IOError, OSError), (errno, strerror): print >> sys.stderr,", "%d) from %s to %s (ports: %s) using zombie host", "%s scan from %s to %s (ports:%s)' else: tup.append(ip2quad(scan.zombie)) line", "scan timeouts self.timeout_l = 3600 # Long-period scan threshold self.threshold_l", "or invalid protocol return timediff = curr - scan.timestamp #", "= entry.ScanEntry(key) scan.src = src scan.dst = dst scan.timestamp =", "= curr lscan.flags_or |= flags lscan.timediffs.append(curr - prev) lscan.update_time_sd() self.update_ports(lscan,", "'Possible slow %s scan (flags:%d) from %s to %s (ports:%s),", "slow_scan=False, unsure=False): \"\"\" Log the scan to file and/or console", "recent1 = self.recent_scans[-1:-2:-1] for recent in recent1: # Was not", "print 'Removing',key,lscan.src,'since SD is',lscan.time_sd del self.long_scans[key] else: # Too large", "scan.flags_or == (TH_SYN|TH_ACK|TH_RST) and len(self.recent_scans): recent1 = self.recent_scans[-1:-2:-1] for recent", "(a<<10) c -= a; c -= b; c ^= (b>>15)", "self.scanlog = open(logfile,'a') print >> sys.stderr, 'Scan logs will be", "SYN scan recently from host # X to host Z.", "= pload.chunks[0].type scan.ports.append(dport) scan.proto = proto self.scans[key] = scan def", "= 'UDP' # Reset flags for UDP scan scan.flags_or =", "scan.type != 'Idle': line = '%s scan (flags:%d) from %s", "= int(struct.unpack('I',ip.src)[0]),int(struct.unpack('I', ip.dst)[0]),int(pload.dport),0 proto = type(pload) if proto == TCP:", "ignored. if scan.flags_or == (TH_SYN|TH_ACK|TH_RST) and len(self.recent_scans): recent1 = self.recent_scans[-1:-2:-1]", "== 'TCP full-connect' and ((scan.src == recent.dst) and (scan.dst ==", "lscan.time_sd<2: # SD is less than 2, possible slow scan", "such entries possible in 60 sec - assuming # a", "= lscan else: lscan = self.long_scans[key] lscan.timestamp = curr lscan.flags_or", "timeouts self.timeout_l = 3600 # Long-period scan threshold self.threshold_l =", "else: del self.scans[scan.hash] return True else: return False def process(self,", "syn', TH_ACK: 'TCP ack', TH_URG|TH_PSH|TH_FIN: 'TCP x-mas', TH_URG|TH_PSH|TH_FIN|TH_ACK: 'TCP x-mas',", "try: pid = os.fork() if pid>0: sys.exit(0) except OSError, e:", "(ports:%s), average timediff %.2fs' msg = line % tuple(tup) self.log(msg)", "if scan.type != 'Idle': line = '%s scan (flags:%d) from", "Log file try: self.scanlog = open(logfile,'a') print >> sys.stderr, 'Scan", "from A->B elif (recent.type == 'reply' and ((scan.src == recent.dst)", "entry import timerlist __author__ = \"pythonhacker\" __maintainer__ = \"pythonhacker\" __version__", "to '.join(scan_ip2quad(scan))) break # Reply from B->A for full-connect scan", "'%s scan (flags:%d) from %s to %s (ports:%s)' else: tup.append(ip2quad(scan.zombie))", "threshold # Timeout for scan entries self.timeout = timeout #", "scan, see if there was a recent idle scan #", "# Log file try: self.scanlog = open(logfile,'a') print >> sys.stderr,", "scan = self.scans[key] if scan.src != src: # Skip packets", "address \"\"\" value = addr h = 0 while value:", "'TCP full-connect', # Not a scan TH_RST|TH_ACK: 'reply'} def __init__(self,", "(flags: %d) from %s to %s (ports: %s) using zombie", "to publish to google. Apr 8 2010 - Better detection", "update port weights... # print 'Weight=>',lscan.weight if not self.inspect_scan(lscan, True):", "scan to file and/or console \"\"\" srcip, dstip = scan_ip2quad(scan)", "log(self, msg): \"\"\" Log a message to console and/or log", "if dport in scan.ports: return # Add weight for port", "__author__ = \"pythonhacker\" __maintainer__ = \"pythonhacker\" __version__ = '0.5.1' __modified__", "from host # X to host Z. Then actually Y", "= ip.data src,dst,dport,flags = int(struct.unpack('I',ip.src)[0]),int(struct.unpack('I', ip.dst)[0]),int(pload.dport),0 proto = type(pload) if", "logs it correctly using correlation! 3. Detects SCTP scan. 4.", "print >>sys.stderr, \"fork #2 failed\", e sys.exit(1) self.loop() def run(self):", "zombie host to the scanning # host when a scanning", "scan.type = self.scan_types.get(scan.flags_or,'unknown') if scan.type in ('', 'reply'): not_scan =", "b, c): a -= b; a -= c; a ^=", "o.add_option(\"-d\", \"--daemonize\", dest=\"daemon\", help=\"Daemonize\", action=\"store_true\", default=False) o.add_option(\"-f\", \"--logfile\", dest=\"logfile\", help=\"File", "'TCP fin/ack', TH_SYN|TH_ACK: 'TCP full-connect', TH_URG|TH_PSH|TH_ACK|TH_RST|TH_SYN|TH_FIN: 'TCP all-flags', TH_SYN|TH_ACK|TH_RST: 'TCP", "self.threshold/2 # Daemonize ? self.daemon = daemon # Log file", "= (slow_scan and len(scan.ports)>=3 and len(scan.timediffs)>=4 and (scan.weight < self.threshold_l))", "correlation! 3. Detects SCTP scan. 4. Detects slow port-scans also.", "19:21:11 IST 2010' # UDP - in progress... SCAN_TIMEOUT =", "sys.exit(0) except OSError, e: print >>sys.stderr, \"fork #2 failed\", e", "if self.scanlog: self.scanlog.write(line + '\\n') self.scanlog.flush() if not self.daemon: print", "ndrop def run_daemon(self): # Disconnect from tty try: pid =", "scan.flags_or == TH_SYN and len(self.recent_scans): # Try last 1 scans", "Recent scans - this list allows to keep scan information", "= dst lscan.timestamp = curr lscan.timediffs.append(curr - prev) lscan.flags_or |=", "new thread and wait for it if self.daemon: print 'Daemonizing...'", "is idle scanning # Z dummy_scans, idle_ports = [], []", "recent in recent1: if recent.type=='Idle' and scan.src==recent.zombie: self.log('Ignoring mis-interpreted syn", "scan.flags_or |= flags if dport in scan.ports: return # Add", "len(scan.ports)>=3 and len(scan.timediffs)>=4 and (scan.weight < self.threshold_l)) not_scan = False", "self.log(\"Ignoring spurious TCP full-connect scan from %s\" % ' to", "#!/usr/bin/env python \"\"\" pyscanlogger: Port scan detector/logger tool, inspired by", "full-connect', TH_URG|TH_PSH|TH_ACK|TH_RST|TH_SYN|TH_FIN: 'TCP all-flags', TH_SYN|TH_ACK|TH_RST: 'TCP full-connect', # Not a", "this was logged recently scanentry = entry.RecentScanEntry(scan, not not_scan) if", "return self.hash_func(self.mix(src, dst, 0xffffff)) def log(self, msg): \"\"\" Log a", ">> sys.stderr, line def log_scan(self, scan, continuation=False, slow_scan=False, unsure=False): \"\"\"", "Port scan detector/logger \"\"\" # TCP flags to scan type", "to the scanning # host when a scanning host is", "# there was no recent full-connect scan from B->A, if", "== recent.src)): # Spurious self.log(\"Ignoring spurious TCP full-connect scan from", "If dameon, then create a new thread and wait for", "scan.type = 'UDP' # Reset flags for UDP scan scan.flags_or", "then create a new thread and wait for it if", "TH_SYN|TH_RST: 'TCP syn', TH_ACK: 'TCP ack', TH_URG|TH_PSH|TH_FIN: 'TCP x-mas', TH_URG|TH_PSH|TH_FIN|TH_ACK:", "GPL v3.0. \"\"\" import sys, os import dpkt, pcap import", "from %s\" % ' to '.join(scan_ip2quad(scan))) not_scan = True break", "scanning # Z dummy_scans, idle_ports = [], [] for item", "so this is spurious and should be ignored. if scan.flags_or", "x: socket.inet_ntoa(struct.pack('I', x)) scan_ip2quad = lambda scan: map(ip2quad, [scan.src, scan.dst])", "opening scan log file %s => %s\" % (logfile, strerror)", "def log_scan(self, scan, continuation=False, slow_scan=False, unsure=False): \"\"\" Log the scan", "not continuation: tup = [scan.type,scan.flags_or,srcip,dstip, ports] if not slow_scan: if", "pload.flags key = self.host_hash(src,dst) curr=time.time() # Keep dropping old entries", "sec by default. # Since entries time out in 60", "logging functions. Licensed under GNU GPL v3.0. \"\"\" import sys,", "flags lscan.timediffs.append(curr - prev) lscan.update_time_sd() self.update_ports(lscan, dport, flags) if lscan.time_sd<2:", "in self.scans: scan = self.scans[key] if scan.src != src: #", "TH_ACK: 'TCP ack', TH_URG|TH_PSH|TH_FIN: 'TCP x-mas', TH_URG|TH_PSH|TH_FIN|TH_ACK: 'TCP x-mas', TH_SYN|TH_FIN:", "= o.parse_args() s=ScanLogger(SCAN_TIMEOUT, WEIGHT_THRESHOLD, 8192, options.daemon, options.logfile) s.run() if __name__", "import struct import socket import time import threading import optparse", "# TCP flag constants TH_URG=dpkt.tcp.TH_URG TH_ACK=dpkt.tcp.TH_ACK TH_PSH=dpkt.tcp.TH_PUSH TH_RST=dpkt.tcp.TH_RST TH_SYN=dpkt.tcp.TH_SYN TH_FIN=dpkt.tcp.TH_FIN", "scan.src = scan.dst scan.dst = rscan.dst scan.zombie = rscan.src scan.type", "for recent in recent1: if recent.type=='Idle' and scan.src==recent.zombie: self.log('Ignoring mis-interpreted", "= '[%s]: %s' % (get_timestamp(), msg) if self.scanlog: self.scanlog.write(line +", "print 'Removing',key,lscan.src,'since not a scan' del self.long_scans[key] elif len(lscan.timediffs)>2: #", "logfile except (IOError, OSError), (errno, strerror): print >> sys.stderr, \"Error", "% ' to '.join(scan_ip2quad(scan))) break # Reply from B->A for", "C as if B is syn scanning it # and", "self.recent_scans.remove(d) else: # Remove entry if slow_scan: del self.long_scans[scan.hash] else:", "if self.daemon: print 'Daemonizing...' self.run_daemon() else: # Run in foreground", "else: lscan = self.long_scans[key] lscan.timestamp = curr lscan.flags_or |= flags", "\"\"\" return self.hash_func(self.mix(src, dst, 0xffffff)) def log(self, msg): \"\"\" Log", "lambda scan: map(ip2quad, [scan.src, scan.dst]) class ScanLogger(object): \"\"\" Port scan", "inspired by scanlogd {http://www.openwall.com/scanlogd} but with added ability to log", "open(logfile,'a') print >> sys.stderr, 'Scan logs will be saved to", "self.scan_types.get(scan.flags_or,'unknown') if scan.type in ('', 'reply'): not_scan = True #", "= [], [] for item in reversed(self.recent_scans): rscan = item[1]", "x)) scan_ip2quad = lambda scan: map(ip2quad, [scan.src, scan.dst]) class ScanLogger(object):", "B - zombie host # C - target host #", "2010 - Better detection of TCP full-connect scan without spurious", "'.join(scan_ip2quad(scan))) break # Reply from B->A for full-connect scan from", "self.daemon: print 'Daemonizing...' self.run_daemon() else: # Run in foreground self.loop()", "ts, pkt in pc: self.process(decode(pkt)) except KeyboardInterrupt: if not self.daemon:", "slow_scan=slow_scan, unsure=maybe_scan) # Remove entry if slow_scan: del self.long_scans[scan.hash] else:", "History Mar 17 2010 - Cleaned up code to publish", "and ((scan.src == recent.dst) and (scan.dst == recent.src))): scan.type =", "Daemonize ? self.daemon = daemon # Log file try: self.scanlog", "(TCP, UDP, SCTP): return pload = ip.data src,dst,dport,flags = int(struct.unpack('I',ip.src)[0]),int(struct.unpack('I',", "os.umask(0) # Second fork try: pid = os.fork() if pid>0:", "= lambda : time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) ip2quad = lambda x:", "scan, skip if not recent.is_scan: continue if recent.type == 'TCP", "self.timeout): # Add entry in long_scans if timediff not larger", "loop(self): pc = pcap.pcap() decode = { pcap.DLT_LOOP:dpkt.loopback.Loopback, pcap.DLT_NULL:dpkt.loopback.Loopback, pcap.DLT_EN10MB:dpkt.ethernet.Ethernet", "'0.5.1' __modified__ = 'Thu Apr 8 19:21:11 IST 2010' #", "scan.weight >= self.threshold)) # Possible scan maybe_scan = (slow_scan and", "= 25 PIDFILE=\"/var/run/pyscanlogger.pid\" # TCP flag constants TH_URG=dpkt.tcp.TH_URG TH_ACK=dpkt.tcp.TH_ACK TH_PSH=dpkt.tcp.TH_PUSH", "threshold self.threshold_l = self.threshold/2 # Daemonize ? self.daemon = daemon", "same time-period. 'n' is 60 sec by default. # Since", "too many # then this is a regular network activity", "flags to scan type mapping scan_types = {0: 'TCP null',", "= 'Idle' scan.ports = idle_ports # for d in dummy_scans:", "be ignored. if scan.flags_or == (TH_SYN|TH_ACK|TH_RST) and len(self.recent_scans): recent1 =", "entry # print 'Removing',key,lscan.src,'since SD is',lscan.time_sd del self.long_scans[key] else: #", "dropping old entries self.recent_scans.collect() if key in self.scans: scan =", "b -= a; b ^= (a<<16) c -= a; c", "TH_SYN and len(self.recent_scans): # Try last 1 scans recent1 =", "maximum such entries possible in 60 sec - assuming #", "0xffffff)) def log(self, msg): \"\"\" Log a message to console", "self.daemon: nrecv, ndrop, nifdrop = pc.stats() print '\\n%d packets received", "Detects all stealth (half-open) and full-connect scans. 2. Detects Idle", "Keep dropping old entries self.recent_scans.collect() if key in self.scans: scan", "scan: map(ip2quad, [scan.src, scan.dst]) class ScanLogger(object): \"\"\" Port scan detector/logger", "return # Add weight for port if dport < 1024:", "could get an apparent RST \"scan\" # from B to", "scan.type != 'Idle': line = 'Continuation of %s scan from", "thread and wait for it if self.daemon: print 'Daemonizing...' self.run_daemon()", "in foreground self.loop() def main(): if os.geteuid() != 0: sys.exit(\"You", "'listening on %s: %s' % (pc.name, pc.filter) for ts, pkt", "= pkt.ip # Ignore non-tcp, non-udp packets if type(ip.data) not", "detection of TCP full-connect scan without spurious and incorrect logging.", "def process(self, pkt): if not hasattr(pkt, 'ip'): return ip =", "value = value >> 9 return h & (8192-1) def", "(half-open) and full-connect scans. 2. Detects Idle scan and logs", "correctly using correlation! 3. Detects SCTP scan. 4. Detects slow", "# print value h ^= value value = value >>", "8 2010 - Better detection of TCP full-connect scan without", "daemon=True, logfile='/var/log/scanlog'): self.scans = entry.EntryLog(maxsize) self.long_scans = entry.EntryLog(maxsize) # Port", "^= (b>>13) a -= b; a -= c; a ^=", "< self.threshold_l)) not_scan = False if is_scan or maybe_scan: scan.logged", "= item[1] if rscan.src==scan.src and rscan.flags_or==TH_SYN and ((rscan.timestamp - scan.timestamp)<30):", "from zombie host %s' % ' to '.join(scan_ip2quad(scan))) break #", "reverse direction or invalid protocol return timediff = curr -", "make sure that # there was no recent full-connect scan", "# of entries - if too many # then this", "self.inspect_scan(scan) else: # Add new entry scan = entry.ScanEntry(key) scan.src", "utf-8 #!/usr/bin/env python \"\"\" pyscanlogger: Port scan detector/logger tool, inspired", "sys.stderr, line def log_scan(self, scan, continuation=False, slow_scan=False, unsure=False): \"\"\" Log", "stealth (half-open) and full-connect scans. 2. Detects Idle scan and", "1. Detects all stealth (half-open) and full-connect scans. 2. Detects", "(recent.type == 'reply' and ((scan.src == recent.dst) and (scan.dst ==", "sure that # there was no recent full-connect scan from", "ports] if not slow_scan: if scan.type != 'Idle': line =", "self.recent_scans.append(scanentry) else: continuation=True if not not_scan: self.log_scan(scan, continuation=continuation, slow_scan=slow_scan, unsure=maybe_scan)", "^= (a<<8) c -= a; c -= b; c ^=", "%H:%M:%S', time.localtime()) ip2quad = lambda x: socket.inet_ntoa(struct.pack('I', x)) scan_ip2quad =", "= False if scan.flags_or==TH_RST: # None does scan using RST,", "If A does an idle scan on C with B", "and len(scan.timediffs)>=4 and (scan.weight < self.threshold_l)) not_scan = False if", "host # If A does an idle scan on C", "be # return packets from a zombie host to the", "zombie host %s' else: tup.append(scan.time_avg) if unsure: line = 'Possible", "= '0.5.1' __modified__ = 'Thu Apr 8 19:21:11 IST 2010'", "scan using RST, however this could be # return packets", "= rscan.dst scan.zombie = rscan.src scan.type = 'Idle' scan.ports =", "self.long_scans[key] lscan.timestamp = curr lscan.flags_or |= flags lscan.timediffs.append(curr - prev)", "Try last 1 scans recent1 = self.recent_scans[-1:-2:-1] for recent in", "17 2010 - Cleaned up code to publish to google.", "idle scan. # Basically # A -scanning host # B", "pc.stats() print '\\n%d packets received by filter' % nrecv print", "-= a; b ^= (a<<10) c -= a; c -=", "value = addr h = 0 while value: # print", "-= a; c -= b; c ^= (b>>13) a -=", "(flags:%d) from %s to %s (ports:%s)' else: tup.append(ip2quad(scan.zombie)) line =", "scan.proto==TCP: idle_scan = False if scan.flags_or==TH_RST: # None does scan", "scan from B->A, if # so this is spurious and", "size is equal # to maximum such entries possible in", "full-connect scan from %s\" % ' to '.join(scan_ip2quad(scan))) not_scan =", "scan.weight += 3 else: scan.weight += 1 scan.ports.append(dport) def inspect_scan(self,", "to scan type mapping scan_types = {0: 'TCP null', TH_FIN:", "3600 # Long-period scan threshold self.threshold_l = self.threshold/2 # Daemonize", "X to host Z. Then actually Y is idle scanning", "a zombie host to the scanning # host when a", "= 0 elif scan.proto==SCTP: if scan.chunk_type==1: scan.type = 'SCTP Init'", "flags 22 from A->B, make sure that # there was", "curr lscan.flags_or |= flags lscan.timediffs.append(curr - prev) lscan.update_time_sd() self.update_ports(lscan, dport,", "run_daemon(self): # Disconnect from tty try: pid = os.fork() if", "a -= c; a ^= (c>>12) b -= c; b", "scan.src = src scan.dst = dst scan.timestamp = curr scan.flags_or", "maybe_scan = (slow_scan and len(scan.ports)>=3 and len(scan.timediffs)>=4 and (scan.weight <", "< 1024: scan.weight += 3 else: scan.weight += 1 scan.ports.append(dport)", "activity # but not a scan, so remove entry if", "and should be ignored. if scan.flags_or == (TH_SYN|TH_ACK|TH_RST) and len(self.recent_scans):", "60 sec - assuming # a scan occurs at most", "__modified__ = 'Thu Apr 8 19:21:11 IST 2010' # UDP", "type(ip.data) not in (TCP, UDP, SCTP): return pload = ip.data", "dest=\"daemon\", help=\"Daemonize\", action=\"store_true\", default=False) o.add_option(\"-f\", \"--logfile\", dest=\"logfile\", help=\"File to save", "scan.dst]) class ScanLogger(object): \"\"\" Port scan detector/logger \"\"\" # TCP", "as to not call duplicate scans # in the same", "!= 'Idle': line = 'Continuation of %s scan from %s", "is_scan = ((slow_scan and scan.weight >= self.threshold_l) or (not slow_scan", "else: # Run in foreground self.loop() def main(): if os.geteuid()", "%s to %s (ports:%s)' else: tup.append(ip2quad(scan.zombie)) line = 'Continuation of", "dameon, then create a new thread and wait for it", "this program\") o=optparse.OptionParser() o.add_option(\"-d\", \"--daemonize\", dest=\"daemon\", help=\"Daemonize\", action=\"store_true\", default=False) o.add_option(\"-f\",", "and logs it correctly using correlation! 3. Detects SCTP scan.", "%s (ports:%s), average timediff %.2fs' msg = line % tuple(tup)", "coding: utf-8 #!/usr/bin/env python \"\"\" pyscanlogger: Port scan detector/logger tool,", "without spurious and incorrect logging. Better logging functions. Licensed under", "ScanLogger(object): \"\"\" Port scan detector/logger \"\"\" # TCP flags to", "curr scan.flags_or |= flags if proto==SCTP: scan.chunk_type = pload.chunks[0].type scan.ports.append(dport)", "this as zombie, then ignore it... elif scan.flags_or == TH_SYN", "spurious TCP full-connect scan from %s\" % ' to '.join(scan_ip2quad(scan)))", "remove entry if (timediff > self.timeout): # Add entry in", "log slow port-scans. Features 1. Detects all stealth (half-open) and", "%s\" % ' to '.join(scan_ip2quad(scan))) not_scan = True break #", "# Not a scan, check # of entries - if", "Mar 17 2010 - Cleaned up code to publish to", "X to Y # See if there was a SYN", "!= 0: sys.exit(\"You must be super-user to run this program\")", "threading import optparse import entry import timerlist __author__ = \"pythonhacker\"", "self.timeout = timeout # Long-period scan timeouts self.timeout_l = 3600", "\"--logfile\", dest=\"logfile\", help=\"File to save logs to\", default=\"/var/log/scanlog\") options, args", "SCTP scan. 4. Detects slow port-scans also. Modification History Mar", "-= b; c ^= (b>>5) a -= b; a -=", "is',lscan.time_sd del self.long_scans[key] else: # Too large timeout, remove key", "scan.timestamp = curr scan.flags_or |= flags if proto==SCTP: scan.chunk_type =", "entries self.timeout = timeout # Long-period scan timeouts self.timeout_l =", "curr lscan.timediffs.append(curr - prev) lscan.flags_or |= flags lscan.ports.append(dport) lscan.proto =", "self.long_scans[key] elif len(lscan.timediffs)>2: # More than 2 entries, but SD", "under GNU GPL v3.0. \"\"\" import sys, os import dpkt,", "this could be # return packets from a zombie host", "Too large timeout, remove key del self.long_scans[key] del self.scans[key] return", "12. self.recent_scans = timerlist.TimerList(12, 60.0) def hash_func(self, addr): \"\"\" Hash", "# so this is spurious and should be ignored. if", "timeout, threshold, maxsize, daemon=True, logfile='/var/log/scanlog'): self.scans = entry.EntryLog(maxsize) self.long_scans =", "host Z. Then actually Y is idle scanning # Z", "= \"pythonhacker\" __version__ = '0.5.1' __modified__ = 'Thu Apr 8", "not self.inspect_scan(lscan, True): # Not a scan, check # of", "scan entries self.timeout = timeout # Long-period scan timeouts self.timeout_l", "return if scan.logged: return scan.timestamp = curr self.update_ports(scan, dport, flags)", "if len(lscan.timediffs)>=10: # print lscan.src, lscan.timediffs, lscan.time_sd print 'Removing',key,lscan.src,'since not", "keep scan information # upto last 'n' seconds, so as", "to run this program\") o=optparse.OptionParser() o.add_option(\"-d\", \"--daemonize\", dest=\"daemon\", help=\"Daemonize\", action=\"store_true\",", "scanning # host when a scanning host is doing an", "'TCP all-flags', TH_SYN|TH_ACK|TH_RST: 'TCP full-connect', # Not a scan TH_RST|TH_ACK:", "def __init__(self, timeout, threshold, maxsize, daemon=True, logfile='/var/log/scanlog'): self.scans = entry.EntryLog(maxsize)", "= 'Possible slow %s scan (flags:%d) from %s to %s", "from B->A, if # so this is spurious and should", "-= c; b -= a; b ^= (a<<16) c -=", "sys.exit(0) except OSError, e: print >>sys.stderr, \"fork #1 failed\", e", "rscan.dst scan.zombie = rscan.src scan.type = 'Idle' scan.ports = idle_ports", "scan.proto==UDP: scan.type = 'UDP' # Reset flags for UDP scan", "get_timestamp = lambda : time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) ip2quad = lambda", "# See if this was logged recently scanentry = entry.RecentScanEntry(scan,", "a -= b; a -= c; a ^= (c>>13) b", "= '%s scan (flags: %d) from %s to %s (ports:", "dst, 0xffffff)) def log(self, msg): \"\"\" Log a message to", "at most every 5 seconds, this would be 12. self.recent_scans", "= entry.ScanEntry(key) lscan.src = src lscan.dst = dst lscan.timestamp =", "TH_FIN: 'TCP fin', TH_SYN: 'TCP syn', TH_SYN|TH_RST: 'TCP syn', TH_ACK:", "see if there was a recent idle scan # with", "tup = [scan.type, srcip,dstip, ports] if not slow_scan: if scan.type", "port if dport < 1024: scan.weight += 3 else: scan.weight", "a ^= (c>>12) b -= c; b -= a; b", "flags) self.inspect_scan(scan) else: # Add new entry scan = entry.ScanEntry(key)", "in the same time-period. 'n' is 60 sec by default.", "value >> 9 return h & (8192-1) def mix(self, a,", "idle_ports # for d in dummy_scans: # self.recent_scans.remove(d) else: #", "failed\", e sys.exit(1) os.setsid() os.umask(0) # Second fork try: pid", "line = '[%s]: %s' % (get_timestamp(), msg) if self.scanlog: self.scanlog.write(line", "ip2quad = lambda x: socket.inet_ntoa(struct.pack('I', x)) scan_ip2quad = lambda scan:", "if B is syn scanning it # and later we", "entries - if too many # then this is a", "# Second fork try: pid = os.fork() if pid>0: open(PIDFILE,'w').write(str(pid))", "scan, so remove entry if len(lscan.timediffs)>=10: # print lscan.src, lscan.timediffs,", "try: pid = os.fork() if pid>0: open(PIDFILE,'w').write(str(pid)) sys.exit(0) except OSError,", "('', 'reply'): not_scan = True # If we see scan", "= type(pload) if proto == TCP: flags = pload.flags key", "Hash mix two host addresses \"\"\" return self.hash_func(self.mix(src, dst, 0xffffff))", "run(self): # If dameon, then create a new thread and", "Better detection of TCP full-connect scan without spurious and incorrect", "rscan.src scan.type = 'Idle' scan.ports = idle_ports # for d", "self.recent_scans[-1:-2:-1] for recent in recent1: # Was not a scan,", "self.timeout_l = 3600 # Long-period scan threshold self.threshold_l = self.threshold/2", "this is a regular network activity # but not a", "python \"\"\" pyscanlogger: Port scan detector/logger tool, inspired by scanlogd", "'TCP full-connect', TH_URG|TH_PSH|TH_ACK|TH_RST|TH_SYN|TH_FIN: 'TCP all-flags', TH_SYN|TH_ACK|TH_RST: 'TCP full-connect', # Not", "scan.chunk_type==1: scan.type = 'SCTP Init' elif scan.chunk_type==10: scan.type = 'SCTP", "SD is too large, # delete the entry # print", "Log a message to console and/or log file \"\"\" line", "print 'Weight=>',lscan.weight if not self.inspect_scan(lscan, True): # Not a scan,", "if slow_scan: del self.long_scans[scan.hash] else: del self.scans[scan.hash] return False else:", "if not slow_scan: if scan.type != 'Idle': line = '%s", "scan, slow_scan=False): # Sure scan is_scan = ((slow_scan and scan.weight", "and scan.weight >= self.threshold_l) or (not slow_scan and scan.weight >=", "= idle_ports # for d in dummy_scans: # self.recent_scans.remove(d) else:", "(c>>12) b -= c; b -= a; b ^= (a<<16)", "scan.src==recent.zombie: self.log('Ignoring mis-interpreted syn scan from zombie host %s' %", "SD is less than 2, possible slow scan # update", "o.add_option(\"-f\", \"--logfile\", dest=\"logfile\", help=\"File to save logs to\", default=\"/var/log/scanlog\") options,", "scan = entry.ScanEntry(key) scan.src = src scan.dst = dst scan.timestamp", "while value: # print value h ^= value value =", "will be saved to %s' % logfile except (IOError, OSError),", "=> %s\" % (logfile, strerror) self.scanlog = None # Recent", "# Possible scan maybe_scan = (slow_scan and len(scan.ports)>=3 and len(scan.timediffs)>=4", "-= c; a ^= (c>>3) b -= c; b -=", "\"scan\" # from B to A # Correlation: If 'RST", "recent1: # Was not a scan, skip if not recent.is_scan:", "else: del self.scans[scan.hash] return False else: scan.type = self.scan_types.get(scan.flags_or,'unknown') if", "to keep scan information # upto last 'n' seconds, so", "(scan.dst == recent.src))): scan.type = 'TCP full-connect' break elif scan.proto==UDP:", "key not in self.long_scans: lscan = entry.ScanEntry(key) lscan.src = src", "# update port weights... # print 'Weight=>',lscan.weight if not self.inspect_scan(lscan,", "# Try last 1 scans recent1 = self.recent_scans[-1:-2:-1] for recent", "\"\"\" import sys, os import dpkt, pcap import struct import", "from B->A for full-connect scan from A->B elif (recent.type ==", "b -= a; b ^= (a<<8) c -= a; c", "# Port scan weight threshold self.threshold = threshold # Timeout", "using RST, however this could be # return packets from", "lambda x: socket.inet_ntoa(struct.pack('I', x)) scan_ip2quad = lambda scan: map(ip2quad, [scan.src,", "= entry.EntryLog(maxsize) self.long_scans = entry.EntryLog(maxsize) # Port scan weight threshold", "self.daemon: print >> sys.stderr, line def log_scan(self, scan, continuation=False, slow_scan=False,", "%s' else: tup.append(scan.time_avg) if unsure: line = 'Possible slow %s", "publish to google. Apr 8 2010 - Better detection of", "(logfile, strerror) self.scanlog = None # Recent scans - this", "elif (recent.type == 'reply' and ((scan.src == recent.dst) and (scan.dst", "TCP flags to scan type mapping scan_types = {0: 'TCP", "a; b ^= (a<<10) c -= a; c -= b;", "TH_RST=dpkt.tcp.TH_RST TH_SYN=dpkt.tcp.TH_SYN TH_FIN=dpkt.tcp.TH_FIN # Protocols TCP=dpkt.tcp.TCP UDP=dpkt.udp.UDP SCTP=dpkt.sctp.SCTP get_timestamp =", "C with B as zombie, # it will appear to", "^= (c>>12) b -= c; b -= a; b ^=", "'reply'): not_scan = True # If we see scan flags", "pkt.ip # Ignore non-tcp, non-udp packets if type(ip.data) not in", "from %s to %s (ports:%s), average timediff %.2fs' else: tup", "target host # If A does an idle scan on", "a -= b; a -= c; a ^= (c>>3) b", "del self.scans[scan.hash] return True else: return False def process(self, pkt):", "# Long-period scan timeouts self.timeout_l = 3600 # Long-period scan", "flags lscan.ports.append(dport) lscan.proto = proto self.long_scans[key] = lscan else: lscan", "def update_ports(self, scan, dport, flags): scan.flags_or |= flags if dport", "large, # delete the entry # print 'Removing',key,lscan.src,'since SD is',lscan.time_sd", "import sys, os import dpkt, pcap import struct import socket", "sys.exit(1) self.loop() def run(self): # If dameon, then create a", "h ^= value value = value >> 9 return h", "slow_scan: del self.long_scans[scan.hash] else: del self.scans[scan.hash] return True else: return", "c; a ^= (c>>13) b -= c; b -= a;", "and ((scan.src == recent.dst) and (scan.dst == recent.src)): # Spurious", "= entry.EntryLog(maxsize) # Port scan weight threshold self.threshold = threshold", "# See if there was a SYN scan recently from", "\"\"\" Log the scan to file and/or console \"\"\" srcip,", "pid = os.fork() if pid>0: sys.exit(0) except OSError, e: print", "a; b ^= (a<<8) c -= a; c -= b;", "recent.src)): # Spurious self.log(\"Ignoring spurious TCP full-connect scan from %s\"", "self.scans: scan = self.scans[key] if scan.src != src: # Skip", "else: # Too large timeout, remove key del self.long_scans[key] del", "= value >> 9 return h & (8192-1) def mix(self,", "+ '\\n') self.scanlog.flush() if not self.daemon: print >> sys.stderr, line", "= 'SCTP Init' elif scan.chunk_type==10: scan.type = 'SCTP COOKIE_ECHO' #", "elif len(lscan.timediffs)>2: # More than 2 entries, but SD is", "print >> sys.stderr, line def log_scan(self, scan, continuation=False, slow_scan=False, unsure=False):", "# Correlation: If 'RST scan' detected from X to Y", "Licensed under GNU GPL v3.0. \"\"\" import sys, os import", "direction or invalid protocol return timediff = curr - scan.timestamp", "# Long-period scan threshold self.threshold_l = self.threshold/2 # Daemonize ?", "in 60 seconds, max size is equal # to maximum", "scan.ports]) if not continuation: tup = [scan.type,scan.flags_or,srcip,dstip, ports] if not", "# C - target host # If A does an", "^= (a<<10) c -= a; c -= b; c ^=", "flags if dport in scan.ports: return # Add weight for", "for port if dport < 1024: scan.weight += 3 else:", "non-udp packets if type(ip.data) not in (TCP, UDP, SCTP): return", "\"pythonhacker\" __version__ = '0.5.1' __modified__ = 'Thu Apr 8 19:21:11", "self.log('Ignoring mis-interpreted syn scan from zombie host %s' % '", "- in progress... SCAN_TIMEOUT = 5 WEIGHT_THRESHOLD = 25 PIDFILE=\"/var/run/pyscanlogger.pid\"", "c -= b; c ^= (b>>15) return abs(c) def host_hash(self,", "if timediff not larger # than longscan timeout prev =", "'TCP syn', TH_SYN|TH_RST: 'TCP syn', TH_ACK: 'TCP ack', TH_URG|TH_PSH|TH_FIN: 'TCP", "average timediff %.2fs' else: line = 'Slow %s scan (flags:%d)", "return packets from a zombie host to the scanning #", "line def log_scan(self, scan, continuation=False, slow_scan=False, unsure=False): \"\"\" Log the", "4. Detects slow port-scans also. Modification History Mar 17 2010", "def hash_func(self, addr): \"\"\" Hash a host address \"\"\" value", "c; a ^= (c>>3) b -= c; b -= a;", "C - target host # If A does an idle", "recent1: if recent.type=='Idle' and scan.src==recent.zombie: self.log('Ignoring mis-interpreted syn scan from", "not a scan' del self.long_scans[key] elif len(lscan.timediffs)>2: # More than", "dst): \"\"\" Hash mix two host addresses \"\"\" return self.hash_func(self.mix(src,", "and/or log file \"\"\" line = '[%s]: %s' % (get_timestamp(),", "','.join([str(port) for port in scan.ports]) if not continuation: tup =", "sys.stderr, 'Scan logs will be saved to %s' % logfile", "full-connect scan from B->A, if # so this is spurious", "with this as zombie, then ignore it... elif scan.flags_or ==", "%s scan (flags:%d) from %s to %s (ports:%s), average timediff", "= scan def loop(self): pc = pcap.pcap() decode = {", "if rscan.src==scan.src and rscan.flags_or==TH_SYN and ((rscan.timestamp - scan.timestamp)<30): idle_scan =", "is too large, # delete the entry # print 'Removing',key,lscan.src,'since", "|= flags lscan.timediffs.append(curr - prev) lscan.update_time_sd() self.update_ports(lscan, dport, flags) if", "= line % tuple(tup) self.log(msg) def update_ports(self, scan, dport, flags):", "log file %s => %s\" % (logfile, strerror) self.scanlog =", "if proto==SCTP: scan.chunk_type = pload.chunks[0].type scan.ports.append(dport) scan.proto = proto self.scans[key]", "rscan.flags_or==TH_SYN and ((rscan.timestamp - scan.timestamp)<30): idle_scan = True idle_ports.append(rscan.ports) dummy_scans.append(item)", "line = 'Continuation of slow %s scan from %s to", "in progress... SCAN_TIMEOUT = 5 WEIGHT_THRESHOLD = 25 PIDFILE=\"/var/run/pyscanlogger.pid\" #", "self.loop() def run(self): # If dameon, then create a new", "does an idle scan on C with B as zombie,", "be saved to %s' % logfile except (IOError, OSError), (errno,", "if scan.flags_or == (TH_SYN|TH_ACK|TH_RST) and len(self.recent_scans): recent1 = self.recent_scans[-1:-2:-1] for", "weight for port if dport < 1024: scan.weight += 3", "'n' is 60 sec by default. # Since entries time", "but not a scan, so remove entry if len(lscan.timediffs)>=10: #", "scanlogd {http://www.openwall.com/scanlogd} but with added ability to log slow port-scans.", "dst scan.timestamp = curr scan.flags_or |= flags if proto==SCTP: scan.chunk_type", "(ports: %s) using zombie host %s' else: tup.append(scan.time_avg) if unsure:", "True): # Not a scan, check # of entries -", "mix(self, a, b, c): a -= b; a -= c;", "new entry scan = entry.ScanEntry(key) scan.src = src scan.dst =", "try: self.scanlog = open(logfile,'a') print >> sys.stderr, 'Scan logs will", "all stealth (half-open) and full-connect scans. 2. Detects Idle scan", "in pc: self.process(decode(pkt)) except KeyboardInterrupt: if not self.daemon: nrecv, ndrop,", "progress... SCAN_TIMEOUT = 5 WEIGHT_THRESHOLD = 25 PIDFILE=\"/var/run/pyscanlogger.pid\" # TCP", "= self.long_scans[key] lscan.timestamp = curr lscan.flags_or |= flags lscan.timediffs.append(curr -", "to not call duplicate scans # in the same time-period.", "if there was a recent idle scan # with this", "+= 1 scan.ports.append(dport) def inspect_scan(self, scan, slow_scan=False): # Sure scan", "scan.src != src: # Skip packets in reverse direction or", "pload.chunks[0].type scan.ports.append(dport) scan.proto = proto self.scans[key] = scan def loop(self):", "file %s => %s\" % (logfile, strerror) self.scanlog = None", "len(self.recent_scans): # Try last 1 scans recent1 = self.recent_scans[-1:-2:-1] for", "import timerlist __author__ = \"pythonhacker\" __maintainer__ = \"pythonhacker\" __version__ =", "and (scan.dst == recent.src))): scan.type = 'TCP full-connect' break elif", "if is_scan or maybe_scan: scan.logged = True if scan.proto==TCP: idle_scan", "def inspect_scan(self, scan, slow_scan=False): # Sure scan is_scan = ((slow_scan", "%s' % logfile except (IOError, OSError), (errno, strerror): print >>", "[scan.src, scan.dst]) class ScanLogger(object): \"\"\" Port scan detector/logger \"\"\" #", "'[%s]: %s' % (get_timestamp(), msg) if self.scanlog: self.scanlog.write(line + '\\n')", "c ^= (b>>5) a -= b; a -= c; a", "True if scan.proto==TCP: idle_scan = False if scan.flags_or==TH_RST: # None", "time import threading import optparse import entry import timerlist __author__", "is a syn scan, see if there was a recent", "else: scan.weight += 1 scan.ports.append(dport) def inspect_scan(self, scan, slow_scan=False): #", "if # so this is spurious and should be ignored.", "def host_hash(self, src, dst): \"\"\" Hash mix two host addresses", "a; c -= b; c ^= (b>>5) a -= b;", "max size is equal # to maximum such entries possible", "delete the entry # print 'Removing',key,lscan.src,'since SD is',lscan.time_sd del self.long_scans[key]", "\"\"\" srcip, dstip = scan_ip2quad(scan) ports = ','.join([str(port) for port", "from %s to %s (ports:%s)' else: tup.append(ip2quad(scan.zombie)) line = '%s", "proto == TCP: flags = pload.flags key = self.host_hash(src,dst) curr=time.time()", "\"fork #1 failed\", e sys.exit(1) os.setsid() os.umask(0) # Second fork", "hash_func(self, addr): \"\"\" Hash a host address \"\"\" value =", "= os.fork() if pid>0: open(PIDFILE,'w').write(str(pid)) sys.exit(0) except OSError, e: print", "action=\"store_true\", default=False) o.add_option(\"-f\", \"--logfile\", dest=\"logfile\", help=\"File to save logs to\",", "'Thu Apr 8 19:21:11 IST 2010' # UDP - in", "get an apparent RST \"scan\" # from B to A", "not_scan = True # If we see scan flags 22", "2010' # UDP - in progress... SCAN_TIMEOUT = 5 WEIGHT_THRESHOLD", "% (logfile, strerror) self.scanlog = None # Recent scans -", "# delete the entry # print 'Removing',key,lscan.src,'since SD is',lscan.time_sd del", "= True if scan.proto==TCP: idle_scan = False if scan.flags_or==TH_RST: #", "= 'Slow %s scan (flags:%d) from %s to %s (ports:%s),", "h = 0 while value: # print value h ^=", "# upto last 'n' seconds, so as to not call", "prev) lscan.update_time_sd() self.update_ports(lscan, dport, flags) if lscan.time_sd<2: # SD is", "import socket import time import threading import optparse import entry", "lscan.timediffs.append(curr - prev) lscan.update_time_sd() self.update_ports(lscan, dport, flags) if lscan.time_sd<2: #", "up code to publish to google. Apr 8 2010 -", "%s => %s\" % (logfile, strerror) self.scanlog = None #", "(ports:%s), average timediff %.2fs' else: line = 'Slow %s scan", "scan.dst = rscan.dst scan.zombie = rscan.src scan.type = 'Idle' scan.ports", "(b>>5) a -= b; a -= c; a ^= (c>>3)", "# from B to A # Correlation: If 'RST scan'", "# If A does an idle scan on C with", "9 return h & (8192-1) def mix(self, a, b, c):", "timediff %.2fs' msg = line % tuple(tup) self.log(msg) def update_ports(self,", "if pid>0: open(PIDFILE,'w').write(str(pid)) sys.exit(0) except OSError, e: print >>sys.stderr, \"fork", "recent.is_scan: continue if recent.type == 'TCP full-connect' and ((scan.src ==", "recent.dst) and (scan.dst == recent.src))): scan.type = 'TCP full-connect' break", "== TH_SYN and len(self.recent_scans): # Try last 1 scans recent1", "SD is',lscan.time_sd del self.long_scans[key] else: # Too large timeout, remove", "and/or console \"\"\" srcip, dstip = scan_ip2quad(scan) ports = ','.join([str(port)", "scan, dport, flags): scan.flags_or |= flags if dport in scan.ports:", "== recent.dst) and (scan.dst == recent.src))): scan.type = 'TCP full-connect'", "8 19:21:11 IST 2010' # UDP - in progress... SCAN_TIMEOUT", "by default. # Since entries time out in 60 seconds,", "item[1] if rscan.src==scan.src and rscan.flags_or==TH_SYN and ((rscan.timestamp - scan.timestamp)<30): idle_scan", "self.daemon = daemon # Log file try: self.scanlog = open(logfile,'a')", "for recent in recent1: # Was not a scan, skip", "'Slow %s scan (flags:%d) from %s to %s (ports:%s), average", "unsure=maybe_scan) # Remove entry if slow_scan: del self.long_scans[scan.hash] else: del", "args = o.parse_args() s=ScanLogger(SCAN_TIMEOUT, WEIGHT_THRESHOLD, 8192, options.daemon, options.logfile) s.run() if", "Sure scan is_scan = ((slow_scan and scan.weight >= self.threshold_l) or", "WEIGHT_THRESHOLD, 8192, options.daemon, options.logfile) s.run() if __name__ == '__main__': main()", "there was a SYN scan recently from host # X", "socket.inet_ntoa(struct.pack('I', x)) scan_ip2quad = lambda scan: map(ip2quad, [scan.src, scan.dst]) class", "scan from zombie host %s' % ' to '.join(scan_ip2quad(scan))) break", "from %s to %s (ports:%s), average timediff %.2fs' else: line", "None does scan using RST, however this could be #", "self.long_scans[scan.hash] else: del self.scans[scan.hash] return True else: return False def", "not a scan, so remove entry if len(lscan.timediffs)>=10: # print", "if lscan.time_sd<2: # SD is less than 2, possible slow", "slow %s scan (flags:%d) from %s to %s (ports:%s), average", "for item in reversed(self.recent_scans): rscan = item[1] if rscan.src==scan.src and", "continuation=False self.recent_scans.append(scanentry) else: continuation=True if not not_scan: self.log_scan(scan, continuation=continuation, slow_scan=slow_scan,", "'ip'): return ip = pkt.ip # Ignore non-tcp, non-udp packets", "longscan timeout prev = self.scans[key].timestamp if timediff<=self.timeout_l: if key not", "lscan.dst = dst lscan.timestamp = curr lscan.timediffs.append(curr - prev) lscan.flags_or", "full-connect' and ((scan.src == recent.dst) and (scan.dst == recent.src)): #", "process(self, pkt): if not hasattr(pkt, 'ip'): return ip = pkt.ip", "e sys.exit(1) self.loop() def run(self): # If dameon, then create", "!= 'Idle': line = '%s scan (flags:%d) from %s to", "& (8192-1) def mix(self, a, b, c): a -= b;", "3. Detects SCTP scan. 4. Detects slow port-scans also. Modification", "not not_scan) if scanentry not in self.recent_scans: continuation=False self.recent_scans.append(scanentry) else:", "# Timeout for scan entries self.timeout = timeout # Long-period", "if scan.type != 'Idle': line = 'Continuation of %s scan", "# Z dummy_scans, idle_ports = [], [] for item in", "# than longscan timeout prev = self.scans[key].timestamp if timediff<=self.timeout_l: if", "b ^= (a<<8) c -= a; c -= b; c", "= self.host_hash(src,dst) curr=time.time() # Keep dropping old entries self.recent_scans.collect() if", "recent full-connect scan from B->A, if # so this is", "self.threshold)) # Possible scan maybe_scan = (slow_scan and len(scan.ports)>=3 and", "-= b; a -= c; a ^= (c>>3) b -=", "to log slow port-scans. Features 1. Detects all stealth (half-open)", "if pid>0: sys.exit(0) except OSError, e: print >>sys.stderr, \"fork #1", "int(struct.unpack('I',ip.src)[0]),int(struct.unpack('I', ip.dst)[0]),int(pload.dport),0 proto = type(pload) if proto == TCP: flags", "lscan.proto = proto self.long_scans[key] = lscan else: lscan = self.long_scans[key]", "idle scan on C with B as zombie, # it", "% (get_timestamp(), msg) if self.scanlog: self.scanlog.write(line + '\\n') self.scanlog.flush() if", "(ports: %s) using zombie host %s' else: tup.append(scan.time_avg) line =", "A->B, make sure that # there was no recent full-connect", "tup = [scan.type,scan.flags_or,srcip,dstip, ports] if not slow_scan: if scan.type !=", "inspect_scan(self, scan, slow_scan=False): # Sure scan is_scan = ((slow_scan and", "# but not a scan, so remove entry if len(lscan.timediffs)>=10:", "60 sec by default. # Since entries time out in", "than longscan timeout prev = self.scans[key].timestamp if timediff<=self.timeout_l: if key", "= curr self.update_ports(scan, dport, flags) self.inspect_scan(scan) else: # Add new", "scan.zombie = rscan.src scan.type = 'Idle' scan.ports = idle_ports #", "ip.data src,dst,dport,flags = int(struct.unpack('I',ip.src)[0]),int(struct.unpack('I', ip.dst)[0]),int(pload.dport),0 proto = type(pload) if proto", "TH_FIN=dpkt.tcp.TH_FIN # Protocols TCP=dpkt.tcp.TCP UDP=dpkt.udp.UDP SCTP=dpkt.sctp.SCTP get_timestamp = lambda :", "self.threshold = threshold # Timeout for scan entries self.timeout =", "pcap.DLT_LOOP:dpkt.loopback.Loopback, pcap.DLT_NULL:dpkt.loopback.Loopback, pcap.DLT_EN10MB:dpkt.ethernet.Ethernet } [pc.datalink()] try: print 'listening on %s:", "a scan, check # of entries - if too many", "TH_SYN=dpkt.tcp.TH_SYN TH_FIN=dpkt.tcp.TH_FIN # Protocols TCP=dpkt.tcp.TCP UDP=dpkt.udp.UDP SCTP=dpkt.sctp.SCTP get_timestamp = lambda", "a, b, c): a -= b; a -= c; a", "scans recent1 = self.recent_scans[-1:-2:-1] for recent in recent1: if recent.type=='Idle'", "scan' detected from X to Y # See if there", "-= c; a ^= (c>>12) b -= c; b -=", "in ('', 'reply'): not_scan = True # If we see", "TCP: flags = pload.flags key = self.host_hash(src,dst) curr=time.time() # Keep", "\"pythonhacker\" __maintainer__ = \"pythonhacker\" __version__ = '0.5.1' __modified__ = 'Thu", "# with this as zombie, then ignore it... elif scan.flags_or", "self.long_scans[key] del self.scans[key] return if scan.logged: return scan.timestamp = curr", "if slow_scan: del self.long_scans[scan.hash] else: del self.scans[scan.hash] return True else:", "syn scanning it # and later we could get an", "dport in scan.ports: return # Add weight for port if", "# print 'Weight=>',lscan.weight if not self.inspect_scan(lscan, True): # Not a", "spurious and incorrect logging. Better logging functions. Licensed under GNU", "but SD is too large, # delete the entry #", "if scan.logged: return scan.timestamp = curr self.update_ports(scan, dport, flags) self.inspect_scan(scan)", "scan scan.flags_or = 0 elif scan.proto==SCTP: if scan.chunk_type==1: scan.type =", "entry if (timediff > self.timeout): # Add entry in long_scans", "duplicate scans # in the same time-period. 'n' is 60", "a scan TH_RST|TH_ACK: 'reply'} def __init__(self, timeout, threshold, maxsize, daemon=True,", "TH_ACK=dpkt.tcp.TH_ACK TH_PSH=dpkt.tcp.TH_PUSH TH_RST=dpkt.tcp.TH_RST TH_SYN=dpkt.tcp.TH_SYN TH_FIN=dpkt.tcp.TH_FIN # Protocols TCP=dpkt.tcp.TCP UDP=dpkt.udp.UDP SCTP=dpkt.sctp.SCTP", "msg) if self.scanlog: self.scanlog.write(line + '\\n') self.scanlog.flush() if not self.daemon:", "detected from X to Y # See if there was", "options, args = o.parse_args() s=ScanLogger(SCAN_TIMEOUT, WEIGHT_THRESHOLD, 8192, options.daemon, options.logfile) s.run()", "of entries - if too many # then this is", "to A # Correlation: If 'RST scan' detected from X", "does scan using RST, however this could be # return", "scan.flags_or==TH_RST: # None does scan using RST, however this could", "all-flags', TH_SYN|TH_ACK|TH_RST: 'TCP full-connect', # Not a scan TH_RST|TH_ACK: 'reply'}", "ability to log slow port-scans. Features 1. Detects all stealth", "B->A for full-connect scan from A->B elif (recent.type == 'reply'", "break # If this is a syn scan, see if", "= timerlist.TimerList(12, 60.0) def hash_func(self, addr): \"\"\" Hash a host", "in recent1: # Was not a scan, skip if not", "%.2fs' else: tup = [scan.type, srcip,dstip, ports] if not slow_scan:", "and wait for it if self.daemon: print 'Daemonizing...' self.run_daemon() else:", "# host when a scanning host is doing an idle", "def log(self, msg): \"\"\" Log a message to console and/or", "-= c; b -= a; b ^= (a<<8) c -=", "scan occurs at most every 5 seconds, this would be", "however this could be # return packets from a zombie", "then ignore it... elif scan.flags_or == TH_SYN and len(self.recent_scans): #", "not larger # than longscan timeout prev = self.scans[key].timestamp if", "len(scan.timediffs)>=4 and (scan.weight < self.threshold_l)) not_scan = False if is_scan", "# If dameon, then create a new thread and wait", "^= (c>>3) b -= c; b -= a; b ^=", "help=\"Daemonize\", action=\"store_true\", default=False) o.add_option(\"-f\", \"--logfile\", dest=\"logfile\", help=\"File to save logs", "msg): \"\"\" Log a message to console and/or log file", "line = 'Slow %s scan (flags:%d) from %s to %s", "= [scan.type,scan.flags_or,srcip,dstip, ports] if not slow_scan: if scan.type != 'Idle':", "scan.ports: return # Add weight for port if dport <", "scan.ports.append(dport) def inspect_scan(self, scan, slow_scan=False): # Sure scan is_scan =", "-= b; a -= c; a ^= (c>>13) b -=", "os.geteuid() != 0: sys.exit(\"You must be super-user to run this", "class ScanLogger(object): \"\"\" Port scan detector/logger \"\"\" # TCP flags", "Port scan detector/logger tool, inspired by scanlogd {http://www.openwall.com/scanlogd} but with", "slow scan # update port weights... # print 'Weight=>',lscan.weight if", "- prev) lscan.flags_or |= flags lscan.ports.append(dport) lscan.proto = proto self.long_scans[key]", "b -= c; b -= a; b ^= (a<<16) c", "x-mas', TH_SYN|TH_FIN: 'TCP syn/fin', TH_FIN|TH_ACK: 'TCP fin/ack', TH_SYN|TH_ACK: 'TCP full-connect',", "type mapping scan_types = {0: 'TCP null', TH_FIN: 'TCP fin',", "in (TCP, UDP, SCTP): return pload = ip.data src,dst,dport,flags =", "pkt): if not hasattr(pkt, 'ip'): return ip = pkt.ip #", "if not self.inspect_scan(lscan, True): # Not a scan, check #", "c): a -= b; a -= c; a ^= (c>>13)", "out in 60 seconds, max size is equal # to", "= curr lscan.timediffs.append(curr - prev) lscan.flags_or |= flags lscan.ports.append(dport) lscan.proto", "host %s' else: tup.append(scan.time_avg) if unsure: line = 'Possible slow", "if scan.flags_or==TH_RST: # None does scan using RST, however this", "packets in reverse direction or invalid protocol return timediff =", "flags): scan.flags_or |= flags if dport in scan.ports: return #", "from %s to %s (ports:%s), average timediff %.2fs' msg =", "regular network activity # but not a scan, so remove", "zombie, then ignore it... elif scan.flags_or == TH_SYN and len(self.recent_scans):", "#1 failed\", e sys.exit(1) os.setsid() os.umask(0) # Second fork try:", "= rscan.src scan.type = 'Idle' scan.ports = idle_ports # for", "functions. Licensed under GNU GPL v3.0. \"\"\" import sys, os", "slow_scan=False): # Sure scan is_scan = ((slow_scan and scan.weight >=", "the same time-period. 'n' is 60 sec by default. #", "3 else: scan.weight += 1 scan.ports.append(dport) def inspect_scan(self, scan, slow_scan=False):", "Cleaned up code to publish to google. Apr 8 2010", "b; a -= c; a ^= (c>>12) b -= c;", "'Idle' scan.ports = idle_ports # for d in dummy_scans: #", "# Add new entry scan = entry.ScanEntry(key) scan.src = src", "OSError, e: print >>sys.stderr, \"fork #1 failed\", e sys.exit(1) os.setsid()", "\"\"\" value = addr h = 0 while value: #", "Update only if not too old, else skip and remove", "import time import threading import optparse import entry import timerlist", "detector/logger \"\"\" # TCP flags to scan type mapping scan_types", "len(lscan.timediffs)>=10: # print lscan.src, lscan.timediffs, lscan.time_sd print 'Removing',key,lscan.src,'since not a", "except OSError, e: print >>sys.stderr, \"fork #2 failed\", e sys.exit(1)", "from A->B, make sure that # there was no recent", "scan.type = 'SCTP COOKIE_ECHO' # See if this was logged", "return False def process(self, pkt): if not hasattr(pkt, 'ip'): return", "# Keep dropping old entries self.recent_scans.collect() if key in self.scans:", "except (IOError, OSError), (errno, strerror): print >> sys.stderr, \"Error opening", "syn', TH_SYN|TH_RST: 'TCP syn', TH_ACK: 'TCP ack', TH_URG|TH_PSH|TH_FIN: 'TCP x-mas',", "time out in 60 seconds, max size is equal #", "= 'Thu Apr 8 19:21:11 IST 2010' # UDP -", "should be ignored. if scan.flags_or == (TH_SYN|TH_ACK|TH_RST) and len(self.recent_scans): recent1", "#2 failed\", e sys.exit(1) self.loop() def run(self): # If dameon,", "skip if not recent.is_scan: continue if recent.type == 'TCP full-connect'", "== recent.dst) and (scan.dst == recent.src)): # Spurious self.log(\"Ignoring spurious", "scan.proto = proto self.scans[key] = scan def loop(self): pc =", "c -= a; c -= b; c ^= (b>>13) a", "a regular network activity # but not a scan, so", "dummy_scans.append(item) if idle_scan: scan.src = scan.dst scan.dst = rscan.dst scan.zombie", "in recent1: if recent.type=='Idle' and scan.src==recent.zombie: self.log('Ignoring mis-interpreted syn scan", "in 60 sec - assuming # a scan occurs at", "curr self.update_ports(scan, dport, flags) self.inspect_scan(scan) else: # Add new entry", "tup.append(ip2quad(scan.zombie)) line = 'Continuation of %s scan from %s to", "= 'SCTP COOKIE_ECHO' # See if this was logged recently", "than 2, possible slow scan # update port weights... #", "to Y # See if there was a SYN scan", "to C as if B is syn scanning it #", "ndrop, nifdrop = pc.stats() print '\\n%d packets received by filter'", "2. Detects Idle scan and logs it correctly using correlation!", "= pload.flags key = self.host_hash(src,dst) curr=time.time() # Keep dropping old", "self.recent_scans[-1:-2:-1] for recent in recent1: if recent.type=='Idle' and scan.src==recent.zombie: self.log('Ignoring", "nifdrop = pc.stats() print '\\n%d packets received by filter' %", "%s (ports: %s) using zombie host %s' else: tup.append(scan.time_avg) line", "host # B - zombie host # C - target", "nrecv, ndrop, nifdrop = pc.stats() print '\\n%d packets received by", "= { pcap.DLT_LOOP:dpkt.loopback.Loopback, pcap.DLT_NULL:dpkt.loopback.Loopback, pcap.DLT_EN10MB:dpkt.ethernet.Ethernet } [pc.datalink()] try: print 'listening", "reversed(self.recent_scans): rscan = item[1] if rscan.src==scan.src and rscan.flags_or==TH_SYN and ((rscan.timestamp", "logged recently scanentry = entry.RecentScanEntry(scan, not not_scan) if scanentry not", "scan.weight >= self.threshold_l) or (not slow_scan and scan.weight >= self.threshold))", "scan # update port weights... # print 'Weight=>',lscan.weight if not", "print >> sys.stderr, \"Error opening scan log file %s =>", "%s to %s (ports:%s)' else: tup.append(ip2quad(scan.zombie)) line = '%s scan", "scan.logged = True if scan.proto==TCP: idle_scan = False if scan.flags_or==TH_RST:", "strerror) self.scanlog = None # Recent scans - this list", "pc: self.process(decode(pkt)) except KeyboardInterrupt: if not self.daemon: nrecv, ndrop, nifdrop", "-= a; b ^= (a<<8) c -= a; c -=", "# and later we could get an apparent RST \"scan\"", "def run_daemon(self): # Disconnect from tty try: pid = os.fork()", "len(lscan.timediffs)>2: # More than 2 entries, but SD is too", "%s (ports:%s), average timediff %.2fs' else: tup = [scan.type, srcip,dstip,", "TCP=dpkt.tcp.TCP UDP=dpkt.udp.UDP SCTP=dpkt.sctp.SCTP get_timestamp = lambda : time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())", "TH_PSH=dpkt.tcp.TH_PUSH TH_RST=dpkt.tcp.TH_RST TH_SYN=dpkt.tcp.TH_SYN TH_FIN=dpkt.tcp.TH_FIN # Protocols TCP=dpkt.tcp.TCP UDP=dpkt.udp.UDP SCTP=dpkt.sctp.SCTP get_timestamp", "if scan.src != src: # Skip packets in reverse direction", "[scan.type,scan.flags_or,srcip,dstip, ports] if not slow_scan: if scan.type != 'Idle': line", "scan.timestamp # Update only if not too old, else skip", "None # Recent scans - this list allows to keep", "self.log_scan(scan, continuation=continuation, slow_scan=slow_scan, unsure=maybe_scan) # Remove entry if slow_scan: del", "there was no recent full-connect scan from B->A, if #", "scan from %s\" % ' to '.join(scan_ip2quad(scan))) not_scan = True", "lscan else: lscan = self.long_scans[key] lscan.timestamp = curr lscan.flags_or |=", "del self.long_scans[key] elif len(lscan.timediffs)>2: # More than 2 entries, but", "WEIGHT_THRESHOLD = 25 PIDFILE=\"/var/run/pyscanlogger.pid\" # TCP flag constants TH_URG=dpkt.tcp.TH_URG TH_ACK=dpkt.tcp.TH_ACK", "== TCP: flags = pload.flags key = self.host_hash(src,dst) curr=time.time() #", "incorrect logging. Better logging functions. Licensed under GNU GPL v3.0.", "if os.geteuid() != 0: sys.exit(\"You must be super-user to run", "# then this is a regular network activity # but", "e: print >>sys.stderr, \"fork #1 failed\", e sys.exit(1) os.setsid() os.umask(0)", "25 PIDFILE=\"/var/run/pyscanlogger.pid\" # TCP flag constants TH_URG=dpkt.tcp.TH_URG TH_ACK=dpkt.tcp.TH_ACK TH_PSH=dpkt.tcp.TH_PUSH TH_RST=dpkt.tcp.TH_RST", "is_scan or maybe_scan: scan.logged = True if scan.proto==TCP: idle_scan =", "self.recent_scans: continuation=False self.recent_scans.append(scanentry) else: continuation=True if not not_scan: self.log_scan(scan, continuation=continuation,", "timeout prev = self.scans[key].timestamp if timediff<=self.timeout_l: if key not in", "s=ScanLogger(SCAN_TIMEOUT, WEIGHT_THRESHOLD, 8192, options.daemon, options.logfile) s.run() if __name__ == '__main__':", "socket import time import threading import optparse import entry import", "+= 3 else: scan.weight += 1 scan.ports.append(dport) def inspect_scan(self, scan,", "spurious and should be ignored. if scan.flags_or == (TH_SYN|TH_ACK|TH_RST) and", "type(pload) if proto == TCP: flags = pload.flags key =", "print >> sys.stderr, 'Scan logs will be saved to %s'", "protocol return timediff = curr - scan.timestamp # Update only", "scan.flags_or |= flags if proto==SCTP: scan.chunk_type = pload.chunks[0].type scan.ports.append(dport) scan.proto", "to host Z. Then actually Y is idle scanning #", "c; b -= a; b ^= (a<<16) c -= a;", "lscan.update_time_sd() self.update_ports(lscan, dport, flags) if lscan.time_sd<2: # SD is less", "scanentry = entry.RecentScanEntry(scan, not not_scan) if scanentry not in self.recent_scans:", "ip = pkt.ip # Ignore non-tcp, non-udp packets if type(ip.data)", "'TCP full-connect' break elif scan.proto==UDP: scan.type = 'UDP' # Reset", "console \"\"\" srcip, dstip = scan_ip2quad(scan) ports = ','.join([str(port) for", "in dummy_scans: # self.recent_scans.remove(d) else: # Remove entry if slow_scan:", "del self.long_scans[key] else: # Too large timeout, remove key del", "# Protocols TCP=dpkt.tcp.TCP UDP=dpkt.udp.UDP SCTP=dpkt.sctp.SCTP get_timestamp = lambda : time.strftime('%Y-%m-%d", "see scan flags 22 from A->B, make sure that #", "full-connect scans. 2. Detects Idle scan and logs it correctly", ">>sys.stderr, \"fork #1 failed\", e sys.exit(1) os.setsid() os.umask(0) # Second", "'Continuation of %s scan from %s to %s (ports: %s)", "scan.dst scan.dst = rscan.dst scan.zombie = rscan.src scan.type = 'Idle'", "Y # See if there was a SYN scan recently", "c -= a; c -= b; c ^= (b>>15) return", "\"Error opening scan log file %s => %s\" % (logfile,", "upto last 'n' seconds, so as to not call duplicate", "except KeyboardInterrupt: if not self.daemon: nrecv, ndrop, nifdrop = pc.stats()", "(not slow_scan and scan.weight >= self.threshold)) # Possible scan maybe_scan", "5 WEIGHT_THRESHOLD = 25 PIDFILE=\"/var/run/pyscanlogger.pid\" # TCP flag constants TH_URG=dpkt.tcp.TH_URG", "TH_FIN|TH_ACK: 'TCP fin/ack', TH_SYN|TH_ACK: 'TCP full-connect', TH_URG|TH_PSH|TH_ACK|TH_RST|TH_SYN|TH_FIN: 'TCP all-flags', TH_SYN|TH_ACK|TH_RST:", "b -= c; b -= a; b ^= (a<<10) c", "else skip and remove entry if (timediff > self.timeout): #", "= src scan.dst = dst scan.timestamp = curr scan.flags_or |=", "host %s' % ' to '.join(scan_ip2quad(scan))) break # Reply from", "packets received by filter' % nrecv print '%d packets dropped", "run this program\") o=optparse.OptionParser() o.add_option(\"-d\", \"--daemonize\", dest=\"daemon\", help=\"Daemonize\", action=\"store_true\", default=False)", "zombie host # C - target host # If A", "full-connect scan from A->B elif (recent.type == 'reply' and ((scan.src", "= self.threshold/2 # Daemonize ? self.daemon = daemon # Log", "scan.type = 'Idle' scan.ports = idle_ports # for d in", "def run(self): # If dameon, then create a new thread", "[] for item in reversed(self.recent_scans): rscan = item[1] if rscan.src==scan.src", "with B as zombie, # it will appear to C", "slow %s scan from %s to %s (ports:%s), average timediff", "(timediff > self.timeout): # Add entry in long_scans if timediff", "'n' seconds, so as to not call duplicate scans #", "map(ip2quad, [scan.src, scan.dst]) class ScanLogger(object): \"\"\" Port scan detector/logger \"\"\"", "idle_scan: scan.src = scan.dst scan.dst = rscan.dst scan.zombie = rscan.src", "RST \"scan\" # from B to A # Correlation: If", "22 from A->B, make sure that # there was no", "\"\"\" Port scan detector/logger \"\"\" # TCP flags to scan", "elif scan.proto==SCTP: if scan.chunk_type==1: scan.type = 'SCTP Init' elif scan.chunk_type==10:", "'%d packets dropped by kernel' % ndrop def run_daemon(self): #", "c ^= (b>>15) return abs(c) def host_hash(self, src, dst): \"\"\"", "else: # Remove entry if slow_scan: del self.long_scans[scan.hash] else: del", "'Idle': line = 'Continuation of %s scan from %s to", "Add weight for port if dport < 1024: scan.weight +=", "True else: return False def process(self, pkt): if not hasattr(pkt,", "= curr scan.flags_or |= flags if proto==SCTP: scan.chunk_type = pload.chunks[0].type", "return pload = ip.data src,dst,dport,flags = int(struct.unpack('I',ip.src)[0]),int(struct.unpack('I', ip.dst)[0]),int(pload.dport),0 proto =", "not self.daemon: print >> sys.stderr, line def log_scan(self, scan, continuation=False,", "TCP flag constants TH_URG=dpkt.tcp.TH_URG TH_ACK=dpkt.tcp.TH_ACK TH_PSH=dpkt.tcp.TH_PUSH TH_RST=dpkt.tcp.TH_RST TH_SYN=dpkt.tcp.TH_SYN TH_FIN=dpkt.tcp.TH_FIN #", "self.scanlog: self.scanlog.write(line + '\\n') self.scanlog.flush() if not self.daemon: print >>", "mis-interpreted syn scan from zombie host %s' % ' to", "a message to console and/or log file \"\"\" line =", "' to '.join(scan_ip2quad(scan))) break # Reply from B->A for full-connect", "not hasattr(pkt, 'ip'): return ip = pkt.ip # Ignore non-tcp,", "'UDP' # Reset flags for UDP scan scan.flags_or = 0", "not in self.long_scans: lscan = entry.ScanEntry(key) lscan.src = src lscan.dst", "b -= a; b ^= (a<<10) c -= a; c", "null', TH_FIN: 'TCP fin', TH_SYN: 'TCP syn', TH_SYN|TH_RST: 'TCP syn',", "a SYN scan recently from host # X to host", "scan.type in ('', 'reply'): not_scan = True # If we", "lscan.src, lscan.timediffs, lscan.time_sd print 'Removing',key,lscan.src,'since not a scan' del self.long_scans[key]", "timerlist __author__ = \"pythonhacker\" __maintainer__ = \"pythonhacker\" __version__ = '0.5.1'", "a; c -= b; c ^= (b>>15) return abs(c) def", "we could get an apparent RST \"scan\" # from B" ]
[ "b): return (a > b) - (a < b) def", "visited[i] = True miggroup.append([i]) cnt += 1 for j in", "= dist closetd = i return closetd def get_domains_on_2sides(target1, target2,", "tup[0]) if not visited[i]: visited[i] = True miggroup.append([i]) cnt +=", "sort_by_strand(val): return val[0][0] def check_edge_in_tuplelist(edge, tpl): for i in tpl:", "2)) combself = [(i, i) for i in range(0, oldlen)]", ":param domain2: :return: \"\"\" return abs(domain1[1] - domain2[1]) def get_closet_domain_to_target(target,", "x t += 1 return v, n def sort_e_by_domain(val): return", "1 == t2[1][1]): visited[j] = True miggroup[cnt].append(j) break return miggroup", "= -1 for i in range(0, len(e)): if visited[i]: continue", "target: :param domains: :return: \"\"\" closet = 10000 closetd =", "t2[1][1]) \\ or (t1[0][1] - 1 == t2[0][1] and t1[1][1]", "oldlen)] combnew = [] if oldlen != newlen: for i", "def get_closest_target(domains, targets): \"\"\" :return: \"\"\" domains = sorted(domains, key=lambda", "= () for i in domains: dist = get_absdist(i, target)", "def get_free_domains(limits, blocks, bound): limits = sorted(limits) interval = limits[1]", "oldlen != newlen: for i in range(0, oldlen): for j", "in indices: vi, ni = get_edge_info(edges[i][0]) if vi[0] == startstrand:", "blocks, bound): limits = sorted(limits) interval = limits[1] - limits[0]", "\"\"\" e = copy.copy(edges) visited = [False for _ in", "cnt += 1 for j in range(0, len(e)): if j", "if oldlen != newlen: for i in range(0, oldlen): for", "and t1[1][1] - 1 == t2[1][1]) \\ or (t1[0][1] -", "= abs(bound - i) if tmp < interval: interval =", "sorted(domains, key=lambda tup: tup[1]) mindist = 10000 mint = None", "domains1[0][0]: closetd1 = get_closet_domain_to_target(target2, domains1) if target1[0] == domains2[0][0]: closetd2", "d = [] for i in indices: vi, ni =", ":param domains2: :return: \"\"\" if target1[0] == domains1[0][0]: closetd1 =", "return 0 else: return 1 def get_edge_info(e): v = [0", "= [(i, i) for i in range(0, oldlen)] combnew =", "== 0: i = 1 elif i == 1: i", "combinations import copy def get_reverse(n): if n == 1: return", "0 else: return 1 def get_edge_info(e): v = [0 for", "= 1 elif i == 1: i = 0 return", "targets): \"\"\" :return: \"\"\" domains = sorted(domains, key=lambda tup: tup[1])", "d def check_following_migration(edges, p=0): \"\"\" :param edges: :return: \"\"\" e", "1 for j in range(0, len(e)): if j != i", "flip(i): if i == 0: i = 1 elif i", "for i in blocks: if limits[1] > i > limits[0]:", ":return: \"\"\" if target1[0] == domains1[0][0]: closetd1 = get_closet_domain_to_target(target1, domains1)", "None for t in targets: dist = min(get_absdist(t, domains[0]), get_absdist(t,", "in range(0, oldlen)] combnew = [] if oldlen != newlen:", "== domains1[0][0]: closetd1 = get_closet_domain_to_target(target1, domains1) elif target2[0] == domains1[0][0]:", "get_closet_domain_to_target(target1, domains2) elif target2[0] == domains2[0][0]: closetd2 = get_closet_domain_to_target(target2, domains2)", "visited[i]: continue e[i] = list(e[i]) e[i][p] = list(e[i][p]) t1 =", "if dist < closet: closet = dist closetd = i", "def get_domains_on_2sides(target1, target2, domains1, domains2): \"\"\" :param target1: :param target2:", "target2[0] == domains2[0][0]: closetd2 = get_closet_domain_to_target(target2, domains2) return closetd1, closetd2", "return abs(domain1[1] - domain2[1]) def get_closet_domain_to_target(target, domains): \"\"\" :param target:", "range(2)] t = 0 for x in e: v[t], n[t]", "= 10000 closetd = () for i in domains: dist", "return val[0][0] def check_edge_in_tuplelist(edge, tpl): for i in tpl: if", "or i - 1 == j: return i, j return", "elif i == 1: i = 0 return i def", "if (t2[0][0] != t1[0][0]) or (t2[1][0] != t1[1][0]): continue for", "in targets: dist = min(get_absdist(t, domains[0]), get_absdist(t, domains[len(domains) - 1]))", "return i, j return None def check_bond_existence(d1, d2, l1, l2):", "domains1) if target1[0] == domains2[0][0]: closetd2 = get_closet_domain_to_target(target1, domains2) elif", "key=lambda tup: tup[0]) if (t1[0][1] + 1 == t2[0][1] and", "d.append(ni[0]) else: d.append(ni[1]) d.sort() return d def check_following_migration(edges, p=0): \"\"\"", "for j in b: if i + 1 == j", "\"\"\" if target1[0] == domains1[0][0]: closetd1 = get_closet_domain_to_target(target1, domains1) elif", "= get_absdist(i, target) if dist < closet: closet = dist", "for i in range(0, oldlen): for j in range(oldlen, newlen):", "== domains2[0][0]: closetd2 = get_closet_domain_to_target(target1, domains2) elif target2[0] == domains2[0][0]:", "\"\"\" return abs(domain1[1] - domain2[1]) def get_closet_domain_to_target(target, domains): \"\"\" :param", "a: for j in b: if i + 1 ==", "domains2: :return: \"\"\" if target1[0] == domains1[0][0]: closetd1 = get_closet_domain_to_target(target1,", "= list(e[j]) e[j][p] = list(e[j][p]) t2 = sorted(e[j][p], key=lambda tup:", "== domains2[0][0]: closetd2 = get_closet_domain_to_target(target2, domains2) return closetd1, closetd2 def", "i in range(len(l1)): if d1 == l1[i] and d2 ==", "= [] if oldlen != newlen: for i in range(0,", "j)) return combold + combnew + combself def get_migrate_nodes(edges, indices,", "_ in e] miggroup = [] cnt = -1 for", "1 return v, n def sort_e_by_domain(val): return val[0][1] def sort_by_strand(val):", "= list(e[j][p]) t2 = sorted(e[j][p], key=lambda tup: tup[0]) if (t2[0][0]", "copy def get_reverse(n): if n == 1: return 0 else:", "< mindist: mint = t return mint def check_continuity(a, b):", "= list(e[i][p]) t1 = sorted(e[i][p], key=lambda tup: tup[0]) if not", "return (a > b) - (a < b) def flip(i):", "i = 1 elif i == 1: i = 0", "domains: :return: \"\"\" closet = 10000 closetd = () for", "from itertools import combinations import copy def get_reverse(n): if n", "in i: return True return False def compare(a, b): return", "= [False for _ in e] miggroup = [] cnt", "def sort_by_strand(val): return val[0][0] def check_edge_in_tuplelist(edge, tpl): for i in", "key=lambda tup: tup[0]) if not visited[i]: visited[i] = True miggroup.append([i])", "return 1 def get_edge_info(e): v = [0 for i in", "v[t], n[t] = x t += 1 return v, n", "cnt = -1 for i in range(0, len(e)): if visited[i]:", "def check_edge_in_tuplelist(edge, tpl): for i in tpl: if edge in", "(t2[0][0] != t1[0][0]) or (t2[1][0] != t1[1][0]): continue for num", "in range(0, len(e)): if visited[i]: continue e[i] = list(e[i]) e[i][p]", "combold = list(combinations(indexlist[cursor:oldlen], 2)) combself = [(i, i) for i", "b): for i in a: for j in b: if", "return interval def get_combinations(oldlen, newlen, cursor, indexlist): combold = list(combinations(indexlist[cursor:oldlen],", "miggroup = [] cnt = -1 for i in range(0,", "domains2) return closetd1, closetd2 def get_closest_target(domains, targets): \"\"\" :return: \"\"\"", "e[i][p] = list(e[i][p]) t1 = sorted(e[i][p], key=lambda tup: tup[0]) if", "i in a: for j in b: if i +", "= sorted(limits) interval = limits[1] - limits[0] for i in", "closetd1, closetd2 def get_closest_target(domains, targets): \"\"\" :return: \"\"\" domains =", "else: d.append(ni[1]) d.sort() return d def check_following_migration(edges, p=0): \"\"\" :param", "edges: :return: \"\"\" e = copy.copy(edges) visited = [False for", "range(2)] n = [0 for i in range(2)] t =", "t = 0 for x in e: v[t], n[t] =", "0 return i def get_free_domains(limits, blocks, bound): limits = sorted(limits)", "return combold + combnew + combself def get_migrate_nodes(edges, indices, startstrand):", "+ 1 == j or i - 1 == j:", "1 == t2[1][1]) \\ or (t1[0][1] - 1 == t2[0][1]", "and not visited[j]: e[j] = list(e[j]) e[j][p] = list(e[j][p]) t2", "in range(0, len(e)): if j != i and not visited[j]:", "val[0][0] def check_edge_in_tuplelist(edge, tpl): for i in tpl: if edge", "for i in range(2)] t = 0 for x in", "\"\"\" :param domain1: :param domain2: :return: \"\"\" return abs(domain1[1] -", "domain2[1]) def get_closet_domain_to_target(target, domains): \"\"\" :param target: :param domains: :return:", "sorted(e[miggroup[cnt][num]][p], key=lambda tup: tup[0]) if (t1[0][1] + 1 == t2[0][1]", "i in tpl: if edge in i: return True return", "tmp return interval def get_combinations(oldlen, newlen, cursor, indexlist): combold =", "for i in range(len(l1)): if d1 == l1[i] and d2", "target) if dist < closet: closet = dist closetd =", "else: return 1 def get_edge_info(e): v = [0 for i", "tpl): for i in tpl: if edge in i: return", "abs(domain1[1] - domain2[1]) def get_closet_domain_to_target(target, domains): \"\"\" :param target: :param", "get_closet_domain_to_target(target2, domains2) return closetd1, closetd2 def get_closest_target(domains, targets): \"\"\" :return:", "= None for t in targets: dist = min(get_absdist(t, domains[0]),", "j: return i, j return None def check_bond_existence(d1, d2, l1,", "= list(e[i]) e[i][p] = list(e[i][p]) t1 = sorted(e[i][p], key=lambda tup:", "key=lambda tup: tup[0]) if (t2[0][0] != t1[0][0]) or (t2[1][0] !=", "= 0 return i def get_free_domains(limits, blocks, bound): limits =", "in range(2)] n = [0 for i in range(2)] t", "t2[1][1]): visited[j] = True miggroup[cnt].append(j) break return miggroup def get_absdist(domain1,", "t1 = sorted(e[miggroup[cnt][num]][p], key=lambda tup: tup[0]) if (t1[0][1] + 1", "domains1) elif target2[0] == domains1[0][0]: closetd1 = get_closet_domain_to_target(target2, domains1) if", "domains2) elif target2[0] == domains2[0][0]: closetd2 = get_closet_domain_to_target(target2, domains2) return", "i - 1 == j: return i, j return None", "visited[j]: e[j] = list(e[j]) e[j][p] = list(e[j][p]) t2 = sorted(e[j][p],", "return d def check_following_migration(edges, p=0): \"\"\" :param edges: :return: \"\"\"", "\"\"\" domains = sorted(domains, key=lambda tup: tup[1]) mindist = 10000", "closetd2 def get_closest_target(domains, targets): \"\"\" :return: \"\"\" domains = sorted(domains,", "range(0, len(e)): if visited[i]: continue e[i] = list(e[i]) e[i][p] =", "domains[len(domains) - 1])) if dist < mindist: mint = t", "t1[1][1] + 1 == t2[1][1]): visited[j] = True miggroup[cnt].append(j) break", "= get_closet_domain_to_target(target1, domains1) elif target2[0] == domains1[0][0]: closetd1 = get_closet_domain_to_target(target2,", "1: i = 0 return i def get_free_domains(limits, blocks, bound):", "tup: tup[0]) if (t1[0][1] + 1 == t2[0][1] and t1[1][1]", "(a > b) - (a < b) def flip(i): if", "== l1[i] and d2 == l2[i]: return True return False", "break return miggroup def get_absdist(domain1, domain2): \"\"\" :param domain1: :param", "if (t1[0][1] + 1 == t2[0][1] and t1[1][1] - 1", "continue e[i] = list(e[i]) e[i][p] = list(e[i][p]) t1 = sorted(e[i][p],", "tup: tup[1]) mindist = 10000 mint = None for t", "True miggroup[cnt].append(j) break return miggroup def get_absdist(domain1, domain2): \"\"\" :param", "get_edge_info(e): v = [0 for i in range(2)] n =", "compare(a, b): return (a > b) - (a < b)", "for i in a: for j in b: if i", "> b) - (a < b) def flip(i): if i", "vi, ni = get_edge_info(edges[i][0]) if vi[0] == startstrand: d.append(ni[0]) else:", "= t return mint def check_continuity(a, b): for i in", "i == 1: i = 0 return i def get_free_domains(limits,", "mindist = 10000 mint = None for t in targets:", "for j in range(oldlen, newlen): combnew.append((i, j)) return combold +", "d.sort() return d def check_following_migration(edges, p=0): \"\"\" :param edges: :return:", "(t1[0][1] - 1 == t2[0][1] and t1[1][1] + 1 ==", "1 == t2[0][1] and t1[1][1] - 1 == t2[1][1]) \\", "< closet: closet = dist closetd = i return closetd", "domains1: :param domains2: :return: \"\"\" if target1[0] == domains1[0][0]: closetd1", "num in range(0, len(miggroup[cnt])): t1 = sorted(e[miggroup[cnt][num]][p], key=lambda tup: tup[0])", "return i def get_free_domains(limits, blocks, bound): limits = sorted(limits) interval", "not visited[i]: visited[i] = True miggroup.append([i]) cnt += 1 for", "() for i in domains: dist = get_absdist(i, target) if", "get_closet_domain_to_target(target2, domains1) if target1[0] == domains2[0][0]: closetd2 = get_closet_domain_to_target(target1, domains2)", "t1[1][0]): continue for num in range(0, len(miggroup[cnt])): t1 = sorted(e[miggroup[cnt][num]][p],", "visited[i]: visited[i] = True miggroup.append([i]) cnt += 1 for j", "target2, domains1, domains2): \"\"\" :param target1: :param target2: :param domains1:", "in blocks: if limits[1] > i > limits[0]: tmp =", "get_free_domains(limits, blocks, bound): limits = sorted(limits) interval = limits[1] -", "in e] miggroup = [] cnt = -1 for i", "list(e[i][p]) t1 = sorted(e[i][p], key=lambda tup: tup[0]) if not visited[i]:", "d2, l1, l2): for i in range(len(l1)): if d1 ==", "i in range(0, oldlen): for j in range(oldlen, newlen): combnew.append((i,", "domains2[0][0]: closetd2 = get_closet_domain_to_target(target1, domains2) elif target2[0] == domains2[0][0]: closetd2", "== 1: i = 0 return i def get_free_domains(limits, blocks,", "limits[0]: tmp = abs(bound - i) if tmp < interval:", "domain1: :param domain2: :return: \"\"\" return abs(domain1[1] - domain2[1]) def", "vi[0] == startstrand: d.append(ni[0]) else: d.append(ni[1]) d.sort() return d def", "def check_following_migration(edges, p=0): \"\"\" :param edges: :return: \"\"\" e =", "get_closet_domain_to_target(target, domains): \"\"\" :param target: :param domains: :return: \"\"\" closet", "get_edge_info(edges[i][0]) if vi[0] == startstrand: d.append(ni[0]) else: d.append(ni[1]) d.sort() return", "get_closest_target(domains, targets): \"\"\" :return: \"\"\" domains = sorted(domains, key=lambda tup:", "0 for x in e: v[t], n[t] = x t", "tup: tup[0]) if (t2[0][0] != t1[0][0]) or (t2[1][0] != t1[1][0]):", "d1 == l1[i] and d2 == l2[i]: return True return", "= list(combinations(indexlist[cursor:oldlen], 2)) combself = [(i, i) for i in", "== j: return i, j return None def check_bond_existence(d1, d2,", "limits = sorted(limits) interval = limits[1] - limits[0] for i", "domains1[0][0]: closetd1 = get_closet_domain_to_target(target1, domains1) elif target2[0] == domains1[0][0]: closetd1", "t1[1][1] - 1 == t2[1][1]) \\ or (t1[0][1] - 1", "oldlen): for j in range(oldlen, newlen): combnew.append((i, j)) return combold", "return miggroup def get_absdist(domain1, domain2): \"\"\" :param domain1: :param domain2:", "dist closetd = i return closetd def get_domains_on_2sides(target1, target2, domains1,", "= 0 for x in e: v[t], n[t] = x", "list(e[j]) e[j][p] = list(e[j][p]) t2 = sorted(e[j][p], key=lambda tup: tup[0])", "\"\"\" closet = 10000 closetd = () for i in", "in b: if i + 1 == j or i", "return closetd1, closetd2 def get_closest_target(domains, targets): \"\"\" :return: \"\"\" domains", "len(e)): if j != i and not visited[j]: e[j] =", "interval: interval = tmp return interval def get_combinations(oldlen, newlen, cursor,", "closetd = i return closetd def get_domains_on_2sides(target1, target2, domains1, domains2):", "1: return 0 else: return 1 def get_edge_info(e): v =", "i > limits[0]: tmp = abs(bound - i) if tmp", "def get_edge_info(e): v = [0 for i in range(2)] n", "def check_bond_existence(d1, d2, l1, l2): for i in range(len(l1)): if", "for j in range(0, len(e)): if j != i and", "combnew = [] if oldlen != newlen: for i in", "mint = None for t in targets: dist = min(get_absdist(t,", "0: i = 1 elif i == 1: i =", "< interval: interval = tmp return interval def get_combinations(oldlen, newlen,", "in domains: dist = get_absdist(i, target) if dist < closet:", "i == 0: i = 1 elif i == 1:", "in range(0, oldlen): for j in range(oldlen, newlen): combnew.append((i, j))", "if edge in i: return True return False def compare(a,", "bound): limits = sorted(limits) interval = limits[1] - limits[0] for", "if j != i and not visited[j]: e[j] = list(e[j])", "t2[0][1] and t1[1][1] + 1 == t2[1][1]): visited[j] = True", "if not visited[i]: visited[i] = True miggroup.append([i]) cnt += 1", ":param target: :param domains: :return: \"\"\" closet = 10000 closetd", "b) - (a < b) def flip(i): if i ==", "in a: for j in b: if i + 1", "e: v[t], n[t] = x t += 1 return v,", "len(miggroup[cnt])): t1 = sorted(e[miggroup[cnt][num]][p], key=lambda tup: tup[0]) if (t1[0][1] +", "b: if i + 1 == j or i -", "1])) if dist < mindist: mint = t return mint", "def get_reverse(n): if n == 1: return 0 else: return", "list(e[i]) e[i][p] = list(e[i][p]) t1 = sorted(e[i][p], key=lambda tup: tup[0])", "[0 for i in range(2)] n = [0 for i", "closet = 10000 closetd = () for i in domains:", "\\ or (t1[0][1] - 1 == t2[0][1] and t1[1][1] +", "domains): \"\"\" :param target: :param domains: :return: \"\"\" closet =", "= True miggroup.append([i]) cnt += 1 for j in range(0,", "[] cnt = -1 for i in range(0, len(e)): if", "t += 1 return v, n def sort_e_by_domain(val): return val[0][1]", "= sorted(e[miggroup[cnt][num]][p], key=lambda tup: tup[0]) if (t1[0][1] + 1 ==", "t in targets: dist = min(get_absdist(t, domains[0]), get_absdist(t, domains[len(domains) -", "j return None def check_bond_existence(d1, d2, l1, l2): for i", "i in indices: vi, ni = get_edge_info(edges[i][0]) if vi[0] ==", "miggroup.append([i]) cnt += 1 for j in range(0, len(e)): if", "range(0, oldlen)] combnew = [] if oldlen != newlen: for", "if limits[1] > i > limits[0]: tmp = abs(bound -", "return val[0][1] def sort_by_strand(val): return val[0][0] def check_edge_in_tuplelist(edge, tpl): for", "v = [0 for i in range(2)] n = [0", "def get_absdist(domain1, domain2): \"\"\" :param domain1: :param domain2: :return: \"\"\"", "(t2[1][0] != t1[1][0]): continue for num in range(0, len(miggroup[cnt])): t1", "1 def get_edge_info(e): v = [0 for i in range(2)]", "= limits[1] - limits[0] for i in blocks: if limits[1]", "newlen, cursor, indexlist): combold = list(combinations(indexlist[cursor:oldlen], 2)) combself = [(i,", "d.append(ni[1]) d.sort() return d def check_following_migration(edges, p=0): \"\"\" :param edges:", "= [0 for i in range(2)] n = [0 for", ":param target2: :param domains1: :param domains2: :return: \"\"\" if target1[0]", "if tmp < interval: interval = tmp return interval def", "interval def get_combinations(oldlen, newlen, cursor, indexlist): combold = list(combinations(indexlist[cursor:oldlen], 2))", "return closetd def get_domains_on_2sides(target1, target2, domains1, domains2): \"\"\" :param target1:", "[0 for i in range(2)] t = 0 for x", "range(0, len(miggroup[cnt])): t1 = sorted(e[miggroup[cnt][num]][p], key=lambda tup: tup[0]) if (t1[0][1]", "i: return True return False def compare(a, b): return (a", "combnew.append((i, j)) return combold + combnew + combself def get_migrate_nodes(edges,", "sorted(e[j][p], key=lambda tup: tup[0]) if (t2[0][0] != t1[0][0]) or (t2[1][0]", "- 1 == t2[1][1]) \\ or (t1[0][1] - 1 ==", ":return: \"\"\" closet = 10000 closetd = () for i", "if target1[0] == domains1[0][0]: closetd1 = get_closet_domain_to_target(target1, domains1) elif target2[0]", "edge in i: return True return False def compare(a, b):", "sorted(e[i][p], key=lambda tup: tup[0]) if not visited[i]: visited[i] = True", "closetd1 = get_closet_domain_to_target(target2, domains1) if target1[0] == domains2[0][0]: closetd2 =", "check_bond_existence(d1, d2, l1, l2): for i in range(len(l1)): if d1", "> limits[0]: tmp = abs(bound - i) if tmp <", "tup[0]) if (t1[0][1] + 1 == t2[0][1] and t1[1][1] -", "def get_combinations(oldlen, newlen, cursor, indexlist): combold = list(combinations(indexlist[cursor:oldlen], 2)) combself", "startstrand: d.append(ni[0]) else: d.append(ni[1]) d.sort() return d def check_following_migration(edges, p=0):", "j in b: if i + 1 == j or", "for _ in e] miggroup = [] cnt = -1", "closetd def get_domains_on_2sides(target1, target2, domains1, domains2): \"\"\" :param target1: :param", "target1[0] == domains2[0][0]: closetd2 = get_closet_domain_to_target(target1, domains2) elif target2[0] ==", "- 1 == j: return i, j return None def", "= get_edge_info(edges[i][0]) if vi[0] == startstrand: d.append(ni[0]) else: d.append(ni[1]) d.sort()", "- 1])) if dist < mindist: mint = t return", "e[j][p] = list(e[j][p]) t2 = sorted(e[j][p], key=lambda tup: tup[0]) if", "= [0 for i in range(2)] t = 0 for", "== startstrand: d.append(ni[0]) else: d.append(ni[1]) d.sort() return d def check_following_migration(edges,", "for i in indices: vi, ni = get_edge_info(edges[i][0]) if vi[0]", "e[j] = list(e[j]) e[j][p] = list(e[j][p]) t2 = sorted(e[j][p], key=lambda", "i in range(0, len(e)): if visited[i]: continue e[i] = list(e[i])", "\"\"\" :param target1: :param target2: :param domains1: :param domains2: :return:", "t1[0][0]) or (t2[1][0] != t1[1][0]): continue for num in range(0,", "copy.copy(edges) visited = [False for _ in e] miggroup =", "== domains1[0][0]: closetd1 = get_closet_domain_to_target(target2, domains1) if target1[0] == domains2[0][0]:", "= get_closet_domain_to_target(target1, domains2) elif target2[0] == domains2[0][0]: closetd2 = get_closet_domain_to_target(target2,", "i def get_free_domains(limits, blocks, bound): limits = sorted(limits) interval =", "val[0][1] def sort_by_strand(val): return val[0][0] def check_edge_in_tuplelist(edge, tpl): for i", "in range(2)] t = 0 for x in e: v[t],", "range(oldlen, newlen): combnew.append((i, j)) return combold + combnew + combself", "if i + 1 == j or i - 1", "if i == 0: i = 1 elif i ==", "(a < b) def flip(i): if i == 0: i", "1 == j or i - 1 == j: return", "= tmp return interval def get_combinations(oldlen, newlen, cursor, indexlist): combold", "if vi[0] == startstrand: d.append(ni[0]) else: d.append(ni[1]) d.sort() return d", "l2): for i in range(len(l1)): if d1 == l1[i] and", "n[t] = x t += 1 return v, n def", "domain2: :return: \"\"\" return abs(domain1[1] - domain2[1]) def get_closet_domain_to_target(target, domains):", "= [] for i in indices: vi, ni = get_edge_info(edges[i][0])", "get_reverse(n): if n == 1: return 0 else: return 1", "- (a < b) def flip(i): if i == 0:", "i) if tmp < interval: interval = tmp return interval", "list(e[j][p]) t2 = sorted(e[j][p], key=lambda tup: tup[0]) if (t2[0][0] !=", "i in domains: dist = get_absdist(i, target) if dist <", "== j or i - 1 == j: return i,", "for num in range(0, len(miggroup[cnt])): t1 = sorted(e[miggroup[cnt][num]][p], key=lambda tup:", "in e: v[t], n[t] = x t += 1 return", "domains: dist = get_absdist(i, target) if dist < closet: closet", "abs(bound - i) if tmp < interval: interval = tmp", "i return closetd def get_domains_on_2sides(target1, target2, domains1, domains2): \"\"\" :param", "1 == t2[0][1] and t1[1][1] + 1 == t2[1][1]): visited[j]", "== t2[0][1] and t1[1][1] + 1 == t2[1][1]): visited[j] =", "!= t1[0][0]) or (t2[1][0] != t1[1][0]): continue for num in", "indices, startstrand): d = [] for i in indices: vi,", "\"\"\" :return: \"\"\" domains = sorted(domains, key=lambda tup: tup[1]) mindist", "range(0, len(e)): if j != i and not visited[j]: e[j]", "mint def check_continuity(a, b): for i in a: for j", "i in blocks: if limits[1] > i > limits[0]: tmp", "i in range(2)] n = [0 for i in range(2)]", "visited[j] = True miggroup[cnt].append(j) break return miggroup def get_absdist(domain1, domain2):", "itertools import combinations import copy def get_reverse(n): if n ==", "def sort_e_by_domain(val): return val[0][1] def sort_by_strand(val): return val[0][0] def check_edge_in_tuplelist(edge,", ":return: \"\"\" return abs(domain1[1] - domain2[1]) def get_closet_domain_to_target(target, domains): \"\"\"", "in range(oldlen, newlen): combnew.append((i, j)) return combold + combnew +", "mindist: mint = t return mint def check_continuity(a, b): for", "get_migrate_nodes(edges, indices, startstrand): d = [] for i in indices:", "elif target2[0] == domains2[0][0]: closetd2 = get_closet_domain_to_target(target2, domains2) return closetd1,", "= min(get_absdist(t, domains[0]), get_absdist(t, domains[len(domains) - 1])) if dist <", "domains[0]), get_absdist(t, domains[len(domains) - 1])) if dist < mindist: mint", "== t2[1][1]): visited[j] = True miggroup[cnt].append(j) break return miggroup def", "def get_closet_domain_to_target(target, domains): \"\"\" :param target: :param domains: :return: \"\"\"", "dist = get_absdist(i, target) if dist < closet: closet =", "l1, l2): for i in range(len(l1)): if d1 == l1[i]", "if d1 == l1[i] and d2 == l2[i]: return True", "closetd = () for i in domains: dist = get_absdist(i,", "range(len(l1)): if d1 == l1[i] and d2 == l2[i]: return", "for i in tpl: if edge in i: return True", "list(combinations(indexlist[cursor:oldlen], 2)) combself = [(i, i) for i in range(0,", "None def check_bond_existence(d1, d2, l1, l2): for i in range(len(l1)):", "+ 1 == t2[0][1] and t1[1][1] - 1 == t2[1][1])", "key=lambda tup: tup[1]) mindist = 10000 mint = None for", "blocks: if limits[1] > i > limits[0]: tmp = abs(bound", "combself = [(i, i) for i in range(0, oldlen)] combnew", "domain2): \"\"\" :param domain1: :param domain2: :return: \"\"\" return abs(domain1[1]", "n == 1: return 0 else: return 1 def get_edge_info(e):", "+ combnew + combself def get_migrate_nodes(edges, indices, startstrand): d =", "= 10000 mint = None for t in targets: dist", "i) for i in range(0, oldlen)] combnew = [] if", "combold + combnew + combself def get_migrate_nodes(edges, indices, startstrand): d", "domains1, domains2): \"\"\" :param target1: :param target2: :param domains1: :param", "return True return False def compare(a, b): return (a >", "for i in range(0, oldlen)] combnew = [] if oldlen", "closet: closet = dist closetd = i return closetd def", "get_domains_on_2sides(target1, target2, domains1, domains2): \"\"\" :param target1: :param target2: :param", "if n == 1: return 0 else: return 1 def", "for t in targets: dist = min(get_absdist(t, domains[0]), get_absdist(t, domains[len(domains)", "startstrand): d = [] for i in indices: vi, ni", "dist = min(get_absdist(t, domains[0]), get_absdist(t, domains[len(domains) - 1])) if dist", ":param domains1: :param domains2: :return: \"\"\" if target1[0] == domains1[0][0]:", "1 elif i == 1: i = 0 return i", "i in range(2)] t = 0 for x in e:", "interval = limits[1] - limits[0] for i in blocks: if", "+= 1 for j in range(0, len(e)): if j !=", "check_edge_in_tuplelist(edge, tpl): for i in tpl: if edge in i:", "dist < mindist: mint = t return mint def check_continuity(a,", "miggroup def get_absdist(domain1, domain2): \"\"\" :param domain1: :param domain2: :return:", "continue for num in range(0, len(miggroup[cnt])): t1 = sorted(e[miggroup[cnt][num]][p], key=lambda", "- i) if tmp < interval: interval = tmp return", "get_absdist(i, target) if dist < closet: closet = dist closetd", "== t2[1][1]) \\ or (t1[0][1] - 1 == t2[0][1] and", "i, j return None def check_bond_existence(d1, d2, l1, l2): for", "limits[1] - limits[0] for i in blocks: if limits[1] >", "= sorted(e[i][p], key=lambda tup: tup[0]) if not visited[i]: visited[i] =", "def flip(i): if i == 0: i = 1 elif", "x in e: v[t], n[t] = x t += 1", "p=0): \"\"\" :param edges: :return: \"\"\" e = copy.copy(edges) visited", "if visited[i]: continue e[i] = list(e[i]) e[i][p] = list(e[i][p]) t1", "= get_closet_domain_to_target(target2, domains1) if target1[0] == domains2[0][0]: closetd2 = get_closet_domain_to_target(target1,", "in range(0, len(miggroup[cnt])): t1 = sorted(e[miggroup[cnt][num]][p], key=lambda tup: tup[0]) if", "def compare(a, b): return (a > b) - (a <", "+ 1 == t2[1][1]): visited[j] = True miggroup[cnt].append(j) break return", "tup[1]) mindist = 10000 mint = None for t in", "+= 1 return v, n def sort_e_by_domain(val): return val[0][1] def", "min(get_absdist(t, domains[0]), get_absdist(t, domains[len(domains) - 1])) if dist < mindist:", "= copy.copy(edges) visited = [False for _ in e] miggroup", "elif target2[0] == domains1[0][0]: closetd1 = get_closet_domain_to_target(target2, domains1) if target1[0]", "target1: :param target2: :param domains1: :param domains2: :return: \"\"\" if", "e] miggroup = [] cnt = -1 for i in", "== t2[0][1] and t1[1][1] - 1 == t2[1][1]) \\ or", "= get_closet_domain_to_target(target2, domains2) return closetd1, closetd2 def get_closest_target(domains, targets): \"\"\"", "e = copy.copy(edges) visited = [False for _ in e]", "def check_continuity(a, b): for i in a: for j in", "return None def check_bond_existence(d1, d2, l1, l2): for i in", "i in range(0, oldlen)] combnew = [] if oldlen !=", "not visited[j]: e[j] = list(e[j]) e[j][p] = list(e[j][p]) t2 =", "j in range(oldlen, newlen): combnew.append((i, j)) return combold + combnew", "def get_migrate_nodes(edges, indices, startstrand): d = [] for i in", "-1 for i in range(0, len(e)): if visited[i]: continue e[i]", "(t1[0][1] + 1 == t2[0][1] and t1[1][1] - 1 ==", "!= i and not visited[j]: e[j] = list(e[j]) e[j][p] =", "if target1[0] == domains2[0][0]: closetd2 = get_closet_domain_to_target(target1, domains2) elif target2[0]", "in range(len(l1)): if d1 == l1[i] and d2 == l2[i]:", ":return: \"\"\" e = copy.copy(edges) visited = [False for _", "combself def get_migrate_nodes(edges, indices, startstrand): d = [] for i", "e[i] = list(e[i]) e[i][p] = list(e[i][p]) t1 = sorted(e[i][p], key=lambda", "t2 = sorted(e[j][p], key=lambda tup: tup[0]) if (t2[0][0] != t1[0][0])", "- 1 == t2[0][1] and t1[1][1] + 1 == t2[1][1]):", "newlen: for i in range(0, oldlen): for j in range(oldlen,", "\"\"\" :param target: :param domains: :return: \"\"\" closet = 10000", "domains2[0][0]: closetd2 = get_closet_domain_to_target(target2, domains2) return closetd1, closetd2 def get_closest_target(domains,", "False def compare(a, b): return (a > b) - (a", "if dist < mindist: mint = t return mint def", "closetd2 = get_closet_domain_to_target(target1, domains2) elif target2[0] == domains2[0][0]: closetd2 =", "or (t2[1][0] != t1[1][0]): continue for num in range(0, len(miggroup[cnt])):", ":param domain1: :param domain2: :return: \"\"\" return abs(domain1[1] - domain2[1])", "= sorted(e[j][p], key=lambda tup: tup[0]) if (t2[0][0] != t1[0][0]) or", "i + 1 == j or i - 1 ==", "t2[0][1] and t1[1][1] - 1 == t2[1][1]) \\ or (t1[0][1]", "or (t1[0][1] - 1 == t2[0][1] and t1[1][1] + 1", "import copy def get_reverse(n): if n == 1: return 0", "= [] cnt = -1 for i in range(0, len(e)):", "closet = dist closetd = i return closetd def get_domains_on_2sides(target1,", "in tpl: if edge in i: return True return False", "tmp = abs(bound - i) if tmp < interval: interval", "get_combinations(oldlen, newlen, cursor, indexlist): combold = list(combinations(indexlist[cursor:oldlen], 2)) combself =", "limits[1] > i > limits[0]: tmp = abs(bound - i)", "targets: dist = min(get_absdist(t, domains[0]), get_absdist(t, domains[len(domains) - 1])) if", "j or i - 1 == j: return i, j", "< b) def flip(i): if i == 0: i =", "1 == j: return i, j return None def check_bond_existence(d1,", ":param edges: :return: \"\"\" e = copy.copy(edges) visited = [False", "> i > limits[0]: tmp = abs(bound - i) if", "get_absdist(t, domains[len(domains) - 1])) if dist < mindist: mint =", "for i in range(0, len(e)): if visited[i]: continue e[i] =", "= sorted(domains, key=lambda tup: tup[1]) mindist = 10000 mint =", "indexlist): combold = list(combinations(indexlist[cursor:oldlen], 2)) combself = [(i, i) for", "mint = t return mint def check_continuity(a, b): for i", "newlen): combnew.append((i, j)) return combold + combnew + combself def", "= True miggroup[cnt].append(j) break return miggroup def get_absdist(domain1, domain2): \"\"\"", "+ combself def get_migrate_nodes(edges, indices, startstrand): d = [] for", "[(i, i) for i in range(0, oldlen)] combnew = []", "\"\"\" :param edges: :return: \"\"\" e = copy.copy(edges) visited =", "[] for i in indices: vi, ni = get_edge_info(edges[i][0]) if", "v, n def sort_e_by_domain(val): return val[0][1] def sort_by_strand(val): return val[0][0]", "sort_e_by_domain(val): return val[0][1] def sort_by_strand(val): return val[0][0] def check_edge_in_tuplelist(edge, tpl):", "return False def compare(a, b): return (a > b) -", "i and not visited[j]: e[j] = list(e[j]) e[j][p] = list(e[j][p])", "len(e)): if visited[i]: continue e[i] = list(e[i]) e[i][p] = list(e[i][p])", "target2: :param domains1: :param domains2: :return: \"\"\" if target1[0] ==", "limits[0] for i in blocks: if limits[1] > i >", "sorted(limits) interval = limits[1] - limits[0] for i in blocks:", "- limits[0] for i in blocks: if limits[1] > i", "closetd2 = get_closet_domain_to_target(target2, domains2) return closetd1, closetd2 def get_closest_target(domains, targets):", "True return False def compare(a, b): return (a > b)", "!= newlen: for i in range(0, oldlen): for j in", "True miggroup.append([i]) cnt += 1 for j in range(0, len(e)):", "t return mint def check_continuity(a, b): for i in a:", "for i in range(2)] n = [0 for i in", "tup[0]) if (t2[0][0] != t1[0][0]) or (t2[1][0] != t1[1][0]): continue", "target1[0] == domains1[0][0]: closetd1 = get_closet_domain_to_target(target1, domains1) elif target2[0] ==", "domains2): \"\"\" :param target1: :param target2: :param domains1: :param domains2:", "range(0, oldlen): for j in range(oldlen, newlen): combnew.append((i, j)) return", "import combinations import copy def get_reverse(n): if n == 1:", "for x in e: v[t], n[t] = x t +=", "ni = get_edge_info(edges[i][0]) if vi[0] == startstrand: d.append(ni[0]) else: d.append(ni[1])", "[False for _ in e] miggroup = [] cnt =", "t1 = sorted(e[i][p], key=lambda tup: tup[0]) if not visited[i]: visited[i]", "!= t1[1][0]): continue for num in range(0, len(miggroup[cnt])): t1 =", "tpl: if edge in i: return True return False def", "and t1[1][1] + 1 == t2[1][1]): visited[j] = True miggroup[cnt].append(j)", "get_closet_domain_to_target(target1, domains1) elif target2[0] == domains1[0][0]: closetd1 = get_closet_domain_to_target(target2, domains1)", "check_following_migration(edges, p=0): \"\"\" :param edges: :return: \"\"\" e = copy.copy(edges)", "10000 mint = None for t in targets: dist =", "return v, n def sort_e_by_domain(val): return val[0][1] def sort_by_strand(val): return", "indices: vi, ni = get_edge_info(edges[i][0]) if vi[0] == startstrand: d.append(ni[0])", "for i in domains: dist = get_absdist(i, target) if dist", ":param domains: :return: \"\"\" closet = 10000 closetd = ()", "i = 0 return i def get_free_domains(limits, blocks, bound): limits", "return mint def check_continuity(a, b): for i in a: for", "b) def flip(i): if i == 0: i = 1", "closetd1 = get_closet_domain_to_target(target1, domains1) elif target2[0] == domains1[0][0]: closetd1 =", "j in range(0, len(e)): if j != i and not", "j != i and not visited[j]: e[j] = list(e[j]) e[j][p]", "[] if oldlen != newlen: for i in range(0, oldlen):", "- domain2[1]) def get_closet_domain_to_target(target, domains): \"\"\" :param target: :param domains:", "tmp < interval: interval = tmp return interval def get_combinations(oldlen,", "== 1: return 0 else: return 1 def get_edge_info(e): v", "n = [0 for i in range(2)] t = 0", "cursor, indexlist): combold = list(combinations(indexlist[cursor:oldlen], 2)) combself = [(i, i)", "visited = [False for _ in e] miggroup = []", "combnew + combself def get_migrate_nodes(edges, indices, startstrand): d = []", "miggroup[cnt].append(j) break return miggroup def get_absdist(domain1, domain2): \"\"\" :param domain1:", ":return: \"\"\" domains = sorted(domains, key=lambda tup: tup[1]) mindist =", "interval = tmp return interval def get_combinations(oldlen, newlen, cursor, indexlist):", "tup: tup[0]) if not visited[i]: visited[i] = True miggroup.append([i]) cnt", "= i return closetd def get_domains_on_2sides(target1, target2, domains1, domains2): \"\"\"", "dist < closet: closet = dist closetd = i return", "get_absdist(domain1, domain2): \"\"\" :param domain1: :param domain2: :return: \"\"\" return", "= x t += 1 return v, n def sort_e_by_domain(val):", "check_continuity(a, b): for i in a: for j in b:", "domains = sorted(domains, key=lambda tup: tup[1]) mindist = 10000 mint", "10000 closetd = () for i in domains: dist =", "n def sort_e_by_domain(val): return val[0][1] def sort_by_strand(val): return val[0][0] def", "target2[0] == domains1[0][0]: closetd1 = get_closet_domain_to_target(target2, domains1) if target1[0] ==", ":param target1: :param target2: :param domains1: :param domains2: :return: \"\"\"" ]
[ "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "adapt this script on your own question answering task. Pointers", "# # Licensed under the Apache License, Version 2.0 (the", "compliance with the License. # You may obtain a copy", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "2.0 (the \"License\"); # you may not use this file", "agreed to in writing, software # distributed under the License", "file except in compliance with the License. # You may", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "Unless required by applicable law or agreed to in writing,", "question answering task. Pointers for this are left as comments.", "distributed under the License is distributed on an \"AS IS\"", "override QATrainer and its base classes (Trainer) class QASparseTrainer(SparseTrainer, QATrainer):", "import SparseTrainer from .qa_train import QATrainer # SparseTrainer should appear", "the base classes, as its functions must override QATrainer and", "the specific language governing permissions and # limitations under the", "classes, as its functions must override QATrainer and its base", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "express or implied. # See the License for the specific", "applicable law or agreed to in writing, software # distributed", "except in compliance with the License. # You may obtain", "(Trainer) class QASparseTrainer(SparseTrainer, QATrainer): def __init__(self, sparse_args, *args, **kwargs): QATrainer.__init__(self,", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "first in the base classes, as its functions must override", "Licensed under the Apache License, Version 2.0 (the \"License\"); #", "own question answering task. Pointers for this are left as", "not use this file except in compliance with the License.", "its functions must override QATrainer and its base classes (Trainer)", "rights reserved. # # Licensed under the Apache License, Version", "License. \"\"\" Sparse Fine-tuning the library models for question answering.", "the library models for question answering. \"\"\" # You can", "writing, software # distributed under the License is distributed on", "def __init__(self, sparse_args, *args, **kwargs): QATrainer.__init__(self, *args, **kwargs) SparseTrainer.__init__(self, sparse_args)", "The HuggingFace Team All rights reserved. # # Licensed under", "in writing, software # distributed under the License is distributed", "comments. from nn_pruning.sparse_trainer import SparseTrainer from .qa_train import QATrainer #", "2020 The HuggingFace Team All rights reserved. # # Licensed", "QATrainer and its base classes (Trainer) class QASparseTrainer(SparseTrainer, QATrainer): def", "you may not use this file except in compliance with", "QATrainer # SparseTrainer should appear first in the base classes,", "# limitations under the License. \"\"\" Sparse Fine-tuning the library", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "for question answering. \"\"\" # You can also adapt this", "from .qa_train import QATrainer # SparseTrainer should appear first in", "its base classes (Trainer) class QASparseTrainer(SparseTrainer, QATrainer): def __init__(self, sparse_args,", "limitations under the License. \"\"\" Sparse Fine-tuning the library models", "use this file except in compliance with the License. #", "for this are left as comments. from nn_pruning.sparse_trainer import SparseTrainer", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "reserved. # # Licensed under the Apache License, Version 2.0", "under the License. \"\"\" Sparse Fine-tuning the library models for", "\"\"\" # You can also adapt this script on your", "the License. \"\"\" Sparse Fine-tuning the library models for question", "QASparseTrainer(SparseTrainer, QATrainer): def __init__(self, sparse_args, *args, **kwargs): QATrainer.__init__(self, *args, **kwargs)", "CONDITIONS OF ANY KIND, either express or implied. # See", "HuggingFace Team All rights reserved. # # Licensed under the", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "Sparse Fine-tuning the library models for question answering. \"\"\" #", "should appear first in the base classes, as its functions", "or implied. # See the License for the specific language", "License is distributed on an \"AS IS\" BASIS, # WITHOUT", "License. # You may obtain a copy of the License", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "License, Version 2.0 (the \"License\"); # you may not use", "permissions and # limitations under the License. \"\"\" Sparse Fine-tuning", "can also adapt this script on your own question answering", "# You may obtain a copy of the License at", "left as comments. from nn_pruning.sparse_trainer import SparseTrainer from .qa_train import", "KIND, either express or implied. # See the License for", "specific language governing permissions and # limitations under the License.", "in the base classes, as its functions must override QATrainer", "under the License is distributed on an \"AS IS\" BASIS,", "and # limitations under the License. \"\"\" Sparse Fine-tuning the", "task. Pointers for this are left as comments. from nn_pruning.sparse_trainer", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "answering task. Pointers for this are left as comments. from", "and its base classes (Trainer) class QASparseTrainer(SparseTrainer, QATrainer): def __init__(self,", "License for the specific language governing permissions and # limitations", "appear first in the base classes, as its functions must", "this are left as comments. from nn_pruning.sparse_trainer import SparseTrainer from", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "as its functions must override QATrainer and its base classes", "script on your own question answering task. Pointers for this", "# SparseTrainer should appear first in the base classes, as", "your own question answering task. Pointers for this are left", "answering. \"\"\" # You can also adapt this script on", "the License for the specific language governing permissions and #", "# Copyright 2020 The HuggingFace Team All rights reserved. #", "(the \"License\"); # you may not use this file except", "Apache License, Version 2.0 (the \"License\"); # you may not", "# you may not use this file except in compliance", "either express or implied. # See the License for the", "OR CONDITIONS OF ANY KIND, either express or implied. #", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "the License is distributed on an \"AS IS\" BASIS, #", "in compliance with the License. # You may obtain a", "classes (Trainer) class QASparseTrainer(SparseTrainer, QATrainer): def __init__(self, sparse_args, *args, **kwargs):", "as comments. from nn_pruning.sparse_trainer import SparseTrainer from .qa_train import QATrainer", "software # distributed under the License is distributed on an", "language governing permissions and # limitations under the License. \"\"\"", "# # Unless required by applicable law or agreed to", "SparseTrainer from .qa_train import QATrainer # SparseTrainer should appear first", "Fine-tuning the library models for question answering. \"\"\" # You", "question answering. \"\"\" # You can also adapt this script", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "# coding=utf-8 # Copyright 2020 The HuggingFace Team All rights", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "from nn_pruning.sparse_trainer import SparseTrainer from .qa_train import QATrainer # SparseTrainer", "functions must override QATrainer and its base classes (Trainer) class", "You can also adapt this script on your own question", "Version 2.0 (the \"License\"); # you may not use this", "law or agreed to in writing, software # distributed under", "this script on your own question answering task. Pointers for", "on your own question answering task. Pointers for this are", "implied. # See the License for the specific language governing", "SparseTrainer should appear first in the base classes, as its", "under the Apache License, Version 2.0 (the \"License\"); # you", "\"License\"); # you may not use this file except in", ".qa_train import QATrainer # SparseTrainer should appear first in the", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "base classes (Trainer) class QASparseTrainer(SparseTrainer, QATrainer): def __init__(self, sparse_args, *args,", "All rights reserved. # # Licensed under the Apache License,", "must override QATrainer and its base classes (Trainer) class QASparseTrainer(SparseTrainer,", "by applicable law or agreed to in writing, software #", "# distributed under the License is distributed on an \"AS", "OF ANY KIND, either express or implied. # See the", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "QATrainer): def __init__(self, sparse_args, *args, **kwargs): QATrainer.__init__(self, *args, **kwargs) SparseTrainer.__init__(self,", "may obtain a copy of the License at # #", "# Unless required by applicable law or agreed to in", "ANY KIND, either express or implied. # See the License", "See the License for the specific language governing permissions and", "import QATrainer # SparseTrainer should appear first in the base", "the License. # You may obtain a copy of the", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "for the specific language governing permissions and # limitations under", "Team All rights reserved. # # Licensed under the Apache", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "to in writing, software # distributed under the License is", "# You can also adapt this script on your own", "class QASparseTrainer(SparseTrainer, QATrainer): def __init__(self, sparse_args, *args, **kwargs): QATrainer.__init__(self, *args,", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "coding=utf-8 # Copyright 2020 The HuggingFace Team All rights reserved.", "# See the License for the specific language governing permissions", "Pointers for this are left as comments. from nn_pruning.sparse_trainer import", "You may obtain a copy of the License at #", "may not use this file except in compliance with the", "or agreed to in writing, software # distributed under the", "governing permissions and # limitations under the License. \"\"\" Sparse", "required by applicable law or agreed to in writing, software", "nn_pruning.sparse_trainer import SparseTrainer from .qa_train import QATrainer # SparseTrainer should", "library models for question answering. \"\"\" # You can also", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "with the License. # You may obtain a copy of", "are left as comments. from nn_pruning.sparse_trainer import SparseTrainer from .qa_train", "this file except in compliance with the License. # You", "the Apache License, Version 2.0 (the \"License\"); # you may", "also adapt this script on your own question answering task.", "base classes, as its functions must override QATrainer and its", "\"\"\" Sparse Fine-tuning the library models for question answering. \"\"\"", "models for question answering. \"\"\" # You can also adapt", "Copyright 2020 The HuggingFace Team All rights reserved. # #" ]
[ "{ 'description': ( 'This specifies whether to create the non-root", "If True, a root volume is created during RAID configuration.", "in keys: driver_internal_info.pop(key, None) task.node.driver_internal_info = driver_internal_info task.node.save() def _prepare_for_read_raid(self,", "is created during RAID configuration. Otherwise, no root volume is", "raid.update_raid_info(node, raid_conf) LOG.debug(\"Node %(uuid)s raid create clean step is done.\",", "_set_clean_failed(self, task, msg, exc): LOG.error(\"RAID configuration job failed for node", "states.CLEANWAIT else: # Raid configuration is done, updating raid_config raid_conf", "% {'node': node.uuid, 'err': msg}) except ilo_error.IloError as ilo_exception: operation", "'ilo_raid_delete_in_progress', 'cleaning_reboot', 'skip_current_clean_step') node.driver_internal_info = driver_internal_info node.save() else: # Raid", "states from ironic.conductor import utils as manager_utils from ironic import", "to create raid\" self._pop_driver_internal_values( task, 'ilo_raid_create_in_progress', 'cleaning_reboot', 'skip_current_clean_step') node.driver_internal_info =", "task.node.driver_internal_info for key in keys: driver_internal_info[key] = False task.node.driver_internal_info =", "'delete_raid') return states.CLEANWAIT else: # Raid configuration is done, updating", "RAID configuration on a bare metal using agent ramdisk. This", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "'description': ( 'This specifies whether to create the non-root volumes.", "specific language governing permissions and limitations # under the License.", "the License. \"\"\" iLO5 RAID specific methods \"\"\" from ironic_lib", "True task.node.driver_internal_info = driver_internal_info task.node.save() def _set_driver_internal_false_value(self, task, *keys): driver_internal_info", "'ilo_raid_delete_in_progress', 'cleaning_reboot', 'skip_current_clean_step') node.driver_internal_info = driver_internal_info node.save() self._set_clean_failed(task, operation, ilo_exception)", "# not use this file except in compliance with the", "the following target RAID configuration: %(target)s\", {'node': node.uuid, 'target': target_raid_config})", "Raid configuration is done, updating raid_config raid_conf = ( ilo_object.read_raid_configuration(", "driver_internal_info.get('ilo_raid_create_in_progress'): ilo_object.create_raid_configuration(target_raid_config) self._prepare_for_read_raid(task, 'create_raid') return states.CLEANWAIT else: # Raid configuration", "LOG.debug(\"Calling OOB RAID create_configuration for node %(node)s \" \"with the", "from ironic.common.i18n import _ from ironic.common import raid from ironic.common", "self._prepare_for_read_raid(task, 'delete_raid') return states.CLEANWAIT else: # Raid configuration is done,", "node.driver_internal_info = driver_internal_info node.save() raise exception.NodeCleaningFailure( \"Clean step delete_configuration failed", "driver_internal_info = task.node.driver_internal_info for key in keys: driver_internal_info.pop(key, None) task.node.driver_internal_info", "msg}) except ilo_error.IloError as ilo_exception: operation = (_(\"Failed to create", "= (\"Unable to delete this logical disks: %s\" % raid_conf['logical_disks'])", "in compliance with the License. You may obtain # a", "def _set_driver_internal_false_value(self, task, *keys): driver_internal_info = task.node.driver_internal_info for key in", "( 'This specifies whether to create the root volume. '", "\"Clean step create_configuration failed \" \"on node %(node)s with error:", "Enterprise Development LP # # Licensed under the Apache License,", "target_raid_config LOG.debug(\"Calling OOB RAID create_configuration for node %(node)s \" \"with", "is done, updating raid_config raid_conf = ilo_object.read_raid_configuration() if not len(raid_conf['logical_disks']):", ":raises: MissingParameterValue, if node.target_raid_config is missing or was found to", "configuration is done, updating raid_config raid_conf = ( ilo_object.read_raid_configuration( raid_config=target_raid_config))", "except ilo_error.IloError as ilo_exception: operation = (_(\"Failed to create raid", "You may obtain # a copy of the License at", "progress, checking status if not driver_internal_info.get('ilo_raid_create_in_progress'): ilo_object.create_raid_configuration(target_raid_config) self._prepare_for_read_raid(task, 'create_raid') return", "instance. :param create_root_volume: If True, a root volume is created", "\" \"on node %(node)s with error: %(err)s\" % {'node': node.uuid,", "found to be empty after skipping root volume and/or non-root", "except ilo_error.IloLogicalDriveNotFoundError: LOG.info(\"No logical drive found to delete on node", "volume. ' 'Defaults to `True`.' ), 'required': False }, 'create_nonroot_volumes':", "if raid_step == 'create_raid': self._set_driver_internal_true_value( task, 'ilo_raid_create_in_progress') else: self._set_driver_internal_true_value( task,", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "driver_internal_info['target_raid_config'] = target_raid_config LOG.debug(\"Calling OOB RAID create_configuration for node %(node)s", "to execute step. \"\"\" node = task.node target_raid_config = raid.filter_target_raid_config(", "the interface.\"\"\" return ilo_common.REQUIRED_PROPERTIES def _set_clean_failed(self, task, msg, exc): LOG.error(\"RAID", "step create_configuration failed \" \"on node %(node)s with error: %(err)s\"", "def create_configuration(self, task, create_root_volume=True, create_nonroot_volumes=True): \"\"\"Create a RAID configuration on", "is True. :raises: MissingParameterValue, if node.target_raid_config is missing or was", "creates a RAID configuration on the given node. :param task:", "node.uuid, 'target': target_raid_config}) ilo_object = ilo_common.get_ilo_object(node) try: # Raid configuration", "the root volume. ' 'Defaults to `True`.' ), 'required': False", "under the License is distributed on an \"AS IS\" BASIS,", "skipping root volume and/or non-root volumes. :raises: NodeCleaningFailure, on failure", "else: self._set_driver_internal_true_value( task, 'ilo_raid_delete_in_progress') self._set_driver_internal_true_value(task, 'cleaning_reboot') self._set_driver_internal_false_value(task, 'skip_current_clean_step') @METRICS.timer('Ilo5RAID.create_configuration') @base.clean_step(priority=0,", "to delete this logical disks: %s\" % raid_conf['logical_disks']) self._pop_driver_internal_values( task,", "iLO5 RAID specific methods \"\"\" from ironic_lib import metrics_utils from", "delete clean step is done.\", {'uuid': node.uuid}) self._pop_driver_internal_values( task, 'ilo_raid_delete_in_progress',", "\"\"\"Return the properties of the interface.\"\"\" return ilo_common.REQUIRED_PROPERTIES def _set_clean_failed(self,", "2018 Hewlett Packard Enterprise Development LP # # Licensed under", "), 'required': False } }) def create_configuration(self, task, create_root_volume=True, create_nonroot_volumes=True):", "'ilo_raid_create_in_progress', 'cleaning_reboot', 'skip_current_clean_step') node.driver_internal_info = driver_internal_info node.save() self._set_clean_failed(task, operation, ilo_exception)", "this logical disks: %s\" % raid_conf['logical_disks']) self._pop_driver_internal_values( task, 'ilo_raid_delete_in_progress', 'cleaning_reboot',", "step is done.\", {'uuid': node.uuid}) self._pop_driver_internal_values( task, 'ilo_raid_delete_in_progress', 'cleaning_reboot', 'skip_current_clean_step')", "are created. Default is True. :raises: MissingParameterValue, if node.target_raid_config is", "ilo_object.read_raid_configuration() if not len(raid_conf['logical_disks']): node.raid_config = {} LOG.debug(\"Node %(uuid)s raid", "is missing or was found to be empty after skipping", "# Raid configuration is done, updating raid_config raid_conf = (", "'This specifies whether to create the non-root volumes. ' 'Defaults", "task, *keys): driver_internal_info = task.node.driver_internal_info for key in keys: driver_internal_info[key]", "under the License. \"\"\" iLO5 RAID specific methods \"\"\" from", "this file except in compliance with the License. You may", "failed \" \"on node %(node)s with error: %(err)s\" % {'node':", "a RAID configuration on a bare metal using agent ramdisk.", "Default is True. :param create_nonroot_volumes: If True, non-root volumes are", "is done.\", {'uuid': node.uuid}) self._pop_driver_internal_values( task, 'ilo_raid_create_in_progress', 'cleaning_reboot', 'skip_current_clean_step') node.driver_internal_info", "*keys): driver_internal_info = task.node.driver_internal_info for key in keys: driver_internal_info[key] =", "%s\" % raid_conf['logical_disks']) self._pop_driver_internal_values( task, 'ilo_raid_delete_in_progress', 'cleaning_reboot', 'skip_current_clean_step') node.driver_internal_info =", "node.save() self._set_clean_failed(task, operation, ilo_exception) @METRICS.timer('Ilo5RAID.delete_configuration') @base.clean_step(priority=0, abortable=False) def delete_configuration(self, task):", "in keys: driver_internal_info[key] = True task.node.driver_internal_info = driver_internal_info task.node.save() def", "\"\"\"Create a RAID configuration on a bare metal using agent", "configuration. :param task: a TaskManager instance containing the node to", "in keys: driver_internal_info[key] = False task.node.driver_internal_info = driver_internal_info task.node.save() def", "created during RAID configuration. Otherwise, no root volume is created.", "software # distributed under the License is distributed on an", "(the \"License\"); you may # not use this file except", "with error: %(err)s\" % {'node': node.uuid, 'err': msg}) except ilo_error.IloError", "node.uuid) self._pop_driver_internal_values(task, 'ilo_raid_create_in_progress', 'cleaning_reboot', 'skip_current_clean_step') node.driver_internal_info = driver_internal_info node.save() self._set_clean_failed(task,", "@METRICS.timer('Ilo5RAID.create_configuration') @base.clean_step(priority=0, abortable=False, argsinfo={ 'create_root_volume': { 'description': ( 'This specifies", "clean step is done.\", {'uuid': node.uuid}) self._pop_driver_internal_values( task, 'ilo_raid_delete_in_progress', 'cleaning_reboot',", "on node %(node)s\", {'node': node.uuid}) except ilo_error.IloError as ilo_exception: operation", "\"\"\" from ironic_lib import metrics_utils from oslo_log import log as", "error: %(err)s\" % {'node': node.uuid, 'err': msg}) except ilo_error.IloError as", "= logging.getLogger(__name__) CONF = conf.CONF METRICS = metrics_utils.get_metrics_logger(__name__) ilo_error =", "raid delete clean step is done.\", {'uuid': node.uuid}) self._pop_driver_internal_values( task,", "{'node': node.uuid, 'err': msg}) except ilo_error.IloError as ilo_exception: operation =", "file except in compliance with the License. You may obtain", "\"Message: '%(message)s'.\", {'node': task.node.uuid, 'message': msg}) task.node.last_error = msg task.process_event('fail')", ":raises: NodeCleaningFailure, on failure to execute step. \"\"\" node =", "with error: %(err)s\" % {'node': node.uuid, 'err': msg}) except ilo_error.IloLogicalDriveNotFoundError:", "raid_conf['logical_disks']) self._pop_driver_internal_values( task, 'ilo_raid_delete_in_progress', 'cleaning_reboot', 'skip_current_clean_step') node.driver_internal_info = driver_internal_info node.save()", "to `True`.' ), 'required': False } }) def create_configuration(self, task,", "OR CONDITIONS OF ANY KIND, either express or implied. See", "the specific language governing permissions and limitations # under the", "node.driver_internal_info = driver_internal_info node.save() raise exception.NodeCleaningFailure( \"Clean step create_configuration failed", "%(uuid)s raid delete clean step is done.\", {'uuid': node.uuid}) self._pop_driver_internal_values(", "configuration on the given node. :param task: a TaskManager instance.", "to be empty after skipping root volume and/or non-root volumes.", "= ilo_object.read_raid_configuration() if not len(raid_conf['logical_disks']): node.raid_config = {} LOG.debug(\"Node %(uuid)s", "# Copyright 2018 Hewlett Packard Enterprise Development LP # #", "under the Apache License, Version 2.0 (the \"License\"); you may", "If True, non-root volumes are created. If False, no non-root", "from ironic.common import states from ironic.conductor import utils as manager_utils", "for node %(node)s \" \"with the following target RAID configuration:", "exception.NodeCleaningFailure( \"Clean step create_configuration failed \" \"on node %(node)s with", "failed msg = \"Unable to create raid\" self._pop_driver_internal_values( task, 'ilo_raid_create_in_progress',", "task.node.driver_internal_info = driver_internal_info task.node.save() def _pop_driver_internal_values(self, task, *keys): driver_internal_info =", "to delete raid configuration on node %s\") % node.uuid) self._pop_driver_internal_values(task,", "driver_internal_info[key] = True task.node.driver_internal_info = driver_internal_info task.node.save() def _set_driver_internal_false_value(self, task,", "delete_configuration failed \" \"on node %(node)s with error: %(err)s\" %", "(_(\"Failed to delete raid configuration on node %s\") % node.uuid)", "driver_internal_info.pop(key, None) task.node.driver_internal_info = driver_internal_info task.node.save() def _prepare_for_read_raid(self, task, raid_step):", "create_nonroot_volumes=True): \"\"\"Create a RAID configuration on a bare metal using", "node.save() raise exception.NodeCleaningFailure( \"Clean step create_configuration failed \" \"on node", "driver_internal_info = task.node.driver_internal_info for key in keys: driver_internal_info[key] = True", "no root volume is created. Default is True. :param create_nonroot_volumes:", "= driver_internal_info node.save() raise exception.NodeCleaningFailure( \"Clean step delete_configuration failed \"", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "\"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY", "logging from oslo_utils import importutils from ironic.common import exception from", "node = task.node target_raid_config = raid.filter_target_raid_config( node, create_root_volume=create_root_volume, create_nonroot_volumes=create_nonroot_volumes) driver_internal_info", "True. :param create_nonroot_volumes: If True, non-root volumes are created. If", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "ilo_common.REQUIRED_PROPERTIES def _set_clean_failed(self, task, msg, exc): LOG.error(\"RAID configuration job failed", "\"\"\" node = task.node LOG.debug(\"OOB RAID delete_configuration invoked for node", "conf from ironic.drivers import base from ironic.drivers.modules import deploy_utils from", "to in writing, software # distributed under the License is", "task.node.save() def _prepare_for_read_raid(self, task, raid_step): deploy_opts = deploy_utils.build_agent_options(task.node) task.driver.boot.prepare_ramdisk(task, deploy_opts)", "non-root volumes are created. If False, no non-root volumes are", "target_raid_config = raid.filter_target_raid_config( node, create_root_volume=create_root_volume, create_nonroot_volumes=create_nonroot_volumes) driver_internal_info = node.driver_internal_info driver_internal_info['target_raid_config']", "to act on. :raises: NodeCleaningFailure, on failure to execute step.", "operation = (_(\"Failed to delete raid configuration on node %s\")", "% node.uuid) self._pop_driver_internal_values(task, 'ilo_raid_delete_in_progress', 'cleaning_reboot', 'skip_current_clean_step') node.driver_internal_info = driver_internal_info node.save()", "%(err)s\" % {'node': node.uuid, 'err': msg}) except ilo_error.IloLogicalDriveNotFoundError: LOG.info(\"No logical", "whether to create the non-root volumes. ' 'Defaults to `True`.'", "import deploy_utils from ironic.drivers.modules.ilo import common as ilo_common LOG =", "task, raid_step): deploy_opts = deploy_utils.build_agent_options(task.node) task.driver.boot.prepare_ramdisk(task, deploy_opts) manager_utils.node_power_action(task, states.REBOOT) if", "or agreed to in writing, software # distributed under the", "True, a root volume is created during RAID configuration. Otherwise,", "True. :raises: MissingParameterValue, if node.target_raid_config is missing or was found", "= task.node.driver_internal_info for key in keys: driver_internal_info.pop(key, None) task.node.driver_internal_info =", "not driver_internal_info.get('ilo_raid_delete_in_progress'): ilo_object.delete_raid_configuration() self._prepare_for_read_raid(task, 'delete_raid') return states.CLEANWAIT else: # Raid", "raid_config raid_conf = ( ilo_object.read_raid_configuration( raid_config=target_raid_config)) if len(raid_conf['logical_disks']): raid.update_raid_info(node, raid_conf)", "required by applicable law or agreed to in writing, software", "import exception from ironic.common.i18n import _ from ironic.common import raid", "manager_utils from ironic import conf from ironic.drivers import base from", "'message': msg}) task.node.last_error = msg task.process_event('fail') def _set_driver_internal_true_value(self, task, *keys):", "target RAID configuration: %(target)s\", {'node': node.uuid, 'target': target_raid_config}) ilo_object =", "self._set_driver_internal_true_value( task, 'ilo_raid_create_in_progress') else: self._set_driver_internal_true_value( task, 'ilo_raid_delete_in_progress') self._set_driver_internal_true_value(task, 'cleaning_reboot') self._set_driver_internal_false_value(task,", "' 'Defaults to `True`.' ), 'required': False } }) def", "`True`.' ), 'required': False } }) def create_configuration(self, task, create_root_volume=True,", "the RAID configuration. :param task: a TaskManager instance containing the", "import common as ilo_common LOG = logging.getLogger(__name__) CONF = conf.CONF", "task, 'ilo_raid_create_in_progress', 'cleaning_reboot', 'skip_current_clean_step') node.driver_internal_info = driver_internal_info node.save() else: #", "'ilo_raid_create_in_progress') else: self._set_driver_internal_true_value( task, 'ilo_raid_delete_in_progress') self._set_driver_internal_true_value(task, 'cleaning_reboot') self._set_driver_internal_false_value(task, 'skip_current_clean_step') @METRICS.timer('Ilo5RAID.create_configuration')", "%(node)s \" \"with the following target RAID configuration: %(target)s\", {'node':", "configuration. Otherwise, no root volume is created. Default is True.", "= (_(\"Failed to delete raid configuration on node %s\") %", "Apache License, Version 2.0 (the \"License\"); you may # not", "specifies whether to create the non-root volumes. ' 'Defaults to", "oslo_utils import importutils from ironic.common import exception from ironic.common.i18n import", "import importutils from ironic.common import exception from ironic.common.i18n import _", "= importutils.try_import('proliantutils.exception') class Ilo5RAID(base.RAIDInterface): \"\"\"Implementation of OOB RAIDInterface for iLO5.\"\"\"", "self._pop_driver_internal_values( task, 'ilo_raid_delete_in_progress', 'cleaning_reboot', 'skip_current_clean_step') node.driver_internal_info = driver_internal_info node.save() else:", "agreed to in writing, software # distributed under the License", "# under the License. \"\"\" iLO5 RAID specific methods \"\"\"", "import log as logging from oslo_utils import importutils from ironic.common", "is True. :param create_nonroot_volumes: If True, non-root volumes are created.", "driver_internal_info = node.driver_internal_info driver_internal_info['target_raid_config'] = target_raid_config LOG.debug(\"Calling OOB RAID create_configuration", "This method creates a RAID configuration on the given node.", "node.save() else: # Raid configuration failed msg = \"Unable to", "= driver_internal_info node.save() raise exception.NodeCleaningFailure( \"Clean step create_configuration failed \"", "self._set_driver_internal_true_value(task, 'cleaning_reboot') self._set_driver_internal_false_value(task, 'skip_current_clean_step') @METRICS.timer('Ilo5RAID.create_configuration') @base.clean_step(priority=0, abortable=False, argsinfo={ 'create_root_volume': {", "= conf.CONF METRICS = metrics_utils.get_metrics_logger(__name__) ilo_error = importutils.try_import('proliantutils.exception') class Ilo5RAID(base.RAIDInterface):", "distributed under the License is distributed on an \"AS IS\"", "}) def create_configuration(self, task, create_root_volume=True, create_nonroot_volumes=True): \"\"\"Create a RAID configuration", "%(uuid)s raid create clean step is done.\", {'uuid': node.uuid}) self._pop_driver_internal_values(", "# Raid configuration failed msg = (\"Unable to delete this", "raid configuration on node %s\") % node.uuid) self._pop_driver_internal_values(task, 'ilo_raid_create_in_progress', 'cleaning_reboot',", "for key in keys: driver_internal_info.pop(key, None) task.node.driver_internal_info = driver_internal_info task.node.save()", "missing or was found to be empty after skipping root", "License, Version 2.0 (the \"License\"); you may # not use", "CONDITIONS OF ANY KIND, either express or implied. See the", "error: %(err)s\" % {'node': node.uuid, 'err': msg}) except ilo_error.IloLogicalDriveNotFoundError: LOG.info(\"No", "states.REBOOT) if raid_step == 'create_raid': self._set_driver_internal_true_value( task, 'ilo_raid_create_in_progress') else: self._set_driver_internal_true_value(", "as ilo_common LOG = logging.getLogger(__name__) CONF = conf.CONF METRICS =", "node. :param task: a TaskManager instance. :param create_root_volume: If True,", "task.node.uuid, 'message': msg}) task.node.last_error = msg task.process_event('fail') def _set_driver_internal_true_value(self, task,", "self._pop_driver_internal_values( task, 'ilo_raid_create_in_progress', 'cleaning_reboot', 'skip_current_clean_step') node.driver_internal_info = driver_internal_info node.save() raise", "from ironic import conf from ironic.drivers import base from ironic.drivers.modules", "logical drive found to delete on node %(node)s\", {'node': node.uuid})", "the non-root volumes. ' 'Defaults to `True`.' ), 'required': False", "self._pop_driver_internal_values(task, 'ilo_raid_create_in_progress', 'cleaning_reboot', 'skip_current_clean_step') node.driver_internal_info = driver_internal_info node.save() self._set_clean_failed(task, operation,", ":param task: a TaskManager instance. :param create_root_volume: If True, a", "not use this file except in compliance with the License.", "the properties of the interface.\"\"\" return ilo_common.REQUIRED_PROPERTIES def _set_clean_failed(self, task,", "configuration in progress, checking status if not driver_internal_info.get('ilo_raid_delete_in_progress'): ilo_object.delete_raid_configuration() self._prepare_for_read_raid(task,", "msg, exc): LOG.error(\"RAID configuration job failed for node %(node)s. \"", "import utils as manager_utils from ironic import conf from ironic.drivers", ":param create_nonroot_volumes: If True, non-root volumes are created. If False,", "manager_utils.node_power_action(task, states.REBOOT) if raid_step == 'create_raid': self._set_driver_internal_true_value( task, 'ilo_raid_create_in_progress') else:", "execute step. \"\"\" node = task.node LOG.debug(\"OOB RAID delete_configuration invoked", "writing, software # distributed under the License is distributed on", "msg = \"Unable to create raid\" self._pop_driver_internal_values( task, 'ilo_raid_create_in_progress', 'cleaning_reboot',", "node.uuid}) self._pop_driver_internal_values( task, 'ilo_raid_create_in_progress', 'cleaning_reboot', 'skip_current_clean_step') node.driver_internal_info = driver_internal_info node.save()", "create_root_volume: If True, a root volume is created during RAID", "node = task.node LOG.debug(\"OOB RAID delete_configuration invoked for node %s.\",", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "on node %s\") % node.uuid) self._pop_driver_internal_values(task, 'ilo_raid_delete_in_progress', 'cleaning_reboot', 'skip_current_clean_step') node.driver_internal_info", "raid create clean step is done.\", {'uuid': node.uuid}) self._pop_driver_internal_values( task,", "raid.filter_target_raid_config( node, create_root_volume=create_root_volume, create_nonroot_volumes=create_nonroot_volumes) driver_internal_info = node.driver_internal_info driver_internal_info['target_raid_config'] = target_raid_config", "'cleaning_reboot', 'skip_current_clean_step') node.driver_internal_info = driver_internal_info node.save() raise exception.NodeCleaningFailure( \"Clean step", "volumes. ' 'Defaults to `True`.' ), 'required': False } })", "node, create_root_volume=create_root_volume, create_nonroot_volumes=create_nonroot_volumes) driver_internal_info = node.driver_internal_info driver_internal_info['target_raid_config'] = target_raid_config LOG.debug(\"Calling", "msg}) task.node.last_error = msg task.process_event('fail') def _set_driver_internal_true_value(self, task, *keys): driver_internal_info", "the License. You may obtain # a copy of the", "an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF", "bare metal using agent ramdisk. This method creates a RAID", "use this file except in compliance with the License. You", "self._set_clean_failed(task, operation, ilo_exception) @METRICS.timer('Ilo5RAID.delete_configuration') @base.clean_step(priority=0, abortable=False) def delete_configuration(self, task): \"\"\"Delete", "task.node.driver_internal_info = driver_internal_info task.node.save() def _set_driver_internal_false_value(self, task, *keys): driver_internal_info =", "node %(node)s. \" \"Message: '%(message)s'.\", {'node': task.node.uuid, 'message': msg}) task.node.last_error", "% raid_conf['logical_disks']) self._pop_driver_internal_values( task, 'ilo_raid_delete_in_progress', 'cleaning_reboot', 'skip_current_clean_step') node.driver_internal_info = driver_internal_info", "{'node': task.node.uuid, 'message': msg}) task.node.last_error = msg task.process_event('fail') def _set_driver_internal_true_value(self,", "on failure to execute step. \"\"\" node = task.node target_raid_config", "as logging from oslo_utils import importutils from ironic.common import exception", "node.target_raid_config is missing or was found to be empty after", "= task.node.driver_internal_info for key in keys: driver_internal_info[key] = False task.node.driver_internal_info", "LOG.debug(\"OOB RAID delete_configuration invoked for node %s.\", node.uuid) driver_internal_info =", "permissions and limitations # under the License. \"\"\" iLO5 RAID", "'required': False }, 'create_nonroot_volumes': { 'description': ( 'This specifies whether", "RAID configuration. Otherwise, no root volume is created. Default is", "task.node LOG.debug(\"OOB RAID delete_configuration invoked for node %s.\", node.uuid) driver_internal_info", "_prepare_for_read_raid(self, task, raid_step): deploy_opts = deploy_utils.build_agent_options(task.node) task.driver.boot.prepare_ramdisk(task, deploy_opts) manager_utils.node_power_action(task, states.REBOOT)", "self._pop_driver_internal_values(task, 'ilo_raid_delete_in_progress', 'cleaning_reboot', 'skip_current_clean_step') node.driver_internal_info = driver_internal_info node.save() self._set_clean_failed(task, operation,", "RAIDInterface for iLO5.\"\"\" def get_properties(self): \"\"\"Return the properties of the", "= task.node.driver_internal_info for key in keys: driver_internal_info[key] = True task.node.driver_internal_info", "== 'create_raid': self._set_driver_internal_true_value( task, 'ilo_raid_create_in_progress') else: self._set_driver_internal_true_value( task, 'ilo_raid_delete_in_progress') self._set_driver_internal_true_value(task,", "If False, no non-root volumes are created. Default is True.", "method creates a RAID configuration on the given node. :param", "create clean step is done.\", {'uuid': node.uuid}) self._pop_driver_internal_values( task, 'ilo_raid_create_in_progress',", "TaskManager instance containing the node to act on. :raises: NodeCleaningFailure,", "configuration failed msg = (\"Unable to delete this logical disks:", "node.driver_internal_info ilo_object = ilo_common.get_ilo_object(node) try: # Raid configuration in progress,", "task: a TaskManager instance. :param create_root_volume: If True, a root", "step. \"\"\" node = task.node LOG.debug(\"OOB RAID delete_configuration invoked for", "task, 'ilo_raid_create_in_progress') else: self._set_driver_internal_true_value( task, 'ilo_raid_delete_in_progress') self._set_driver_internal_true_value(task, 'cleaning_reboot') self._set_driver_internal_false_value(task, 'skip_current_clean_step')", "Raid configuration in progress, checking status if not driver_internal_info.get('ilo_raid_delete_in_progress'): ilo_object.delete_raid_configuration()", "License is distributed on an \"AS IS\" BASIS, WITHOUT #", "KIND, either express or implied. See the # License for", "root volume. ' 'Defaults to `True`.' ), 'required': False },", "of OOB RAIDInterface for iLO5.\"\"\" def get_properties(self): \"\"\"Return the properties", "volumes. :raises: NodeCleaningFailure, on failure to execute step. \"\"\" node", "}, 'create_nonroot_volumes': { 'description': ( 'This specifies whether to create", "\"License\"); you may # not use this file except in", "LOG.debug(\"Node %(uuid)s raid delete clean step is done.\", {'uuid': node.uuid})", "raid_conf = ( ilo_object.read_raid_configuration( raid_config=target_raid_config)) if len(raid_conf['logical_disks']): raid.update_raid_info(node, raid_conf) LOG.debug(\"Node", "driver_internal_info task.node.save() def _pop_driver_internal_values(self, task, *keys): driver_internal_info = task.node.driver_internal_info for", "IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND,", "in progress, checking status if not driver_internal_info.get('ilo_raid_create_in_progress'): ilo_object.create_raid_configuration(target_raid_config) self._prepare_for_read_raid(task, 'create_raid')", "express or implied. See the # License for the specific", "License. \"\"\" iLO5 RAID specific methods \"\"\" from ironic_lib import", "node.raid_config = {} LOG.debug(\"Node %(uuid)s raid delete clean step is", "%(node)s. \" \"Message: '%(message)s'.\", {'node': task.node.uuid, 'message': msg}) task.node.last_error =", "% node.uuid) self._pop_driver_internal_values(task, 'ilo_raid_create_in_progress', 'cleaning_reboot', 'skip_current_clean_step') node.driver_internal_info = driver_internal_info node.save()", "the Apache License, Version 2.0 (the \"License\"); you may #", "'create_root_volume': { 'description': ( 'This specifies whether to create the", "True, non-root volumes are created. If False, no non-root volumes", "metal using agent ramdisk. This method creates a RAID configuration", "deploy_opts) manager_utils.node_power_action(task, states.REBOOT) if raid_step == 'create_raid': self._set_driver_internal_true_value( task, 'ilo_raid_create_in_progress')", "node %s\") % node.uuid) self._pop_driver_internal_values(task, 'ilo_raid_delete_in_progress', 'cleaning_reboot', 'skip_current_clean_step') node.driver_internal_info =", "def get_properties(self): \"\"\"Return the properties of the interface.\"\"\" return ilo_common.REQUIRED_PROPERTIES", "volume is created during RAID configuration. Otherwise, no root volume", "task.node.save() def _pop_driver_internal_values(self, task, *keys): driver_internal_info = task.node.driver_internal_info for key", "See the # License for the specific language governing permissions", "following target RAID configuration: %(target)s\", {'node': node.uuid, 'target': target_raid_config}) ilo_object", "@base.clean_step(priority=0, abortable=False, argsinfo={ 'create_root_volume': { 'description': ( 'This specifies whether", "if len(raid_conf['logical_disks']): raid.update_raid_info(node, raid_conf) LOG.debug(\"Node %(uuid)s raid create clean step", "operation, ilo_exception) @METRICS.timer('Ilo5RAID.delete_configuration') @base.clean_step(priority=0, abortable=False) def delete_configuration(self, task): \"\"\"Delete the", "msg task.process_event('fail') def _set_driver_internal_true_value(self, task, *keys): driver_internal_info = task.node.driver_internal_info for", "_set_driver_internal_true_value(self, task, *keys): driver_internal_info = task.node.driver_internal_info for key in keys:", "self._pop_driver_internal_values( task, 'ilo_raid_delete_in_progress', 'cleaning_reboot', 'skip_current_clean_step') node.driver_internal_info = driver_internal_info node.save() raise", "# a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "node.driver_internal_info = driver_internal_info node.save() self._set_clean_failed(task, operation, ilo_exception) @METRICS.timer('Ilo5RAID.delete_configuration') @base.clean_step(priority=0, abortable=False)", "RAID create_configuration for node %(node)s \" \"with the following target", "create_configuration failed \" \"on node %(node)s with error: %(err)s\" %", "base from ironic.drivers.modules import deploy_utils from ironic.drivers.modules.ilo import common as", "on a bare metal using agent ramdisk. This method creates", "\"Unable to create raid\" self._pop_driver_internal_values( task, 'ilo_raid_create_in_progress', 'cleaning_reboot', 'skip_current_clean_step') node.driver_internal_info", "'Defaults to `True`.' ), 'required': False }, 'create_nonroot_volumes': { 'description':", "as ilo_exception: operation = (_(\"Failed to delete raid configuration on", "node to act on. :raises: NodeCleaningFailure, on failure to execute", "(\"Unable to delete this logical disks: %s\" % raid_conf['logical_disks']) self._pop_driver_internal_values(", "len(raid_conf['logical_disks']): node.raid_config = {} LOG.debug(\"Node %(uuid)s raid delete clean step", "law or agreed to in writing, software # distributed under", "get_properties(self): \"\"\"Return the properties of the interface.\"\"\" return ilo_common.REQUIRED_PROPERTIES def", "failed for node %(node)s. \" \"Message: '%(message)s'.\", {'node': task.node.uuid, 'message':", "for node %s.\", node.uuid) driver_internal_info = node.driver_internal_info ilo_object = ilo_common.get_ilo_object(node)", "and/or non-root volumes. :raises: NodeCleaningFailure, on failure to execute step.", "= driver_internal_info task.node.save() def _pop_driver_internal_values(self, task, *keys): driver_internal_info = task.node.driver_internal_info", "'skip_current_clean_step') node.driver_internal_info = driver_internal_info node.save() else: # Raid configuration failed", "import _ from ironic.common import raid from ironic.common import states", "on the given node. :param task: a TaskManager instance. :param", "= True task.node.driver_internal_info = driver_internal_info task.node.save() def _set_driver_internal_false_value(self, task, *keys):", "given node. :param task: a TaskManager instance. :param create_root_volume: If", "abortable=False, argsinfo={ 'create_root_volume': { 'description': ( 'This specifies whether to", "RAID configuration on the given node. :param task: a TaskManager", "'ilo_raid_delete_in_progress', 'cleaning_reboot', 'skip_current_clean_step') node.driver_internal_info = driver_internal_info node.save() raise exception.NodeCleaningFailure( \"Clean", "implied. See the # License for the specific language governing", "from ironic_lib import metrics_utils from oslo_log import log as logging", "node %(node)s\", {'node': node.uuid}) except ilo_error.IloError as ilo_exception: operation =", "import metrics_utils from oslo_log import log as logging from oslo_utils", "log as logging from oslo_utils import importutils from ironic.common import", "root volume is created during RAID configuration. Otherwise, no root", "driver_internal_info[key] = False task.node.driver_internal_info = driver_internal_info task.node.save() def _pop_driver_internal_values(self, task,", "import base from ironic.drivers.modules import deploy_utils from ironic.drivers.modules.ilo import common", "deploy_utils.build_agent_options(task.node) task.driver.boot.prepare_ramdisk(task, deploy_opts) manager_utils.node_power_action(task, states.REBOOT) if raid_step == 'create_raid': self._set_driver_internal_true_value(", "= task.node LOG.debug(\"OOB RAID delete_configuration invoked for node %s.\", node.uuid)", "to execute step. \"\"\" node = task.node LOG.debug(\"OOB RAID delete_configuration", "'err': msg}) except ilo_error.IloLogicalDriveNotFoundError: LOG.info(\"No logical drive found to delete", "node.uuid) self._pop_driver_internal_values(task, 'ilo_raid_delete_in_progress', 'cleaning_reboot', 'skip_current_clean_step') node.driver_internal_info = driver_internal_info node.save() self._set_clean_failed(task,", "= task.node target_raid_config = raid.filter_target_raid_config( node, create_root_volume=create_root_volume, create_nonroot_volumes=create_nonroot_volumes) driver_internal_info =", "RAID configuration. :param task: a TaskManager instance containing the node", "LOG.debug(\"Node %(uuid)s raid create clean step is done.\", {'uuid': node.uuid})", "{} LOG.debug(\"Node %(uuid)s raid delete clean step is done.\", {'uuid':", "'cleaning_reboot', 'skip_current_clean_step') node.driver_internal_info = driver_internal_info node.save() self._set_clean_failed(task, operation, ilo_exception) @METRICS.timer('Ilo5RAID.delete_configuration')", "= node.driver_internal_info driver_internal_info['target_raid_config'] = target_raid_config LOG.debug(\"Calling OOB RAID create_configuration for", "def _set_driver_internal_true_value(self, task, *keys): driver_internal_info = task.node.driver_internal_info for key in", "keys: driver_internal_info.pop(key, None) task.node.driver_internal_info = driver_internal_info task.node.save() def _prepare_for_read_raid(self, task,", "exception from ironic.common.i18n import _ from ironic.common import raid from", "\"\"\" node = task.node target_raid_config = raid.filter_target_raid_config( node, create_root_volume=create_root_volume, create_nonroot_volumes=create_nonroot_volumes)", "task, create_root_volume=True, create_nonroot_volumes=True): \"\"\"Create a RAID configuration on a bare", "non-root volumes are created. Default is True. :raises: MissingParameterValue, if", "configuration: %(target)s\", {'node': node.uuid, 'target': target_raid_config}) ilo_object = ilo_common.get_ilo_object(node) try:", "if not driver_internal_info.get('ilo_raid_create_in_progress'): ilo_object.create_raid_configuration(target_raid_config) self._prepare_for_read_raid(task, 'create_raid') return states.CLEANWAIT else: #", "\"on node %(node)s with error: %(err)s\" % {'node': node.uuid, 'err':", "iLO5.\"\"\" def get_properties(self): \"\"\"Return the properties of the interface.\"\"\" return", "Copyright 2018 Hewlett Packard Enterprise Development LP # # Licensed", "language governing permissions and limitations # under the License. \"\"\"", "from ironic.drivers import base from ironic.drivers.modules import deploy_utils from ironic.drivers.modules.ilo", "done, updating raid_config raid_conf = ( ilo_object.read_raid_configuration( raid_config=target_raid_config)) if len(raid_conf['logical_disks']):", "is done.\", {'uuid': node.uuid}) self._pop_driver_internal_values( task, 'ilo_raid_delete_in_progress', 'cleaning_reboot', 'skip_current_clean_step') node.driver_internal_info", "importutils from ironic.common import exception from ironic.common.i18n import _ from", "be empty after skipping root volume and/or non-root volumes. :raises:", "keys: driver_internal_info[key] = True task.node.driver_internal_info = driver_internal_info task.node.save() def _set_driver_internal_false_value(self,", "ilo_exception) @METRICS.timer('Ilo5RAID.delete_configuration') @base.clean_step(priority=0, abortable=False) def delete_configuration(self, task): \"\"\"Delete the RAID", "failure to execute step. \"\"\" node = task.node LOG.debug(\"OOB RAID", "configuration on node %s\") % node.uuid) self._pop_driver_internal_values(task, 'ilo_raid_create_in_progress', 'cleaning_reboot', 'skip_current_clean_step')", "'description': ( 'This specifies whether to create the root volume.", "volumes are created. If False, no non-root volumes are created.", ":param task: a TaskManager instance containing the node to act", "LOG.info(\"No logical drive found to delete on node %(node)s\", {'node':", "from oslo_utils import importutils from ironic.common import exception from ironic.common.i18n", "or was found to be empty after skipping root volume", "as ilo_exception: operation = (_(\"Failed to create raid configuration on", "\" \"Message: '%(message)s'.\", {'node': task.node.uuid, 'message': msg}) task.node.last_error = msg", "self._pop_driver_internal_values( task, 'ilo_raid_create_in_progress', 'cleaning_reboot', 'skip_current_clean_step') node.driver_internal_info = driver_internal_info node.save() else:", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR", "on failure to execute step. \"\"\" node = task.node LOG.debug(\"OOB", "# # Licensed under the Apache License, Version 2.0 (the", "= raid.filter_target_raid_config( node, create_root_volume=create_root_volume, create_nonroot_volumes=create_nonroot_volumes) driver_internal_info = node.driver_internal_info driver_internal_info['target_raid_config'] =", "driver_internal_info.get('ilo_raid_delete_in_progress'): ilo_object.delete_raid_configuration() self._prepare_for_read_raid(task, 'delete_raid') return states.CLEANWAIT else: # Raid configuration", "disks: %s\" % raid_conf['logical_disks']) self._pop_driver_internal_values( task, 'ilo_raid_delete_in_progress', 'cleaning_reboot', 'skip_current_clean_step') node.driver_internal_info", "node.driver_internal_info = driver_internal_info node.save() else: # Raid configuration failed msg", "'%(message)s'.\", {'node': task.node.uuid, 'message': msg}) task.node.last_error = msg task.process_event('fail') def", "= ( ilo_object.read_raid_configuration( raid_config=target_raid_config)) if len(raid_conf['logical_disks']): raid.update_raid_info(node, raid_conf) LOG.debug(\"Node %(uuid)s", "raid_config=target_raid_config)) if len(raid_conf['logical_disks']): raid.update_raid_info(node, raid_conf) LOG.debug(\"Node %(uuid)s raid create clean", "class Ilo5RAID(base.RAIDInterface): \"\"\"Implementation of OOB RAIDInterface for iLO5.\"\"\" def get_properties(self):", "node.save() raise exception.NodeCleaningFailure( \"Clean step delete_configuration failed \" \"on node", "driver_internal_info task.node.save() def _prepare_for_read_raid(self, task, raid_step): deploy_opts = deploy_utils.build_agent_options(task.node) task.driver.boot.prepare_ramdisk(task,", "key in keys: driver_internal_info[key] = True task.node.driver_internal_info = driver_internal_info task.node.save()", "'create_raid') return states.CLEANWAIT else: # Raid configuration is done, updating", "to create raid configuration on node %s\") % node.uuid) self._pop_driver_internal_values(task,", "delete on node %(node)s\", {'node': node.uuid}) except ilo_error.IloError as ilo_exception:", "obtain # a copy of the License at # #", "common as ilo_common LOG = logging.getLogger(__name__) CONF = conf.CONF METRICS", "'target': target_raid_config}) ilo_object = ilo_common.get_ilo_object(node) try: # Raid configuration in", "Ilo5RAID(base.RAIDInterface): \"\"\"Implementation of OOB RAIDInterface for iLO5.\"\"\" def get_properties(self): \"\"\"Return", "= driver_internal_info task.node.save() def _prepare_for_read_raid(self, task, raid_step): deploy_opts = deploy_utils.build_agent_options(task.node)", "ironic.common import states from ironic.conductor import utils as manager_utils from", "Version 2.0 (the \"License\"); you may # not use this", "ilo_object = ilo_common.get_ilo_object(node) try: # Raid configuration in progress, checking", "ilo_object.delete_raid_configuration() self._prepare_for_read_raid(task, 'delete_raid') return states.CLEANWAIT else: # Raid configuration is", "= driver_internal_info node.save() else: # Raid configuration failed msg =", "failure to execute step. \"\"\" node = task.node target_raid_config =", "'ilo_raid_create_in_progress', 'cleaning_reboot', 'skip_current_clean_step') node.driver_internal_info = driver_internal_info node.save() else: # Raid", "governing permissions and limitations # under the License. \"\"\" iLO5", "driver_internal_info node.save() raise exception.NodeCleaningFailure( \"Clean step delete_configuration failed \" \"on", "task.process_event('fail') def _set_driver_internal_true_value(self, task, *keys): driver_internal_info = task.node.driver_internal_info for key", "_set_driver_internal_false_value(self, task, *keys): driver_internal_info = task.node.driver_internal_info for key in keys:", "ironic.drivers import base from ironic.drivers.modules import deploy_utils from ironic.drivers.modules.ilo import", "'skip_current_clean_step') @METRICS.timer('Ilo5RAID.create_configuration') @base.clean_step(priority=0, abortable=False, argsinfo={ 'create_root_volume': { 'description': ( 'This", "execute step. \"\"\" node = task.node target_raid_config = raid.filter_target_raid_config( node,", "the node to act on. :raises: NodeCleaningFailure, on failure to", "from ironic.drivers.modules.ilo import common as ilo_common LOG = logging.getLogger(__name__) CONF", "% {'node': node.uuid, 'err': msg}) except ilo_error.IloLogicalDriveNotFoundError: LOG.info(\"No logical drive", "License for the specific language governing permissions and limitations #", "ilo_error.IloError as ilo_exception: operation = (_(\"Failed to delete raid configuration", "a root volume is created during RAID configuration. Otherwise, no", "# Raid configuration in progress, checking status if not driver_internal_info.get('ilo_raid_create_in_progress'):", "clean step is done.\", {'uuid': node.uuid}) self._pop_driver_internal_values( task, 'ilo_raid_create_in_progress', 'cleaning_reboot',", "on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS", "delete_configuration invoked for node %s.\", node.uuid) driver_internal_info = node.driver_internal_info ilo_object", "not len(raid_conf['logical_disks']): node.raid_config = {} LOG.debug(\"Node %(uuid)s raid delete clean", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "{ 'description': ( 'This specifies whether to create the root", "node %s.\", node.uuid) driver_internal_info = node.driver_internal_info ilo_object = ilo_common.get_ilo_object(node) try:", "{'node': node.uuid, 'target': target_raid_config}) ilo_object = ilo_common.get_ilo_object(node) try: # Raid", "oslo_log import log as logging from oslo_utils import importutils from", "= \"Unable to create raid\" self._pop_driver_internal_values( task, 'ilo_raid_create_in_progress', 'cleaning_reboot', 'skip_current_clean_step')", "a TaskManager instance. :param create_root_volume: If True, a root volume", "raid configuration on node %s\") % node.uuid) self._pop_driver_internal_values(task, 'ilo_raid_delete_in_progress', 'cleaning_reboot',", "task: a TaskManager instance containing the node to act on.", "create_nonroot_volumes: If True, non-root volumes are created. If False, no", "from oslo_log import log as logging from oslo_utils import importutils", "to create the root volume. ' 'Defaults to `True`.' ),", "%(node)s with error: %(err)s\" % {'node': node.uuid, 'err': msg}) except", "whether to create the root volume. ' 'Defaults to `True`.'", "ilo_common.get_ilo_object(node) try: # Raid configuration in progress, checking status if", "node.uuid) driver_internal_info = node.driver_internal_info ilo_object = ilo_common.get_ilo_object(node) try: # Raid", "self._set_driver_internal_true_value( task, 'ilo_raid_delete_in_progress') self._set_driver_internal_true_value(task, 'cleaning_reboot') self._set_driver_internal_false_value(task, 'skip_current_clean_step') @METRICS.timer('Ilo5RAID.create_configuration') @base.clean_step(priority=0, abortable=False,", "node %(node)s with error: %(err)s\" % {'node': node.uuid, 'err': msg})", "updating raid_config raid_conf = ilo_object.read_raid_configuration() if not len(raid_conf['logical_disks']): node.raid_config =", "found to delete on node %(node)s\", {'node': node.uuid}) except ilo_error.IloError", "'Defaults to `True`.' ), 'required': False } }) def create_configuration(self,", "specifies whether to create the root volume. ' 'Defaults to", "{'node': node.uuid, 'err': msg}) except ilo_error.IloLogicalDriveNotFoundError: LOG.info(\"No logical drive found", "task.node target_raid_config = raid.filter_target_raid_config( node, create_root_volume=create_root_volume, create_nonroot_volumes=create_nonroot_volumes) driver_internal_info = node.driver_internal_info", "), 'required': False }, 'create_nonroot_volumes': { 'description': ( 'This specifies", "len(raid_conf['logical_disks']): raid.update_raid_info(node, raid_conf) LOG.debug(\"Node %(uuid)s raid create clean step is", "Licensed under the Apache License, Version 2.0 (the \"License\"); you", "raise exception.NodeCleaningFailure( \"Clean step create_configuration failed \" \"on node %(node)s", "was found to be empty after skipping root volume and/or", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "driver_internal_info task.node.save() def _set_driver_internal_false_value(self, task, *keys): driver_internal_info = task.node.driver_internal_info for", "raid_conf = ilo_object.read_raid_configuration() if not len(raid_conf['logical_disks']): node.raid_config = {} LOG.debug(\"Node", "LP # # Licensed under the Apache License, Version 2.0", "'cleaning_reboot', 'skip_current_clean_step') node.driver_internal_info = driver_internal_info node.save() else: # Raid configuration", "for key in keys: driver_internal_info[key] = False task.node.driver_internal_info = driver_internal_info", "to `True`.' ), 'required': False }, 'create_nonroot_volumes': { 'description': (", "if node.target_raid_config is missing or was found to be empty", "failed msg = (\"Unable to delete this logical disks: %s\"", "def _pop_driver_internal_values(self, task, *keys): driver_internal_info = task.node.driver_internal_info for key in", "driver_internal_info node.save() self._set_clean_failed(task, operation, ilo_exception) @METRICS.timer('Ilo5RAID.delete_configuration') @base.clean_step(priority=0, abortable=False) def delete_configuration(self,", "compliance with the License. You may obtain # a copy", "containing the node to act on. :raises: NodeCleaningFailure, on failure", "in progress, checking status if not driver_internal_info.get('ilo_raid_delete_in_progress'): ilo_object.delete_raid_configuration() self._prepare_for_read_raid(task, 'delete_raid')", "utils as manager_utils from ironic import conf from ironic.drivers import", "def _set_clean_failed(self, task, msg, exc): LOG.error(\"RAID configuration job failed for", "ilo_error = importutils.try_import('proliantutils.exception') class Ilo5RAID(base.RAIDInterface): \"\"\"Implementation of OOB RAIDInterface for", "ironic.common import exception from ironic.common.i18n import _ from ironic.common import", "create_root_volume=create_root_volume, create_nonroot_volumes=create_nonroot_volumes) driver_internal_info = node.driver_internal_info driver_internal_info['target_raid_config'] = target_raid_config LOG.debug(\"Calling OOB", "node.uuid}) self._pop_driver_internal_values( task, 'ilo_raid_delete_in_progress', 'cleaning_reboot', 'skip_current_clean_step') node.driver_internal_info = driver_internal_info node.save()", "} }) def create_configuration(self, task, create_root_volume=True, create_nonroot_volumes=True): \"\"\"Create a RAID", "create raid configuration on node %s\") % node.uuid) self._pop_driver_internal_values(task, 'ilo_raid_create_in_progress',", "return states.CLEANWAIT else: # Raid configuration is done, updating raid_config", "if not len(raid_conf['logical_disks']): node.raid_config = {} LOG.debug(\"Node %(uuid)s raid delete", "{'node': node.uuid}) except ilo_error.IloError as ilo_exception: operation = (_(\"Failed to", "the # License for the specific language governing permissions and", "create the root volume. ' 'Defaults to `True`.' ), 'required':", "# Raid configuration is done, updating raid_config raid_conf = ilo_object.read_raid_configuration()", "# # Unless required by applicable law or agreed to", "%s\") % node.uuid) self._pop_driver_internal_values(task, 'ilo_raid_create_in_progress', 'cleaning_reboot', 'skip_current_clean_step') node.driver_internal_info = driver_internal_info", "Raid configuration is done, updating raid_config raid_conf = ilo_object.read_raid_configuration() if", "NodeCleaningFailure, on failure to execute step. \"\"\" node = task.node", "non-root volumes. ' 'Defaults to `True`.' ), 'required': False }", "node.driver_internal_info driver_internal_info['target_raid_config'] = target_raid_config LOG.debug(\"Calling OOB RAID create_configuration for node", "logical disks: %s\" % raid_conf['logical_disks']) self._pop_driver_internal_values( task, 'ilo_raid_delete_in_progress', 'cleaning_reboot', 'skip_current_clean_step')", "%s.\", node.uuid) driver_internal_info = node.driver_internal_info ilo_object = ilo_common.get_ilo_object(node) try: #", "RAID configuration: %(target)s\", {'node': node.uuid, 'target': target_raid_config}) ilo_object = ilo_common.get_ilo_object(node)", "step delete_configuration failed \" \"on node %(node)s with error: %(err)s\"", "%s\") % node.uuid) self._pop_driver_internal_values(task, 'ilo_raid_delete_in_progress', 'cleaning_reboot', 'skip_current_clean_step') node.driver_internal_info = driver_internal_info", "# Raid configuration in progress, checking status if not driver_internal_info.get('ilo_raid_delete_in_progress'):", "'cleaning_reboot') self._set_driver_internal_false_value(task, 'skip_current_clean_step') @METRICS.timer('Ilo5RAID.create_configuration') @base.clean_step(priority=0, abortable=False, argsinfo={ 'create_root_volume': { 'description':", "*keys): driver_internal_info = task.node.driver_internal_info for key in keys: driver_internal_info.pop(key, None)", "False }, 'create_nonroot_volumes': { 'description': ( 'This specifies whether to", "done.\", {'uuid': node.uuid}) self._pop_driver_internal_values( task, 'ilo_raid_create_in_progress', 'cleaning_reboot', 'skip_current_clean_step') node.driver_internal_info =", "= ilo_common.get_ilo_object(node) try: # Raid configuration in progress, checking status", "progress, checking status if not driver_internal_info.get('ilo_raid_delete_in_progress'): ilo_object.delete_raid_configuration() self._prepare_for_read_raid(task, 'delete_raid') return", "ilo_exception: operation = (_(\"Failed to delete raid configuration on node", "Otherwise, no root volume is created. Default is True. :param", "ramdisk. This method creates a RAID configuration on the given", "else: # Raid configuration failed msg = \"Unable to create", "2.0 (the \"License\"); you may # not use this file", "from ironic.drivers.modules import deploy_utils from ironic.drivers.modules.ilo import common as ilo_common", "OOB RAIDInterface for iLO5.\"\"\" def get_properties(self): \"\"\"Return the properties of", "False, no non-root volumes are created. Default is True. :raises:", "task.node.last_error = msg task.process_event('fail') def _set_driver_internal_true_value(self, task, *keys): driver_internal_info =", "'ilo_raid_create_in_progress', 'cleaning_reboot', 'skip_current_clean_step') node.driver_internal_info = driver_internal_info node.save() raise exception.NodeCleaningFailure( \"Clean", "(_(\"Failed to create raid configuration on node %s\") % node.uuid)", "= node.driver_internal_info ilo_object = ilo_common.get_ilo_object(node) try: # Raid configuration in", "as manager_utils from ironic import conf from ironic.drivers import base", "logging.getLogger(__name__) CONF = conf.CONF METRICS = metrics_utils.get_metrics_logger(__name__) ilo_error = importutils.try_import('proliantutils.exception')", "deploy_utils from ironic.drivers.modules.ilo import common as ilo_common LOG = logging.getLogger(__name__)", "'ilo_raid_delete_in_progress') self._set_driver_internal_true_value(task, 'cleaning_reboot') self._set_driver_internal_false_value(task, 'skip_current_clean_step') @METRICS.timer('Ilo5RAID.create_configuration') @base.clean_step(priority=0, abortable=False, argsinfo={ 'create_root_volume':", "deploy_opts = deploy_utils.build_agent_options(task.node) task.driver.boot.prepare_ramdisk(task, deploy_opts) manager_utils.node_power_action(task, states.REBOOT) if raid_step ==", "task): \"\"\"Delete the RAID configuration. :param task: a TaskManager instance", "task, msg, exc): LOG.error(\"RAID configuration job failed for node %(node)s.", "volumes are created. Default is True. :raises: MissingParameterValue, if node.target_raid_config", "import conf from ironic.drivers import base from ironic.drivers.modules import deploy_utils", "\"with the following target RAID configuration: %(target)s\", {'node': node.uuid, 'target':", "is done, updating raid_config raid_conf = ( ilo_object.read_raid_configuration( raid_config=target_raid_config)) if", "by applicable law or agreed to in writing, software #", "raid_conf) LOG.debug(\"Node %(uuid)s raid create clean step is done.\", {'uuid':", "'skip_current_clean_step') node.driver_internal_info = driver_internal_info node.save() raise exception.NodeCleaningFailure( \"Clean step create_configuration", "act on. :raises: NodeCleaningFailure, on failure to execute step. \"\"\"", "node.save() else: # Raid configuration failed msg = (\"Unable to", "'err': msg}) except ilo_error.IloError as ilo_exception: operation = (_(\"Failed to", "instance containing the node to act on. :raises: NodeCleaningFailure, on", "%(node)s\", {'node': node.uuid}) except ilo_error.IloError as ilo_exception: operation = (_(\"Failed", "specific methods \"\"\" from ironic_lib import metrics_utils from oslo_log import", "task.node.driver_internal_info for key in keys: driver_internal_info[key] = True task.node.driver_internal_info =", "create_nonroot_volumes=create_nonroot_volumes) driver_internal_info = node.driver_internal_info driver_internal_info['target_raid_config'] = target_raid_config LOG.debug(\"Calling OOB RAID", "invoked for node %s.\", node.uuid) driver_internal_info = node.driver_internal_info ilo_object =", "else: # Raid configuration is done, updating raid_config raid_conf =", "is created. Default is True. :param create_nonroot_volumes: If True, non-root", "<reponame>armohamm/ironic # Copyright 2018 Hewlett Packard Enterprise Development LP #", "\" \"with the following target RAID configuration: %(target)s\", {'node': node.uuid,", "BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either", "ilo_exception: operation = (_(\"Failed to create raid configuration on node", "key in keys: driver_internal_info.pop(key, None) task.node.driver_internal_info = driver_internal_info task.node.save() def", "task, 'ilo_raid_create_in_progress', 'cleaning_reboot', 'skip_current_clean_step') node.driver_internal_info = driver_internal_info node.save() raise exception.NodeCleaningFailure(", "create_configuration(self, task, create_root_volume=True, create_nonroot_volumes=True): \"\"\"Create a RAID configuration on a", "OOB RAID create_configuration for node %(node)s \" \"with the following", "'create_raid': self._set_driver_internal_true_value( task, 'ilo_raid_create_in_progress') else: self._set_driver_internal_true_value( task, 'ilo_raid_delete_in_progress') self._set_driver_internal_true_value(task, 'cleaning_reboot')", "task.node.driver_internal_info for key in keys: driver_internal_info.pop(key, None) task.node.driver_internal_info = driver_internal_info", "created. Default is True. :raises: MissingParameterValue, if node.target_raid_config is missing", "msg}) except ilo_error.IloLogicalDriveNotFoundError: LOG.info(\"No logical drive found to delete on", "to delete on node %(node)s\", {'node': node.uuid}) except ilo_error.IloError as", "limitations # under the License. \"\"\" iLO5 RAID specific methods", "= (_(\"Failed to create raid configuration on node %s\") %", "abortable=False) def delete_configuration(self, task): \"\"\"Delete the RAID configuration. :param task:", "node.uuid}) except ilo_error.IloError as ilo_exception: operation = (_(\"Failed to delete", "argsinfo={ 'create_root_volume': { 'description': ( 'This specifies whether to create", "( ilo_object.read_raid_configuration( raid_config=target_raid_config)) if len(raid_conf['logical_disks']): raid.update_raid_info(node, raid_conf) LOG.debug(\"Node %(uuid)s raid", "and limitations # under the License. \"\"\" iLO5 RAID specific", "ilo_object.read_raid_configuration( raid_config=target_raid_config)) if len(raid_conf['logical_disks']): raid.update_raid_info(node, raid_conf) LOG.debug(\"Node %(uuid)s raid create", "else: # Raid configuration failed msg = (\"Unable to delete", "LOG = logging.getLogger(__name__) CONF = conf.CONF METRICS = metrics_utils.get_metrics_logger(__name__) ilo_error", "delete_configuration(self, task): \"\"\"Delete the RAID configuration. :param task: a TaskManager", "= {} LOG.debug(\"Node %(uuid)s raid delete clean step is done.\",", "driver_internal_info node.save() raise exception.NodeCleaningFailure( \"Clean step create_configuration failed \" \"on", "not driver_internal_info.get('ilo_raid_create_in_progress'): ilo_object.create_raid_configuration(target_raid_config) self._prepare_for_read_raid(task, 'create_raid') return states.CLEANWAIT else: # Raid", "ilo_object.create_raid_configuration(target_raid_config) self._prepare_for_read_raid(task, 'create_raid') return states.CLEANWAIT else: # Raid configuration is", "try: # Raid configuration in progress, checking status if not", "may obtain # a copy of the License at #", "# Raid configuration failed msg = \"Unable to create raid\"", "step is done.\", {'uuid': node.uuid}) self._pop_driver_internal_values( task, 'ilo_raid_create_in_progress', 'cleaning_reboot', 'skip_current_clean_step')", "Unless required by applicable law or agreed to in writing,", "from ironic.common import raid from ironic.common import states from ironic.conductor", "task.node.driver_internal_info = driver_internal_info task.node.save() def _prepare_for_read_raid(self, task, raid_step): deploy_opts =", "delete raid configuration on node %s\") % node.uuid) self._pop_driver_internal_values(task, 'ilo_raid_delete_in_progress',", "node.uuid, 'err': msg}) except ilo_error.IloError as ilo_exception: operation = (_(\"Failed", "CONF = conf.CONF METRICS = metrics_utils.get_metrics_logger(__name__) ilo_error = importutils.try_import('proliantutils.exception') class", "volume and/or non-root volumes. :raises: NodeCleaningFailure, on failure to execute", "non-root volumes. :raises: NodeCleaningFailure, on failure to execute step. \"\"\"", "metrics_utils from oslo_log import log as logging from oslo_utils import", "a TaskManager instance containing the node to act on. :raises:", "checking status if not driver_internal_info.get('ilo_raid_delete_in_progress'): ilo_object.delete_raid_configuration() self._prepare_for_read_raid(task, 'delete_raid') return states.CLEANWAIT", "METRICS = metrics_utils.get_metrics_logger(__name__) ilo_error = importutils.try_import('proliantutils.exception') class Ilo5RAID(base.RAIDInterface): \"\"\"Implementation of", "applicable law or agreed to in writing, software # distributed", "from ironic.common import exception from ironic.common.i18n import _ from ironic.common", "done.\", {'uuid': node.uuid}) self._pop_driver_internal_values( task, 'ilo_raid_delete_in_progress', 'cleaning_reboot', 'skip_current_clean_step') node.driver_internal_info =", "no non-root volumes are created. Default is True. :raises: MissingParameterValue,", "{'uuid': node.uuid}) self._pop_driver_internal_values( task, 'ilo_raid_delete_in_progress', 'cleaning_reboot', 'skip_current_clean_step') node.driver_internal_info = driver_internal_info", "return ilo_common.REQUIRED_PROPERTIES def _set_clean_failed(self, task, msg, exc): LOG.error(\"RAID configuration job", "interface.\"\"\" return ilo_common.REQUIRED_PROPERTIES def _set_clean_failed(self, task, msg, exc): LOG.error(\"RAID configuration", "OF ANY KIND, either express or implied. See the #", "configuration failed msg = \"Unable to create raid\" self._pop_driver_internal_values( task,", "job failed for node %(node)s. \" \"Message: '%(message)s'.\", {'node': task.node.uuid,", "operation = (_(\"Failed to create raid configuration on node %s\")", "task, 'ilo_raid_delete_in_progress') self._set_driver_internal_true_value(task, 'cleaning_reboot') self._set_driver_internal_false_value(task, 'skip_current_clean_step') @METRICS.timer('Ilo5RAID.create_configuration') @base.clean_step(priority=0, abortable=False, argsinfo={", "'required': False } }) def create_configuration(self, task, create_root_volume=True, create_nonroot_volumes=True): \"\"\"Create", "WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express", "in writing, software # distributed under the License is distributed", "for key in keys: driver_internal_info[key] = True task.node.driver_internal_info = driver_internal_info", "a bare metal using agent ramdisk. This method creates a", "@METRICS.timer('Ilo5RAID.delete_configuration') @base.clean_step(priority=0, abortable=False) def delete_configuration(self, task): \"\"\"Delete the RAID configuration.", "keys: driver_internal_info[key] = False task.node.driver_internal_info = driver_internal_info task.node.save() def _pop_driver_internal_values(self,", "import states from ironic.conductor import utils as manager_utils from ironic", "create_root_volume=True, create_nonroot_volumes=True): \"\"\"Create a RAID configuration on a bare metal", "\"\"\"Delete the RAID configuration. :param task: a TaskManager instance containing", "updating raid_config raid_conf = ( ilo_object.read_raid_configuration( raid_config=target_raid_config)) if len(raid_conf['logical_disks']): raid.update_raid_info(node,", "False task.node.driver_internal_info = driver_internal_info task.node.save() def _pop_driver_internal_values(self, task, *keys): driver_internal_info", "driver_internal_info = task.node.driver_internal_info for key in keys: driver_internal_info[key] = False", "None) task.node.driver_internal_info = driver_internal_info task.node.save() def _prepare_for_read_raid(self, task, raid_step): deploy_opts", "= target_raid_config LOG.debug(\"Calling OOB RAID create_configuration for node %(node)s \"", "ironic import conf from ironic.drivers import base from ironic.drivers.modules import", "exc): LOG.error(\"RAID configuration job failed for node %(node)s. \" \"Message:", "for iLO5.\"\"\" def get_properties(self): \"\"\"Return the properties of the interface.\"\"\"", "'create_nonroot_volumes': { 'description': ( 'This specifies whether to create the", "root volume and/or non-root volumes. :raises: NodeCleaningFailure, on failure to", "= driver_internal_info node.save() self._set_clean_failed(task, operation, ilo_exception) @METRICS.timer('Ilo5RAID.delete_configuration') @base.clean_step(priority=0, abortable=False) def", "a RAID configuration on the given node. :param task: a", "empty after skipping root volume and/or non-root volumes. :raises: NodeCleaningFailure,", "ironic.conductor import utils as manager_utils from ironic import conf from", "= msg task.process_event('fail') def _set_driver_internal_true_value(self, task, *keys): driver_internal_info = task.node.driver_internal_info", "created. If False, no non-root volumes are created. Default is", "%(target)s\", {'node': node.uuid, 'target': target_raid_config}) ilo_object = ilo_common.get_ilo_object(node) try: #", "for node %(node)s. \" \"Message: '%(message)s'.\", {'node': task.node.uuid, 'message': msg})", "'This specifies whether to create the root volume. ' 'Defaults", "either express or implied. See the # License for the", "except ilo_error.IloError as ilo_exception: operation = (_(\"Failed to delete raid", "ilo_common LOG = logging.getLogger(__name__) CONF = conf.CONF METRICS = metrics_utils.get_metrics_logger(__name__)", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "exception.NodeCleaningFailure( \"Clean step delete_configuration failed \" \"on node %(node)s with", "status if not driver_internal_info.get('ilo_raid_create_in_progress'): ilo_object.create_raid_configuration(target_raid_config) self._prepare_for_read_raid(task, 'create_raid') return states.CLEANWAIT else:", "\"Clean step delete_configuration failed \" \"on node %(node)s with error:", "raid\" self._pop_driver_internal_values( task, 'ilo_raid_create_in_progress', 'cleaning_reboot', 'skip_current_clean_step') node.driver_internal_info = driver_internal_info node.save()", "may # not use this file except in compliance with", "# License for the specific language governing permissions and limitations", "with the License. You may obtain # a copy of", "of the interface.\"\"\" return ilo_common.REQUIRED_PROPERTIES def _set_clean_failed(self, task, msg, exc):", "MissingParameterValue, if node.target_raid_config is missing or was found to be", "configuration on a bare metal using agent ramdisk. This method", "drive found to delete on node %(node)s\", {'node': node.uuid}) except", "Development LP # # Licensed under the Apache License, Version", "you may # not use this file except in compliance", "step. \"\"\" node = task.node target_raid_config = raid.filter_target_raid_config( node, create_root_volume=create_root_volume,", "Raid configuration in progress, checking status if not driver_internal_info.get('ilo_raid_create_in_progress'): ilo_object.create_raid_configuration(target_raid_config)", "node %s\") % node.uuid) self._pop_driver_internal_values(task, 'ilo_raid_create_in_progress', 'cleaning_reboot', 'skip_current_clean_step') node.driver_internal_info =", "to create the non-root volumes. ' 'Defaults to `True`.' ),", "after skipping root volume and/or non-root volumes. :raises: NodeCleaningFailure, on", "on. :raises: NodeCleaningFailure, on failure to execute step. \"\"\" node", "task, 'ilo_raid_delete_in_progress', 'cleaning_reboot', 'skip_current_clean_step') node.driver_internal_info = driver_internal_info node.save() else: #", "' 'Defaults to `True`.' ), 'required': False }, 'create_nonroot_volumes': {", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "( 'This specifies whether to create the non-root volumes. '", "driver_internal_info = node.driver_internal_info ilo_object = ilo_common.get_ilo_object(node) try: # Raid configuration", "# WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "volume is created. Default is True. :param create_nonroot_volumes: If True,", "\"\"\"Implementation of OOB RAIDInterface for iLO5.\"\"\" def get_properties(self): \"\"\"Return the", "raise exception.NodeCleaningFailure( \"Clean step delete_configuration failed \" \"on node %(node)s", "the License is distributed on an \"AS IS\" BASIS, WITHOUT", "metrics_utils.get_metrics_logger(__name__) ilo_error = importutils.try_import('proliantutils.exception') class Ilo5RAID(base.RAIDInterface): \"\"\"Implementation of OOB RAIDInterface", "_ from ironic.common import raid from ironic.common import states from", "self._prepare_for_read_raid(task, 'create_raid') return states.CLEANWAIT else: # Raid configuration is done,", "Default is True. :raises: MissingParameterValue, if node.target_raid_config is missing or", "= metrics_utils.get_metrics_logger(__name__) ilo_error = importutils.try_import('proliantutils.exception') class Ilo5RAID(base.RAIDInterface): \"\"\"Implementation of OOB", "key in keys: driver_internal_info[key] = False task.node.driver_internal_info = driver_internal_info task.node.save()", "create the non-root volumes. ' 'Defaults to `True`.' ), 'required':", "Raid configuration failed msg = \"Unable to create raid\" self._pop_driver_internal_values(", "Packard Enterprise Development LP # # Licensed under the Apache", "raid_step == 'create_raid': self._set_driver_internal_true_value( task, 'ilo_raid_create_in_progress') else: self._set_driver_internal_true_value( task, 'ilo_raid_delete_in_progress')", "`True`.' ), 'required': False }, 'create_nonroot_volumes': { 'description': ( 'This", "create_configuration for node %(node)s \" \"with the following target RAID", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "def delete_configuration(self, task): \"\"\"Delete the RAID configuration. :param task: a", "= deploy_utils.build_agent_options(task.node) task.driver.boot.prepare_ramdisk(task, deploy_opts) manager_utils.node_power_action(task, states.REBOOT) if raid_step == 'create_raid':", "configuration on node %s\") % node.uuid) self._pop_driver_internal_values(task, 'ilo_raid_delete_in_progress', 'cleaning_reboot', 'skip_current_clean_step')", "create raid\" self._pop_driver_internal_values( task, 'ilo_raid_create_in_progress', 'cleaning_reboot', 'skip_current_clean_step') node.driver_internal_info = driver_internal_info", "import raid from ironic.common import states from ironic.conductor import utils", "ironic.drivers.modules import deploy_utils from ironic.drivers.modules.ilo import common as ilo_common LOG", "for the specific language governing permissions and limitations # under", "Hewlett Packard Enterprise Development LP # # Licensed under the", "False } }) def create_configuration(self, task, create_root_volume=True, create_nonroot_volumes=True): \"\"\"Create a", "root volume is created. Default is True. :param create_nonroot_volumes: If", "driver_internal_info node.save() else: # Raid configuration failed msg = \"Unable", "task.driver.boot.prepare_ramdisk(task, deploy_opts) manager_utils.node_power_action(task, states.REBOOT) if raid_step == 'create_raid': self._set_driver_internal_true_value( task,", "RAID delete_configuration invoked for node %s.\", node.uuid) driver_internal_info = node.driver_internal_info", "TaskManager instance. :param create_root_volume: If True, a root volume is", "raid_config raid_conf = ilo_object.read_raid_configuration() if not len(raid_conf['logical_disks']): node.raid_config = {}", "= driver_internal_info task.node.save() def _set_driver_internal_false_value(self, task, *keys): driver_internal_info = task.node.driver_internal_info", "_pop_driver_internal_values(self, task, *keys): driver_internal_info = task.node.driver_internal_info for key in keys:", "importutils.try_import('proliantutils.exception') class Ilo5RAID(base.RAIDInterface): \"\"\"Implementation of OOB RAIDInterface for iLO5.\"\"\" def", "'skip_current_clean_step') node.driver_internal_info = driver_internal_info node.save() self._set_clean_failed(task, operation, ilo_exception) @METRICS.timer('Ilo5RAID.delete_configuration') @base.clean_step(priority=0,", "self._set_driver_internal_false_value(task, 'skip_current_clean_step') @METRICS.timer('Ilo5RAID.create_configuration') @base.clean_step(priority=0, abortable=False, argsinfo={ 'create_root_volume': { 'description': (", "if not driver_internal_info.get('ilo_raid_delete_in_progress'): ilo_object.delete_raid_configuration() self._prepare_for_read_raid(task, 'delete_raid') return states.CLEANWAIT else: #", "except in compliance with the License. You may obtain #", "= False task.node.driver_internal_info = driver_internal_info task.node.save() def _pop_driver_internal_values(self, task, *keys):", "done, updating raid_config raid_conf = ilo_object.read_raid_configuration() if not len(raid_conf['logical_disks']): node.raid_config", "the given node. :param task: a TaskManager instance. :param create_root_volume:", "RAID specific methods \"\"\" from ironic_lib import metrics_utils from oslo_log", "task.node.save() def _set_driver_internal_false_value(self, task, *keys): driver_internal_info = task.node.driver_internal_info for key", "Raid configuration failed msg = (\"Unable to delete this logical", "%(err)s\" % {'node': node.uuid, 'err': msg}) except ilo_error.IloError as ilo_exception:", "{'uuid': node.uuid}) self._pop_driver_internal_values( task, 'ilo_raid_create_in_progress', 'cleaning_reboot', 'skip_current_clean_step') node.driver_internal_info = driver_internal_info", "using agent ramdisk. This method creates a RAID configuration on", "License. You may obtain # a copy of the License", "checking status if not driver_internal_info.get('ilo_raid_create_in_progress'): ilo_object.create_raid_configuration(target_raid_config) self._prepare_for_read_raid(task, 'create_raid') return states.CLEANWAIT", "methods \"\"\" from ironic_lib import metrics_utils from oslo_log import log", "ironic.drivers.modules.ilo import common as ilo_common LOG = logging.getLogger(__name__) CONF =", "msg = (\"Unable to delete this logical disks: %s\" %", "ANY KIND, either express or implied. See the # License", "# distributed under the License is distributed on an \"AS", "configuration in progress, checking status if not driver_internal_info.get('ilo_raid_create_in_progress'): ilo_object.create_raid_configuration(target_raid_config) self._prepare_for_read_raid(task,", "def _prepare_for_read_raid(self, task, raid_step): deploy_opts = deploy_utils.build_agent_options(task.node) task.driver.boot.prepare_ramdisk(task, deploy_opts) manager_utils.node_power_action(task,", "# Unless required by applicable law or agreed to in", "properties of the interface.\"\"\" return ilo_common.REQUIRED_PROPERTIES def _set_clean_failed(self, task, msg,", "task, *keys): driver_internal_info = task.node.driver_internal_info for key in keys: driver_internal_info.pop(key,", "ilo_error.IloLogicalDriveNotFoundError: LOG.info(\"No logical drive found to delete on node %(node)s\",", "'skip_current_clean_step') node.driver_internal_info = driver_internal_info node.save() raise exception.NodeCleaningFailure( \"Clean step delete_configuration", "@base.clean_step(priority=0, abortable=False) def delete_configuration(self, task): \"\"\"Delete the RAID configuration. :param", "node %(node)s \" \"with the following target RAID configuration: %(target)s\",", "ironic.common.i18n import _ from ironic.common import raid from ironic.common import", "created. Default is True. :param create_nonroot_volumes: If True, non-root volumes", "is distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES", "\"\"\" iLO5 RAID specific methods \"\"\" from ironic_lib import metrics_utils", "ironic_lib import metrics_utils from oslo_log import log as logging from", "delete this logical disks: %s\" % raid_conf['logical_disks']) self._pop_driver_internal_values( task, 'ilo_raid_delete_in_progress',", "raid_step): deploy_opts = deploy_utils.build_agent_options(task.node) task.driver.boot.prepare_ramdisk(task, deploy_opts) manager_utils.node_power_action(task, states.REBOOT) if raid_step", "configuration job failed for node %(node)s. \" \"Message: '%(message)s'.\", {'node':", "ilo_error.IloError as ilo_exception: operation = (_(\"Failed to create raid configuration", "node.uuid, 'err': msg}) except ilo_error.IloLogicalDriveNotFoundError: LOG.info(\"No logical drive found to", "during RAID configuration. Otherwise, no root volume is created. Default", "conf.CONF METRICS = metrics_utils.get_metrics_logger(__name__) ilo_error = importutils.try_import('proliantutils.exception') class Ilo5RAID(base.RAIDInterface): \"\"\"Implementation", "target_raid_config}) ilo_object = ilo_common.get_ilo_object(node) try: # Raid configuration in progress,", "LOG.error(\"RAID configuration job failed for node %(node)s. \" \"Message: '%(message)s'.\",", "agent ramdisk. This method creates a RAID configuration on the", "are created. If False, no non-root volumes are created. Default", "driver_internal_info node.save() else: # Raid configuration failed msg = (\"Unable", "task, 'ilo_raid_delete_in_progress', 'cleaning_reboot', 'skip_current_clean_step') node.driver_internal_info = driver_internal_info node.save() raise exception.NodeCleaningFailure(", "ironic.common import raid from ironic.common import states from ironic.conductor import", "on node %s\") % node.uuid) self._pop_driver_internal_values(task, 'ilo_raid_create_in_progress', 'cleaning_reboot', 'skip_current_clean_step') node.driver_internal_info", "from ironic.conductor import utils as manager_utils from ironic import conf", "status if not driver_internal_info.get('ilo_raid_delete_in_progress'): ilo_object.delete_raid_configuration() self._prepare_for_read_raid(task, 'delete_raid') return states.CLEANWAIT else:", ":param create_root_volume: If True, a root volume is created during", "configuration is done, updating raid_config raid_conf = ilo_object.read_raid_configuration() if not", "or implied. See the # License for the specific language", "raid from ironic.common import states from ironic.conductor import utils as" ]
[ "QUEUE_EVENT_IO, QUEUE_EVENT_TYPES ) from ...base.participant import ( create_singleton_identity, NOT_PARTICIPANT, )", "for bootstrap parts of an extension. This should be imported", "from ...core.shutdown.api import ( SystemShutdownEvent, as_system_shutdown_listener, SystemShutdownFinalizeEvent, as_system_shutdown_finalize_listener, TARGET_ID_SYSTEM_SHUTDOWN, )", "as_request_dispose_listener, SystemStartedEvent, as_system_started_listener, ) from ...base.events.bus import ( EventProtectionModel, GLOBAL_EVENT_PROTECTION,", "import ( # These are generally just bootstrap events. DisposeCompleteEvent,", "This should be imported along with the `simp` module. \"\"\"", "INTERNAL_EVENT_PROTECTION, PRODUCE_EVENT_PROTECTION, CONSUME_EVENT_PROTECTION, REQUEST_EVENT_PROTECTION, RESPONSE_EVENT_PROTECTION, ) from ...core.extensions.api import ANY_VERSION", "QUEUE_EVENT_HIGH, QUEUE_EVENT_IO, QUEUE_EVENT_TYPES ) from ...base.participant import ( create_singleton_identity, NOT_PARTICIPANT,", "register_event, EVENT_WILDCARD, TARGET_WILDCARD, QUEUE_EVENT_NORMAL, QUEUE_EVENT_HIGH, QUEUE_EVENT_IO, QUEUE_EVENT_TYPES ) from ...base.participant", "events. DisposeCompleteEvent, as_dispose_complete_listener, RequestDisposeEvent, as_request_dispose_listener, SystemStartedEvent, as_system_started_listener, ) from ...base.events.bus", "PRODUCE_EVENT_PROTECTION, CONSUME_EVENT_PROTECTION, REQUEST_EVENT_PROTECTION, RESPONSE_EVENT_PROTECTION, ) from ...core.extensions.api import ANY_VERSION from", "just bootstrap events. DisposeCompleteEvent, as_dispose_complete_listener, RequestDisposeEvent, as_request_dispose_listener, SystemStartedEvent, as_system_started_listener, )", "( EventBus, ListenerRegistrar, ListenerSetup, QueuePriority, ExtensionMetadataStruct, register_event, EVENT_WILDCARD, TARGET_WILDCARD, QUEUE_EVENT_NORMAL,", "import ( EventProtectionModel, GLOBAL_EVENT_PROTECTION, INTERNAL_EVENT_PROTECTION, PRODUCE_EVENT_PROTECTION, CONSUME_EVENT_PROTECTION, REQUEST_EVENT_PROTECTION, RESPONSE_EVENT_PROTECTION, )", "EventProtectionModel, GLOBAL_EVENT_PROTECTION, INTERNAL_EVENT_PROTECTION, PRODUCE_EVENT_PROTECTION, CONSUME_EVENT_PROTECTION, REQUEST_EVENT_PROTECTION, RESPONSE_EVENT_PROTECTION, ) from ...core.extensions.api", ") from ...base.events.bus import ( EventProtectionModel, GLOBAL_EVENT_PROTECTION, INTERNAL_EVENT_PROTECTION, PRODUCE_EVENT_PROTECTION, CONSUME_EVENT_PROTECTION,", "from ...core.extensions.api import ANY_VERSION from ...core.shutdown.api import ( SystemShutdownEvent, as_system_shutdown_listener,", "NOT_PARTICIPANT, ) from ...base.events import ( # These are generally", "the `simp` module. \"\"\" from ...base.bus import ( EventBus, ListenerRegistrar,", "# These are generally just bootstrap events. DisposeCompleteEvent, as_dispose_complete_listener, RequestDisposeEvent,", "from ...base.events.bus import ( EventProtectionModel, GLOBAL_EVENT_PROTECTION, INTERNAL_EVENT_PROTECTION, PRODUCE_EVENT_PROTECTION, CONSUME_EVENT_PROTECTION, REQUEST_EVENT_PROTECTION,", "parts of an extension. This should be imported along with", "TARGET_WILDCARD, QUEUE_EVENT_NORMAL, QUEUE_EVENT_HIGH, QUEUE_EVENT_IO, QUEUE_EVENT_TYPES ) from ...base.participant import (", "SystemStartedEvent, as_system_started_listener, ) from ...base.events.bus import ( EventProtectionModel, GLOBAL_EVENT_PROTECTION, INTERNAL_EVENT_PROTECTION,", "of an extension. This should be imported along with the", "ListenerRegistrar, ListenerSetup, QueuePriority, ExtensionMetadataStruct, register_event, EVENT_WILDCARD, TARGET_WILDCARD, QUEUE_EVENT_NORMAL, QUEUE_EVENT_HIGH, QUEUE_EVENT_IO,", "CONSUME_EVENT_PROTECTION, REQUEST_EVENT_PROTECTION, RESPONSE_EVENT_PROTECTION, ) from ...core.extensions.api import ANY_VERSION from ...core.shutdown.api", "along with the `simp` module. \"\"\" from ...base.bus import (", "\"\"\" from ...base.bus import ( EventBus, ListenerRegistrar, ListenerSetup, QueuePriority, ExtensionMetadataStruct,", ") from ...base.events import ( # These are generally just", "bootstrap parts of an extension. This should be imported along", "( EventProtectionModel, GLOBAL_EVENT_PROTECTION, INTERNAL_EVENT_PROTECTION, PRODUCE_EVENT_PROTECTION, CONSUME_EVENT_PROTECTION, REQUEST_EVENT_PROTECTION, RESPONSE_EVENT_PROTECTION, ) from", "`simp` module. \"\"\" from ...base.bus import ( EventBus, ListenerRegistrar, ListenerSetup,", "ANY_VERSION from ...core.shutdown.api import ( SystemShutdownEvent, as_system_shutdown_listener, SystemShutdownFinalizeEvent, as_system_shutdown_finalize_listener, TARGET_ID_SYSTEM_SHUTDOWN,", "...base.events.bus import ( EventProtectionModel, GLOBAL_EVENT_PROTECTION, INTERNAL_EVENT_PROTECTION, PRODUCE_EVENT_PROTECTION, CONSUME_EVENT_PROTECTION, REQUEST_EVENT_PROTECTION, RESPONSE_EVENT_PROTECTION,", "QUEUE_EVENT_NORMAL, QUEUE_EVENT_HIGH, QUEUE_EVENT_IO, QUEUE_EVENT_TYPES ) from ...base.participant import ( create_singleton_identity,", "from ...base.participant import ( create_singleton_identity, NOT_PARTICIPANT, ) from ...base.events import", "GLOBAL_EVENT_PROTECTION, INTERNAL_EVENT_PROTECTION, PRODUCE_EVENT_PROTECTION, CONSUME_EVENT_PROTECTION, REQUEST_EVENT_PROTECTION, RESPONSE_EVENT_PROTECTION, ) from ...core.extensions.api import", "as_system_started_listener, ) from ...base.events.bus import ( EventProtectionModel, GLOBAL_EVENT_PROTECTION, INTERNAL_EVENT_PROTECTION, PRODUCE_EVENT_PROTECTION,", "Petronia imports for bootstrap parts of an extension. This should", "from ...base.events import ( # These are generally just bootstrap", "imports for bootstrap parts of an extension. This should be", "bootstrap events. DisposeCompleteEvent, as_dispose_complete_listener, RequestDisposeEvent, as_request_dispose_listener, SystemStartedEvent, as_system_started_listener, ) from", "ExtensionMetadataStruct, register_event, EVENT_WILDCARD, TARGET_WILDCARD, QUEUE_EVENT_NORMAL, QUEUE_EVENT_HIGH, QUEUE_EVENT_IO, QUEUE_EVENT_TYPES ) from", "create_singleton_identity, NOT_PARTICIPANT, ) from ...base.events import ( # These are", "are generally just bootstrap events. DisposeCompleteEvent, as_dispose_complete_listener, RequestDisposeEvent, as_request_dispose_listener, SystemStartedEvent,", "extension. This should be imported along with the `simp` module.", "QueuePriority, ExtensionMetadataStruct, register_event, EVENT_WILDCARD, TARGET_WILDCARD, QUEUE_EVENT_NORMAL, QUEUE_EVENT_HIGH, QUEUE_EVENT_IO, QUEUE_EVENT_TYPES )", "from ...base.bus import ( EventBus, ListenerRegistrar, ListenerSetup, QueuePriority, ExtensionMetadataStruct, register_event,", "generally just bootstrap events. DisposeCompleteEvent, as_dispose_complete_listener, RequestDisposeEvent, as_request_dispose_listener, SystemStartedEvent, as_system_started_listener,", "RESPONSE_EVENT_PROTECTION, ) from ...core.extensions.api import ANY_VERSION from ...core.shutdown.api import (", "QUEUE_EVENT_TYPES ) from ...base.participant import ( create_singleton_identity, NOT_PARTICIPANT, ) from", "be imported along with the `simp` module. \"\"\" from ...base.bus", "RequestDisposeEvent, as_request_dispose_listener, SystemStartedEvent, as_system_started_listener, ) from ...base.events.bus import ( EventProtectionModel,", "EventBus, ListenerRegistrar, ListenerSetup, QueuePriority, ExtensionMetadataStruct, register_event, EVENT_WILDCARD, TARGET_WILDCARD, QUEUE_EVENT_NORMAL, QUEUE_EVENT_HIGH,", "import ( EventBus, ListenerRegistrar, ListenerSetup, QueuePriority, ExtensionMetadataStruct, register_event, EVENT_WILDCARD, TARGET_WILDCARD,", "ListenerSetup, QueuePriority, ExtensionMetadataStruct, register_event, EVENT_WILDCARD, TARGET_WILDCARD, QUEUE_EVENT_NORMAL, QUEUE_EVENT_HIGH, QUEUE_EVENT_IO, QUEUE_EVENT_TYPES", "( # These are generally just bootstrap events. DisposeCompleteEvent, as_dispose_complete_listener,", "import ( create_singleton_identity, NOT_PARTICIPANT, ) from ...base.events import ( #", "Common Petronia imports for bootstrap parts of an extension. This", "...base.events import ( # These are generally just bootstrap events.", "These are generally just bootstrap events. DisposeCompleteEvent, as_dispose_complete_listener, RequestDisposeEvent, as_request_dispose_listener,", "REQUEST_EVENT_PROTECTION, RESPONSE_EVENT_PROTECTION, ) from ...core.extensions.api import ANY_VERSION from ...core.shutdown.api import", "imported along with the `simp` module. \"\"\" from ...base.bus import", "( create_singleton_identity, NOT_PARTICIPANT, ) from ...base.events import ( # These", "DisposeCompleteEvent, as_dispose_complete_listener, RequestDisposeEvent, as_request_dispose_listener, SystemStartedEvent, as_system_started_listener, ) from ...base.events.bus import", "import ANY_VERSION from ...core.shutdown.api import ( SystemShutdownEvent, as_system_shutdown_listener, SystemShutdownFinalizeEvent, as_system_shutdown_finalize_listener,", "module. \"\"\" from ...base.bus import ( EventBus, ListenerRegistrar, ListenerSetup, QueuePriority,", "...base.participant import ( create_singleton_identity, NOT_PARTICIPANT, ) from ...base.events import (", "EVENT_WILDCARD, TARGET_WILDCARD, QUEUE_EVENT_NORMAL, QUEUE_EVENT_HIGH, QUEUE_EVENT_IO, QUEUE_EVENT_TYPES ) from ...base.participant import", ") from ...core.extensions.api import ANY_VERSION from ...core.shutdown.api import ( SystemShutdownEvent,", "\"\"\" Common Petronia imports for bootstrap parts of an extension.", "an extension. This should be imported along with the `simp`", "...base.bus import ( EventBus, ListenerRegistrar, ListenerSetup, QueuePriority, ExtensionMetadataStruct, register_event, EVENT_WILDCARD,", "should be imported along with the `simp` module. \"\"\" from", "with the `simp` module. \"\"\" from ...base.bus import ( EventBus,", "...core.extensions.api import ANY_VERSION from ...core.shutdown.api import ( SystemShutdownEvent, as_system_shutdown_listener, SystemShutdownFinalizeEvent,", ") from ...base.participant import ( create_singleton_identity, NOT_PARTICIPANT, ) from ...base.events", "as_dispose_complete_listener, RequestDisposeEvent, as_request_dispose_listener, SystemStartedEvent, as_system_started_listener, ) from ...base.events.bus import (" ]
[ "info_name != \"to_string\": info = getattr(info_cls, info_name) try: info_value =", "in [ cl.mem_flags.READ_ONLY, #cl.mem_flags.READ_WRITE, #cl.mem_flags.WRITE_ONLY ]: for itype in [", "[ cl.mem_object_type.IMAGE2D, cl.mem_object_type.IMAGE3D ]: try: formats = cl.get_supported_image_formats(ctx, mf, itype)", "\", \".join( \"{}-{}\".format( cl.channel_order.to_string(iform.channel_order, \"<unknown channel order 0x%x>\"), str_chd_type(iform.channel_data_type)) for", "\"<unknown channel order 0x%x>\"), str_chd_type(iform.channel_data_type)) for iform in formats) print(\"{}", "result = result.replace(\"FLOAT\", \"F\") return result formats = \", \".join(", "print(f\"{info_name}: {info_value}\") except: print(\"%s: <error>\" % info_name) for platform in", "try: formats = cl.get_supported_image_formats(ctx, mf, itype) except: formats = \"<error>\"", "cl.mem_object_type.IMAGE2D, cl.mem_object_type.IMAGE3D ]: try: formats = cl.get_supported_image_formats(ctx, mf, itype) except:", "in cl.get_platforms(): print(75*\"=\") print(platform) print(75*\"=\") if not options.short: print_info(platform, cl.platform_info)", "cl.Context([device]) for mf in [ cl.mem_flags.READ_ONLY, #cl.mem_flags.READ_WRITE, #cl.mem_flags.WRITE_ONLY ]: for", "options.short: print_info(platform, cl.platform_info) for device in platform.get_devices(): if not options.short:", "type %d>\") result = result.replace(\"_INT\", \"\") result = result.replace(\"UNSIGNED\", \"U\")", "in platform.get_devices(): if not options.short: print(75*\"-\") print(device) if not options.short:", "print(75*\"=\") print(platform) print(75*\"=\") if not options.short: print_info(platform, cl.platform_info) for device", "try: info_value = obj.get_info(info) except: info_value = \"<error>\" if (info_cls", "<error>\" % info_name) for platform in cl.get_platforms(): print(75*\"=\") print(platform) print(75*\"=\")", "= \"<error>\" if (info_cls == cl.device_info and info_name == \"PARTITION_TYPES_EXT\"", "formats = cl.get_supported_image_formats(ctx, mf, itype) except: formats = \"<error>\" else:", "device in platform.get_devices(): if not options.short: print(75*\"-\") print(device) if not", "property %d>\") for v in info_value])) else: try: print(f\"{info_name}: {info_value}\")", "= result.replace(\"SIGNED\", \"S\") result = result.replace(\"NORM\", \"N\") result = result.replace(\"FLOAT\",", "(options, args) = parser.parse_args() def print_info(obj, info_cls): for info_name in", "print(platform) print(75*\"=\") if not options.short: print_info(platform, cl.platform_info) for device in", "not options.short: print_info(platform, cl.platform_info) for device in platform.get_devices(): if not", "= obj.get_info(info) except: info_value = \"<error>\" if (info_cls == cl.device_info", "= \"<error>\" else: def str_chd_type(chdtype): result = cl.channel_type.to_string(chdtype, \"<unknown channel", "def str_chd_type(chdtype): result = cl.channel_type.to_string(chdtype, \"<unknown channel data type %d>\")", "cl.device_info) ctx = cl.Context([device]) for mf in [ cl.mem_flags.READ_ONLY, #cl.mem_flags.READ_WRITE,", "in [ cl.mem_object_type.IMAGE2D, cl.mem_object_type.IMAGE3D ]: try: formats = cl.get_supported_image_formats(ctx, mf,", "device properties\") (options, args) = parser.parse_args() def print_info(obj, info_cls): for", "result = result.replace(\"NORM\", \"N\") result = result.replace(\"FLOAT\", \"F\") return result", "cl.device_partition_property_ext.to_string(v, \"<unknown device partition property %d>\") for v in info_value]))", "mf in [ cl.mem_flags.READ_ONLY, #cl.mem_flags.READ_WRITE, #cl.mem_flags.WRITE_ONLY ]: for itype in", "str_chd_type(iform.channel_data_type)) for iform in formats) print(\"{} {} FORMATS: {}\\n\".format( cl.mem_object_type.to_string(itype),", "info_cls): for info_name in sorted(dir(info_cls)): if not info_name.startswith(\"_\") and info_name", "= \", \".join( \"{}-{}\".format( cl.channel_order.to_string(iform.channel_order, \"<unknown channel order 0x%x>\"), str_chd_type(iform.channel_data_type))", "(info_cls == cl.device_info and info_name == \"PARTITION_TYPES_EXT\" and isinstance(info_value, list)):", "except: formats = \"<error>\" else: def str_chd_type(chdtype): result = cl.channel_type.to_string(chdtype,", "mf, itype) except: formats = \"<error>\" else: def str_chd_type(chdtype): result", "\"S\") result = result.replace(\"NORM\", \"N\") result = result.replace(\"FLOAT\", \"F\") return", "print_info(obj, info_cls): for info_name in sorted(dir(info_cls)): if not info_name.startswith(\"_\") and", "info_name) for platform in cl.get_platforms(): print(75*\"=\") print(platform) print(75*\"=\") if not", "% info_name) for platform in cl.get_platforms(): print(75*\"=\") print(platform) print(75*\"=\") if", "0x%x>\"), str_chd_type(iform.channel_data_type)) for iform in formats) print(\"{} {} FORMATS: {}\\n\".format(", "<filename>examples/dump-properties.py import pyopencl as cl from optparse import OptionParser parser", "\"<error>\" if (info_cls == cl.device_info and info_name == \"PARTITION_TYPES_EXT\" and", "= getattr(info_cls, info_name) try: info_value = obj.get_info(info) except: info_value =", "OptionParser parser = OptionParser() parser.add_option(\"-s\", \"--short\", action=\"store_true\", help=\"don't print all", "\"to_string\": info = getattr(info_cls, info_name) try: info_value = obj.get_info(info) except:", "result = cl.channel_type.to_string(chdtype, \"<unknown channel data type %d>\") result =", "cl.platform_info) for device in platform.get_devices(): if not options.short: print(75*\"-\") print(device)", "parser.parse_args() def print_info(obj, info_cls): for info_name in sorted(dir(info_cls)): if not", "sorted(dir(info_cls)): if not info_name.startswith(\"_\") and info_name != \"to_string\": info =", "if (info_cls == cl.device_info and info_name == \"PARTITION_TYPES_EXT\" and isinstance(info_value,", "options.short: print(75*\"-\") print(device) if not options.short: print(75*\"-\") print_info(device, cl.device_info) ctx", "info_value = \"<error>\" if (info_cls == cl.device_info and info_name ==", "and info_name != \"to_string\": info = getattr(info_cls, info_name) try: info_value", "isinstance(info_value, list)): print(\"{}: {}\".format(info_name, [ cl.device_partition_property_ext.to_string(v, \"<unknown device partition property", "= cl.channel_type.to_string(chdtype, \"<unknown channel data type %d>\") result = result.replace(\"_INT\",", "print_info(device, cl.device_info) ctx = cl.Context([device]) for mf in [ cl.mem_flags.READ_ONLY,", "for v in info_value])) else: try: print(f\"{info_name}: {info_value}\") except: print(\"%s:", "obj.get_info(info) except: info_value = \"<error>\" if (info_cls == cl.device_info and", "if not options.short: print_info(platform, cl.platform_info) for device in platform.get_devices(): if", "parser.add_option(\"-s\", \"--short\", action=\"store_true\", help=\"don't print all device properties\") (options, args)", "[ cl.device_partition_property_ext.to_string(v, \"<unknown device partition property %d>\") for v in", "str_chd_type(chdtype): result = cl.channel_type.to_string(chdtype, \"<unknown channel data type %d>\") result", "info_name) try: info_value = obj.get_info(info) except: info_value = \"<error>\" if", "print(\"%s: <error>\" % info_name) for platform in cl.get_platforms(): print(75*\"=\") print(platform)", "print all device properties\") (options, args) = parser.parse_args() def print_info(obj,", "channel data type %d>\") result = result.replace(\"_INT\", \"\") result =", "{}\".format(info_name, [ cl.device_partition_property_ext.to_string(v, \"<unknown device partition property %d>\") for v", "]: for itype in [ cl.mem_object_type.IMAGE2D, cl.mem_object_type.IMAGE3D ]: try: formats", "cl.mem_object_type.IMAGE3D ]: try: formats = cl.get_supported_image_formats(ctx, mf, itype) except: formats", "if not options.short: print(75*\"-\") print_info(device, cl.device_info) ctx = cl.Context([device]) for", "and isinstance(info_value, list)): print(\"{}: {}\".format(info_name, [ cl.device_partition_property_ext.to_string(v, \"<unknown device partition", "device partition property %d>\") for v in info_value])) else: try:", "if not options.short: print(75*\"-\") print(device) if not options.short: print(75*\"-\") print_info(device,", "formats) print(\"{} {} FORMATS: {}\\n\".format( cl.mem_object_type.to_string(itype), cl.mem_flags.to_string(mf), formats)) del ctx", "for iform in formats) print(\"{} {} FORMATS: {}\\n\".format( cl.mem_object_type.to_string(itype), cl.mem_flags.to_string(mf),", "\"N\") result = result.replace(\"FLOAT\", \"F\") return result formats = \",", "cl.channel_order.to_string(iform.channel_order, \"<unknown channel order 0x%x>\"), str_chd_type(iform.channel_data_type)) for iform in formats)", "parser = OptionParser() parser.add_option(\"-s\", \"--short\", action=\"store_true\", help=\"don't print all device", "#cl.mem_flags.READ_WRITE, #cl.mem_flags.WRITE_ONLY ]: for itype in [ cl.mem_object_type.IMAGE2D, cl.mem_object_type.IMAGE3D ]:", "result = result.replace(\"_INT\", \"\") result = result.replace(\"UNSIGNED\", \"U\") result =", "iform in formats) print(\"{} {} FORMATS: {}\\n\".format( cl.mem_object_type.to_string(itype), cl.mem_flags.to_string(mf), formats))", "for device in platform.get_devices(): if not options.short: print(75*\"-\") print(device) if", "cl.device_info and info_name == \"PARTITION_TYPES_EXT\" and isinstance(info_value, list)): print(\"{}: {}\".format(info_name,", "== cl.device_info and info_name == \"PARTITION_TYPES_EXT\" and isinstance(info_value, list)): print(\"{}:", "ctx = cl.Context([device]) for mf in [ cl.mem_flags.READ_ONLY, #cl.mem_flags.READ_WRITE, #cl.mem_flags.WRITE_ONLY", "platform in cl.get_platforms(): print(75*\"=\") print(platform) print(75*\"=\") if not options.short: print_info(platform,", "\".join( \"{}-{}\".format( cl.channel_order.to_string(iform.channel_order, \"<unknown channel order 0x%x>\"), str_chd_type(iform.channel_data_type)) for iform", "not info_name.startswith(\"_\") and info_name != \"to_string\": info = getattr(info_cls, info_name)", "]: try: formats = cl.get_supported_image_formats(ctx, mf, itype) except: formats =", "for itype in [ cl.mem_object_type.IMAGE2D, cl.mem_object_type.IMAGE3D ]: try: formats =", "from optparse import OptionParser parser = OptionParser() parser.add_option(\"-s\", \"--short\", action=\"store_true\",", "== \"PARTITION_TYPES_EXT\" and isinstance(info_value, list)): print(\"{}: {}\".format(info_name, [ cl.device_partition_property_ext.to_string(v, \"<unknown", "not options.short: print(75*\"-\") print(device) if not options.short: print(75*\"-\") print_info(device, cl.device_info)", "platform.get_devices(): if not options.short: print(75*\"-\") print(device) if not options.short: print(75*\"-\")", "info_value])) else: try: print(f\"{info_name}: {info_value}\") except: print(\"%s: <error>\" % info_name)", "= result.replace(\"_INT\", \"\") result = result.replace(\"UNSIGNED\", \"U\") result = result.replace(\"SIGNED\",", "\"F\") return result formats = \", \".join( \"{}-{}\".format( cl.channel_order.to_string(iform.channel_order, \"<unknown", "= result.replace(\"NORM\", \"N\") result = result.replace(\"FLOAT\", \"F\") return result formats", "return result formats = \", \".join( \"{}-{}\".format( cl.channel_order.to_string(iform.channel_order, \"<unknown channel", "args) = parser.parse_args() def print_info(obj, info_cls): for info_name in sorted(dir(info_cls)):", "not options.short: print(75*\"-\") print_info(device, cl.device_info) ctx = cl.Context([device]) for mf", "pyopencl as cl from optparse import OptionParser parser = OptionParser()", "import pyopencl as cl from optparse import OptionParser parser =", "\"U\") result = result.replace(\"SIGNED\", \"S\") result = result.replace(\"NORM\", \"N\") result", "%d>\") result = result.replace(\"_INT\", \"\") result = result.replace(\"UNSIGNED\", \"U\") result", "partition property %d>\") for v in info_value])) else: try: print(f\"{info_name}:", "channel order 0x%x>\"), str_chd_type(iform.channel_data_type)) for iform in formats) print(\"{} {}", "else: try: print(f\"{info_name}: {info_value}\") except: print(\"%s: <error>\" % info_name) for", "for platform in cl.get_platforms(): print(75*\"=\") print(platform) print(75*\"=\") if not options.short:", "itype) except: formats = \"<error>\" else: def str_chd_type(chdtype): result =", "cl.channel_type.to_string(chdtype, \"<unknown channel data type %d>\") result = result.replace(\"_INT\", \"\")", "print(75*\"-\") print_info(device, cl.device_info) ctx = cl.Context([device]) for mf in [", "\"--short\", action=\"store_true\", help=\"don't print all device properties\") (options, args) =", "= cl.Context([device]) for mf in [ cl.mem_flags.READ_ONLY, #cl.mem_flags.READ_WRITE, #cl.mem_flags.WRITE_ONLY ]:", "\"PARTITION_TYPES_EXT\" and isinstance(info_value, list)): print(\"{}: {}\".format(info_name, [ cl.device_partition_property_ext.to_string(v, \"<unknown device", "= result.replace(\"FLOAT\", \"F\") return result formats = \", \".join( \"{}-{}\".format(", "result.replace(\"UNSIGNED\", \"U\") result = result.replace(\"SIGNED\", \"S\") result = result.replace(\"NORM\", \"N\")", "except: print(\"%s: <error>\" % info_name) for platform in cl.get_platforms(): print(75*\"=\")", "info_value = obj.get_info(info) except: info_value = \"<error>\" if (info_cls ==", "\"<unknown channel data type %d>\") result = result.replace(\"_INT\", \"\") result", "all device properties\") (options, args) = parser.parse_args() def print_info(obj, info_cls):", "cl.get_platforms(): print(75*\"=\") print(platform) print(75*\"=\") if not options.short: print_info(platform, cl.platform_info) for", "formats = \"<error>\" else: def str_chd_type(chdtype): result = cl.channel_type.to_string(chdtype, \"<unknown", "options.short: print(75*\"-\") print_info(device, cl.device_info) ctx = cl.Context([device]) for mf in", "getattr(info_cls, info_name) try: info_value = obj.get_info(info) except: info_value = \"<error>\"", "v in info_value])) else: try: print(f\"{info_name}: {info_value}\") except: print(\"%s: <error>\"", "info_name.startswith(\"_\") and info_name != \"to_string\": info = getattr(info_cls, info_name) try:", "data type %d>\") result = result.replace(\"_INT\", \"\") result = result.replace(\"UNSIGNED\",", "print(device) if not options.short: print(75*\"-\") print_info(device, cl.device_info) ctx = cl.Context([device])", "itype in [ cl.mem_object_type.IMAGE2D, cl.mem_object_type.IMAGE3D ]: try: formats = cl.get_supported_image_formats(ctx,", "= cl.get_supported_image_formats(ctx, mf, itype) except: formats = \"<error>\" else: def", "\"<unknown device partition property %d>\") for v in info_value])) else:", "if not info_name.startswith(\"_\") and info_name != \"to_string\": info = getattr(info_cls,", "print(\"{}: {}\".format(info_name, [ cl.device_partition_property_ext.to_string(v, \"<unknown device partition property %d>\") for", "print_info(platform, cl.platform_info) for device in platform.get_devices(): if not options.short: print(75*\"-\")", "formats = \", \".join( \"{}-{}\".format( cl.channel_order.to_string(iform.channel_order, \"<unknown channel order 0x%x>\"),", "action=\"store_true\", help=\"don't print all device properties\") (options, args) = parser.parse_args()", "%d>\") for v in info_value])) else: try: print(f\"{info_name}: {info_value}\") except:", "order 0x%x>\"), str_chd_type(iform.channel_data_type)) for iform in formats) print(\"{} {} FORMATS:", "and info_name == \"PARTITION_TYPES_EXT\" and isinstance(info_value, list)): print(\"{}: {}\".format(info_name, [", "cl from optparse import OptionParser parser = OptionParser() parser.add_option(\"-s\", \"--short\",", "in sorted(dir(info_cls)): if not info_name.startswith(\"_\") and info_name != \"to_string\": info", "in info_value])) else: try: print(f\"{info_name}: {info_value}\") except: print(\"%s: <error>\" %", "[ cl.mem_flags.READ_ONLY, #cl.mem_flags.READ_WRITE, #cl.mem_flags.WRITE_ONLY ]: for itype in [ cl.mem_object_type.IMAGE2D,", "#cl.mem_flags.WRITE_ONLY ]: for itype in [ cl.mem_object_type.IMAGE2D, cl.mem_object_type.IMAGE3D ]: try:", "result.replace(\"_INT\", \"\") result = result.replace(\"UNSIGNED\", \"U\") result = result.replace(\"SIGNED\", \"S\")", "cl.get_supported_image_formats(ctx, mf, itype) except: formats = \"<error>\" else: def str_chd_type(chdtype):", "\"<error>\" else: def str_chd_type(chdtype): result = cl.channel_type.to_string(chdtype, \"<unknown channel data", "= result.replace(\"UNSIGNED\", \"U\") result = result.replace(\"SIGNED\", \"S\") result = result.replace(\"NORM\",", "result.replace(\"FLOAT\", \"F\") return result formats = \", \".join( \"{}-{}\".format( cl.channel_order.to_string(iform.channel_order,", "import OptionParser parser = OptionParser() parser.add_option(\"-s\", \"--short\", action=\"store_true\", help=\"don't print", "for info_name in sorted(dir(info_cls)): if not info_name.startswith(\"_\") and info_name !=", "print(75*\"=\") if not options.short: print_info(platform, cl.platform_info) for device in platform.get_devices():", "try: print(f\"{info_name}: {info_value}\") except: print(\"%s: <error>\" % info_name) for platform", "\"{}-{}\".format( cl.channel_order.to_string(iform.channel_order, \"<unknown channel order 0x%x>\"), str_chd_type(iform.channel_data_type)) for iform in", "help=\"don't print all device properties\") (options, args) = parser.parse_args() def", "cl.mem_flags.READ_ONLY, #cl.mem_flags.READ_WRITE, #cl.mem_flags.WRITE_ONLY ]: for itype in [ cl.mem_object_type.IMAGE2D, cl.mem_object_type.IMAGE3D", "\"\") result = result.replace(\"UNSIGNED\", \"U\") result = result.replace(\"SIGNED\", \"S\") result", "= OptionParser() parser.add_option(\"-s\", \"--short\", action=\"store_true\", help=\"don't print all device properties\")", "else: def str_chd_type(chdtype): result = cl.channel_type.to_string(chdtype, \"<unknown channel data type", "result formats = \", \".join( \"{}-{}\".format( cl.channel_order.to_string(iform.channel_order, \"<unknown channel order", "print(75*\"-\") print(device) if not options.short: print(75*\"-\") print_info(device, cl.device_info) ctx =", "{info_value}\") except: print(\"%s: <error>\" % info_name) for platform in cl.get_platforms():", "result = result.replace(\"SIGNED\", \"S\") result = result.replace(\"NORM\", \"N\") result =", "result = result.replace(\"UNSIGNED\", \"U\") result = result.replace(\"SIGNED\", \"S\") result =", "info_name in sorted(dir(info_cls)): if not info_name.startswith(\"_\") and info_name != \"to_string\":", "OptionParser() parser.add_option(\"-s\", \"--short\", action=\"store_true\", help=\"don't print all device properties\") (options,", "as cl from optparse import OptionParser parser = OptionParser() parser.add_option(\"-s\",", "!= \"to_string\": info = getattr(info_cls, info_name) try: info_value = obj.get_info(info)", "for mf in [ cl.mem_flags.READ_ONLY, #cl.mem_flags.READ_WRITE, #cl.mem_flags.WRITE_ONLY ]: for itype", "result.replace(\"SIGNED\", \"S\") result = result.replace(\"NORM\", \"N\") result = result.replace(\"FLOAT\", \"F\")", "info = getattr(info_cls, info_name) try: info_value = obj.get_info(info) except: info_value", "def print_info(obj, info_cls): for info_name in sorted(dir(info_cls)): if not info_name.startswith(\"_\")", "optparse import OptionParser parser = OptionParser() parser.add_option(\"-s\", \"--short\", action=\"store_true\", help=\"don't", "properties\") (options, args) = parser.parse_args() def print_info(obj, info_cls): for info_name", "except: info_value = \"<error>\" if (info_cls == cl.device_info and info_name", "= parser.parse_args() def print_info(obj, info_cls): for info_name in sorted(dir(info_cls)): if", "result.replace(\"NORM\", \"N\") result = result.replace(\"FLOAT\", \"F\") return result formats =", "in formats) print(\"{} {} FORMATS: {}\\n\".format( cl.mem_object_type.to_string(itype), cl.mem_flags.to_string(mf), formats)) del", "info_name == \"PARTITION_TYPES_EXT\" and isinstance(info_value, list)): print(\"{}: {}\".format(info_name, [ cl.device_partition_property_ext.to_string(v,", "list)): print(\"{}: {}\".format(info_name, [ cl.device_partition_property_ext.to_string(v, \"<unknown device partition property %d>\")" ]
[ "on outer function template_dir = 'c_generated_code/{}_constraints/'.format(name) in_file = 'phi_e_constraint.in.h' out_file", "self.nlp_dims, self.nlp_in, stage, field, value_data_p) return def constraints_set(self, stage_, field_,", "nbx, regarding idxbx, ubx, lbx.') else: dims.nbx = nbx nbu", "self.shared_lib.ocp_nlp_cost_model_set(self.nlp_config, \\ self.nlp_dims, self.nlp_in, stage, field, value_data_p) return def constraints_set(self,", "is_empty(constraints.lsh): constraints.lsh = np.zeros((nsh,)) elif constraints.lsh.shape[0] != nsh: raise Exception('inconsistent", "# and/or other materials provided with the distribution. # #", "ocp_nlp_dict[acados_struct] setattr(acados_ocp, acados_struct, acados_attribute) return acados_ocp def ocp_generate_external_functions(acados_ocp, model): model", "stage_, field_, value_): \"\"\" set numerical data in the cost", "integrator type.\") if acados_ocp.solver_options.hessian_approx == 'EXACT': opts = dict(generate_hess=1) else:", "\\ self.nlp_dims, self.nlp_in, stage, field, value_data_p) return def constraints_set(self, stage_,", "elif acados_ocp.solver_options.integrator_type == 'GNSF': generate_c_code_gnsf(model) else: raise Exception(\"ocp_generate_external_functions: unknown integrator", "\\ [c_void_p, c_void_p, c_char_p, c_void_p] self.shared_lib.ocp_nlp_solver_opts_set(self.nlp_config, \\ self.nlp_opts, field, byref(value_ctypes))", "nsbu nsh = constraints.idxsh.shape[0] if is_empty(constraints.lsh): constraints.lsh = np.zeros((nsh,)) elif", "funciton with formatting for acados_struct, v in ocp_layout.items(): # skip", "\\n su: slack variables of soft upper inequality constraints \\n", "regarding idxsbx, lsbx.') if is_empty(constraints.usbx): constraints.usbx = np.zeros((nsbx,)) elif constraints.usbx.shape[0]", "time previous call 'time_lin', # cpu time for linearization 'time_sim',", "out_fields + mem_fields)) self.shared_lib.ocp_nlp_dims_get_from_attr.argtypes = \\ [c_void_p, c_void_p, c_void_p, c_int,", "c_void_p] self.shared_lib.ocp_nlp_constraints_model_set(self.nlp_config, \\ self.nlp_dims, self.nlp_in, stage, field, value_data_p) return def", "about last iteration 'stat_m', 'stat_n', ] field = field_ field", "'ext_cost_num_hess' :param value_: of appropriate size \"\"\" # cast value_", "cost.Zl.shape[0] elif cost.Zu.shape[0] != ns: wrong_field = \"Zu\" dim =", "tuple(dims): raise Exception('AcadosOcpSolver.cost_set(): mismatching dimension', \\ ' for field \"{}\"", "= '{}_external_cost.h'.format(name) render_template(in_file, out_file, template_dir, json_path) # external cost -", "json2dict(ocp_nlp_json, ocp_nlp_json['dims']) # Instantiate AcadosOcp object acados_ocp = AcadosOcp() #", "nonlinear constraints: con_r_expr but con_phi_expr is nonempty') else: dims.nr =", "the information of the last solver call: :param field_: string", "issues value_ = value_.astype(float) field = field_ field = field.encode('utf-8')", "generate_c_code_gnsf from .generate_c_code_constraint import generate_c_code_constraint from .generate_c_code_nls_cost import generate_c_code_nls_cost from", "if is_empty(constraints.lsphi_e): constraints.lsphi_e = np.zeros((nsphi_e,)) elif constraints.lsphi_e.shape[0] != nsphi_e: raise", "cost.Zu.shape[0] != ns: wrong_field = \"Zu\" dim = cost.Zu.shape[0] elif", "self.nlp_solver, field, out_data) return out # Note: this function should", "string, e.g. 'print_level', 'rti_phase', 'initialize_t_slacks', 'step_length' :param value_: of type", "can ' 'take only values 0, 1, 2 for SQP-RTI-type", "AcadosOcp from .acados_model import acados_model_strip_casadi_symbolics from .utils import is_column, is_empty,", "'BGH' and acados_ocp.dims.nh > 0: template_dir = 'c_generated_code/{}_constraints/'.format(name) in_file =", "c_int, c_char_p, c_void_p] self.shared_lib.ocp_nlp_out_set(self.nlp_config, \\ self.nlp_dims, self.nlp_out, stage, field, value_data_p)", "regarding W, cost_y_expr.') elif casadi_length(model.cost_y_expr) != ny: raise Exception('inconsistent dimension", "'make_sfun.m' render_template(in_file, out_file, template_dir, json_path) in_file = 'acados_sim_solver.in.c' out_file =", "dims.ny_e = ny_e ## constraints # initial if (constraints.lbx_0 ==", "integer corresponding to shooting node :param field_: string in ['x',", "# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF", "f'\\nGot W[{cost.W.shape}], yref[{cost.yref.shape}]\\n') dims.ny = ny elif cost.cost_type == 'NONLINEAR_LS':", "= casadi_length(model.con_phi_expr_e) if is_empty(model.con_r_expr_e): raise Exception('convex over nonlinear constraints: con_r_expr_e", "structure description ocp_layout = get_ocp_nlp_layout() # Copy input ocp object", "nsphi.\\n\\t'\\ + f'With nsbx = {nsbx}, nsbu = {nsbu}, nsg", "acados_ocp.dims.nphi > 0: # constraints on outer function template_dir =", "'make_sfun.in.m' out_file = 'make_sfun.m' render_template(in_file, out_file, template_dir, json_path) in_file =", "elif cost.zu.shape[0] != ns: wrong_field = \"zu\" dim = cost.zu.shape[0]", "self.shared_lib.acados_get_nlp_solver() self.acados_ocp = acados_ocp def solve(self): \"\"\" solve the ocp", "shooting node :param field_: string, e.g. 'yref', 'W', 'ext_cost_num_hess' :param", "model.p and parameter_values.') ## cost # path if cost.cost_type ==", "sqp_iter+1]) out = np.ascontiguousarray( np.zeros( (stat_n[0]+1, min_size[0]) ), dtype=np.float64) out_data", "in_file = 'h_e_constraint.in.h' out_file = '{}_h_e_constraint.h'.format(name) render_template(in_file, out_file, template_dir, json_path)", "time regularization 'sqp_iter', # number of SQP iterations 'statistics', #", "else: dims.np = casadi_length(model.p) if acados_ocp.parameter_values.shape[0] != dims.np: raise Exception('inconsistent", "nsbx_e: raise Exception('inconsistent dimension nsbx_e, regarding idxsbx_e, usbx_e.') dims.nsbx_e =", "cost if acados_ocp.cost.cost_type == 'EXTERNAL': template_dir = 'c_generated_code/{}_cost/'.format(name) in_file =", "!= ny or cost.Vu.shape[0] != ny: raise Exception('inconsistent dimension ny,", "if is_empty(model.cost_y_expr_e) and ny_e != 0: raise Exception('inconsistent dimension ny_e:", "EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE", "'pi', 'lam', 't'] # cast value_ to avoid conversion issues", "acados_class2dict,\\ format_class_dict, ocp_check_against_layout, np_array_to_list, make_model_consistent,\\ set_up_imported_gnsf_model def make_ocp_dims_consistent(acados_ocp): dims =", "if acados_ocp.cost.cost_type_e == 'EXTERNAL': template_dir = 'c_generated_code/{}_cost/'.format(name) in_file = 'external_cost_e.in.h'", "= 'Makefile' render_template(in_file, out_file, template_dir, json_path) in_file = 'acados_solver_sfun.in.c' out_file", "if constraints.ubu.shape[0] != nbu or constraints.lbu.shape[0] != nbu: raise Exception('inconsistent", "= \\ [c_void_p, c_void_p, c_void_p, c_int, c_char_p, POINTER(c_int)] self.shared_lib.ocp_nlp_constraint_dims_get_from_attr.restype =", "json_file=json_file) if not os.path.exists(json_path): raise Exception('{} not found!'.format(json_path)) template_dir =", "def constraints_set(self, stage_, field_, value_): \"\"\" set numerical data in", "idxsphi_e, usphi_e.') dims.nsphi_e = nsphi_e # terminal ns_e = nsbx_e", "terminal constraints on outer function template_dir = 'c_generated_code/{}_constraints/'.format(name) in_file =", "list of conditions and the following disclaimer. # # 2.", "field_): \"\"\" get the information of the last solver call:", "elif constraints.ush.shape[0] != nsh: raise Exception('inconsistent dimension nsh, regarding idxsh,", "0) if value_shape != tuple(dims): raise Exception('AcadosOcpSolver.cost_set(): mismatching dimension', \\", "over nonlinear function if acados_ocp.constraints.constr_type_e == 'BGP' and acados_ocp.dims.nphi_e >", "constraints.ubx_0.shape if not this_shape == other_shape: raise Exception('lbx_0, ubx_0 have", "Exception('solver option {} must be of type str. You have", "c_void_p self.nlp_solver = self.shared_lib.acados_get_nlp_solver() self.acados_ocp = acados_ocp def solve(self): \"\"\"", "'h_e_constraint.in.h' out_file = '{}_h_e_constraint.h'.format(name) render_template(in_file, out_file, template_dir, json_path) # nonlinear", "self.nlp_dims, self.nlp_out, stage, field, value_data_p) return def cost_set(self, stage_, field_,", "have {}.'.format(field_, type(value_))) else: value_ctypes = c_int(value_) elif field_ in", "self.acados_ocp.solver_options.nlp_solver_type == 'SQP_RTI': print('\\niter\\tqp_stat\\tqp_iter') if stat.shape[0]>3: print('\\tqp_res_stat\\tqp_res_eq\\tqp_res_ineq\\tqp_res_comp') for jj in", "for inequalities \\n t: slack variables corresponding to evaluation of", "# number of SQP iterations 'statistics', # table with info", "\"Zu\" dim = cost.Zu.shape[0] elif cost.zl.shape[0] != ns: wrong_field =", "generate_c_code_gnsf(model) else: raise Exception(\"ocp_generate_external_functions: unknown integrator type.\") if acados_ocp.solver_options.hessian_approx ==", "field = field_ field = field.encode('utf-8') if (field_ not in", "is_empty(model.con_h_expr): nh = casadi_length(model.con_h_expr) else: nh = 0 if constraints.uh.shape[0]", "[c_void_p, c_void_p, c_void_p, c_int, c_char_p] self.shared_lib.ocp_nlp_dims_get_from_attr.restype = c_int dims =", "cost # path if cost.cost_type == 'LINEAR_LS': ny = cost.W.shape[0]", "= CDLL(self.shared_lib_name) self.shared_lib.acados_create() self.solver_created = True self.shared_lib.acados_get_nlp_opts.restype = c_void_p self.nlp_opts", "0 for SQP-type solvers') field = field_ field = field.encode('utf-8')", "self.shared_lib.acados_update_params.argtypes = [c_int, POINTER(c_double)] self.shared_lib.acados_update_params.restype = c_int value_data = cast(value_.ctypes.data,", "# terminal nbx_e = constraints.idxbx_e.shape[0] if constraints.ubx_e.shape[0] != nbx_e or", "f, default=np_array_to_list, indent=4, sort_keys=True) def ocp_formulation_json_load(json_file='acados_ocp_nlp.json'): # Load acados_ocp_nlp structure", "ny # terminal if cost.cost_type_e == 'LINEAR_LS': ny_e = cost.W_e.shape[0]", "raise Exception('inconsistent dimension np, regarding model.p and parameter_values.') ## cost", "have nu columns.') if cost.yref.shape[0] != ny: raise Exception('inconsistent dimension:", "+ nsg + nsphi wrong_field = \"\" if cost.Zl.shape[0] !=", "!= nsbx: raise Exception('inconsistent dimension nsbx, regarding idxsbx, usbx.') dims.nsbx", "acados_ocp.model.name # setting up loader and environment json_path = '{cwd}/{json_file}'.format(", "field_ field = field.encode('utf-8') if (field_ not in out_fields +", "c_void_p, c_char_p, c_char_p] self.shared_lib.ocp_nlp_solver_opts_set(self.nlp_config, \\ self.nlp_opts, field, value_ctypes) else: self.shared_lib.ocp_nlp_solver_opts_set.argtypes", "= self.shared_lib.ocp_nlp_dims_get_from_attr(self.nlp_config, \\ self.nlp_dims, self.nlp_out, stage_, field) out = np.ascontiguousarray(np.zeros((dims,)),", "should be column vector!') # nu if is_empty(model.u): dims.nu =", "if cost.Zl.shape[0] != ns: wrong_field = \"Zl\" dim = cost.Zl.shape[0]", "# Slack dimensions nsbx = constraints.idxsbx.shape[0] if is_empty(constraints.lsbx): constraints.lsbx =", "= {nsh}, nsphi = {nsphi}') dims.ns = ns nsbx_e =", "constraints: con_r_expr but con_phi_expr is nonempty') else: dims.nr = casadi_length(model.con_r_expr)", "constraints_set def set(self, stage_, field_, value_): cost_fields = ['y_ref', 'yref']", "{wrong_field}, with dimension {dim}, \\n\\t'\\ + f'Detected ns_e = {ns_e}", "json_path) in_file = 'acados_sim_solver.in.h' out_file = 'acados_sim_solver_{}.h'.format(name) render_template(in_file, out_file, template_dir,", "out_file = 'acados_solver_{}.h'.format(name) render_template(in_file, out_file, template_dir, json_path) in_file = 'Makefile.in'", "and binary forms, with or without # modification, are permitted", "cost.cost_type_e == 'NONLINEAR_LS': ny_e = cost.W_e.shape[0] if is_empty(model.cost_y_expr_e) and ny_e", "or value_ > 2: raise Exception('AcadosOcpSolver.solve(): argument \\'rti_phase\\' can '", "nbx or constraints.lbx.shape[0] != nbx: raise Exception('inconsistent dimension nbx, regarding", "# <NAME>, <NAME>, <NAME>, <NAME>, <NAME> # # This file", "np.zeros((nsh,)) elif constraints.ush.shape[0] != nsh: raise Exception('inconsistent dimension nsh, regarding", "c_void_p, c_void_p, c_int, c_char_p, c_void_p] self.shared_lib.ocp_nlp_constraints_model_set(self.nlp_config, \\ self.nlp_dims, self.nlp_in, stage,", "ny, regarding W, Vx, Vu.' + \\ f'\\nGot W[{cost.W.shape}], Vx[{cost.Vx.shape}],", "= 'acados_solver_{}.c'.format(name) render_template(in_file, out_file, template_dir, json_path) in_file = 'acados_solver.in.h' out_file", "should have nu columns.') if cost.yref.shape[0] != ny: raise Exception('inconsistent", "\\ stat[3][jj], stat[4][jj], int(stat[5][jj]), int(stat[6][jj]))) if stat.shape[0]>7: print('\\t{:e}\\t{:e}\\t{:e}\\t{:e}'.format( \\ stat[7][jj],", "iteration 'stat_m', 'stat_n', ] field = field_ field = field.encode('utf-8')", ":param field_: string in ['x', 'u', 'z', 'pi', 'lam', 't',", "have {})'.format(dims, value_.shape[0]) raise Exception(msg) value_data = cast(value_.ctypes.data, POINTER(c_double)) value_data_p", "raise Exception('inconsistent dimension nsbx, regarding idxsbx, lsbx.') if is_empty(constraints.usbx): constraints.usbx", "int_fields: if not isinstance(value_, int): raise Exception('solver option {} must", "# Copy input ocp object dictionary ocp_nlp_dict = dict(deepcopy(acados_ocp).__dict__) #", "SQP iterations 'statistics', # table with info about last iteration", "of source code must retain the above copyright notice, #", "nsbx_e + nsh_e + nsg_e + nsphi_e wrong_field = \"\"", "ocp_formulation_json_dump(acados_ocp, json_file) # render templates ocp_render_templates(acados_ocp, json_file) ## Compile solver", "else: value_ctypes = c_int(value_) elif field_ in double_fields: if not", "raise Exception('inconsistent dimension: Vx should have nx columns.') if cost.Vu.shape[1]", "self.shared_lib # NOTE: DLL cannot be easily unloaded!!! # see", "Exception('inconsistent dimension N, regarding shooting_nodes.') time_steps = np.zeros((dims.N,)) for i", "if acados_ocp.solver_options.integrator_type == 'ERK': # explicit model -- generate C", "stage_, field, out_data) return out def print_statistics(self): stat = self.get_stats(\"statistics\")", "'EXACT': opts = dict(generate_hess=1) else: opts = dict(generate_hess=0) if acados_ocp.dims.nphi", "Exception(f'Inconsistent discretization: {opts.tf}'\\ f' = tf != sum(opts.time_steps) = {tf}.')", "== 'NONLINEAR_LS': generate_c_code_nls_cost(model, model.name, False) elif acados_ocp.cost.cost_type == 'EXTERNAL': generate_c_code_external_cost(model,", "print('\\tqp_res_stat\\tqp_res_eq\\tqp_res_ineq\\tqp_res_comp') for jj in range(stat.shape[1]): print('{:d}\\t{:d}\\t{:d}'.format( int(stat[0][jj]), int(stat[1][jj]), int(stat[2][jj]))) if", "have nx columns.') if cost.yref_e.shape[0] != ny_e: raise Exception('inconsistent dimension:", "not is_empty(opts.shooting_nodes): if np.shape(opts.shooting_nodes)[0] != dims.N+1: raise Exception('inconsistent dimension N,", "if (tf - opts.tf) / tf > 1e-15: raise Exception(f'Inconsistent", "dictionary ocp_nlp_dict = dict(deepcopy(acados_ocp).__dict__) # TODO: maybe make one funciton", "if not isinstance(value_, float): raise Exception('solver option {} must be", "if stat.shape[0]>7: print('\\tqp_res_stat\\tqp_res_eq\\tqp_res_ineq\\tqp_res_comp') for jj in range(stat.shape[1]): print('{:d}\\t{:e}\\t{:e}\\t{:e}\\t{:e}\\t{:d}\\t{:d}'.format( \\ int(stat[0][jj]),", "dims.nsh_e = nsh_e nsg_e = constraints.idxsg_e.shape[0] if is_empty(constraints.lsg_e): constraints.lsg_e =", "GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR", "WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF", "import sys, os, json import numpy as np from ctypes", "= constraints.lbx_0.shape other_shape = constraints.ubx_0.shape if not this_shape == other_shape:", "elif field_ in string_fields: if not isinstance(value_, str): raise Exception('solver", "is_column(constraints.lbx_0): raise Exception('lbx_0, ubx_0 must be column vectors!') dims.nbx_0 =", "dims.nz != 0 and cost.Vz.shape[0] != ny: raise Exception('inconsistent dimension", "dims.nbx = nbx nbu = constraints.idxbu.shape[0] if constraints.ubu.shape[0] != nbu", "def options_set(self, field_, value_): \"\"\" set options of the solver:", "0 and cost.Vz.shape[0] != ny: raise Exception('inconsistent dimension ny, regarding", "] field = field_ field = field.encode('utf-8') if (field_ not", ".generate_c_code_gnsf import generate_c_code_gnsf from .generate_c_code_constraint import generate_c_code_constraint from .generate_c_code_nls_cost import", "BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,", "= 'acados_sim_solver_{}.h'.format(name) render_template(in_file, out_file, template_dir, json_path) ## folder model template_dir", "stage_, field_): \"\"\" get the last solution of the solver:", "raise Exception('inconsistent dimension: regarding W_e, yref_e.') dims.ny_e = ny_e elif", "!= dims.nx and ny != 0: raise Exception('inconsistent dimension: Vx", "= ['x', 'u', 'z', 'pi', 'lam', 't'] mem_fields = ['sl',", "= field.encode('utf-8') stage = c_int(stage_) # treat parameters separately if", "mismatching dimension' \\ ' for field \"{}\" with dimension {}", "!= 0: raise Exception('inconsistent dimension: Vu should have nu columns.')", "\\ or constraints.D.shape[0] != ng: raise Exception('inconsistent dimension ng, regarding", "node :param field_: string, e.g. 'yref', 'W', 'ext_cost_num_hess' :param value_:", "generate_c_code_external_cost from .acados_ocp import AcadosOcp from .acados_model import acados_model_strip_casadi_symbolics from", "THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS", "= 'main_{}.c'.format(name) render_template(in_file, out_file, template_dir, json_path) in_file = 'acados_solver.in.c' out_file", "size for field {wrong_field}, with dimension {dim}, \\n\\t'\\ + f'Detected", "and ny_e != 0: raise Exception('inconsistent dimension: Vx_e should have", "' for field \"{}\" with dimension {} (you have {})'.format(", "= casadi_length(model.x) else: raise Exception('model.x should be column vector!') #", "if constraints.uh_e.shape[0] != nh_e or constraints.lh_e.shape[0] != nh_e: raise Exception('inconsistent", "acados_ocp.solver_options.time_steps[0] # generate external functions ocp_generate_external_functions(acados_ocp, model) # dump to", "of external function calls 'time_sim_la', # cpu time for integrator", "[c_void_p, c_void_p, c_void_p, c_int, c_char_p, c_void_p] self.shared_lib.ocp_nlp_out_set(self.nlp_config, \\ self.nlp_dims, self.nlp_out,", "constraints_fields = ['lbx', 'ubx', 'lbu', 'ubu'] out_fields = ['x', 'u',", "int, float \"\"\" int_fields = ['print_level', 'rti_phase', 'initialize_t_slacks'] double_fields =", "TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR", "ny != 0: raise Exception('inconsistent dimension: Vx should have nx", "Exception('inconsistent dimension nsbx_e, regarding idxsbx_e, lsbx_e.') if is_empty(constraints.usbx_e): constraints.usbx_e =", "# nz if is_empty(model.z): dims.nz = 0 else: dims.nz =", "get_ocp_nlp_layout() with open(json_file, 'r') as f: ocp_nlp_json = json.load(f) ocp_nlp_dict", "dims.ng_e = ng_e if not is_empty(model.con_h_expr_e): nh_e = casadi_length(model.con_h_expr_e) else:", "'acados_sim_solver_{}.h'.format(name) render_template(in_file, out_file, template_dir, json_path) ## folder model template_dir =", "# Load acados_ocp_nlp structure description ocp_layout = get_ocp_nlp_layout() # Copy", "!= nbx or constraints.lbx.shape[0] != nbx: raise Exception('inconsistent dimension nbx,", "in out_fields + mem_fields): raise Exception('AcadosOcpSolver.get(): {} is an invalid", "can ' 'take only value 0 for SQP-type solvers') field", "return def __del__(self): if self.solver_created: self.shared_lib.acados_free() del self.shared_lib # NOTE:", "in_file = 'external_cost.in.h' out_file = '{}_external_cost.h'.format(name) render_template(in_file, out_file, template_dir, json_path)", "last iteration 'stat_m', 'stat_n', ] field = field_ field =", "regarding lam, t: \\n the inequalities are internally organized in", "W, Vx, Vu.' + \\ f'\\nGot W[{cost.W.shape}], Vx[{cost.Vx.shape}], Vu[{cost.Vu.shape}]\\n') if", "== 'ERK': # explicit model -- generate C code generate_c_code_explicit_ode(model)", "template_dir, json_path) # terminal constraints on convex over nonlinear function", "or constraints.D.shape[0] != ng: raise Exception('inconsistent dimension ng, regarding lg,", "type str. You have {}.'.format(field_, type(value_))) else: value_ctypes = value_.encode('utf-8')", "acados_ocp.__dict__ = ocp_nlp_dict # laod class attributes dict, dims, constraints,", "{nsg_e}, nsh_e = {nsh_e}, nsphi_e = {nsphi_e}') dims.ns_e = ns_e", "= \"\" if cost.Zl_e.shape[0] != ns_e: wrong_field = \"Zl_e\" dim", "elif field_ in double_fields: if not isinstance(value_, float): raise Exception('solver", "if acados_ocp.cost.cost_type_e == 'NONLINEAR_LS': generate_c_code_nls_cost(model, model.name, True) elif acados_ocp.cost.cost_type_e ==", "[] and constraints.ubx_0 == []): dims.nbx_0 = 0 else: this_shape", "acados_ocp = AcadosOcp() # load class dict acados_ocp.__dict__ = ocp_nlp_dict", "!= \"\": raise Exception(f'Inconsistent size for field {wrong_field}, with dimension", "raise Exception('inconsistent dimension nsh_e, regarding idxsh_e, ush_e.') dims.nsh_e = nsh_e", "constraints.lsh.shape[0] != nsh: raise Exception('inconsistent dimension nsh, regarding idxsh, lsh.')", "self.shared_lib.acados_get_nlp_solver.restype = c_void_p self.nlp_solver = self.shared_lib.acados_get_nlp_solver() self.acados_ocp = acados_ocp def", "the last solution of the solver: :param stage: integer corresponding", "column vector!') # nu if is_empty(model.u): dims.nu = 0 else:", "'c_generated_code/{}_cost/'.format(name) in_file = 'cost_y_e_fun.in.h' out_file = '{}_cost_y_e_fun.h'.format(name) render_template(in_file, out_file, template_dir,", "opts.tf) / tf > 1e-15: raise Exception(f'Inconsistent discretization: {opts.tf}'\\ f'", "# set integrator time automatically acados_ocp.solver_options.Tsim = acados_ocp.solver_options.time_steps[0] # generate", "= cost.Zu.shape[0] elif cost.zl.shape[0] != ns: wrong_field = \"zl\" dim", "= 'c_generated_code/{}_constraints/'.format(name) in_file = 'phi_e_constraint.in.h' out_file = '{}_phi_e_constraint.h'.format(name) render_template(in_file, out_file,", "nsh_e: raise Exception('inconsistent dimension nsh_e, regarding idxsh_e, ush_e.') dims.nsh_e =", "ocp_nlp_json['dims']) # Instantiate AcadosOcp object acados_ocp = AcadosOcp() # load", "Redistributions of source code must retain the above copyright notice,", "tf > 1e-15: raise Exception(f'Inconsistent discretization: {opts.tf}'\\ f' = tf", "Function, SX from copy import deepcopy from .generate_c_code_explicit_ode import generate_c_code_explicit_ode", "\\'rti_phase\\' can ' 'take only value 0 for SQP-type solvers')", "out_file, template_dir, json_path) ## folder model template_dir = 'c_generated_code/{}_model/'.format(name) in_file", "elif field_ in mem_fields: self.shared_lib.ocp_nlp_get_at_stage.argtypes = \\ [c_void_p, c_void_p, c_void_p,", "parameter_values.') ## cost # path if cost.cost_type == 'LINEAR_LS': ny", "<NAME>, <NAME>, <NAME>, # <NAME>, <NAME>, <NAME>, <NAME>, # <NAME>,", "object acados_ocp = AcadosOcp() # load class dict acados_ocp.__dict__ =", "'time_lin', 'time_sim', 'time_sim_ad', 'time_sim_la', 'time_qp', 'time_qp_solver_call', 'time_reg', 'sqp_iter'] \"\"\" fields", "if is_empty(model.z): dims.nz = 0 else: dims.nz = casadi_length(model.z) #", "HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN", "# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT", "ocp object attributes dictionaries ocp_nlp_dict[acados_struct]=dict(getattr(acados_ocp, acados_struct).__dict__) ocp_nlp_dict = format_class_dict(ocp_nlp_dict) #", "tuple(dims), value_shape)) value_data = cast(value_.ctypes.data, POINTER(c_double)) value_data_p = cast((value_data), c_void_p)", "t: \\n the inequalities are internally organized in the following", "ocp_layout = get_ocp_nlp_layout() with open(json_file, 'r') as f: ocp_nlp_json =", "ocp_nlp_dict = dict(deepcopy(acados_ocp).__dict__) # TODO: maybe make one funciton with", "f: json.dump(ocp_nlp_dict, f, default=np_array_to_list, indent=4, sort_keys=True) def ocp_formulation_json_load(json_file='acados_ocp_nlp.json'): # Load", "cost.zl_e.shape[0] elif cost.zu_e.shape[0] != ns_e: wrong_field = \"zu_e\" dim =", "constraints.usbx_e.shape[0] != nsbx_e: raise Exception('inconsistent dimension nsbx_e, regarding idxsbx_e, usbx_e.')", "outer function template_dir = 'c_generated_code/{}_constraints/'.format(name) in_file = 'phi_e_constraint.in.h' out_file =", "Vu, Vz.' + \\ f'\\nGot W[{cost.W.shape}], Vx[{cost.Vx.shape}], Vu[{cost.Vu.shape}], Vz[{cost.Vz.shape}]\\n') if", "np.zeros((acados_ocp.dims.ny_e, acados_ocp.dims.nx)) if acados_ocp.cost.cost_type == 'NONLINEAR_LS': generate_c_code_nls_cost(model, model.name, False) elif", "node :param field_: string, e.g. 'lbx' :param value_: of appropriate", "if self.solver_created: self.shared_lib.acados_free() del self.shared_lib # NOTE: DLL cannot be", "model.name, False, opts) if acados_ocp.dims.nphi_e > 0 or acados_ocp.dims.nh_e >", "opts = dict(generate_hess=1) generate_c_code_implicit_ode(model, opts) elif acados_ocp.solver_options.integrator_type == 'GNSF': generate_c_code_gnsf(model)", "self.shared_lib.ocp_nlp_get(self.nlp_config, self.nlp_solver, field, out_data) return out # Note: this function", "os.path.dirname(current_module.__file__) with open(acados_path + '/acados_layout.json', 'r') as f: ocp_nlp_layout =", "not a valid argument.\\ \\nPossible values are {}. Exiting.\".format(field, \\", "'AcadosOcpSolver.set(): mismatching dimension for field \"{}\" '.format(field_) msg += 'with", "from copy import deepcopy from .generate_c_code_explicit_ode import generate_c_code_explicit_ode from .generate_c_code_implicit_ode", "dims_dict) with open(json_file, 'w') as f: json.dump(ocp_nlp_dict, f, default=np_array_to_list, indent=4,", "+ nsbu + nsh + nsg + nsphi wrong_field =", "(you have {})'.format( \\ field_, tuple(dims), value_shape)) value_data = cast(value_.ctypes.data,", "value_.shape if len(value_shape) == 1: value_shape = (value_shape[0], 0) if", "\"Zl\" dim = cost.Zl.shape[0] elif cost.Zu.shape[0] != ns: wrong_field =", "if is_empty(constraints.ush_e): constraints.ush_e = np.zeros((nsh_e,)) elif constraints.ush_e.shape[0] != nsh_e: raise", "c_void_p] self.shared_lib.ocp_nlp_get(self.nlp_config, self.nlp_solver, field, out_data) return out # Note: this", "in the constraint module of the solver: Parameters: :param stage_:", "constraints.uh_e.shape[0] != nh_e or constraints.lh_e.shape[0] != nh_e: raise Exception('inconsistent dimension", "out_file, template_dir, json_path) # constraints on convex over nonlinear function", "field_: string, e.g. 'yref', 'W', 'ext_cost_num_hess' :param value_: of appropriate", "Vx, Vu, Vz.' + \\ f'\\nGot W[{cost.W.shape}], Vx[{cost.Vx.shape}], Vu[{cost.Vu.shape}], Vz[{cost.Vz.shape}]\\n')", "open(json_file, 'w') as f: json.dump(ocp_nlp_dict, f, default=np_array_to_list, indent=4, sort_keys=True) def", "be column vectors!') dims.nbx_0 = constraints.lbx_0.size if all(constraints.lbx_0 == constraints.ubx_0):", "clean_ocp_shared_lib') os.system('make ocp_shared_lib') os.chdir('..') self.shared_lib_name = 'c_generated_code/libacados_ocp_solver_' + model.name +", "POINTER(c_double)] self.shared_lib.acados_update_params.restype = c_int value_data = cast(value_.ctypes.data, POINTER(c_double)) self.shared_lib.acados_update_params(stage, value_data,", "if is_empty(constraints.usphi): constraints.usphi = np.zeros((nsphi,)) elif constraints.usphi.shape[0] != nsphi: raise", "= {nsbx}, nsbu = {nsbu}, nsg = {nsg}, nsh =", "raise Exception('inconsistent dimension: regarding W, yref.' + \\ f'\\nGot W[{cost.W.shape}],", "casadi_length(model.con_h_expr) else: nh = 0 if constraints.uh.shape[0] != nh or", "OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE", "+ out_fields: raise Exception(\"AcadosOcpSolver.set(): {} is not a valid argument.\\", "self.shared_lib.ocp_nlp_out_set.argtypes = \\ [c_void_p, c_void_p, c_void_p, c_int, c_char_p, c_void_p] self.shared_lib.ocp_nlp_out_set(self.nlp_config,", "# Instantiate AcadosOcp object acados_ocp = AcadosOcp() # load class", "c_char_p] self.shared_lib.ocp_nlp_solver_opts_set(self.nlp_config, \\ self.nlp_opts, field, value_ctypes) else: self.shared_lib.ocp_nlp_solver_opts_set.argtypes = \\", "= field.encode('utf-8') stage = c_int(stage_) self.shared_lib.ocp_nlp_constraint_dims_get_from_attr.argtypes = \\ [c_void_p, c_void_p,", "!= ng or constraints.C.shape[0] != ng \\ or constraints.D.shape[0] !=", "json.load(f) ocp_nlp_dict = json2dict(ocp_nlp_json, ocp_nlp_json['dims']) # Instantiate AcadosOcp object acados_ocp", "Vu[{cost.Vu.shape}], Vz[{cost.Vz.shape}]\\n') if cost.Vx.shape[1] != dims.nx and ny != 0:", "if len(value_shape) == 1: value_shape = (value_shape[0], 0) if value_shape", "\\ self.nlp_dims, self.nlp_out, stage_, field, out_data) elif field_ in mem_fields:", "np.ascontiguousarray(np.zeros((2,)), dtype=np.intc) dims_data = cast(dims.ctypes.data, POINTER(c_int)) self.shared_lib.ocp_nlp_constraint_dims_get_from_attr(self.nlp_config, \\ self.nlp_dims, self.nlp_out,", "POINTER(c_double)) value_data_p = cast((value_data), c_void_p) self.shared_lib.ocp_nlp_constraints_model_set.argtypes = \\ [c_void_p, c_void_p,", "\\ self.nlp_opts, field, byref(value_ctypes)) return def __del__(self): if self.solver_created: self.shared_lib.acados_free()", "field_ in double_fields: if not isinstance(value_, float): raise Exception('solver option", "> 0 or acados_ocp.dims.nh > 0: generate_c_code_constraint(model, model.name, False, opts)", "constraints.ubx_0): dims.nbxe_0 = dims.nbx_0 # path nbx = constraints.idxbx.shape[0] if", "!= nsh_e: raise Exception('inconsistent dimension nsh_e, regarding idxsh_e, ush_e.') dims.nsh_e", "f: ocp_nlp_layout = json.load(f) return ocp_nlp_layout def ocp_formulation_json_dump(acados_ocp, json_file='acados_ocp_nlp.json'): #", "regarding idxsg, lsg.') if is_empty(constraints.usg): constraints.usg = np.zeros((nsg,)) elif constraints.usg.shape[0]", "'GNSF': generate_c_code_gnsf(model) else: raise Exception(\"ocp_generate_external_functions: unknown integrator type.\") if acados_ocp.solver_options.hessian_approx", "Render templates in_file = 'main.in.c' out_file = 'main_{}.c'.format(name) render_template(in_file, out_file,", "= (value_shape[0], 0) if value_shape != tuple(dims): raise Exception('AcadosOcpSolver.constraints_set(): mismatching", "value_data_p) return def constraints_set(self, stage_, field_, value_): \"\"\" set numerical", "of the solver: Parameters: :param stage_: integer corresponding to shooting", "in_file = 'h_constraint.in.h' out_file = '{}_h_constraint.h'.format(name) render_template(in_file, out_file, template_dir, json_path)", "# TODO: maybe make one funciton with formatting for acados_struct,", "lbx_e.') else: dims.nbx_e = nbx_e ng_e = constraints.lg_e.shape[0] if constraints.ug_e.shape[0]", "Exception('inconsistent dimension ny_e: regarding W_e, cost_y_expr_e.' + \\ f'\\nGot W_e[{cost.W_e.shape}],", "constraints.idxsbu.shape[0] if is_empty(constraints.lsbu): constraints.lsbu = np.zeros((nsbu,)) elif constraints.lsbu.shape[0] != nsbu:", "= \\ [c_void_p, c_void_p, c_void_p, c_int, c_char_p] self.shared_lib.ocp_nlp_dims_get_from_attr.restype = c_int", "if self.acados_ocp.solver_options.nlp_solver_type == 'SQP': print('\\niter\\tres_stat\\tres_eq\\t\\tres_ineq\\tres_comp\\tqp_stat\\tqp_iter') if stat.shape[0]>7: print('\\tqp_res_stat\\tqp_res_eq\\tqp_res_ineq\\tqp_res_comp') for jj", "\"\"\" get the information of the last solver call: :param", "constraints.lsg_e.shape[0] != nsg_e: raise Exception('inconsistent dimension nsg_e, regarding idxsg_e, lsg_e.')", "# strip symbolics ocp_nlp_dict['model'] = acados_model_strip_casadi_symbolics(ocp_nlp_dict['model']) # strip shooting_nodes ocp_nlp_dict['solver_options'].pop('shooting_nodes',", "wrong_field = \"Zu\" dim = cost.Zu.shape[0] elif cost.zl.shape[0] != ns:", "f: ocp_nlp_json = json.load(f) ocp_nlp_dict = json2dict(ocp_nlp_json, ocp_nlp_json['dims']) # Instantiate", "'external_cost_e.in.h' out_file = '{}_external_cost_e.h'.format(name) render_template(in_file, out_file, template_dir, json_path) class AcadosOcpSolver:", "Vz[{cost.Vz.shape}]\\n') if cost.Vx.shape[1] != dims.nx and ny != 0: raise", "Exception('inconsistent dimension: Vu should have nu columns.') if cost.yref.shape[0] !=", "\\ field_, tuple(dims), value_shape)) value_data = cast(value_.ctypes.data, POINTER(c_double)) value_data_p =", "!= ng \\ or constraints.D.shape[0] != ng: raise Exception('inconsistent dimension", "= nsbx_e + nsh_e + nsg_e + nsphi_e wrong_field =", "You have {}.'.format(field_, type(value_))) else: value_ctypes = c_int(value_) elif field_", "if cost.Zl_e.shape[0] != ns_e: wrong_field = \"Zl_e\" dim = cost.Zl_e.shape[0]", "Exception('inconsistent dimension nsbu, regarding idxsbu, usbu.') dims.nsbu = nsbu nsh", "form must reproduce the above copyright notice, # this list", "= \\ [c_void_p, c_void_p, c_void_p, c_int, c_char_p, c_void_p] self.shared_lib.ocp_nlp_out_get(self.nlp_config, \\", "+ \\ f'\\nGot W[{cost.W.shape}], yref[{cost.yref.shape}]\\n') dims.ny = ny elif cost.cost_type", "self.nlp_dims, self.nlp_in, stage, field, value_data_p) elif field_ in cost_fields: self.shared_lib.ocp_nlp_cost_model_set.argtypes", "# 1. Redistributions of source code must retain the above", "= cost.W.shape[0] if cost.Vx.shape[0] != ny or cost.Vu.shape[0] != ny:", "c_int value_data = cast(value_.ctypes.data, POINTER(c_double)) self.shared_lib.acados_update_params(stage, value_data, value_.shape[0]) else: if", "{})'.format( \\ field_, tuple(dims), value_shape)) value_data = cast(value_.ctypes.data, POINTER(c_double)) value_data_p", "cpu time regularization 'sqp_iter', # number of SQP iterations 'statistics',", "{} must be of type int. You have {}.'.format(field_, type(value_)))", "!= ns_e: wrong_field = \"zu_e\" dim = cost.zu_e.shape[0] if wrong_field", "acados_model_strip_casadi_symbolics from .utils import is_column, is_empty, casadi_length, render_template, acados_class2dict,\\ format_class_dict,", "\\ int(stat[0][jj]), stat[1][jj], stat[2][jj], \\ stat[3][jj], stat[4][jj], int(stat[5][jj]), int(stat[6][jj]))) if", "'sqp_iter'] \"\"\" fields = ['time_tot', # total cpu time previous", "f'With nsbx = {nsbx}, nsbu = {nsbu}, nsg = {nsg},", "Exception('convex over nonlinear constraints: con_r_expr but con_phi_expr is nonempty') else:", "nsbx: raise Exception('inconsistent dimension nsbx, regarding idxsbx, lsbx.') if is_empty(constraints.usbx):", "generate_c_code_external_cost(model, True) def ocp_render_templates(acados_ocp, json_file): name = acados_ocp.model.name # setting", "dimension' \\ ' for field \"{}\" with dimension {} (you", "stat[3][jj], stat[4][jj], int(stat[5][jj]), int(stat[6][jj]))) if stat.shape[0]>7: print('\\t{:e}\\t{:e}\\t{:e}\\t{:e}'.format( \\ stat[7][jj], stat[8][jj],", "dimension ny: regarding W, cost_y_expr.') elif casadi_length(model.cost_y_expr) != ny: raise", "be of type str. You have {}.'.format(field_, type(value_))) else: value_ctypes", "EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,", "OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY", "Exception('inconsistent dimension np, regarding model.p and parameter_values.') ## cost #", "self.shared_lib.ocp_nlp_get_at_stage(self.nlp_config, \\ self.nlp_dims, self.nlp_solver, stage_, field, out_data) return out def", "= '{}_h_constraint.h'.format(name) render_template(in_file, out_file, template_dir, json_path) # terminal nonlinear constraints", "elif constraints.ush_e.shape[0] != nsh_e: raise Exception('inconsistent dimension nsh_e, regarding idxsh_e,", "= np.zeros((nsg_e,)) elif constraints.usg_e.shape[0] != nsg_e: raise Exception('inconsistent dimension nsg_e,", "from .generate_c_code_implicit_ode import generate_c_code_implicit_ode from .generate_c_code_gnsf import generate_c_code_gnsf from .generate_c_code_constraint", "Possible values are {}. Exiting.'.format(field_, out_fields + mem_fields)) self.shared_lib.ocp_nlp_dims_get_from_attr.argtypes =", "regarding model.p and parameter_values.') ## cost # path if cost.cost_type", "code must retain the above copyright notice, # this list", "{wrong_field}, with dimension {dim}, \\n\\t'\\ + f'Detected ns = {ns}", "- opts.shooting_nodes[i] opts.time_steps = time_steps elif (not is_empty(opts.time_steps)) and (not", "acados. # # The 2-Clause BSD License # # Redistribution", "are {}. Exiting.\".format(field, \\ constraints_fields + cost_fields + out_fields +", "dims.nu = 0 else: dims.nu = casadi_length(model.u) # nz if", "\"{}\" '.format(field_) msg += 'with dimension {} (you have {})'.format(dims,", "value_ > 2: raise Exception('AcadosOcpSolver.solve(): argument \\'rti_phase\\' can ' 'take", "dims.nr_e = 0 else: dims.nphi_e = casadi_length(model.con_phi_expr_e) if is_empty(model.con_r_expr_e): raise", "value_data_p) return def cost_set(self, stage_, field_, value_): \"\"\" set numerical", "for field \"{}\" with dimension {} (you have {})'.format( \\", "generate_c_code_external_cost(model, False) if acados_ocp.cost.cost_type_e == 'NONLINEAR_LS': generate_c_code_nls_cost(model, model.name, True) elif", "== 'BGH' and acados_ocp.dims.nh_e > 0: template_dir = 'c_generated_code/{}_constraints/'.format(name) in_file", "constraints.usbx_e = np.zeros((nsbx_e,)) elif constraints.usbx_e.shape[0] != nsbx_e: raise Exception('inconsistent dimension", "explicit model -- generate C code generate_c_code_explicit_ode(model) elif acados_ocp.solver_options.integrator_type ==", "argument.\\ \\n Possible values are {}. Exiting.'.format(field_, out_fields + mem_fields))", "# cpu time for integrator contribution of linear algebra 'time_qp',", "json_path) in_file = 'acados_solver.in.c' out_file = 'acados_solver_{}.c'.format(name) render_template(in_file, out_file, template_dir,", "json_path) # nonlinear constraints if acados_ocp.constraints.constr_type == 'BGH' and acados_ocp.dims.nh", "np.zeros((nsg_e,)) elif constraints.lsg_e.shape[0] != nsg_e: raise Exception('inconsistent dimension nsg_e, regarding", "inequalities \\n t: slack variables corresponding to evaluation of all", "<NAME>, <NAME>, <NAME>, <NAME>, <NAME> # # This file is", "# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR", "shooting node :param field_: string, e.g. 'lbx' :param value_: of", "distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT", "field, value_data_p) return def options_set(self, field_, value_): \"\"\" set options", "Exception('inconsistent dimension ng, regarding lg, ug, C, D.') else: dims.ng", "c_char_p, c_void_p] self.shared_lib.ocp_nlp_constraints_model_set(self.nlp_config, \\ self.nlp_dims, self.nlp_in, stage, field, value_data_p) elif", "'c_generated_code/{}_constraints/'.format(name) in_file = 'h_constraint.in.h' out_file = '{}_h_constraint.h'.format(name) render_template(in_file, out_file, template_dir,", "lsphi.') if is_empty(constraints.usphi): constraints.usphi = np.zeros((nsphi,)) elif constraints.usphi.shape[0] != nsphi:", "!= nsbx: raise Exception('inconsistent dimension nsbx, regarding idxsbx, lsbx.') if", "uh, con_h_expr.') else: dims.nh = nh if is_empty(model.con_phi_expr): dims.nphi =", "= 'c_generated_code/{}_constraints/'.format(name) in_file = 'h_constraint.in.h' out_file = '{}_h_constraint.h'.format(name) render_template(in_file, out_file,", "if not isinstance(value_, int): raise Exception('solver option {} must be", "stat.shape[0]>7: print('\\t{:e}\\t{:e}\\t{:e}\\t{:e}'.format( \\ stat[7][jj], stat[8][jj], stat[9][jj], stat[10][jj])) print('\\n') elif self.acados_ocp.solver_options.nlp_solver_type", "['sl', 'su'] field = field_ field = field.encode('utf-8') if (field_", "if constraints.ug.shape[0] != ng or constraints.C.shape[0] != ng \\ or", "Exception('AcadosOcpSolver.constraints_set(): mismatching dimension' \\ ' for field \"{}\" with dimension", "<NAME> # # This file is part of acados. #", "template_dir = 'c_generated_code/{}_model/'.format(name) in_file = 'model.in.h' out_file = '{}_model.h'.format(name) render_template(in_file,", "= {nsbx_e}, nsg_e = {nsg_e}, nsh_e = {nsh_e}, nsphi_e =", "Exception(\"ocp_generate_external_functions: unknown integrator type.\") if acados_ocp.solver_options.hessian_approx == 'EXACT': opts =", "ocp_nlp_dict = json2dict(ocp_nlp_json, ocp_nlp_json['dims']) # Instantiate AcadosOcp object acados_ocp =", "def set(self, stage_, field_, value_): cost_fields = ['y_ref', 'yref'] constraints_fields", "terminal nonlinear cost function if acados_ocp.cost.cost_type_e == 'NONLINEAR_LS': template_dir =", "dims.nbu = nbu ng = constraints.lg.shape[0] if constraints.ug.shape[0] != ng", "out_data) elif field_ in mem_fields: self.shared_lib.ocp_nlp_get_at_stage.argtypes = \\ [c_void_p, c_void_p,", "WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES", "* np.ones((dims.N,)) elif not is_empty(opts.shooting_nodes): if np.shape(opts.shooting_nodes)[0] != dims.N+1: raise", "for dynamics equality constraints \\n lam: multipliers for inequalities \\n", "!= 0: raise Exception('inconsistent dimension ny: regarding W, cost_y_expr.') elif", "nsbu = constraints.idxsbu.shape[0] if is_empty(constraints.lsbu): constraints.lsbu = np.zeros((nsbu,)) elif constraints.lsbu.shape[0]", "c_int, c_char_p, c_void_p] self.shared_lib.ocp_nlp_cost_model_set(self.nlp_config, \\ self.nlp_dims, self.nlp_in, stage, field, value_data_p)", "'.so' # get self.shared_lib = CDLL(self.shared_lib_name) self.shared_lib.acados_create() self.solver_created = True", "# terminal nonlinear constraints if acados_ocp.constraints.constr_type_e == 'BGH' and acados_ocp.dims.nh_e", "usbx_e.') dims.nsbx_e = nsbx_e nsh_e = constraints.idxsh_e.shape[0] if is_empty(constraints.lsh_e): constraints.lsh_e", "# Copyright 2019 <NAME>, <NAME>, <NAME>, # <NAME>, <NAME>, <NAME>,", "stat[9][jj], stat[10][jj])) print('\\n') elif self.acados_ocp.solver_options.nlp_solver_type == 'SQP_RTI': print('\\niter\\tqp_stat\\tqp_iter') if stat.shape[0]>3:", "<NAME>, # <NAME>, <NAME>, <NAME>, <NAME>, # <NAME>, <NAME>, <NAME>,", "dims.nbx_0 = 0 else: this_shape = constraints.lbx_0.shape other_shape = constraints.ubx_0.shape", "self.shared_lib.ocp_nlp_dims_get_from_attr.argtypes = \\ [c_void_p, c_void_p, c_void_p, c_int, c_char_p] self.shared_lib.ocp_nlp_dims_get_from_attr.restype =", "acados ocp solver C object \"\"\" def __init__(self, acados_ocp, json_file='acados_ocp_nlp.json'):", "model): model = make_model_consistent(model) if acados_ocp.solver_options.integrator_type == 'ERK': # explicit", "nsbx_e, regarding idxsbx_e, usbx_e.') dims.nsbx_e = nsbx_e nsh_e = constraints.idxsh_e.shape[0]", "0: raise Exception('inconsistent dimension: Vx_e should have nx columns.') if", "'LINEAR_LS': ny_e = cost.W_e.shape[0] if cost.Vx_e.shape[0] != ny_e: raise Exception('inconsistent", "dims = np.ascontiguousarray(np.zeros((2,)), dtype=np.intc) dims_data = cast(dims.ctypes.data, POINTER(c_int)) self.shared_lib.ocp_nlp_constraint_dims_get_from_attr(self.nlp_config, \\", "elif cost.Zu_e.shape[0] != ns_e: wrong_field = \"Zu_e\" dim = cost.Zu_e.shape[0]", "nsbx_e: raise Exception('inconsistent dimension nsbx_e, regarding idxsbx_e, lsbx_e.') if is_empty(constraints.usbx_e):", "\"\"\" set options of the solver: Parameters: :param field_: string,", "the cost module of the solver: :param stage_: integer corresponding", "ubx_e, lbx_e.') else: dims.nbx_e = nbx_e ng_e = constraints.lg_e.shape[0] if", "wrong_field = \"zu\" dim = cost.zu.shape[0] if wrong_field != \"\":", "casadi_length(model.con_phi_expr_e) if is_empty(model.con_r_expr_e): raise Exception('convex over nonlinear constraints: con_r_expr_e but", "constraints.ug_e.shape[0] != ng_e or constraints.C_e.shape[0] != ng_e: raise Exception('inconsistent dimension", "the following disclaimer in the documentation # and/or other materials", "range(stat.shape[1]): print('{:d}\\t{:d}\\t{:d}'.format( int(stat[0][jj]), int(stat[1][jj]), int(stat[2][jj]))) if stat.shape[0]>3: print('\\t{:e}\\t{:e}\\t{:e}\\t{:e}'.format( \\ stat[3][jj],", "cpu time for linearization 'time_sim', # cpu time for integrator", "dimension nsh, regarding idxsh, ush.') dims.nsh = nsh nsphi =", "Exception('solver option {} must be of type int. You have", "out_file = '{}_cost_y_fun.h'.format(name) render_template(in_file, out_file, template_dir, json_path) # terminal nonlinear", "* from casadi import CasadiMeta, Function, SX from copy import", "dimension nbu, regarding idxbu, ubu, lbu.') else: dims.nbu = nbu", "= ny elif cost.cost_type == 'NONLINEAR_LS': ny = cost.W.shape[0] if", "function template_dir = 'c_generated_code/{}_constraints/'.format(name) in_file = 'phi_constraint.in.h' out_file = '{}_phi_constraint.h'.format(name)", "formatting for acados_struct, v in ocp_layout.items(): # skip non dict", "= ['time_tot', # total cpu time previous call 'time_lin', #", "lam, t: \\n the inequalities are internally organized in the", "attributes dict, dims, constraints, etc for acados_struct, v in ocp_layout.items():", "[c_void_p, c_void_p, c_void_p, c_int, c_char_p, POINTER(c_int)] self.shared_lib.ocp_nlp_cost_dims_get_from_attr.restype = c_int dims", "external cost if acados_ocp.cost.cost_type == 'EXTERNAL': template_dir = 'c_generated_code/{}_cost/'.format(name) in_file", "= np.ascontiguousarray(np.zeros((1,)), dtype=np.int64) out_data = cast(out.ctypes.data, POINTER(c_int64)) elif field_ ==", "self.shared_lib_name = 'c_generated_code/libacados_ocp_solver_' + model.name + '.so' # get self.shared_lib", "acados_struct, v in ocp_layout.items(): # skip non dict attributes if", "Exception('inconsistent dimension nsphi, regarding idxsphi, lsphi.') if is_empty(constraints.usphi): constraints.usphi =", "with formatting for acados_struct, v in ocp_layout.items(): # skip non", "(without converting the QP) 'time_qp_xcond', 'time_reg', # cpu time regularization", "IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE.; #", "PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT", "ns_e: wrong_field = \"zl_e\" dim = cost.zl_e.shape[0] elif cost.zu_e.shape[0] !=", "ocp_nlp_json = json.load(f) ocp_nlp_dict = json2dict(ocp_nlp_json, ocp_nlp_json['dims']) # Instantiate AcadosOcp", "'Makefile.in' out_file = 'Makefile' render_template(in_file, out_file, template_dir, json_path) in_file =", "initial if (constraints.lbx_0 == [] and constraints.ubx_0 == []): dims.nbx_0", "constraints.ubu.shape[0] != nbu or constraints.lbu.shape[0] != nbu: raise Exception('inconsistent dimension", "call: :param field_: string in ['statistics', 'time_tot', 'time_lin', 'time_sim', 'time_sim_ad',", "ns: wrong_field = \"zl\" dim = cost.zl.shape[0] elif cost.zu.shape[0] !=", "folder model template_dir = 'c_generated_code/{}_model/'.format(name) in_file = 'model.in.h' out_file =", "nbx_e or constraints.lbx_e.shape[0] != nbx_e: raise Exception('inconsistent dimension nbx_e, regarding", "acados_ocp.solver_options.integrator_type == 'GNSF': generate_c_code_gnsf(model) else: raise Exception(\"ocp_generate_external_functions: unknown integrator type.\")", "matrices if not acados_ocp.cost.cost_type == 'LINEAR_LS': acados_ocp.cost.Vx = np.zeros((acados_ocp.dims.ny, acados_ocp.dims.nx))", "if value_shape != tuple(dims): raise Exception('AcadosOcpSolver.cost_set(): mismatching dimension', \\ '", "c_int dims = np.ascontiguousarray(np.zeros((2,)), dtype=np.intc) dims_data = cast(dims.ctypes.data, POINTER(c_int)) self.shared_lib.ocp_nlp_constraint_dims_get_from_attr(self.nlp_config,", "raise Exception('inconsistent dimension ng, regarding lg, ug, C, D.') else:", "else: this_shape = constraints.lbx_0.shape other_shape = constraints.ubx_0.shape if not this_shape", "nsh_e + nsg_e + nsphi_e wrong_field = \"\" if cost.Zl_e.shape[0]", "{dim}, \\n\\t'\\ + f'Detected ns_e = {ns_e} = nsbx_e +", "over nonlinear function if acados_ocp.constraints.constr_type == 'BGP' and acados_ocp.dims.nphi >", "out def print_statistics(self): stat = self.get_stats(\"statistics\") if self.acados_ocp.solver_options.nlp_solver_type == 'SQP':", "is_empty(opts.time_steps)) and (not is_empty(opts.shooting_nodes)): Exception('Please provide either time_steps or shooting_nodes", "nsg = {nsg}, nsh = {nsh}, nsphi = {nsphi}') dims.ns", "dimension nsbx, regarding idxsbx, lsbx.') if is_empty(constraints.usbx): constraints.usbx = np.zeros((nsbx,))", "\\ self.nlp_dims, self.nlp_in, stage, field, value_data_p) elif field_ in out_fields:", "ocp with current input \"\"\" status = self.shared_lib.acados_solve() return status", "\"\"\" get the last solution of the solver: :param stage:", "del self.shared_lib # NOTE: DLL cannot be easily unloaded!!! #", "isinstance(value_, int): raise Exception('solver option {} must be of type", "= np.zeros((nsbx_e,)) elif constraints.usbx_e.shape[0] != nsbx_e: raise Exception('inconsistent dimension nsbx_e,", "= 0 else: dims.nphi = casadi_length(model.con_phi_expr) if is_empty(model.con_r_expr): raise Exception('convex", "c_int dims = self.shared_lib.ocp_nlp_dims_get_from_attr(self.nlp_config, \\ self.nlp_dims, self.nlp_out, stage_, field) out", "else: dims.nr = casadi_length(model.con_r_expr) # terminal nbx_e = constraints.idxbx_e.shape[0] if", "'EXTERNAL': template_dir = 'c_generated_code/{}_cost/'.format(name) in_file = 'external_cost.in.h' out_file = '{}_external_cost.h'.format(name)", "> 0: template_dir = 'c_generated_code/{}_constraints/'.format(name) in_file = 'h_e_constraint.in.h' out_file =", "== 'IRK': # implicit model -- generate C code opts", "Exception('inconsistent dimension nsh, regarding idxsh, ush.') dims.nsh = nsh nsphi", "'rti_phase', 'initialize_t_slacks', 'step_length' :param value_: of type int, float \"\"\"", "!= nsh: raise Exception('inconsistent dimension nsh, regarding idxsh, ush.') dims.nsh", "from .acados_ocp import AcadosOcp from .acados_model import acados_model_strip_casadi_symbolics from .utils", "return def cost_set(self, stage_, field_, value_): \"\"\" set numerical data", "'time_qp_xcond', 'time_reg', # cpu time regularization 'sqp_iter', # number of", "total cpu time previous call 'time_lin', # cpu time for", "cost.cost_type == 'NONLINEAR_LS': ny = cost.W.shape[0] if is_empty(model.cost_y_expr) and ny", "this_shape == other_shape: raise Exception('lbx_0, ubx_0 have different shapes!') if", "multipliers for dynamics equality constraints \\n lam: multipliers for inequalities", "= np.zeros((dims.N,)) for i in range(dims.N): time_steps[i] = opts.shooting_nodes[i+1] -", "corresponding to evaluation of all inequalities (at the solution) \\n", "constraints on outer function template_dir = 'c_generated_code/{}_constraints/'.format(name) in_file = 'phi_constraint.in.h'", "0 else: dims.nphi = casadi_length(model.con_phi_expr) if is_empty(model.con_r_expr): raise Exception('convex over", "0 else: dims.nz = casadi_length(model.z) # np if is_empty(model.p): dims.np", "dims.nsg = nsg ns = nsbx + nsbu + nsh", "acados_ocp.cost.Vu = np.zeros((acados_ocp.dims.ny, acados_ocp.dims.nu)) if not acados_ocp.cost.cost_type_e == 'LINEAR_LS': acados_ocp.cost.Vx_e", "render_template(in_file, out_file, template_dir, json_path) # terminal constraints on convex over", "+ f'Detected ns = {ns} = nsbx + nsbu +", "self.nlp_opts, field, byref(value_ctypes)) return def __del__(self): if self.solver_created: self.shared_lib.acados_free() del", "raise Exception('inconsistent dimension nsg, regarding idxsg, lsg.') if is_empty(constraints.usg): constraints.usg", "the solution) \\n sl: slack variables of soft lower inequality", "constraints_fields + cost_fields + out_fields + ['p'])) self.shared_lib.ocp_nlp_dims_get_from_attr.argtypes = \\", "usphi] .. note:: pi: multipliers for dynamics equality constraints \\n", "W, Vx, Vu, Vz.' + \\ f'\\nGot W[{cost.W.shape}], Vx[{cost.Vx.shape}], Vu[{cost.Vu.shape}],", "and environment json_path = '{cwd}/{json_file}'.format( cwd=os.getcwd(), json_file=json_file) if not os.path.exists(json_path):", "nh_e, regarding lh_e, uh_e, con_h_expr_e.') else: dims.nh_e = nh_e if", "dims.ns_e = ns_e # discretization if is_empty(opts.time_steps) and is_empty(opts.shooting_nodes): #", "+= 'with dimension {} (you have {})'.format(dims, value_.shape[0]) raise Exception(msg)", "LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS", "regarding lh, uh, con_h_expr.') else: dims.nh = nh if is_empty(model.con_phi_expr):", "constraints.lh_e.shape[0] != nh_e: raise Exception('inconsistent dimension nh_e, regarding lh_e, uh_e,", "out_fields + ['p'])) self.shared_lib.ocp_nlp_dims_get_from_attr.argtypes = \\ [c_void_p, c_void_p, c_void_p, c_int,", "acados_attribute = getattr(acados_ocp, acados_struct) acados_attribute.__dict__ = ocp_nlp_dict[acados_struct] setattr(acados_ocp, acados_struct, acados_attribute)", "= cost.zl_e.shape[0] elif cost.zu_e.shape[0] != ns_e: wrong_field = \"zu_e\" dim", "= acados_class2dict(acados_ocp.dims) ocp_check_against_layout(ocp_nlp_dict, dims_dict) with open(json_file, 'w') as f: json.dump(ocp_nlp_dict,", "internally organized in the following order: \\n [ lbu lbx", "= 'acados_sim_solver.in.c' out_file = 'acados_sim_solver_{}.c'.format(name) render_template(in_file, out_file, template_dir, json_path) in_file", "\\ [c_void_p, c_void_p, c_void_p, c_int, c_char_p, POINTER(c_int)] self.shared_lib.ocp_nlp_constraint_dims_get_from_attr.restype = c_int", "dim = cost.Zu.shape[0] elif cost.zl.shape[0] != ns: wrong_field = \"zl\"", "json_path) in_file = 'acados_solver.in.h' out_file = 'acados_solver_{}.h'.format(name) render_template(in_file, out_file, template_dir,", "stat[2][jj], \\ stat[3][jj], stat[4][jj], int(stat[5][jj]), int(stat[6][jj]))) if stat.shape[0]>7: print('\\t{:e}\\t{:e}\\t{:e}\\t{:e}'.format( \\", "## constraints # initial if (constraints.lbx_0 == [] and constraints.ubx_0", "!= 'SQP_RTI' and value_ > 0: raise Exception('AcadosOcpSolver.solve(): argument \\'rti_phase\\'", "is_empty(constraints.lsh_e): constraints.lsh_e = np.zeros((nsh_e,)) elif constraints.lsh_e.shape[0] != nsh_e: raise Exception('inconsistent", "nsh_e: raise Exception('inconsistent dimension nsh_e, regarding idxsh_e, lsh_e.') if is_empty(constraints.ush_e):", "in cost_fields: self.shared_lib.ocp_nlp_cost_model_set.argtypes = \\ [c_void_p, c_void_p, c_void_p, c_int, c_char_p,", "lsphi_e.') if is_empty(constraints.usphi_e): constraints.usphi_e = np.zeros((nsphi_e,)) elif constraints.usphi_e.shape[0] != nsphi_e:", "= 'cost_y_fun.in.h' out_file = '{}_cost_y_fun.h'.format(name) render_template(in_file, out_file, template_dir, json_path) #", "float): raise Exception('solver option {} must be of type float.", "conditions and the following disclaimer. # # 2. Redistributions in", "!= nsbu: raise Exception('inconsistent dimension nsbu, regarding idxsbu, lsbu.') if", "continue # setattr(ocp_nlp, acados_struct, dict(getattr(acados_ocp, acados_struct).__dict__)) # Copy ocp object", "raise Exception('inconsistent dimension ny_e: regarding W_e, cost_y_expr_e.') if cost.yref_e.shape[0] !=", "out_file = '{}_h_constraint.h'.format(name) render_template(in_file, out_file, template_dir, json_path) # terminal nonlinear", "'stat_n', ] field = field_ field = field.encode('utf-8') if (field_", "in_file = 'cost_y_fun.in.h' out_file = '{}_cost_y_fun.h'.format(name) render_template(in_file, out_file, template_dir, json_path)", "self.shared_lib.ocp_nlp_solver_opts_set(self.nlp_config, \\ self.nlp_opts, field, value_ctypes) else: self.shared_lib.ocp_nlp_solver_opts_set.argtypes = \\ [c_void_p,", "raise Exception('inconsistent dimension: regarding W_e, yref_e.') dims.ny_e = ny_e ##", "if field_ in constraints_fields: self.shared_lib.ocp_nlp_constraints_model_set.argtypes = \\ [c_void_p, c_void_p, c_void_p,", "be easily unloaded!!! # see https://stackoverflow.com/questions/359498/how-can-i-unload-a-dll-using-ctypes-in-python # while isLoaded(self.shared_lib_name): #", "> 0: generate_c_code_constraint(model, model.name, True, opts) # dummy matrices if", "= \\ [c_void_p, c_void_p, c_void_p, c_int, c_char_p, c_void_p] self.shared_lib.ocp_nlp_get_at_stage(self.nlp_config, \\", "= '{}_h_e_constraint.h'.format(name) render_template(in_file, out_file, template_dir, json_path) # nonlinear cost function", "node :param field_: string in ['x', 'u', 'z', 'pi', 'lam',", "mismatching dimension for field \"{}\" '.format(field_) msg += 'with dimension", "int(stat[0][jj]), int(stat[1][jj]), int(stat[2][jj]))) if stat.shape[0]>3: print('\\t{:e}\\t{:e}\\t{:e}\\t{:e}'.format( \\ stat[3][jj], stat[4][jj], stat[5][jj],", "self.shared_lib.ocp_nlp_get_at_stage.argtypes = \\ [c_void_p, c_void_p, c_void_p, c_int, c_char_p, c_void_p] self.shared_lib.ocp_nlp_get_at_stage(self.nlp_config,", "!= ny: raise Exception('inconsistent dimension ny, regarding W, Vx, Vu.'", "import generate_c_code_constraint from .generate_c_code_nls_cost import generate_c_code_nls_cost from .generate_c_code_external_cost import generate_c_code_external_cost", "acados_attribute) return acados_ocp def ocp_generate_external_functions(acados_ocp, model): model = make_model_consistent(model) if", "DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING,", "dims.nsbx = nsbx nsbu = constraints.idxsbu.shape[0] if is_empty(constraints.lsbu): constraints.lsbu =", "dims.N * np.ones((dims.N,)) elif not is_empty(opts.shooting_nodes): if np.shape(opts.shooting_nodes)[0] != dims.N+1:", "constraints.usbu.shape[0] != nsbu: raise Exception('inconsistent dimension nsbu, regarding idxsbu, usbu.')", "is_empty(model.u): dims.nu = 0 else: dims.nu = casadi_length(model.u) # nz", "OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT", "organized in the following order: \\n [ lbu lbx lg", "out_data = cast(out.ctypes.data, POINTER(c_double)) if (field_ in out_fields): self.shared_lib.ocp_nlp_out_get.argtypes =", "dimension {} (you have {})'.format( \\ field_, tuple(dims), value_shape)) value_data", "cost.W.shape[0] if is_empty(model.cost_y_expr) and ny != 0: raise Exception('inconsistent dimension", "constraint module of the solver: Parameters: :param stage_: integer corresponding", "only value 0 for SQP-type solvers') field = field_ field", "## folder model template_dir = 'c_generated_code/{}_model/'.format(name) in_file = 'model.in.h' out_file", "0: template_dir = 'c_generated_code/{}_constraints/'.format(name) in_file = 'h_constraint.in.h' out_file = '{}_h_constraint.h'.format(name)", "\\ [c_void_p, c_void_p, c_char_p, c_char_p] self.shared_lib.ocp_nlp_solver_opts_set(self.nlp_config, \\ self.nlp_opts, field, value_ctypes)", "!= nsphi_e: raise Exception('inconsistent dimension nsphi_e, regarding idxsphi_e, lsphi_e.') if", "yref[{cost.yref.shape}]\\n') dims.ny = ny # terminal if cost.cost_type_e == 'LINEAR_LS':", "constraints.lsh_e = np.zeros((nsh_e,)) elif constraints.lsh_e.shape[0] != nsh_e: raise Exception('inconsistent dimension", "\"\": raise Exception(f'Inconsistent size for field {wrong_field}, with dimension {dim},", "'LINEAR_LS': ny = cost.W.shape[0] if cost.Vx.shape[0] != ny or cost.Vu.shape[0]", "'IRK': # implicit model -- generate C code opts =", "c_int, c_char_p] self.shared_lib.ocp_nlp_dims_get_from_attr.restype = c_int dims = self.shared_lib.ocp_nlp_dims_get_from_attr(self.nlp_config, \\ self.nlp_dims,", "0 else: dims.nphi_e = casadi_length(model.con_phi_expr_e) if is_empty(model.con_r_expr_e): raise Exception('convex over", "get self.shared_lib = CDLL(self.shared_lib_name) self.shared_lib.acados_create() self.solver_created = True self.shared_lib.acados_get_nlp_opts.restype =", "np.zeros((dims.N,)) for i in range(dims.N): time_steps[i] = opts.shooting_nodes[i+1] - opts.shooting_nodes[i]", "that the following conditions are met: # # 1. Redistributions", "render_template(in_file, out_file, template_dir, json_path) # external cost - terminal if", "{} (you have {})'.format(field_, tuple(dims), value_shape)) value_data = cast(value_.ctypes.data, POINTER(c_double))", "= value_.astype(float) field = field_ field = field.encode('utf-8') stage =", "invalid argument.\\ \\n Possible values are {}. Exiting.'.format(field_, out_fields +", "1: value_shape = (value_shape[0], 0) if value_shape != tuple(dims): raise", "'acados_sim_solver.in.h' out_file = 'acados_sim_solver_{}.h'.format(name) render_template(in_file, out_file, template_dir, json_path) ## folder", "cost_set(self, stage_, field_, value_): \"\"\" set numerical data in the", "= 0 else: dims.nu = casadi_length(model.u) # nz if is_empty(model.z):", "cpu time for integrator 'time_sim_ad', # cpu time for integrator", "if acados_ocp.constraints.constr_type_e == 'BGP' and acados_ocp.dims.nphi_e > 0: # terminal", "= cost.zl.shape[0] elif cost.zu.shape[0] != ns: wrong_field = \"zu\" dim", "elif cost.zu_e.shape[0] != ns_e: wrong_field = \"zu_e\" dim = cost.zu_e.shape[0]", "be of type int. You have {}.'.format(field_, type(value_))) else: value_ctypes", "<NAME>, <NAME>, <NAME>, <NAME>, # <NAME>, <NAME>, <NAME>, <NAME>, #", "['statistics', 'time_tot', 'time_lin', 'time_sim', 'time_sim_ad', 'time_sim_la', 'time_qp', 'time_qp_solver_call', 'time_reg', 'sqp_iter']", "regarding idxsh_e, ush_e.') dims.nsh_e = nsh_e nsg_e = constraints.idxsg_e.shape[0] if", "== 'LINEAR_LS': acados_ocp.cost.Vx_e = np.zeros((acados_ocp.dims.ny_e, acados_ocp.dims.nx)) if acados_ocp.cost.cost_type == 'NONLINEAR_LS':", "Exception(f'Inconsistent size for field {wrong_field}, with dimension {dim}, \\n\\t'\\ +", "field \"{}\" with dimension {} (you have {})'.format( \\ field_,", "'p': self.shared_lib.acados_update_params.argtypes = [c_int, POINTER(c_double)] self.shared_lib.acados_update_params.restype = c_int value_data =", "is_empty(constraints.lsbu): constraints.lsbu = np.zeros((nsbu,)) elif constraints.lsbu.shape[0] != nsbu: raise Exception('inconsistent", "= c_int(stage_) self.shared_lib.ocp_nlp_constraint_dims_get_from_attr.argtypes = \\ [c_void_p, c_void_p, c_void_p, c_int, c_char_p,", "!= nsh: raise Exception('inconsistent dimension nsh, regarding idxsh, lsh.') if", "import numpy as np from ctypes import * from casadi", "not isinstance(value_, float): raise Exception('solver option {} must be of", "= {nsg}, nsh = {nsh}, nsphi = {nsphi}') dims.ns =", "out_data) return out # Note: this function should not be", "function if acados_ocp.constraints.constr_type_e == 'BGP' and acados_ocp.dims.nphi_e > 0: #", "self.solver_created: self.shared_lib.acados_free() del self.shared_lib # NOTE: DLL cannot be easily", "OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE", "= np.sum(opts.time_steps) if (tf - opts.tf) / tf > 1e-15:", "idxbx, ubx, lbx.') else: dims.nbx = nbx nbu = constraints.idxbu.shape[0]", "INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF", "regarding W, Vx, Vu, Vz.' + \\ f'\\nGot W[{cost.W.shape}], Vx[{cost.Vx.shape}],", "0 or acados_ocp.dims.nh > 0: generate_c_code_constraint(model, model.name, False, opts) if", "= self.get_stats(\"sqp_iter\") stat_m = self.get_stats(\"stat_m\") stat_n = self.get_stats(\"stat_n\") min_size =", "'r') as f: ocp_nlp_layout = json.load(f) return ocp_nlp_layout def ocp_formulation_json_dump(acados_ocp,", "ocp_layout = get_ocp_nlp_layout() # Copy input ocp object dictionary ocp_nlp_dict", "cost.zu_e.shape[0] != ns_e: wrong_field = \"zu_e\" dim = cost.zu_e.shape[0] if", "dimension ny_e: regarding W_e, cost_y_expr_e.') elif casadi_length(model.cost_y_expr_e) != ny_e: raise", "constraints.lg.shape[0] if constraints.ug.shape[0] != ng or constraints.C.shape[0] != ng \\", "'time_sim_la', # cpu time for integrator contribution of linear algebra", "!= ng_e: raise Exception('inconsistent dimension ng_e, regarding_e lg_e, ug_e, C_e.')", "the distribution. # # THIS SOFTWARE IS PROVIDED BY THE", "= np.zeros((acados_ocp.dims.ny, acados_ocp.dims.nx)) acados_ocp.cost.Vu = np.zeros((acados_ocp.dims.ny, acados_ocp.dims.nu)) if not acados_ocp.cost.cost_type_e", "casadi_length, render_template, acados_class2dict,\\ format_class_dict, ocp_check_against_layout, np_array_to_list, make_model_consistent,\\ set_up_imported_gnsf_model def make_ocp_dims_consistent(acados_ocp):", "ny, regarding W, Vx, Vu, Vz.' + \\ f'\\nGot W[{cost.W.shape}],", "Exception('inconsistent dimension nsg, regarding idxsg, usg.') dims.nsg = nsg ns", "'acados_solver_{}.c'.format(name) render_template(in_file, out_file, template_dir, json_path) in_file = 'acados_solver.in.h' out_file =", "{nsphi_e}') dims.ns_e = ns_e # discretization if is_empty(opts.time_steps) and is_empty(opts.shooting_nodes):", "\\nPossible values are {}. Exiting.\".format(field, \\ constraints_fields + cost_fields +", "last solution of the solver: :param stage: integer corresponding to", "if cost.Vu.shape[1] != dims.nu and ny != 0: raise Exception('inconsistent", "generate_c_code_nls_cost from .generate_c_code_external_cost import generate_c_code_external_cost from .acados_ocp import AcadosOcp from", "\\ constraints_fields + cost_fields + out_fields + ['p'])) self.shared_lib.ocp_nlp_dims_get_from_attr.argtypes =", "!= nbu: raise Exception('inconsistent dimension nbu, regarding idxbu, ubu, lbu.')", "self.shared_lib.ocp_nlp_constraint_dims_get_from_attr.argtypes = \\ [c_void_p, c_void_p, c_void_p, c_int, c_char_p, POINTER(c_int)] self.shared_lib.ocp_nlp_constraint_dims_get_from_attr.restype", "template_dir, json_path) in_file = 'make_sfun.in.m' out_file = 'make_sfun.m' render_template(in_file, out_file,", "= cast(out.ctypes.data, POINTER(c_double)) if (field_ in out_fields): self.shared_lib.ocp_nlp_out_get.argtypes = \\", "print('\\t{:e}\\t{:e}\\t{:e}\\t{:e}'.format( \\ stat[3][jj], stat[4][jj], stat[5][jj], stat[6][jj])) print('\\n') return def get_stats(self,", "OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER", "stat = self.get_stats(\"statistics\") if self.acados_ocp.solver_options.nlp_solver_type == 'SQP': print('\\niter\\tres_stat\\tres_eq\\t\\tres_ineq\\tres_comp\\tqp_stat\\tqp_iter') if stat.shape[0]>7:", "2019 <NAME>, <NAME>, <NAME>, # <NAME>, <NAME>, <NAME>, <NAME>, #", "Exception('inconsistent dimension nh, regarding lh, uh, con_h_expr.') else: dims.nh =", "ush_e.') dims.nsh_e = nsh_e nsg_e = constraints.idxsg_e.shape[0] if is_empty(constraints.lsg_e): constraints.lsg_e", "= cast(dims.ctypes.data, POINTER(c_int)) self.shared_lib.ocp_nlp_cost_dims_get_from_attr(self.nlp_config, \\ self.nlp_dims, self.nlp_out, stage_, field, dims_data)", "json_path) # external cost - terminal if acados_ocp.cost.cost_type_e == 'EXTERNAL':", "== []): dims.nbx_0 = 0 else: this_shape = constraints.lbx_0.shape other_shape", "c_char_p, c_void_p] self.shared_lib.ocp_nlp_out_set(self.nlp_config, \\ self.nlp_dims, self.nlp_out, stage, field, value_data_p) return", "should have nx columns.') if cost.yref_e.shape[0] != ny_e: raise Exception('inconsistent", "not this_shape == other_shape: raise Exception('lbx_0, ubx_0 have different shapes!')", "= 'make_sfun.in.m' out_file = 'make_sfun.m' render_template(in_file, out_file, template_dir, json_path) in_file", "dimension nsphi, regarding idxsphi, usphi.') dims.nsphi = nsphi nsg =", "# setting up loader and environment json_path = '{cwd}/{json_file}'.format( cwd=os.getcwd(),", "else: dims.nh = nh if is_empty(model.con_phi_expr): dims.nphi = 0 dims.nr", "from ctypes import * from casadi import CasadiMeta, Function, SX", "in_file = 'acados_solver_sfun.in.c' out_file = 'acados_solver_sfunction_{}.c'.format(name) render_template(in_file, out_file, template_dir, json_path)", "out_fields: raise Exception(\"AcadosOcpSolver.set(): {} is not a valid argument.\\ \\nPossible", "template_dir = 'c_generated_code/{}_cost/'.format(name) in_file = 'external_cost_e.in.h' out_file = '{}_external_cost_e.h'.format(name) render_template(in_file,", "for SQP-RTI-type solvers') if self.acados_ocp.solver_options.nlp_solver_type != 'SQP_RTI' and value_ >", "np.zeros((nsbx,)) elif constraints.lsbx.shape[0] != nsbx: raise Exception('inconsistent dimension nsbx, regarding", "!= ns: wrong_field = \"Zl\" dim = cost.Zl.shape[0] elif cost.Zu.shape[0]", "json_path) ## folder model template_dir = 'c_generated_code/{}_model/'.format(name) in_file = 'model.in.h'", "are {}. Exiting.'.format(fields, fields)) if field_ in ['sqp_iter', 'stat_m', 'stat_n']:", "of type int. You have {}.'.format(field_, type(value_))) else: value_ctypes =", "False, opts) if acados_ocp.dims.nphi_e > 0 or acados_ocp.dims.nh_e > 0:", "stage_, field_, value_): cost_fields = ['y_ref', 'yref'] constraints_fields = ['lbx',", "solver: :param stage_: integer corresponding to shooting node :param field_:", "a valid argument.\\ \\n Possible values are {}. Exiting.'.format(fields, fields))", "value_data = cast(value_.ctypes.data, POINTER(c_double)) value_data_p = cast((value_data), c_void_p) self.shared_lib.ocp_nlp_cost_model_set.argtypes =", "== 'NONLINEAR_LS': ny = cost.W.shape[0] if is_empty(model.cost_y_expr) and ny !=", "ny: raise Exception('inconsistent dimension ny, regarding W, Vx, Vu, Vz.'", "used anymore, better use cost_set, constraints_set def set(self, stage_, field_,", "value_data, value_.shape[0]) else: if field_ not in constraints_fields + cost_fields", "= 0 else: dims.nz = casadi_length(model.z) # np if is_empty(model.p):", "generate_c_code_constraint(model, model.name, False, opts) if acados_ocp.dims.nphi_e > 0 or acados_ocp.dims.nh_e", "value_data = cast(value_.ctypes.data, POINTER(c_double)) value_data_p = cast((value_data), c_void_p) self.shared_lib.ocp_nlp_constraints_model_set.argtypes =", "cwd=os.getcwd(), json_file=json_file) if not os.path.exists(json_path): raise Exception('{} not found!'.format(json_path)) template_dir", "the QP) 'time_qp_xcond', 'time_reg', # cpu time regularization 'sqp_iter', #", "= casadi_length(model.con_r_expr_e) # Slack dimensions nsbx = constraints.idxsbx.shape[0] if is_empty(constraints.lsbx):", "constraints \\n \"\"\" out_fields = ['x', 'u', 'z', 'pi', 'lam',", "!= ny_e: raise Exception('inconsistent dimension ny_e: regarding W_e, cost_y_expr_e.' +", "' 'take only value 0 for SQP-type solvers') field =", "[c_void_p, c_void_p, c_char_p, c_void_p] self.shared_lib.ocp_nlp_solver_opts_set(self.nlp_config, \\ self.nlp_opts, field, byref(value_ctypes)) return", "= nbu ng = constraints.lg.shape[0] if constraints.ug.shape[0] != ng or", "argument.\\ \\n Possible values are {}. Exiting.'.format(fields, fields)) if field_", "os.path.exists(json_path): raise Exception('{} not found!'.format(json_path)) template_dir = 'c_generated_code/' ## Render", "in string_fields: if not isinstance(value_, str): raise Exception('solver option {}", "ug, C, D.') else: dims.ng = ng if not is_empty(model.con_h_expr):", "'take only value 0 for SQP-type solvers') field = field_", "!= nsg: raise Exception('inconsistent dimension nsg, regarding idxsg, usg.') dims.nsg", "'{}_h_e_constraint.h'.format(name) render_template(in_file, out_file, template_dir, json_path) # nonlinear cost function if", "'SQP_RTI' and value_ > 0: raise Exception('AcadosOcpSolver.solve(): argument \\'rti_phase\\' can", "or acados_ocp.dims.nh > 0: generate_c_code_constraint(model, model.name, False, opts) if acados_ocp.dims.nphi_e", "AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN", "dim = cost.Zl.shape[0] elif cost.Zu.shape[0] != ns: wrong_field = \"Zu\"", "POINTER(c_int)) self.shared_lib.ocp_nlp_cost_dims_get_from_attr(self.nlp_config, \\ self.nlp_dims, self.nlp_out, stage_, field, dims_data) value_shape =", "self.shared_lib.ocp_nlp_solver_opts_set.argtypes = \\ [c_void_p, c_void_p, c_char_p, c_char_p] self.shared_lib.ocp_nlp_solver_opts_set(self.nlp_config, \\ self.nlp_opts,", "is_empty(constraints.lsbx_e): constraints.lsbx_e = np.zeros((nsbx_e,)) elif constraints.lsbx_e.shape[0] != nsbx_e: raise Exception('inconsistent", "Exception('inconsistent dimension nsphi_e, regarding idxsphi_e, lsphi_e.') if is_empty(constraints.usphi_e): constraints.usphi_e =", "raise Exception(\"AcadosOcpSolver.set(): {} is not a valid argument.\\ \\nPossible values", "yref.' + \\ f'\\nGot W[{cost.W.shape}], yref[{cost.yref.shape}]\\n') dims.ny = ny elif", "solver: Parameters: :param field_: string, e.g. 'print_level', 'rti_phase', 'initialize_t_slacks', 'step_length'", "ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY,", "nbu or constraints.lbu.shape[0] != nbu: raise Exception('inconsistent dimension nbu, regarding", "model = make_model_consistent(model) if acados_ocp.solver_options.integrator_type == 'ERK': # explicit model", "with current input \"\"\" status = self.shared_lib.acados_solve() return status def", "np.zeros((acados_ocp.dims.ny, acados_ocp.dims.nu)) if not acados_ocp.cost.cost_type_e == 'LINEAR_LS': acados_ocp.cost.Vx_e = np.zeros((acados_ocp.dims.ny_e,", "ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT", "the acados ocp solver C object \"\"\" def __init__(self, acados_ocp,", "np, regarding model.p and parameter_values.') ## cost # path if", "uphi; \\n lsbu lsbx lsg lsh lsphi usbu usbx usg", "c_char_p, c_void_p] self.shared_lib.ocp_nlp_out_get(self.nlp_config, \\ self.nlp_dims, self.nlp_out, stage_, field, out_data) elif", "columns.') if cost.yref.shape[0] != ny: raise Exception('inconsistent dimension: regarding W,", "def solve(self): \"\"\" solve the ocp with current input \"\"\"", "= cast(value_.ctypes.data, POINTER(c_double)) self.shared_lib.acados_update_params(stage, value_data, value_.shape[0]) else: if field_ not", "Exception('inconsistent dimension nsbu, regarding idxsbu, lsbu.') if is_empty(constraints.usbu): constraints.usbu =", "nsbu: raise Exception('inconsistent dimension nsbu, regarding idxsbu, usbu.') dims.nsbu =", "> 2: raise Exception('AcadosOcpSolver.solve(): argument \\'rti_phase\\' can ' 'take only", "dims = self.shared_lib.ocp_nlp_dims_get_from_attr(self.nlp_config, \\ self.nlp_dims, self.nlp_out, stage_, field) out =", "True) def ocp_render_templates(acados_ocp, json_file): name = acados_ocp.model.name # setting up", "cost.Zu_e.shape[0] != ns_e: wrong_field = \"Zu_e\" dim = cost.Zu_e.shape[0] elif", "POINTER(c_double)) value_data_p = cast((value_data), c_void_p) self.shared_lib.ocp_nlp_cost_model_set.argtypes = \\ [c_void_p, c_void_p,", "constraints.idxbu.shape[0] if constraints.ubu.shape[0] != nbu or constraints.lbu.shape[0] != nbu: raise", "== other_shape: raise Exception('lbx_0, ubx_0 have different shapes!') if not", "'time_sim_la', 'time_qp', 'time_qp_solver_call', 'time_reg', 'sqp_iter'] \"\"\" fields = ['time_tot', #", "np.zeros((nsphi,)) elif constraints.lsphi.shape[0] != nsphi: raise Exception('inconsistent dimension nsphi, regarding", "dimension nsg_e, regarding idxsg_e, lsg_e.') if is_empty(constraints.usg_e): constraints.usg_e = np.zeros((nsg_e,))", "\\ f'\\nGot W[{cost.W.shape}], Vx[{cost.Vx.shape}], Vu[{cost.Vu.shape}], Vz[{cost.Vz.shape}]\\n') if cost.Vx.shape[1] != dims.nx", "but con_phi_expr_e is nonempty') else: dims.nr_e = casadi_length(model.con_r_expr_e) # Slack", "< 0 or value_ > 2: raise Exception('AcadosOcpSolver.solve(): argument \\'rti_phase\\'", "c_char_p] self.shared_lib.ocp_nlp_dims_get_from_attr.restype = c_int dims = self.shared_lib.ocp_nlp_dims_get_from_attr(self.nlp_config, \\ self.nlp_dims, self.nlp_out,", "= 0 dims.nr = 0 else: dims.nphi = casadi_length(model.con_phi_expr) if", "current input \"\"\" status = self.shared_lib.acados_solve() return status def get(self,", "self.shared_lib.ocp_nlp_solver_opts_set(self.nlp_config, \\ self.nlp_opts, field, byref(value_ctypes)) return def __del__(self): if self.solver_created:", "THE # POSSIBILITY OF SUCH DAMAGE.; # import sys, os,", "IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"", "if is_empty(constraints.usbx_e): constraints.usbx_e = np.zeros((nsbx_e,)) elif constraints.usbx_e.shape[0] != nsbx_e: raise", "self.shared_lib.ocp_nlp_dims_get_from_attr(self.nlp_config, \\ self.nlp_dims, self.nlp_out, stage_, field) if value_.shape[0] != dims:", "but con_phi_expr is nonempty') else: dims.nr = casadi_length(model.con_r_expr) # terminal", "['x', 'u', 'z', 'pi', 'lam', 't'] mem_fields = ['sl', 'su']", "render_template(in_file, out_file, template_dir, json_path) in_file = 'Makefile.in' out_file = 'Makefile'", "not in out_fields + mem_fields): raise Exception('AcadosOcpSolver.get(): {} is an", "value_data_p) return def options_set(self, field_, value_): \"\"\" set options of", "have different shapes!') if not is_column(constraints.lbx_0): raise Exception('lbx_0, ubx_0 must", "dim = cost.zl.shape[0] elif cost.zu.shape[0] != ns: wrong_field = \"zu\"", "raise Exception('AcadosOcpSolver.cost_set(): mismatching dimension', \\ ' for field \"{}\" with", "getattr(acados_ocp, acados_struct) acados_attribute.__dict__ = ocp_nlp_dict[acados_struct] setattr(acados_ocp, acados_struct, acados_attribute) return acados_ocp", "self.solver_created = True self.shared_lib.acados_get_nlp_opts.restype = c_void_p self.nlp_opts = self.shared_lib.acados_get_nlp_opts() self.shared_lib.acados_get_nlp_dims.restype", "as f: ocp_nlp_layout = json.load(f) return ocp_nlp_layout def ocp_formulation_json_dump(acados_ocp, json_file='acados_ocp_nlp.json'):", "elif constraints.lsh_e.shape[0] != nsh_e: raise Exception('inconsistent dimension nsh_e, regarding idxsh_e,", "lg, ug, C, D.') else: dims.ng = ng if not", "terminal if acados_ocp.cost.cost_type_e == 'EXTERNAL': template_dir = 'c_generated_code/{}_cost/'.format(name) in_file =", "+ nsbu + nsg + nsh + nsphi.\\n\\t'\\ + f'With", "'lam', 't'] mem_fields = ['sl', 'su'] field = field_ field", "raise Exception('inconsistent dimension nsg_e, regarding idxsg_e, usg_e.') dims.nsg_e = nsg_e", "POINTER(c_int)] self.shared_lib.ocp_nlp_constraint_dims_get_from_attr.restype = c_int dims = np.ascontiguousarray(np.zeros((2,)), dtype=np.intc) dims_data =", "convex over nonlinear function if acados_ocp.constraints.constr_type == 'BGP' and acados_ocp.dims.nphi", "SX from copy import deepcopy from .generate_c_code_explicit_ode import generate_c_code_explicit_ode from", "string_fields = ['globalization'] if field_ in int_fields: if not isinstance(value_,", "{nsg}, nsh = {nsh}, nsphi = {nsphi}') dims.ns = ns", "nsh, regarding idxsh, ush.') dims.nsh = nsh nsphi = constraints.idxsphi.shape[0]", "solver: Parameters: :param stage_: integer corresponding to shooting node :param", "+ nsg + nsh + nsphi.\\n\\t'\\ + f'With nsbx =", "os.chdir('..') self.shared_lib_name = 'c_generated_code/libacados_ocp_solver_' + model.name + '.so' # get", "BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY", "'external_cost.in.h' out_file = '{}_external_cost.h'.format(name) render_template(in_file, out_file, template_dir, json_path) # external", "if not is_empty(model.con_h_expr_e): nh_e = casadi_length(model.con_h_expr_e) else: nh_e = 0", "ocp_shared_lib') os.chdir('..') self.shared_lib_name = 'c_generated_code/libacados_ocp_solver_' + model.name + '.so' #", "!= ns: wrong_field = \"Zu\" dim = cost.Zu.shape[0] elif cost.zl.shape[0]", "SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS", "of acados. # # The 2-Clause BSD License # #", "# path nbx = constraints.idxbx.shape[0] if constraints.ubx.shape[0] != nbx or", "SQP-type solvers') field = field_ field = field.encode('utf-8') if field_", "(INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT", "nx if is_column(model.x): dims.nx = casadi_length(model.x) else: raise Exception('model.x should", "cast(out.ctypes.data, POINTER(c_double)) self.shared_lib.ocp_nlp_get.argtypes = [c_void_p, c_void_p, c_char_p, c_void_p] self.shared_lib.ocp_nlp_get(self.nlp_config, self.nlp_solver,", "ny_e ## constraints # initial if (constraints.lbx_0 == [] and", "dimension ny, regarding W, Vx, Vu.' + \\ f'\\nGot W[{cost.W.shape}],", "field \"{}\" with dimension {} (you have {})'.format(field_, tuple(dims), value_shape))", "cost.cost_type == 'LINEAR_LS': ny = cost.W.shape[0] if cost.Vx.shape[0] != ny", "2: raise Exception('AcadosOcpSolver.solve(): argument \\'rti_phase\\' can ' 'take only values", "THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A", "casadi_length(model.cost_y_expr) != ny: raise Exception('inconsistent dimension ny: regarding W, cost_y_expr.')", "ush.') dims.nsh = nsh nsphi = constraints.idxsphi.shape[0] if is_empty(constraints.lsphi): constraints.lsphi", "out_file = '{}_phi_constraint.h'.format(name) render_template(in_file, out_file, template_dir, json_path) # terminal constraints", "Exception('inconsistent dimension nsh_e, regarding idxsh_e, ush_e.') dims.nsh_e = nsh_e nsg_e", "is_empty(model.cost_y_expr_e) and ny_e != 0: raise Exception('inconsistent dimension ny_e: regarding", "acados_ocp.dims.nphi_e > 0 or acados_ocp.dims.nh_e > 0: generate_c_code_constraint(model, model.name, True,", "cost function if acados_ocp.cost.cost_type == 'NONLINEAR_LS': template_dir = 'c_generated_code/{}_cost/'.format(name) in_file", "float. You have {}.'.format(field_, type(value_))) else: value_ctypes = c_double(value_) elif", "constraints.lsbu.shape[0] != nsbu: raise Exception('inconsistent dimension nsbu, regarding idxsbu, lsbu.')", "!= nsh_e: raise Exception('inconsistent dimension nsh_e, regarding idxsh_e, lsh_e.') if", "dimension nsbu, regarding idxsbu, lsbu.') if is_empty(constraints.usbu): constraints.usbu = np.zeros((nsbu,))", "sum(opts.time_steps) = {tf}.') def get_ocp_nlp_layout(): current_module = sys.modules[__name__] acados_path =", "out_file, template_dir, json_path) in_file = 'acados_solver.in.c' out_file = 'acados_solver_{}.c'.format(name) render_template(in_file,", "BSD License # # Redistribution and use in source and", "elif acados_ocp.cost.cost_type_e == 'EXTERNAL': generate_c_code_external_cost(model, True) def ocp_render_templates(acados_ocp, json_file): name", "int): raise Exception('solver option {} must be of type int.", "if is_empty(constraints.usg): constraints.usg = np.zeros((nsg,)) elif constraints.usg.shape[0] != nsg: raise", "= nsh_e nsg_e = constraints.idxsg_e.shape[0] if is_empty(constraints.lsg_e): constraints.lsg_e = np.zeros((nsg_e,))", "elif constraints.usbx.shape[0] != nsbx: raise Exception('inconsistent dimension nsbx, regarding idxsbx,", "def ocp_generate_external_functions(acados_ocp, model): model = make_model_consistent(model) if acados_ocp.solver_options.integrator_type == 'ERK':", "'time_qp', 'time_qp_solver_call', 'time_reg', 'sqp_iter'] \"\"\" fields = ['time_tot', # total", "acados_ocp def ocp_generate_external_functions(acados_ocp, model): model = make_model_consistent(model) if acados_ocp.solver_options.integrator_type ==", "self.shared_lib.ocp_nlp_dims_get_from_attr.restype = c_int dims = self.shared_lib.ocp_nlp_dims_get_from_attr(self.nlp_config, \\ self.nlp_dims, self.nlp_out, stage_,", "CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF #", "regarding idxsbx_e, usbx_e.') dims.nsbx_e = nsbx_e nsh_e = constraints.idxsh_e.shape[0] if", "'time_sim_ad', # cpu time for integrator contribution of external function", "is nonempty') else: dims.nr = casadi_length(model.con_r_expr) # terminal nbx_e =", "if stat.shape[0]>3: print('\\t{:e}\\t{:e}\\t{:e}\\t{:e}'.format( \\ stat[3][jj], stat[4][jj], stat[5][jj], stat[6][jj])) print('\\n') return", "OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON", "if cost.yref_e.shape[0] != ny_e: raise Exception('inconsistent dimension: regarding W_e, yref_e.')", "have {}.'.format(field_, type(value_))) else: value_ctypes = value_.encode('utf-8') if field_ ==", "= nsbx + nsbu + nsh + nsg + nsphi", "found!'.format(json_path)) template_dir = 'c_generated_code/' ## Render templates in_file = 'main.in.c'", "double_fields: if not isinstance(value_, float): raise Exception('solver option {} must", "if is_empty(opts.time_steps) and is_empty(opts.shooting_nodes): # uniform discretization opts.time_steps = opts.tf", "{nsphi}') dims.ns = ns nsbx_e = constraints.idxsbx_e.shape[0] if is_empty(constraints.lsbx_e): constraints.lsbx_e", "acados_path = os.path.dirname(current_module.__file__) with open(acados_path + '/acados_layout.json', 'r') as f:", "= tf != sum(opts.time_steps) = {tf}.') def get_ocp_nlp_layout(): current_module =", "must retain the above copyright notice, # this list of", "= c_void_p self.nlp_config = self.shared_lib.acados_get_nlp_config() self.shared_lib.acados_get_nlp_out.restype = c_void_p self.nlp_out =", "= {tf}.') def get_ocp_nlp_layout(): current_module = sys.modules[__name__] acados_path = os.path.dirname(current_module.__file__)", "regarding W, yref.' + \\ f'\\nGot W[{cost.W.shape}], yref[{cost.yref.shape}]\\n') dims.ny =", "if is_empty(constraints.lsphi): constraints.lsphi = np.zeros((nsphi,)) elif constraints.lsphi.shape[0] != nsphi: raise", "cost_y_expr_e.') elif casadi_length(model.cost_y_expr_e) != ny_e: raise Exception('inconsistent dimension ny_e: regarding", "return status def get(self, stage_, field_): \"\"\" get the last", "== 'EXTERNAL': generate_c_code_external_cost(model, True) def ocp_render_templates(acados_ocp, json_file): name = acados_ocp.model.name", "constraints \\n lam: multipliers for inequalities \\n t: slack variables", "'take only values 0, 1, 2 for SQP-RTI-type solvers') if", "dims.ny_e = ny_e elif cost.cost_type_e == 'NONLINEAR_LS': ny_e = cost.W_e.shape[0]", "# terminal constraints on convex over nonlinear function if acados_ocp.constraints.constr_type_e", "acados_ocp.constraints model = acados_ocp.model opts = acados_ocp.solver_options # nx if", "in string_fields: self.shared_lib.ocp_nlp_solver_opts_set.argtypes = \\ [c_void_p, c_void_p, c_char_p, c_char_p] self.shared_lib.ocp_nlp_solver_opts_set(self.nlp_config,", "make_ocp_dims_consistent(acados_ocp): dims = acados_ocp.dims cost = acados_ocp.cost constraints = acados_ocp.constraints", "value_ctypes = c_double(value_) elif field_ in string_fields: if not isinstance(value_,", "materials provided with the distribution. # # THIS SOFTWARE IS", "dimension: regarding W_e, yref_e.') dims.ny_e = ny_e ## constraints #", "consistent make_ocp_dims_consistent(acados_ocp) if acados_ocp.solver_options.integrator_type == 'GNSF': set_up_imported_gnsf_model(acados_ocp) # set integrator", "columns.') if cost.Vu.shape[1] != dims.nu and ny != 0: raise", "cost_y_expr_e.') if cost.yref_e.shape[0] != ny_e: raise Exception('inconsistent dimension: regarding W_e,", "must reproduce the above copyright notice, # this list of", "nsbu + nsg + nsh + nsphi.\\n\\t'\\ + f'With nsbx", "acados_ocp.cost.cost_type == 'LINEAR_LS': acados_ocp.cost.Vx = np.zeros((acados_ocp.dims.ny, acados_ocp.dims.nx)) acados_ocp.cost.Vu = np.zeros((acados_ocp.dims.ny,", "= ['step_length'] string_fields = ['globalization'] if field_ in int_fields: if", "automatically acados_ocp.solver_options.Tsim = acados_ocp.solver_options.time_steps[0] # generate external functions ocp_generate_external_functions(acados_ocp, model)", "'c_generated_code/{}_cost/'.format(name) in_file = 'external_cost.in.h' out_file = '{}_external_cost.h'.format(name) render_template(in_file, out_file, template_dir,", "value_ctypes = value_.encode('utf-8') if field_ == 'rti_phase': if value_ <", "nh: raise Exception('inconsistent dimension nh, regarding lh, uh, con_h_expr.') else:", "dims.nsbu = nsbu nsh = constraints.idxsh.shape[0] if is_empty(constraints.lsh): constraints.lsh =", "shooting_nodes ocp_nlp_dict['solver_options'].pop('shooting_nodes', None) dims_dict = acados_class2dict(acados_ocp.dims) ocp_check_against_layout(ocp_nlp_dict, dims_dict) with open(json_file,", "stage, field, value_data_p) elif field_ in cost_fields: self.shared_lib.ocp_nlp_cost_model_set.argtypes = \\", "dummy matrices if not acados_ocp.cost.cost_type == 'LINEAR_LS': acados_ocp.cost.Vx = np.zeros((acados_ocp.dims.ny,", "stage_, field, dims_data) value_shape = value_.shape if len(value_shape) == 1:", "!= dims.np: raise Exception('inconsistent dimension np, regarding model.p and parameter_values.')", "up loader and environment json_path = '{cwd}/{json_file}'.format( cwd=os.getcwd(), json_file=json_file) if", "Exception('inconsistent dimension: Vx_e should have nx columns.') if cost.yref_e.shape[0] !=", "= 'model.in.h' out_file = '{}_model.h'.format(name) render_template(in_file, out_file, template_dir, json_path) #", "!= tuple(dims): raise Exception('AcadosOcpSolver.constraints_set(): mismatching dimension' \\ ' for field", "dict(generate_hess=1) else: opts = dict(generate_hess=0) if acados_ocp.dims.nphi > 0 or", "lbu.') else: dims.nbu = nbu ng = constraints.lg.shape[0] if constraints.ug.shape[0]", "template_dir = 'c_generated_code/{}_constraints/'.format(name) in_file = 'phi_e_constraint.in.h' out_file = '{}_phi_e_constraint.h'.format(name) render_template(in_file,", "json_file='acados_ocp_nlp.json'): self.solver_created = False model = acados_ocp.model # make dims", "dimension ng, regarding lg, ug, C, D.') else: dims.ng =", "{nsbu}, nsg = {nsg}, nsh = {nsh}, nsphi = {nsphi}')", "of the solver: :param stage_: integer corresponding to shooting node", "# This file is part of acados. # # The", "!= nsbx_e: raise Exception('inconsistent dimension nsbx_e, regarding idxsbx_e, lsbx_e.') if", "acados_ocp.dims.nu)) if not acados_ocp.cost.cost_type_e == 'LINEAR_LS': acados_ocp.cost.Vx_e = np.zeros((acados_ocp.dims.ny_e, acados_ocp.dims.nx))", "value_.shape[0]) raise Exception(msg) value_data = cast(value_.ctypes.data, POINTER(c_double)) value_data_p = cast((value_data),", "== constraints.ubx_0): dims.nbxe_0 = dims.nbx_0 # path nbx = constraints.idxbx.shape[0]", "raise Exception('AcadosOcpSolver.solve(): argument \\'rti_phase\\' can ' 'take only values 0,", "print('\\t{:e}\\t{:e}\\t{:e}\\t{:e}'.format( \\ stat[7][jj], stat[8][jj], stat[9][jj], stat[10][jj])) print('\\n') elif self.acados_ocp.solver_options.nlp_solver_type ==", "SQP-RTI-type solvers') if self.acados_ocp.solver_options.nlp_solver_type != 'SQP_RTI' and value_ > 0:", "'LINEAR_LS': acados_ocp.cost.Vx = np.zeros((acados_ocp.dims.ny, acados_ocp.dims.nx)) acados_ocp.cost.Vu = np.zeros((acados_ocp.dims.ny, acados_ocp.dims.nu)) if", "c_char_p, c_char_p] self.shared_lib.ocp_nlp_solver_opts_set(self.nlp_config, \\ self.nlp_opts, field, value_ctypes) else: self.shared_lib.ocp_nlp_solver_opts_set.argtypes =", "field, out_data) return out # Note: this function should not", "= np.zeros((nsg,)) elif constraints.usg.shape[0] != nsg: raise Exception('inconsistent dimension nsg,", "\\ self.nlp_dims, self.nlp_in, stage, field, value_data_p) return def options_set(self, field_,", "attributes if not isinstance(v, dict): continue # setattr(ocp_nlp, acados_struct, dict(getattr(acados_ocp,", "wrong_field = \"Zl\" dim = cost.Zl.shape[0] elif cost.Zu.shape[0] != ns:", "!= nsg: raise Exception('inconsistent dimension nsg, regarding idxsg, lsg.') if", "render_template(in_file, out_file, template_dir, json_path) # nonlinear constraints if acados_ocp.constraints.constr_type ==", "c_int(value_) elif field_ in double_fields: if not isinstance(value_, float): raise", "dims.nz = casadi_length(model.z) # np if is_empty(model.p): dims.np = 0", "idxsbu, usbu.') dims.nsbu = nsbu nsh = constraints.idxsh.shape[0] if is_empty(constraints.lsh):", "# load class dict acados_ocp.__dict__ = ocp_nlp_dict # laod class", "C_e.') else: dims.ng_e = ng_e if not is_empty(model.con_h_expr_e): nh_e =", "idxsbx_e, usbx_e.') dims.nsbx_e = nsbx_e nsh_e = constraints.idxsh_e.shape[0] if is_empty(constraints.lsh_e):", "the solver: :param stage_: integer corresponding to shooting node :param", "in_file = 'acados_solver.in.c' out_file = 'acados_solver_{}.c'.format(name) render_template(in_file, out_file, template_dir, json_path)", "is_empty(model.con_phi_expr_e): dims.nphi_e = 0 dims.nr_e = 0 else: dims.nphi_e =", "= 'acados_solver.in.h' out_file = 'acados_solver_{}.h'.format(name) render_template(in_file, out_file, template_dir, json_path) in_file", "cpu time previous call 'time_lin', # cpu time for linearization", "is_empty(constraints.usphi_e): constraints.usphi_e = np.zeros((nsphi_e,)) elif constraints.usphi_e.shape[0] != nsphi_e: raise Exception('inconsistent", "con_h_expr.') else: dims.nh = nh if is_empty(model.con_phi_expr): dims.nphi = 0", "\"\"\" def __init__(self, acados_ocp, json_file='acados_ocp_nlp.json'): self.solver_created = False model =", "\"zu\" dim = cost.zu.shape[0] if wrong_field != \"\": raise Exception(f'Inconsistent", "value_data_p = cast((value_data), c_void_p) self.shared_lib.ocp_nlp_constraints_model_set.argtypes = \\ [c_void_p, c_void_p, c_void_p,", "acados_ocp.cost.cost_type_e == 'EXTERNAL': template_dir = 'c_generated_code/{}_cost/'.format(name) in_file = 'external_cost_e.in.h' out_file", "!= ny: raise Exception('inconsistent dimension: regarding W, yref.' + \\", "shooting_nodes.') time_steps = np.zeros((dims.N,)) for i in range(dims.N): time_steps[i] =", "if cost.Vx_e.shape[0] != ny_e: raise Exception('inconsistent dimension ny_e: regarding W_e,", "COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT,", "dimension nsg_e, regarding idxsg_e, usg_e.') dims.nsg_e = nsg_e nsphi_e =", "if acados_ocp.dims.nphi_e > 0 or acados_ocp.dims.nh_e > 0: generate_c_code_constraint(model, model.name,", "of the solver: :param stage: integer corresponding to shooting node", "solution 'time_qp_solver_call', # cpu time inside qp solver (without converting", "if is_empty(model.u): dims.nu = 0 else: dims.nu = casadi_length(model.u) #", "POINTER(c_int)] self.shared_lib.ocp_nlp_cost_dims_get_from_attr.restype = c_int dims = np.ascontiguousarray(np.zeros((2,)), dtype=np.intc) dims_data =", "argument \\'rti_phase\\' can ' 'take only value 0 for SQP-type", "= acados_ocp.solver_options # nx if is_column(model.x): dims.nx = casadi_length(model.x) else:", "import generate_c_code_gnsf from .generate_c_code_constraint import generate_c_code_constraint from .generate_c_code_nls_cost import generate_c_code_nls_cost", "skip non dict attributes if not isinstance(v, dict): continue #", "> 0: raise Exception('AcadosOcpSolver.solve(): argument \\'rti_phase\\' can ' 'take only", "value_.encode('utf-8') if field_ == 'rti_phase': if value_ < 0 or", "= nsg ns = nsbx + nsbu + nsh +", "make_model_consistent,\\ set_up_imported_gnsf_model def make_ocp_dims_consistent(acados_ocp): dims = acados_ocp.dims cost = acados_ocp.cost", "cast(value_.ctypes.data, POINTER(c_double)) value_data_p = cast((value_data), c_void_p) if field_ in constraints_fields:", "def ocp_render_templates(acados_ocp, json_file): name = acados_ocp.model.name # setting up loader", "np.ascontiguousarray(np.zeros((2,)), dtype=np.intc) dims_data = cast(dims.ctypes.data, POINTER(c_int)) self.shared_lib.ocp_nlp_cost_dims_get_from_attr(self.nlp_config, \\ self.nlp_dims, self.nlp_out,", "cost.zu_e.shape[0] if wrong_field != \"\": raise Exception(f'Inconsistent size for field", "AND CONTRIBUTORS \"AS IS\" # AND ANY EXPRESS OR IMPLIED", "out_file, template_dir, json_path) in_file = 'acados_sim_solver.in.h' out_file = 'acados_sim_solver_{}.h'.format(name) render_template(in_file,", "value_shape)) value_data = cast(value_.ctypes.data, POINTER(c_double)) value_data_p = cast((value_data), c_void_p) self.shared_lib.ocp_nlp_cost_model_set.argtypes", "nonlinear cost function if acados_ocp.cost.cost_type_e == 'NONLINEAR_LS': template_dir = 'c_generated_code/{}_cost/'.format(name)", "Exception('inconsistent dimension ny_e: regarding W_e, cost_y_expr_e.') elif casadi_length(model.cost_y_expr_e) != ny_e:", "acados_ocp.dims.nx)) if acados_ocp.cost.cost_type == 'NONLINEAR_LS': generate_c_code_nls_cost(model, model.name, False) elif acados_ocp.cost.cost_type", "raise Exception(\"ocp_generate_external_functions: unknown integrator type.\") if acados_ocp.solver_options.hessian_approx == 'EXACT': opts", "default=np_array_to_list, indent=4, sort_keys=True) def ocp_formulation_json_load(json_file='acados_ocp_nlp.json'): # Load acados_ocp_nlp structure description", "if field_ in ['sqp_iter', 'stat_m', 'stat_n']: out = np.ascontiguousarray(np.zeros((1,)), dtype=np.int64)", "option {} must be of type float. You have {}.'.format(field_,", "slack variables of soft upper inequality constraints \\n \"\"\" out_fields", ":param field_: string, e.g. 'print_level', 'rti_phase', 'initialize_t_slacks', 'step_length' :param value_:", "sl: slack variables of soft lower inequality constraints \\n su:", "if value_ < 0 or value_ > 2: raise Exception('AcadosOcpSolver.solve():", "constraints.ush_e = np.zeros((nsh_e,)) elif constraints.ush_e.shape[0] != nsh_e: raise Exception('inconsistent dimension", "casadi_length(model.p) if acados_ocp.parameter_values.shape[0] != dims.np: raise Exception('inconsistent dimension np, regarding", "nsg_e: raise Exception('inconsistent dimension nsg_e, regarding idxsg_e, usg_e.') dims.nsg_e =", "in_file = 'external_cost_e.in.h' out_file = '{}_external_cost_e.h'.format(name) render_template(in_file, out_file, template_dir, json_path)", "c_char_p, c_void_p] self.shared_lib.ocp_nlp_cost_model_set(self.nlp_config, \\ self.nlp_dims, self.nlp_in, stage, field, value_data_p) return", "field = field.encode('utf-8') if field_ in string_fields: self.shared_lib.ocp_nlp_solver_opts_set.argtypes = \\", "constraints.idxsg.shape[0] if is_empty(constraints.lsg): constraints.lsg = np.zeros((nsg,)) elif constraints.lsg.shape[0] != nsg:", "the ocp with current input \"\"\" status = self.shared_lib.acados_solve() return", "stat[4][jj], stat[5][jj], stat[6][jj])) print('\\n') return def get_stats(self, field_): \"\"\" get", "# strip shooting_nodes ocp_nlp_dict['solver_options'].pop('shooting_nodes', None) dims_dict = acados_class2dict(acados_ocp.dims) ocp_check_against_layout(ocp_nlp_dict, dims_dict)", "nu if is_empty(model.u): dims.nu = 0 else: dims.nu = casadi_length(model.u)", "self.shared_lib.acados_get_nlp_dims.restype = c_void_p self.nlp_dims = self.shared_lib.acados_get_nlp_dims() self.shared_lib.acados_get_nlp_config.restype = c_void_p self.nlp_config", "acados_ocp.parameter_values.shape[0] != dims.np: raise Exception('inconsistent dimension np, regarding model.p and", "= 'make_sfun.m' render_template(in_file, out_file, template_dir, json_path) in_file = 'acados_sim_solver.in.c' out_file", "c_void_p] self.shared_lib.ocp_nlp_get_at_stage(self.nlp_config, \\ self.nlp_dims, self.nlp_solver, stage_, field, out_data) return out", "is_empty(opts.shooting_nodes)): Exception('Please provide either time_steps or shooting_nodes for nonuniform discretization')", "out_file, template_dir, json_path) # nonlinear cost function if acados_ocp.cost.cost_type ==", "out = np.ascontiguousarray(np.zeros((1,)), dtype=np.int64) out_data = cast(out.ctypes.data, POINTER(c_int64)) elif field_", "nbu = constraints.idxbu.shape[0] if constraints.ubu.shape[0] != nbu or constraints.lbu.shape[0] !=", "if is_empty(model.cost_y_expr) and ny != 0: raise Exception('inconsistent dimension ny:", "Compile solver os.chdir('c_generated_code') os.system('make clean_ocp_shared_lib') os.system('make ocp_shared_lib') os.chdir('..') self.shared_lib_name =", "value_shape = (value_shape[0], 0) if value_shape != tuple(dims): raise Exception('AcadosOcpSolver.cost_set():", "solvers') field = field_ field = field.encode('utf-8') if field_ in", "nsg + nsh + nsphi.\\n\\t'\\ + f'With nsbx = {nsbx},", "= c_int(stage_) # treat parameters separately if field_ is 'p':", "{} (you have {})'.format(dims, value_.shape[0]) raise Exception(msg) value_data = cast(value_.ctypes.data,", "# cpu time for integrator 'time_sim_ad', # cpu time for", "fields): raise Exception('AcadosOcpSolver.get_stats(): {} is not a valid argument.\\ \\n", "import CasadiMeta, Function, SX from copy import deepcopy from .generate_c_code_explicit_ode", "cost_fields = ['y_ref', 'yref'] constraints_fields = ['lbx', 'ubx', 'lbu', 'ubu']", "ng: raise Exception('inconsistent dimension ng, regarding lg, ug, C, D.')", "= constraints.idxbx.shape[0] if constraints.ubx.shape[0] != nbx or constraints.lbx.shape[0] != nbx:", "raise Exception('inconsistent dimension nsphi, regarding idxsphi, usphi.') dims.nsphi = nsphi", "lsh_e.') if is_empty(constraints.ush_e): constraints.ush_e = np.zeros((nsh_e,)) elif constraints.ush_e.shape[0] != nsh_e:", "if acados_ocp.cost.cost_type_e == 'NONLINEAR_LS': template_dir = 'c_generated_code/{}_cost/'.format(name) in_file = 'cost_y_e_fun.in.h'", "== 'EXTERNAL': template_dir = 'c_generated_code/{}_cost/'.format(name) in_file = 'external_cost_e.in.h' out_file =", "\\ self.nlp_dims, self.nlp_out, stage_, field, dims_data) value_shape = value_.shape if", "json_path) # terminal nonlinear cost function if acados_ocp.cost.cost_type_e == 'NONLINEAR_LS':", "shapes!') if not is_column(constraints.lbx_0): raise Exception('lbx_0, ubx_0 must be column", "json_path) # external cost if acados_ocp.cost.cost_type == 'EXTERNAL': template_dir =", "\"AS IS\" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,", "nsphi_e = constraints.idxsphi_e.shape[0] if is_empty(constraints.lsphi_e): constraints.lsphi_e = np.zeros((nsphi_e,)) elif constraints.lsphi_e.shape[0]", "0: generate_c_code_constraint(model, model.name, True, opts) # dummy matrices if not", "# total cpu time previous call 'time_lin', # cpu time", "cost.yref.shape[0] != ny: raise Exception('inconsistent dimension: regarding W, yref.' +", "W_e, cost_y_expr_e.') if cost.yref_e.shape[0] != ny_e: raise Exception('inconsistent dimension: regarding", "regarding idxsbu, lsbu.') if is_empty(constraints.usbu): constraints.usbu = np.zeros((nsbu,)) elif constraints.usbu.shape[0]", "out_file = 'acados_sim_solver_{}.h'.format(name) render_template(in_file, out_file, template_dir, json_path) ## folder model", "inside qp solver (without converting the QP) 'time_qp_xcond', 'time_reg', #", "CONTRIBUTORS \"AS IS\" # AND ANY EXPRESS OR IMPLIED WARRANTIES,", "time_steps = np.zeros((dims.N,)) for i in range(dims.N): time_steps[i] = opts.shooting_nodes[i+1]", "stage, field, value_data_p) elif field_ in out_fields: self.shared_lib.ocp_nlp_out_set.argtypes = \\", "field.encode('utf-8') stage = c_int(stage_) self.shared_lib.ocp_nlp_constraint_dims_get_from_attr.argtypes = \\ [c_void_p, c_void_p, c_void_p,", "with dimension {} (you have {})'.format(field_, tuple(dims), value_shape)) value_data =", "string in ['x', 'u', 'z', 'pi', 'lam', 't', 'sl', 'su',]", "ny_e != 0: raise Exception('inconsistent dimension: Vx_e should have nx", "\\n lam: multipliers for inequalities \\n t: slack variables corresponding", "Exception('lbx_0, ubx_0 must be column vectors!') dims.nbx_0 = constraints.lbx_0.size if", "= nbx_e ng_e = constraints.lg_e.shape[0] if constraints.ug_e.shape[0] != ng_e or", "'rti_phase': if value_ < 0 or value_ > 2: raise", "nsphi = constraints.idxsphi.shape[0] if is_empty(constraints.lsphi): constraints.lsphi = np.zeros((nsphi,)) elif constraints.lsphi.shape[0]", "dimension ny_e: regarding W_e, cost_y_expr_e.') if cost.yref_e.shape[0] != ny_e: raise", "corresponding to shooting node :param field_: string in ['x', 'u',", "object attributes dictionaries ocp_nlp_dict[acados_struct]=dict(getattr(acados_ocp, acados_struct).__dict__) ocp_nlp_dict = format_class_dict(ocp_nlp_dict) # strip", "FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL", "elif cost.zl_e.shape[0] != ns_e: wrong_field = \"zl_e\" dim = cost.zl_e.shape[0]", "# cast value_ to avoid conversion issues value_ = value_.astype(float)", "== 'SQP_RTI': print('\\niter\\tqp_stat\\tqp_iter') if stat.shape[0]>3: print('\\tqp_res_stat\\tqp_res_eq\\tqp_res_ineq\\tqp_res_comp') for jj in range(stat.shape[1]):", "# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR", "raise Exception('inconsistent dimension nbx, regarding idxbx, ubx, lbx.') else: dims.nbx", "type.\") if acados_ocp.solver_options.hessian_approx == 'EXACT': opts = dict(generate_hess=1) else: opts", "field = field.encode('utf-8') stage = c_int(stage_) self.shared_lib.ocp_nlp_constraint_dims_get_from_attr.argtypes = \\ [c_void_p,", "valid argument.\\ \\nPossible values are {}. Exiting.\".format(field, \\ constraints_fields +", "= ['y_ref', 'yref'] constraints_fields = ['lbx', 'ubx', 'lbu', 'ubu'] out_fields", "value_ > 0: raise Exception('AcadosOcpSolver.solve(): argument \\'rti_phase\\' can ' 'take", "'time_reg', # cpu time regularization 'sqp_iter', # number of SQP", "ng_e if not is_empty(model.con_h_expr_e): nh_e = casadi_length(model.con_h_expr_e) else: nh_e =", "over nonlinear constraints: con_r_expr_e but con_phi_expr_e is nonempty') else: dims.nr_e", "stat.shape[0]>7: print('\\tqp_res_stat\\tqp_res_eq\\tqp_res_ineq\\tqp_res_comp') for jj in range(stat.shape[1]): print('{:d}\\t{:e}\\t{:e}\\t{:e}\\t{:e}\\t{:d}\\t{:d}'.format( \\ int(stat[0][jj]), stat[1][jj],", "= '{}_phi_e_constraint.h'.format(name) render_template(in_file, out_file, template_dir, json_path) # nonlinear constraints if", "print('{:d}\\t{:e}\\t{:e}\\t{:e}\\t{:e}\\t{:d}\\t{:d}'.format( \\ int(stat[0][jj]), stat[1][jj], stat[2][jj], \\ stat[3][jj], stat[4][jj], int(stat[5][jj]), int(stat[6][jj])))", "ubu, lbu.') else: dims.nbu = nbu ng = constraints.lg.shape[0] if", "TODO: maybe make one funciton with formatting for acados_struct, v", "= casadi_length(model.con_phi_expr) if is_empty(model.con_r_expr): raise Exception('convex over nonlinear constraints: con_r_expr", "constraints, etc for acados_struct, v in ocp_layout.items(): # skip non", "ny = cost.W.shape[0] if is_empty(model.cost_y_expr) and ny != 0: raise", "not found!'.format(json_path)) template_dir = 'c_generated_code/' ## Render templates in_file =", "= 0 if constraints.uh_e.shape[0] != nh_e or constraints.lh_e.shape[0] != nh_e:", "solvers') if self.acados_ocp.solver_options.nlp_solver_type != 'SQP_RTI' and value_ > 0: raise", "dims.nphi = 0 dims.nr = 0 else: dims.nphi = casadi_length(model.con_phi_expr)", "C object \"\"\" def __init__(self, acados_ocp, json_file='acados_ocp_nlp.json'): self.solver_created = False", "= value_.encode('utf-8') if field_ == 'rti_phase': if value_ < 0", "for jj in range(stat.shape[1]): print('{:d}\\t{:e}\\t{:e}\\t{:e}\\t{:e}\\t{:d}\\t{:d}'.format( \\ int(stat[0][jj]), stat[1][jj], stat[2][jj], \\", "= np.ascontiguousarray(np.zeros((2,)), dtype=np.intc) dims_data = cast(dims.ctypes.data, POINTER(c_int)) self.shared_lib.ocp_nlp_constraint_dims_get_from_attr(self.nlp_config, \\ self.nlp_dims,", ":param value_: of appropriate size \"\"\" # cast value_ to", "acados_ocp def solve(self): \"\"\" solve the ocp with current input", "have {})'.format( \\ field_, tuple(dims), value_shape)) value_data = cast(value_.ctypes.data, POINTER(c_double))", "np.zeros((nsh_e,)) elif constraints.lsh_e.shape[0] != nsh_e: raise Exception('inconsistent dimension nsh_e, regarding", "template_dir = 'c_generated_code/{}_constraints/'.format(name) in_file = 'h_constraint.in.h' out_file = '{}_h_constraint.h'.format(name) render_template(in_file,", "are {}. Exiting.'.format(field_, out_fields + mem_fields)) self.shared_lib.ocp_nlp_dims_get_from_attr.argtypes = \\ [c_void_p,", "'NONLINEAR_LS': ny_e = cost.W_e.shape[0] if is_empty(model.cost_y_expr_e) and ny_e != 0:", "with info about last iteration 'stat_m', 'stat_n', ] field =", "\\ f'\\nGot W[{cost.W.shape}], yref[{cost.yref.shape}]\\n') dims.ny = ny elif cost.cost_type ==", "from .generate_c_code_gnsf import generate_c_code_gnsf from .generate_c_code_constraint import generate_c_code_constraint from .generate_c_code_nls_cost", "or without # modification, are permitted provided that the following", "IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE", "symbolics ocp_nlp_dict['model'] = acados_model_strip_casadi_symbolics(ocp_nlp_dict['model']) # strip shooting_nodes ocp_nlp_dict['solver_options'].pop('shooting_nodes', None) dims_dict", "is_empty(model.con_h_expr_e): nh_e = casadi_length(model.con_h_expr_e) else: nh_e = 0 if constraints.uh_e.shape[0]", "field = field.encode('utf-8') if (field_ not in out_fields + mem_fields):", "dims = self.shared_lib.ocp_nlp_dims_get_from_attr(self.nlp_config, \\ self.nlp_dims, self.nlp_out, stage_, field) if value_.shape[0]", "regarding W, cost_y_expr.') if cost.yref.shape[0] != ny: raise Exception('inconsistent dimension:", "dims.np = casadi_length(model.p) if acados_ocp.parameter_values.shape[0] != dims.np: raise Exception('inconsistent dimension", "cpu time for integrator contribution of external function calls 'time_sim_la',", "acados_ocp.cost.cost_type == 'EXTERNAL': template_dir = 'c_generated_code/{}_cost/'.format(name) in_file = 'external_cost.in.h' out_file", "field_): \"\"\" get the last solution of the solver: :param", "\\ [c_void_p, c_void_p, c_void_p, c_int, c_char_p, c_void_p] self.shared_lib.ocp_nlp_out_get(self.nlp_config, \\ self.nlp_dims,", "field_ field = field.encode('utf-8') stage = c_int(stage_) # treat parameters", "time qp solution 'time_qp_solver_call', # cpu time inside qp solver", "'w') as f: json.dump(ocp_nlp_dict, f, default=np_array_to_list, indent=4, sort_keys=True) def ocp_formulation_json_load(json_file='acados_ocp_nlp.json'):", "dimension nsh, regarding idxsh, lsh.') if is_empty(constraints.ush): constraints.ush = np.zeros((nsh,))", "integrator time automatically acados_ocp.solver_options.Tsim = acados_ocp.solver_options.time_steps[0] # generate external functions", ".acados_ocp import AcadosOcp from .acados_model import acados_model_strip_casadi_symbolics from .utils import", "'{}_h_constraint.h'.format(name) render_template(in_file, out_file, template_dir, json_path) # terminal nonlinear constraints if", "constraints.usg_e = np.zeros((nsg_e,)) elif constraints.usg_e.shape[0] != nsg_e: raise Exception('inconsistent dimension", "= 'c_generated_code/{}_model/'.format(name) in_file = 'model.in.h' out_file = '{}_model.h'.format(name) render_template(in_file, out_file,", "value_shape != tuple(dims): raise Exception('AcadosOcpSolver.constraints_set(): mismatching dimension' \\ ' for", "value_: of type int, float \"\"\" int_fields = ['print_level', 'rti_phase',", "is_column, is_empty, casadi_length, render_template, acados_class2dict,\\ format_class_dict, ocp_check_against_layout, np_array_to_list, make_model_consistent,\\ set_up_imported_gnsf_model", "elif cost.cost_type_e == 'NONLINEAR_LS': ny_e = cost.W_e.shape[0] if is_empty(model.cost_y_expr_e) and", "nbx_e ng_e = constraints.lg_e.shape[0] if constraints.ug_e.shape[0] != ng_e or constraints.C_e.shape[0]", "USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED", "(tf - opts.tf) / tf > 1e-15: raise Exception(f'Inconsistent discretization:", "regarding idxbx_e, ubx_e, lbx_e.') else: dims.nbx_e = nbx_e ng_e =", "raise Exception('{} not found!'.format(json_path)) template_dir = 'c_generated_code/' ## Render templates", "wrong_field = \"zl\" dim = cost.zl.shape[0] elif cost.zu.shape[0] != ns:", "cost.Zu_e.shape[0] elif cost.zl_e.shape[0] != ns_e: wrong_field = \"zl_e\" dim =", "regarding W_e, cost_y_expr_e.' + \\ f'\\nGot W_e[{cost.W_e.shape}], Vx_e[{cost.Vx_e.shape}]') if cost.Vx_e.shape[1]", "self.get_stats(\"stat_m\") stat_n = self.get_stats(\"stat_n\") min_size = min([stat_m, sqp_iter+1]) out =", "cast((value_data), c_void_p) self.shared_lib.ocp_nlp_cost_model_set.argtypes = \\ [c_void_p, c_void_p, c_void_p, c_int, c_char_p,", "== 'statistics': sqp_iter = self.get_stats(\"sqp_iter\") stat_m = self.get_stats(\"stat_m\") stat_n =", "nu columns.') if cost.yref.shape[0] != ny: raise Exception('inconsistent dimension: regarding", "constraints.usphi_e = np.zeros((nsphi_e,)) elif constraints.usphi_e.shape[0] != nsphi_e: raise Exception('inconsistent dimension", "copy import deepcopy from .generate_c_code_explicit_ode import generate_c_code_explicit_ode from .generate_c_code_implicit_ode import", "return ocp_nlp_layout def ocp_formulation_json_dump(acados_ocp, json_file='acados_ocp_nlp.json'): # Load acados_ocp_nlp structure description", "values are {}. Exiting.\".format(field, \\ constraints_fields + cost_fields + out_fields", "field_ field = field.encode('utf-8') stage = c_int(stage_) self.shared_lib.ocp_nlp_cost_dims_get_from_attr.argtypes = \\", "ny elif cost.cost_type == 'NONLINEAR_LS': ny = cost.W.shape[0] if is_empty(model.cost_y_expr)", "'u', 'pi', 'lam', 't'] # cast value_ to avoid conversion", "dims.nsg_e = nsg_e nsphi_e = constraints.idxsphi_e.shape[0] if is_empty(constraints.lsphi_e): constraints.lsphi_e =", "'{}_model.h'.format(name) render_template(in_file, out_file, template_dir, json_path) # constraints on convex over", "better use cost_set, constraints_set def set(self, stage_, field_, value_): cost_fields", "Exiting.'.format(fields, fields)) if field_ in ['sqp_iter', 'stat_m', 'stat_n']: out =", "!= ns_e: wrong_field = \"Zl_e\" dim = cost.Zl_e.shape[0] elif cost.Zu_e.shape[0]", "raise Exception('inconsistent dimension ny_e: regarding W_e, cost_y_expr_e.') elif casadi_length(model.cost_y_expr_e) !=", "nonlinear constraints if acados_ocp.constraints.constr_type_e == 'BGH' and acados_ocp.dims.nh_e > 0:", "cpu time inside qp solver (without converting the QP) 'time_qp_xcond',", "OF SUCH DAMAGE.; # import sys, os, json import numpy", "Note: this function should not be used anymore, better use", "module of the solver: Parameters: :param stage_: integer corresponding to", "info about last iteration 'stat_m', 'stat_n', ] field = field_", "{}.'.format(field_, type(value_))) else: value_ctypes = c_int(value_) elif field_ in double_fields:", "if is_empty(constraints.usg_e): constraints.usg_e = np.zeros((nsg_e,)) elif constraints.usg_e.shape[0] != nsg_e: raise", "> 1e-15: raise Exception(f'Inconsistent discretization: {opts.tf}'\\ f' = tf !=", "\"\"\" set numerical data in the constraint module of the", "= '{}_model.h'.format(name) render_template(in_file, out_file, template_dir, json_path) # constraints on convex", "c_void_p, c_void_p, c_int, c_char_p, c_void_p] self.shared_lib.ocp_nlp_out_set(self.nlp_config, \\ self.nlp_dims, self.nlp_out, stage,", "dims = acados_ocp.dims cost = acados_ocp.cost constraints = acados_ocp.constraints model", "generate external functions ocp_generate_external_functions(acados_ocp, model) # dump to json ocp_formulation_json_dump(acados_ocp,", "\"\"\" class to interact with the acados ocp solver C", "string, e.g. 'lbx' :param value_: of appropriate size \"\"\" #", "np.zeros((nsbu,)) elif constraints.lsbu.shape[0] != nsbu: raise Exception('inconsistent dimension nsbu, regarding", "model.name, True, opts) # dummy matrices if not acados_ocp.cost.cost_type ==", "not is_empty(model.con_h_expr): nh = casadi_length(model.con_h_expr) else: nh = 0 if", "ocp solver C object \"\"\" def __init__(self, acados_ocp, json_file='acados_ocp_nlp.json'): self.solver_created", "i in range(dims.N): time_steps[i] = opts.shooting_nodes[i+1] - opts.shooting_nodes[i] opts.time_steps =", "\"{}\" with dimension {} (you have {})'.format( \\ field_, tuple(dims),", "'cost_y_e_fun.in.h' out_file = '{}_cost_y_e_fun.h'.format(name) render_template(in_file, out_file, template_dir, json_path) # external", "json_path) in_file = 'acados_sim_solver.in.c' out_file = 'acados_sim_solver_{}.c'.format(name) render_template(in_file, out_file, template_dir,", "THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE", "nsbx: raise Exception('inconsistent dimension nsbx, regarding idxsbx, usbx.') dims.nsbx =", "stage_, field) out = np.ascontiguousarray(np.zeros((dims,)), dtype=np.float64) out_data = cast(out.ctypes.data, POINTER(c_double))", "nsg: raise Exception('inconsistent dimension nsg, regarding idxsg, lsg.') if is_empty(constraints.usg):", "{} must be of type float. You have {}.'.format(field_, type(value_)))", "np.zeros((nsphi_e,)) elif constraints.usphi_e.shape[0] != nsphi_e: raise Exception('inconsistent dimension nsphi_e, regarding", "np.zeros((nsg,)) elif constraints.usg.shape[0] != nsg: raise Exception('inconsistent dimension nsg, regarding", "== 'BGP' and acados_ocp.dims.nphi_e > 0: # terminal constraints on", "is_empty(model.con_phi_expr): dims.nphi = 0 dims.nr = 0 else: dims.nphi =", "= ['sl', 'su'] field = field_ field = field.encode('utf-8') if", "acados_ocp.cost.cost_type_e == 'LINEAR_LS': acados_ocp.cost.Vx_e = np.zeros((acados_ocp.dims.ny_e, acados_ocp.dims.nx)) if acados_ocp.cost.cost_type ==", "opts.shooting_nodes[i+1] - opts.shooting_nodes[i] opts.time_steps = time_steps elif (not is_empty(opts.time_steps)) and", "regularization 'sqp_iter', # number of SQP iterations 'statistics', # table", "# treat parameters separately if field_ is 'p': self.shared_lib.acados_update_params.argtypes =", "+ '.so' # get self.shared_lib = CDLL(self.shared_lib_name) self.shared_lib.acados_create() self.solver_created =", "wrong_field = \"\" if cost.Zl.shape[0] != ns: wrong_field = \"Zl\"", "regarding W_e, cost_y_expr_e.') if cost.yref_e.shape[0] != ny_e: raise Exception('inconsistent dimension:", "field \"{}\" '.format(field_) msg += 'with dimension {} (you have", "json_path) in_file = 'Makefile.in' out_file = 'Makefile' render_template(in_file, out_file, template_dir,", "must be of type str. You have {}.'.format(field_, type(value_))) else:", "field_: string, e.g. 'print_level', 'rti_phase', 'initialize_t_slacks', 'step_length' :param value_: of", "path nbx = constraints.idxbx.shape[0] if constraints.ubx.shape[0] != nbx or constraints.lbx.shape[0]", "c_void_p self.nlp_config = self.shared_lib.acados_get_nlp_config() self.shared_lib.acados_get_nlp_out.restype = c_void_p self.nlp_out = self.shared_lib.acados_get_nlp_out()", "environment json_path = '{cwd}/{json_file}'.format( cwd=os.getcwd(), json_file=json_file) if not os.path.exists(json_path): raise", "0: generate_c_code_constraint(model, model.name, False, opts) if acados_ocp.dims.nphi_e > 0 or", "json_file): name = acados_ocp.model.name # setting up loader and environment", "ns: wrong_field = \"Zu\" dim = cost.Zu.shape[0] elif cost.zl.shape[0] !=", "this_shape = constraints.lbx_0.shape other_shape = constraints.ubx_0.shape if not this_shape ==", "use in source and binary forms, with or without #", "0: raise Exception('inconsistent dimension ny: regarding W, cost_y_expr.') elif casadi_length(model.cost_y_expr)", "value_shape = value_.shape if len(value_shape) == 1: value_shape = (value_shape[0],", "if not this_shape == other_shape: raise Exception('lbx_0, ubx_0 have different", "= ns_e # discretization if is_empty(opts.time_steps) and is_empty(opts.shooting_nodes): # uniform", "POINTER(c_double)) self.shared_lib.ocp_nlp_get.argtypes = [c_void_p, c_void_p, c_char_p, c_void_p] self.shared_lib.ocp_nlp_get(self.nlp_config, self.nlp_solver, field,", "ny_e = cost.W_e.shape[0] if cost.Vx_e.shape[0] != ny_e: raise Exception('inconsistent dimension", "0 if constraints.uh.shape[0] != nh or constraints.lh.shape[0] != nh: raise", "template_dir, json_path) in_file = 'acados_solver.in.h' out_file = 'acados_solver_{}.h'.format(name) render_template(in_file, out_file,", "field, out_data) return out def print_statistics(self): stat = self.get_stats(\"statistics\") if", "= self.shared_lib.acados_get_nlp_config() self.shared_lib.acados_get_nlp_out.restype = c_void_p self.nlp_out = self.shared_lib.acados_get_nlp_out() self.shared_lib.acados_get_nlp_in.restype =", "c_void_p self.nlp_out = self.shared_lib.acados_get_nlp_out() self.shared_lib.acados_get_nlp_in.restype = c_void_p self.nlp_in = self.shared_lib.acados_get_nlp_in()", "cost.zl.shape[0] elif cost.zu.shape[0] != ns: wrong_field = \"zu\" dim =", "'stat_m', 'stat_n', ] field = field_ field = field.encode('utf-8') if", "STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING", "acados_ocp.dims.nh_e > 0: generate_c_code_constraint(model, model.name, True, opts) # dummy matrices", "dynamics equality constraints \\n lam: multipliers for inequalities \\n t:", "constraints.lsh_e.shape[0] != nsh_e: raise Exception('inconsistent dimension nsh_e, regarding idxsh_e, lsh_e.')", "sort_keys=True) def ocp_formulation_json_load(json_file='acados_ocp_nlp.json'): # Load acados_ocp_nlp structure description ocp_layout =", "raise Exception('AcadosOcpSolver.get(): {} is an invalid argument.\\ \\n Possible values", "constraints \\n su: slack variables of soft upper inequality constraints", "acados_attribute.__dict__ = ocp_nlp_dict[acados_struct] setattr(acados_ocp, acados_struct, acados_attribute) return acados_ocp def ocp_generate_external_functions(acados_ocp,", "self.nlp_dims, self.nlp_out, stage_, field, dims_data) value_shape = value_.shape if len(value_shape)", "if acados_ocp.solver_options.hessian_approx == 'EXACT': opts = dict(generate_hess=1) else: opts =", "integer corresponding to shooting node :param field_: string, e.g. 'lbx'", "= ocp_nlp_dict[acados_struct] setattr(acados_ocp, acados_struct, acados_attribute) return acados_ocp def ocp_generate_external_functions(acados_ocp, model):", "elif constraints.usphi.shape[0] != nsphi: raise Exception('inconsistent dimension nsphi, regarding idxsphi,", "from casadi import CasadiMeta, Function, SX from copy import deepcopy", "dtype=np.float64) out_data = cast(out.ctypes.data, POINTER(c_double)) if (field_ in out_fields): self.shared_lib.ocp_nlp_out_get.argtypes", "template_dir, json_path) # terminal nonlinear constraints if acados_ocp.constraints.constr_type_e == 'BGH'", "Exception('inconsistent dimension nbx_e, regarding idxbx_e, ubx_e, lbx_e.') else: dims.nbx_e =", "'time_sim', 'time_sim_ad', 'time_sim_la', 'time_qp', 'time_qp_solver_call', 'time_reg', 'sqp_iter'] \"\"\" fields =", "ubx_0 have different shapes!') if not is_column(constraints.lbx_0): raise Exception('lbx_0, ubx_0", "ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES", "cost.zu.shape[0] if wrong_field != \"\": raise Exception(f'Inconsistent size for field", "out_fields: self.shared_lib.ocp_nlp_out_set.argtypes = \\ [c_void_p, c_void_p, c_void_p, c_int, c_char_p, c_void_p]", "= \"zu_e\" dim = cost.zu_e.shape[0] if wrong_field != \"\": raise", "def get_ocp_nlp_layout(): current_module = sys.modules[__name__] acados_path = os.path.dirname(current_module.__file__) with open(acados_path", "json_path) in_file = 'make_sfun.in.m' out_file = 'make_sfun.m' render_template(in_file, out_file, template_dir,", "self.nlp_in = self.shared_lib.acados_get_nlp_in() self.shared_lib.acados_get_nlp_solver.restype = c_void_p self.nlp_solver = self.shared_lib.acados_get_nlp_solver() self.acados_ocp", "## Render templates in_file = 'main.in.c' out_file = 'main_{}.c'.format(name) render_template(in_file,", "= 0 else: this_shape = constraints.lbx_0.shape other_shape = constraints.ubx_0.shape if", "value_data_p = cast((value_data), c_void_p) if field_ in constraints_fields: self.shared_lib.ocp_nlp_constraints_model_set.argtypes =", "ocp_nlp_dict['model'] = acados_model_strip_casadi_symbolics(ocp_nlp_dict['model']) # strip shooting_nodes ocp_nlp_dict['solver_options'].pop('shooting_nodes', None) dims_dict =", "stat[4][jj], int(stat[5][jj]), int(stat[6][jj]))) if stat.shape[0]>7: print('\\t{:e}\\t{:e}\\t{:e}\\t{:e}'.format( \\ stat[7][jj], stat[8][jj], stat[9][jj],", "out_fields): self.shared_lib.ocp_nlp_out_get.argtypes = \\ [c_void_p, c_void_p, c_void_p, c_int, c_char_p, c_void_p]", "= 'acados_solver_sfun.in.c' out_file = 'acados_solver_sfunction_{}.c'.format(name) render_template(in_file, out_file, template_dir, json_path) in_file", "= casadi_length(model.p) if acados_ocp.parameter_values.shape[0] != dims.np: raise Exception('inconsistent dimension np,", "constraints.ush.shape[0] != nsh: raise Exception('inconsistent dimension nsh, regarding idxsh, ush.')", "usbu usbx usg ush usphi] .. note:: pi: multipliers for", "from .utils import is_column, is_empty, casadi_length, render_template, acados_class2dict,\\ format_class_dict, ocp_check_against_layout,", "cast(out.ctypes.data, POINTER(c_int64)) elif field_ == 'statistics': sqp_iter = self.get_stats(\"sqp_iter\") stat_m", "in constraints_fields + cost_fields + out_fields: raise Exception(\"AcadosOcpSolver.set(): {} is", "dims.np = 0 else: dims.np = casadi_length(model.p) if acados_ocp.parameter_values.shape[0] !=", "dims.nx = casadi_length(model.x) else: raise Exception('model.x should be column vector!')", "OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,", "format_class_dict, ocp_check_against_layout, np_array_to_list, make_model_consistent,\\ set_up_imported_gnsf_model def make_ocp_dims_consistent(acados_ocp): dims = acados_ocp.dims", "/ tf > 1e-15: raise Exception(f'Inconsistent discretization: {opts.tf}'\\ f' =", "if acados_ocp.solver_options.integrator_type == 'GNSF': set_up_imported_gnsf_model(acados_ocp) # set integrator time automatically", "= \"zl\" dim = cost.zl.shape[0] elif cost.zu.shape[0] != ns: wrong_field", "\\n\\t'\\ + f'Detected ns_e = {ns_e} = nsbx_e + nsg_e", "ns = nsbx + nsbu + nsh + nsg +", "!= 0 and cost.Vz.shape[0] != ny: raise Exception('inconsistent dimension ny,", "= json.load(f) return ocp_nlp_layout def ocp_formulation_json_dump(acados_ocp, json_file='acados_ocp_nlp.json'): # Load acados_ocp_nlp", "evaluation of all inequalities (at the solution) \\n sl: slack", "mismatching dimension', \\ ' for field \"{}\" with dimension {}", "class AcadosOcpSolver: \"\"\" class to interact with the acados ocp", "dict, dims, constraints, etc for acados_struct, v in ocp_layout.items(): #", "nsg_e nsphi_e = constraints.idxsphi_e.shape[0] if is_empty(constraints.lsphi_e): constraints.lsphi_e = np.zeros((nsphi_e,)) elif", "= np.zeros((nsbu,)) elif constraints.lsbu.shape[0] != nsbu: raise Exception('inconsistent dimension nsbu,", "outer function template_dir = 'c_generated_code/{}_constraints/'.format(name) in_file = 'phi_constraint.in.h' out_file =", "stage, field, value_data_p) return def cost_set(self, stage_, field_, value_): \"\"\"", "dims_data = cast(dims.ctypes.data, POINTER(c_int)) self.shared_lib.ocp_nlp_constraint_dims_get_from_attr(self.nlp_config, \\ self.nlp_dims, self.nlp_out, stage_, field,", "/ dims.N * np.ones((dims.N,)) elif not is_empty(opts.shooting_nodes): if np.shape(opts.shooting_nodes)[0] !=", "'{}_cost_y_fun.h'.format(name) render_template(in_file, out_file, template_dir, json_path) # terminal nonlinear cost function", "if acados_ocp.cost.cost_type == 'EXTERNAL': template_dir = 'c_generated_code/{}_cost/'.format(name) in_file = 'external_cost.in.h'", "(you have {})'.format(field_, tuple(dims), value_shape)) value_data = cast(value_.ctypes.data, POINTER(c_double)) value_data_p", "\"\"\" out_fields = ['x', 'u', 'z', 'pi', 'lam', 't'] mem_fields", "model) # dump to json ocp_formulation_json_dump(acados_ocp, json_file) # render templates", "opts.time_steps = time_steps elif (not is_empty(opts.time_steps)) and (not is_empty(opts.shooting_nodes)): Exception('Please", "dims.ny = ny # terminal if cost.cost_type_e == 'LINEAR_LS': ny_e", "raise Exception(f'Inconsistent size for field {wrong_field}, with dimension {dim}, \\n\\t'\\", "= json2dict(ocp_nlp_json, ocp_nlp_json['dims']) # Instantiate AcadosOcp object acados_ocp = AcadosOcp()", "'main.in.c' out_file = 'main_{}.c'.format(name) render_template(in_file, out_file, template_dir, json_path) in_file =", "= acados_ocp def solve(self): \"\"\" solve the ocp with current", "jj in range(stat.shape[1]): print('{:d}\\t{:d}\\t{:d}'.format( int(stat[0][jj]), int(stat[1][jj]), int(stat[2][jj]))) if stat.shape[0]>3: print('\\t{:e}\\t{:e}\\t{:e}\\t{:e}'.format(", "con_r_expr_e but con_phi_expr_e is nonempty') else: dims.nr_e = casadi_length(model.con_r_expr_e) #", "constraints.ubx.shape[0] != nbx or constraints.lbx.shape[0] != nbx: raise Exception('inconsistent dimension", "Vx should have nx columns.') if cost.Vu.shape[1] != dims.nu and", "is_empty(model.cost_y_expr) and ny != 0: raise Exception('inconsistent dimension ny: regarding", "with dimension {dim}, \\n\\t'\\ + f'Detected ns = {ns} =", "or constraints.lbx_e.shape[0] != nbx_e: raise Exception('inconsistent dimension nbx_e, regarding idxbx_e,", "np.ascontiguousarray( np.zeros( (stat_n[0]+1, min_size[0]) ), dtype=np.float64) out_data = cast(out.ctypes.data, POINTER(c_double))", "elif casadi_length(model.cost_y_expr) != ny: raise Exception('inconsistent dimension ny: regarding W,", "ny != 0: raise Exception('inconsistent dimension ny: regarding W, cost_y_expr.')", "EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE.;", "acados_ocp.dims.nphi > 0 or acados_ocp.dims.nh > 0: generate_c_code_constraint(model, model.name, False,", "or constraints.lbu.shape[0] != nbu: raise Exception('inconsistent dimension nbu, regarding idxbu,", "['y_ref', 'yref'] constraints_fields = ['lbx', 'ubx', 'lbu', 'ubu'] out_fields =", "tuple(dims): raise Exception('AcadosOcpSolver.constraints_set(): mismatching dimension' \\ ' for field \"{}\"", "DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND", "<NAME>, <NAME>, <NAME>, <NAME> # # This file is part", "ns_e = {ns_e} = nsbx_e + nsg_e + nsh_e +", "time automatically acados_ocp.solver_options.Tsim = acados_ocp.solver_options.time_steps[0] # generate external functions ocp_generate_external_functions(acados_ocp,", "nsphi: raise Exception('inconsistent dimension nsphi, regarding idxsphi, usphi.') dims.nsphi =", "np.zeros((acados_ocp.dims.ny, acados_ocp.dims.nx)) acados_ocp.cost.Vu = np.zeros((acados_ocp.dims.ny, acados_ocp.dims.nu)) if not acados_ocp.cost.cost_type_e ==", "[c_int, POINTER(c_double)] self.shared_lib.acados_update_params.restype = c_int value_data = cast(value_.ctypes.data, POINTER(c_double)) self.shared_lib.acados_update_params(stage,", "self.nlp_in, stage, field, value_data_p) elif field_ in cost_fields: self.shared_lib.ocp_nlp_cost_model_set.argtypes =", "shooting_nodes for nonuniform discretization') tf = np.sum(opts.time_steps) if (tf -", "in_file = 'cost_y_e_fun.in.h' out_file = '{}_cost_y_e_fun.h'.format(name) render_template(in_file, out_file, template_dir, json_path)", "be column vector!') # nu if is_empty(model.u): dims.nu = 0", "DAMAGE.; # import sys, os, json import numpy as np", "self.nlp_dims, self.nlp_out, stage_, field) out = np.ascontiguousarray(np.zeros((dims,)), dtype=np.float64) out_data =", "!= ng: raise Exception('inconsistent dimension ng, regarding lg, ug, C,", "False) elif acados_ocp.cost.cost_type == 'EXTERNAL': generate_c_code_external_cost(model, False) if acados_ocp.cost.cost_type_e ==", "!= ny_e: raise Exception('inconsistent dimension ny_e: regarding W_e, cost_y_expr_e.') if", "self.nlp_dims, self.nlp_in, stage, field, value_data_p) elif field_ in out_fields: self.shared_lib.ocp_nlp_out_set.argtypes", "setattr(ocp_nlp, acados_struct, dict(getattr(acados_ocp, acados_struct).__dict__)) # Copy ocp object attributes dictionaries", "HOLDERS AND CONTRIBUTORS \"AS IS\" # AND ANY EXPRESS OR", ".acados_model import acados_model_strip_casadi_symbolics from .utils import is_column, is_empty, casadi_length, render_template,", "= \"\" if cost.Zl.shape[0] != ns: wrong_field = \"Zl\" dim", "== 'GNSF': set_up_imported_gnsf_model(acados_ocp) # set integrator time automatically acados_ocp.solver_options.Tsim =", "= os.path.dirname(current_module.__file__) with open(acados_path + '/acados_layout.json', 'r') as f: ocp_nlp_layout", "out_file = '{}_phi_e_constraint.h'.format(name) render_template(in_file, out_file, template_dir, json_path) # nonlinear constraints", "generate_c_code_constraint(model, model.name, True, opts) # dummy matrices if not acados_ocp.cost.cost_type", "\\ self.nlp_opts, field, value_ctypes) else: self.shared_lib.ocp_nlp_solver_opts_set.argtypes = \\ [c_void_p, c_void_p,", "yref[{cost.yref.shape}]\\n') dims.ny = ny elif cost.cost_type == 'NONLINEAR_LS': ny =", "is_empty(constraints.ush): constraints.ush = np.zeros((nsh,)) elif constraints.ush.shape[0] != nsh: raise Exception('inconsistent", "self.nlp_solver = self.shared_lib.acados_get_nlp_solver() self.acados_ocp = acados_ocp def solve(self): \"\"\" solve", "ocp_nlp_dict['solver_options'].pop('shooting_nodes', None) dims_dict = acados_class2dict(acados_ocp.dims) ocp_check_against_layout(ocp_nlp_dict, dims_dict) with open(json_file, 'w')", "in_file = 'model.in.h' out_file = '{}_model.h'.format(name) render_template(in_file, out_file, template_dir, json_path)", "float \"\"\" int_fields = ['print_level', 'rti_phase', 'initialize_t_slacks'] double_fields = ['step_length']", "field, dims_data) value_shape = value_.shape if len(value_shape) == 1: value_shape", "Exception('inconsistent dimension nbu, regarding idxbu, ubu, lbu.') else: dims.nbu =", "in range(stat.shape[1]): print('{:d}\\t{:e}\\t{:e}\\t{:e}\\t{:e}\\t{:d}\\t{:d}'.format( \\ int(stat[0][jj]), stat[1][jj], stat[2][jj], \\ stat[3][jj], stat[4][jj],", "dimension nsbx, regarding idxsbx, usbx.') dims.nsbx = nsbx nsbu =", "= c_void_p self.nlp_in = self.shared_lib.acados_get_nlp_in() self.shared_lib.acados_get_nlp_solver.restype = c_void_p self.nlp_solver =", "self.shared_lib.acados_get_nlp_config.restype = c_void_p self.nlp_config = self.shared_lib.acados_get_nlp_config() self.shared_lib.acados_get_nlp_out.restype = c_void_p self.nlp_out", "= self.get_stats(\"statistics\") if self.acados_ocp.solver_options.nlp_solver_type == 'SQP': print('\\niter\\tres_stat\\tres_eq\\t\\tres_ineq\\tres_comp\\tqp_stat\\tqp_iter') if stat.shape[0]>7: print('\\tqp_res_stat\\tqp_res_eq\\tqp_res_ineq\\tqp_res_comp')", "Exception('inconsistent dimension nsbx_e, regarding idxsbx_e, usbx_e.') dims.nsbx_e = nsbx_e nsh_e", "columns.') if cost.yref_e.shape[0] != ny_e: raise Exception('inconsistent dimension: regarding W_e,", "if cost.yref.shape[0] != ny: raise Exception('inconsistent dimension: regarding W, yref.'", "= np.zeros((nsphi_e,)) elif constraints.usphi_e.shape[0] != nsphi_e: raise Exception('inconsistent dimension nsphi_e,", "out_file, template_dir, json_path) class AcadosOcpSolver: \"\"\" class to interact with", "if constraints.ug_e.shape[0] != ng_e or constraints.C_e.shape[0] != ng_e: raise Exception('inconsistent", "dimension nsg, regarding idxsg, lsg.') if is_empty(constraints.usg): constraints.usg = np.zeros((nsg,))", "= ['print_level', 'rti_phase', 'initialize_t_slacks'] double_fields = ['step_length'] string_fields = ['globalization']", "out_data = cast(out.ctypes.data, POINTER(c_double)) self.shared_lib.ocp_nlp_get.argtypes = [c_void_p, c_void_p, c_char_p, c_void_p]", "= c_void_p self.nlp_solver = self.shared_lib.acados_get_nlp_solver() self.acados_ocp = acados_ocp def solve(self):", "= c_void_p self.nlp_opts = self.shared_lib.acados_get_nlp_opts() self.shared_lib.acados_get_nlp_dims.restype = c_void_p self.nlp_dims =", "<NAME>, <NAME>, <NAME> # # This file is part of", "= np.zeros((nsbu,)) elif constraints.usbu.shape[0] != nsbu: raise Exception('inconsistent dimension nsbu,", "of the solver: Parameters: :param field_: string, e.g. 'print_level', 'rti_phase',", "else: dims.nbx = nbx nbu = constraints.idxbu.shape[0] if constraints.ubu.shape[0] !=", "lsh lsphi usbu usbx usg ush usphi] .. note:: pi:", "!= dims: msg = 'AcadosOcpSolver.set(): mismatching dimension for field \"{}\"", "nsg_e, regarding idxsg_e, lsg_e.') if is_empty(constraints.usg_e): constraints.usg_e = np.zeros((nsg_e,)) elif", "dims.ns = ns nsbx_e = constraints.idxsbx_e.shape[0] if is_empty(constraints.lsbx_e): constraints.lsbx_e =", "elif field_ in cost_fields: self.shared_lib.ocp_nlp_cost_model_set.argtypes = \\ [c_void_p, c_void_p, c_void_p,", "= constraints.idxbu.shape[0] if constraints.ubu.shape[0] != nbu or constraints.lbu.shape[0] != nbu:", "= nh_e if is_empty(model.con_phi_expr_e): dims.nphi_e = 0 dims.nr_e = 0", "'h_constraint.in.h' out_file = '{}_h_constraint.h'.format(name) render_template(in_file, out_file, template_dir, json_path) # terminal", "cost_fields: self.shared_lib.ocp_nlp_cost_model_set.argtypes = \\ [c_void_p, c_void_p, c_void_p, c_int, c_char_p, c_void_p]", "dict(generate_hess=0) if acados_ocp.dims.nphi > 0 or acados_ocp.dims.nh > 0: generate_c_code_constraint(model,", "constraints on outer function template_dir = 'c_generated_code/{}_constraints/'.format(name) in_file = 'phi_e_constraint.in.h'", "regarding idxsh, lsh.') if is_empty(constraints.ush): constraints.ush = np.zeros((nsh,)) elif constraints.ush.shape[0]", "SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR", "dimension nsbu, regarding idxsbu, usbu.') dims.nsbu = nsbu nsh =", "field_: string in ['x', 'u', 'z', 'pi', 'lam', 't', 'sl',", "np.zeros((nsbx_e,)) elif constraints.lsbx_e.shape[0] != nsbx_e: raise Exception('inconsistent dimension nsbx_e, regarding", "= 'c_generated_code/{}_cost/'.format(name) in_file = 'external_cost_e.in.h' out_file = '{}_external_cost_e.h'.format(name) render_template(in_file, out_file,", "constraints.idxsphi_e.shape[0] if is_empty(constraints.lsphi_e): constraints.lsphi_e = np.zeros((nsphi_e,)) elif constraints.lsphi_e.shape[0] != nsphi_e:", "QP) 'time_qp_xcond', 'time_reg', # cpu time regularization 'sqp_iter', # number", "nsh_e nsg_e = constraints.idxsg_e.shape[0] if is_empty(constraints.lsg_e): constraints.lsg_e = np.zeros((nsg_e,)) elif", "constraints.idxsg_e.shape[0] if is_empty(constraints.lsg_e): constraints.lsg_e = np.zeros((nsg_e,)) elif constraints.lsg_e.shape[0] != nsg_e:", "value_ = value_.astype(float) field = field_ field = field.encode('utf-8') stage", "calls 'time_sim_la', # cpu time for integrator contribution of linear", "string, e.g. 'yref', 'W', 'ext_cost_num_hess' :param value_: of appropriate size", "ny_e != 0: raise Exception('inconsistent dimension ny_e: regarding W_e, cost_y_expr_e.')", "# explicit model -- generate C code generate_c_code_explicit_ode(model) elif acados_ocp.solver_options.integrator_type", "None) dims_dict = acados_class2dict(acados_ocp.dims) ocp_check_against_layout(ocp_nlp_dict, dims_dict) with open(json_file, 'w') as", "sys.modules[__name__] acados_path = os.path.dirname(current_module.__file__) with open(acados_path + '/acados_layout.json', 'r') as", "nsbx, regarding idxsbx, lsbx.') if is_empty(constraints.usbx): constraints.usbx = np.zeros((nsbx,)) elif", "= field_ field = field.encode('utf-8') stage = c_int(stage_) self.shared_lib.ocp_nlp_constraint_dims_get_from_attr.argtypes =", "__del__(self): if self.solver_created: self.shared_lib.acados_free() del self.shared_lib # NOTE: DLL cannot", "print_statistics(self): stat = self.get_stats(\"statistics\") if self.acados_ocp.solver_options.nlp_solver_type == 'SQP': print('\\niter\\tres_stat\\tres_eq\\t\\tres_ineq\\tres_comp\\tqp_stat\\tqp_iter') if", "generate_c_code_explicit_ode(model) elif acados_ocp.solver_options.integrator_type == 'IRK': # implicit model -- generate", "ny: raise Exception('inconsistent dimension ny: regarding W, cost_y_expr.') if cost.yref.shape[0]", "dict(getattr(acados_ocp, acados_struct).__dict__)) # Copy ocp object attributes dictionaries ocp_nlp_dict[acados_struct]=dict(getattr(acados_ocp, acados_struct).__dict__)", "# initial if (constraints.lbx_0 == [] and constraints.ubx_0 == []):", "opts = dict(generate_hess=0) if acados_ocp.dims.nphi > 0 or acados_ocp.dims.nh >", "constraints.idxsphi.shape[0] if is_empty(constraints.lsphi): constraints.lsphi = np.zeros((nsphi,)) elif constraints.lsphi.shape[0] != nsphi:", "not acados_ocp.cost.cost_type_e == 'LINEAR_LS': acados_ocp.cost.Vx_e = np.zeros((acados_ocp.dims.ny_e, acados_ocp.dims.nx)) if acados_ocp.cost.cost_type", "range(stat.shape[1]): print('{:d}\\t{:e}\\t{:e}\\t{:e}\\t{:e}\\t{:d}\\t{:d}'.format( \\ int(stat[0][jj]), stat[1][jj], stat[2][jj], \\ stat[3][jj], stat[4][jj], int(stat[5][jj]),", "on outer function template_dir = 'c_generated_code/{}_constraints/'.format(name) in_file = 'phi_constraint.in.h' out_file", "# # Copyright 2019 <NAME>, <NAME>, <NAME>, # <NAME>, <NAME>,", "if is_empty(constraints.usbu): constraints.usbu = np.zeros((nsbu,)) elif constraints.usbu.shape[0] != nsbu: raise", "for integrator contribution of external function calls 'time_sim_la', # cpu", "# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)", "constraints_fields + cost_fields + out_fields: raise Exception(\"AcadosOcpSolver.set(): {} is not", "'SQP': print('\\niter\\tres_stat\\tres_eq\\t\\tres_ineq\\tres_comp\\tqp_stat\\tqp_iter') if stat.shape[0]>7: print('\\tqp_res_stat\\tqp_res_eq\\tqp_res_ineq\\tqp_res_comp') for jj in range(stat.shape[1]): print('{:d}\\t{:e}\\t{:e}\\t{:e}\\t{:e}\\t{:d}\\t{:d}'.format(", "function calls 'time_sim_la', # cpu time for integrator contribution of", "= \"zu\" dim = cost.zu.shape[0] if wrong_field != \"\": raise", "= nsphi_e # terminal ns_e = nsbx_e + nsh_e +", "\\n \"\"\" out_fields = ['x', 'u', 'z', 'pi', 'lam', 't']", "= cast((value_data), c_void_p) if field_ in constraints_fields: self.shared_lib.ocp_nlp_constraints_model_set.argtypes = \\", "= 'c_generated_code/{}_constraints/'.format(name) in_file = 'phi_constraint.in.h' out_file = '{}_phi_constraint.h'.format(name) render_template(in_file, out_file,", "= dict(deepcopy(acados_ocp).__dict__) # TODO: maybe make one funciton with formatting", "terminal nonlinear constraints if acados_ocp.constraints.constr_type_e == 'BGH' and acados_ocp.dims.nh_e >", "C code opts = dict(generate_hess=1) generate_c_code_implicit_ode(model, opts) elif acados_ocp.solver_options.integrator_type ==", "nbx_e = constraints.idxbx_e.shape[0] if constraints.ubx_e.shape[0] != nbx_e or constraints.lbx_e.shape[0] !=", "get(self, stage_, field_): \"\"\" get the last solution of the", "to shooting node :param field_: string, e.g. 'yref', 'W', 'ext_cost_num_hess'", "= cost.zu.shape[0] if wrong_field != \"\": raise Exception(f'Inconsistent size for", "ARISING IN ANY WAY OUT OF THE USE OF THIS", "and the following disclaimer. # # 2. Redistributions in binary", "elif acados_ocp.solver_options.integrator_type == 'IRK': # implicit model -- generate C", ".utils import is_column, is_empty, casadi_length, render_template, acados_class2dict,\\ format_class_dict, ocp_check_against_layout, np_array_to_list,", "print('\\niter\\tres_stat\\tres_eq\\t\\tres_ineq\\tres_comp\\tqp_stat\\tqp_iter') if stat.shape[0]>7: print('\\tqp_res_stat\\tqp_res_eq\\tqp_res_ineq\\tqp_res_comp') for jj in range(stat.shape[1]): print('{:d}\\t{:e}\\t{:e}\\t{:e}\\t{:e}\\t{:d}\\t{:d}'.format( \\", "ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN", "W[{cost.W.shape}], yref[{cost.yref.shape}]\\n') dims.ny = ny elif cost.cost_type == 'NONLINEAR_LS': ny", "+ model.name + '.so' # get self.shared_lib = CDLL(self.shared_lib_name) self.shared_lib.acados_create()", "Redistributions in binary form must reproduce the above copyright notice,", "if field_ in string_fields: self.shared_lib.ocp_nlp_solver_opts_set.argtypes = \\ [c_void_p, c_void_p, c_char_p,", "is_empty(constraints.lsg): constraints.lsg = np.zeros((nsg,)) elif constraints.lsg.shape[0] != nsg: raise Exception('inconsistent", "= constraints.idxsbx_e.shape[0] if is_empty(constraints.lsbx_e): constraints.lsbx_e = np.zeros((nsbx_e,)) elif constraints.lsbx_e.shape[0] !=", "raise Exception('inconsistent dimension N, regarding shooting_nodes.') time_steps = np.zeros((dims.N,)) for", "idxsbx, usbx.') dims.nsbx = nsbx nsbu = constraints.idxsbu.shape[0] if is_empty(constraints.lsbu):", "f'Detected ns = {ns} = nsbx + nsbu + nsg", "open(json_file, 'r') as f: ocp_nlp_json = json.load(f) ocp_nlp_dict = json2dict(ocp_nlp_json,", "import deepcopy from .generate_c_code_explicit_ode import generate_c_code_explicit_ode from .generate_c_code_implicit_ode import generate_c_code_implicit_ode", "OF THE # POSSIBILITY OF SUCH DAMAGE.; # import sys,", "= constraints.lg_e.shape[0] if constraints.ug_e.shape[0] != ng_e or constraints.C_e.shape[0] != ng_e:", "nonuniform discretization') tf = np.sum(opts.time_steps) if (tf - opts.tf) /", "os.chdir('c_generated_code') os.system('make clean_ocp_shared_lib') os.system('make ocp_shared_lib') os.chdir('..') self.shared_lib_name = 'c_generated_code/libacados_ocp_solver_' +", "c_int, c_char_p, c_void_p] self.shared_lib.ocp_nlp_constraints_model_set(self.nlp_config, \\ self.nlp_dims, self.nlp_in, stage, field, value_data_p)", "str. You have {}.'.format(field_, type(value_))) else: value_ctypes = value_.encode('utf-8') if", "cast((value_data), c_void_p) self.shared_lib.ocp_nlp_constraints_model_set.argtypes = \\ [c_void_p, c_void_p, c_void_p, c_int, c_char_p,", "template_dir, json_path) # constraints on convex over nonlinear function if", "is_empty(constraints.lsphi_e): constraints.lsphi_e = np.zeros((nsphi_e,)) elif constraints.lsphi_e.shape[0] != nsphi_e: raise Exception('inconsistent", "!= dims.nx and ny_e != 0: raise Exception('inconsistent dimension: Vx_e", "constraints.lg_e.shape[0] if constraints.ug_e.shape[0] != ng_e or constraints.C_e.shape[0] != ng_e: raise", "cost module of the solver: :param stage_: integer corresponding to", "constraints.idxsbx_e.shape[0] if is_empty(constraints.lsbx_e): constraints.lsbx_e = np.zeros((nsbx_e,)) elif constraints.lsbx_e.shape[0] != nsbx_e:", "lsphi usbu usbx usg ush usphi] .. note:: pi: multipliers", "else: value_ctypes = c_double(value_) elif field_ in string_fields: if not", "self.acados_ocp.solver_options.nlp_solver_type != 'SQP_RTI' and value_ > 0: raise Exception('AcadosOcpSolver.solve(): argument", "and acados_ocp.dims.nphi > 0: # constraints on outer function template_dir", "out_file, template_dir, json_path) # nonlinear constraints if acados_ocp.constraints.constr_type == 'BGH'", "!= nsg_e: raise Exception('inconsistent dimension nsg_e, regarding idxsg_e, usg_e.') dims.nsg_e", ":param stage: integer corresponding to shooting node :param field_: string", "= 'c_generated_code/{}_constraints/'.format(name) in_file = 'h_e_constraint.in.h' out_file = '{}_h_e_constraint.h'.format(name) render_template(in_file, out_file,", "render_template(in_file, out_file, template_dir, json_path) in_file = 'acados_solver.in.c' out_file = 'acados_solver_{}.c'.format(name)", "'.format(field_) msg += 'with dimension {} (you have {})'.format(dims, value_.shape[0])", "int. You have {}.'.format(field_, type(value_))) else: value_ctypes = c_int(value_) elif", "constraints.lsg = np.zeros((nsg,)) elif constraints.lsg.shape[0] != nsg: raise Exception('inconsistent dimension", "f'\\nGot W[{cost.W.shape}], Vx[{cost.Vx.shape}], Vu[{cost.Vu.shape}]\\n') if dims.nz != 0 and cost.Vz.shape[0]", "raise Exception('lbx_0, ubx_0 must be column vectors!') dims.nbx_0 = constraints.lbx_0.size", "{dim}, \\n\\t'\\ + f'Detected ns = {ns} = nsbx +", "template_dir, json_path) in_file = 'Makefile.in' out_file = 'Makefile' render_template(in_file, out_file,", "0 or acados_ocp.dims.nh_e > 0: generate_c_code_constraint(model, model.name, True, opts) #", "\"zl_e\" dim = cost.zl_e.shape[0] elif cost.zu_e.shape[0] != ns_e: wrong_field =", "self.nlp_solver, stage_, field, out_data) return out def print_statistics(self): stat =", "and acados_ocp.dims.nphi_e > 0: # terminal constraints on outer function", "self.shared_lib.ocp_nlp_out_get.argtypes = \\ [c_void_p, c_void_p, c_void_p, c_int, c_char_p, c_void_p] self.shared_lib.ocp_nlp_out_get(self.nlp_config,", "+ out_fields + ['p'])) self.shared_lib.ocp_nlp_dims_get_from_attr.argtypes = \\ [c_void_p, c_void_p, c_void_p,", "acados_ocp.dims.nh > 0: generate_c_code_constraint(model, model.name, False, opts) if acados_ocp.dims.nphi_e >", ".generate_c_code_external_cost import generate_c_code_external_cost from .acados_ocp import AcadosOcp from .acados_model import", "dimension: Vx should have nx columns.') if cost.Vu.shape[1] != dims.nu", "LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING", "self.nlp_opts, field, value_ctypes) else: self.shared_lib.ocp_nlp_solver_opts_set.argtypes = \\ [c_void_p, c_void_p, c_char_p,", "of type str. You have {}.'.format(field_, type(value_))) else: value_ctypes =", "easily unloaded!!! # see https://stackoverflow.com/questions/359498/how-can-i-unload-a-dll-using-ctypes-in-python # while isLoaded(self.shared_lib_name): # dlclose(handle)", "c_char_p, c_void_p] self.shared_lib.ocp_nlp_constraints_model_set(self.nlp_config, \\ self.nlp_dims, self.nlp_in, stage, field, value_data_p) return", "raise Exception('inconsistent dimension: Vx_e should have nx columns.') if cost.yref_e.shape[0]", "1e-15: raise Exception(f'Inconsistent discretization: {opts.tf}'\\ f' = tf != sum(opts.time_steps)", "constraints.lsphi = np.zeros((nsphi,)) elif constraints.lsphi.shape[0] != nsphi: raise Exception('inconsistent dimension", "nsg_e: raise Exception('inconsistent dimension nsg_e, regarding idxsg_e, lsg_e.') if is_empty(constraints.usg_e):", "ocp_nlp_dict # laod class attributes dict, dims, constraints, etc for", "field.encode('utf-8') stage = c_int(stage_) self.shared_lib.ocp_nlp_cost_dims_get_from_attr.argtypes = \\ [c_void_p, c_void_p, c_void_p,", "stage = c_int(stage_) self.shared_lib.ocp_nlp_cost_dims_get_from_attr.argtypes = \\ [c_void_p, c_void_p, c_void_p, c_int,", "Exception('inconsistent dimension ny_e: regarding W_e, cost_y_expr_e.') if cost.yref_e.shape[0] != ny_e:", "uniform discretization opts.time_steps = opts.tf / dims.N * np.ones((dims.N,)) elif", "os.system('make clean_ocp_shared_lib') os.system('make ocp_shared_lib') os.chdir('..') self.shared_lib_name = 'c_generated_code/libacados_ocp_solver_' + model.name", "constraints.uh.shape[0] != nh or constraints.lh.shape[0] != nh: raise Exception('inconsistent dimension", "ocp_check_against_layout(ocp_nlp_dict, dims_dict) with open(json_file, 'w') as f: json.dump(ocp_nlp_dict, f, default=np_array_to_list,", "= self.shared_lib.acados_get_nlp_solver() self.acados_ocp = acados_ocp def solve(self): \"\"\" solve the", "= \"Zu_e\" dim = cost.Zu_e.shape[0] elif cost.zl_e.shape[0] != ns_e: wrong_field", "copyright notice, # this list of conditions and the following", "+ \\ f'\\nGot W[{cost.W.shape}], Vx[{cost.Vx.shape}], Vu[{cost.Vu.shape}], Vz[{cost.Vz.shape}]\\n') if cost.Vx.shape[1] !=", "nsphi_e, regarding idxsphi_e, lsphi_e.') if is_empty(constraints.usphi_e): constraints.usphi_e = np.zeros((nsphi_e,)) elif", "set_up_imported_gnsf_model(acados_ocp) # set integrator time automatically acados_ocp.solver_options.Tsim = acados_ocp.solver_options.time_steps[0] #", "else: if field_ not in constraints_fields + cost_fields + out_fields:", "== 'EXTERNAL': template_dir = 'c_generated_code/{}_cost/'.format(name) in_file = 'external_cost.in.h' out_file =", "are internally organized in the following order: \\n [ lbu", "= (value_shape[0], 0) if value_shape != tuple(dims): raise Exception('AcadosOcpSolver.cost_set(): mismatching", "value 0 for SQP-type solvers') field = field_ field =", "values 0, 1, 2 for SQP-RTI-type solvers') if self.acados_ocp.solver_options.nlp_solver_type !=", "self.shared_lib.acados_get_nlp_in.restype = c_void_p self.nlp_in = self.shared_lib.acados_get_nlp_in() self.shared_lib.acados_get_nlp_solver.restype = c_void_p self.nlp_solver", "Exception('{} not found!'.format(json_path)) template_dir = 'c_generated_code/' ## Render templates in_file", "c_void_p, c_void_p, c_int, c_char_p, POINTER(c_int)] self.shared_lib.ocp_nlp_cost_dims_get_from_attr.restype = c_int dims =", "# table with info about last iteration 'stat_m', 'stat_n', ]", "field = field.encode('utf-8') stage = c_int(stage_) # treat parameters separately", "nsg + nsphi wrong_field = \"\" if cost.Zl.shape[0] != ns:", "self.nlp_in, stage, field, value_data_p) return def constraints_set(self, stage_, field_, value_):", "str): raise Exception('solver option {} must be of type str.", "= ocp_nlp_dict # laod class attributes dict, dims, constraints, etc", "cost.Zl_e.shape[0] elif cost.Zu_e.shape[0] != ns_e: wrong_field = \"Zu_e\" dim =", "out_file = '{}_model.h'.format(name) render_template(in_file, out_file, template_dir, json_path) # constraints on", "with open(json_file, 'r') as f: ocp_nlp_json = json.load(f) ocp_nlp_dict =", "return def constraints_set(self, stage_, field_, value_): \"\"\" set numerical data", "of SQP iterations 'statistics', # table with info about last", ".generate_c_code_nls_cost import generate_c_code_nls_cost from .generate_c_code_external_cost import generate_c_code_external_cost from .acados_ocp import", "raise Exception('inconsistent dimension nsbx, regarding idxsbx, usbx.') dims.nsbx = nsbx", "wrong_field = \"\" if cost.Zl_e.shape[0] != ns_e: wrong_field = \"Zl_e\"", "field = field_ field = field.encode('utf-8') stage = c_int(stage_) self.shared_lib.ocp_nlp_constraint_dims_get_from_attr.argtypes", "in_file = 'acados_sim_solver.in.h' out_file = 'acados_sim_solver_{}.h'.format(name) render_template(in_file, out_file, template_dir, json_path)", "nsbu, regarding idxsbu, usbu.') dims.nsbu = nsbu nsh = constraints.idxsh.shape[0]", "value_ctypes = c_int(value_) elif field_ in double_fields: if not isinstance(value_,", "= 'acados_sim_solver_{}.c'.format(name) render_template(in_file, out_file, template_dir, json_path) in_file = 'acados_sim_solver.in.h' out_file", "value_ctypes) else: self.shared_lib.ocp_nlp_solver_opts_set.argtypes = \\ [c_void_p, c_void_p, c_char_p, c_void_p] self.shared_lib.ocp_nlp_solver_opts_set(self.nlp_config,", "stage = c_int(stage_) # treat parameters separately if field_ is", "set_up_imported_gnsf_model def make_ocp_dims_consistent(acados_ocp): dims = acados_ocp.dims cost = acados_ocp.cost constraints", "implicit model -- generate C code opts = dict(generate_hess=1) generate_c_code_implicit_ode(model,", "raise Exception('inconsistent dimension nsh, regarding idxsh, lsh.') if is_empty(constraints.ush): constraints.ush", "{})'.format(dims, value_.shape[0]) raise Exception(msg) value_data = cast(value_.ctypes.data, POINTER(c_double)) value_data_p =", "lg lh lphi ubu ubx ug uh uphi; \\n lsbu", "[c_void_p, c_void_p, c_void_p, c_int, c_char_p, c_void_p] self.shared_lib.ocp_nlp_constraints_model_set(self.nlp_config, \\ self.nlp_dims, self.nlp_in,", "stage, field, value_data_p) return def constraints_set(self, stage_, field_, value_): \"\"\"", "to shooting node :param field_: string, e.g. 'lbx' :param value_:", "c_void_p, c_int, c_char_p, POINTER(c_int)] self.shared_lib.ocp_nlp_constraint_dims_get_from_attr.restype = c_int dims = np.ascontiguousarray(np.zeros((2,)),", "= self.get_stats(\"stat_n\") min_size = min([stat_m, sqp_iter+1]) out = np.ascontiguousarray( np.zeros(", "self.nlp_out, stage, field, value_data_p) return def cost_set(self, stage_, field_, value_):", "out_file = 'make_sfun.m' render_template(in_file, out_file, template_dir, json_path) in_file = 'acados_sim_solver.in.c'", "= 'phi_constraint.in.h' out_file = '{}_phi_constraint.h'.format(name) render_template(in_file, out_file, template_dir, json_path) #", "idxbx_e, ubx_e, lbx_e.') else: dims.nbx_e = nbx_e ng_e = constraints.lg_e.shape[0]", "LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS", "this list of conditions and the following disclaimer. # #", "self.nlp_in, stage, field, value_data_p) return def options_set(self, field_, value_): \"\"\"", "' 'take only values 0, 1, 2 for SQP-RTI-type solvers')", "solution of the solver: :param stage: integer corresponding to shooting", "IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,", "other materials provided with the distribution. # # THIS SOFTWARE", "for field \"{}\" '.format(field_) msg += 'with dimension {} (you", "field = field.encode('utf-8') stage = c_int(stage_) self.shared_lib.ocp_nlp_cost_dims_get_from_attr.argtypes = \\ [c_void_p,", "{nsh}, nsphi = {nsphi}') dims.ns = ns nsbx_e = constraints.idxsbx_e.shape[0]", "double_fields = ['step_length'] string_fields = ['globalization'] if field_ in int_fields:", "without # modification, are permitted provided that the following conditions", "raise Exception('solver option {} must be of type float. You", "elif constraints.usbu.shape[0] != nsbu: raise Exception('inconsistent dimension nsbu, regarding idxsbu,", "acados_struct).__dict__)) # Copy ocp object attributes dictionaries ocp_nlp_dict[acados_struct]=dict(getattr(acados_ocp, acados_struct).__dict__) ocp_nlp_dict", "out_file = 'acados_sim_solver_{}.c'.format(name) render_template(in_file, out_file, template_dir, json_path) in_file = 'acados_sim_solver.in.h'", "raise Exception('convex over nonlinear constraints: con_r_expr but con_phi_expr is nonempty')", "sys, os, json import numpy as np from ctypes import", "c_char_p, c_void_p] self.shared_lib.ocp_nlp_solver_opts_set(self.nlp_config, \\ self.nlp_opts, field, byref(value_ctypes)) return def __del__(self):", "lsg lsh lsphi usbu usbx usg ush usphi] .. note::", "raise Exception('solver option {} must be of type str. You", "= 'acados_solver_sfunction_{}.c'.format(name) render_template(in_file, out_file, template_dir, json_path) in_file = 'make_sfun.in.m' out_file", "dims.N+1: raise Exception('inconsistent dimension N, regarding shooting_nodes.') time_steps = np.zeros((dims.N,))", "PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,", "self.nlp_out = self.shared_lib.acados_get_nlp_out() self.shared_lib.acados_get_nlp_in.restype = c_void_p self.nlp_in = self.shared_lib.acados_get_nlp_in() self.shared_lib.acados_get_nlp_solver.restype", "if cost.Vx_e.shape[1] != dims.nx and ny_e != 0: raise Exception('inconsistent", "POINTER(c_int64)) elif field_ == 'statistics': sqp_iter = self.get_stats(\"sqp_iter\") stat_m =", "dims.ng = ng if not is_empty(model.con_h_expr): nh = casadi_length(model.con_h_expr) else:", "import generate_c_code_nls_cost from .generate_c_code_external_cost import generate_c_code_external_cost from .acados_ocp import AcadosOcp", "time for integrator 'time_sim_ad', # cpu time for integrator contribution", "= field_ field = field.encode('utf-8') stage = c_int(stage_) # treat", "self.shared_lib.ocp_nlp_cost_model_set(self.nlp_config, \\ self.nlp_dims, self.nlp_in, stage, field, value_data_p) elif field_ in", "== 'GNSF': generate_c_code_gnsf(model) else: raise Exception(\"ocp_generate_external_functions: unknown integrator type.\") if", "= self.get_stats(\"stat_m\") stat_n = self.get_stats(\"stat_n\") min_size = min([stat_m, sqp_iter+1]) out", "\\'rti_phase\\' can ' 'take only values 0, 1, 2 for", "dims.nz = 0 else: dims.nz = casadi_length(model.z) # np if", "dimension {} (you have {})'.format(field_, tuple(dims), value_shape)) value_data = cast(value_.ctypes.data,", "nsphi_e # terminal ns_e = nsbx_e + nsh_e + nsg_e", "dimension ng_e, regarding_e lg_e, ug_e, C_e.') else: dims.ng_e = ng_e", "model -- generate C code opts = dict(generate_hess=1) generate_c_code_implicit_ode(model, opts)", "module of the solver: :param stage_: integer corresponding to shooting", "stat_n = self.get_stats(\"stat_n\") min_size = min([stat_m, sqp_iter+1]) out = np.ascontiguousarray(", "self.shared_lib.ocp_nlp_constraint_dims_get_from_attr(self.nlp_config, \\ self.nlp_dims, self.nlp_out, stage_, field, dims_data) value_shape = value_.shape", "{} is not a valid argument.\\ \\nPossible values are {}.", "Exception('inconsistent dimension nsphi, regarding idxsphi, usphi.') dims.nsphi = nsphi nsg", "self.nlp_out, stage_, field) if value_.shape[0] != dims: msg = 'AcadosOcpSolver.set():", "get_ocp_nlp_layout() # Copy input ocp object dictionary ocp_nlp_dict = dict(deepcopy(acados_ocp).__dict__)", "<NAME>, # <NAME>, <NAME>, <NAME>, <NAME>, <NAME> # # This", "casadi_length(model.x) else: raise Exception('model.x should be column vector!') # nu", "template_dir, json_path) # nonlinear cost function if acados_ocp.cost.cost_type == 'NONLINEAR_LS':", "Exception('AcadosOcpSolver.solve(): argument \\'rti_phase\\' can ' 'take only values 0, 1,", "cost.cost_type_e == 'LINEAR_LS': ny_e = cost.W_e.shape[0] if cost.Vx_e.shape[0] != ny_e:", "self.shared_lib.acados_get_nlp_in() self.shared_lib.acados_get_nlp_solver.restype = c_void_p self.nlp_solver = self.shared_lib.acados_get_nlp_solver() self.acados_ocp = acados_ocp", "== 1: value_shape = (value_shape[0], 0) if value_shape != tuple(dims):", "out_data = cast(out.ctypes.data, POINTER(c_int64)) elif field_ == 'statistics': sqp_iter =", "render_template, acados_class2dict,\\ format_class_dict, ocp_check_against_layout, np_array_to_list, make_model_consistent,\\ set_up_imported_gnsf_model def make_ocp_dims_consistent(acados_ocp): dims", "nsbx + nsbu + nsg + nsh + nsphi.\\n\\t'\\ +", "acados_ocp.solver_options.Tsim = acados_ocp.solver_options.time_steps[0] # generate external functions ocp_generate_external_functions(acados_ocp, model) #", "to avoid conversion issues value_ = value_.astype(float) field = field_", "'EXTERNAL': generate_c_code_external_cost(model, False) if acados_ocp.cost.cost_type_e == 'NONLINEAR_LS': generate_c_code_nls_cost(model, model.name, True)", "the inequalities are internally organized in the following order: \\n", "= 'Makefile.in' out_file = 'Makefile' render_template(in_file, out_file, template_dir, json_path) in_file", "else: dims.ng = ng if not is_empty(model.con_h_expr): nh = casadi_length(model.con_h_expr)", "# external cost if acados_ocp.cost.cost_type == 'EXTERNAL': template_dir = 'c_generated_code/{}_cost/'.format(name)", "Exiting.\".format(field, \\ constraints_fields + cost_fields + out_fields + ['p'])) self.shared_lib.ocp_nlp_dims_get_from_attr.argtypes", "set numerical data in the cost module of the solver:", "{} must be of type str. You have {}.'.format(field_, type(value_)))", "is_empty(constraints.usg): constraints.usg = np.zeros((nsg,)) elif constraints.usg.shape[0] != nsg: raise Exception('inconsistent", "casadi import CasadiMeta, Function, SX from copy import deepcopy from", "if not os.path.exists(json_path): raise Exception('{} not found!'.format(json_path)) template_dir = 'c_generated_code/'", "or acados_ocp.dims.nh_e > 0: generate_c_code_constraint(model, model.name, True, opts) # dummy", "'acados_solver.in.h' out_file = 'acados_solver_{}.h'.format(name) render_template(in_file, out_file, template_dir, json_path) in_file =", "lh_e, uh_e, con_h_expr_e.') else: dims.nh_e = nh_e if is_empty(model.con_phi_expr_e): dims.nphi_e", "soft upper inequality constraints \\n \"\"\" out_fields = ['x', 'u',", "e.g. 'lbx' :param value_: of appropriate size \"\"\" # cast", "if is_empty(constraints.lsg): constraints.lsg = np.zeros((nsg,)) elif constraints.lsg.shape[0] != nsg: raise", "the constraint module of the solver: Parameters: :param stage_: integer", "# # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS", "if self.acados_ocp.solver_options.nlp_solver_type != 'SQP_RTI' and value_ > 0: raise Exception('AcadosOcpSolver.solve():", "integer corresponding to shooting node :param field_: string, e.g. 'yref',", "nsh_e = constraints.idxsh_e.shape[0] if is_empty(constraints.lsh_e): constraints.lsh_e = np.zeros((nsh_e,)) elif constraints.lsh_e.shape[0]", "idxsh_e, ush_e.') dims.nsh_e = nsh_e nsg_e = constraints.idxsg_e.shape[0] if is_empty(constraints.lsg_e):", "dims = np.ascontiguousarray(np.zeros((2,)), dtype=np.intc) dims_data = cast(dims.ctypes.data, POINTER(c_int)) self.shared_lib.ocp_nlp_cost_dims_get_from_attr(self.nlp_config, \\", "= casadi_length(model.con_h_expr) else: nh = 0 if constraints.uh.shape[0] != nh", "c_char_p, POINTER(c_int)] self.shared_lib.ocp_nlp_constraint_dims_get_from_attr.restype = c_int dims = np.ascontiguousarray(np.zeros((2,)), dtype=np.intc) dims_data", "time inside qp solver (without converting the QP) 'time_qp_xcond', 'time_reg',", "ny_e: raise Exception('inconsistent dimension: regarding W_e, yref_e.') dims.ny_e = ny_e", "c_void_p, c_char_p, c_void_p] self.shared_lib.ocp_nlp_solver_opts_set(self.nlp_config, \\ self.nlp_opts, field, byref(value_ctypes)) return def", "['x', 'u', 'pi', 'lam', 't'] # cast value_ to avoid", "ny: raise Exception('inconsistent dimension ny, regarding W, Vx, Vu.' +", "one funciton with formatting for acados_struct, v in ocp_layout.items(): #", "is an invalid argument.\\ \\n Possible values are {}. Exiting.'.format(field_,", "# -*- coding: future_fstrings -*- # # Copyright 2019 <NAME>,", "ubx, lbx.') else: dims.nbx = nbx nbu = constraints.idxbu.shape[0] if", "casadi_length(model.z) # np if is_empty(model.p): dims.np = 0 else: dims.np", "out_data) return out def print_statistics(self): stat = self.get_stats(\"statistics\") if self.acados_ocp.solver_options.nlp_solver_type", "solver: :param stage: integer corresponding to shooting node :param field_:", "Exception('inconsistent dimension nsg, regarding idxsg, lsg.') if is_empty(constraints.usg): constraints.usg =", "\"\"\" set numerical data in the cost module of the", "constraints.lsg.shape[0] != nsg: raise Exception('inconsistent dimension nsg, regarding idxsg, lsg.')", "c_int dims = np.ascontiguousarray(np.zeros((2,)), dtype=np.intc) dims_data = cast(dims.ctypes.data, POINTER(c_int)) self.shared_lib.ocp_nlp_cost_dims_get_from_attr(self.nlp_config,", "{nsbx}, nsbu = {nsbu}, nsg = {nsg}, nsh = {nsh},", "elif constraints.lsphi_e.shape[0] != nsphi_e: raise Exception('inconsistent dimension nsphi_e, regarding idxsphi_e,", "raise Exception('lbx_0, ubx_0 have different shapes!') if not is_column(constraints.lbx_0): raise", "treat parameters separately if field_ is 'p': self.shared_lib.acados_update_params.argtypes = [c_int,", "= 'main.in.c' out_file = 'main_{}.c'.format(name) render_template(in_file, out_file, template_dir, json_path) in_file", "= \\ [c_void_p, c_void_p, c_void_p, c_int, c_char_p, POINTER(c_int)] self.shared_lib.ocp_nlp_cost_dims_get_from_attr.restype =", "\"\" if cost.Zl_e.shape[0] != ns_e: wrong_field = \"Zl_e\" dim =", "constraints.usg.shape[0] != nsg: raise Exception('inconsistent dimension nsg, regarding idxsg, usg.')", "= json.load(f) ocp_nlp_dict = json2dict(ocp_nlp_json, ocp_nlp_json['dims']) # Instantiate AcadosOcp object", "dims.nh_e = nh_e if is_empty(model.con_phi_expr_e): dims.nphi_e = 0 dims.nr_e =", "dict acados_ocp.__dict__ = ocp_nlp_dict # laod class attributes dict, dims,", "FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT", "is_empty(model.con_r_expr): raise Exception('convex over nonlinear constraints: con_r_expr but con_phi_expr is", "nsh nsphi = constraints.idxsphi.shape[0] if is_empty(constraints.lsphi): constraints.lsphi = np.zeros((nsphi,)) elif", "= ['x', 'u', 'pi', 'lam', 't'] # cast value_ to", "acados_ocp.constraints.constr_type == 'BGP' and acados_ocp.dims.nphi > 0: # constraints on", "POINTER(c_int)) self.shared_lib.ocp_nlp_constraint_dims_get_from_attr(self.nlp_config, \\ self.nlp_dims, self.nlp_out, stage_, field, dims_data) value_shape =", "template_dir, json_path) # external cost - terminal if acados_ocp.cost.cost_type_e ==", "external functions ocp_generate_external_functions(acados_ocp, model) # dump to json ocp_formulation_json_dump(acados_ocp, json_file)", "or cost.Vu.shape[0] != ny: raise Exception('inconsistent dimension ny, regarding W,", "= ng_e if not is_empty(model.con_h_expr_e): nh_e = casadi_length(model.con_h_expr_e) else: nh_e", "out_file, template_dir, json_path) in_file = 'Makefile.in' out_file = 'Makefile' render_template(in_file,", "FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO", "Exception('inconsistent dimension ny: regarding W, cost_y_expr.') elif casadi_length(model.cost_y_expr) != ny:", "ns_e: wrong_field = \"zu_e\" dim = cost.zu_e.shape[0] if wrong_field !=", "stage_, field_, value_): \"\"\" set numerical data in the constraint", "ocp_render_templates(acados_ocp, json_file): name = acados_ocp.model.name # setting up loader and", "elif constraints.lsbx_e.shape[0] != nsbx_e: raise Exception('inconsistent dimension nsbx_e, regarding idxsbx_e,", "function if acados_ocp.cost.cost_type == 'NONLINEAR_LS': template_dir = 'c_generated_code/{}_cost/'.format(name) in_file =", "have {}.'.format(field_, type(value_))) else: value_ctypes = c_double(value_) elif field_ in", "constraints on convex over nonlinear function if acados_ocp.constraints.constr_type == 'BGP'", "contribution of external function calls 'time_sim_la', # cpu time for", "print('\\niter\\tqp_stat\\tqp_iter') if stat.shape[0]>3: print('\\tqp_res_stat\\tqp_res_eq\\tqp_res_ineq\\tqp_res_comp') for jj in range(stat.shape[1]): print('{:d}\\t{:d}\\t{:d}'.format( int(stat[0][jj]),", "IS\" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT", "argument \\'rti_phase\\' can ' 'take only values 0, 1, 2", "raise Exception('inconsistent dimension nbu, regarding idxbu, ubu, lbu.') else: dims.nbu", "con_phi_expr is nonempty') else: dims.nr = casadi_length(model.con_r_expr) # terminal nbx_e", "+ nsh + nsphi.\\n\\t'\\ + f'With nsbx = {nsbx}, nsbu", "> 0: # terminal constraints on outer function template_dir =", "value_.shape[0]) else: if field_ not in constraints_fields + cost_fields +", "= np.zeros((nsphi_e,)) elif constraints.lsphi_e.shape[0] != nsphi_e: raise Exception('inconsistent dimension nsphi_e,", "be of type float. You have {}.'.format(field_, type(value_))) else: value_ctypes", "!= nsphi: raise Exception('inconsistent dimension nsphi, regarding idxsphi, usphi.') dims.nsphi", "dims.nh = nh if is_empty(model.con_phi_expr): dims.nphi = 0 dims.nr =", "stat[5][jj], stat[6][jj])) print('\\n') return def get_stats(self, field_): \"\"\" get the", "c_int dims = self.shared_lib.ocp_nlp_dims_get_from_attr(self.nlp_config, \\ self.nlp_dims, self.nlp_out, stage_, field) if", "ng if not is_empty(model.con_h_expr): nh = casadi_length(model.con_h_expr) else: nh =", "= c_int dims = np.ascontiguousarray(np.zeros((2,)), dtype=np.intc) dims_data = cast(dims.ctypes.data, POINTER(c_int))", "in fields): raise Exception('AcadosOcpSolver.get_stats(): {} is not a valid argument.\\", "value_ < 0 or value_ > 2: raise Exception('AcadosOcpSolver.solve(): argument", "value_data_p) elif field_ in cost_fields: self.shared_lib.ocp_nlp_cost_model_set.argtypes = \\ [c_void_p, c_void_p,", "'initialize_t_slacks', 'step_length' :param value_: of type int, float \"\"\" int_fields", "else: dims.nh_e = nh_e if is_empty(model.con_phi_expr_e): dims.nphi_e = 0 dims.nr_e", "elif cost.zl.shape[0] != ns: wrong_field = \"zl\" dim = cost.zl.shape[0]", "= [c_int, POINTER(c_double)] self.shared_lib.acados_update_params.restype = c_int value_data = cast(value_.ctypes.data, POINTER(c_double))", "c_void_p, c_int, c_char_p, c_void_p] self.shared_lib.ocp_nlp_out_set(self.nlp_config, \\ self.nlp_dims, self.nlp_out, stage, field,", "'Makefile' render_template(in_file, out_file, template_dir, json_path) in_file = 'acados_solver_sfun.in.c' out_file =", "field_, value_): \"\"\" set numerical data in the cost module", "cost.Zu.shape[0] elif cost.zl.shape[0] != ns: wrong_field = \"zl\" dim =", "'time_sim_ad', 'time_sim_la', 'time_qp', 'time_qp_solver_call', 'time_reg', 'sqp_iter'] \"\"\" fields = ['time_tot',", "constraints.lh.shape[0] != nh: raise Exception('inconsistent dimension nh, regarding lh, uh,", "acados_ocp.solver_options.integrator_type == 'ERK': # explicit model -- generate C code", "if not isinstance(v, dict): continue # setattr(ocp_nlp, acados_struct, dict(getattr(acados_ocp, acados_struct).__dict__))", "if value_shape != tuple(dims): raise Exception('AcadosOcpSolver.constraints_set(): mismatching dimension' \\ '", "'print_level', 'rti_phase', 'initialize_t_slacks', 'step_length' :param value_: of type int, float", "cost.Vx_e.shape[0] != ny_e: raise Exception('inconsistent dimension ny_e: regarding W_e, cost_y_expr_e.'", "nsphi_e: raise Exception('inconsistent dimension nsphi_e, regarding idxsphi_e, lsphi_e.') if is_empty(constraints.usphi_e):", "or constraints.C.shape[0] != ng \\ or constraints.D.shape[0] != ng: raise", "= 'h_e_constraint.in.h' out_file = '{}_h_e_constraint.h'.format(name) render_template(in_file, out_file, template_dir, json_path) #", "regarding W_e, yref_e.') dims.ny_e = ny_e ## constraints # initial", "else: dims.nbx_e = nbx_e ng_e = constraints.lg_e.shape[0] if constraints.ug_e.shape[0] !=", "\\ f'\\nGot W[{cost.W.shape}], yref[{cost.yref.shape}]\\n') dims.ny = ny # terminal if", "def make_ocp_dims_consistent(acados_ocp): dims = acados_ocp.dims cost = acados_ocp.cost constraints =", "idxsg, lsg.') if is_empty(constraints.usg): constraints.usg = np.zeros((nsg,)) elif constraints.usg.shape[0] !=", "nsphi wrong_field = \"\" if cost.Zl.shape[0] != ns: wrong_field =", "'NONLINEAR_LS': template_dir = 'c_generated_code/{}_cost/'.format(name) in_file = 'cost_y_fun.in.h' out_file = '{}_cost_y_fun.h'.format(name)", "following order: \\n [ lbu lbx lg lh lphi ubu", "= 'AcadosOcpSolver.set(): mismatching dimension for field \"{}\" '.format(field_) msg +=", "status = self.shared_lib.acados_solve() return status def get(self, stage_, field_): \"\"\"", "\\ f'\\nGot W_e[{cost.W_e.shape}], Vx_e[{cost.Vx_e.shape}]') if cost.Vx_e.shape[1] != dims.nx and ny_e", "nbx: raise Exception('inconsistent dimension nbx, regarding idxbx, ubx, lbx.') else:", "c_void_p, c_void_p, c_int, c_char_p, c_void_p] self.shared_lib.ocp_nlp_out_get(self.nlp_config, \\ self.nlp_dims, self.nlp_out, stage_,", "# nx if is_column(model.x): dims.nx = casadi_length(model.x) else: raise Exception('model.x", "= field_ field = field.encode('utf-8') stage = c_int(stage_) self.shared_lib.ocp_nlp_cost_dims_get_from_attr.argtypes =", "constraints.lsbx.shape[0] != nsbx: raise Exception('inconsistent dimension nsbx, regarding idxsbx, lsbx.')", "2. Redistributions in binary form must reproduce the above copyright", "AcadosOcpSolver: \"\"\" class to interact with the acados ocp solver", "json_path) # constraints on convex over nonlinear function if acados_ocp.constraints.constr_type", "= cast(out.ctypes.data, POINTER(c_double)) self.shared_lib.ocp_nlp_get.argtypes = [c_void_p, c_void_p, c_char_p, c_void_p] self.shared_lib.ocp_nlp_get(self.nlp_config,", "\\ [c_void_p, c_void_p, c_void_p, c_int, c_char_p, c_void_p] self.shared_lib.ocp_nlp_get_at_stage(self.nlp_config, \\ self.nlp_dims,", "dims.nsphi_e = nsphi_e # terminal ns_e = nsbx_e + nsh_e", "MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED.", "constraints.C.shape[0] != ng \\ or constraints.D.shape[0] != ng: raise Exception('inconsistent", "OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT", "constraints on convex over nonlinear function if acados_ocp.constraints.constr_type_e == 'BGP'", "'BGP' and acados_ocp.dims.nphi > 0: # constraints on outer function", "= opts.tf / dims.N * np.ones((dims.N,)) elif not is_empty(opts.shooting_nodes): if", "option {} must be of type int. You have {}.'.format(field_,", "(field_ not in out_fields + mem_fields): raise Exception('AcadosOcpSolver.get(): {} is", "+ nsphi_e wrong_field = \"\" if cost.Zl_e.shape[0] != ns_e: wrong_field", "constraints.lsbx = np.zeros((nsbx,)) elif constraints.lsbx.shape[0] != nsbx: raise Exception('inconsistent dimension", "import acados_model_strip_casadi_symbolics from .utils import is_column, is_empty, casadi_length, render_template, acados_class2dict,\\", "the last solver call: :param field_: string in ['statistics', 'time_tot',", "Exception(\"AcadosOcpSolver.set(): {} is not a valid argument.\\ \\nPossible values are", "nsg: raise Exception('inconsistent dimension nsg, regarding idxsg, usg.') dims.nsg =", "is_empty(constraints.lsbx): constraints.lsbx = np.zeros((nsbx,)) elif constraints.lsbx.shape[0] != nsbx: raise Exception('inconsistent", "\"\"\" fields = ['time_tot', # total cpu time previous call", "# Note: this function should not be used anymore, better", "if is_empty(model.p): dims.np = 0 else: dims.np = casadi_length(model.p) if", "is_empty(opts.shooting_nodes): if np.shape(opts.shooting_nodes)[0] != dims.N+1: raise Exception('inconsistent dimension N, regarding", "self.nlp_dims, self.nlp_in, stage, field, value_data_p) return def options_set(self, field_, value_):", "msg += 'with dimension {} (you have {})'.format(dims, value_.shape[0]) raise", "W, cost_y_expr.') if cost.yref.shape[0] != ny: raise Exception('inconsistent dimension: regarding", "lsbu lsbx lsg lsh lsphi usbu usbx usg ush usphi]", "class attributes dict, dims, constraints, etc for acados_struct, v in", "else: raise Exception(\"ocp_generate_external_functions: unknown integrator type.\") if acados_ocp.solver_options.hessian_approx == 'EXACT':", "TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF", "as f: ocp_nlp_json = json.load(f) ocp_nlp_dict = json2dict(ocp_nlp_json, ocp_nlp_json['dims']) #", "= c_double(value_) elif field_ in string_fields: if not isinstance(value_, str):", "BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" # AND", "dims.nsbx_e = nsbx_e nsh_e = constraints.idxsh_e.shape[0] if is_empty(constraints.lsh_e): constraints.lsh_e =", "# 2. Redistributions in binary form must reproduce the above", "out_file = 'main_{}.c'.format(name) render_template(in_file, out_file, template_dir, json_path) in_file = 'acados_solver.in.c'", "AcadosOcp() # load class dict acados_ocp.__dict__ = ocp_nlp_dict # laod", "W_e, yref_e.') dims.ny_e = ny_e elif cost.cost_type_e == 'NONLINEAR_LS': ny_e", "out_file = '{}_external_cost.h'.format(name) render_template(in_file, out_file, template_dir, json_path) # external cost", "min([stat_m, sqp_iter+1]) out = np.ascontiguousarray( np.zeros( (stat_n[0]+1, min_size[0]) ), dtype=np.float64)", "is_empty(model.con_r_expr_e): raise Exception('convex over nonlinear constraints: con_r_expr_e but con_phi_expr_e is", "= cost.Zl_e.shape[0] elif cost.Zu_e.shape[0] != ns_e: wrong_field = \"Zu_e\" dim", "regarding W_e, cost_y_expr_e.') elif casadi_length(model.cost_y_expr_e) != ny_e: raise Exception('inconsistent dimension", "not be used anymore, better use cost_set, constraints_set def set(self,", "an invalid argument.\\ \\n Possible values are {}. Exiting.'.format(field_, out_fields", "if cost.cost_type_e == 'LINEAR_LS': ny_e = cost.W_e.shape[0] if cost.Vx_e.shape[0] !=", "value_shape)) value_data = cast(value_.ctypes.data, POINTER(c_double)) value_data_p = cast((value_data), c_void_p) self.shared_lib.ocp_nlp_constraints_model_set.argtypes", "# # 1. Redistributions of source code must retain the", "above copyright notice, # this list of conditions and the", "not isinstance(v, dict): continue # setattr(ocp_nlp, acados_struct, dict(getattr(acados_ocp, acados_struct).__dict__)) #", "and cost.Vz.shape[0] != ny: raise Exception('inconsistent dimension ny, regarding W,", "note:: pi: multipliers for dynamics equality constraints \\n lam: multipliers", "\\ self.nlp_dims, self.nlp_out, stage_, field) out = np.ascontiguousarray(np.zeros((dims,)), dtype=np.float64) out_data", "# # Redistribution and use in source and binary forms,", "if is_empty(constraints.lsbu): constraints.lsbu = np.zeros((nsbu,)) elif constraints.lsbu.shape[0] != nsbu: raise", "terminal constraints on convex over nonlinear function if acados_ocp.constraints.constr_type_e ==", "json ocp_formulation_json_dump(acados_ocp, json_file) # render templates ocp_render_templates(acados_ocp, json_file) ## Compile", "dims.np: raise Exception('inconsistent dimension np, regarding model.p and parameter_values.') ##", "True self.shared_lib.acados_get_nlp_opts.restype = c_void_p self.nlp_opts = self.shared_lib.acados_get_nlp_opts() self.shared_lib.acados_get_nlp_dims.restype = c_void_p", "np.zeros((nsg,)) elif constraints.lsg.shape[0] != nsg: raise Exception('inconsistent dimension nsg, regarding", "field, value_data_p) return def constraints_set(self, stage_, field_, value_): \"\"\" set", "lsg.') if is_empty(constraints.usg): constraints.usg = np.zeros((nsg,)) elif constraints.usg.shape[0] != nsg:", "\\n Possible values are {}. Exiting.'.format(field_, out_fields + mem_fields)) self.shared_lib.ocp_nlp_dims_get_from_attr.argtypes", "<NAME>, <NAME>, <NAME>, <NAME>, # <NAME>, <NAME>, <NAME>, <NAME>, <NAME>", "'acados_solver.in.c' out_file = 'acados_solver_{}.c'.format(name) render_template(in_file, out_file, template_dir, json_path) in_file =", "!= nbx: raise Exception('inconsistent dimension nbx, regarding idxbx, ubx, lbx.')", "dims.nu and ny != 0: raise Exception('inconsistent dimension: Vu should", "skip non dict attributes if not isinstance(v, dict): continue acados_attribute", "class to interact with the acados ocp solver C object", "f'\\nGot W[{cost.W.shape}], Vx[{cost.Vx.shape}], Vu[{cost.Vu.shape}], Vz[{cost.Vz.shape}]\\n') if cost.Vx.shape[1] != dims.nx and", "value_ to avoid conversion issues value_ = value_.astype(float) field =", "c_void_p, c_int, c_char_p, POINTER(c_int)] self.shared_lib.ocp_nlp_cost_dims_get_from_attr.restype = c_int dims = np.ascontiguousarray(np.zeros((2,)),", "vector!') # nu if is_empty(model.u): dims.nu = 0 else: dims.nu", "field, out_data) elif field_ in mem_fields: self.shared_lib.ocp_nlp_get_at_stage.argtypes = \\ [c_void_p,", "cost.W_e.shape[0] if cost.Vx_e.shape[0] != ny_e: raise Exception('inconsistent dimension ny_e: regarding", "nh_e if is_empty(model.con_phi_expr_e): dims.nphi_e = 0 dims.nr_e = 0 else:", "= cast((value_data), c_void_p) self.shared_lib.ocp_nlp_constraints_model_set.argtypes = \\ [c_void_p, c_void_p, c_void_p, c_int,", "part of acados. # # The 2-Clause BSD License #", "field = field_ field = field.encode('utf-8') stage = c_int(stage_) self.shared_lib.ocp_nlp_cost_dims_get_from_attr.argtypes", "int(stat[2][jj]))) if stat.shape[0]>3: print('\\t{:e}\\t{:e}\\t{:e}\\t{:e}'.format( \\ stat[3][jj], stat[4][jj], stat[5][jj], stat[6][jj])) print('\\n')", "ocp_generate_external_functions(acados_ocp, model): model = make_model_consistent(model) if acados_ocp.solver_options.integrator_type == 'ERK': #", "self.nlp_out, stage_, field, dims_data) value_shape = value_.shape if len(value_shape) ==", "opts = dict(generate_hess=1) else: opts = dict(generate_hess=0) if acados_ocp.dims.nphi >", "c_int, c_char_p, c_void_p] self.shared_lib.ocp_nlp_out_get(self.nlp_config, \\ self.nlp_dims, self.nlp_out, stage_, field, out_data)", "field) if value_.shape[0] != dims: msg = 'AcadosOcpSolver.set(): mismatching dimension", "for i in range(dims.N): time_steps[i] = opts.shooting_nodes[i+1] - opts.shooting_nodes[i] opts.time_steps", "def ocp_formulation_json_load(json_file='acados_ocp_nlp.json'): # Load acados_ocp_nlp structure description ocp_layout = get_ocp_nlp_layout()", "cost function if acados_ocp.cost.cost_type_e == 'NONLINEAR_LS': template_dir = 'c_generated_code/{}_cost/'.format(name) in_file", "= True self.shared_lib.acados_get_nlp_opts.restype = c_void_p self.nlp_opts = self.shared_lib.acados_get_nlp_opts() self.shared_lib.acados_get_nlp_dims.restype =", "variables of soft upper inequality constraints \\n \"\"\" out_fields =", "\\ stat[3][jj], stat[4][jj], stat[5][jj], stat[6][jj])) print('\\n') return def get_stats(self, field_):", "THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR", "usg ush usphi] .. note:: pi: multipliers for dynamics equality", ".. note:: regarding lam, t: \\n the inequalities are internally", "the following disclaimer. # # 2. Redistributions in binary form", "dimension nh_e, regarding lh_e, uh_e, con_h_expr_e.') else: dims.nh_e = nh_e", "= np.zeros((nsphi,)) elif constraints.lsphi.shape[0] != nsphi: raise Exception('inconsistent dimension nsphi,", "np.zeros((nsphi_e,)) elif constraints.lsphi_e.shape[0] != nsphi_e: raise Exception('inconsistent dimension nsphi_e, regarding", "+ f'With nsbx_e = {nsbx_e}, nsg_e = {nsg_e}, nsh_e =", "self.shared_lib = CDLL(self.shared_lib_name) self.shared_lib.acados_create() self.solver_created = True self.shared_lib.acados_get_nlp_opts.restype = c_void_p", "\\n lsbu lsbx lsg lsh lsphi usbu usbx usg ush", "lsbu.') if is_empty(constraints.usbu): constraints.usbu = np.zeros((nsbu,)) elif constraints.usbu.shape[0] != nsbu:", "\\ f'\\nGot W[{cost.W.shape}], Vx[{cost.Vx.shape}], Vu[{cost.Vu.shape}]\\n') if dims.nz != 0 and", "{ns} = nsbx + nsbu + nsg + nsh +", "!= nsphi_e: raise Exception('inconsistent dimension nsphi_e, regarding idxsphi_e, usphi_e.') dims.nsphi_e", "source and binary forms, with or without # modification, are", "c_void_p] self.shared_lib.ocp_nlp_out_get(self.nlp_config, \\ self.nlp_dims, self.nlp_out, stage_, field, out_data) elif field_", "separately if field_ is 'p': self.shared_lib.acados_update_params.argtypes = [c_int, POINTER(c_double)] self.shared_lib.acados_update_params.restype", "False) if acados_ocp.cost.cost_type_e == 'NONLINEAR_LS': generate_c_code_nls_cost(model, model.name, True) elif acados_ocp.cost.cost_type_e", "code generate_c_code_explicit_ode(model) elif acados_ocp.solver_options.integrator_type == 'IRK': # implicit model --", "unknown integrator type.\") if acados_ocp.solver_options.hessian_approx == 'EXACT': opts = dict(generate_hess=1)", "['p'])) self.shared_lib.ocp_nlp_dims_get_from_attr.argtypes = \\ [c_void_p, c_void_p, c_void_p, c_int, c_char_p] self.shared_lib.ocp_nlp_dims_get_from_attr.restype", "'t', 'sl', 'su',] .. note:: regarding lam, t: \\n the", "model = acados_ocp.model opts = acados_ocp.solver_options # nx if is_column(model.x):", "regarding idxsphi_e, lsphi_e.') if is_empty(constraints.usphi_e): constraints.usphi_e = np.zeros((nsphi_e,)) elif constraints.usphi_e.shape[0]", "INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER", "\\ [c_void_p, c_void_p, c_void_p, c_int, c_char_p, c_void_p] self.shared_lib.ocp_nlp_cost_model_set(self.nlp_config, \\ self.nlp_dims,", "elif constraints.lsg_e.shape[0] != nsg_e: raise Exception('inconsistent dimension nsg_e, regarding idxsg_e,", "'/acados_layout.json', 'r') as f: ocp_nlp_layout = json.load(f) return ocp_nlp_layout def", "regarding idxbu, ubu, lbu.') else: dims.nbu = nbu ng =", "CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,", "is_empty(constraints.usphi): constraints.usphi = np.zeros((nsphi,)) elif constraints.usphi.shape[0] != nsphi: raise Exception('inconsistent", "nsbx_e = {nsbx_e}, nsg_e = {nsg_e}, nsh_e = {nsh_e}, nsphi_e", "self.shared_lib.acados_get_nlp_opts.restype = c_void_p self.nlp_opts = self.shared_lib.acados_get_nlp_opts() self.shared_lib.acados_get_nlp_dims.restype = c_void_p self.nlp_dims", "with dimension {dim}, \\n\\t'\\ + f'Detected ns_e = {ns_e} =", "out_file = '{}_external_cost_e.h'.format(name) render_template(in_file, out_file, template_dir, json_path) class AcadosOcpSolver: \"\"\"", "pi: multipliers for dynamics equality constraints \\n lam: multipliers for", "nsg, regarding idxsg, usg.') dims.nsg = nsg ns = nsbx", "print('\\tqp_res_stat\\tqp_res_eq\\tqp_res_ineq\\tqp_res_comp') for jj in range(stat.shape[1]): print('{:d}\\t{:e}\\t{:e}\\t{:e}\\t{:e}\\t{:d}\\t{:d}'.format( \\ int(stat[0][jj]), stat[1][jj], stat[2][jj],", "indent=4, sort_keys=True) def ocp_formulation_json_load(json_file='acados_ocp_nlp.json'): # Load acados_ocp_nlp structure description ocp_layout", "c_void_p, c_int, c_char_p, c_void_p] self.shared_lib.ocp_nlp_constraints_model_set(self.nlp_config, \\ self.nlp_dims, self.nlp_in, stage, field,", "is_empty(opts.time_steps) and is_empty(opts.shooting_nodes): # uniform discretization opts.time_steps = opts.tf /", "0 dims.nr_e = 0 else: dims.nphi_e = casadi_length(model.con_phi_expr_e) if is_empty(model.con_r_expr_e):", "= 0 else: dims.nphi_e = casadi_length(model.con_phi_expr_e) if is_empty(model.con_r_expr_e): raise Exception('convex", "qp solution 'time_qp_solver_call', # cpu time inside qp solver (without", "if dims.nz != 0 and cost.Vz.shape[0] != ny: raise Exception('inconsistent", "print('\\n') return def get_stats(self, field_): \"\"\" get the information of", "POINTER(c_double)) value_data_p = cast((value_data), c_void_p) if field_ in constraints_fields: self.shared_lib.ocp_nlp_constraints_model_set.argtypes", "Parameters: :param field_: string, e.g. 'print_level', 'rti_phase', 'initialize_t_slacks', 'step_length' :param", "and (not is_empty(opts.shooting_nodes)): Exception('Please provide either time_steps or shooting_nodes for", "nonlinear constraints: con_r_expr_e but con_phi_expr_e is nonempty') else: dims.nr_e =", "if cost.Vx.shape[0] != ny or cost.Vu.shape[0] != ny: raise Exception('inconsistent", "# dummy matrices if not acados_ocp.cost.cost_type == 'LINEAR_LS': acados_ocp.cost.Vx =", "C, D.') else: dims.ng = ng if not is_empty(model.con_h_expr): nh", "regarding idxbx, ubx, lbx.') else: dims.nbx = nbx nbu =", "if not acados_ocp.cost.cost_type == 'LINEAR_LS': acados_ocp.cost.Vx = np.zeros((acados_ocp.dims.ny, acados_ocp.dims.nx)) acados_ocp.cost.Vu", "= 0 else: dims.np = casadi_length(model.p) if acados_ocp.parameter_values.shape[0] != dims.np:", "idxsh, lsh.') if is_empty(constraints.ush): constraints.ush = np.zeros((nsh,)) elif constraints.ush.shape[0] !=", "POINTER(c_double)) self.shared_lib.acados_update_params(stage, value_data, value_.shape[0]) else: if field_ not in constraints_fields", "ubx ug uh uphi; \\n lsbu lsbx lsg lsh lsphi", "else: dims.nphi_e = casadi_length(model.con_phi_expr_e) if is_empty(model.con_r_expr_e): raise Exception('convex over nonlinear", "0: raise Exception('AcadosOcpSolver.solve(): argument \\'rti_phase\\' can ' 'take only value", "constraints.lsbx_e = np.zeros((nsbx_e,)) elif constraints.lsbx_e.shape[0] != nsbx_e: raise Exception('inconsistent dimension", "dims.nx and ny != 0: raise Exception('inconsistent dimension: Vx should", "dtype=np.int64) out_data = cast(out.ctypes.data, POINTER(c_int64)) elif field_ == 'statistics': sqp_iter", "in ocp_layout.items(): # skip non dict attributes if not isinstance(v,", "ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE.; # import", "tf != sum(opts.time_steps) = {tf}.') def get_ocp_nlp_layout(): current_module = sys.modules[__name__]", "f'\\nGot W_e[{cost.W_e.shape}], Vx_e[{cost.Vx_e.shape}]') if cost.Vx_e.shape[1] != dims.nx and ny_e !=", "'model.in.h' out_file = '{}_model.h'.format(name) render_template(in_file, out_file, template_dir, json_path) # constraints", "c_void_p, c_void_p, c_int, c_char_p, c_void_p] self.shared_lib.ocp_nlp_get_at_stage(self.nlp_config, \\ self.nlp_dims, self.nlp_solver, stage_,", "discretization: {opts.tf}'\\ f' = tf != sum(opts.time_steps) = {tf}.') def", "= 'acados_sim_solver.in.h' out_file = 'acados_sim_solver_{}.h'.format(name) render_template(in_file, out_file, template_dir, json_path) ##", "dim = cost.Zu_e.shape[0] elif cost.zl_e.shape[0] != ns_e: wrong_field = \"zl_e\"", "and acados_ocp.dims.nh_e > 0: template_dir = 'c_generated_code/{}_constraints/'.format(name) in_file = 'h_e_constraint.in.h'", "usphi_e.') dims.nsphi_e = nsphi_e # terminal ns_e = nsbx_e +", "int(stat[6][jj]))) if stat.shape[0]>7: print('\\t{:e}\\t{:e}\\t{:e}\\t{:e}'.format( \\ stat[7][jj], stat[8][jj], stat[9][jj], stat[10][jj])) print('\\n')", "dimension np, regarding model.p and parameter_values.') ## cost # path", "not isinstance(value_, str): raise Exception('solver option {} must be of", "raise Exception('inconsistent dimension nsg, regarding idxsg, usg.') dims.nsg = nsg", "N, regarding shooting_nodes.') time_steps = np.zeros((dims.N,)) for i in range(dims.N):", "EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE", "import is_column, is_empty, casadi_length, render_template, acados_class2dict,\\ format_class_dict, ocp_check_against_layout, np_array_to_list, make_model_consistent,\\", "'{}_external_cost_e.h'.format(name) render_template(in_file, out_file, template_dir, json_path) class AcadosOcpSolver: \"\"\" class to", "return def get_stats(self, field_): \"\"\" get the information of the", "['lbx', 'ubx', 'lbu', 'ubu'] out_fields = ['x', 'u', 'pi', 'lam',", "0: # constraints on outer function template_dir = 'c_generated_code/{}_constraints/'.format(name) in_file", "ng or constraints.C.shape[0] != ng \\ or constraints.D.shape[0] != ng:", "= constraints.idxsh.shape[0] if is_empty(constraints.lsh): constraints.lsh = np.zeros((nsh,)) elif constraints.lsh.shape[0] !=", "mem_fields: self.shared_lib.ocp_nlp_get_at_stage.argtypes = \\ [c_void_p, c_void_p, c_void_p, c_int, c_char_p, c_void_p]", "# this list of conditions and the following disclaimer. #", "corresponding to shooting node :param field_: string, e.g. 'lbx' :param", "# render templates ocp_render_templates(acados_ocp, json_file) ## Compile solver os.chdir('c_generated_code') os.system('make", "notice, # this list of conditions and the following disclaimer", "dict): continue acados_attribute = getattr(acados_ocp, acados_struct) acados_attribute.__dict__ = ocp_nlp_dict[acados_struct] setattr(acados_ocp,", "if np.shape(opts.shooting_nodes)[0] != dims.N+1: raise Exception('inconsistent dimension N, regarding shooting_nodes.')", "= acados_ocp.constraints model = acados_ocp.model opts = acados_ocp.solver_options # nx", "self.nlp_in, stage, field, value_data_p) elif field_ in out_fields: self.shared_lib.ocp_nlp_out_set.argtypes =", "nsbx nsbu = constraints.idxsbu.shape[0] if is_empty(constraints.lsbu): constraints.lsbu = np.zeros((nsbu,)) elif", "self.shared_lib.ocp_nlp_out_set(self.nlp_config, \\ self.nlp_dims, self.nlp_out, stage, field, value_data_p) return def cost_set(self,", "'sqp_iter', # number of SQP iterations 'statistics', # table with", "0 if constraints.uh_e.shape[0] != nh_e or constraints.lh_e.shape[0] != nh_e: raise", ".generate_c_code_explicit_ode import generate_c_code_explicit_ode from .generate_c_code_implicit_ode import generate_c_code_implicit_ode from .generate_c_code_gnsf import", "is_empty(constraints.usbx_e): constraints.usbx_e = np.zeros((nsbx_e,)) elif constraints.usbx_e.shape[0] != nsbx_e: raise Exception('inconsistent", "C code generate_c_code_explicit_ode(model) elif acados_ocp.solver_options.integrator_type == 'IRK': # implicit model", "field, value_data_p) elif field_ in cost_fields: self.shared_lib.ocp_nlp_cost_model_set.argtypes = \\ [c_void_p,", "if not isinstance(v, dict): continue acados_attribute = getattr(acados_ocp, acados_struct) acados_attribute.__dict__", "else: dims.nr_e = casadi_length(model.con_r_expr_e) # Slack dimensions nsbx = constraints.idxsbx.shape[0]", "else: self.shared_lib.ocp_nlp_solver_opts_set.argtypes = \\ [c_void_p, c_void_p, c_char_p, c_void_p] self.shared_lib.ocp_nlp_solver_opts_set(self.nlp_config, \\", "= nsbx nsbu = constraints.idxsbu.shape[0] if is_empty(constraints.lsbu): constraints.lsbu = np.zeros((nsbu,))", "elif constraints.usg.shape[0] != nsg: raise Exception('inconsistent dimension nsg, regarding idxsg,", "open(acados_path + '/acados_layout.json', 'r') as f: ocp_nlp_layout = json.load(f) return", "usbx.') dims.nsbx = nsbx nsbu = constraints.idxsbu.shape[0] if is_empty(constraints.lsbu): constraints.lsbu", "= self.shared_lib.ocp_nlp_dims_get_from_attr(self.nlp_config, \\ self.nlp_dims, self.nlp_out, stage_, field) if value_.shape[0] !=", "disclaimer in the documentation # and/or other materials provided with", "external cost - terminal if acados_ocp.cost.cost_type_e == 'EXTERNAL': template_dir =", "in int_fields: if not isinstance(value_, int): raise Exception('solver option {}", "nsbu = {nsbu}, nsg = {nsg}, nsh = {nsh}, nsphi", "regarding lg, ug, C, D.') else: dims.ng = ng if", "f'\\nGot W[{cost.W.shape}], yref[{cost.yref.shape}]\\n') dims.ny = ny # terminal if cost.cost_type_e", "# laod class attributes dict, dims, constraints, etc for acados_struct,", "= c_int value_data = cast(value_.ctypes.data, POINTER(c_double)) self.shared_lib.acados_update_params(stage, value_data, value_.shape[0]) else:", "BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR", "= np.zeros((acados_ocp.dims.ny, acados_ocp.dims.nu)) if not acados_ocp.cost.cost_type_e == 'LINEAR_LS': acados_ocp.cost.Vx_e =", "Vx[{cost.Vx.shape}], Vu[{cost.Vu.shape}], Vz[{cost.Vz.shape}]\\n') if cost.Vx.shape[1] != dims.nx and ny !=", "in_file = 'acados_solver.in.h' out_file = 'acados_solver_{}.h'.format(name) render_template(in_file, out_file, template_dir, json_path)", "yref_e.') dims.ny_e = ny_e ## constraints # initial if (constraints.lbx_0", "constraints.usg = np.zeros((nsg,)) elif constraints.usg.shape[0] != nsg: raise Exception('inconsistent dimension", "lbu lbx lg lh lphi ubu ubx ug uh uphi;", "lh, uh, con_h_expr.') else: dims.nh = nh if is_empty(model.con_phi_expr): dims.nphi", "= nbx nbu = constraints.idxbu.shape[0] if constraints.ubu.shape[0] != nbu or", "self.shared_lib.acados_get_nlp_out() self.shared_lib.acados_get_nlp_in.restype = c_void_p self.nlp_in = self.shared_lib.acados_get_nlp_in() self.shared_lib.acados_get_nlp_solver.restype = c_void_p", "constraints if acados_ocp.constraints.constr_type_e == 'BGH' and acados_ocp.dims.nh_e > 0: template_dir", "= cast(value_.ctypes.data, POINTER(c_double)) value_data_p = cast((value_data), c_void_p) self.shared_lib.ocp_nlp_cost_model_set.argtypes = \\", "if field_ not in constraints_fields + cost_fields + out_fields: raise", "= np.ascontiguousarray(np.zeros((2,)), dtype=np.intc) dims_data = cast(dims.ctypes.data, POINTER(c_int)) self.shared_lib.ocp_nlp_cost_dims_get_from_attr(self.nlp_config, \\ self.nlp_dims,", "raise Exception('inconsistent dimension ny, regarding W, Vx, Vu, Vz.' +", "and ny != 0: raise Exception('inconsistent dimension ny: regarding W,", "ns = {ns} = nsbx + nsbu + nsg +", "cost.Vu.shape[0] != ny: raise Exception('inconsistent dimension ny, regarding W, Vx,", "\"\"\" # cast value_ to avoid conversion issues value_ =", "= self.shared_lib.acados_get_nlp_out() self.shared_lib.acados_get_nlp_in.restype = c_void_p self.nlp_in = self.shared_lib.acados_get_nlp_in() self.shared_lib.acados_get_nlp_solver.restype =", "fields = ['time_tot', # total cpu time previous call 'time_lin',", "nsh: raise Exception('inconsistent dimension nsh, regarding idxsh, ush.') dims.nsh =", "idxsphi, usphi.') dims.nsphi = nsphi nsg = constraints.idxsg.shape[0] if is_empty(constraints.lsg):", "cost.W.shape[0] if cost.Vx.shape[0] != ny or cost.Vu.shape[0] != ny: raise", ".generate_c_code_implicit_ode import generate_c_code_implicit_ode from .generate_c_code_gnsf import generate_c_code_gnsf from .generate_c_code_constraint import", "\\ [c_void_p, c_void_p, c_void_p, c_int, c_char_p, c_void_p] self.shared_lib.ocp_nlp_constraints_model_set(self.nlp_config, \\ self.nlp_dims,", "and is_empty(opts.shooting_nodes): # uniform discretization opts.time_steps = opts.tf / dims.N", "nsphi = {nsphi}') dims.ns = ns nsbx_e = constraints.idxsbx_e.shape[0] if", "setattr(acados_ocp, acados_struct, acados_attribute) return acados_ocp def ocp_generate_external_functions(acados_ocp, model): model =", "not a valid argument.\\ \\n Possible values are {}. Exiting.'.format(fields,", "= get_ocp_nlp_layout() # Copy input ocp object dictionary ocp_nlp_dict =", "to json ocp_formulation_json_dump(acados_ocp, json_file) # render templates ocp_render_templates(acados_ocp, json_file) ##", "elif not is_empty(opts.shooting_nodes): if np.shape(opts.shooting_nodes)[0] != dims.N+1: raise Exception('inconsistent dimension", "nbx_e, regarding idxbx_e, ubx_e, lbx_e.') else: dims.nbx_e = nbx_e ng_e", "dimension nbx_e, regarding idxbx_e, ubx_e, lbx_e.') else: dims.nbx_e = nbx_e", "!= nsbu: raise Exception('inconsistent dimension nsbu, regarding idxsbu, usbu.') dims.nsbu", "nsh_e = {nsh_e}, nsphi_e = {nsphi_e}') dims.ns_e = ns_e #", "field_ == 'rti_phase': if value_ < 0 or value_ >", "cost.Vu.shape[1] != dims.nu and ny != 0: raise Exception('inconsistent dimension:", "return out def print_statistics(self): stat = self.get_stats(\"statistics\") if self.acados_ocp.solver_options.nlp_solver_type ==", "idxsh, ush.') dims.nsh = nsh nsphi = constraints.idxsphi.shape[0] if is_empty(constraints.lsphi):", "+ nsphi_e.\\n\\t'\\ + f'With nsbx_e = {nsbx_e}, nsg_e = {nsg_e},", "stat[10][jj])) print('\\n') elif self.acados_ocp.solver_options.nlp_solver_type == 'SQP_RTI': print('\\niter\\tqp_stat\\tqp_iter') if stat.shape[0]>3: print('\\tqp_res_stat\\tqp_res_eq\\tqp_res_ineq\\tqp_res_comp')", "regarding W, Vx, Vu.' + \\ f'\\nGot W[{cost.W.shape}], Vx[{cost.Vx.shape}], Vu[{cost.Vu.shape}]\\n')", "dim = cost.zu.shape[0] if wrong_field != \"\": raise Exception(f'Inconsistent size", "Parameters: :param stage_: integer corresponding to shooting node :param field_:", "value_): \"\"\" set numerical data in the constraint module of", "c_void_p self.nlp_dims = self.shared_lib.acados_get_nlp_dims() self.shared_lib.acados_get_nlp_config.restype = c_void_p self.nlp_config = self.shared_lib.acados_get_nlp_config()", "# cpu time inside qp solver (without converting the QP)", "ng_e: raise Exception('inconsistent dimension ng_e, regarding_e lg_e, ug_e, C_e.') else:", "np.shape(opts.shooting_nodes)[0] != dims.N+1: raise Exception('inconsistent dimension N, regarding shooting_nodes.') time_steps", "if is_empty(constraints.lsbx_e): constraints.lsbx_e = np.zeros((nsbx_e,)) elif constraints.lsbx_e.shape[0] != nsbx_e: raise", "nsh = constraints.idxsh.shape[0] if is_empty(constraints.lsh): constraints.lsh = np.zeros((nsh,)) elif constraints.lsh.shape[0]", "!= nsphi: raise Exception('inconsistent dimension nsphi, regarding idxsphi, lsphi.') if", "acados_ocp.cost.Vx_e = np.zeros((acados_ocp.dims.ny_e, acados_ocp.dims.nx)) if acados_ocp.cost.cost_type == 'NONLINEAR_LS': generate_c_code_nls_cost(model, model.name,", "option {} must be of type str. You have {}.'.format(field_,", "time_steps or shooting_nodes for nonuniform discretization') tf = np.sum(opts.time_steps) if", "int(stat[0][jj]), stat[1][jj], stat[2][jj], \\ stat[3][jj], stat[4][jj], int(stat[5][jj]), int(stat[6][jj]))) if stat.shape[0]>7:", "Redistribution and use in source and binary forms, with or", "path if cost.cost_type == 'LINEAR_LS': ny = cost.W.shape[0] if cost.Vx.shape[0]", "nh_e or constraints.lh_e.shape[0] != nh_e: raise Exception('inconsistent dimension nh_e, regarding", "\\ ' for field \"{}\" with dimension {} (you have", "= c_int(stage_) self.shared_lib.ocp_nlp_cost_dims_get_from_attr.argtypes = \\ [c_void_p, c_void_p, c_void_p, c_int, c_char_p,", "= acados_ocp.model # make dims consistent make_ocp_dims_consistent(acados_ocp) if acados_ocp.solver_options.integrator_type ==", "self.shared_lib.ocp_nlp_dims_get_from_attr(self.nlp_config, \\ self.nlp_dims, self.nlp_out, stage_, field) out = np.ascontiguousarray(np.zeros((dims,)), dtype=np.float64)", "wrong_field = \"Zu_e\" dim = cost.Zu_e.shape[0] elif cost.zl_e.shape[0] != ns_e:", "variables of soft lower inequality constraints \\n su: slack variables", "int_fields = ['print_level', 'rti_phase', 'initialize_t_slacks'] double_fields = ['step_length'] string_fields =", "dims.nbx_0 = constraints.lbx_0.size if all(constraints.lbx_0 == constraints.ubx_0): dims.nbxe_0 = dims.nbx_0", "nh_e = 0 if constraints.uh_e.shape[0] != nh_e or constraints.lh_e.shape[0] !=", "import generate_c_code_explicit_ode from .generate_c_code_implicit_ode import generate_c_code_implicit_ode from .generate_c_code_gnsf import generate_c_code_gnsf", "wrong_field = \"Zl_e\" dim = cost.Zl_e.shape[0] elif cost.Zu_e.shape[0] != ns_e:", "acados_ocp.solver_options.integrator_type == 'GNSF': set_up_imported_gnsf_model(acados_ocp) # set integrator time automatically acados_ocp.solver_options.Tsim", "stat[3][jj], stat[4][jj], stat[5][jj], stat[6][jj])) print('\\n') return def get_stats(self, field_): \"\"\"", "['time_tot', # total cpu time previous call 'time_lin', # cpu", "value_shape = (value_shape[0], 0) if value_shape != tuple(dims): raise Exception('AcadosOcpSolver.constraints_set():", "= acados_ocp.dims cost = acados_ocp.cost constraints = acados_ocp.constraints model =", "jj in range(stat.shape[1]): print('{:d}\\t{:e}\\t{:e}\\t{:e}\\t{:e}\\t{:d}\\t{:d}'.format( \\ int(stat[0][jj]), stat[1][jj], stat[2][jj], \\ stat[3][jj],", "= self.shared_lib.acados_get_nlp_in() self.shared_lib.acados_get_nlp_solver.restype = c_void_p self.nlp_solver = self.shared_lib.acados_get_nlp_solver() self.acados_ocp =", "from .generate_c_code_external_cost import generate_c_code_external_cost from .acados_ocp import AcadosOcp from .acados_model", "if is_empty(constraints.lsh): constraints.lsh = np.zeros((nsh,)) elif constraints.lsh.shape[0] != nsh: raise", "laod class attributes dict, dims, constraints, etc for acados_struct, v", "[c_void_p, c_void_p, c_void_p, c_int, c_char_p, c_void_p] self.shared_lib.ocp_nlp_get_at_stage(self.nlp_config, \\ self.nlp_dims, self.nlp_solver,", "out_fields + mem_fields): raise Exception('AcadosOcpSolver.get(): {} is an invalid argument.\\", "'rti_phase', 'initialize_t_slacks'] double_fields = ['step_length'] string_fields = ['globalization'] if field_", "Exception('inconsistent dimension nh_e, regarding lh_e, uh_e, con_h_expr_e.') else: dims.nh_e =", "!= 0: raise Exception('inconsistent dimension ny_e: regarding W_e, cost_y_expr_e.') elif", "This file is part of acados. # # The 2-Clause", "!= nbx_e: raise Exception('inconsistent dimension nbx_e, regarding idxbx_e, ubx_e, lbx_e.')", "nsh = {nsh}, nsphi = {nsphi}') dims.ns = ns nsbx_e", "render_template(in_file, out_file, template_dir, json_path) # terminal nonlinear constraints if acados_ocp.constraints.constr_type_e", "acados_ocp.constraints.constr_type == 'BGH' and acados_ocp.dims.nh > 0: template_dir = 'c_generated_code/{}_constraints/'.format(name)", "value_: of appropriate size \"\"\" # cast value_ to avoid", "f'Detected ns_e = {ns_e} = nsbx_e + nsg_e + nsh_e", "self.shared_lib.ocp_nlp_cost_dims_get_from_attr.restype = c_int dims = np.ascontiguousarray(np.zeros((2,)), dtype=np.intc) dims_data = cast(dims.ctypes.data,", "c_int, c_char_p, POINTER(c_int)] self.shared_lib.ocp_nlp_cost_dims_get_from_attr.restype = c_int dims = np.ascontiguousarray(np.zeros((2,)), dtype=np.intc)", "binary form must reproduce the above copyright notice, # this", "# dump to json ocp_formulation_json_dump(acados_ocp, json_file) # render templates ocp_render_templates(acados_ocp,", "= constraints.idxbx_e.shape[0] if constraints.ubx_e.shape[0] != nbx_e or constraints.lbx_e.shape[0] != nbx_e:", "c_void_p, c_int, c_char_p, c_void_p] self.shared_lib.ocp_nlp_cost_model_set(self.nlp_config, \\ self.nlp_dims, self.nlp_in, stage, field,", "Vx, Vu.' + \\ f'\\nGot W[{cost.W.shape}], Vx[{cost.Vx.shape}], Vu[{cost.Vu.shape}]\\n') if dims.nz", "cost.zu.shape[0] != ns: wrong_field = \"zu\" dim = cost.zu.shape[0] if", "'c_generated_code/{}_constraints/'.format(name) in_file = 'phi_e_constraint.in.h' out_file = '{}_phi_e_constraint.h'.format(name) render_template(in_file, out_file, template_dir,", "= 'external_cost_e.in.h' out_file = '{}_external_cost_e.h'.format(name) render_template(in_file, out_file, template_dir, json_path) class", "valid argument.\\ \\n Possible values are {}. Exiting.'.format(fields, fields)) if", ".generate_c_code_constraint import generate_c_code_constraint from .generate_c_code_nls_cost import generate_c_code_nls_cost from .generate_c_code_external_cost import", "raise Exception('AcadosOcpSolver.constraints_set(): mismatching dimension' \\ ' for field \"{}\" with", "function template_dir = 'c_generated_code/{}_constraints/'.format(name) in_file = 'phi_e_constraint.in.h' out_file = '{}_phi_e_constraint.h'.format(name)", "acados_class2dict(acados_ocp.dims) ocp_check_against_layout(ocp_nlp_dict, dims_dict) with open(json_file, 'w') as f: json.dump(ocp_nlp_dict, f,", "INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT", "CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) #", "= constraints.idxsg.shape[0] if is_empty(constraints.lsg): constraints.lsg = np.zeros((nsg,)) elif constraints.lsg.shape[0] !=", "OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS", "to interact with the acados ocp solver C object \"\"\"", "Exception('inconsistent dimension ny, regarding W, Vx, Vu.' + \\ f'\\nGot", "{ns_e} = nsbx_e + nsg_e + nsh_e + nsphi_e.\\n\\t'\\ +", "-- generate C code opts = dict(generate_hess=1) generate_c_code_implicit_ode(model, opts) elif", "min_size[0]) ), dtype=np.float64) out_data = cast(out.ctypes.data, POINTER(c_double)) else: out =", "dimension {dim}, \\n\\t'\\ + f'Detected ns_e = {ns_e} = nsbx_e", "nsbx = {nsbx}, nsbu = {nsbu}, nsg = {nsg}, nsh", "generate_c_code_nls_cost(model, model.name, True) elif acados_ocp.cost.cost_type_e == 'EXTERNAL': generate_c_code_external_cost(model, True) def", "cast(out.ctypes.data, POINTER(c_double)) if (field_ in out_fields): self.shared_lib.ocp_nlp_out_get.argtypes = \\ [c_void_p,", "file is part of acados. # # The 2-Clause BSD", "set integrator time automatically acados_ocp.solver_options.Tsim = acados_ocp.solver_options.time_steps[0] # generate external", "is nonempty') else: dims.nr_e = casadi_length(model.con_r_expr_e) # Slack dimensions nsbx", "dtype=np.float64) out_data = cast(out.ctypes.data, POINTER(c_double)) self.shared_lib.ocp_nlp_get.argtypes = [c_void_p, c_void_p, c_char_p,", "ny != 0: raise Exception('inconsistent dimension: Vu should have nu", "'{}_phi_e_constraint.h'.format(name) render_template(in_file, out_file, template_dir, json_path) # nonlinear constraints if acados_ocp.constraints.constr_type", "== 'NONLINEAR_LS': ny_e = cost.W_e.shape[0] if is_empty(model.cost_y_expr_e) and ny_e !=", "is_empty(opts.shooting_nodes): # uniform discretization opts.time_steps = opts.tf / dims.N *", "# discretization if is_empty(opts.time_steps) and is_empty(opts.shooting_nodes): # uniform discretization opts.time_steps", "either time_steps or shooting_nodes for nonuniform discretization') tf = np.sum(opts.time_steps)", "ocp_nlp_dict[acados_struct]=dict(getattr(acados_ocp, acados_struct).__dict__) ocp_nlp_dict = format_class_dict(ocp_nlp_dict) # strip symbolics ocp_nlp_dict['model'] =", "solve(self): \"\"\" solve the ocp with current input \"\"\" status", "su: slack variables of soft upper inequality constraints \\n \"\"\"", "!= ns_e: wrong_field = \"zl_e\" dim = cost.zl_e.shape[0] elif cost.zu_e.shape[0]", "of conditions and the following disclaimer in the documentation #", "ocp_formulation_json_load(json_file='acados_ocp_nlp.json'): # Load acados_ocp_nlp structure description ocp_layout = get_ocp_nlp_layout() with", "if stat.shape[0]>3: print('\\tqp_res_stat\\tqp_res_eq\\tqp_res_ineq\\tqp_res_comp') for jj in range(stat.shape[1]): print('{:d}\\t{:d}\\t{:d}'.format( int(stat[0][jj]), int(stat[1][jj]),", "value_): cost_fields = ['y_ref', 'yref'] constraints_fields = ['lbx', 'ubx', 'lbu',", "dims.nu = casadi_length(model.u) # nz if is_empty(model.z): dims.nz = 0", "'phi_e_constraint.in.h' out_file = '{}_phi_e_constraint.h'.format(name) render_template(in_file, out_file, template_dir, json_path) # nonlinear", "raise Exception('convex over nonlinear constraints: con_r_expr_e but con_phi_expr_e is nonempty')", "cost_y_expr.') if cost.yref.shape[0] != ny: raise Exception('inconsistent dimension: regarding W,", "model = acados_ocp.model # make dims consistent make_ocp_dims_consistent(acados_ocp) if acados_ocp.solver_options.integrator_type", "[c_void_p, c_void_p, c_char_p, c_void_p] self.shared_lib.ocp_nlp_get(self.nlp_config, self.nlp_solver, field, out_data) return out", "range(dims.N): time_steps[i] = opts.shooting_nodes[i+1] - opts.shooting_nodes[i] opts.time_steps = time_steps elif", "Exception('lbx_0, ubx_0 have different shapes!') if not is_column(constraints.lbx_0): raise Exception('lbx_0,", "if constraints.uh.shape[0] != nh or constraints.lh.shape[0] != nh: raise Exception('inconsistent", "json_path) # terminal nonlinear constraints if acados_ocp.constraints.constr_type_e == 'BGH' and", "if acados_ocp.constraints.constr_type == 'BGH' and acados_ocp.dims.nh > 0: template_dir =", "= self.shared_lib.acados_get_nlp_opts() self.shared_lib.acados_get_nlp_dims.restype = c_void_p self.nlp_dims = self.shared_lib.acados_get_nlp_dims() self.shared_lib.acados_get_nlp_config.restype =", "of linear algebra 'time_qp', # cpu time qp solution 'time_qp_solver_call',", "yref.' + \\ f'\\nGot W[{cost.W.shape}], yref[{cost.yref.shape}]\\n') dims.ny = ny #", "elif constraints.lsbx.shape[0] != nsbx: raise Exception('inconsistent dimension nsbx, regarding idxsbx,", "lbx.') else: dims.nbx = nbx nbu = constraints.idxbu.shape[0] if constraints.ubu.shape[0]", "nz if is_empty(model.z): dims.nz = 0 else: dims.nz = casadi_length(model.z)", "ny_e = cost.W_e.shape[0] if is_empty(model.cost_y_expr_e) and ny_e != 0: raise", "\\n [ lbu lbx lg lh lphi ubu ubx ug", "\"\" if cost.Zl.shape[0] != ns: wrong_field = \"Zl\" dim =", "is not a valid argument.\\ \\nPossible values are {}. Exiting.\".format(field,", "usg_e.') dims.nsg_e = nsg_e nsphi_e = constraints.idxsphi_e.shape[0] if is_empty(constraints.lsphi_e): constraints.lsphi_e", "= {nsphi}') dims.ns = ns nsbx_e = constraints.idxsbx_e.shape[0] if is_empty(constraints.lsbx_e):", "'{}_external_cost.h'.format(name) render_template(in_file, out_file, template_dir, json_path) # external cost - terminal", "ocp_check_against_layout, np_array_to_list, make_model_consistent,\\ set_up_imported_gnsf_model def make_ocp_dims_consistent(acados_ocp): dims = acados_ocp.dims cost", "def __del__(self): if self.solver_created: self.shared_lib.acados_free() del self.shared_lib # NOTE: DLL", "t: slack variables corresponding to evaluation of all inequalities (at", "USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE #", "dim = cost.zl_e.shape[0] elif cost.zu_e.shape[0] != ns_e: wrong_field = \"zu_e\"", "'acados_solver_sfunction_{}.c'.format(name) render_template(in_file, out_file, template_dir, json_path) in_file = 'make_sfun.in.m' out_file =", "type(value_))) else: value_ctypes = value_.encode('utf-8') if field_ == 'rti_phase': if", "regarding idxsg, usg.') dims.nsg = nsg ns = nsbx +", "'ERK': # explicit model -- generate C code generate_c_code_explicit_ode(model) elif", "= field.encode('utf-8') if (field_ not in fields): raise Exception('AcadosOcpSolver.get_stats(): {}", "is_empty, casadi_length, render_template, acados_class2dict,\\ format_class_dict, ocp_check_against_layout, np_array_to_list, make_model_consistent,\\ set_up_imported_gnsf_model def", "is_column(model.x): dims.nx = casadi_length(model.x) else: raise Exception('model.x should be column", "(constraints.lbx_0 == [] and constraints.ubx_0 == []): dims.nbx_0 = 0", "+ nsg_e + nsh_e + nsphi_e.\\n\\t'\\ + f'With nsbx_e =", "constraints_fields: self.shared_lib.ocp_nlp_constraints_model_set.argtypes = \\ [c_void_p, c_void_p, c_void_p, c_int, c_char_p, c_void_p]", "c_void_p) self.shared_lib.ocp_nlp_constraints_model_set.argtypes = \\ [c_void_p, c_void_p, c_void_p, c_int, c_char_p, c_void_p]", "# # The 2-Clause BSD License # # Redistribution and", "= casadi_length(model.u) # nz if is_empty(model.z): dims.nz = 0 else:", "nbx_e: raise Exception('inconsistent dimension nbx_e, regarding idxbx_e, ubx_e, lbx_e.') else:", "nsphi, regarding idxsphi, usphi.') dims.nsphi = nsphi nsg = constraints.idxsg.shape[0]", "{nsh_e}, nsphi_e = {nsphi_e}') dims.ns_e = ns_e # discretization if", "'NONLINEAR_LS': generate_c_code_nls_cost(model, model.name, False) elif acados_ocp.cost.cost_type == 'EXTERNAL': generate_c_code_external_cost(model, False)", "description ocp_layout = get_ocp_nlp_layout() # Copy input ocp object dictionary", "usbx usg ush usphi] .. note:: pi: multipliers for dynamics", "elif constraints.usbx_e.shape[0] != nsbx_e: raise Exception('inconsistent dimension nsbx_e, regarding idxsbx_e,", "# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER", "field, byref(value_ctypes)) return def __del__(self): if self.solver_created: self.shared_lib.acados_free() del self.shared_lib", "input ocp object dictionary ocp_nlp_dict = dict(deepcopy(acados_ocp).__dict__) # TODO: maybe", "field.encode('utf-8') if (field_ not in fields): raise Exception('AcadosOcpSolver.get_stats(): {} is", "of the last solver call: :param field_: string in ['statistics',", "== 'BGP' and acados_ocp.dims.nphi > 0: # constraints on outer", "Exiting.'.format(field_, out_fields + mem_fields)) self.shared_lib.ocp_nlp_dims_get_from_attr.argtypes = \\ [c_void_p, c_void_p, c_void_p,", "field_ in string_fields: self.shared_lib.ocp_nlp_solver_opts_set.argtypes = \\ [c_void_p, c_void_p, c_char_p, c_char_p]", "\"{}\" with dimension {} (you have {})'.format(field_, tuple(dims), value_shape)) value_data", "raise Exception('inconsistent dimension ny_e: regarding W_e, cost_y_expr_e.' + \\ f'\\nGot", "0 else: this_shape = constraints.lbx_0.shape other_shape = constraints.ubx_0.shape if not", "type(value_))) else: value_ctypes = c_int(value_) elif field_ in double_fields: if", "acados_ocp.cost.Vx = np.zeros((acados_ocp.dims.ny, acados_ocp.dims.nx)) acados_ocp.cost.Vu = np.zeros((acados_ocp.dims.ny, acados_ocp.dims.nu)) if not", "raise Exception('inconsistent dimension nsphi, regarding idxsphi, lsphi.') if is_empty(constraints.usphi): constraints.usphi", "'c_generated_code/{}_cost/'.format(name) in_file = 'external_cost_e.in.h' out_file = '{}_external_cost_e.h'.format(name) render_template(in_file, out_file, template_dir,", "= make_model_consistent(model) if acados_ocp.solver_options.integrator_type == 'ERK': # explicit model --", "field_: string in ['statistics', 'time_tot', 'time_lin', 'time_sim', 'time_sim_ad', 'time_sim_la', 'time_qp',", "template_dir, json_path) in_file = 'acados_sim_solver.in.h' out_file = 'acados_sim_solver_{}.h'.format(name) render_template(in_file, out_file,", "value_data_p) elif field_ in out_fields: self.shared_lib.ocp_nlp_out_set.argtypes = \\ [c_void_p, c_void_p,", "of all inequalities (at the solution) \\n sl: slack variables", "not in constraints_fields + cost_fields + out_fields: raise Exception(\"AcadosOcpSolver.set(): {}", "# nu if is_empty(model.u): dims.nu = 0 else: dims.nu =", "render_template(in_file, out_file, template_dir, json_path) in_file = 'make_sfun.in.m' out_file = 'make_sfun.m'", "Load acados_ocp_nlp structure description ocp_layout = get_ocp_nlp_layout() with open(json_file, 'r')", "= field.encode('utf-8') if (field_ not in out_fields + mem_fields): raise", "different shapes!') if not is_column(constraints.lbx_0): raise Exception('lbx_0, ubx_0 must be", "\"zl\" dim = cost.zl.shape[0] elif cost.zu.shape[0] != ns: wrong_field =", "out_file = 'Makefile' render_template(in_file, out_file, template_dir, json_path) in_file = 'acados_solver_sfun.in.c'", "OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED", "the following order: \\n [ lbu lbx lg lh lphi", "out = np.ascontiguousarray( np.zeros( (stat_n[0]+1, min_size[0]) ), dtype=np.float64) out_data =", "c_void_p] self.shared_lib.ocp_nlp_solver_opts_set(self.nlp_config, \\ self.nlp_opts, field, byref(value_ctypes)) return def __del__(self): if", "), dtype=np.float64) out_data = cast(out.ctypes.data, POINTER(c_double)) else: out = np.ascontiguousarray(np.zeros((1,)),", "print('{:d}\\t{:d}\\t{:d}'.format( int(stat[0][jj]), int(stat[1][jj]), int(stat[2][jj]))) if stat.shape[0]>3: print('\\t{:e}\\t{:e}\\t{:e}\\t{:e}'.format( \\ stat[3][jj], stat[4][jj],", "LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION)", "integrator contribution of linear algebra 'time_qp', # cpu time qp", "+ cost_fields + out_fields + ['p'])) self.shared_lib.ocp_nlp_dims_get_from_attr.argtypes = \\ [c_void_p,", "in the cost module of the solver: :param stage_: integer", "type int, float \"\"\" int_fields = ['print_level', 'rti_phase', 'initialize_t_slacks'] double_fields", "= field.encode('utf-8') stage = c_int(stage_) self.shared_lib.ocp_nlp_cost_dims_get_from_attr.argtypes = \\ [c_void_p, c_void_p,", "regarding idxsbx, usbx.') dims.nsbx = nsbx nsbu = constraints.idxsbu.shape[0] if", "cost.Zl_e.shape[0] != ns_e: wrong_field = \"Zl_e\" dim = cost.Zl_e.shape[0] elif", "nsphi nsg = constraints.idxsg.shape[0] if is_empty(constraints.lsg): constraints.lsg = np.zeros((nsg,)) elif", "acados_ocp.constraints.constr_type_e == 'BGP' and acados_ocp.dims.nphi_e > 0: # terminal constraints", "= np.zeros((nsh_e,)) elif constraints.lsh_e.shape[0] != nsh_e: raise Exception('inconsistent dimension nsh_e,", "Exception('inconsistent dimension ny: regarding W, cost_y_expr.') if cost.yref.shape[0] != ny:", "# import sys, os, json import numpy as np from", "THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY", "== [] and constraints.ubx_0 == []): dims.nbx_0 = 0 else:", "in_file = 'acados_sim_solver.in.c' out_file = 'acados_sim_solver_{}.c'.format(name) render_template(in_file, out_file, template_dir, json_path)", "\"zu_e\" dim = cost.zu_e.shape[0] if wrong_field != \"\": raise Exception(f'Inconsistent", "and ny != 0: raise Exception('inconsistent dimension: Vu should have", "'t'] mem_fields = ['sl', 'su'] field = field_ field =", "\\ [c_void_p, c_void_p, c_void_p, c_int, c_char_p] self.shared_lib.ocp_nlp_dims_get_from_attr.restype = c_int dims", "nsbx_e nsh_e = constraints.idxsh_e.shape[0] if is_empty(constraints.lsh_e): constraints.lsh_e = np.zeros((nsh_e,)) elif", "cost_fields + out_fields: raise Exception(\"AcadosOcpSolver.set(): {} is not a valid", "value_data = cast(value_.ctypes.data, POINTER(c_double)) value_data_p = cast((value_data), c_void_p) if field_", "0 else: dims.np = casadi_length(model.p) if acados_ocp.parameter_values.shape[0] != dims.np: raise", "of type int, float \"\"\" int_fields = ['print_level', 'rti_phase', 'initialize_t_slacks']", "= {nsphi_e}') dims.ns_e = ns_e # discretization if is_empty(opts.time_steps) and", "NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES;", "acados_ocp.model opts = acados_ocp.solver_options # nx if is_column(model.x): dims.nx =", "terminal nbx_e = constraints.idxbx_e.shape[0] if constraints.ubx_e.shape[0] != nbx_e or constraints.lbx_e.shape[0]", "mem_fields = ['sl', 'su'] field = field_ field = field.encode('utf-8')", "constraints.lsh = np.zeros((nsh,)) elif constraints.lsh.shape[0] != nsh: raise Exception('inconsistent dimension", "c_void_p, c_int, c_char_p] self.shared_lib.ocp_nlp_dims_get_from_attr.restype = c_int dims = self.shared_lib.ocp_nlp_dims_get_from_attr(self.nlp_config, \\", "stat[6][jj])) print('\\n') return def get_stats(self, field_): \"\"\" get the information", "= constraints.idxsbu.shape[0] if is_empty(constraints.lsbu): constraints.lsbu = np.zeros((nsbu,)) elif constraints.lsbu.shape[0] !=", "'GNSF': set_up_imported_gnsf_model(acados_ocp) # set integrator time automatically acados_ocp.solver_options.Tsim = acados_ocp.solver_options.time_steps[0]", "casadi_length(model.u) # nz if is_empty(model.z): dims.nz = 0 else: dims.nz", "cost.Vx.shape[1] != dims.nx and ny != 0: raise Exception('inconsistent dimension:", "dictionaries ocp_nlp_dict[acados_struct]=dict(getattr(acados_ocp, acados_struct).__dict__) ocp_nlp_dict = format_class_dict(ocp_nlp_dict) # strip symbolics ocp_nlp_dict['model']", "= getattr(acados_ocp, acados_struct) acados_attribute.__dict__ = ocp_nlp_dict[acados_struct] setattr(acados_ocp, acados_struct, acados_attribute) return", "in_file = 'Makefile.in' out_file = 'Makefile' render_template(in_file, out_file, template_dir, json_path)", "model.name, True) elif acados_ocp.cost.cost_type_e == 'EXTERNAL': generate_c_code_external_cost(model, True) def ocp_render_templates(acados_ocp,", "out = np.ascontiguousarray(np.zeros((dims,)), dtype=np.float64) out_data = cast(out.ctypes.data, POINTER(c_double)) if (field_", "field {wrong_field}, with dimension {dim}, \\n\\t'\\ + f'Detected ns_e =", "qp solver (without converting the QP) 'time_qp_xcond', 'time_reg', # cpu", "np.ascontiguousarray(np.zeros((1,)), dtype=np.int64) out_data = cast(out.ctypes.data, POINTER(c_int64)) elif field_ == 'statistics':", "['step_length'] string_fields = ['globalization'] if field_ in int_fields: if not", "class dict acados_ocp.__dict__ = ocp_nlp_dict # laod class attributes dict,", "nonlinear cost function if acados_ocp.cost.cost_type == 'NONLINEAR_LS': template_dir = 'c_generated_code/{}_cost/'.format(name)", "dtype=np.intc) dims_data = cast(dims.ctypes.data, POINTER(c_int)) self.shared_lib.ocp_nlp_cost_dims_get_from_attr(self.nlp_config, \\ self.nlp_dims, self.nlp_out, stage_,", "field_ field = field.encode('utf-8') if (field_ not in fields): raise", "value_shape != tuple(dims): raise Exception('AcadosOcpSolver.cost_set(): mismatching dimension', \\ ' for", "BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF", "raise Exception('inconsistent dimension nsg_e, regarding idxsg_e, lsg_e.') if is_empty(constraints.usg_e): constraints.usg_e", "else: dims.nphi = casadi_length(model.con_phi_expr) if is_empty(model.con_r_expr): raise Exception('convex over nonlinear", "== 'NONLINEAR_LS': template_dir = 'c_generated_code/{}_cost/'.format(name) in_file = 'cost_y_e_fun.in.h' out_file =", "acados_ocp.solver_options.integrator_type == 'IRK': # implicit model -- generate C code", "acados_ocp.dims.nh > 0: template_dir = 'c_generated_code/{}_constraints/'.format(name) in_file = 'h_constraint.in.h' out_file", "is part of acados. # # The 2-Clause BSD License", "template_dir = 'c_generated_code/{}_constraints/'.format(name) in_file = 'h_e_constraint.in.h' out_file = '{}_h_e_constraint.h'.format(name) render_template(in_file,", "dimension ny: regarding W, cost_y_expr.') if cost.yref.shape[0] != ny: raise", "# np if is_empty(model.p): dims.np = 0 else: dims.np =", "W_e, yref_e.') dims.ny_e = ny_e ## constraints # initial if", "# <NAME>, <NAME>, <NAME>, <NAME>, # <NAME>, <NAME>, <NAME>, <NAME>,", "W[{cost.W.shape}], yref[{cost.yref.shape}]\\n') dims.ny = ny # terminal if cost.cost_type_e ==", "function should not be used anymore, better use cost_set, constraints_set", "and use in source and binary forms, with or without", "Vx[{cost.Vx.shape}], Vu[{cost.Vu.shape}]\\n') if dims.nz != 0 and cost.Vz.shape[0] != ny:", "slack variables corresponding to evaluation of all inequalities (at the", "acados_struct, acados_attribute) return acados_ocp def ocp_generate_external_functions(acados_ocp, model): model = make_model_consistent(model)", "order: \\n [ lbu lbx lg lh lphi ubu ubx", "in the following order: \\n [ lbu lbx lg lh", "c_int, c_char_p, c_void_p] self.shared_lib.ocp_nlp_get_at_stage(self.nlp_config, \\ self.nlp_dims, self.nlp_solver, stage_, field, out_data)", "+ nsg_e + nsphi_e wrong_field = \"\" if cost.Zl_e.shape[0] !=", "cost = acados_ocp.cost constraints = acados_ocp.constraints model = acados_ocp.model opts", "import generate_c_code_external_cost from .acados_ocp import AcadosOcp from .acados_model import acados_model_strip_casadi_symbolics", "c_int(stage_) self.shared_lib.ocp_nlp_constraint_dims_get_from_attr.argtypes = \\ [c_void_p, c_void_p, c_void_p, c_int, c_char_p, POINTER(c_int)]", "= 'c_generated_code/{}_cost/'.format(name) in_file = 'cost_y_fun.in.h' out_file = '{}_cost_y_fun.h'.format(name) render_template(in_file, out_file,", "IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE", "strip symbolics ocp_nlp_dict['model'] = acados_model_strip_casadi_symbolics(ocp_nlp_dict['model']) # strip shooting_nodes ocp_nlp_dict['solver_options'].pop('shooting_nodes', None)", "if all(constraints.lbx_0 == constraints.ubx_0): dims.nbxe_0 = dims.nbx_0 # path nbx", "= nsbx + nsbu + nsg + nsh + nsphi.\\n\\t'\\", "'time_qp', # cpu time qp solution 'time_qp_solver_call', # cpu time", "isinstance(value_, float): raise Exception('solver option {} must be of type", "functions ocp_generate_external_functions(acados_ocp, model) # dump to json ocp_formulation_json_dump(acados_ocp, json_file) #", "__init__(self, acados_ocp, json_file='acados_ocp_nlp.json'): self.solver_created = False model = acados_ocp.model #", "constraints.lsbu = np.zeros((nsbu,)) elif constraints.lsbu.shape[0] != nsbu: raise Exception('inconsistent dimension", "print('\\n') elif self.acados_ocp.solver_options.nlp_solver_type == 'SQP_RTI': print('\\niter\\tqp_stat\\tqp_iter') if stat.shape[0]>3: print('\\tqp_res_stat\\tqp_res_eq\\tqp_res_ineq\\tqp_res_comp') for", "should not be used anymore, better use cost_set, constraints_set def", "else: dims.ng_e = ng_e if not is_empty(model.con_h_expr_e): nh_e = casadi_length(model.con_h_expr_e)", "W_e, cost_y_expr_e.' + \\ f'\\nGot W_e[{cost.W_e.shape}], Vx_e[{cost.Vx_e.shape}]') if cost.Vx_e.shape[1] !=", "= False model = acados_ocp.model # make dims consistent make_ocp_dims_consistent(acados_ocp)", "conditions and the following disclaimer in the documentation # and/or", "dimension nsg, regarding idxsg, usg.') dims.nsg = nsg ns =", "0 or value_ > 2: raise Exception('AcadosOcpSolver.solve(): argument \\'rti_phase\\' can", "!= nsbx_e: raise Exception('inconsistent dimension nsbx_e, regarding idxsbx_e, usbx_e.') dims.nsbx_e", "v in ocp_layout.items(): # skip non dict attributes if not", "= constraints.ubx_0.shape if not this_shape == other_shape: raise Exception('lbx_0, ubx_0", "out_file = 'acados_solver_{}.c'.format(name) render_template(in_file, out_file, template_dir, json_path) in_file = 'acados_solver.in.h'", "constraints.lsbx_e.shape[0] != nsbx_e: raise Exception('inconsistent dimension nsbx_e, regarding idxsbx_e, lsbx_e.')", "tf = np.sum(opts.time_steps) if (tf - opts.tf) / tf >", "= np.ascontiguousarray(np.zeros((dims,)), dtype=np.float64) out_data = cast(out.ctypes.data, POINTER(c_double)) if (field_ in", "dims.ny = ny elif cost.cost_type == 'NONLINEAR_LS': ny = cost.W.shape[0]", "reproduce the above copyright notice, # this list of conditions", "dimensions nsbx = constraints.idxsbx.shape[0] if is_empty(constraints.lsbx): constraints.lsbx = np.zeros((nsbx,)) elif", "is_empty(constraints.lsg_e): constraints.lsg_e = np.zeros((nsg_e,)) elif constraints.lsg_e.shape[0] != nsg_e: raise Exception('inconsistent", "nsbu + nsh + nsg + nsphi wrong_field = \"\"", "if is_empty(model.con_phi_expr_e): dims.nphi_e = 0 dims.nr_e = 0 else: dims.nphi_e", "idxsbx_e, lsbx_e.') if is_empty(constraints.usbx_e): constraints.usbx_e = np.zeros((nsbx_e,)) elif constraints.usbx_e.shape[0] !=", "'u', 'z', 'pi', 'lam', 't', 'sl', 'su',] .. note:: regarding", "options_set(self, field_, value_): \"\"\" set options of the solver: Parameters:", "attributes if not isinstance(v, dict): continue acados_attribute = getattr(acados_ocp, acados_struct)", "variables corresponding to evaluation of all inequalities (at the solution)", "dim = cost.zu_e.shape[0] if wrong_field != \"\": raise Exception(f'Inconsistent size", "self.shared_lib.acados_get_nlp_dims() self.shared_lib.acados_get_nlp_config.restype = c_void_p self.nlp_config = self.shared_lib.acados_get_nlp_config() self.shared_lib.acados_get_nlp_out.restype = c_void_p", "dims: msg = 'AcadosOcpSolver.set(): mismatching dimension for field \"{}\" '.format(field_)", "forms, with or without # modification, are permitted provided that", "field.encode('utf-8') if field_ in string_fields: self.shared_lib.ocp_nlp_solver_opts_set.argtypes = \\ [c_void_p, c_void_p,", "## cost # path if cost.cost_type == 'LINEAR_LS': ny =", "c_void_p] self.shared_lib.ocp_nlp_cost_model_set(self.nlp_config, \\ self.nlp_dims, self.nlp_in, stage, field, value_data_p) elif field_", "dims.nr = 0 else: dims.nphi = casadi_length(model.con_phi_expr) if is_empty(model.con_r_expr): raise", "dump to json ocp_formulation_json_dump(acados_ocp, json_file) # render templates ocp_render_templates(acados_ocp, json_file)", "= self.shared_lib.acados_solve() return status def get(self, stage_, field_): \"\"\" get", "and/or other materials provided with the distribution. # # THIS", "have {})'.format(field_, tuple(dims), value_shape)) value_data = cast(value_.ctypes.data, POINTER(c_double)) value_data_p =", "con_phi_expr_e is nonempty') else: dims.nr_e = casadi_length(model.con_r_expr_e) # Slack dimensions", "c_int(stage_) # treat parameters separately if field_ is 'p': self.shared_lib.acados_update_params.argtypes", "the solver: Parameters: :param field_: string, e.g. 'print_level', 'rti_phase', 'initialize_t_slacks',", "dimension N, regarding shooting_nodes.') time_steps = np.zeros((dims.N,)) for i in", "[ lbu lbx lg lh lphi ubu ubx ug uh", "\\ self.nlp_dims, self.nlp_out, stage_, field) if value_.shape[0] != dims: msg", "np.zeros((nsh,)) elif constraints.lsh.shape[0] != nsh: raise Exception('inconsistent dimension nsh, regarding", "if acados_ocp.constraints.constr_type == 'BGP' and acados_ocp.dims.nphi > 0: # constraints", "ny_e: regarding W_e, cost_y_expr_e.' + \\ f'\\nGot W_e[{cost.W_e.shape}], Vx_e[{cost.Vx_e.shape}]') if", "stage_, field, out_data) elif field_ in mem_fields: self.shared_lib.ocp_nlp_get_at_stage.argtypes = \\", "dims.nsphi = nsphi nsg = constraints.idxsg.shape[0] if is_empty(constraints.lsg): constraints.lsg =", "raise Exception('inconsistent dimension nbx_e, regarding idxbx_e, ubx_e, lbx_e.') else: dims.nbx_e", "template_dir = 'c_generated_code/{}_cost/'.format(name) in_file = 'cost_y_fun.in.h' out_file = '{}_cost_y_fun.h'.format(name) render_template(in_file,", "the documentation # and/or other materials provided with the distribution.", "nsg, regarding idxsg, lsg.') if is_empty(constraints.usg): constraints.usg = np.zeros((nsg,)) elif", "def __init__(self, acados_ocp, json_file='acados_ocp_nlp.json'): self.solver_created = False model = acados_ocp.model", "setting up loader and environment json_path = '{cwd}/{json_file}'.format( cwd=os.getcwd(), json_file=json_file)", "np.zeros((nsbu,)) elif constraints.usbu.shape[0] != nsbu: raise Exception('inconsistent dimension nsbu, regarding", "self.shared_lib.acados_get_nlp_config() self.shared_lib.acados_get_nlp_out.restype = c_void_p self.nlp_out = self.shared_lib.acados_get_nlp_out() self.shared_lib.acados_get_nlp_in.restype = c_void_p", "elif constraints.lsh.shape[0] != nsh: raise Exception('inconsistent dimension nsh, regarding idxsh,", "raise Exception('inconsistent dimension nsh_e, regarding idxsh_e, lsh_e.') if is_empty(constraints.ush_e): constraints.ush_e", "= 'c_generated_code/{}_cost/'.format(name) in_file = 'external_cost.in.h' out_file = '{}_external_cost.h'.format(name) render_template(in_file, out_file,", "<NAME>, <NAME> # # This file is part of acados.", "raise Exception('AcadosOcpSolver.solve(): argument \\'rti_phase\\' can ' 'take only value 0", "are permitted provided that the following conditions are met: #", "constraints.ug.shape[0] != ng or constraints.C.shape[0] != ng \\ or constraints.D.shape[0]", "+ f'Detected ns_e = {ns_e} = nsbx_e + nsg_e +", "nonlinear function if acados_ocp.constraints.constr_type == 'BGP' and acados_ocp.dims.nphi > 0:", "# generate external functions ocp_generate_external_functions(acados_ocp, model) # dump to json", "> 0: template_dir = 'c_generated_code/{}_constraints/'.format(name) in_file = 'h_constraint.in.h' out_file =", "self.shared_lib.acados_create() self.solver_created = True self.shared_lib.acados_get_nlp_opts.restype = c_void_p self.nlp_opts = self.shared_lib.acados_get_nlp_opts()", "dimension {} (you have {})'.format(dims, value_.shape[0]) raise Exception(msg) value_data =", "acados_model_strip_casadi_symbolics(ocp_nlp_dict['model']) # strip shooting_nodes ocp_nlp_dict['solver_options'].pop('shooting_nodes', None) dims_dict = acados_class2dict(acados_ocp.dims) ocp_check_against_layout(ocp_nlp_dict,", "= cast(value_.ctypes.data, POINTER(c_double)) value_data_p = cast((value_data), c_void_p) self.shared_lib.ocp_nlp_constraints_model_set.argtypes = \\", "# terminal nonlinear cost function if acados_ocp.cost.cost_type_e == 'NONLINEAR_LS': template_dir", "return def options_set(self, field_, value_): \"\"\" set options of the", "WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE #", "met: # # 1. Redistributions of source code must retain", "'{cwd}/{json_file}'.format( cwd=os.getcwd(), json_file=json_file) if not os.path.exists(json_path): raise Exception('{} not found!'.format(json_path))", "if acados_ocp.constraints.constr_type_e == 'BGH' and acados_ocp.dims.nh_e > 0: template_dir =", "def get(self, stage_, field_): \"\"\" get the last solution of", "all(constraints.lbx_0 == constraints.ubx_0): dims.nbxe_0 = dims.nbx_0 # path nbx =", "non dict attributes if not isinstance(v, dict): continue # setattr(ocp_nlp,", "of soft lower inequality constraints \\n su: slack variables of", "c_void_p, c_int, c_char_p, c_void_p] self.shared_lib.ocp_nlp_out_get(self.nlp_config, \\ self.nlp_dims, self.nlp_out, stage_, field,", "provide either time_steps or shooting_nodes for nonuniform discretization') tf =", "constraints_set(self, stage_, field_, value_): \"\"\" set numerical data in the", "raise Exception('inconsistent dimension nsphi_e, regarding idxsphi_e, usphi_e.') dims.nsphi_e = nsphi_e", "if constraints.ubx.shape[0] != nbx or constraints.lbx.shape[0] != nbx: raise Exception('inconsistent", "ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR", "nbx nbu = constraints.idxbu.shape[0] if constraints.ubu.shape[0] != nbu or constraints.lbu.shape[0]", "Vu should have nu columns.') if cost.yref.shape[0] != ny: raise", "in ['statistics', 'time_tot', 'time_lin', 'time_sim', 'time_sim_ad', 'time_sim_la', 'time_qp', 'time_qp_solver_call', 'time_reg',", "# Redistribution and use in source and binary forms, with", "discretization if is_empty(opts.time_steps) and is_empty(opts.shooting_nodes): # uniform discretization opts.time_steps =", "- terminal if acados_ocp.cost.cost_type_e == 'EXTERNAL': template_dir = 'c_generated_code/{}_cost/'.format(name) in_file", "to evaluation of all inequalities (at the solution) \\n sl:", "table with info about last iteration 'stat_m', 'stat_n', ] field", "dimension: regarding W_e, yref_e.') dims.ny_e = ny_e elif cost.cost_type_e ==", "the above copyright notice, # this list of conditions and", "nonlinear constraints if acados_ocp.constraints.constr_type == 'BGH' and acados_ocp.dims.nh > 0:", "'time_qp_solver_call', # cpu time inside qp solver (without converting the", "cost_y_expr.') elif casadi_length(model.cost_y_expr) != ny: raise Exception('inconsistent dimension ny: regarding", "raise Exception('model.x should be column vector!') # nu if is_empty(model.u):", "def cost_set(self, stage_, field_, value_): \"\"\" set numerical data in", "dict): continue # setattr(ocp_nlp, acados_struct, dict(getattr(acados_ocp, acados_struct).__dict__)) # Copy ocp", "acados_ocp.cost.cost_type == 'NONLINEAR_LS': generate_c_code_nls_cost(model, model.name, False) elif acados_ocp.cost.cost_type == 'EXTERNAL':", "in_file = 'make_sfun.in.m' out_file = 'make_sfun.m' render_template(in_file, out_file, template_dir, json_path)", "mem_fields)) self.shared_lib.ocp_nlp_dims_get_from_attr.argtypes = \\ [c_void_p, c_void_p, c_void_p, c_int, c_char_p] self.shared_lib.ocp_nlp_dims_get_from_attr.restype", "field_ in ['sqp_iter', 'stat_m', 'stat_n']: out = np.ascontiguousarray(np.zeros((1,)), dtype=np.int64) out_data", "elif field_ in out_fields: self.shared_lib.ocp_nlp_out_set.argtypes = \\ [c_void_p, c_void_p, c_void_p,", "provided with the distribution. # # THIS SOFTWARE IS PROVIDED", "ng \\ or constraints.D.shape[0] != ng: raise Exception('inconsistent dimension ng,", "= ng if not is_empty(model.con_h_expr): nh = casadi_length(model.con_h_expr) else: nh", "Exception('inconsistent dimension nsg_e, regarding idxsg_e, usg_e.') dims.nsg_e = nsg_e nsphi_e", "ns_e: wrong_field = \"Zl_e\" dim = cost.Zl_e.shape[0] elif cost.Zu_e.shape[0] !=", "== 'LINEAR_LS': acados_ocp.cost.Vx = np.zeros((acados_ocp.dims.ny, acados_ocp.dims.nx)) acados_ocp.cost.Vu = np.zeros((acados_ocp.dims.ny, acados_ocp.dims.nu))", "Possible values are {}. Exiting.'.format(fields, fields)) if field_ in ['sqp_iter',", "and ny_e != 0: raise Exception('inconsistent dimension ny_e: regarding W_e,", "LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN", "cost_y_expr_e.' + \\ f'\\nGot W_e[{cost.W_e.shape}], Vx_e[{cost.Vx_e.shape}]') if cost.Vx_e.shape[1] != dims.nx", "slack variables of soft lower inequality constraints \\n su: slack", "template_dir = 'c_generated_code/{}_cost/'.format(name) in_file = 'external_cost.in.h' out_file = '{}_external_cost.h'.format(name) render_template(in_file,", "= self.shared_lib.acados_get_nlp_dims() self.shared_lib.acados_get_nlp_config.restype = c_void_p self.nlp_config = self.shared_lib.acados_get_nlp_config() self.shared_lib.acados_get_nlp_out.restype =", "is_empty(constraints.lsphi): constraints.lsphi = np.zeros((nsphi,)) elif constraints.lsphi.shape[0] != nsphi: raise Exception('inconsistent", "nonempty') else: dims.nr = casadi_length(model.con_r_expr) # terminal nbx_e = constraints.idxbx_e.shape[0]", "W_e, cost_y_expr_e.') elif casadi_length(model.cost_y_expr_e) != ny_e: raise Exception('inconsistent dimension ny_e:", "'acados_sim_solver.in.c' out_file = 'acados_sim_solver_{}.c'.format(name) render_template(in_file, out_file, template_dir, json_path) in_file =", "self.shared_lib.acados_get_nlp_out.restype = c_void_p self.nlp_out = self.shared_lib.acados_get_nlp_out() self.shared_lib.acados_get_nlp_in.restype = c_void_p self.nlp_in", "cost.Vx.shape[0] != ny or cost.Vu.shape[0] != ny: raise Exception('inconsistent dimension", "= cast(out.ctypes.data, POINTER(c_double)) else: out = np.ascontiguousarray(np.zeros((1,)), dtype=np.float64) out_data =", "casadi_length(model.con_r_expr_e) # Slack dimensions nsbx = constraints.idxsbx.shape[0] if is_empty(constraints.lsbx): constraints.lsbx", "# constraints on outer function template_dir = 'c_generated_code/{}_constraints/'.format(name) in_file =", "c_void_p) self.shared_lib.ocp_nlp_cost_model_set.argtypes = \\ [c_void_p, c_void_p, c_void_p, c_int, c_char_p, c_void_p]", "'sl', 'su',] .. note:: regarding lam, t: \\n the inequalities", "nh if is_empty(model.con_phi_expr): dims.nphi = 0 dims.nr = 0 else:", "and value_ > 0: raise Exception('AcadosOcpSolver.solve(): argument \\'rti_phase\\' can '", "DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS", "OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,", "object \"\"\" def __init__(self, acados_ocp, json_file='acados_ocp_nlp.json'): self.solver_created = False model", "out_file = '{}_h_e_constraint.h'.format(name) render_template(in_file, out_file, template_dir, json_path) # nonlinear cost", "\"Zu_e\" dim = cost.Zu_e.shape[0] elif cost.zl_e.shape[0] != ns_e: wrong_field =", "= \"zl_e\" dim = cost.zl_e.shape[0] elif cost.zu_e.shape[0] != ns_e: wrong_field", "anymore, better use cost_set, constraints_set def set(self, stage_, field_, value_):", "= constraints.lbx_0.size if all(constraints.lbx_0 == constraints.ubx_0): dims.nbxe_0 = dims.nbx_0 #", "template_dir, json_path) ## folder model template_dir = 'c_generated_code/{}_model/'.format(name) in_file =", "= time_steps elif (not is_empty(opts.time_steps)) and (not is_empty(opts.shooting_nodes)): Exception('Please provide", "'time_sim', # cpu time for integrator 'time_sim_ad', # cpu time", "templates in_file = 'main.in.c' out_file = 'main_{}.c'.format(name) render_template(in_file, out_file, template_dir,", "elif constraints.lsphi.shape[0] != nsphi: raise Exception('inconsistent dimension nsphi, regarding idxsphi,", "(not is_empty(opts.shooting_nodes)): Exception('Please provide either time_steps or shooting_nodes for nonuniform", "\\ stat[7][jj], stat[8][jj], stat[9][jj], stat[10][jj])) print('\\n') elif self.acados_ocp.solver_options.nlp_solver_type == 'SQP_RTI':", "json_path) class AcadosOcpSolver: \"\"\" class to interact with the acados", "in mem_fields: self.shared_lib.ocp_nlp_get_at_stage.argtypes = \\ [c_void_p, c_void_p, c_void_p, c_int, c_char_p,", "= cost.Zl.shape[0] elif cost.Zu.shape[0] != ns: wrong_field = \"Zu\" dim", "regarding_e lg_e, ug_e, C_e.') else: dims.ng_e = ng_e if not", "generate_c_code_nls_cost(model, model.name, False) elif acados_ocp.cost.cost_type == 'EXTERNAL': generate_c_code_external_cost(model, False) if", "self.shared_lib.acados_solve() return status def get(self, stage_, field_): \"\"\" get the", "IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED", "wrong_field != \"\": raise Exception(f'Inconsistent size for field {wrong_field}, with", "\"\"\" status = self.shared_lib.acados_solve() return status def get(self, stage_, field_):", "= 'acados_solver.in.c' out_file = 'acados_solver_{}.c'.format(name) render_template(in_file, out_file, template_dir, json_path) in_file", "constraints.idxbx_e.shape[0] if constraints.ubx_e.shape[0] != nbx_e or constraints.lbx_e.shape[0] != nbx_e: raise", "out_file, template_dir, json_path) # external cost - terminal if acados_ocp.cost.cost_type_e", "\\n the inequalities are internally organized in the following order:", "if cost.Vx.shape[1] != dims.nx and ny != 0: raise Exception('inconsistent", "if is_empty(model.con_phi_expr): dims.nphi = 0 dims.nr = 0 else: dims.nphi", "over nonlinear constraints: con_r_expr but con_phi_expr is nonempty') else: dims.nr", "[c_void_p, c_void_p, c_void_p, c_int, c_char_p, POINTER(c_int)] self.shared_lib.ocp_nlp_constraint_dims_get_from_attr.restype = c_int dims", "in double_fields: if not isinstance(value_, float): raise Exception('solver option {}", "self.shared_lib.acados_update_params(stage, value_data, value_.shape[0]) else: if field_ not in constraints_fields +", "import generate_c_code_implicit_ode from .generate_c_code_gnsf import generate_c_code_gnsf from .generate_c_code_constraint import generate_c_code_constraint", "self.nlp_dims, self.nlp_solver, stage_, field, out_data) return out def print_statistics(self): stat", "min_size = min([stat_m, sqp_iter+1]) out = np.ascontiguousarray( np.zeros( (stat_n[0]+1, min_size[0])", "acados_ocp.cost.cost_type == 'EXTERNAL': generate_c_code_external_cost(model, False) if acados_ocp.cost.cost_type_e == 'NONLINEAR_LS': generate_c_code_nls_cost(model,", "raise Exception('inconsistent dimension nh, regarding lh, uh, con_h_expr.') else: dims.nh", "'z', 'pi', 'lam', 't'] mem_fields = ['sl', 'su'] field =", "SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH", "import * from casadi import CasadiMeta, Function, SX from copy", "and constraints.ubx_0 == []): dims.nbx_0 = 0 else: this_shape =", "shooting node :param field_: string in ['x', 'u', 'z', 'pi',", "'time_lin', # cpu time for linearization 'time_sim', # cpu time", "field = field.encode('utf-8') if (field_ not in fields): raise Exception('AcadosOcpSolver.get_stats():", "if not is_column(constraints.lbx_0): raise Exception('lbx_0, ubx_0 must be column vectors!')", "dimension {dim}, \\n\\t'\\ + f'Detected ns = {ns} = nsbx", "= ny_e elif cost.cost_type_e == 'NONLINEAR_LS': ny_e = cost.W_e.shape[0] if", "cost.Zl.shape[0] != ns: wrong_field = \"Zl\" dim = cost.Zl.shape[0] elif", "'lam', 't'] # cast value_ to avoid conversion issues value_", "and the following disclaimer in the documentation # and/or other", "else: opts = dict(generate_hess=0) if acados_ocp.dims.nphi > 0 or acados_ocp.dims.nh", "# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND", "= \"Zl\" dim = cost.Zl.shape[0] elif cost.Zu.shape[0] != ns: wrong_field", "acados_ocp.solver_options.hessian_approx == 'EXACT': opts = dict(generate_hess=1) else: opts = dict(generate_hess=0)", "lg_e, ug_e, C_e.') else: dims.ng_e = ng_e if not is_empty(model.con_h_expr_e):", "field_, value_): \"\"\" set numerical data in the constraint module", "!= nsg_e: raise Exception('inconsistent dimension nsg_e, regarding idxsg_e, lsg_e.') if", "of type float. You have {}.'.format(field_, type(value_))) else: value_ctypes =", "other_shape: raise Exception('lbx_0, ubx_0 have different shapes!') if not is_column(constraints.lbx_0):", "template_dir = 'c_generated_code/{}_cost/'.format(name) in_file = 'cost_y_e_fun.in.h' out_file = '{}_cost_y_e_fun.h'.format(name) render_template(in_file,", "c_void_p self.nlp_opts = self.shared_lib.acados_get_nlp_opts() self.shared_lib.acados_get_nlp_dims.restype = c_void_p self.nlp_dims = self.shared_lib.acados_get_nlp_dims()", "regarding idxsbu, usbu.') dims.nsbu = nsbu nsh = constraints.idxsh.shape[0] if", "= np.zeros((nsbx,)) elif constraints.usbx.shape[0] != nsbx: raise Exception('inconsistent dimension nsbx,", "c_char_p, c_void_p] self.shared_lib.ocp_nlp_get(self.nlp_config, self.nlp_solver, field, out_data) return out # Note:", "dimension nsh_e, regarding idxsh_e, lsh_e.') if is_empty(constraints.ush_e): constraints.ush_e = np.zeros((nsh_e,))", "if cost.cost_type == 'LINEAR_LS': ny = cost.W.shape[0] if cost.Vx.shape[0] !=", "json_path) in_file = 'acados_solver_sfun.in.c' out_file = 'acados_solver_sfunction_{}.c'.format(name) render_template(in_file, out_file, template_dir,", "on convex over nonlinear function if acados_ocp.constraints.constr_type == 'BGP' and", "cast(value_.ctypes.data, POINTER(c_double)) self.shared_lib.acados_update_params(stage, value_data, value_.shape[0]) else: if field_ not in", "# # 2. Redistributions in binary form must reproduce the", "c_void_p] self.shared_lib.ocp_nlp_out_set(self.nlp_config, \\ self.nlp_dims, self.nlp_out, stage, field, value_data_p) return def", "= \"Zl_e\" dim = cost.Zl_e.shape[0] elif cost.Zu_e.shape[0] != ns_e: wrong_field", "= constraints.idxsphi_e.shape[0] if is_empty(constraints.lsphi_e): constraints.lsphi_e = np.zeros((nsphi_e,)) elif constraints.lsphi_e.shape[0] !=", "make_model_consistent(model) if acados_ocp.solver_options.integrator_type == 'ERK': # explicit model -- generate", "cast(value_.ctypes.data, POINTER(c_double)) value_data_p = cast((value_data), c_void_p) self.shared_lib.ocp_nlp_cost_model_set.argtypes = \\ [c_void_p,", "regarding idxsphi_e, usphi_e.') dims.nsphi_e = nsphi_e # terminal ns_e =", "Instantiate AcadosOcp object acados_ocp = AcadosOcp() # load class dict", "disclaimer. # # 2. Redistributions in binary form must reproduce", "0: template_dir = 'c_generated_code/{}_constraints/'.format(name) in_file = 'h_e_constraint.in.h' out_file = '{}_h_e_constraint.h'.format(name)", "= np.zeros((nsbx_e,)) elif constraints.lsbx_e.shape[0] != nsbx_e: raise Exception('inconsistent dimension nsbx_e,", "cast(value_.ctypes.data, POINTER(c_double)) value_data_p = cast((value_data), c_void_p) self.shared_lib.ocp_nlp_constraints_model_set.argtypes = \\ [c_void_p,", "string_fields: if not isinstance(value_, str): raise Exception('solver option {} must", "# terminal constraints on outer function template_dir = 'c_generated_code/{}_constraints/'.format(name) in_file", "dims.nsh = nsh nsphi = constraints.idxsphi.shape[0] if is_empty(constraints.lsphi): constraints.lsphi =", "dimension ny_e: regarding W_e, cost_y_expr_e.' + \\ f'\\nGot W_e[{cost.W_e.shape}], Vx_e[{cost.Vx_e.shape}]')", "= \"Zu\" dim = cost.Zu.shape[0] elif cost.zl.shape[0] != ns: wrong_field", "nsphi_e.\\n\\t'\\ + f'With nsbx_e = {nsbx_e}, nsg_e = {nsg_e}, nsh_e", "c_void_p self.nlp_in = self.shared_lib.acados_get_nlp_in() self.shared_lib.acados_get_nlp_solver.restype = c_void_p self.nlp_solver = self.shared_lib.acados_get_nlp_solver()", "NOTE: DLL cannot be easily unloaded!!! # see https://stackoverflow.com/questions/359498/how-can-i-unload-a-dll-using-ctypes-in-python #", "stat[1][jj], stat[2][jj], \\ stat[3][jj], stat[4][jj], int(stat[5][jj]), int(stat[6][jj]))) if stat.shape[0]>7: print('\\t{:e}\\t{:e}\\t{:e}\\t{:e}'.format(", "if stat.shape[0]>7: print('\\t{:e}\\t{:e}\\t{:e}\\t{:e}'.format( \\ stat[7][jj], stat[8][jj], stat[9][jj], stat[10][jj])) print('\\n') elif", "= nsphi nsg = constraints.idxsg.shape[0] if is_empty(constraints.lsg): constraints.lsg = np.zeros((nsg,))", "retain the above copyright notice, # this list of conditions", "get_ocp_nlp_layout(): current_module = sys.modules[__name__] acados_path = os.path.dirname(current_module.__file__) with open(acados_path +", "cost.zl.shape[0] != ns: wrong_field = \"zl\" dim = cost.zl.shape[0] elif", "acados_ocp.constraints.constr_type_e == 'BGH' and acados_ocp.dims.nh_e > 0: template_dir = 'c_generated_code/{}_constraints/'.format(name)", "\\n sl: slack variables of soft lower inequality constraints \\n", "[]): dims.nbx_0 = 0 else: this_shape = constraints.lbx_0.shape other_shape =", "non dict attributes if not isinstance(v, dict): continue acados_attribute =", ":param field_: string, e.g. 'lbx' :param value_: of appropriate size", "out_file, template_dir, json_path) # terminal constraints on convex over nonlinear", "OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY", "template_dir, json_path) # nonlinear constraints if acados_ocp.constraints.constr_type == 'BGH' and", "= nsbx_e nsh_e = constraints.idxsh_e.shape[0] if is_empty(constraints.lsh_e): constraints.lsh_e = np.zeros((nsh_e,))", "self.solver_created = False model = acados_ocp.model # make dims consistent", "nsbu: raise Exception('inconsistent dimension nsbu, regarding idxsbu, lsbu.') if is_empty(constraints.usbu):", "+ mem_fields): raise Exception('AcadosOcpSolver.get(): {} is an invalid argument.\\ \\n", "field_, value_): \"\"\" set options of the solver: Parameters: :param", "= casadi_length(model.con_h_expr_e) else: nh_e = 0 if constraints.uh_e.shape[0] != nh_e", "WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE", "nsh_e, regarding idxsh_e, lsh_e.') if is_empty(constraints.ush_e): constraints.ush_e = np.zeros((nsh_e,)) elif", "= AcadosOcp() # load class dict acados_ocp.__dict__ = ocp_nlp_dict #", "= constraints.idxsphi.shape[0] if is_empty(constraints.lsphi): constraints.lsphi = np.zeros((nsphi,)) elif constraints.lsphi.shape[0] !=", "field, value_ctypes) else: self.shared_lib.ocp_nlp_solver_opts_set.argtypes = \\ [c_void_p, c_void_p, c_char_p, c_void_p]", "if is_empty(constraints.lsh_e): constraints.lsh_e = np.zeros((nsh_e,)) elif constraints.lsh_e.shape[0] != nsh_e: raise", "dim = cost.Zl_e.shape[0] elif cost.Zu_e.shape[0] != ns_e: wrong_field = \"Zu_e\"", "modification, are permitted provided that the following conditions are met:", "raise Exception('inconsistent dimension: Vu should have nu columns.') if cost.yref.shape[0]", "json.dump(ocp_nlp_dict, f, default=np_array_to_list, indent=4, sort_keys=True) def ocp_formulation_json_load(json_file='acados_ocp_nlp.json'): # Load acados_ocp_nlp", "ny: raise Exception('inconsistent dimension: regarding W, yref.' + \\ f'\\nGot", "cost.Vx_e.shape[1] != dims.nx and ny_e != 0: raise Exception('inconsistent dimension:", "= field.encode('utf-8') if field_ in string_fields: self.shared_lib.ocp_nlp_solver_opts_set.argtypes = \\ [c_void_p,", "!= ns: wrong_field = \"zl\" dim = cost.zl.shape[0] elif cost.zu.shape[0]", "field.encode('utf-8') if (field_ not in out_fields + mem_fields): raise Exception('AcadosOcpSolver.get():", "for jj in range(stat.shape[1]): print('{:d}\\t{:d}\\t{:d}'.format( int(stat[0][jj]), int(stat[1][jj]), int(stat[2][jj]))) if stat.shape[0]>3:", "np if is_empty(model.p): dims.np = 0 else: dims.np = casadi_length(model.p)", "out_file, template_dir, json_path) in_file = 'acados_solver.in.h' out_file = 'acados_solver_{}.h'.format(name) render_template(in_file,", "# ARISING IN ANY WAY OUT OF THE USE OF", "time_steps[i] = opts.shooting_nodes[i+1] - opts.shooting_nodes[i] opts.time_steps = time_steps elif (not", "for linearization 'time_sim', # cpu time for integrator 'time_sim_ad', #", "solve the ocp with current input \"\"\" status = self.shared_lib.acados_solve()", "(field_ not in fields): raise Exception('AcadosOcpSolver.get_stats(): {} is not a", "if is_empty(model.con_r_expr_e): raise Exception('convex over nonlinear constraints: con_r_expr_e but con_phi_expr_e", "with open(acados_path + '/acados_layout.json', 'r') as f: ocp_nlp_layout = json.load(f)", "wrong_field = \"zu_e\" dim = cost.zu_e.shape[0] if wrong_field != \"\":", "'c_generated_code/{}_cost/'.format(name) in_file = 'cost_y_fun.in.h' out_file = '{}_cost_y_fun.h'.format(name) render_template(in_file, out_file, template_dir,", "dimension nsphi, regarding idxsphi, lsphi.') if is_empty(constraints.usphi): constraints.usphi = np.zeros((nsphi,))", "wrong_field = \"zl_e\" dim = cost.zl_e.shape[0] elif cost.zu_e.shape[0] != ns_e:", "# uniform discretization opts.time_steps = opts.tf / dims.N * np.ones((dims.N,))", "render_template(in_file, out_file, template_dir, json_path) in_file = 'acados_sim_solver.in.c' out_file = 'acados_sim_solver_{}.c'.format(name)", "'lam', 't', 'sl', 'su',] .. note:: regarding lam, t: \\n", "np.ascontiguousarray(np.zeros((dims,)), dtype=np.float64) out_data = cast(out.ctypes.data, POINTER(c_double)) if (field_ in out_fields):", "self.shared_lib.ocp_nlp_cost_dims_get_from_attr.argtypes = \\ [c_void_p, c_void_p, c_void_p, c_int, c_char_p, POINTER(c_int)] self.shared_lib.ocp_nlp_cost_dims_get_from_attr.restype", "else: nh = 0 if constraints.uh.shape[0] != nh or constraints.lh.shape[0]", "elif cost.cost_type == 'NONLINEAR_LS': ny = cost.W.shape[0] if is_empty(model.cost_y_expr) and", "upper inequality constraints \\n \"\"\" out_fields = ['x', 'u', 'z',", "self.nlp_config = self.shared_lib.acados_get_nlp_config() self.shared_lib.acados_get_nlp_out.restype = c_void_p self.nlp_out = self.shared_lib.acados_get_nlp_out() self.shared_lib.acados_get_nlp_in.restype", "not in fields): raise Exception('AcadosOcpSolver.get_stats(): {} is not a valid", "if acados_ocp.cost.cost_type == 'NONLINEAR_LS': template_dir = 'c_generated_code/{}_cost/'.format(name) in_file = 'cost_y_fun.in.h'", "regarding lh_e, uh_e, con_h_expr_e.') else: dims.nh_e = nh_e if is_empty(model.con_phi_expr_e):", "dimension: Vu should have nu columns.') if cost.yref.shape[0] != ny:", "self.shared_lib.ocp_nlp_constraints_model_set(self.nlp_config, \\ self.nlp_dims, self.nlp_in, stage, field, value_data_p) return def options_set(self,", "nsh + nsphi.\\n\\t'\\ + f'With nsbx = {nsbx}, nsbu =", "= \\ [c_void_p, c_void_p, c_char_p, c_void_p] self.shared_lib.ocp_nlp_solver_opts_set(self.nlp_config, \\ self.nlp_opts, field,", "+ nsphi.\\n\\t'\\ + f'With nsbx = {nsbx}, nsbu = {nsbu},", "for field {wrong_field}, with dimension {dim}, \\n\\t'\\ + f'Detected ns", "template_dir, json_path) in_file = 'acados_solver_sfun.in.c' out_file = 'acados_solver_sfunction_{}.c'.format(name) render_template(in_file, out_file,", "'t'] # cast value_ to avoid conversion issues value_ =", "c_void_p, c_void_p, c_int, c_char_p, c_void_p] self.shared_lib.ocp_nlp_cost_model_set(self.nlp_config, \\ self.nlp_dims, self.nlp_in, stage,", "model -- generate C code generate_c_code_explicit_ode(model) elif acados_ocp.solver_options.integrator_type == 'IRK':", "+ nsphi wrong_field = \"\" if cost.Zl.shape[0] != ns: wrong_field", "in_file = 'phi_constraint.in.h' out_file = '{}_phi_constraint.h'.format(name) render_template(in_file, out_file, template_dir, json_path)", "field_ not in constraints_fields + cost_fields + out_fields: raise Exception(\"AcadosOcpSolver.set():", "Vx_e should have nx columns.') if cost.yref_e.shape[0] != ny_e: raise", "- opts.tf) / tf > 1e-15: raise Exception(f'Inconsistent discretization: {opts.tf}'\\", "get_stats(self, field_): \"\"\" get the information of the last solver", "on convex over nonlinear function if acados_ocp.constraints.constr_type_e == 'BGP' and", "'c_generated_code/' ## Render templates in_file = 'main.in.c' out_file = 'main_{}.c'.format(name)", "or constraints.lh.shape[0] != nh: raise Exception('inconsistent dimension nh, regarding lh,", "OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE #", "'acados_solver_{}.h'.format(name) render_template(in_file, out_file, template_dir, json_path) in_file = 'Makefile.in' out_file =", "field_ in mem_fields: self.shared_lib.ocp_nlp_get_at_stage.argtypes = \\ [c_void_p, c_void_p, c_void_p, c_int,", "raise Exception('solver option {} must be of type int. You", "+ nsh_e + nsphi_e.\\n\\t'\\ + f'With nsbx_e = {nsbx_e}, nsg_e", "Copy ocp object attributes dictionaries ocp_nlp_dict[acados_struct]=dict(getattr(acados_ocp, acados_struct).__dict__) ocp_nlp_dict = format_class_dict(ocp_nlp_dict)", "{}.'.format(field_, type(value_))) else: value_ctypes = value_.encode('utf-8') if field_ == 'rti_phase':", "SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED", "input \"\"\" status = self.shared_lib.acados_solve() return status def get(self, stage_,", "= {nsbu}, nsg = {nsg}, nsh = {nsh}, nsphi =", "'su',] .. note:: regarding lam, t: \\n the inequalities are", "def print_statistics(self): stat = self.get_stats(\"statistics\") if self.acados_ocp.solver_options.nlp_solver_type == 'SQP': print('\\niter\\tres_stat\\tres_eq\\t\\tres_ineq\\tres_comp\\tqp_stat\\tqp_iter')", "cost.Vz.shape[0] != ny: raise Exception('inconsistent dimension ny, regarding W, Vx,", "structure description ocp_layout = get_ocp_nlp_layout() with open(json_file, 'r') as f:", "int(stat[5][jj]), int(stat[6][jj]))) if stat.shape[0]>7: print('\\t{:e}\\t{:e}\\t{:e}\\t{:e}'.format( \\ stat[7][jj], stat[8][jj], stat[9][jj], stat[10][jj]))", "# # This file is part of acados. # #", "all inequalities (at the solution) \\n sl: slack variables of", "yref_e.') dims.ny_e = ny_e elif cost.cost_type_e == 'NONLINEAR_LS': ny_e =", "nsg_e + nsh_e + nsphi_e.\\n\\t'\\ + f'With nsbx_e = {nsbx_e},", "'statistics', # table with info about last iteration 'stat_m', 'stat_n',", "raise Exception(f'Inconsistent discretization: {opts.tf}'\\ f' = tf != sum(opts.time_steps) =", "NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE #", "fields)) if field_ in ['sqp_iter', 'stat_m', 'stat_n']: out = np.ascontiguousarray(np.zeros((1,)),", "= np.zeros((nsg,)) elif constraints.lsg.shape[0] != nsg: raise Exception('inconsistent dimension nsg,", "== 'NONLINEAR_LS': template_dir = 'c_generated_code/{}_cost/'.format(name) in_file = 'cost_y_fun.in.h' out_file =", "if field_ in int_fields: if not isinstance(value_, int): raise Exception('solver", "ng = constraints.lg.shape[0] if constraints.ug.shape[0] != ng or constraints.C.shape[0] !=", "constraints.D.shape[0] != ng: raise Exception('inconsistent dimension ng, regarding lg, ug,", "dims.nr = casadi_length(model.con_r_expr) # terminal nbx_e = constraints.idxbx_e.shape[0] if constraints.ubx_e.shape[0]", "template_dir = 'c_generated_code/' ## Render templates in_file = 'main.in.c' out_file", "soft lower inequality constraints \\n su: slack variables of soft", "acados_ocp_nlp structure description ocp_layout = get_ocp_nlp_layout() # Copy input ocp", "for field {wrong_field}, with dimension {dim}, \\n\\t'\\ + f'Detected ns_e", "'stat_m', 'stat_n']: out = np.ascontiguousarray(np.zeros((1,)), dtype=np.int64) out_data = cast(out.ctypes.data, POINTER(c_int64))", "constraints.lbx_0.size if all(constraints.lbx_0 == constraints.ubx_0): dims.nbxe_0 = dims.nbx_0 # path", "= nsbx_e + nsg_e + nsh_e + nsphi_e.\\n\\t'\\ + f'With", "np.zeros((nsh_e,)) elif constraints.ush_e.shape[0] != nsh_e: raise Exception('inconsistent dimension nsh_e, regarding", "== 'rti_phase': if value_ < 0 or value_ > 2:", "SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;", "constraints.idxsh.shape[0] if is_empty(constraints.lsh): constraints.lsh = np.zeros((nsh,)) elif constraints.lsh.shape[0] != nsh:", "stat[7][jj], stat[8][jj], stat[9][jj], stat[10][jj])) print('\\n') elif self.acados_ocp.solver_options.nlp_solver_type == 'SQP_RTI': print('\\niter\\tqp_stat\\tqp_iter')", "out_file, template_dir, json_path) # external cost if acados_ocp.cost.cost_type == 'EXTERNAL':", "acados_ocp.dims.nphi_e > 0: # terminal constraints on outer function template_dir", "{}. Exiting.\".format(field, \\ constraints_fields + cost_fields + out_fields + ['p']))", "lsh.') if is_empty(constraints.ush): constraints.ush = np.zeros((nsh,)) elif constraints.ush.shape[0] != nsh:", "self.shared_lib.ocp_nlp_solver_opts_set.argtypes = \\ [c_void_p, c_void_p, c_char_p, c_void_p] self.shared_lib.ocp_nlp_solver_opts_set(self.nlp_config, \\ self.nlp_opts,", "or constraints.C_e.shape[0] != ng_e: raise Exception('inconsistent dimension ng_e, regarding_e lg_e,", "-*- # # Copyright 2019 <NAME>, <NAME>, <NAME>, # <NAME>,", "nh, regarding lh, uh, con_h_expr.') else: dims.nh = nh if", "W, yref.' + \\ f'\\nGot W[{cost.W.shape}], yref[{cost.yref.shape}]\\n') dims.ny = ny", "if is_empty(constraints.usbx): constraints.usbx = np.zeros((nsbx,)) elif constraints.usbx.shape[0] != nsbx: raise", "0: raise Exception('inconsistent dimension: Vx should have nx columns.') if", "= np.zeros((nsphi,)) elif constraints.usphi.shape[0] != nsphi: raise Exception('inconsistent dimension nsphi,", "set(self, stage_, field_, value_): cost_fields = ['y_ref', 'yref'] constraints_fields =", "data in the cost module of the solver: :param stage_:", "OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY", "Exception('inconsistent dimension ng_e, regarding_e lg_e, ug_e, C_e.') else: dims.ng_e =", "number of SQP iterations 'statistics', # table with info about", "constraints.lsphi.shape[0] != nsphi: raise Exception('inconsistent dimension nsphi, regarding idxsphi, lsphi.')", "COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" # AND ANY EXPRESS", "= np.zeros((nsg_e,)) elif constraints.lsg_e.shape[0] != nsg_e: raise Exception('inconsistent dimension nsg_e,", "if is_empty(constraints.usphi_e): constraints.usphi_e = np.zeros((nsphi_e,)) elif constraints.usphi_e.shape[0] != nsphi_e: raise", "stat[8][jj], stat[9][jj], stat[10][jj])) print('\\n') elif self.acados_ocp.solver_options.nlp_solver_type == 'SQP_RTI': print('\\niter\\tqp_stat\\tqp_iter') if", "W, cost_y_expr.') elif casadi_length(model.cost_y_expr) != ny: raise Exception('inconsistent dimension ny:", "== 'EXTERNAL': generate_c_code_external_cost(model, False) if acados_ocp.cost.cost_type_e == 'NONLINEAR_LS': generate_c_code_nls_cost(model, model.name,", "ng_e or constraints.C_e.shape[0] != ng_e: raise Exception('inconsistent dimension ng_e, regarding_e", "'c_generated_code/{}_constraints/'.format(name) in_file = 'phi_constraint.in.h' out_file = '{}_phi_constraint.h'.format(name) render_template(in_file, out_file, template_dir,", "# external cost - terminal if acados_ocp.cost.cost_type_e == 'EXTERNAL': template_dir", "cost_fields + out_fields + ['p'])) self.shared_lib.ocp_nlp_dims_get_from_attr.argtypes = \\ [c_void_p, c_void_p,", "INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT", "!= 0: raise Exception('inconsistent dimension: Vx_e should have nx columns.')", "ns nsbx_e = constraints.idxsbx_e.shape[0] if is_empty(constraints.lsbx_e): constraints.lsbx_e = np.zeros((nsbx_e,)) elif", "\\n t: slack variables corresponding to evaluation of all inequalities", "raise Exception('inconsistent dimension ng_e, regarding_e lg_e, ug_e, C_e.') else: dims.ng_e", "ocp object dictionary ocp_nlp_dict = dict(deepcopy(acados_ocp).__dict__) # TODO: maybe make", "# cpu time for integrator contribution of external function calls", "cast value_ to avoid conversion issues value_ = value_.astype(float) field", "CDLL(self.shared_lib_name) self.shared_lib.acados_create() self.solver_created = True self.shared_lib.acados_get_nlp_opts.restype = c_void_p self.nlp_opts =", "False model = acados_ocp.model # make dims consistent make_ocp_dims_consistent(acados_ocp) if", "Exception('Please provide either time_steps or shooting_nodes for nonuniform discretization') tf", "= 'phi_e_constraint.in.h' out_file = '{}_phi_e_constraint.h'.format(name) render_template(in_file, out_file, template_dir, json_path) #", "acados_ocp.cost.cost_type_e == 'NONLINEAR_LS': generate_c_code_nls_cost(model, model.name, True) elif acados_ocp.cost.cost_type_e == 'EXTERNAL':", "nsh_e, regarding idxsh_e, ush_e.') dims.nsh_e = nsh_e nsg_e = constraints.idxsg_e.shape[0]", "acados_ocp.solver_options # nx if is_column(model.x): dims.nx = casadi_length(model.x) else: raise", "ny = cost.W.shape[0] if cost.Vx.shape[0] != ny or cost.Vu.shape[0] !=", "c_void_p] self.shared_lib.ocp_nlp_constraints_model_set(self.nlp_config, \\ self.nlp_dims, self.nlp_in, stage, field, value_data_p) elif field_", "avoid conversion issues value_ = value_.astype(float) field = field_ field", "field_, tuple(dims), value_shape)) value_data = cast(value_.ctypes.data, POINTER(c_double)) value_data_p = cast((value_data),", "regarding idxsg_e, lsg_e.') if is_empty(constraints.usg_e): constraints.usg_e = np.zeros((nsg_e,)) elif constraints.usg_e.shape[0]", "\\n Possible values are {}. Exiting.'.format(fields, fields)) if field_ in", "constraints if acados_ocp.constraints.constr_type == 'BGH' and acados_ocp.dims.nh > 0: template_dir", "opts.shooting_nodes[i] opts.time_steps = time_steps elif (not is_empty(opts.time_steps)) and (not is_empty(opts.shooting_nodes)):", "'z', 'pi', 'lam', 't', 'sl', 'su',] .. note:: regarding lam,", "acados_ocp.cost.cost_type_e == 'NONLINEAR_LS': template_dir = 'c_generated_code/{}_cost/'.format(name) in_file = 'cost_y_e_fun.in.h' out_file", "# cpu time for linearization 'time_sim', # cpu time for", "Exception('AcadosOcpSolver.cost_set(): mismatching dimension', \\ ' for field \"{}\" with dimension", "corresponding to shooting node :param field_: string, e.g. 'yref', 'W',", "nsphi, regarding idxsphi, lsphi.') if is_empty(constraints.usphi): constraints.usphi = np.zeros((nsphi,)) elif", "if value_.shape[0] != dims: msg = 'AcadosOcpSolver.set(): mismatching dimension for", "= cost.W_e.shape[0] if is_empty(model.cost_y_expr_e) and ny_e != 0: raise Exception('inconsistent", "regarding idxsphi, lsphi.') if is_empty(constraints.usphi): constraints.usphi = np.zeros((nsphi,)) elif constraints.usphi.shape[0]", "# constraints on convex over nonlinear function if acados_ocp.constraints.constr_type ==", "Exception('inconsistent dimension: regarding W, yref.' + \\ f'\\nGot W[{cost.W.shape}], yref[{cost.yref.shape}]\\n')", "value_): \"\"\" set options of the solver: Parameters: :param field_:", "if field_ is 'p': self.shared_lib.acados_update_params.argtypes = [c_int, POINTER(c_double)] self.shared_lib.acados_update_params.restype =", "cost.yref_e.shape[0] != ny_e: raise Exception('inconsistent dimension: regarding W_e, yref_e.') dims.ny_e", "THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" # AND ANY", "model template_dir = 'c_generated_code/{}_model/'.format(name) in_file = 'model.in.h' out_file = '{}_model.h'.format(name)", "= constraints.idxsh_e.shape[0] if is_empty(constraints.lsh_e): constraints.lsh_e = np.zeros((nsh_e,)) elif constraints.lsh_e.shape[0] !=", "{}. Exiting.'.format(fields, fields)) if field_ in ['sqp_iter', 'stat_m', 'stat_n']: out", ":param value_: of type int, float \"\"\" int_fields = ['print_level',", "must be column vectors!') dims.nbx_0 = constraints.lbx_0.size if all(constraints.lbx_0 ==", "!= nh or constraints.lh.shape[0] != nh: raise Exception('inconsistent dimension nh,", "constraints.lsphi_e.shape[0] != nsphi_e: raise Exception('inconsistent dimension nsphi_e, regarding idxsphi_e, lsphi_e.')", "acados_ocp.dims.nx)) acados_ocp.cost.Vu = np.zeros((acados_ocp.dims.ny, acados_ocp.dims.nu)) if not acados_ocp.cost.cost_type_e == 'LINEAR_LS':", "np.zeros( (stat_n[0]+1, min_size[0]) ), dtype=np.float64) out_data = cast(out.ctypes.data, POINTER(c_double)) else:", "generate_c_code_implicit_ode from .generate_c_code_gnsf import generate_c_code_gnsf from .generate_c_code_constraint import generate_c_code_constraint from", "ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,", "constraints.lbx_0.shape other_shape = constraints.ubx_0.shape if not this_shape == other_shape: raise", "> 0: # constraints on outer function template_dir = 'c_generated_code/{}_constraints/'.format(name)", "render_template(in_file, out_file, template_dir, json_path) # constraints on convex over nonlinear", "numerical data in the cost module of the solver: :param", "self.shared_lib.acados_get_nlp_opts() self.shared_lib.acados_get_nlp_dims.restype = c_void_p self.nlp_dims = self.shared_lib.acados_get_nlp_dims() self.shared_lib.acados_get_nlp_config.restype = c_void_p", "raise Exception('inconsistent dimension nsbx_e, regarding idxsbx_e, lsbx_e.') if is_empty(constraints.usbx_e): constraints.usbx_e", "+ nsh_e + nsg_e + nsphi_e wrong_field = \"\" if", "value_data_p = cast((value_data), c_void_p) self.shared_lib.ocp_nlp_cost_model_set.argtypes = \\ [c_void_p, c_void_p, c_void_p,", "!= ny: raise Exception('inconsistent dimension ny: regarding W, cost_y_expr.') if", "and ny != 0: raise Exception('inconsistent dimension: Vx should have", "notice, # this list of conditions and the following disclaimer.", "generate_c_code_explicit_ode from .generate_c_code_implicit_ode import generate_c_code_implicit_ode from .generate_c_code_gnsf import generate_c_code_gnsf from", "dict(generate_hess=1) generate_c_code_implicit_ode(model, opts) elif acados_ocp.solver_options.integrator_type == 'GNSF': generate_c_code_gnsf(model) else: raise", "\"\"\" int_fields = ['print_level', 'rti_phase', 'initialize_t_slacks'] double_fields = ['step_length'] string_fields", "self.shared_lib.ocp_nlp_constraints_model_set(self.nlp_config, \\ self.nlp_dims, self.nlp_in, stage, field, value_data_p) elif field_ in", "0 else: dims.nu = casadi_length(model.u) # nz if is_empty(model.z): dims.nz", "np.sum(opts.time_steps) if (tf - opts.tf) / tf > 1e-15: raise", "acados_ocp.cost.cost_type == 'NONLINEAR_LS': template_dir = 'c_generated_code/{}_cost/'.format(name) in_file = 'cost_y_fun.in.h' out_file", "out_file, template_dir, json_path) # terminal nonlinear cost function if acados_ocp.cost.cost_type_e", "raise Exception('inconsistent dimension ny, regarding W, Vx, Vu.' + \\", "0: raise Exception('inconsistent dimension: Vu should have nu columns.') if", "= cost.W.shape[0] if is_empty(model.cost_y_expr) and ny != 0: raise Exception('inconsistent", "elif (not is_empty(opts.time_steps)) and (not is_empty(opts.shooting_nodes)): Exception('Please provide either time_steps", "self.nlp_dims, self.nlp_out, stage_, field) if value_.shape[0] != dims: msg =", "'BGH' and acados_ocp.dims.nh_e > 0: template_dir = 'c_generated_code/{}_constraints/'.format(name) in_file =", "# terminal if cost.cost_type_e == 'LINEAR_LS': ny_e = cost.W_e.shape[0] if", "with the acados ocp solver C object \"\"\" def __init__(self,", "value_data = cast(value_.ctypes.data, POINTER(c_double)) self.shared_lib.acados_update_params(stage, value_data, value_.shape[0]) else: if field_", "idxsphi, lsphi.') if is_empty(constraints.usphi): constraints.usphi = np.zeros((nsphi,)) elif constraints.usphi.shape[0] !=", "regarding idxsg_e, usg_e.') dims.nsg_e = nsg_e nsphi_e = constraints.idxsphi_e.shape[0] if", "ocp_render_templates(acados_ocp, json_file) ## Compile solver os.chdir('c_generated_code') os.system('make clean_ocp_shared_lib') os.system('make ocp_shared_lib')", "constraints # initial if (constraints.lbx_0 == [] and constraints.ubx_0 ==", "column vectors!') dims.nbx_0 = constraints.lbx_0.size if all(constraints.lbx_0 == constraints.ubx_0): dims.nbxe_0", "= cost.zu_e.shape[0] if wrong_field != \"\": raise Exception(f'Inconsistent size for", "\"Zl_e\" dim = cost.Zl_e.shape[0] elif cost.Zu_e.shape[0] != ns_e: wrong_field =", "!= ny: raise Exception('inconsistent dimension ny, regarding W, Vx, Vu,", "out_file, template_dir, json_path) in_file = 'acados_sim_solver.in.c' out_file = 'acados_sim_solver_{}.c'.format(name) render_template(in_file,", "Exception('inconsistent dimension ny, regarding W, Vx, Vu, Vz.' + \\", "raise Exception('AcadosOcpSolver.get_stats(): {} is not a valid argument.\\ \\n Possible", "for field \"{}\" with dimension {} (you have {})'.format(field_, tuple(dims),", "regarding idxsbx_e, lsbx_e.') if is_empty(constraints.usbx_e): constraints.usbx_e = np.zeros((nsbx_e,)) elif constraints.usbx_e.shape[0]", "NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF", "= 'cost_y_e_fun.in.h' out_file = '{}_cost_y_e_fun.h'.format(name) render_template(in_file, out_file, template_dir, json_path) #", "dimension nbx, regarding idxbx, ubx, lbx.') else: dims.nbx = nbx", "set options of the solver: Parameters: :param field_: string, e.g.", "CasadiMeta, Function, SX from copy import deepcopy from .generate_c_code_explicit_ode import", "> 0: generate_c_code_constraint(model, model.name, False, opts) if acados_ocp.dims.nphi_e > 0", "= opts.shooting_nodes[i+1] - opts.shooting_nodes[i] opts.time_steps = time_steps elif (not is_empty(opts.time_steps))", "= dims.nbx_0 # path nbx = constraints.idxbx.shape[0] if constraints.ubx.shape[0] !=", "{} is an invalid argument.\\ \\n Possible values are {}.", "in ['sqp_iter', 'stat_m', 'stat_n']: out = np.ascontiguousarray(np.zeros((1,)), dtype=np.int64) out_data =", "['x', 'u', 'z', 'pi', 'lam', 't', 'sl', 'su',] .. note::", "json_file='acados_ocp_nlp.json'): # Load acados_ocp_nlp structure description ocp_layout = get_ocp_nlp_layout() #", "= np.ascontiguousarray( np.zeros( (stat_n[0]+1, min_size[0]) ), dtype=np.float64) out_data = cast(out.ctypes.data,", "acados_ocp.model # make dims consistent make_ocp_dims_consistent(acados_ocp) if acados_ocp.solver_options.integrator_type == 'GNSF':", "dims.nr_e = casadi_length(model.con_r_expr_e) # Slack dimensions nsbx = constraints.idxsbx.shape[0] if", "import AcadosOcp from .acados_model import acados_model_strip_casadi_symbolics from .utils import is_column,", "2 for SQP-RTI-type solvers') if self.acados_ocp.solver_options.nlp_solver_type != 'SQP_RTI' and value_", "'main_{}.c'.format(name) render_template(in_file, out_file, template_dir, json_path) in_file = 'acados_solver.in.c' out_file =", "c_void_p, c_char_p, c_void_p] self.shared_lib.ocp_nlp_get(self.nlp_config, self.nlp_solver, field, out_data) return out #", "solver os.chdir('c_generated_code') os.system('make clean_ocp_shared_lib') os.system('make ocp_shared_lib') os.chdir('..') self.shared_lib_name = 'c_generated_code/libacados_ocp_solver_'", "= \\ [c_void_p, c_void_p, c_void_p, c_int, c_char_p, c_void_p] self.shared_lib.ocp_nlp_constraints_model_set(self.nlp_config, \\", "= nsg_e nsphi_e = constraints.idxsphi_e.shape[0] if is_empty(constraints.lsphi_e): constraints.lsphi_e = np.zeros((nsphi_e,))", "field = field_ field = field.encode('utf-8') stage = c_int(stage_) #", "dims.nx and ny_e != 0: raise Exception('inconsistent dimension: Vx_e should", "if (field_ not in fields): raise Exception('AcadosOcpSolver.get_stats(): {} is not", "dimension ny, regarding W, Vx, Vu, Vz.' + \\ f'\\nGot", "ocp_nlp_layout = json.load(f) return ocp_nlp_layout def ocp_formulation_json_dump(acados_ocp, json_file='acados_ocp_nlp.json'): # Load", "function if acados_ocp.constraints.constr_type == 'BGP' and acados_ocp.dims.nphi > 0: #", "solver C object \"\"\" def __init__(self, acados_ocp, json_file='acados_ocp_nlp.json'): self.solver_created =", "c_char_p, c_void_p] self.shared_lib.ocp_nlp_cost_model_set(self.nlp_config, \\ self.nlp_dims, self.nlp_in, stage, field, value_data_p) elif", "ush usphi] .. note:: pi: multipliers for dynamics equality constraints", "last solver call: :param field_: string in ['statistics', 'time_tot', 'time_lin',", "= \\ [c_void_p, c_void_p, c_void_p, c_int, c_char_p, c_void_p] self.shared_lib.ocp_nlp_out_set(self.nlp_config, \\", "np_array_to_list, make_model_consistent,\\ set_up_imported_gnsf_model def make_ocp_dims_consistent(acados_ocp): dims = acados_ocp.dims cost =", "if is_empty(constraints.lsg_e): constraints.lsg_e = np.zeros((nsg_e,)) elif constraints.lsg_e.shape[0] != nsg_e: raise", "idxsphi_e, lsphi_e.') if is_empty(constraints.usphi_e): constraints.usphi_e = np.zeros((nsphi_e,)) elif constraints.usphi_e.shape[0] !=", "DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE", "solution) \\n sl: slack variables of soft lower inequality constraints", "regarding shooting_nodes.') time_steps = np.zeros((dims.N,)) for i in range(dims.N): time_steps[i]", "= acados_model_strip_casadi_symbolics(ocp_nlp_dict['model']) # strip shooting_nodes ocp_nlp_dict['solver_options'].pop('shooting_nodes', None) dims_dict = acados_class2dict(acados_ocp.dims)", "raise Exception('inconsistent dimension nsbu, regarding idxsbu, usbu.') dims.nsbu = nsbu", "f' = tf != sum(opts.time_steps) = {tf}.') def get_ocp_nlp_layout(): current_module", "template_dir = 'c_generated_code/{}_constraints/'.format(name) in_file = 'phi_constraint.in.h' out_file = '{}_phi_constraint.h'.format(name) render_template(in_file,", "# The 2-Clause BSD License # # Redistribution and use", "# get self.shared_lib = CDLL(self.shared_lib_name) self.shared_lib.acados_create() self.solver_created = True self.shared_lib.acados_get_nlp_opts.restype", "# cpu time qp solution 'time_qp_solver_call', # cpu time inside", "= get_ocp_nlp_layout() with open(json_file, 'r') as f: ocp_nlp_json = json.load(f)", "out_file, template_dir, json_path) in_file = 'make_sfun.in.m' out_file = 'make_sfun.m' render_template(in_file,", "= field_ field = field.encode('utf-8') if field_ in string_fields: self.shared_lib.ocp_nlp_solver_opts_set.argtypes", "ny_e: regarding W_e, cost_y_expr_e.') elif casadi_length(model.cost_y_expr_e) != ny_e: raise Exception('inconsistent", "template_dir, json_path) # external cost if acados_ocp.cost.cost_type == 'EXTERNAL': template_dir", "= c_void_p self.nlp_out = self.shared_lib.acados_get_nlp_out() self.shared_lib.acados_get_nlp_in.restype = c_void_p self.nlp_in =", "ns: wrong_field = \"zu\" dim = cost.zu.shape[0] if wrong_field !=", "-*- coding: future_fstrings -*- # # Copyright 2019 <NAME>, <NAME>,", "field_, value_): cost_fields = ['y_ref', 'yref'] constraints_fields = ['lbx', 'ubx',", "nsbx = constraints.idxsbx.shape[0] if is_empty(constraints.lsbx): constraints.lsbx = np.zeros((nsbx,)) elif constraints.lsbx.shape[0]", "nsbx_e, regarding idxsbx_e, lsbx_e.') if is_empty(constraints.usbx_e): constraints.usbx_e = np.zeros((nsbx_e,)) elif", "ng, regarding lg, ug, C, D.') else: dims.ng = ng", "use cost_set, constraints_set def set(self, stage_, field_, value_): cost_fields =", "constraints.idxsbx.shape[0] if is_empty(constraints.lsbx): constraints.lsbx = np.zeros((nsbx,)) elif constraints.lsbx.shape[0] != nsbx:", "'BGP' and acados_ocp.dims.nphi_e > 0: # terminal constraints on outer", "= min([stat_m, sqp_iter+1]) out = np.ascontiguousarray( np.zeros( (stat_n[0]+1, min_size[0]) ),", "# Load acados_ocp_nlp structure description ocp_layout = get_ocp_nlp_layout() with open(json_file,", "call 'time_lin', # cpu time for linearization 'time_sim', # cpu", "have nx columns.') if cost.Vu.shape[1] != dims.nu and ny !=", "if is_empty(model.con_r_expr): raise Exception('convex over nonlinear constraints: con_r_expr but con_phi_expr", "stage_: integer corresponding to shooting node :param field_: string, e.g.", "dims_data) value_shape = value_.shape if len(value_shape) == 1: value_shape =", "render templates ocp_render_templates(acados_ocp, json_file) ## Compile solver os.chdir('c_generated_code') os.system('make clean_ocp_shared_lib')", "ny or cost.Vu.shape[0] != ny: raise Exception('inconsistent dimension ny, regarding", "= cost.Zu_e.shape[0] elif cost.zl_e.shape[0] != ns_e: wrong_field = \"zl_e\" dim", "constraints.usg_e.shape[0] != nsg_e: raise Exception('inconsistent dimension nsg_e, regarding idxsg_e, usg_e.')", "= constraints.idxsbx.shape[0] if is_empty(constraints.lsbx): constraints.lsbx = np.zeros((nsbx,)) elif constraints.lsbx.shape[0] !=", "nsbx + nsbu + nsh + nsg + nsphi wrong_field", "ny: regarding W, cost_y_expr.') if cost.yref.shape[0] != ny: raise Exception('inconsistent", "render_template(in_file, out_file, template_dir, json_path) in_file = 'acados_sim_solver.in.h' out_file = 'acados_sim_solver_{}.h'.format(name)", "self.shared_lib.ocp_nlp_out_get(self.nlp_config, \\ self.nlp_dims, self.nlp_out, stage_, field, out_data) elif field_ in", "self.nlp_dims, self.nlp_out, stage_, field, out_data) elif field_ in mem_fields: self.shared_lib.ocp_nlp_get_at_stage.argtypes", "value_.astype(float) field = field_ field = field.encode('utf-8') stage = c_int(stage_)", "+ \\ f'\\nGot W[{cost.W.shape}], Vx[{cost.Vx.shape}], Vu[{cost.Vu.shape}]\\n') if dims.nz != 0", "dims_dict = acados_class2dict(acados_ocp.dims) ocp_check_against_layout(ocp_nlp_dict, dims_dict) with open(json_file, 'w') as f:", "c_void_p, c_int, c_char_p, c_void_p] self.shared_lib.ocp_nlp_get_at_stage(self.nlp_config, \\ self.nlp_dims, self.nlp_solver, stage_, field,", "converting the QP) 'time_qp_xcond', 'time_reg', # cpu time regularization 'sqp_iter',", "0, 1, 2 for SQP-RTI-type solvers') if self.acados_ocp.solver_options.nlp_solver_type != 'SQP_RTI'", "c_int, c_char_p, POINTER(c_int)] self.shared_lib.ocp_nlp_constraint_dims_get_from_attr.restype = c_int dims = np.ascontiguousarray(np.zeros((2,)), dtype=np.intc)", "format_class_dict(ocp_nlp_dict) # strip symbolics ocp_nlp_dict['model'] = acados_model_strip_casadi_symbolics(ocp_nlp_dict['model']) # strip shooting_nodes", "'stat_n']: out = np.ascontiguousarray(np.zeros((1,)), dtype=np.int64) out_data = cast(out.ctypes.data, POINTER(c_int64)) elif", "np.zeros((nsbx_e,)) elif constraints.usbx_e.shape[0] != nsbx_e: raise Exception('inconsistent dimension nsbx_e, regarding", "nsg_e, regarding idxsg_e, usg_e.') dims.nsg_e = nsg_e nsphi_e = constraints.idxsphi_e.shape[0]", "'W', 'ext_cost_num_hess' :param value_: of appropriate size \"\"\" # cast", "# implicit model -- generate C code opts = dict(generate_hess=1)", "= ny_e ## constraints # initial if (constraints.lbx_0 == []", "= sys.modules[__name__] acados_path = os.path.dirname(current_module.__file__) with open(acados_path + '/acados_layout.json', 'r')", "deepcopy from .generate_c_code_explicit_ode import generate_c_code_explicit_ode from .generate_c_code_implicit_ode import generate_c_code_implicit_ode from", "+ f'With nsbx = {nsbx}, nsbu = {nsbu}, nsg =", "with open(json_file, 'w') as f: json.dump(ocp_nlp_dict, f, default=np_array_to_list, indent=4, sort_keys=True)", "json_path) # terminal constraints on convex over nonlinear function if", "lh lphi ubu ubx ug uh uphi; \\n lsbu lsbx", "raise Exception('inconsistent dimension nh_e, regarding lh_e, uh_e, con_h_expr_e.') else: dims.nh_e", "if not isinstance(value_, str): raise Exception('solver option {} must be", "lsbx_e.') if is_empty(constraints.usbx_e): constraints.usbx_e = np.zeros((nsbx_e,)) elif constraints.usbx_e.shape[0] != nsbx_e:", "sqp_iter = self.get_stats(\"sqp_iter\") stat_m = self.get_stats(\"stat_m\") stat_n = self.get_stats(\"stat_n\") min_size", "Vu.' + \\ f'\\nGot W[{cost.W.shape}], Vx[{cost.Vx.shape}], Vu[{cost.Vu.shape}]\\n') if dims.nz !=", "generate C code generate_c_code_explicit_ode(model) elif acados_ocp.solver_options.integrator_type == 'IRK': # implicit", "Exception('inconsistent dimension: Vx should have nx columns.') if cost.Vu.shape[1] !=", "dimension for field \"{}\" '.format(field_) msg += 'with dimension {}", "cast(dims.ctypes.data, POINTER(c_int)) self.shared_lib.ocp_nlp_constraint_dims_get_from_attr(self.nlp_config, \\ self.nlp_dims, self.nlp_out, stage_, field, dims_data) value_shape", "nonempty') else: dims.nr_e = casadi_length(model.con_r_expr_e) # Slack dimensions nsbx =", "solver (without converting the QP) 'time_qp_xcond', 'time_reg', # cpu time", "following conditions are met: # # 1. Redistributions of source", "'lbu', 'ubu'] out_fields = ['x', 'u', 'pi', 'lam', 't'] #", "Exception('convex over nonlinear constraints: con_r_expr_e but con_phi_expr_e is nonempty') else:", "'NONLINEAR_LS': template_dir = 'c_generated_code/{}_cost/'.format(name) in_file = 'cost_y_e_fun.in.h' out_file = '{}_cost_y_e_fun.h'.format(name)", "<NAME>, <NAME>, <NAME>, # <NAME>, <NAME>, <NAME>, <NAME>, <NAME> #", "acados_ocp.dims cost = acados_ocp.cost constraints = acados_ocp.constraints model = acados_ocp.model", "np.ones((dims.N,)) elif not is_empty(opts.shooting_nodes): if np.shape(opts.shooting_nodes)[0] != dims.N+1: raise Exception('inconsistent", "(not is_empty(opts.time_steps)) and (not is_empty(opts.shooting_nodes)): Exception('Please provide either time_steps or", "> 0 or acados_ocp.dims.nh_e > 0: generate_c_code_constraint(model, model.name, True, opts)", "out_fields = ['x', 'u', 'pi', 'lam', 't'] # cast value_", "acados_ocp_nlp structure description ocp_layout = get_ocp_nlp_layout() with open(json_file, 'r') as", "== 'BGH' and acados_ocp.dims.nh > 0: template_dir = 'c_generated_code/{}_constraints/'.format(name) in_file", "Load acados_ocp_nlp structure description ocp_layout = get_ocp_nlp_layout() # Copy input", "dtype=np.float64) out_data = cast(out.ctypes.data, POINTER(c_double)) else: out = np.ascontiguousarray(np.zeros((1,)), dtype=np.float64)", "nsphi_e wrong_field = \"\" if cost.Zl_e.shape[0] != ns_e: wrong_field =", "elif field_ == 'statistics': sqp_iter = self.get_stats(\"sqp_iter\") stat_m = self.get_stats(\"stat_m\")", "must be of type int. You have {}.'.format(field_, type(value_))) else:", "from .generate_c_code_constraint import generate_c_code_constraint from .generate_c_code_nls_cost import generate_c_code_nls_cost from .generate_c_code_external_cost", "nsphi_e: raise Exception('inconsistent dimension nsphi_e, regarding idxsphi_e, usphi_e.') dims.nsphi_e =", "if is_column(model.x): dims.nx = casadi_length(model.x) else: raise Exception('model.x should be", "lam: multipliers for inequalities \\n t: slack variables corresponding to", "'statistics': sqp_iter = self.get_stats(\"sqp_iter\") stat_m = self.get_stats(\"stat_m\") stat_n = self.get_stats(\"stat_n\")", "constraints = acados_ocp.constraints model = acados_ocp.model opts = acados_ocp.solver_options #", "POINTER(c_double)) if (field_ in out_fields): self.shared_lib.ocp_nlp_out_get.argtypes = \\ [c_void_p, c_void_p,", "if constraints.ubx_e.shape[0] != nbx_e or constraints.lbx_e.shape[0] != nbx_e: raise Exception('inconsistent", "opts.tf / dims.N * np.ones((dims.N,)) elif not is_empty(opts.shooting_nodes): if np.shape(opts.shooting_nodes)[0]", "CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN #", "casadi_length(model.cost_y_expr_e) != ny_e: raise Exception('inconsistent dimension ny_e: regarding W_e, cost_y_expr_e.')", "e.g. 'yref', 'W', 'ext_cost_num_hess' :param value_: of appropriate size \"\"\"", "True, opts) # dummy matrices if not acados_ocp.cost.cost_type == 'LINEAR_LS':", "dict attributes if not isinstance(v, dict): continue # setattr(ocp_nlp, acados_struct,", "msg = 'AcadosOcpSolver.set(): mismatching dimension for field \"{}\" '.format(field_) msg", "constraints.lsphi_e = np.zeros((nsphi_e,)) elif constraints.lsphi_e.shape[0] != nsphi_e: raise Exception('inconsistent dimension", "AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT,", "is_empty(constraints.usbx): constraints.usbx = np.zeros((nsbx,)) elif constraints.usbx.shape[0] != nsbx: raise Exception('inconsistent", "parameters separately if field_ is 'p': self.shared_lib.acados_update_params.argtypes = [c_int, POINTER(c_double)]", "constraints.C_e.shape[0] != ng_e: raise Exception('inconsistent dimension ng_e, regarding_e lg_e, ug_e,", "value_.shape[0] != dims: msg = 'AcadosOcpSolver.set(): mismatching dimension for field", "ubx_0 must be column vectors!') dims.nbx_0 = constraints.lbx_0.size if all(constraints.lbx_0", "elif casadi_length(model.cost_y_expr_e) != ny_e: raise Exception('inconsistent dimension ny_e: regarding W_e,", "= format_class_dict(ocp_nlp_dict) # strip symbolics ocp_nlp_dict['model'] = acados_model_strip_casadi_symbolics(ocp_nlp_dict['model']) # strip", "as f: json.dump(ocp_nlp_dict, f, default=np_array_to_list, indent=4, sort_keys=True) def ocp_formulation_json_load(json_file='acados_ocp_nlp.json'): #", "\\ self.nlp_dims, self.nlp_solver, stage_, field, out_data) return out def print_statistics(self):", "self.nlp_opts = self.shared_lib.acados_get_nlp_opts() self.shared_lib.acados_get_nlp_dims.restype = c_void_p self.nlp_dims = self.shared_lib.acados_get_nlp_dims() self.shared_lib.acados_get_nlp_config.restype", ":param stage_: integer corresponding to shooting node :param field_: string,", "!= nbx_e or constraints.lbx_e.shape[0] != nbx_e: raise Exception('inconsistent dimension nbx_e,", "ng_e = constraints.lg_e.shape[0] if constraints.ug_e.shape[0] != ng_e or constraints.C_e.shape[0] !=", "'r') as f: ocp_nlp_json = json.load(f) ocp_nlp_dict = json2dict(ocp_nlp_json, ocp_nlp_json['dims'])", "if acados_ocp.cost.cost_type == 'NONLINEAR_LS': generate_c_code_nls_cost(model, model.name, False) elif acados_ocp.cost.cost_type ==", "dims_data = cast(dims.ctypes.data, POINTER(c_int)) self.shared_lib.ocp_nlp_cost_dims_get_from_attr(self.nlp_config, \\ self.nlp_dims, self.nlp_out, stage_, field,", "'time_qp_solver_call', 'time_reg', 'sqp_iter'] \"\"\" fields = ['time_tot', # total cpu", "self.shared_lib.ocp_nlp_constraint_dims_get_from_attr.restype = c_int dims = np.ascontiguousarray(np.zeros((2,)), dtype=np.intc) dims_data = cast(dims.ctypes.data,", "regarding W_e, yref_e.') dims.ny_e = ny_e elif cost.cost_type_e == 'NONLINEAR_LS':", "out_file, template_dir, json_path) # terminal nonlinear constraints if acados_ocp.constraints.constr_type_e ==", "!= nh_e: raise Exception('inconsistent dimension nh_e, regarding lh_e, uh_e, con_h_expr_e.')", "generate C code opts = dict(generate_hess=1) generate_c_code_implicit_ode(model, opts) elif acados_ocp.solver_options.integrator_type", "SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS #", "documentation # and/or other materials provided with the distribution. #", "Exception('inconsistent dimension nsh_e, regarding idxsh_e, lsh_e.') if is_empty(constraints.ush_e): constraints.ush_e =", "not acados_ocp.cost.cost_type == 'LINEAR_LS': acados_ocp.cost.Vx = np.zeros((acados_ocp.dims.ny, acados_ocp.dims.nx)) acados_ocp.cost.Vu =", "template_dir, json_path) class AcadosOcpSolver: \"\"\" class to interact with the", "cpu time qp solution 'time_qp_solver_call', # cpu time inside qp", "'step_length' :param value_: of type int, float \"\"\" int_fields =", "render_template(in_file, out_file, template_dir, json_path) # terminal nonlinear cost function if", "if acados_ocp.dims.nphi > 0 or acados_ocp.dims.nh > 0: generate_c_code_constraint(model, model.name,", "lsbx lsg lsh lsphi usbu usbx usg ush usphi] ..", "source code must retain the above copyright notice, # this", ".. note:: pi: multipliers for dynamics equality constraints \\n lam:", "attributes dictionaries ocp_nlp_dict[acados_struct]=dict(getattr(acados_ocp, acados_struct).__dict__) ocp_nlp_dict = format_class_dict(ocp_nlp_dict) # strip symbolics", "generate_c_code_implicit_ode(model, opts) elif acados_ocp.solver_options.integrator_type == 'GNSF': generate_c_code_gnsf(model) else: raise Exception(\"ocp_generate_external_functions:", "field.encode('utf-8') stage = c_int(stage_) # treat parameters separately if field_", "f'With nsbx_e = {nsbx_e}, nsg_e = {nsg_e}, nsh_e = {nsh_e},", "== 'LINEAR_LS': ny = cost.W.shape[0] if cost.Vx.shape[0] != ny or", "= 'external_cost.in.h' out_file = '{}_external_cost.h'.format(name) render_template(in_file, out_file, template_dir, json_path) #", "field_ field = field.encode('utf-8') if field_ in string_fields: self.shared_lib.ocp_nlp_solver_opts_set.argtypes =", "idxsg_e, lsg_e.') if is_empty(constraints.usg_e): constraints.usg_e = np.zeros((nsg_e,)) elif constraints.usg_e.shape[0] !=", "elif acados_ocp.cost.cost_type == 'EXTERNAL': generate_c_code_external_cost(model, False) if acados_ocp.cost.cost_type_e == 'NONLINEAR_LS':", "else: dims.nu = casadi_length(model.u) # nz if is_empty(model.z): dims.nz =", "nsg ns = nsbx + nsbu + nsh + nsg", "this function should not be used anymore, better use cost_set,", "= np.zeros((nsh,)) elif constraints.ush.shape[0] != nsh: raise Exception('inconsistent dimension nsh,", "inequality constraints \\n \"\"\" out_fields = ['x', 'u', 'z', 'pi',", "is 'p': self.shared_lib.acados_update_params.argtypes = [c_int, POINTER(c_double)] self.shared_lib.acados_update_params.restype = c_int value_data", "field_: string, e.g. 'lbx' :param value_: of appropriate size \"\"\"", "W[{cost.W.shape}], Vx[{cost.Vx.shape}], Vu[{cost.Vu.shape}]\\n') if dims.nz != 0 and cost.Vz.shape[0] !=", "= value_.shape if len(value_shape) == 1: value_shape = (value_shape[0], 0)", "numpy as np from ctypes import * from casadi import", "Exception('inconsistent dimension nbx, regarding idxbx, ubx, lbx.') else: dims.nbx =", "field_ in cost_fields: self.shared_lib.ocp_nlp_cost_model_set.argtypes = \\ [c_void_p, c_void_p, c_void_p, c_int,", "template_dir, json_path) in_file = 'acados_sim_solver.in.c' out_file = 'acados_sim_solver_{}.c'.format(name) render_template(in_file, out_file,", "['globalization'] if field_ in int_fields: if not isinstance(value_, int): raise", "if (field_ in out_fields): self.shared_lib.ocp_nlp_out_get.argtypes = \\ [c_void_p, c_void_p, c_void_p,", "POINTER(c_double)) else: out = np.ascontiguousarray(np.zeros((1,)), dtype=np.float64) out_data = cast(out.ctypes.data, POINTER(c_double))", "Exception('inconsistent dimension nsbx, regarding idxsbx, lsbx.') if is_empty(constraints.usbx): constraints.usbx =", "= casadi_length(model.con_r_expr) # terminal nbx_e = constraints.idxbx_e.shape[0] if constraints.ubx_e.shape[0] !=", "nsh: raise Exception('inconsistent dimension nsh, regarding idxsh, lsh.') if is_empty(constraints.ush):", "0: raise Exception('inconsistent dimension ny_e: regarding W_e, cost_y_expr_e.') elif casadi_length(model.cost_y_expr_e)", "for acados_struct, v in ocp_layout.items(): # skip non dict attributes", "if not acados_ocp.cost.cost_type_e == 'LINEAR_LS': acados_ocp.cost.Vx_e = np.zeros((acados_ocp.dims.ny_e, acados_ocp.dims.nx)) if", "self.acados_ocp.solver_options.nlp_solver_type == 'SQP': print('\\niter\\tres_stat\\tres_eq\\t\\tres_ineq\\tres_comp\\tqp_stat\\tqp_iter') if stat.shape[0]>7: print('\\tqp_res_stat\\tqp_res_eq\\tqp_res_ineq\\tqp_res_comp') for jj in", "= field_ field = field.encode('utf-8') if (field_ not in fields):", "for SQP-type solvers') field = field_ field = field.encode('utf-8') if", "The 2-Clause BSD License # # Redistribution and use in", "nx columns.') if cost.Vu.shape[1] != dims.nu and ny != 0:", "strip shooting_nodes ocp_nlp_dict['solver_options'].pop('shooting_nodes', None) dims_dict = acados_class2dict(acados_ocp.dims) ocp_check_against_layout(ocp_nlp_dict, dims_dict) with", "IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR", "<NAME>, <NAME>, # <NAME>, <NAME>, <NAME>, <NAME>, <NAME> # #", "of conditions and the following disclaimer. # # 2. Redistributions", "lsbx.') if is_empty(constraints.usbx): constraints.usbx = np.zeros((nsbx,)) elif constraints.usbx.shape[0] != nsbx:", "raise Exception('inconsistent dimension nsh, regarding idxsh, ush.') dims.nsh = nsh", "string in ['statistics', 'time_tot', 'time_lin', 'time_sim', 'time_sim_ad', 'time_sim_la', 'time_qp', 'time_qp_solver_call',", "c_void_p, c_void_p, c_int, c_char_p, POINTER(c_int)] self.shared_lib.ocp_nlp_constraint_dims_get_from_attr.restype = c_int dims =", "continue acados_attribute = getattr(acados_ocp, acados_struct) acados_attribute.__dict__ = ocp_nlp_dict[acados_struct] setattr(acados_ocp, acados_struct,", "= 'acados_solver_{}.h'.format(name) render_template(in_file, out_file, template_dir, json_path) in_file = 'Makefile.in' out_file", "get the last solution of the solver: :param stage: integer", "constraints.idxsh_e.shape[0] if is_empty(constraints.lsh_e): constraints.lsh_e = np.zeros((nsh_e,)) elif constraints.lsh_e.shape[0] != nsh_e:", "with the distribution. # # THIS SOFTWARE IS PROVIDED BY", "constraints.usphi.shape[0] != nsphi: raise Exception('inconsistent dimension nsphi, regarding idxsphi, usphi.')", "con_h_expr_e.') else: dims.nh_e = nh_e if is_empty(model.con_phi_expr_e): dims.nphi_e = 0", "nh or constraints.lh.shape[0] != nh: raise Exception('inconsistent dimension nh, regarding", "in range(stat.shape[1]): print('{:d}\\t{:d}\\t{:d}'.format( int(stat[0][jj]), int(stat[1][jj]), int(stat[2][jj]))) if stat.shape[0]>3: print('\\t{:e}\\t{:e}\\t{:e}\\t{:e}'.format( \\", "= cast(out.ctypes.data, POINTER(c_int64)) elif field_ == 'statistics': sqp_iter = self.get_stats(\"sqp_iter\")", "PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" #", "(value_shape[0], 0) if value_shape != tuple(dims): raise Exception('AcadosOcpSolver.constraints_set(): mismatching dimension'", "0) if value_shape != tuple(dims): raise Exception('AcadosOcpSolver.constraints_set(): mismatching dimension' \\", "and acados_ocp.dims.nh > 0: template_dir = 'c_generated_code/{}_constraints/'.format(name) in_file = 'h_constraint.in.h'", "nsphi_e = {nsphi_e}') dims.ns_e = ns_e # discretization if is_empty(opts.time_steps)", "'ubu'] out_fields = ['x', 'u', 'pi', 'lam', 't'] # cast", "'NONLINEAR_LS': ny = cost.W.shape[0] if is_empty(model.cost_y_expr) and ny != 0:", "elif constraints.usg_e.shape[0] != nsg_e: raise Exception('inconsistent dimension nsg_e, regarding idxsg_e,", "PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY", "TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY", "constraints.ubx_0 == []): dims.nbx_0 = 0 else: this_shape = constraints.lbx_0.shape", "!= 0: raise Exception('inconsistent dimension: Vx should have nx columns.')", "regarding idxsh, ush.') dims.nsh = nsh nsphi = constraints.idxsphi.shape[0] if", "in_file = 'main.in.c' out_file = 'main_{}.c'.format(name) render_template(in_file, out_file, template_dir, json_path)", "if field_ == 'rti_phase': if value_ < 0 or value_", "self.shared_lib.ocp_nlp_cost_dims_get_from_attr(self.nlp_config, \\ self.nlp_dims, self.nlp_out, stage_, field, dims_data) value_shape = value_.shape", "options of the solver: Parameters: :param field_: string, e.g. 'print_level',", "constraints.usbx = np.zeros((nsbx,)) elif constraints.usbx.shape[0] != nsbx: raise Exception('inconsistent dimension", "time for linearization 'time_sim', # cpu time for integrator 'time_sim_ad',", "constraints.lbx.shape[0] != nbx: raise Exception('inconsistent dimension nbx, regarding idxbx, ubx,", "in source and binary forms, with or without # modification,", "W[{cost.W.shape}], Vx[{cost.Vx.shape}], Vu[{cost.Vu.shape}], Vz[{cost.Vz.shape}]\\n') if cost.Vx.shape[1] != dims.nx and ny", "# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,", "raise Exception('inconsistent dimension ny: regarding W, cost_y_expr.') if cost.yref.shape[0] !=", "A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL", "and parameter_values.') ## cost # path if cost.cost_type == 'LINEAR_LS':", "AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED", "current_module = sys.modules[__name__] acados_path = os.path.dirname(current_module.__file__) with open(acados_path + '/acados_layout.json',", "permitted provided that the following conditions are met: # #", "field {wrong_field}, with dimension {dim}, \\n\\t'\\ + f'Detected ns =", "lbx lg lh lphi ubu ubx ug uh uphi; \\n", "\"\"\" solve the ocp with current input \"\"\" status =", "previous call 'time_lin', # cpu time for linearization 'time_sim', #", "name = acados_ocp.model.name # setting up loader and environment json_path", "ny_e: regarding W_e, cost_y_expr_e.') if cost.yref_e.shape[0] != ny_e: raise Exception('inconsistent", "!= tuple(dims): raise Exception('AcadosOcpSolver.cost_set(): mismatching dimension', \\ ' for field", "self.shared_lib.acados_free() del self.shared_lib # NOTE: DLL cannot be easily unloaded!!!", "from .acados_model import acados_model_strip_casadi_symbolics from .utils import is_column, is_empty, casadi_length,", "\\ [c_void_p, c_void_p, c_void_p, c_int, c_char_p, c_void_p] self.shared_lib.ocp_nlp_out_set(self.nlp_config, \\ self.nlp_dims,", "in the documentation # and/or other materials provided with the", "for integrator 'time_sim_ad', # cpu time for integrator contribution of", "nsg_e + nsphi_e wrong_field = \"\" if cost.Zl_e.shape[0] != ns_e:", "dimension', \\ ' for field \"{}\" with dimension {} (you", "constraints.usbx.shape[0] != nsbx: raise Exception('inconsistent dimension nsbx, regarding idxsbx, usbx.')", "casadi_length(model.con_phi_expr) if is_empty(model.con_r_expr): raise Exception('convex over nonlinear constraints: con_r_expr but", "Exception(msg) value_data = cast(value_.ctypes.data, POINTER(c_double)) value_data_p = cast((value_data), c_void_p) if", "field_ in constraints_fields: self.shared_lib.ocp_nlp_constraints_model_set.argtypes = \\ [c_void_p, c_void_p, c_void_p, c_int,", "c_char_p, POINTER(c_int)] self.shared_lib.ocp_nlp_cost_dims_get_from_attr.restype = c_int dims = np.ascontiguousarray(np.zeros((2,)), dtype=np.intc) dims_data", "{opts.tf}'\\ f' = tf != sum(opts.time_steps) = {tf}.') def get_ocp_nlp_layout():", "AcadosOcp object acados_ocp = AcadosOcp() # load class dict acados_ocp.__dict__", "information of the last solver call: :param field_: string in", "0: # terminal constraints on outer function template_dir = 'c_generated_code/{}_constraints/'.format(name)", "raise Exception('inconsistent dimension nsbx_e, regarding idxsbx_e, usbx_e.') dims.nsbx_e = nsbx_e", "else: raise Exception('model.x should be column vector!') # nu if", "isinstance(v, dict): continue acados_attribute = getattr(acados_ocp, acados_struct) acados_attribute.__dict__ = ocp_nlp_dict[acados_struct]", "acados_ocp, json_file='acados_ocp_nlp.json'): self.solver_created = False model = acados_ocp.model # make", "algebra 'time_qp', # cpu time qp solution 'time_qp_solver_call', # cpu", "render_template(in_file, out_file, template_dir, json_path) ## folder model template_dir = 'c_generated_code/{}_model/'.format(name)", "= 'c_generated_code/libacados_ocp_solver_' + model.name + '.so' # get self.shared_lib =", "constraints.lsg_e = np.zeros((nsg_e,)) elif constraints.lsg_e.shape[0] != nsg_e: raise Exception('inconsistent dimension", "== 'SQP': print('\\niter\\tres_stat\\tres_eq\\t\\tres_ineq\\tres_comp\\tqp_stat\\tqp_iter') if stat.shape[0]>7: print('\\tqp_res_stat\\tqp_res_eq\\tqp_res_ineq\\tqp_res_comp') for jj in range(stat.shape[1]):", "uh uphi; \\n lsbu lsbx lsg lsh lsphi usbu usbx", "acados_struct) acados_attribute.__dict__ = ocp_nlp_dict[acados_struct] setattr(acados_ocp, acados_struct, acados_attribute) return acados_ocp def", "mem_fields): raise Exception('AcadosOcpSolver.get(): {} is an invalid argument.\\ \\n Possible", "# nonlinear cost function if acados_ocp.cost.cost_type == 'NONLINEAR_LS': template_dir =", "Vx_e[{cost.Vx_e.shape}]') if cost.Vx_e.shape[1] != dims.nx and ny_e != 0: raise", "= np.zeros((acados_ocp.dims.ny_e, acados_ocp.dims.nx)) if acados_ocp.cost.cost_type == 'NONLINEAR_LS': generate_c_code_nls_cost(model, model.name, False)", "np.zeros((nsg_e,)) elif constraints.usg_e.shape[0] != nsg_e: raise Exception('inconsistent dimension nsg_e, regarding", "out = np.ascontiguousarray(np.zeros((1,)), dtype=np.float64) out_data = cast(out.ctypes.data, POINTER(c_double)) self.shared_lib.ocp_nlp_get.argtypes =", "# NOTE: DLL cannot be easily unloaded!!! # see https://stackoverflow.com/questions/359498/how-can-i-unload-a-dll-using-ctypes-in-python", "lphi ubu ubx ug uh uphi; \\n lsbu lsbx lsg", "code opts = dict(generate_hess=1) generate_c_code_implicit_ode(model, opts) elif acados_ocp.solver_options.integrator_type == 'GNSF':", "= acados_ocp.model opts = acados_ocp.solver_options # nx if is_column(model.x): dims.nx", "ubu ubx ug uh uphi; \\n lsbu lsbx lsg lsh", "2-Clause BSD License # # Redistribution and use in source", "\\ self.nlp_dims, self.nlp_in, stage, field, value_data_p) elif field_ in cost_fields:", "stat_m = self.get_stats(\"stat_m\") stat_n = self.get_stats(\"stat_n\") min_size = min([stat_m, sqp_iter+1])", "np.ascontiguousarray(np.zeros((1,)), dtype=np.float64) out_data = cast(out.ctypes.data, POINTER(c_double)) self.shared_lib.ocp_nlp_get.argtypes = [c_void_p, c_void_p,", "constraints.usbu = np.zeros((nsbu,)) elif constraints.usbu.shape[0] != nsbu: raise Exception('inconsistent dimension", "(field_ in out_fields): self.shared_lib.ocp_nlp_out_get.argtypes = \\ [c_void_p, c_void_p, c_void_p, c_int,", "THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF", "make one funciton with formatting for acados_struct, v in ocp_layout.items():", "json import numpy as np from ctypes import * from", "c_char_p, c_void_p] self.shared_lib.ocp_nlp_get_at_stage(self.nlp_config, \\ self.nlp_dims, self.nlp_solver, stage_, field, out_data) return", "make dims consistent make_ocp_dims_consistent(acados_ocp) if acados_ocp.solver_options.integrator_type == 'GNSF': set_up_imported_gnsf_model(acados_ocp) #", "must be of type float. You have {}.'.format(field_, type(value_))) else:", "constraints: con_r_expr_e but con_phi_expr_e is nonempty') else: dims.nr_e = casadi_length(model.con_r_expr_e)", "Exception('model.x should be column vector!') # nu if is_empty(model.u): dims.nu", "nonlinear function if acados_ocp.constraints.constr_type_e == 'BGP' and acados_ocp.dims.nphi_e > 0:", "load class dict acados_ocp.__dict__ = ocp_nlp_dict # laod class attributes", "is_empty(constraints.ush_e): constraints.ush_e = np.zeros((nsh_e,)) elif constraints.ush_e.shape[0] != nsh_e: raise Exception('inconsistent", "else: out = np.ascontiguousarray(np.zeros((1,)), dtype=np.float64) out_data = cast(out.ctypes.data, POINTER(c_double)) self.shared_lib.ocp_nlp_get.argtypes", "usbu.') dims.nsbu = nsbu nsh = constraints.idxsh.shape[0] if is_empty(constraints.lsh): constraints.lsh", "nh = casadi_length(model.con_h_expr) else: nh = 0 if constraints.uh.shape[0] !=", "ocp_generate_external_functions(acados_ocp, model) # dump to json ocp_formulation_json_dump(acados_ocp, json_file) # render", "raise Exception(msg) value_data = cast(value_.ctypes.data, POINTER(c_double)) value_data_p = cast((value_data), c_void_p)", "You have {}.'.format(field_, type(value_))) else: value_ctypes = value_.encode('utf-8') if field_", "with or without # modification, are permitted provided that the", "= '{}_cost_y_e_fun.h'.format(name) render_template(in_file, out_file, template_dir, json_path) # external cost if", "elif cost.Zu.shape[0] != ns: wrong_field = \"Zu\" dim = cost.Zu.shape[0]", "json_path) # nonlinear cost function if acados_ocp.cost.cost_type == 'NONLINEAR_LS': template_dir", "'pi', 'lam', 't', 'sl', 'su',] .. note:: regarding lam, t:", "{} is not a valid argument.\\ \\n Possible values are", "etc for acados_struct, v in ocp_layout.items(): # skip non dict", "cost_set, constraints_set def set(self, stage_, field_, value_): cost_fields = ['y_ref',", "numerical data in the constraint module of the solver: Parameters:", "elif self.acados_ocp.solver_options.nlp_solver_type == 'SQP_RTI': print('\\niter\\tqp_stat\\tqp_iter') if stat.shape[0]>3: print('\\tqp_res_stat\\tqp_res_eq\\tqp_res_ineq\\tqp_res_comp') for jj", "return out # Note: this function should not be used", "{})'.format(field_, tuple(dims), value_shape)) value_data = cast(value_.ctypes.data, POINTER(c_double)) value_data_p = cast((value_data),", "iterations 'statistics', # table with info about last iteration 'stat_m',", "True) elif acados_ocp.cost.cost_type_e == 'EXTERNAL': generate_c_code_external_cost(model, True) def ocp_render_templates(acados_ocp, json_file):", "'with dimension {} (you have {})'.format(dims, value_.shape[0]) raise Exception(msg) value_data", "HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT,", "1, 2 for SQP-RTI-type solvers') if self.acados_ocp.solver_options.nlp_solver_type != 'SQP_RTI' and", "= [c_void_p, c_void_p, c_char_p, c_void_p] self.shared_lib.ocp_nlp_get(self.nlp_config, self.nlp_solver, field, out_data) return", "linearization 'time_sim', # cpu time for integrator 'time_sim_ad', # cpu", "dimension nh, regarding lh, uh, con_h_expr.') else: dims.nh = nh", "# terminal ns_e = nsbx_e + nsh_e + nsg_e +", "'time_tot', 'time_lin', 'time_sim', 'time_sim_ad', 'time_sim_la', 'time_qp', 'time_qp_solver_call', 'time_reg', 'sqp_iter'] \"\"\"", "nbu ng = constraints.lg.shape[0] if constraints.ug.shape[0] != ng or constraints.C.shape[0]", "type float. You have {}.'.format(field_, type(value_))) else: value_ctypes = c_double(value_)", "stage, field, value_data_p) return def options_set(self, field_, value_): \"\"\" set", "= ['globalization'] if field_ in int_fields: if not isinstance(value_, int):", "not is_empty(model.con_h_expr_e): nh_e = casadi_length(model.con_h_expr_e) else: nh_e = 0 if", "if wrong_field != \"\": raise Exception(f'Inconsistent size for field {wrong_field},", "# cpu time regularization 'sqp_iter', # number of SQP iterations", "[c_void_p, c_void_p, c_void_p, c_int, c_char_p, c_void_p] self.shared_lib.ocp_nlp_cost_model_set(self.nlp_config, \\ self.nlp_dims, self.nlp_in,", "raise Exception('inconsistent dimension ny: regarding W, cost_y_expr.') elif casadi_length(model.cost_y_expr) !=", "# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR", "# this list of conditions and the following disclaimer in", "status def get(self, stage_, field_): \"\"\" get the last solution", "constraints.ush = np.zeros((nsh,)) elif constraints.ush.shape[0] != nsh: raise Exception('inconsistent dimension", "coding: future_fstrings -*- # # Copyright 2019 <NAME>, <NAME>, <NAME>,", "W_e[{cost.W_e.shape}], Vx_e[{cost.Vx_e.shape}]') if cost.Vx_e.shape[1] != dims.nx and ny_e != 0:", "ng_e, regarding_e lg_e, ug_e, C_e.') else: dims.ng_e = ng_e if", "loader and environment json_path = '{cwd}/{json_file}'.format( cwd=os.getcwd(), json_file=json_file) if not", "cost.W_e.shape[0] if is_empty(model.cost_y_expr_e) and ny_e != 0: raise Exception('inconsistent dimension", "ny_e: raise Exception('inconsistent dimension ny_e: regarding W_e, cost_y_expr_e.') if cost.yref_e.shape[0]", "other_shape = constraints.ubx_0.shape if not this_shape == other_shape: raise Exception('lbx_0,", "<NAME>, <NAME>, # <NAME>, <NAME>, <NAME>, <NAME>, # <NAME>, <NAME>,", "cpu time for integrator contribution of linear algebra 'time_qp', #", "elif constraints.usphi_e.shape[0] != nsphi_e: raise Exception('inconsistent dimension nsphi_e, regarding idxsphi_e,", "note:: regarding lam, t: \\n the inequalities are internally organized", "nbx = constraints.idxbx.shape[0] if constraints.ubx.shape[0] != nbx or constraints.lbx.shape[0] !=", "== 'NONLINEAR_LS': generate_c_code_nls_cost(model, model.name, True) elif acados_ocp.cost.cost_type_e == 'EXTERNAL': generate_c_code_external_cost(model,", "elif constraints.lsg.shape[0] != nsg: raise Exception('inconsistent dimension nsg, regarding idxsg,", ":param field_: string in ['statistics', 'time_tot', 'time_lin', 'time_sim', 'time_sim_ad', 'time_sim_la',", "is_empty(constraints.usbu): constraints.usbu = np.zeros((nsbu,)) elif constraints.usbu.shape[0] != nsbu: raise Exception('inconsistent", "['print_level', 'rti_phase', 'initialize_t_slacks'] double_fields = ['step_length'] string_fields = ['globalization'] if", "regarding idxsphi, usphi.') dims.nsphi = nsphi nsg = constraints.idxsg.shape[0] if", "'acados_solver_sfun.in.c' out_file = 'acados_solver_sfunction_{}.c'.format(name) render_template(in_file, out_file, template_dir, json_path) in_file =", "time for integrator contribution of linear algebra 'time_qp', # cpu", "integrator contribution of external function calls 'time_sim_la', # cpu time", "self.shared_lib.ocp_nlp_cost_model_set.argtypes = \\ [c_void_p, c_void_p, c_void_p, c_int, c_char_p, c_void_p] self.shared_lib.ocp_nlp_cost_model_set(self.nlp_config,", "render_template(in_file, out_file, template_dir, json_path) in_file = 'acados_solver_sfun.in.c' out_file = 'acados_solver_sfunction_{}.c'.format(name)", "else: dims.nbu = nbu ng = constraints.lg.shape[0] if constraints.ug.shape[0] !=", "POSSIBILITY OF SUCH DAMAGE.; # import sys, os, json import", "'time_reg', 'sqp_iter'] \"\"\" fields = ['time_tot', # total cpu time", "dims.nbx_e = nbx_e ng_e = constraints.lg_e.shape[0] if constraints.ug_e.shape[0] != ng_e", "Exception('AcadosOcpSolver.get_stats(): {} is not a valid argument.\\ \\n Possible values", "self.shared_lib.acados_update_params.restype = c_int value_data = cast(value_.ctypes.data, POINTER(c_double)) self.shared_lib.acados_update_params(stage, value_data, value_.shape[0])", "not os.path.exists(json_path): raise Exception('{} not found!'.format(json_path)) template_dir = 'c_generated_code/' ##", "def get_stats(self, field_): \"\"\" get the information of the last", "OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE", "= 'c_generated_code/' ## Render templates in_file = 'main.in.c' out_file =", "ocp_layout.items(): # skip non dict attributes if not isinstance(v, dict):", "out_file = 'acados_solver_sfunction_{}.c'.format(name) render_template(in_file, out_file, template_dir, json_path) in_file = 'make_sfun.in.m'", "as np from ctypes import * from casadi import CasadiMeta,", "isinstance(value_, str): raise Exception('solver option {} must be of type", "usg.') dims.nsg = nsg ns = nsbx + nsbu +", "lower inequality constraints \\n su: slack variables of soft upper", "dict attributes if not isinstance(v, dict): continue acados_attribute = getattr(acados_ocp,", "return acados_ocp def ocp_generate_external_functions(acados_ocp, model): model = make_model_consistent(model) if acados_ocp.solver_options.integrator_type", "{}. Exiting.'.format(field_, out_fields + mem_fields)) self.shared_lib.ocp_nlp_dims_get_from_attr.argtypes = \\ [c_void_p, c_void_p,", "'lbx' :param value_: of appropriate size \"\"\" # cast value_", "field_ is 'p': self.shared_lib.acados_update_params.argtypes = [c_int, POINTER(c_double)] self.shared_lib.acados_update_params.restype = c_int", "out_data = cast(out.ctypes.data, POINTER(c_double)) else: out = np.ascontiguousarray(np.zeros((1,)), dtype=np.float64) out_data", "are met: # # 1. Redistributions of source code must", "OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF", "else: dims.nz = casadi_length(model.z) # np if is_empty(model.p): dims.np =", "ny_e: raise Exception('inconsistent dimension ny_e: regarding W_e, cost_y_expr_e.' + \\", "nx columns.') if cost.yref_e.shape[0] != ny_e: raise Exception('inconsistent dimension: regarding", "if not is_empty(model.con_h_expr): nh = casadi_length(model.con_h_expr) else: nh = 0", "if is_empty(constraints.lsbx): constraints.lsbx = np.zeros((nsbx,)) elif constraints.lsbx.shape[0] != nsbx: raise", "ns_e = nsbx_e + nsh_e + nsg_e + nsphi_e wrong_field", "argument.\\ \\nPossible values are {}. Exiting.\".format(field, \\ constraints_fields + cost_fields", "= constraints.lg.shape[0] if constraints.ug.shape[0] != ng or constraints.C.shape[0] != ng", "inequalities (at the solution) \\n sl: slack variables of soft", "time for integrator contribution of external function calls 'time_sim_la', #", "# POSSIBILITY OF SUCH DAMAGE.; # import sys, os, json", "be used anymore, better use cost_set, constraints_set def set(self, stage_,", "in binary form must reproduce the above copyright notice, #", "= cast(dims.ctypes.data, POINTER(c_int)) self.shared_lib.ocp_nlp_constraint_dims_get_from_attr(self.nlp_config, \\ self.nlp_dims, self.nlp_out, stage_, field, dims_data)", "'yref'] constraints_fields = ['lbx', 'ubx', 'lbu', 'ubu'] out_fields = ['x',", "= casadi_length(model.z) # np if is_empty(model.p): dims.np = 0 else:", "solver call: :param field_: string in ['statistics', 'time_tot', 'time_lin', 'time_sim',", "len(value_shape) == 1: value_shape = (value_shape[0], 0) if value_shape !=", "binary forms, with or without # modification, are permitted provided", "self.nlp_out, stage_, field) out = np.ascontiguousarray(np.zeros((dims,)), dtype=np.float64) out_data = cast(out.ctypes.data,", "field_ in string_fields: if not isinstance(value_, str): raise Exception('solver option", "dimension nsh_e, regarding idxsh_e, ush_e.') dims.nsh_e = nsh_e nsg_e =", "make_ocp_dims_consistent(acados_ocp) if acados_ocp.solver_options.integrator_type == 'GNSF': set_up_imported_gnsf_model(acados_ocp) # set integrator time", "!= nh: raise Exception('inconsistent dimension nh, regarding lh, uh, con_h_expr.')", "= ns nsbx_e = constraints.idxsbx_e.shape[0] if is_empty(constraints.lsbx_e): constraints.lsbx_e = np.zeros((nsbx_e,))", "uh_e, con_h_expr_e.') else: dims.nh_e = nh_e if is_empty(model.con_phi_expr_e): dims.nphi_e =", "= acados_ocp.solver_options.time_steps[0] # generate external functions ocp_generate_external_functions(acados_ocp, model) # dump", "ug uh uphi; \\n lsbu lsbx lsg lsh lsphi usbu", "provided that the following conditions are met: # # 1.", "'acados_sim_solver_{}.c'.format(name) render_template(in_file, out_file, template_dir, json_path) in_file = 'acados_sim_solver.in.h' out_file =", "multipliers for inequalities \\n t: slack variables corresponding to evaluation", "in out_fields): self.shared_lib.ocp_nlp_out_get.argtypes = \\ [c_void_p, c_void_p, c_void_p, c_int, c_char_p,", "= cast(value_.ctypes.data, POINTER(c_double)) value_data_p = cast((value_data), c_void_p) if field_ in", "nsh + nsg + nsphi wrong_field = \"\" if cost.Zl.shape[0]", "= '{}_external_cost_e.h'.format(name) render_template(in_file, out_file, template_dir, json_path) class AcadosOcpSolver: \"\"\" class", "= nsh nsphi = constraints.idxsphi.shape[0] if is_empty(constraints.lsphi): constraints.lsphi = np.zeros((nsphi,))", "field_ field = field.encode('utf-8') stage = c_int(stage_) self.shared_lib.ocp_nlp_constraint_dims_get_from_attr.argtypes = \\", "(at the solution) \\n sl: slack variables of soft lower", "'{}_cost_y_e_fun.h'.format(name) render_template(in_file, out_file, template_dir, json_path) # external cost if acados_ocp.cost.cost_type", "if (constraints.lbx_0 == [] and constraints.ubx_0 == []): dims.nbx_0 =", "dimension nsbx_e, regarding idxsbx_e, usbx_e.') dims.nsbx_e = nsbx_e nsh_e =", "'cost_y_fun.in.h' out_file = '{}_cost_y_fun.h'.format(name) render_template(in_file, out_file, template_dir, json_path) # terminal", "Exception('inconsistent dimension: regarding W_e, yref_e.') dims.ny_e = ny_e elif cost.cost_type_e", "description ocp_layout = get_ocp_nlp_layout() with open(json_file, 'r') as f: ocp_nlp_json", "'c_generated_code/{}_constraints/'.format(name) in_file = 'h_e_constraint.in.h' out_file = '{}_h_e_constraint.h'.format(name) render_template(in_file, out_file, template_dir,", "nsphi: raise Exception('inconsistent dimension nsphi, regarding idxsphi, lsphi.') if is_empty(constraints.usphi):", "data in the constraint module of the solver: Parameters: :param", "or constraints.lbx.shape[0] != nbx: raise Exception('inconsistent dimension nbx, regarding idxbx,", "== 'LINEAR_LS': ny_e = cost.W_e.shape[0] if cost.Vx_e.shape[0] != ny_e: raise", "dimension nsphi_e, regarding idxsphi_e, lsphi_e.') if is_empty(constraints.usphi_e): constraints.usphi_e = np.zeros((nsphi_e,))", "\\n\\t'\\ + f'Detected ns = {ns} = nsbx + nsbu", "render_template(in_file, out_file, template_dir, json_path) # nonlinear cost function if acados_ocp.cost.cost_type", "= \\ [c_void_p, c_void_p, c_char_p, c_char_p] self.shared_lib.ocp_nlp_solver_opts_set(self.nlp_config, \\ self.nlp_opts, field,", "stage = c_int(stage_) self.shared_lib.ocp_nlp_constraint_dims_get_from_attr.argtypes = \\ [c_void_p, c_void_p, c_void_p, c_int,", "nh_e: raise Exception('inconsistent dimension nh_e, regarding lh_e, uh_e, con_h_expr_e.') else:", "from .generate_c_code_explicit_ode import generate_c_code_explicit_ode from .generate_c_code_implicit_ode import generate_c_code_implicit_ode from .generate_c_code_gnsf", "c_void_p) if field_ in constraints_fields: self.shared_lib.ocp_nlp_constraints_model_set.argtypes = \\ [c_void_p, c_void_p,", "{} (you have {})'.format( \\ field_, tuple(dims), value_shape)) value_data =", "= constraints.idxsg_e.shape[0] if is_empty(constraints.lsg_e): constraints.lsg_e = np.zeros((nsg_e,)) elif constraints.lsg_e.shape[0] !=", "field = field_ field = field.encode('utf-8') if field_ in string_fields:", "Exception('inconsistent dimension nsbx, regarding idxsbx, usbx.') dims.nsbx = nsbx nsbu", "+ cost_fields + out_fields: raise Exception(\"AcadosOcpSolver.set(): {} is not a", "isinstance(v, dict): continue # setattr(ocp_nlp, acados_struct, dict(getattr(acados_ocp, acados_struct).__dict__)) # Copy", "SUCH DAMAGE.; # import sys, os, json import numpy as", "template_dir, json_path) in_file = 'acados_solver.in.c' out_file = 'acados_solver_{}.c'.format(name) render_template(in_file, out_file,", "Copyright 2019 <NAME>, <NAME>, <NAME>, # <NAME>, <NAME>, <NAME>, <NAME>,", "{}.'.format(field_, type(value_))) else: value_ctypes = c_double(value_) elif field_ in string_fields:", "equality constraints \\n lam: multipliers for inequalities \\n t: slack", "constraints.usphi_e.shape[0] != nsphi_e: raise Exception('inconsistent dimension nsphi_e, regarding idxsphi_e, usphi_e.')", "nsphi_e, regarding idxsphi_e, usphi_e.') dims.nsphi_e = nsphi_e # terminal ns_e", "the solver: Parameters: :param stage_: integer corresponding to shooting node", "json_path = '{cwd}/{json_file}'.format( cwd=os.getcwd(), json_file=json_file) if not os.path.exists(json_path): raise Exception('{}", "+ \\ f'\\nGot W[{cost.W.shape}], yref[{cost.yref.shape}]\\n') dims.ny = ny # terminal", "opts = acados_ocp.solver_options # nx if is_column(model.x): dims.nx = casadi_length(model.x)", "not isinstance(v, dict): continue acados_attribute = getattr(acados_ocp, acados_struct) acados_attribute.__dict__ =", "ocp_nlp_layout def ocp_formulation_json_dump(acados_ocp, json_file='acados_ocp_nlp.json'): # Load acados_ocp_nlp structure description ocp_layout", "nsbx_e = constraints.idxsbx_e.shape[0] if is_empty(constraints.lsbx_e): constraints.lsbx_e = np.zeros((nsbx_e,)) elif constraints.lsbx_e.shape[0]", "conditions are met: # # 1. Redistributions of source code", "self.get_stats(\"statistics\") if self.acados_ocp.solver_options.nlp_solver_type == 'SQP': print('\\niter\\tres_stat\\tres_eq\\t\\tres_ineq\\tres_comp\\tqp_stat\\tqp_iter') if stat.shape[0]>7: print('\\tqp_res_stat\\tqp_res_eq\\tqp_res_ineq\\tqp_res_comp') for", "dims.nphi_e = casadi_length(model.con_phi_expr_e) if is_empty(model.con_r_expr_e): raise Exception('convex over nonlinear constraints:", "is_empty(constraints.usg_e): constraints.usg_e = np.zeros((nsg_e,)) elif constraints.usg_e.shape[0] != nsg_e: raise Exception('inconsistent", "not isinstance(value_, int): raise Exception('solver option {} must be of", "opts) if acados_ocp.dims.nphi_e > 0 or acados_ocp.dims.nh_e > 0: generate_c_code_constraint(model,", "maybe make one funciton with formatting for acados_struct, v in", "integrator 'time_sim_ad', # cpu time for integrator contribution of external", "## Compile solver os.chdir('c_generated_code') os.system('make clean_ocp_shared_lib') os.system('make ocp_shared_lib') os.chdir('..') self.shared_lib_name", "constraints.lbu.shape[0] != nbu: raise Exception('inconsistent dimension nbu, regarding idxbu, ubu,", "stage: integer corresponding to shooting node :param field_: string in", "!= dims.nu and ny != 0: raise Exception('inconsistent dimension: Vu", "dims consistent make_ocp_dims_consistent(acados_ocp) if acados_ocp.solver_options.integrator_type == 'GNSF': set_up_imported_gnsf_model(acados_ocp) # set", "list of conditions and the following disclaimer in the documentation", "out_file = '{}_cost_y_e_fun.h'.format(name) render_template(in_file, out_file, template_dir, json_path) # external cost", "[c_void_p, c_void_p, c_char_p, c_char_p] self.shared_lib.ocp_nlp_solver_opts_set(self.nlp_config, \\ self.nlp_opts, field, value_ctypes) else:", "casadi_length(model.con_r_expr) # terminal nbx_e = constraints.idxbx_e.shape[0] if constraints.ubx_e.shape[0] != nbx_e", "= c_int dims = self.shared_lib.ocp_nlp_dims_get_from_attr(self.nlp_config, \\ self.nlp_dims, self.nlp_out, stage_, field)", "nh_e = casadi_length(model.con_h_expr_e) else: nh_e = 0 if constraints.uh_e.shape[0] !=", "# skip non dict attributes if not isinstance(v, dict): continue", "constraints.idxbx.shape[0] if constraints.ubx.shape[0] != nbx or constraints.lbx.shape[0] != nbx: raise", "Exception('inconsistent dimension nsphi_e, regarding idxsphi_e, usphi_e.') dims.nsphi_e = nsphi_e #", "Exception('inconsistent dimension: regarding W_e, yref_e.') dims.ny_e = ny_e ## constraints", "# modification, are permitted provided that the following conditions are", "following disclaimer. # # 2. Redistributions in binary form must", "e.g. 'print_level', 'rti_phase', 'initialize_t_slacks', 'step_length' :param value_: of type int,", "usphi.') dims.nsphi = nsphi nsg = constraints.idxsg.shape[0] if is_empty(constraints.lsg): constraints.lsg", "following disclaimer in the documentation # and/or other materials provided", "(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS", "\\ [c_void_p, c_void_p, c_void_p, c_int, c_char_p, POINTER(c_int)] self.shared_lib.ocp_nlp_cost_dims_get_from_attr.restype = c_int", "for nonuniform discretization') tf = np.sum(opts.time_steps) if (tf - opts.tf)", "dimension nsbx_e, regarding idxsbx_e, lsbx_e.') if is_empty(constraints.usbx_e): constraints.usbx_e = np.zeros((nsbx_e,))", "object dictionary ocp_nlp_dict = dict(deepcopy(acados_ocp).__dict__) # TODO: maybe make one", "= acados_ocp.cost constraints = acados_ocp.constraints model = acados_ocp.model opts =", "= 0 dims.nr_e = 0 else: dims.nphi_e = casadi_length(model.con_phi_expr_e) if", "'c_generated_code/libacados_ocp_solver_' + model.name + '.so' # get self.shared_lib = CDLL(self.shared_lib_name)", "!= ns_e: wrong_field = \"Zu_e\" dim = cost.Zu_e.shape[0] elif cost.zl_e.shape[0]", "linear algebra 'time_qp', # cpu time qp solution 'time_qp_solver_call', #", "dict(deepcopy(acados_ocp).__dict__) # TODO: maybe make one funciton with formatting for", "# setattr(ocp_nlp, acados_struct, dict(getattr(acados_ocp, acados_struct).__dict__)) # Copy ocp object attributes", "if is_empty(constraints.ush): constraints.ush = np.zeros((nsh,)) elif constraints.ush.shape[0] != nsh: raise", "= np.ascontiguousarray(np.zeros((1,)), dtype=np.float64) out_data = cast(out.ctypes.data, POINTER(c_double)) self.shared_lib.ocp_nlp_get.argtypes = [c_void_p,", "= field_ field = field.encode('utf-8') if (field_ not in out_fields", "dims.nbxe_0 = dims.nbx_0 # path nbx = constraints.idxbx.shape[0] if constraints.ubx.shape[0]", "ny_e elif cost.cost_type_e == 'NONLINEAR_LS': ny_e = cost.W_e.shape[0] if is_empty(model.cost_y_expr_e)", "render_template(in_file, out_file, template_dir, json_path) in_file = 'acados_solver.in.h' out_file = 'acados_solver_{}.h'.format(name)", "c_void_p, c_void_p, c_int, c_char_p] self.shared_lib.ocp_nlp_dims_get_from_attr.restype = c_int dims = self.shared_lib.ocp_nlp_dims_get_from_attr(self.nlp_config,", "json_file) ## Compile solver os.chdir('c_generated_code') os.system('make clean_ocp_shared_lib') os.system('make ocp_shared_lib') os.chdir('..')", "Slack dimensions nsbx = constraints.idxsbx.shape[0] if is_empty(constraints.lsbx): constraints.lsbx = np.zeros((nsbx,))", "nsbx_e + nsg_e + nsh_e + nsphi_e.\\n\\t'\\ + f'With nsbx_e", "dimension nsphi_e, regarding idxsphi_e, usphi_e.') dims.nsphi_e = nsphi_e # terminal", "nsg_e = {nsg_e}, nsh_e = {nsh_e}, nsphi_e = {nsphi_e}') dims.ns_e", "'initialize_t_slacks'] double_fields = ['step_length'] string_fields = ['globalization'] if field_ in", "to shooting node :param field_: string in ['x', 'u', 'z',", "!= ny_e: raise Exception('inconsistent dimension: regarding W_e, yref_e.') dims.ny_e =", "acados_ocp.cost constraints = acados_ocp.constraints model = acados_ocp.model opts = acados_ocp.solver_options", "acados_struct).__dict__) ocp_nlp_dict = format_class_dict(ocp_nlp_dict) # strip symbolics ocp_nlp_dict['model'] = acados_model_strip_casadi_symbolics(ocp_nlp_dict['model'])", "opts) # dummy matrices if not acados_ocp.cost.cost_type == 'LINEAR_LS': acados_ocp.cost.Vx", "int(stat[1][jj]), int(stat[2][jj]))) if stat.shape[0]>3: print('\\t{:e}\\t{:e}\\t{:e}\\t{:e}'.format( \\ stat[3][jj], stat[4][jj], stat[5][jj], stat[6][jj]))", "function if acados_ocp.cost.cost_type_e == 'NONLINEAR_LS': template_dir = 'c_generated_code/{}_cost/'.format(name) in_file =", "stage_, field) if value_.shape[0] != dims: msg = 'AcadosOcpSolver.set(): mismatching", "os, json import numpy as np from ctypes import *", "!= nh_e or constraints.lh_e.shape[0] != nh_e: raise Exception('inconsistent dimension nh_e,", "in out_fields: self.shared_lib.ocp_nlp_out_set.argtypes = \\ [c_void_p, c_void_p, c_void_p, c_int, c_char_p,", "'yref', 'W', 'ext_cost_num_hess' :param value_: of appropriate size \"\"\" #", "= \\ [c_void_p, c_void_p, c_void_p, c_int, c_char_p, c_void_p] self.shared_lib.ocp_nlp_cost_model_set(self.nlp_config, \\", "c_void_p] self.shared_lib.ocp_nlp_cost_model_set(self.nlp_config, \\ self.nlp_dims, self.nlp_in, stage, field, value_data_p) return def", "idxsbx, lsbx.') if is_empty(constraints.usbx): constraints.usbx = np.zeros((nsbx,)) elif constraints.usbx.shape[0] !=", "value_): \"\"\" set numerical data in the cost module of", "in constraints_fields: self.shared_lib.ocp_nlp_constraints_model_set.argtypes = \\ [c_void_p, c_void_p, c_void_p, c_int, c_char_p,", "out # Note: this function should not be used anymore,", "is_empty(model.z): dims.nz = 0 else: dims.nz = casadi_length(model.z) # np", "Copy input ocp object dictionary ocp_nlp_dict = dict(deepcopy(acados_ocp).__dict__) # TODO:", "= nsbu nsh = constraints.idxsh.shape[0] if is_empty(constraints.lsh): constraints.lsh = np.zeros((nsh,))", "self.shared_lib.ocp_nlp_constraints_model_set.argtypes = \\ [c_void_p, c_void_p, c_void_p, c_int, c_char_p, c_void_p] self.shared_lib.ocp_nlp_constraints_model_set(self.nlp_config,", "idxbu, ubu, lbu.') else: dims.nbu = nbu ng = constraints.lg.shape[0]", "'ubx', 'lbu', 'ubu'] out_fields = ['x', 'u', 'pi', 'lam', 't']", "raise Exception('inconsistent dimension nsbu, regarding idxsbu, lsbu.') if is_empty(constraints.usbu): constraints.usbu", "= {ns} = nsbx + nsbu + nsg + nsh", "+ mem_fields)) self.shared_lib.ocp_nlp_dims_get_from_attr.argtypes = \\ [c_void_p, c_void_p, c_void_p, c_int, c_char_p]", "Exception('inconsistent dimension nsg_e, regarding idxsg_e, lsg_e.') if is_empty(constraints.usg_e): constraints.usg_e =", "field_ in out_fields: self.shared_lib.ocp_nlp_out_set.argtypes = \\ [c_void_p, c_void_p, c_void_p, c_int,", "field, value_data_p) return def cost_set(self, stage_, field_, value_): \"\"\" set", "or constraints.lh_e.shape[0] != nh_e: raise Exception('inconsistent dimension nh_e, regarding lh_e,", "constraints.lbx_e.shape[0] != nbx_e: raise Exception('inconsistent dimension nbx_e, regarding idxbx_e, ubx_e,", "'phi_constraint.in.h' out_file = '{}_phi_constraint.h'.format(name) render_template(in_file, out_file, template_dir, json_path) # terminal", "with dimension {} (you have {})'.format( \\ field_, tuple(dims), value_shape))", "!= sum(opts.time_steps) = {tf}.') def get_ocp_nlp_layout(): current_module = sys.modules[__name__] acados_path", "opts.time_steps = opts.tf / dims.N * np.ones((dims.N,)) elif not is_empty(opts.shooting_nodes):", "model.name + '.so' # get self.shared_lib = CDLL(self.shared_lib_name) self.shared_lib.acados_create() self.solver_created", "con_r_expr but con_phi_expr is nonempty') else: dims.nr = casadi_length(model.con_r_expr) #", "constraints.ush_e.shape[0] != nsh_e: raise Exception('inconsistent dimension nsh_e, regarding idxsh_e, ush_e.')", "np.zeros((nsphi,)) elif constraints.usphi.shape[0] != nsphi: raise Exception('inconsistent dimension nsphi, regarding", "cost.zl_e.shape[0] != ns_e: wrong_field = \"zl_e\" dim = cost.zl_e.shape[0] elif", "external function calls 'time_sim_la', # cpu time for integrator contribution", "LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR #", "if acados_ocp.parameter_values.shape[0] != dims.np: raise Exception('inconsistent dimension np, regarding model.p", "'pi', 'lam', 't'] mem_fields = ['sl', 'su'] field = field_", "cast((value_data), c_void_p) if field_ in constraints_fields: self.shared_lib.ocp_nlp_constraints_model_set.argtypes = \\ [c_void_p,", "(stat_n[0]+1, min_size[0]) ), dtype=np.float64) out_data = cast(out.ctypes.data, POINTER(c_double)) else: out", "'LINEAR_LS': acados_ocp.cost.Vx_e = np.zeros((acados_ocp.dims.ny_e, acados_ocp.dims.nx)) if acados_ocp.cost.cost_type == 'NONLINEAR_LS': generate_c_code_nls_cost(model,", "\\ self.nlp_dims, self.nlp_out, stage, field, value_data_p) return def cost_set(self, stage_,", "ns_e # discretization if is_empty(opts.time_steps) and is_empty(opts.shooting_nodes): # uniform discretization", "Exception('solver option {} must be of type float. You have", "contribution of linear algebra 'time_qp', # cpu time qp solution", "= np.zeros((nsbx,)) elif constraints.lsbx.shape[0] != nsbx: raise Exception('inconsistent dimension nsbx,", "discretization') tf = np.sum(opts.time_steps) if (tf - opts.tf) / tf", "nbu, regarding idxbu, ubu, lbu.') else: dims.nbu = nbu ng", "nh = 0 if constraints.uh.shape[0] != nh or constraints.lh.shape[0] !=", "dims.nphi_e = 0 dims.nr_e = 0 else: dims.nphi_e = casadi_length(model.con_phi_expr_e)", "Exception('AcadosOcpSolver.solve(): argument \\'rti_phase\\' can ' 'take only value 0 for", "should have nx columns.') if cost.Vu.shape[1] != dims.nu and ny", "conversion issues value_ = value_.astype(float) field = field_ field =", "the following conditions are met: # # 1. Redistributions of", "# nonlinear constraints if acados_ocp.constraints.constr_type == 'BGH' and acados_ocp.dims.nh >", "this list of conditions and the following disclaimer in the", "is not a valid argument.\\ \\n Possible values are {}.", "cast(dims.ctypes.data, POINTER(c_int)) self.shared_lib.ocp_nlp_cost_dims_get_from_attr(self.nlp_config, \\ self.nlp_dims, self.nlp_out, stage_, field, dims_data) value_shape", "+ '/acados_layout.json', 'r') as f: ocp_nlp_layout = json.load(f) return ocp_nlp_layout", "values are {}. Exiting.'.format(field_, out_fields + mem_fields)) self.shared_lib.ocp_nlp_dims_get_from_attr.argtypes = \\", "model.name, False) elif acados_ocp.cost.cost_type == 'EXTERNAL': generate_c_code_external_cost(model, False) if acados_ocp.cost.cost_type_e", "= {nsg_e}, nsh_e = {nsh_e}, nsphi_e = {nsphi_e}') dims.ns_e =", "only values 0, 1, 2 for SQP-RTI-type solvers') if self.acados_ocp.solver_options.nlp_solver_type", "'c_generated_code/{}_model/'.format(name) in_file = 'model.in.h' out_file = '{}_model.h'.format(name) render_template(in_file, out_file, template_dir,", "'SQP_RTI': print('\\niter\\tqp_stat\\tqp_iter') if stat.shape[0]>3: print('\\tqp_res_stat\\tqp_res_eq\\tqp_res_ineq\\tqp_res_comp') for jj in range(stat.shape[1]): print('{:d}\\t{:d}\\t{:d}'.format(", "c_int(stage_) self.shared_lib.ocp_nlp_cost_dims_get_from_attr.argtypes = \\ [c_void_p, c_void_p, c_void_p, c_int, c_char_p, POINTER(c_int)]", "constraints.usphi = np.zeros((nsphi,)) elif constraints.usphi.shape[0] != nsphi: raise Exception('inconsistent dimension", "= {ns_e} = nsbx_e + nsg_e + nsh_e + nsphi_e.\\n\\t'\\", "np.zeros((nsbx,)) elif constraints.usbx.shape[0] != nsbx: raise Exception('inconsistent dimension nsbx, regarding", "acados_ocp.dims.nh_e > 0: template_dir = 'c_generated_code/{}_constraints/'.format(name) in_file = 'h_e_constraint.in.h' out_file", "self.shared_lib.ocp_nlp_get.argtypes = [c_void_p, c_void_p, c_char_p, c_void_p] self.shared_lib.ocp_nlp_get(self.nlp_config, self.nlp_solver, field, out_data)", "= cost.W_e.shape[0] if cost.Vx_e.shape[0] != ny_e: raise Exception('inconsistent dimension ny_e:", "License # # Redistribution and use in source and binary", "idxsh_e, lsh_e.') if is_empty(constraints.ush_e): constraints.ush_e = np.zeros((nsh_e,)) elif constraints.ush_e.shape[0] !=", "'{}_phi_constraint.h'.format(name) render_template(in_file, out_file, template_dir, json_path) # terminal constraints on convex", "= ['lbx', 'ubx', 'lbu', 'ubu'] out_fields = ['x', 'u', 'pi',", "in range(dims.N): time_steps[i] = opts.shooting_nodes[i+1] - opts.shooting_nodes[i] opts.time_steps = time_steps", "= {nsh_e}, nsphi_e = {nsphi_e}') dims.ns_e = ns_e # discretization", "!= dims.N+1: raise Exception('inconsistent dimension N, regarding shooting_nodes.') time_steps =", "vectors!') dims.nbx_0 = constraints.lbx_0.size if all(constraints.lbx_0 == constraints.ubx_0): dims.nbxe_0 =", "(you have {})'.format(dims, value_.shape[0]) raise Exception(msg) value_data = cast(value_.ctypes.data, POINTER(c_double))", "+ ['p'])) self.shared_lib.ocp_nlp_dims_get_from_attr.argtypes = \\ [c_void_p, c_void_p, c_void_p, c_int, c_char_p]", "future_fstrings -*- # # Copyright 2019 <NAME>, <NAME>, <NAME>, #", "templates ocp_render_templates(acados_ocp, json_file) ## Compile solver os.chdir('c_generated_code') os.system('make clean_ocp_shared_lib') os.system('make", "Vu[{cost.Vu.shape}]\\n') if dims.nz != 0 and cost.Vz.shape[0] != ny: raise", "inequality constraints \\n su: slack variables of soft upper inequality", "lsg_e.') if is_empty(constraints.usg_e): constraints.usg_e = np.zeros((nsg_e,)) elif constraints.usg_e.shape[0] != nsg_e:", "{nsbx_e}, nsg_e = {nsg_e}, nsh_e = {nsh_e}, nsphi_e = {nsphi_e}')", "opts) elif acados_ocp.solver_options.integrator_type == 'GNSF': generate_c_code_gnsf(model) else: raise Exception(\"ocp_generate_external_functions: unknown", "= dict(generate_hess=0) if acados_ocp.dims.nphi > 0 or acados_ocp.dims.nh > 0:", "ocp_formulation_json_dump(acados_ocp, json_file='acados_ocp_nlp.json'): # Load acados_ocp_nlp structure description ocp_layout = get_ocp_nlp_layout()", "nsbu, regarding idxsbu, lsbu.') if is_empty(constraints.usbu): constraints.usbu = np.zeros((nsbu,)) elif", "= c_int(value_) elif field_ in double_fields: if not isinstance(value_, float):", "np from ctypes import * from casadi import CasadiMeta, Function,", "!= nbu or constraints.lbu.shape[0] != nbu: raise Exception('inconsistent dimension nbu,", "ctypes import * from casadi import CasadiMeta, Function, SX from", "interact with the acados ocp solver C object \"\"\" def", "not is_column(constraints.lbx_0): raise Exception('lbx_0, ubx_0 must be column vectors!') dims.nbx_0", "cost - terminal if acados_ocp.cost.cost_type_e == 'EXTERNAL': template_dir = 'c_generated_code/{}_cost/'.format(name)", "values are {}. Exiting.'.format(fields, fields)) if field_ in ['sqp_iter', 'stat_m',", "c_double(value_) elif field_ in string_fields: if not isinstance(value_, str): raise", "acados_ocp.cost.cost_type_e == 'EXTERNAL': generate_c_code_external_cost(model, True) def ocp_render_templates(acados_ocp, json_file): name =", "{tf}.') def get_ocp_nlp_layout(): current_module = sys.modules[__name__] acados_path = os.path.dirname(current_module.__file__) with", "in_file = 'phi_e_constraint.in.h' out_file = '{}_phi_e_constraint.h'.format(name) render_template(in_file, out_file, template_dir, json_path)", "size \"\"\" # cast value_ to avoid conversion issues value_", "dtype=np.intc) dims_data = cast(dims.ctypes.data, POINTER(c_int)) self.shared_lib.ocp_nlp_constraint_dims_get_from_attr(self.nlp_config, \\ self.nlp_dims, self.nlp_out, stage_,", "D.') else: dims.ng = ng if not is_empty(model.con_h_expr): nh =", "inequalities are internally organized in the following order: \\n [", "[c_void_p, c_void_p, c_void_p, c_int, c_char_p, c_void_p] self.shared_lib.ocp_nlp_out_get(self.nlp_config, \\ self.nlp_dims, self.nlp_out,", "= 0 if constraints.uh.shape[0] != nh or constraints.lh.shape[0] != nh:", "set numerical data in the constraint module of the solver:", "raise Exception('inconsistent dimension nsphi_e, regarding idxsphi_e, lsphi_e.') if is_empty(constraints.usphi_e): constraints.usphi_e", "is_empty(model.p): dims.np = 0 else: dims.np = casadi_length(model.p) if acados_ocp.parameter_values.shape[0]", "self.get_stats(\"stat_n\") min_size = min([stat_m, sqp_iter+1]) out = np.ascontiguousarray( np.zeros( (stat_n[0]+1,", ":param field_: string, e.g. 'yref', 'W', 'ext_cost_num_hess' :param value_: of", "Exception('inconsistent dimension nsh, regarding idxsh, lsh.') if is_empty(constraints.ush): constraints.ush =", "the solver: :param stage: integer corresponding to shooting node :param", "# make dims consistent make_ocp_dims_consistent(acados_ocp) if acados_ocp.solver_options.integrator_type == 'GNSF': set_up_imported_gnsf_model(acados_ocp)", "'EXTERNAL': template_dir = 'c_generated_code/{}_cost/'.format(name) in_file = 'external_cost_e.in.h' out_file = '{}_external_cost_e.h'.format(name)", "else: value_ctypes = value_.encode('utf-8') if field_ == 'rti_phase': if value_", "field_ == 'statistics': sqp_iter = self.get_stats(\"sqp_iter\") stat_m = self.get_stats(\"stat_m\") stat_n", "acados_struct, dict(getattr(acados_ocp, acados_struct).__dict__)) # Copy ocp object attributes dictionaries ocp_nlp_dict[acados_struct]=dict(getattr(acados_ocp,", "= acados_ocp.model.name # setting up loader and environment json_path =", "' for field \"{}\" with dimension {} (you have {})'.format(field_,", "# Copy ocp object attributes dictionaries ocp_nlp_dict[acados_struct]=dict(getattr(acados_ocp, acados_struct).__dict__) ocp_nlp_dict =", "= cast((value_data), c_void_p) self.shared_lib.ocp_nlp_cost_model_set.argtypes = \\ [c_void_p, c_void_p, c_void_p, c_int,", "= np.zeros((nsh,)) elif constraints.lsh.shape[0] != nsh: raise Exception('inconsistent dimension nsh,", "ns_e: wrong_field = \"Zu_e\" dim = cost.Zu_e.shape[0] elif cost.zl_e.shape[0] !=", "'u', 'z', 'pi', 'lam', 't'] mem_fields = ['sl', 'su'] field", "type(value_))) else: value_ctypes = c_double(value_) elif field_ in string_fields: if", "byref(value_ctypes)) return def __del__(self): if self.solver_created: self.shared_lib.acados_free() del self.shared_lib #", "self.nlp_out, stage_, field, out_data) elif field_ in mem_fields: self.shared_lib.ocp_nlp_get_at_stage.argtypes =", "for integrator contribution of linear algebra 'time_qp', # cpu time", "self.acados_ocp = acados_ocp def solve(self): \"\"\" solve the ocp with", "DLL cannot be easily unloaded!!! # see https://stackoverflow.com/questions/359498/how-can-i-unload-a-dll-using-ctypes-in-python # while", "out_file, template_dir, json_path) in_file = 'acados_solver_sfun.in.c' out_file = 'acados_solver_sfunction_{}.c'.format(name) render_template(in_file,", "= c_void_p self.nlp_dims = self.shared_lib.acados_get_nlp_dims() self.shared_lib.acados_get_nlp_config.restype = c_void_p self.nlp_config =", "if (field_ not in out_fields + mem_fields): raise Exception('AcadosOcpSolver.get(): {}", "= '{}_phi_constraint.h'.format(name) render_template(in_file, out_file, template_dir, json_path) # terminal constraints on", "os.system('make ocp_shared_lib') os.chdir('..') self.shared_lib_name = 'c_generated_code/libacados_ocp_solver_' + model.name + '.so'", "nsg = constraints.idxsg.shape[0] if is_empty(constraints.lsg): constraints.lsg = np.zeros((nsg,)) elif constraints.lsg.shape[0]", "ocp_nlp_dict = format_class_dict(ocp_nlp_dict) # strip symbolics ocp_nlp_dict['model'] = acados_model_strip_casadi_symbolics(ocp_nlp_dict['model']) #", "out_fields = ['x', 'u', 'z', 'pi', 'lam', 't'] mem_fields =", "self.get_stats(\"sqp_iter\") stat_m = self.get_stats(\"stat_m\") stat_n = self.get_stats(\"stat_n\") min_size = min([stat_m,", "NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND", "= np.zeros((nsh_e,)) elif constraints.ush_e.shape[0] != nsh_e: raise Exception('inconsistent dimension nsh_e,", "dims.nphi = casadi_length(model.con_phi_expr) if is_empty(model.con_r_expr): raise Exception('convex over nonlinear constraints:", "idxsg_e, usg_e.') dims.nsg_e = nsg_e nsphi_e = constraints.idxsphi_e.shape[0] if is_empty(constraints.lsphi_e):", "casadi_length(model.con_h_expr_e) else: nh_e = 0 if constraints.uh_e.shape[0] != nh_e or", "ns: wrong_field = \"Zl\" dim = cost.Zl.shape[0] elif cost.Zu.shape[0] !=", "'su'] field = field_ field = field.encode('utf-8') if (field_ not", "+ nsh + nsg + nsphi wrong_field = \"\" if", "in ['x', 'u', 'z', 'pi', 'lam', 't', 'sl', 'su',] ..", "def ocp_formulation_json_dump(acados_ocp, json_file='acados_ocp_nlp.json'): # Load acados_ocp_nlp structure description ocp_layout =", "1. Redistributions of source code must retain the above copyright", "= dict(generate_hess=1) else: opts = dict(generate_hess=0) if acados_ocp.dims.nphi > 0", "= 'h_constraint.in.h' out_file = '{}_h_constraint.h'.format(name) render_template(in_file, out_file, template_dir, json_path) #", "cast(out.ctypes.data, POINTER(c_double)) else: out = np.ascontiguousarray(np.zeros((1,)), dtype=np.float64) out_data = cast(out.ctypes.data,", "PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE", "== 'EXACT': opts = dict(generate_hess=1) else: opts = dict(generate_hess=0) if", "elif constraints.lsbu.shape[0] != nsbu: raise Exception('inconsistent dimension nsbu, regarding idxsbu,", "'NONLINEAR_LS': generate_c_code_nls_cost(model, model.name, True) elif acados_ocp.cost.cost_type_e == 'EXTERNAL': generate_c_code_external_cost(model, True)", "a valid argument.\\ \\nPossible values are {}. Exiting.\".format(field, \\ constraints_fields", "idxsbu, lsbu.') if is_empty(constraints.usbu): constraints.usbu = np.zeros((nsbu,)) elif constraints.usbu.shape[0] !=", "+ \\ f'\\nGot W_e[{cost.W_e.shape}], Vx_e[{cost.Vx_e.shape}]') if cost.Vx_e.shape[1] != dims.nx and", "json.load(f) return ocp_nlp_layout def ocp_formulation_json_dump(acados_ocp, json_file='acados_ocp_nlp.json'): # Load acados_ocp_nlp structure", "stat.shape[0]>3: print('\\tqp_res_stat\\tqp_res_eq\\tqp_res_ineq\\tqp_res_comp') for jj in range(stat.shape[1]): print('{:d}\\t{:d}\\t{:d}'.format( int(stat[0][jj]), int(stat[1][jj]), int(stat[2][jj])))", "0 dims.nr = 0 else: dims.nphi = casadi_length(model.con_phi_expr) if is_empty(model.con_r_expr):", "terminal if cost.cost_type_e == 'LINEAR_LS': ny_e = cost.W_e.shape[0] if cost.Vx_e.shape[0]", "appropriate size \"\"\" # cast value_ to avoid conversion issues", "= ny # terminal if cost.cost_type_e == 'LINEAR_LS': ny_e =", "field_ in int_fields: if not isinstance(value_, int): raise Exception('solver option", "# path if cost.cost_type == 'LINEAR_LS': ny = cost.W.shape[0] if", "Vz.' + \\ f'\\nGot W[{cost.W.shape}], Vx[{cost.Vx.shape}], Vu[{cost.Vu.shape}], Vz[{cost.Vz.shape}]\\n') if cost.Vx.shape[1]", "idxsg, usg.') dims.nsg = nsg ns = nsbx + nsbu", "self.nlp_dims = self.shared_lib.acados_get_nlp_dims() self.shared_lib.acados_get_nlp_config.restype = c_void_p self.nlp_config = self.shared_lib.acados_get_nlp_config() self.shared_lib.acados_get_nlp_out.restype", "dimension: regarding W, yref.' + \\ f'\\nGot W[{cost.W.shape}], yref[{cost.yref.shape}]\\n') dims.ny", "= dict(generate_hess=1) generate_c_code_implicit_ode(model, opts) elif acados_ocp.solver_options.integrator_type == 'GNSF': generate_c_code_gnsf(model) else:", "'EXTERNAL': generate_c_code_external_cost(model, True) def ocp_render_templates(acados_ocp, json_file): name = acados_ocp.model.name #", "!= ng_e or constraints.C_e.shape[0] != ng_e: raise Exception('inconsistent dimension ng_e,", "render_template(in_file, out_file, template_dir, json_path) class AcadosOcpSolver: \"\"\" class to interact", "['sqp_iter', 'stat_m', 'stat_n']: out = np.ascontiguousarray(np.zeros((1,)), dtype=np.int64) out_data = cast(out.ctypes.data,", "from .generate_c_code_nls_cost import generate_c_code_nls_cost from .generate_c_code_external_cost import generate_c_code_external_cost from .acados_ocp", "field, value_data_p) elif field_ in out_fields: self.shared_lib.ocp_nlp_out_set.argtypes = \\ [c_void_p,", "get the information of the last solver call: :param field_:", "generate_c_code_constraint from .generate_c_code_nls_cost import generate_c_code_nls_cost from .generate_c_code_external_cost import generate_c_code_external_cost from", "dims, constraints, etc for acados_struct, v in ocp_layout.items(): # skip", "nsbx, regarding idxsbx, usbx.') dims.nsbx = nsbx nsbu = constraints.idxsbu.shape[0]", "type int. You have {}.'.format(field_, type(value_))) else: value_ctypes = c_int(value_)", "render_template(in_file, out_file, template_dir, json_path) # external cost if acados_ocp.cost.cost_type ==", "ny: regarding W, cost_y_expr.') elif casadi_length(model.cost_y_expr) != ny: raise Exception('inconsistent", "of soft upper inequality constraints \\n \"\"\" out_fields = ['x',", "You have {}.'.format(field_, type(value_))) else: value_ctypes = c_double(value_) elif field_", "dimension: Vx_e should have nx columns.') if cost.yref_e.shape[0] != ny_e:", "string_fields: self.shared_lib.ocp_nlp_solver_opts_set.argtypes = \\ [c_void_p, c_void_p, c_char_p, c_char_p] self.shared_lib.ocp_nlp_solver_opts_set(self.nlp_config, \\", "terminal ns_e = nsbx_e + nsh_e + nsg_e + nsphi_e", "= nh if is_empty(model.con_phi_expr): dims.nphi = 0 dims.nr = 0", "time_steps elif (not is_empty(opts.time_steps)) and (not is_empty(opts.shooting_nodes)): Exception('Please provide either", "or shooting_nodes for nonuniform discretization') tf = np.sum(opts.time_steps) if (tf", "= '{cwd}/{json_file}'.format( cwd=os.getcwd(), json_file=json_file) if not os.path.exists(json_path): raise Exception('{} not", "= 'c_generated_code/{}_cost/'.format(name) in_file = 'cost_y_e_fun.in.h' out_file = '{}_cost_y_e_fun.h'.format(name) render_template(in_file, out_file,", "convex over nonlinear function if acados_ocp.constraints.constr_type_e == 'BGP' and acados_ocp.dims.nphi_e", "json_file) # render templates ocp_render_templates(acados_ocp, json_file) ## Compile solver os.chdir('c_generated_code')", "ug_e, C_e.') else: dims.ng_e = ng_e if not is_empty(model.con_h_expr_e): nh_e", "stat.shape[0]>3: print('\\t{:e}\\t{:e}\\t{:e}\\t{:e}'.format( \\ stat[3][jj], stat[4][jj], stat[5][jj], stat[6][jj])) print('\\n') return def", "nsh, regarding idxsh, lsh.') if is_empty(constraints.ush): constraints.ush = np.zeros((nsh,)) elif", "nbu: raise Exception('inconsistent dimension nbu, regarding idxbu, ubu, lbu.') else:", "= '{}_cost_y_fun.h'.format(name) render_template(in_file, out_file, template_dir, json_path) # terminal nonlinear cost", "regarding idxsh_e, lsh_e.') if is_empty(constraints.ush_e): constraints.ush_e = np.zeros((nsh_e,)) elif constraints.ush_e.shape[0]", "nsh_e + nsphi_e.\\n\\t'\\ + f'With nsbx_e = {nsbx_e}, nsg_e =", "Exception('AcadosOcpSolver.get(): {} is an invalid argument.\\ \\n Possible values are", "(value_shape[0], 0) if value_shape != tuple(dims): raise Exception('AcadosOcpSolver.cost_set(): mismatching dimension',", "template_dir, json_path) # terminal nonlinear cost function if acados_ocp.cost.cost_type_e ==", "of appropriate size \"\"\" # cast value_ to avoid conversion", "-- generate C code generate_c_code_explicit_ode(model) elif acados_ocp.solver_options.integrator_type == 'IRK': #", "discretization opts.time_steps = opts.tf / dims.N * np.ones((dims.N,)) elif not", "else: nh_e = 0 if constraints.uh_e.shape[0] != nh_e or constraints.lh_e.shape[0]", "nsg_e = constraints.idxsg_e.shape[0] if is_empty(constraints.lsg_e): constraints.lsg_e = np.zeros((nsg_e,)) elif constraints.lsg_e.shape[0]", "!= ns: wrong_field = \"zu\" dim = cost.zu.shape[0] if wrong_field", "cannot be easily unloaded!!! # see https://stackoverflow.com/questions/359498/how-can-i-unload-a-dll-using-ctypes-in-python # while isLoaded(self.shared_lib_name):", "constraints.ubx_e.shape[0] != nbx_e or constraints.lbx_e.shape[0] != nbx_e: raise Exception('inconsistent dimension", "dims.nbx_0 # path nbx = constraints.idxbx.shape[0] if constraints.ubx.shape[0] != nbx", "field) out = np.ascontiguousarray(np.zeros((dims,)), dtype=np.float64) out_data = cast(out.ctypes.data, POINTER(c_double)) if" ]
[ "/ 255.0 h, w = img.shape psize = min(min(patchSize, h),", "h_, start_x : start_x + w_] = sigma if saveResults:", "isinstance(pch_size, int): pch_H = pch_W = pch_size else: sys.exit('The input", "Internal number of sub-image-patches. :param dirOut: Directory where to save", "num_pch = num_H * num_W pch = np.zeros((C, pch_H*pch_W, num_pch),", "pch_H, pch_W, num_pch)) def noise_estimate(im, pch_size=8): ''' Implement of noise", "sys import os import glob def im2patch(im, pch_size, stride=1): '''", "w: end_x = w end_x = shift_factor * ((end_x) //", "start_x = end_x - psize if end_y > h: end_y", ":start_y + h_, start_x : start_x + w_] = sigma", "by patch. Based on: \"An Efficient Statistical Method for Image", "start_x : start_x + w_] = sigma if saveResults: if", "pch_size x pch_size x num_pch tensor num_pch = pch.shape[3] pch", "of the following paper: <NAME> , <NAME> , <NAME> .", "= psize shift_factor = 2 # Result array estimatedNoiseMap =", "Example # if __name__ == '__main__': # dirIn = r\"../../../data/udacity/img/GT\"", "W numpy tensor, range [0,1] pch_size: patch_size Output: noise_level: the", "rangey: end_x = start_x + psize end_y = start_y +", "C, H, W = im.shape num_H = len(range(0, H-pch_H+1, stride_H))", "* ((end_y) // shift_factor) start_y = end_y - psize tileM", "os import glob def im2patch(im, pch_size, stride=1): ''' Transform image", "noise of image patches. The noise is estimated patch by", "x num_pch tensor num_pch = pch.shape[3] pch = pch.reshape((-1, num_pch))", "start_x in rangex: for start_y in rangey: end_x = start_x", "elif isinstance(pch_size, int): pch_H = pch_W = pch_size else: sys.exit('The", "len(range(0, H-pch_H+1, stride_H)) num_W = len(range(0, W-pch_W+1, stride_W)) num_pch =", "Level Estimation\" (2015) :param imgPath: Path to the input image.", "+ psize end_y = start_y + psize if end_x >", "== 3: im = im.transpose((2, 0, 1)) else: im =", "= num_H * num_W pch = np.zeros((C, pch_H*pch_W, num_pch), dtype=im.dtype)", "kk, :] = temp.reshape((C, num_pch)) kk += 1 return pch.reshape((C,", "W x 3 or H x W numpy tensor, range", "img / 255.0 h, w = img.shape psize = min(min(patchSize,", "np.array(cv2.imread(imgPath)) try: img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) img = img /", "patch_step) for start_x in rangex: for start_y in rangey: end_x", "h: end_y = h end_y = shift_factor * ((end_y) //", "kk = 0 for ii in range(pch_H): for jj in", "''' if im.ndim == 3: im = im.transpose((2, 0, 1))", "x W numpy tensor, range [0,1] pch_size: patch_size Output: noise_level:", "# dirOut = r\"../../../data/udacity/labels_noise_patchwise/PCA\" # imgFileEnding = \".jpg\" # for", "input of pch_size must be a integer or a int", "isinstance(stride, int): stride_H = stride_W = stride else: sys.exit('The input", "Level Estimation[C]// 2015 IEEE International Conference on Computer Vision (ICCV).", "ii in range(pch_H): for jj in range(pch_W): temp = im[:,", "image, H x W x 3 or H x W", "num_pch)) # d x num_pch matrix d = pch.shape[0] mu", "matrix d = pch.shape[0] mu = pch.mean(axis=1, keepdims=True) # d", "shift_factor * ((end_x) // shift_factor) start_x = end_x - psize", "= cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) img = img / 255.0 h, w", "range(pch_H): for jj in range(pch_W): temp = im[:, ii:H-pch_H+ii+1:stride_H, jj:W-pch_W+jj+1:stride_W]", "\"\"\" Estimates the standard deviation of (additive white gaussian) noise", "estimated patch by patch. Based on: \"An Efficient Statistical Method", "in rangex: for start_y in rangey: end_x = start_x +", "if np.sum(sig_value[:ii]>tau) == np.sum(sig_value[:ii] < tau): return np.sqrt(tau) def run(imgPath,", "Noise Level Estimation[C]// 2015 IEEE International Conference on Computer Vision", "integer ''' if isinstance(pch_size, tuple): pch_H, pch_W = pch_size elif", "psize if end_y > h: end_y = h end_y =", "psize tileM = img[start_y:end_y, start_x:end_x] h_, w_ = tileM.shape sigma", "Method for Image Noise Level Estimation\" (2015) :param imgPath: Path", "Image patch size. :param internalNumPatches: Internal number of sub-image-patches. :param", "H x W image, numpy format pch_size: (int, int) tuple", "Conference on Computer Vision (ICCV). IEEE Computer Society, 2015. Input:", "Based on: \"An Efficient Statistical Method for Image Noise Level", "pch_size must be a integer or a int tuple!') if", "tuple): pch_H, pch_W = pch_size elif isinstance(pch_size, int): pch_H =", ":param patchSize: Image patch size. :param internalNumPatches: Internal number of", "3 x H x W or 1 X H x", "# image to patch pch = im2patch(im, pch_size, 3) #", "im = np.expand_dims(im, axis=0) # image to patch pch =", "level ''' if im.ndim == 3: im = im.transpose((2, 0,", "3: im = im.transpose((2, 0, 1)) else: im = np.expand_dims(im,", "os.path.join(dirOut) if not os.path.exists(dirOut): os.makedirs(dirOut) noiseMapPath = os.path.join(dirOut, imgName +", "+ w_] = sigma if saveResults: if dirOut is not", "input of stride must be a integer or a int", "the noise image, H x W x 3 or H", "* 255.0 estimatedNoiseMap[start_y :start_y + h_, start_x : start_x +", "W or 1 X H x W image, numpy format", "// shift_factor) start_y = end_y - psize tileM = img[start_y:end_y,", "H x W numpy tensor, range [0,1] pch_size: patch_size Output:", "= pch - mu sigma_X = np.matmul(X, X.transpose()) / num_pch", ":param saveResults: Whether to save the estimation results or not.", "pch[:, kk, :] = temp.reshape((C, num_pch)) kk += 1 return", "noise is estimated patch by patch. Based on: \"An Efficient", "= os.path.join(dirOut) if not os.path.exists(dirOut): os.makedirs(dirOut) noiseMapPath = os.path.join(dirOut, imgName", "* ((end_x) // shift_factor) start_x = end_x - psize if", "pch_H*pch_W, num_pch), dtype=im.dtype) kk = 0 for ii in range(pch_H):", "format pch_size: (int, int) tuple or integer stride: (int, int)", "range(-1, -d-1, -1): tau = np.mean(sig_value[:ii]) if np.sum(sig_value[:ii]>tau) == np.sum(sig_value[:ii]", "\"\"\" # Load image img = np.array(cv2.imread(imgPath)) try: img =", "image to patch pch = im2patch(im, pch_size, 3) # C", "= end_y - psize tileM = img[start_y:end_y, start_x:end_x] h_, w_", "0 for ii in range(pch_H): for jj in range(pch_W): temp", "white gaussian) noise of image patches. The noise is estimated", "''' Transform image to patches. Input: im: 3 x H", "num_H = len(range(0, H-pch_H+1, stride_H)) num_W = len(range(0, W-pch_W+1, stride_W))", "= 0 for ii in range(pch_H): for jj in range(pch_W):", "saveResults=True): \"\"\" Estimates the standard deviation of (additive white gaussian)", "stride elif isinstance(stride, int): stride_H = stride_W = stride else:", "for imgPath in glob.glob(os.path.join(dirIn, \"*\" + imgFileEnding)): # run(imgPath, 128,", "((end_x) // shift_factor) start_x = end_x - psize if end_y", "end_y - psize tileM = img[start_y:end_y, start_x:end_x] h_, w_ =", "# Load image img = np.array(cv2.imread(imgPath)) try: img = cv2.cvtColor(img,", "stride_H = stride_W = stride else: sys.exit('The input of stride", "dtype=np.int8) rangex = range(0, w, patch_step) rangey = range(0, h,", "im: the noise image, H x W x 3 or", "= r\"../../../data/udacity/img/GT\" # dirOut = r\"../../../data/udacity/labels_noise_patchwise/PCA\" # imgFileEnding = \".jpg\"", "dirIn = r\"../../../data/udacity/img/GT\" # dirOut = r\"../../../data/udacity/labels_noise_patchwise/PCA\" # imgFileEnding =", "noise level estimation of the following paper: <NAME> , <NAME>", "if __name__ == '__main__': # dirIn = r\"../../../data/udacity/img/GT\" # dirOut", "tensor, range [0,1] pch_size: patch_size Output: noise_level: the estimated noise", ", <NAME> , <NAME> . An Efficient Statistical Method for", "estimatedNoiseMap) return estimatedNoiseMap except: return None # Example # if", "temp = im[:, ii:H-pch_H+ii+1:stride_H, jj:W-pch_W+jj+1:stride_W] pch[:, kk, :] = temp.reshape((C,", "for ii in range(pch_H): for jj in range(pch_W): temp =", "num_W = len(range(0, W-pch_W+1, stride_W)) num_pch = num_H * num_W", "imgPath.split(os.sep)[-1].split(\".\")[0] dirOut = os.path.join(dirOut) if not os.path.exists(dirOut): os.makedirs(dirOut) noiseMapPath =", "im: 3 x H x W or 1 X H", "shift_factor = 2 # Result array estimatedNoiseMap = np.zeros([h, w],", "x num_pch matrix d = pch.shape[0] mu = pch.mean(axis=1, keepdims=True)", "a integer or a int tuple!') if isinstance(stride, tuple): stride_H,", "temp.reshape((C, num_pch)) kk += 1 return pch.reshape((C, pch_H, pch_W, num_pch))", "stride_W = stride elif isinstance(stride, int): stride_H = stride_W =", "or H x W numpy tensor, range [0,1] pch_size: patch_size", "to patches. Input: im: 3 x H x W or", "as np import cv2 import sys import os import glob", "1 X H x W image, numpy format pch_size: (int,", "<NAME> , <NAME> , <NAME> . An Efficient Statistical Method", "of pch_size must be a integer or a int tuple!')", "glob def im2patch(im, pch_size, stride=1): ''' Transform image to patches.", "255.0 h, w = img.shape psize = min(min(patchSize, h), w)", "+ \".npz\") if not os.path.exists(noiseMapPath): np.savez_compressed(noiseMapPath, estimatedNoiseMap) return estimatedNoiseMap except:", "following paper: <NAME> , <NAME> , <NAME> . An Efficient", "Computer Vision (ICCV). IEEE Computer Society, 2015. Input: im: the", "input image. :param patchSize: Image patch size. :param internalNumPatches: Internal", "np.zeros([h, w], dtype=np.int8) rangex = range(0, w, patch_step) rangey =", "# Result array estimatedNoiseMap = np.zeros([h, w], dtype=np.int8) rangex =", "sys.exit('The input of pch_size must be a integer or a", "Statistical Method for Image Noise Level Estimation[C]// 2015 IEEE International", "noise_estimate(im, pch_size=8): ''' Implement of noise level estimation of the", "w end_x = shift_factor * ((end_x) // shift_factor) start_x =", "internalNumPatches) * 255.0 estimatedNoiseMap[start_y :start_y + h_, start_x : start_x", ":param imgPath: Path to the input image. :param patchSize: Image", "= np.mean(sig_value[:ii]) if np.sum(sig_value[:ii]>tau) == np.sum(sig_value[:ii] < tau): return np.sqrt(tau)", "start_y = end_y - psize tileM = img[start_y:end_y, start_x:end_x] h_,", "w) psize -= psize % 2 patch_step = psize shift_factor", "pch_W, num_pch)) def noise_estimate(im, pch_size=8): ''' Implement of noise level", "noise estimation results. :param saveResults: Whether to save the estimation", "try: img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) img = img / 255.0", "return None # Example # if __name__ == '__main__': #", "= pch.shape[0] mu = pch.mean(axis=1, keepdims=True) # d x 1", "end_x = shift_factor * ((end_x) // shift_factor) start_x = end_x", "import os import glob def im2patch(im, pch_size, stride=1): ''' Transform", "pch.shape[3] pch = pch.reshape((-1, num_pch)) # d x num_pch matrix", "except: return None # Example # if __name__ == '__main__':", "noise image, H x W x 3 or H x", "def im2patch(im, pch_size, stride=1): ''' Transform image to patches. Input:", "= sigma if saveResults: if dirOut is not None: imgName", "Efficient Statistical Method for Image Noise Level Estimation[C]// 2015 IEEE", "keepdims=True) # d x 1 X = pch - mu", "# C x pch_size x pch_size x num_pch tensor num_pch", "H, W = im.shape num_H = len(range(0, H-pch_H+1, stride_H)) num_W", "// shift_factor) start_x = end_x - psize if end_y >", "import glob def im2patch(im, pch_size, stride=1): ''' Transform image to", "pch_size: patch_size Output: noise_level: the estimated noise level ''' if", "or 1 X H x W image, numpy format pch_size:", "pch_H, pch_W = pch_size elif isinstance(pch_size, int): pch_H = pch_W", "if not os.path.exists(dirOut): os.makedirs(dirOut) noiseMapPath = os.path.join(dirOut, imgName + \".npz\")", "estimated noise level ''' if im.ndim == 3: im =", "tuple or integer ''' if isinstance(pch_size, tuple): pch_H, pch_W =", "where to save the noise estimation results. :param saveResults: Whether", "patch_step) rangey = range(0, h, patch_step) for start_x in rangex:", "# d x 1 X = pch - mu sigma_X", "or not. :return: None \"\"\" # Load image img =", "numpy as np import cv2 import sys import os import", "= np.linalg.eigh(sigma_X) sig_value.sort() for ii in range(-1, -d-1, -1): tau", "np.matmul(X, X.transpose()) / num_pch sig_value, _ = np.linalg.eigh(sigma_X) sig_value.sort() for", "range(0, h, patch_step) for start_x in rangex: for start_y in", "W image, numpy format pch_size: (int, int) tuple or integer", "is estimated patch by patch. Based on: \"An Efficient Statistical", "np.sqrt(tau) def run(imgPath, patchSize, internalNumPatches, dirOut, saveResults=True): \"\"\" Estimates the", "= np.array(cv2.imread(imgPath)) try: img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) img = img", "array estimatedNoiseMap = np.zeros([h, w], dtype=np.int8) rangex = range(0, w,", "of (additive white gaussian) noise of image patches. The noise", "psize = min(min(patchSize, h), w) psize -= psize % 2", "= np.matmul(X, X.transpose()) / num_pch sig_value, _ = np.linalg.eigh(sigma_X) sig_value.sort()", "> h: end_y = h end_y = shift_factor * ((end_y)", "for ii in range(-1, -d-1, -1): tau = np.mean(sig_value[:ii]) if", "import cv2 import sys import os import glob def im2patch(im,", "results. :param saveResults: Whether to save the estimation results or", "deviation of (additive white gaussian) noise of image patches. The", "save the noise estimation results. :param saveResults: Whether to save", "W-pch_W+1, stride_W)) num_pch = num_H * num_W pch = np.zeros((C,", "C x pch_size x pch_size x num_pch tensor num_pch =", "psize % 2 patch_step = psize shift_factor = 2 #", "a int tuple!') if isinstance(stride, tuple): stride_H, stride_W = stride", "is not None: imgName = imgPath.split(os.sep)[-1].split(\".\")[0] dirOut = os.path.join(dirOut) if", "_ = np.linalg.eigh(sigma_X) sig_value.sort() for ii in range(-1, -d-1, -1):", "im = im.transpose((2, 0, 1)) else: im = np.expand_dims(im, axis=0)", "noise_estimate(tileM, internalNumPatches) * 255.0 estimatedNoiseMap[start_y :start_y + h_, start_x :", "(ICCV). IEEE Computer Society, 2015. Input: im: the noise image,", "def run(imgPath, patchSize, internalNumPatches, dirOut, saveResults=True): \"\"\" Estimates the standard", "in range(-1, -d-1, -1): tau = np.mean(sig_value[:ii]) if np.sum(sig_value[:ii]>tau) ==", "X = pch - mu sigma_X = np.matmul(X, X.transpose()) /", "= noise_estimate(tileM, internalNumPatches) * 255.0 estimatedNoiseMap[start_y :start_y + h_, start_x", "= tileM.shape sigma = noise_estimate(tileM, internalNumPatches) * 255.0 estimatedNoiseMap[start_y :start_y", "stride_W)) num_pch = num_H * num_W pch = np.zeros((C, pch_H*pch_W,", "# imgFileEnding = \".jpg\" # for imgPath in glob.glob(os.path.join(dirIn, \"*\"", "= shift_factor * ((end_y) // shift_factor) start_y = end_y -", "= imgPath.split(os.sep)[-1].split(\".\")[0] dirOut = os.path.join(dirOut) if not os.path.exists(dirOut): os.makedirs(dirOut) noiseMapPath", "or integer ''' if isinstance(pch_size, tuple): pch_H, pch_W = pch_size", "IEEE International Conference on Computer Vision (ICCV). IEEE Computer Society,", "the following paper: <NAME> , <NAME> , <NAME> . An", "= stride else: sys.exit('The input of stride must be a", "pch = im2patch(im, pch_size, 3) # C x pch_size x", "tuple!') if isinstance(stride, tuple): stride_H, stride_W = stride elif isinstance(stride,", "for start_x in rangex: for start_y in rangey: end_x =", "Society, 2015. Input: im: the noise image, H x W", "the noise estimation results. :param saveResults: Whether to save the", "Efficient Statistical Method for Image Noise Level Estimation\" (2015) :param", "3 or H x W numpy tensor, range [0,1] pch_size:", "jj:W-pch_W+jj+1:stride_W] pch[:, kk, :] = temp.reshape((C, num_pch)) kk += 1", "end_x > w: end_x = w end_x = shift_factor *", ". An Efficient Statistical Method for Image Noise Level Estimation[C]//", "1)) else: im = np.expand_dims(im, axis=0) # image to patch", "(int, int) tuple or integer stride: (int, int) tuple or", "else: im = np.expand_dims(im, axis=0) # image to patch pch", "dirOut is not None: imgName = imgPath.split(os.sep)[-1].split(\".\")[0] dirOut = os.path.join(dirOut)", "if isinstance(stride, tuple): stride_H, stride_W = stride elif isinstance(stride, int):", "h, w = img.shape psize = min(min(patchSize, h), w) psize", "end_y = shift_factor * ((end_y) // shift_factor) start_y = end_y", "noise_level: the estimated noise level ''' if im.ndim == 3:", "np.sum(sig_value[:ii] < tau): return np.sqrt(tau) def run(imgPath, patchSize, internalNumPatches, dirOut,", "np.mean(sig_value[:ii]) if np.sum(sig_value[:ii]>tau) == np.sum(sig_value[:ii] < tau): return np.sqrt(tau) def", "= os.path.join(dirOut, imgName + \".npz\") if not os.path.exists(noiseMapPath): np.savez_compressed(noiseMapPath, estimatedNoiseMap)", "cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) img = img / 255.0 h, w =", "level estimation of the following paper: <NAME> , <NAME> ,", "range [0,1] pch_size: patch_size Output: noise_level: the estimated noise level", "w_] = sigma if saveResults: if dirOut is not None:", "x pch_size x num_pch tensor num_pch = pch.shape[3] pch =", "0, 1)) else: im = np.expand_dims(im, axis=0) # image to", "for jj in range(pch_W): temp = im[:, ii:H-pch_H+ii+1:stride_H, jj:W-pch_W+jj+1:stride_W] pch[:,", "pch_size x num_pch tensor num_pch = pch.shape[3] pch = pch.reshape((-1,", "to save the estimation results or not. :return: None \"\"\"", "sys.exit('The input of stride must be a integer or a", "tau = np.mean(sig_value[:ii]) if np.sum(sig_value[:ii]>tau) == np.sum(sig_value[:ii] < tau): return", "Estimates the standard deviation of (additive white gaussian) noise of", "the standard deviation of (additive white gaussian) noise of image", "= 2 # Result array estimatedNoiseMap = np.zeros([h, w], dtype=np.int8)", "= np.zeros([h, w], dtype=np.int8) rangex = range(0, w, patch_step) rangey", "int): pch_H = pch_W = pch_size else: sys.exit('The input of", "end_x = w end_x = shift_factor * ((end_x) // shift_factor)", "255.0 estimatedNoiseMap[start_y :start_y + h_, start_x : start_x + w_]", ": start_x + w_] = sigma if saveResults: if dirOut", "Image Noise Level Estimation\" (2015) :param imgPath: Path to the", "Noise Level Estimation\" (2015) :param imgPath: Path to the input", "Load image img = np.array(cv2.imread(imgPath)) try: img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)", "* num_W pch = np.zeros((C, pch_H*pch_W, num_pch), dtype=im.dtype) kk =", "to the input image. :param patchSize: Image patch size. :param", "im.ndim == 3: im = im.transpose((2, 0, 1)) else: im", "mu = pch.mean(axis=1, keepdims=True) # d x 1 X =", "os.makedirs(dirOut) noiseMapPath = os.path.join(dirOut, imgName + \".npz\") if not os.path.exists(noiseMapPath):", "w, patch_step) rangey = range(0, h, patch_step) for start_x in", "(additive white gaussian) noise of image patches. The noise is", "''' Implement of noise level estimation of the following paper:", "(int, int) tuple or integer ''' if isinstance(pch_size, tuple): pch_H,", "in rangey: end_x = start_x + psize end_y = start_y", "for start_y in rangey: end_x = start_x + psize end_y", "im[:, ii:H-pch_H+ii+1:stride_H, jj:W-pch_W+jj+1:stride_W] pch[:, kk, :] = temp.reshape((C, num_pch)) kk", "be a integer or a int tuple!') if isinstance(stride, tuple):", "standard deviation of (additive white gaussian) noise of image patches.", "or a int tuple!') C, H, W = im.shape num_H", "for Image Noise Level Estimation\" (2015) :param imgPath: Path to", "jj in range(pch_W): temp = im[:, ii:H-pch_H+ii+1:stride_H, jj:W-pch_W+jj+1:stride_W] pch[:, kk,", "= end_x - psize if end_y > h: end_y =", "gaussian) noise of image patches. The noise is estimated patch", "image patches. The noise is estimated patch by patch. Based", "Estimation[C]// 2015 IEEE International Conference on Computer Vision (ICCV). IEEE", "2 # Result array estimatedNoiseMap = np.zeros([h, w], dtype=np.int8) rangex", "= img.shape psize = min(min(patchSize, h), w) psize -= psize", "in glob.glob(os.path.join(dirIn, \"*\" + imgFileEnding)): # run(imgPath, 128, 8, dirOut)", "internalNumPatches: Internal number of sub-image-patches. :param dirOut: Directory where to", "paper: <NAME> , <NAME> , <NAME> . An Efficient Statistical", "> w: end_x = w end_x = shift_factor * ((end_x)", ":param dirOut: Directory where to save the noise estimation results.", "if not os.path.exists(noiseMapPath): np.savez_compressed(noiseMapPath, estimatedNoiseMap) return estimatedNoiseMap except: return None", "Implement of noise level estimation of the following paper: <NAME>", "kk += 1 return pch.reshape((C, pch_H, pch_W, num_pch)) def noise_estimate(im,", "= stride elif isinstance(stride, int): stride_H = stride_W = stride", "psize shift_factor = 2 # Result array estimatedNoiseMap = np.zeros([h,", "= h end_y = shift_factor * ((end_y) // shift_factor) start_y", "not None: imgName = imgPath.split(os.sep)[-1].split(\".\")[0] dirOut = os.path.join(dirOut) if not", "of noise level estimation of the following paper: <NAME> ,", "Output: noise_level: the estimated noise level ''' if im.ndim ==", "the input image. :param patchSize: Image patch size. :param internalNumPatches:", "results or not. :return: None \"\"\" # Load image img", "pch = pch.reshape((-1, num_pch)) # d x num_pch matrix d", "cv2 import sys import os import glob def im2patch(im, pch_size,", "saveResults: Whether to save the estimation results or not. :return:", "stride_H)) num_W = len(range(0, W-pch_W+1, stride_W)) num_pch = num_H *", "d = pch.shape[0] mu = pch.mean(axis=1, keepdims=True) # d x", "d x num_pch matrix d = pch.shape[0] mu = pch.mean(axis=1,", "psize if end_x > w: end_x = w end_x =", "np.savez_compressed(noiseMapPath, estimatedNoiseMap) return estimatedNoiseMap except: return None # Example #", "or a int tuple!') if isinstance(stride, tuple): stride_H, stride_W =", "Method for Image Noise Level Estimation[C]// 2015 IEEE International Conference", "(2015) :param imgPath: Path to the input image. :param patchSize:", "The noise is estimated patch by patch. Based on: \"An", "of image patches. The noise is estimated patch by patch.", "start_y + psize if end_x > w: end_x = w", "# Example # if __name__ == '__main__': # dirIn =", "h), w) psize -= psize % 2 patch_step = psize", "stride=1): ''' Transform image to patches. Input: im: 3 x", "return estimatedNoiseMap except: return None # Example # if __name__", "isinstance(stride, tuple): stride_H, stride_W = stride elif isinstance(stride, int): stride_H", "estimatedNoiseMap[start_y :start_y + h_, start_x : start_x + w_] =", "h, patch_step) for start_x in rangex: for start_y in rangey:", "end_y = h end_y = shift_factor * ((end_y) // shift_factor)", "- psize if end_y > h: end_y = h end_y", "pch_size, 3) # C x pch_size x pch_size x num_pch", "tuple or integer stride: (int, int) tuple or integer '''", "3) # C x pch_size x pch_size x num_pch tensor", "+= 1 return pch.reshape((C, pch_H, pch_W, num_pch)) def noise_estimate(im, pch_size=8):", "num_pch sig_value, _ = np.linalg.eigh(sigma_X) sig_value.sort() for ii in range(-1,", "H x W or 1 X H x W image,", "patch. Based on: \"An Efficient Statistical Method for Image Noise", "numpy tensor, range [0,1] pch_size: patch_size Output: noise_level: the estimated", "np.expand_dims(im, axis=0) # image to patch pch = im2patch(im, pch_size,", "the estimation results or not. :return: None \"\"\" # Load", "end_y > h: end_y = h end_y = shift_factor *", "pch.mean(axis=1, keepdims=True) # d x 1 X = pch -", "psize -= psize % 2 patch_step = psize shift_factor =", "os.path.exists(noiseMapPath): np.savez_compressed(noiseMapPath, estimatedNoiseMap) return estimatedNoiseMap except: return None # Example", "os.path.join(dirOut, imgName + \".npz\") if not os.path.exists(noiseMapPath): np.savez_compressed(noiseMapPath, estimatedNoiseMap) return", "tensor num_pch = pch.shape[3] pch = pch.reshape((-1, num_pch)) # d", "not os.path.exists(noiseMapPath): np.savez_compressed(noiseMapPath, estimatedNoiseMap) return estimatedNoiseMap except: return None #", "= pch.mean(axis=1, keepdims=True) # d x 1 X = pch", "''' if isinstance(pch_size, tuple): pch_H, pch_W = pch_size elif isinstance(pch_size,", "imgPath: Path to the input image. :param patchSize: Image patch", "save the estimation results or not. :return: None \"\"\" #", "pch.reshape((-1, num_pch)) # d x num_pch matrix d = pch.shape[0]", "patchSize, internalNumPatches, dirOut, saveResults=True): \"\"\" Estimates the standard deviation of", "num_pch), dtype=im.dtype) kk = 0 for ii in range(pch_H): for", "dirOut = os.path.join(dirOut) if not os.path.exists(dirOut): os.makedirs(dirOut) noiseMapPath = os.path.join(dirOut,", "patchSize: Image patch size. :param internalNumPatches: Internal number of sub-image-patches.", "np import cv2 import sys import os import glob def", "run(imgPath, patchSize, internalNumPatches, dirOut, saveResults=True): \"\"\" Estimates the standard deviation", "if dirOut is not None: imgName = imgPath.split(os.sep)[-1].split(\".\")[0] dirOut =", "im.shape num_H = len(range(0, H-pch_H+1, stride_H)) num_W = len(range(0, W-pch_W+1,", "= len(range(0, W-pch_W+1, stride_W)) num_pch = num_H * num_W pch", "estimation results or not. :return: None \"\"\" # Load image", "sigma = noise_estimate(tileM, internalNumPatches) * 255.0 estimatedNoiseMap[start_y :start_y + h_,", "or integer stride: (int, int) tuple or integer ''' if", "min(min(patchSize, h), w) psize -= psize % 2 patch_step =", "Input: im: the noise image, H x W x 3", "psize end_y = start_y + psize if end_x > w:", "Estimation\" (2015) :param imgPath: Path to the input image. :param", "= range(0, h, patch_step) for start_x in rangex: for start_y", "img[start_y:end_y, start_x:end_x] h_, w_ = tileM.shape sigma = noise_estimate(tileM, internalNumPatches)", "sig_value, _ = np.linalg.eigh(sigma_X) sig_value.sort() for ii in range(-1, -d-1,", "internalNumPatches, dirOut, saveResults=True): \"\"\" Estimates the standard deviation of (additive", "start_x + psize end_y = start_y + psize if end_x", "= pch.reshape((-1, num_pch)) # d x num_pch matrix d =", "for Image Noise Level Estimation[C]// 2015 IEEE International Conference on", "imgPath in glob.glob(os.path.join(dirIn, \"*\" + imgFileEnding)): # run(imgPath, 128, 8,", "= pch_W = pch_size else: sys.exit('The input of pch_size must", "\".npz\") if not os.path.exists(noiseMapPath): np.savez_compressed(noiseMapPath, estimatedNoiseMap) return estimatedNoiseMap except: return", "= range(0, w, patch_step) rangey = range(0, h, patch_step) for", "in range(pch_W): temp = im[:, ii:H-pch_H+ii+1:stride_H, jj:W-pch_W+jj+1:stride_W] pch[:, kk, :]", "h end_y = shift_factor * ((end_y) // shift_factor) start_y =", "if im.ndim == 3: im = im.transpose((2, 0, 1)) else:", "patch size. :param internalNumPatches: Internal number of sub-image-patches. :param dirOut:", "International Conference on Computer Vision (ICCV). IEEE Computer Society, 2015.", "os.path.exists(dirOut): os.makedirs(dirOut) noiseMapPath = os.path.join(dirOut, imgName + \".npz\") if not", "\".jpg\" # for imgPath in glob.glob(os.path.join(dirIn, \"*\" + imgFileEnding)): #", "start_x + w_] = sigma if saveResults: if dirOut is", "integer or a int tuple!') if isinstance(stride, tuple): stride_H, stride_W", "= \".jpg\" # for imgPath in glob.glob(os.path.join(dirIn, \"*\" + imgFileEnding)):", "image to patches. Input: im: 3 x H x W", "% 2 patch_step = psize shift_factor = 2 # Result", "+ psize if end_x > w: end_x = w end_x", "= im2patch(im, pch_size, 3) # C x pch_size x pch_size", "return np.sqrt(tau) def run(imgPath, patchSize, internalNumPatches, dirOut, saveResults=True): \"\"\" Estimates", "range(pch_W): temp = im[:, ii:H-pch_H+ii+1:stride_H, jj:W-pch_W+jj+1:stride_W] pch[:, kk, :] =", "integer stride: (int, int) tuple or integer ''' if isinstance(pch_size,", "not os.path.exists(dirOut): os.makedirs(dirOut) noiseMapPath = os.path.join(dirOut, imgName + \".npz\") if", "-d-1, -1): tau = np.mean(sig_value[:ii]) if np.sum(sig_value[:ii]>tau) == np.sum(sig_value[:ii] <", "pch_W = pch_size else: sys.exit('The input of pch_size must be", "on Computer Vision (ICCV). IEEE Computer Society, 2015. Input: im:", "elif isinstance(stride, int): stride_H = stride_W = stride else: sys.exit('The", "int): stride_H = stride_W = stride else: sys.exit('The input of", "dirOut, saveResults=True): \"\"\" Estimates the standard deviation of (additive white", "img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) img = img / 255.0 h,", "imgName + \".npz\") if not os.path.exists(noiseMapPath): np.savez_compressed(noiseMapPath, estimatedNoiseMap) return estimatedNoiseMap", "__name__ == '__main__': # dirIn = r\"../../../data/udacity/img/GT\" # dirOut =", "int tuple!') if isinstance(stride, tuple): stride_H, stride_W = stride elif", "sigma_X = np.matmul(X, X.transpose()) / num_pch sig_value, _ = np.linalg.eigh(sigma_X)", "number of sub-image-patches. :param dirOut: Directory where to save the", "not. :return: None \"\"\" # Load image img = np.array(cv2.imread(imgPath))", "H-pch_H+1, stride_H)) num_W = len(range(0, W-pch_W+1, stride_W)) num_pch = num_H", "patch by patch. Based on: \"An Efficient Statistical Method for", "\"An Efficient Statistical Method for Image Noise Level Estimation\" (2015)", "= pch.shape[3] pch = pch.reshape((-1, num_pch)) # d x num_pch", "np.zeros((C, pch_H*pch_W, num_pch), dtype=im.dtype) kk = 0 for ii in", "Input: im: 3 x H x W or 1 X", ":param internalNumPatches: Internal number of sub-image-patches. :param dirOut: Directory where", "'__main__': # dirIn = r\"../../../data/udacity/img/GT\" # dirOut = r\"../../../data/udacity/labels_noise_patchwise/PCA\" #", "else: sys.exit('The input of pch_size must be a integer or", "start_x:end_x] h_, w_ = tileM.shape sigma = noise_estimate(tileM, internalNumPatches) *", "patch pch = im2patch(im, pch_size, 3) # C x pch_size", "num_pch)) kk += 1 return pch.reshape((C, pch_H, pch_W, num_pch)) def", "int tuple!') C, H, W = im.shape num_H = len(range(0,", "tau): return np.sqrt(tau) def run(imgPath, patchSize, internalNumPatches, dirOut, saveResults=True): \"\"\"", "to patch pch = im2patch(im, pch_size, 3) # C x", "if isinstance(pch_size, tuple): pch_H, pch_W = pch_size elif isinstance(pch_size, int):", "# for imgPath in glob.glob(os.path.join(dirIn, \"*\" + imgFileEnding)): # run(imgPath,", "im2patch(im, pch_size, 3) # C x pch_size x pch_size x", "imgFileEnding = \".jpg\" # for imgPath in glob.glob(os.path.join(dirIn, \"*\" +", "if end_x > w: end_x = w end_x = shift_factor", "integer or a int tuple!') C, H, W = im.shape", "estimation of the following paper: <NAME> , <NAME> , <NAME>", "<NAME> , <NAME> . An Efficient Statistical Method for Image", "image. :param patchSize: Image patch size. :param internalNumPatches: Internal number", "must be a integer or a int tuple!') if isinstance(stride,", "pch_size else: sys.exit('The input of pch_size must be a integer", "must be a integer or a int tuple!') C, H,", "# if __name__ == '__main__': # dirIn = r\"../../../data/udacity/img/GT\" #", "= stride_W = stride else: sys.exit('The input of stride must", "im2patch(im, pch_size, stride=1): ''' Transform image to patches. Input: im:", "shift_factor) start_y = end_y - psize tileM = img[start_y:end_y, start_x:end_x]", "[0,1] pch_size: patch_size Output: noise_level: the estimated noise level '''", "/ num_pch sig_value, _ = np.linalg.eigh(sigma_X) sig_value.sort() for ii in", "-1): tau = np.mean(sig_value[:ii]) if np.sum(sig_value[:ii]>tau) == np.sum(sig_value[:ii] < tau):", "d x 1 X = pch - mu sigma_X =", "stride must be a integer or a int tuple!') C,", "= img / 255.0 h, w = img.shape psize =", "= len(range(0, H-pch_H+1, stride_H)) num_W = len(range(0, W-pch_W+1, stride_W)) num_pch", "Result array estimatedNoiseMap = np.zeros([h, w], dtype=np.int8) rangex = range(0,", "= shift_factor * ((end_x) // shift_factor) start_x = end_x -", "= img[start_y:end_y, start_x:end_x] h_, w_ = tileM.shape sigma = noise_estimate(tileM,", "ii in range(-1, -d-1, -1): tau = np.mean(sig_value[:ii]) if np.sum(sig_value[:ii]>tau)", "pch_size, stride=1): ''' Transform image to patches. Input: im: 3", "end_x = start_x + psize end_y = start_y + psize", "Computer Society, 2015. Input: im: the noise image, H x", "import numpy as np import cv2 import sys import os", "image img = np.array(cv2.imread(imgPath)) try: img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) img", "= im.shape num_H = len(range(0, H-pch_H+1, stride_H)) num_W = len(range(0,", "Whether to save the estimation results or not. :return: None", "= start_y + psize if end_x > w: end_x =", "dirOut: Directory where to save the noise estimation results. :param", "pch_size: (int, int) tuple or integer stride: (int, int) tuple", "= pch_size else: sys.exit('The input of pch_size must be a", "stride else: sys.exit('The input of stride must be a integer", "x 3 or H x W numpy tensor, range [0,1]", "im.transpose((2, 0, 1)) else: im = np.expand_dims(im, axis=0) # image", "= w end_x = shift_factor * ((end_x) // shift_factor) start_x", "tuple): stride_H, stride_W = stride elif isinstance(stride, int): stride_H =", "-= psize % 2 patch_step = psize shift_factor = 2", "x W image, numpy format pch_size: (int, int) tuple or", "None \"\"\" # Load image img = np.array(cv2.imread(imgPath)) try: img", "to save the noise estimation results. :param saveResults: Whether to", "rangex: for start_y in rangey: end_x = start_x + psize", ":] = temp.reshape((C, num_pch)) kk += 1 return pch.reshape((C, pch_H,", "size. :param internalNumPatches: Internal number of sub-image-patches. :param dirOut: Directory", "x H x W or 1 X H x W", "be a integer or a int tuple!') C, H, W", "dirOut = r\"../../../data/udacity/labels_noise_patchwise/PCA\" # imgFileEnding = \".jpg\" # for imgPath", "1 X = pch - mu sigma_X = np.matmul(X, X.transpose())", "of sub-image-patches. :param dirOut: Directory where to save the noise", "stride_W = stride else: sys.exit('The input of stride must be", "num_pch)) def noise_estimate(im, pch_size=8): ''' Implement of noise level estimation", "estimatedNoiseMap except: return None # Example # if __name__ ==", "num_pch tensor num_pch = pch.shape[3] pch = pch.reshape((-1, num_pch)) #", "end_x - psize if end_y > h: end_y = h", "import sys import os import glob def im2patch(im, pch_size, stride=1):", "start_y in rangey: end_x = start_x + psize end_y =", "= np.expand_dims(im, axis=0) # image to patch pch = im2patch(im,", "Transform image to patches. Input: im: 3 x H x", "int) tuple or integer ''' if isinstance(pch_size, tuple): pch_H, pch_W", "w = img.shape psize = min(min(patchSize, h), w) psize -=", "# dirIn = r\"../../../data/udacity/img/GT\" # dirOut = r\"../../../data/udacity/labels_noise_patchwise/PCA\" # imgFileEnding", "x 1 X = pch - mu sigma_X = np.matmul(X,", "estimation results. :param saveResults: Whether to save the estimation results", "- mu sigma_X = np.matmul(X, X.transpose()) / num_pch sig_value, _", "end_y = start_y + psize if end_x > w: end_x", "- psize tileM = img[start_y:end_y, start_x:end_x] h_, w_ = tileM.shape", "pch_size=8): ''' Implement of noise level estimation of the following", "isinstance(pch_size, tuple): pch_H, pch_W = pch_size elif isinstance(pch_size, int): pch_H", "num_H * num_W pch = np.zeros((C, pch_H*pch_W, num_pch), dtype=im.dtype) kk", "img = img / 255.0 h, w = img.shape psize", "num_pch = pch.shape[3] pch = pch.reshape((-1, num_pch)) # d x", "pch = np.zeros((C, pch_H*pch_W, num_pch), dtype=im.dtype) kk = 0 for", "sig_value.sort() for ii in range(-1, -d-1, -1): tau = np.mean(sig_value[:ii])", "An Efficient Statistical Method for Image Noise Level Estimation[C]// 2015", "x W or 1 X H x W image, numpy", "pch_W = pch_size elif isinstance(pch_size, int): pch_H = pch_W =", "rangey = range(0, h, patch_step) for start_x in rangex: for", "stride_H, stride_W = stride elif isinstance(stride, int): stride_H = stride_W", "mu sigma_X = np.matmul(X, X.transpose()) / num_pch sig_value, _ =", "Image Noise Level Estimation[C]// 2015 IEEE International Conference on Computer", "pch_H = pch_W = pch_size else: sys.exit('The input of pch_size", "2015. Input: im: the noise image, H x W x", "imgName = imgPath.split(os.sep)[-1].split(\".\")[0] dirOut = os.path.join(dirOut) if not os.path.exists(dirOut): os.makedirs(dirOut)", "else: sys.exit('The input of stride must be a integer or", "len(range(0, W-pch_W+1, stride_W)) num_pch = num_H * num_W pch =", "tileM = img[start_y:end_y, start_x:end_x] h_, w_ = tileM.shape sigma =", "= temp.reshape((C, num_pch)) kk += 1 return pch.reshape((C, pch_H, pch_W,", "range(0, w, patch_step) rangey = range(0, h, patch_step) for start_x", "shift_factor * ((end_y) // shift_factor) start_y = end_y - psize", "patches. The noise is estimated patch by patch. Based on:", "if saveResults: if dirOut is not None: imgName = imgPath.split(os.sep)[-1].split(\".\")[0]", "int) tuple or integer stride: (int, int) tuple or integer", "tuple!') C, H, W = im.shape num_H = len(range(0, H-pch_H+1,", "<reponame>MaikWischow/Camera-Condition-Monitoring<gh_stars>1-10 import numpy as np import cv2 import sys import", "pch - mu sigma_X = np.matmul(X, X.transpose()) / num_pch sig_value,", "= im.transpose((2, 0, 1)) else: im = np.expand_dims(im, axis=0) #", "= np.zeros((C, pch_H*pch_W, num_pch), dtype=im.dtype) kk = 0 for ii", "= r\"../../../data/udacity/labels_noise_patchwise/PCA\" # imgFileEnding = \".jpg\" # for imgPath in", ", <NAME> . An Efficient Statistical Method for Image Noise", "# d x num_pch matrix d = pch.shape[0] mu =", "h_, w_ = tileM.shape sigma = noise_estimate(tileM, internalNumPatches) * 255.0", ":return: None \"\"\" # Load image img = np.array(cv2.imread(imgPath)) try:", "patch_size Output: noise_level: the estimated noise level ''' if im.ndim", "w_ = tileM.shape sigma = noise_estimate(tileM, internalNumPatches) * 255.0 estimatedNoiseMap[start_y", "< tau): return np.sqrt(tau) def run(imgPath, patchSize, internalNumPatches, dirOut, saveResults=True):", "cv2.COLOR_RGB2GRAY) img = img / 255.0 h, w = img.shape", "img.shape psize = min(min(patchSize, h), w) psize -= psize %", "num_pch matrix d = pch.shape[0] mu = pch.mean(axis=1, keepdims=True) #", "noiseMapPath = os.path.join(dirOut, imgName + \".npz\") if not os.path.exists(noiseMapPath): np.savez_compressed(noiseMapPath,", "IEEE Computer Society, 2015. Input: im: the noise image, H", "on: \"An Efficient Statistical Method for Image Noise Level Estimation\"", "= pch_size elif isinstance(pch_size, int): pch_H = pch_W = pch_size", "return pch.reshape((C, pch_H, pch_W, num_pch)) def noise_estimate(im, pch_size=8): ''' Implement", "np.sum(sig_value[:ii]>tau) == np.sum(sig_value[:ii] < tau): return np.sqrt(tau) def run(imgPath, patchSize,", "= start_x + psize end_y = start_y + psize if", "img = np.array(cv2.imread(imgPath)) try: img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) img =", "sigma if saveResults: if dirOut is not None: imgName =", "2015 IEEE International Conference on Computer Vision (ICCV). IEEE Computer", "tileM.shape sigma = noise_estimate(tileM, internalNumPatches) * 255.0 estimatedNoiseMap[start_y :start_y +", "= im[:, ii:H-pch_H+ii+1:stride_H, jj:W-pch_W+jj+1:stride_W] pch[:, kk, :] = temp.reshape((C, num_pch))", "((end_y) // shift_factor) start_y = end_y - psize tileM =", "2 patch_step = psize shift_factor = 2 # Result array", "== np.sum(sig_value[:ii] < tau): return np.sqrt(tau) def run(imgPath, patchSize, internalNumPatches,", "X H x W image, numpy format pch_size: (int, int)", "a int tuple!') C, H, W = im.shape num_H =", "H x W x 3 or H x W numpy", "the estimated noise level ''' if im.ndim == 3: im", "== '__main__': # dirIn = r\"../../../data/udacity/img/GT\" # dirOut = r\"../../../data/udacity/labels_noise_patchwise/PCA\"", "Statistical Method for Image Noise Level Estimation\" (2015) :param imgPath:", "in range(pch_H): for jj in range(pch_W): temp = im[:, ii:H-pch_H+ii+1:stride_H,", "stride: (int, int) tuple or integer ''' if isinstance(pch_size, tuple):", "def noise_estimate(im, pch_size=8): ''' Implement of noise level estimation of", "patches. Input: im: 3 x H x W or 1", "dtype=im.dtype) kk = 0 for ii in range(pch_H): for jj", "Directory where to save the noise estimation results. :param saveResults:", "None # Example # if __name__ == '__main__': # dirIn", "<NAME> . An Efficient Statistical Method for Image Noise Level", "x W x 3 or H x W numpy tensor,", "= min(min(patchSize, h), w) psize -= psize % 2 patch_step", "if end_y > h: end_y = h end_y = shift_factor", "a integer or a int tuple!') C, H, W =", "num_W pch = np.zeros((C, pch_H*pch_W, num_pch), dtype=im.dtype) kk = 0", "patch_step = psize shift_factor = 2 # Result array estimatedNoiseMap", "Vision (ICCV). IEEE Computer Society, 2015. Input: im: the noise", "image, numpy format pch_size: (int, int) tuple or integer stride:", "noise level ''' if im.ndim == 3: im = im.transpose((2,", "ii:H-pch_H+ii+1:stride_H, jj:W-pch_W+jj+1:stride_W] pch[:, kk, :] = temp.reshape((C, num_pch)) kk +=", "pch.reshape((C, pch_H, pch_W, num_pch)) def noise_estimate(im, pch_size=8): ''' Implement of", "r\"../../../data/udacity/img/GT\" # dirOut = r\"../../../data/udacity/labels_noise_patchwise/PCA\" # imgFileEnding = \".jpg\" #", "saveResults: if dirOut is not None: imgName = imgPath.split(os.sep)[-1].split(\".\")[0] dirOut", "of stride must be a integer or a int tuple!')", "x pch_size x pch_size x num_pch tensor num_pch = pch.shape[3]", "pch.shape[0] mu = pch.mean(axis=1, keepdims=True) # d x 1 X", "Path to the input image. :param patchSize: Image patch size.", "W = im.shape num_H = len(range(0, H-pch_H+1, stride_H)) num_W =", "1 return pch.reshape((C, pch_H, pch_W, num_pch)) def noise_estimate(im, pch_size=8): '''", "sub-image-patches. :param dirOut: Directory where to save the noise estimation", "rangex = range(0, w, patch_step) rangey = range(0, h, patch_step)", "r\"../../../data/udacity/labels_noise_patchwise/PCA\" # imgFileEnding = \".jpg\" # for imgPath in glob.glob(os.path.join(dirIn,", "+ h_, start_x : start_x + w_] = sigma if", "np.linalg.eigh(sigma_X) sig_value.sort() for ii in range(-1, -d-1, -1): tau =", "pch_size elif isinstance(pch_size, int): pch_H = pch_W = pch_size else:", "estimatedNoiseMap = np.zeros([h, w], dtype=np.int8) rangex = range(0, w, patch_step)", "shift_factor) start_x = end_x - psize if end_y > h:", "w], dtype=np.int8) rangex = range(0, w, patch_step) rangey = range(0,", "None: imgName = imgPath.split(os.sep)[-1].split(\".\")[0] dirOut = os.path.join(dirOut) if not os.path.exists(dirOut):", "X.transpose()) / num_pch sig_value, _ = np.linalg.eigh(sigma_X) sig_value.sort() for ii", "axis=0) # image to patch pch = im2patch(im, pch_size, 3)", "numpy format pch_size: (int, int) tuple or integer stride: (int," ]
[ "the specified states: >>> @requires_state(AppState.RUNNING | AppState.FINISHED) ... def function(self):", "AppState changes to *FINISHED*. This is checked via the :class:`Application`", "self._state = AppState.JOINED self.clean_up() @requires_state(AppState.RUNNING | AppState.FINISHED) def cancel(self): \"\"\"", "self.clean_up() @requires_state(AppState.RUNNING | AppState.FINISHED) def cancel(self): \"\"\" Cancel the application", "*JOINED*. This can only be done from the *RUNNING* or", "an external piece of runnable software in any sense. Subclasses", "\"\"\" Check if the application has finished. PROTECTED: Override when", "= auto() FINISHED = auto() JOINED = auto() CANCELLED =", "the application has finished. PROTECTED: Override when inheriting. Returns -------", "for methods of :class:`Application` subclasses that raises an :class:`AppStateError` in", "interval : float Time (in seconds) between calls of :func:`is_finished()`", "= AppState.CANCELLED raise else: self._state = AppState.JOINED self.clean_up() @requires_state(AppState.RUNNING |", "otherwise \"\"\" pass @abc.abstractmethod def wait_interval(self): \"\"\" The time interval", "PROTECTED: Override when inheriting. Returns ------- finished : bool True", "[\"Application\", \"AppStateError\", \"TimeoutError\", \"VersionError\", \"AppState\", \"requires_state\"] import abc import time", "self.cancel() raise TimeoutError( f\"The application expired its timeout \" f\"({timeout:.1f}", "AppState.FINISHED) ... def function(self): ... pass \"\"\" def decorator(func): @wraps(func)", "wraps from enum import Flag, auto class AppState(Flag): \"\"\" This", "is *RUNNING*, this method waits until the application is *FINISHED*.", "or *FINISHED* state. \"\"\" self._state = AppState.CANCELLED self.clean_up() def get_app_state(self):", "Parameters ---------- timeout : float, optional If this parameter is", "enum type represents the app states of an application. \"\"\"", "terminates. PROTECTED: Optionally override when inheriting. \"\"\" pass class AppStateError(Exception):", "the current app state. Returns ------- app_state : AppState The", "current app state. \"\"\" if self._state == AppState.RUNNING: if self.is_finished():", "def is_finished(self): \"\"\" Check if the application has finished. PROTECTED:", "timeout is not None and time.time()-self._start_time > timeout: self.cancel() raise", "when inheriting. Returns ------- finished : bool True of the", ":class:`Application` is not in the specified :class:`AppState` `app_state`. Parameters ----------", "finished, false otherwise \"\"\" pass @abc.abstractmethod def wait_interval(self): \"\"\" The", "Indicate that the application lifecycle was violated. \"\"\" pass class", "\"TimeoutError\", \"VersionError\", \"AppState\", \"requires_state\"] import abc import time from functools", "this abstract base class specify the respective kind of software", "raised and the application is cancelled. Raises ------ TimeoutError If", "def evaluate(self): \"\"\" Evaluate application results. Called in :func:`join()`. PROTECTED:", "AppState.CANCELLED self.clean_up() def get_app_state(self): \"\"\" Get the current app state.", "self._state = AppState.FINISHED return self._state @abc.abstractmethod def run(self): \"\"\" Commence", "and :func:`join()` other Python code can be executed, while the", "the application run and set its state to *RUNNING*. This", "AppState.FINISHED) def join(self, timeout=None): \"\"\" Conclude the application run and", "has finished, false otherwise \"\"\" pass @abc.abstractmethod def wait_interval(self): \"\"\"", "raises an :class:`AppStateError` in case the method is called, when", "termination: Directly after its instantiation the app is in the", ":class:`AppStateError` is called. The application run behaves like an additional", "state is required\" ) return func(*args, **kwargs) return wrapper return", "kind of software and the way of interacting with it.", "PROTECTED: Optionally override when inheriting. \"\"\" pass class AppStateError(Exception): \"\"\"", "to *FINISHED*. This is checked via the :class:`Application` type specific", "'LICENSE.rst' for further # information. __name__ = \"biotite.application\" __author__ =", "call the :func:`join()` method, concluding the application in the *JOINED*", "the joining process. PROTECTED: Override when inheriting. Returns ------- interval", "until this value (in seconds) runs out. After this time", "run and set its state to *RUNNING*. This can only", "is specified, the :class:`Application` only waits for finishing until this", "the application finishes the AppState changes to *FINISHED*. This is", "= AppState.FINISHED return self._state @abc.abstractmethod def run(self): \"\"\" Commence the", "abstract base class specify the respective kind of software and", "that raises an :class:`AppStateError` in case the method is called,", "the AppState changes to *FINISHED*. This is checked via the", "Application(metaclass=abc.ABCMeta): \"\"\" This class is a wrapper around an external", "def requires_state(app_state): \"\"\" A decorator for methods of :class:`Application` subclasses", "is in {instance.get_app_state()} state, \" f\"but {app_state} state is required\"", "A decorator for methods of :class:`Application` subclasses that raises an", "when in *RUNNING* or *FINISHED* state. \"\"\" self._state = AppState.CANCELLED", "Returns ------- interval : float Time (in seconds) between calls", "method, too, but there are no accessible results. If a", "in one of the specified states: >>> @requires_state(AppState.RUNNING | AppState.FINISHED)", "the 3-Clause BSD License. Please see 'LICENSE.rst' for further #", "the application is *FINISHED* the joining process happens immediately, if", "*FINISHED* the joining process happens immediately, if otherwise the application", "Indicate that the application's timeout expired. \"\"\" pass class VersionError(Exception):", "is checked via the :class:`Application` type specific :func:`is_finished()` method. The", "no accessible results. If a method is called in an", "If the joining process exceeds the `timeout` value. \"\"\" time.sleep(self.wait_interval())", "finished. PROTECTED: Override when inheriting. Returns ------- finished : bool", "app state. Examples -------- Raises :class:`AppStateError` when `function` is called,", "if self._state == AppState.RUNNING: if self.is_finished(): self._state = AppState.FINISHED return", "state to *JOINED*. This can only be done from the", "the joining process happens immediately, if otherwise the application is", "self.clean_up() def get_app_state(self): \"\"\" Get the current app state. Returns", "Called in :func:`join()`. PROTECTED: Override when inheriting. \"\"\" pass def", "\"\"\" This class is a wrapper around an external piece", "Called in :func:`start()`. PROTECTED: Override when inheriting. \"\"\" pass @abc.abstractmethod", ":class:`AppStateError` in case the method is called, when the :class:`Application`", "be done from the *CREATED* state. \"\"\" self.run() self._start_time =", "run. After the user calls the :func:`start()` method, the app", ") return func(*args, **kwargs) return wrapper return decorator class Application(metaclass=abc.ABCMeta):", "after its instantiation the app is in the *CREATED* state.", "*FINISHED*. Parameters ---------- timeout : float, optional If this parameter", "def decorator(func): @wraps(func) def wrapper(*args, **kwargs): # First parameter of", "time.sleep(self.wait_interval()) try: self.evaluate() except AppStateError: raise except: self._state = AppState.CANCELLED", "has finished. PROTECTED: Override when inheriting. Returns ------- finished :", "unsuitable app state, an :class:`AppStateError` is called. The application run", "decorator for methods of :class:`Application` subclasses that raises an :class:`AppStateError`", "app state. Returns ------- app_state : AppState The current app", "After this time is exceeded a :class:`TimeoutError` is raised and", "run. Called in :func:`start()`. PROTECTED: Override when inheriting. \"\"\" pass", "to *RUNNING* and the :class:`Application` type specific :func:`run()` method is", "the application lifecycle was violated. \"\"\" pass class TimeoutError(Exception): \"\"\"", "time.time() self._state = AppState.RUNNING @requires_state(AppState.RUNNING | AppState.FINISHED) def join(self, timeout=None):", "the application when in *RUNNING* or *FINISHED* state. \"\"\" self._state", "wrapper(*args, **kwargs): # First parameter of method is always 'self'", "function(self): ... pass \"\"\" def decorator(func): @wraps(func) def wrapper(*args, **kwargs):", "parameters can be set for the application run. After the", "into the *JOINED* state as soon as the application reaches", "in case the method is called, when the :class:`Application` is", "method is always 'self' instance = args[0] if not instance._state", "is called, if :class:`Application` is not in one of the", "when inheriting. \"\"\" pass def clean_up(self): \"\"\" Do clean up", "RUNNING = auto() FINISHED = auto() JOINED = auto() CANCELLED", "else: self._state = AppState.JOINED self.clean_up() @requires_state(AppState.RUNNING | AppState.FINISHED) def cancel(self):", ":class:`TimeoutError` is raised and the application is cancelled. Raises ------", "the way of interacting with it. Every :class:`Application` runs through", "time.time()-self._start_time > timeout: self.cancel() raise TimeoutError( f\"The application expired its", "see 'LICENSE.rst' for further # information. __name__ = \"biotite.application\" __author__", "in the *RUNNING* state: This will constantly check :func:`is_finished()` and", "not in the specified :class:`AppState` `app_state`. Parameters ---------- app_state :", "the *CREATED* state. \"\"\" self.run() self._start_time = time.time() self._state =", "in the *CANCELLED* state. This triggers the :func:`clean_up()` method, too,", "different app states (instances of enum :class:`AppState`) from its creation", "of the application has finished, false otherwise \"\"\" pass @abc.abstractmethod", "__name__ = \"biotite.application\" __author__ = \"<NAME>\" __all__ = [\"Application\", \"AppStateError\",", "this parameter is specified, the :class:`Application` only waits for finishing", "Raises :class:`AppStateError` when `function` is called, if :class:`Application` is not", "---------- app_state : AppState The required app state. Examples --------", "AppState The current app state. \"\"\" if self._state == AppState.RUNNING:", "be called in the *RUNNING* state: This will constantly check", "app state. \"\"\" if self._state == AppState.RUNNING: if self.is_finished(): self._state", "is always 'self' instance = args[0] if not instance._state &", "parameter of method is always 'self' instance = args[0] if", "the :func:`start()` method, the app state is set to *RUNNING*", "\"\"\" Conclude the application run and set its state to", "def function(self): ... pass \"\"\" def decorator(func): @wraps(func) def wrapper(*args,", "self.run() self._start_time = time.time() self._state = AppState.RUNNING @requires_state(AppState.RUNNING | AppState.FINISHED)", "app state, an :class:`AppStateError` is called. The application run behaves", "its timeout \" f\"({timeout:.1f} s)\" ) else: time.sleep(self.wait_interval()) time.sleep(self.wait_interval()) try:", "executed, while the application runs in the background. \"\"\" def", "application expired its timeout \" f\"({timeout:.1f} s)\" ) else: time.sleep(self.wait_interval())", "AppState.CREATED @requires_state(AppState.CREATED) def start(self): \"\"\" Start the application run and", "Raises ------ TimeoutError If the joining process exceeds the `timeout`", "else: time.sleep(self.wait_interval()) time.sleep(self.wait_interval()) try: self.evaluate() except AppStateError: raise except: self._state", "Commence the application run. Called in :func:`start()`. PROTECTED: Override when", "AppState.FINISHED return self._state @abc.abstractmethod def run(self): \"\"\" Commence the application", "even be called in the *RUNNING* state: This will constantly", "application is in {instance.get_app_state()} state, \" f\"but {app_state} state is", "return self._state @abc.abstractmethod def run(self): \"\"\" Commence the application run.", "& app_state: raise AppStateError( f\"The application is in {instance.get_app_state()} state,", "*RUNNING* or *FINISHED* leaves the application in the *CANCELLED* state.", "\"\"\" time.sleep(self.wait_interval()) while self.get_app_state() != AppState.FINISHED: if timeout is not", "timeout : float, optional If this parameter is specified, the", "of :func:`start()` and :func:`join()` other Python code can be executed,", "When the application finishes the AppState changes to *FINISHED*. This", "is required\" ) return func(*args, **kwargs) return wrapper return decorator", "the app state is set to *RUNNING* and the :class:`Application`", "type represents the app states of an application. \"\"\" CREATED", "specific :func:`evaluate()` method. Furthermore this executes the :class:`Application` type specific", "of :class:`Application` subclasses that raises an :class:`AppStateError` in case the", "an :class:`AppStateError` is called. The application run behaves like an", ": AppState The current app state. \"\"\" if self._state ==", "__init__(self): self._state = AppState.CREATED @requires_state(AppState.CREATED) def start(self): \"\"\" Start the", "if timeout is not None and time.time()-self._start_time > timeout: self.cancel()", "the background. \"\"\" def __init__(self): self._state = AppState.CREATED @requires_state(AppState.CREATED) def", "After the user calls the :func:`start()` method, the app state", "the *CANCELLED* state. This triggers the :func:`clean_up()` method, too, but", "inheriting. \"\"\" pass def clean_up(self): \"\"\" Do clean up work", "\"\"\" Indicate that the application's version is invalid. \"\"\" pass", "application is *FINISHED* the joining process happens immediately, if otherwise", "its creation until its termination: Directly after its instantiation the", "------- interval : float Time (in seconds) between calls of", "the specified :class:`AppState` `app_state`. Parameters ---------- app_state : AppState The", "First parameter of method is always 'self' instance = args[0]", "inheriting. Returns ------- interval : float Time (in seconds) between", ":func:`is_finished()` and will directly go into the *JOINED* state as", "states: >>> @requires_state(AppState.RUNNING | AppState.FINISHED) ... def function(self): ... pass", "interval of :func:`is_finished()` calls in the joining process. PROTECTED: Override", "of enum :class:`AppState`) from its creation until its termination: Directly", "from the *RUNNING* or *FINISHED* state. If the application is", "app_state : AppState The current app state. \"\"\" if self._state", "FINISHED = auto() JOINED = auto() CANCELLED = auto() def", "Parameters ---------- app_state : AppState The required app state. Examples", "3-Clause BSD License. Please see 'LICENSE.rst' for further # information.", "the *RUNNING* state: This will constantly check :func:`is_finished()` and will", "around an external piece of runnable software in any sense.", "external piece of runnable software in any sense. Subclasses of", "timeout: self.cancel() raise TimeoutError( f\"The application expired its timeout \"", "def wait_interval(self): \"\"\" The time interval of :func:`is_finished()` calls in", "= [\"Application\", \"AppStateError\", \"TimeoutError\", \"VersionError\", \"AppState\", \"requires_state\"] import abc import", ":func:`cancel()` method while the application is *RUNNING* or *FINISHED* leaves", "an additional thread: Between the call of :func:`start()` and :func:`join()`", "additional thread: Between the call of :func:`start()` and :func:`join()` other", "self._state = AppState.CREATED @requires_state(AppState.CREATED) def start(self): \"\"\" Start the application", "information. __name__ = \"biotite.application\" __author__ = \"<NAME>\" __all__ = [\"Application\",", "The required app state. Examples -------- Raises :class:`AppStateError` when `function`", "or *FINISHED* leaves the application in the *CANCELLED* state. This", "import abc import time from functools import wraps from enum", "calls in the joining process. PROTECTED: Override when inheriting. Returns", "run(self): \"\"\" Commence the application run. Called in :func:`start()`. PROTECTED:", "state. Examples -------- Raises :class:`AppStateError` when `function` is called, if", "raise AppStateError( f\"The application is in {instance.get_app_state()} state, \" f\"but", "can even be called in the *RUNNING* state: This will", "def wrapper(*args, **kwargs): # First parameter of method is always", "from enum import Flag, auto class AppState(Flag): \"\"\" This enum", "specify the respective kind of software and the way of", "VersionError(Exception): \"\"\" Indicate that the application's version is invalid. \"\"\"", "sense. Subclasses of this abstract base class specify the respective", "This class is a wrapper around an external piece of", "state to *RUNNING*. This can only be done from the", "@abc.abstractmethod def is_finished(self): \"\"\" Check if the application has finished.", "of an application. \"\"\" CREATED = auto() RUNNING = auto()", "while the application is *RUNNING* or *FINISHED* leaves the application", "*RUNNING* state: This will constantly check :func:`is_finished()` and will directly", "\" f\"({timeout:.1f} s)\" ) else: time.sleep(self.wait_interval()) time.sleep(self.wait_interval()) try: self.evaluate() except", "\"\"\" pass @abc.abstractmethod def wait_interval(self): \"\"\" The time interval of", "application's timeout expired. \"\"\" pass class VersionError(Exception): \"\"\" Indicate that", "expired its timeout \" f\"({timeout:.1f} s)\" ) else: time.sleep(self.wait_interval()) time.sleep(self.wait_interval())", "making the results of the application accessible by executing the", "def run(self): \"\"\" Commence the application run. Called in :func:`start()`.", ":func:`is_finished()` in :func:`join()` \"\"\" pass @abc.abstractmethod def evaluate(self): \"\"\" Evaluate", "of runnable software in any sense. Subclasses of this abstract", "Override when inheriting. \"\"\" pass def clean_up(self): \"\"\" Do clean", "{instance.get_app_state()} state, \" f\"but {app_state} state is required\" ) return", "In this state further parameters can be set for the", ":func:`join()` method, concluding the application in the *JOINED* state and", "this value (in seconds) runs out. After this time is", "the application is cancelled. Raises ------ TimeoutError If the joining", "and is distributed # under the 3-Clause BSD License. Please", ": float, optional If this parameter is specified, the :class:`Application`", ":class:`Application` type specific :func:`run()` method is called. When the application", "self.is_finished(): self._state = AppState.FINISHED return self._state @abc.abstractmethod def run(self): \"\"\"", "Override when inheriting. Returns ------- finished : bool True of", "when inheriting. \"\"\" pass class AppStateError(Exception): \"\"\" Indicate that the", "application runs in the background. \"\"\" def __init__(self): self._state =", "not None and time.time()-self._start_time > timeout: self.cancel() raise TimeoutError( f\"The", "the application in the *JOINED* state and making the results", "AppStateError( f\"The application is in {instance.get_app_state()} state, \" f\"but {app_state}", "method. :func:`join()` can even be called in the *RUNNING* state:", "runs in the background. \"\"\" def __init__(self): self._state = AppState.CREATED", "AppStateError: raise except: self._state = AppState.CANCELLED raise else: self._state =", ":func:`join()`. PROTECTED: Override when inheriting. \"\"\" pass def clean_up(self): \"\"\"", "of this abstract base class specify the respective kind of", "joining process exceeds the `timeout` value. \"\"\" time.sleep(self.wait_interval()) while self.get_app_state()", "concluding the application in the *JOINED* state and making the", "runnable software in any sense. Subclasses of this abstract base", "\"biotite.application\" __author__ = \"<NAME>\" __all__ = [\"Application\", \"AppStateError\", \"TimeoutError\", \"VersionError\",", "application. \"\"\" CREATED = auto() RUNNING = auto() FINISHED =", "clean up work after the application terminates. PROTECTED: Optionally override", "violated. \"\"\" pass class TimeoutError(Exception): \"\"\" Indicate that the application's", "AppState.FINISHED) def cancel(self): \"\"\" Cancel the application when in *RUNNING*", "if not instance._state & app_state: raise AppStateError( f\"The application is", "soon as the application reaches the *FINISHED* state. Calling the", "wrapper around an external piece of runnable software in any", "application reaches the *FINISHED* state. Calling the :func:`cancel()` method while", "its termination: Directly after its instantiation the app is in", "raise except: self._state = AppState.CANCELLED raise else: self._state = AppState.JOINED", "\"\"\" if self._state == AppState.RUNNING: if self.is_finished(): self._state = AppState.FINISHED", "class VersionError(Exception): \"\"\" Indicate that the application's version is invalid.", "any sense. Subclasses of this abstract base class specify the", "seconds) between calls of :func:`is_finished()` in :func:`join()` \"\"\" pass @abc.abstractmethod", "of the specified states: >>> @requires_state(AppState.RUNNING | AppState.FINISHED) ... def", "state and making the results of the application accessible by", "immediately, if otherwise the application is *RUNNING*, this method waits", "Between the call of :func:`start()` and :func:`join()` other Python code", "done from the *RUNNING* or *FINISHED* state. If the application", "base class specify the respective kind of software and the", "TimeoutError(Exception): \"\"\" Indicate that the application's timeout expired. \"\"\" pass", "finished : bool True of the application has finished, false", "in the specified :class:`AppState` `app_state`. Parameters ---------- app_state : AppState", "after the application terminates. PROTECTED: Optionally override when inheriting. \"\"\"", "class Application(metaclass=abc.ABCMeta): \"\"\" This class is a wrapper around an", "is *FINISHED*. Parameters ---------- timeout : float, optional If this", "app_state: raise AppStateError( f\"The application is in {instance.get_app_state()} state, \"", "lifecycle was violated. \"\"\" pass class TimeoutError(Exception): \"\"\" Indicate that", "run behaves like an additional thread: Between the call of", "runs through a different app states (instances of enum :class:`AppState`)", "set to *RUNNING* and the :class:`Application` type specific :func:`run()` method", "through a different app states (instances of enum :class:`AppState`) from", "the application runs in the background. \"\"\" def __init__(self): self._state", "until the application is *FINISHED*. Parameters ---------- timeout : float,", "self._state = AppState.CANCELLED self.clean_up() def get_app_state(self): \"\"\" Get the current", "of interacting with it. Every :class:`Application` runs through a different", "\"<NAME>\" __all__ = [\"Application\", \"AppStateError\", \"TimeoutError\", \"VersionError\", \"AppState\", \"requires_state\"] import", "the app states of an application. \"\"\" CREATED = auto()", "time from functools import wraps from enum import Flag, auto", "changes to *FINISHED*. This is checked via the :class:`Application` type", "the application is *RUNNING*, this method waits until the application", "__author__ = \"<NAME>\" __all__ = [\"Application\", \"AppStateError\", \"TimeoutError\", \"VersionError\", \"AppState\",", "when inheriting. Returns ------- interval : float Time (in seconds)", "but there are no accessible results. If a method is", "and set its state to *JOINED*. This can only be", ":func:`join()` can even be called in the *RUNNING* state: This", "the user calls the :func:`start()` method, the app state is", "clean_up(self): \"\"\" Do clean up work after the application terminates.", "called. The application run behaves like an additional thread: Between", ": bool True of the application has finished, false otherwise", "called. When the application finishes the AppState changes to *FINISHED*.", "can only be done from the *CREATED* state. \"\"\" self.run()", "functools import wraps from enum import Flag, auto class AppState(Flag):", ":class:`Application` type specific :func:`is_finished()` method. The user can now call", "The current app state. \"\"\" if self._state == AppState.RUNNING: if", "application has finished. PROTECTED: Override when inheriting. Returns ------- finished", "AppState.FINISHED: if timeout is not None and time.time()-self._start_time > timeout:", "in an unsuitable app state, an :class:`AppStateError` is called. The", "if self.is_finished(): self._state = AppState.FINISHED return self._state @abc.abstractmethod def run(self):", "state: This will constantly check :func:`is_finished()` and will directly go", "specific :func:`clean_up()` method. :func:`join()` can even be called in the", "application has finished, false otherwise \"\"\" pass @abc.abstractmethod def wait_interval(self):", ":func:`evaluate()` method. Furthermore this executes the :class:`Application` type specific :func:`clean_up()`", ":class:`Application` runs through a different app states (instances of enum", "that the application's timeout expired. \"\"\" pass class VersionError(Exception): \"\"\"", "accessible by executing the :class:`Application` type specific :func:`evaluate()` method. Furthermore", "value (in seconds) runs out. After this time is exceeded", "decorator class Application(metaclass=abc.ABCMeta): \"\"\" This class is a wrapper around", "timeout=None): \"\"\" Conclude the application run and set its state", "will directly go into the *JOINED* state as soon as", "seconds) runs out. After this time is exceeded a :class:`TimeoutError`", "set its state to *JOINED*. This can only be done", "auto() RUNNING = auto() FINISHED = auto() JOINED = auto()", "*FINISHED* state. Calling the :func:`cancel()` method while the application is", "between calls of :func:`is_finished()` in :func:`join()` \"\"\" pass @abc.abstractmethod def", "only be done from the *CREATED* state. \"\"\" self.run() self._start_time", "== AppState.RUNNING: if self.is_finished(): self._state = AppState.FINISHED return self._state @abc.abstractmethod", ":func:`start()`. PROTECTED: Override when inheriting. \"\"\" pass @abc.abstractmethod def is_finished(self):", "source code is part of the Biotite package and is", "state. This triggers the :func:`clean_up()` method, too, but there are", "specific :func:`run()` method is called. When the application finishes the", "True of the application has finished, false otherwise \"\"\" pass", "Get the current app state. Returns ------- app_state : AppState", "\"\"\" pass class AppStateError(Exception): \"\"\" Indicate that the application lifecycle", "called, when the :class:`Application` is not in the specified :class:`AppState`", "the application run. After the user calls the :func:`start()` method,", ":func:`clean_up()` method. :func:`join()` can even be called in the *RUNNING*", "in the *CREATED* state. In this state further parameters can", ":class:`Application` is not in one of the specified states: >>>", "def cancel(self): \"\"\" Cancel the application when in *RUNNING* or", ": float Time (in seconds) between calls of :func:`is_finished()` in", "timeout expired. \"\"\" pass class VersionError(Exception): \"\"\" Indicate that the", "License. Please see 'LICENSE.rst' for further # information. __name__ =", "s)\" ) else: time.sleep(self.wait_interval()) time.sleep(self.wait_interval()) try: self.evaluate() except AppStateError: raise", "in the background. \"\"\" def __init__(self): self._state = AppState.CREATED @requires_state(AppState.CREATED)", "while the application runs in the background. \"\"\" def __init__(self):", "\"\"\" Do clean up work after the application terminates. PROTECTED:", "= AppState.RUNNING @requires_state(AppState.RUNNING | AppState.FINISHED) def join(self, timeout=None): \"\"\" Conclude", "only be done from the *RUNNING* or *FINISHED* state. If", "start(self): \"\"\" Start the application run and set its state", "*RUNNING* or *FINISHED* state. If the application is *FINISHED* the", "\"requires_state\"] import abc import time from functools import wraps from", "process exceeds the `timeout` value. \"\"\" time.sleep(self.wait_interval()) while self.get_app_state() !=", "This source code is part of the Biotite package and", "= auto() RUNNING = auto() FINISHED = auto() JOINED =", "further parameters can be set for the application run. After", "is *FINISHED* the joining process happens immediately, if otherwise the", "set its state to *RUNNING*. This can only be done", "the *JOINED* state as soon as the application reaches the", "timeout \" f\"({timeout:.1f} s)\" ) else: time.sleep(self.wait_interval()) time.sleep(self.wait_interval()) try: self.evaluate()", "def join(self, timeout=None): \"\"\" Conclude the application run and set", "*FINISHED*. This is checked via the :class:`Application` type specific :func:`is_finished()`", "in :func:`join()`. PROTECTED: Override when inheriting. \"\"\" pass def clean_up(self):", "under the 3-Clause BSD License. Please see 'LICENSE.rst' for further", "application run. After the user calls the :func:`start()` method, the", "only waits for finishing until this value (in seconds) runs", "TimeoutError If the joining process exceeds the `timeout` value. \"\"\"", "*FINISHED* leaves the application in the *CANCELLED* state. This triggers", "the *FINISHED* state. Calling the :func:`cancel()` method while the application", "class AppState(Flag): \"\"\" This enum type represents the app states", "app is in the *CREATED* state. In this state further", "and time.time()-self._start_time > timeout: self.cancel() raise TimeoutError( f\"The application expired", "inheriting. \"\"\" pass class AppStateError(Exception): \"\"\" Indicate that the application", "specific :func:`is_finished()` method. The user can now call the :func:`join()`", "waits for finishing until this value (in seconds) runs out.", "in :func:`start()`. PROTECTED: Override when inheriting. \"\"\" pass @abc.abstractmethod def", "thread: Between the call of :func:`start()` and :func:`join()` other Python", "Conclude the application run and set its state to *JOINED*.", "\"AppStateError\", \"TimeoutError\", \"VersionError\", \"AppState\", \"requires_state\"] import abc import time from", "| AppState.FINISHED) ... def function(self): ... pass \"\"\" def decorator(func):", "= auto() def requires_state(app_state): \"\"\" A decorator for methods of", "happens immediately, if otherwise the application is *RUNNING*, this method", "(instances of enum :class:`AppState`) from its creation until its termination:", ":func:`join()` other Python code can be executed, while the application", "*JOINED* state and making the results of the application accessible", "import wraps from enum import Flag, auto class AppState(Flag): \"\"\"", "-------- Raises :class:`AppStateError` when `function` is called, if :class:`Application` is", "application in the *CANCELLED* state. This triggers the :func:`clean_up()` method,", "exceeds the `timeout` value. \"\"\" time.sleep(self.wait_interval()) while self.get_app_state() != AppState.FINISHED:", "self.evaluate() except AppStateError: raise except: self._state = AppState.CANCELLED raise else:", "respective kind of software and the way of interacting with", "app state is set to *RUNNING* and the :class:`Application` type", "otherwise the application is *RUNNING*, this method waits until the", "evaluate(self): \"\"\" Evaluate application results. Called in :func:`join()`. PROTECTED: Override", "up work after the application terminates. PROTECTED: Optionally override when", "\"\"\" Indicate that the application's timeout expired. \"\"\" pass class", "Cancel the application when in *RUNNING* or *FINISHED* state. \"\"\"", "class is a wrapper around an external piece of runnable", "cancel(self): \"\"\" Cancel the application when in *RUNNING* or *FINISHED*", "!= AppState.FINISHED: if timeout is not None and time.time()-self._start_time >", "the application terminates. PROTECTED: Optionally override when inheriting. \"\"\" pass", "app_state : AppState The required app state. Examples -------- Raises", "is part of the Biotite package and is distributed #", "is not in the specified :class:`AppState` `app_state`. Parameters ---------- app_state", "func(*args, **kwargs) return wrapper return decorator class Application(metaclass=abc.ABCMeta): \"\"\" This", "If a method is called in an unsuitable app state,", "and the way of interacting with it. Every :class:`Application` runs", "calls the :func:`start()` method, the app state is set to", "states of an application. \"\"\" CREATED = auto() RUNNING =", "application accessible by executing the :class:`Application` type specific :func:`evaluate()` method.", ">>> @requires_state(AppState.RUNNING | AppState.FINISHED) ... def function(self): ... pass \"\"\"", "part of the Biotite package and is distributed # under", "pass def clean_up(self): \"\"\" Do clean up work after the", "the :func:`join()` method, concluding the application in the *JOINED* state", "an application. \"\"\" CREATED = auto() RUNNING = auto() FINISHED", "check :func:`is_finished()` and will directly go into the *JOINED* state", "as soon as the application reaches the *FINISHED* state. Calling", "(in seconds) between calls of :func:`is_finished()` in :func:`join()` \"\"\" pass", "joining process. PROTECTED: Override when inheriting. Returns ------- interval :", "with it. Every :class:`Application` runs through a different app states", ":func:`run()` method is called. When the application finishes the AppState", "If the application is *FINISHED* the joining process happens immediately,", "the `timeout` value. \"\"\" time.sleep(self.wait_interval()) while self.get_app_state() != AppState.FINISHED: if", "wrapper return decorator class Application(metaclass=abc.ABCMeta): \"\"\" This class is a", "from its creation until its termination: Directly after its instantiation", "AppState.JOINED self.clean_up() @requires_state(AppState.RUNNING | AppState.FINISHED) def cancel(self): \"\"\" Cancel the", "override when inheriting. \"\"\" pass class AppStateError(Exception): \"\"\" Indicate that", "@requires_state(AppState.RUNNING | AppState.FINISHED) ... def function(self): ... pass \"\"\" def", "\"\"\" def __init__(self): self._state = AppState.CREATED @requires_state(AppState.CREATED) def start(self): \"\"\"", "@requires_state(AppState.RUNNING | AppState.FINISHED) def join(self, timeout=None): \"\"\" Conclude the application", "or *FINISHED* state. If the application is *FINISHED* the joining", "\"\"\" pass def clean_up(self): \"\"\" Do clean up work after", "can be set for the application run. After the user", "method, the app state is set to *RUNNING* and the", "self._state = AppState.RUNNING @requires_state(AppState.RUNNING | AppState.FINISHED) def join(self, timeout=None): \"\"\"", "states (instances of enum :class:`AppState`) from its creation until its", "state as soon as the application reaches the *FINISHED* state.", "AppState.RUNNING: if self.is_finished(): self._state = AppState.FINISHED return self._state @abc.abstractmethod def", "= \"biotite.application\" __author__ = \"<NAME>\" __all__ = [\"Application\", \"AppStateError\", \"TimeoutError\",", "optional If this parameter is specified, the :class:`Application` only waits", "method waits until the application is *FINISHED*. Parameters ---------- timeout", "pass \"\"\" def decorator(func): @wraps(func) def wrapper(*args, **kwargs): # First", "... def function(self): ... pass \"\"\" def decorator(func): @wraps(func) def", "a wrapper around an external piece of runnable software in", ") else: time.sleep(self.wait_interval()) time.sleep(self.wait_interval()) try: self.evaluate() except AppStateError: raise except:", "specified :class:`AppState` `app_state`. Parameters ---------- app_state : AppState The required", "\"\"\" Evaluate application results. Called in :func:`join()`. PROTECTED: Override when", "application run and set its state to *JOINED*. This can", "application is *RUNNING* or *FINISHED* leaves the application in the", "f\"The application is in {instance.get_app_state()} state, \" f\"but {app_state} state", "*CANCELLED* state. This triggers the :func:`clean_up()` method, too, but there", "application run. Called in :func:`start()`. PROTECTED: Override when inheriting. \"\"\"", "\"\"\" pass @abc.abstractmethod def evaluate(self): \"\"\" Evaluate application results. Called", "the application has finished, false otherwise \"\"\" pass @abc.abstractmethod def", "type specific :func:`clean_up()` method. :func:`join()` can even be called in", "of the application accessible by executing the :class:`Application` type specific", "@wraps(func) def wrapper(*args, **kwargs): # First parameter of method is", "is not in one of the specified states: >>> @requires_state(AppState.RUNNING", "pass class VersionError(Exception): \"\"\" Indicate that the application's version is", "too, but there are no accessible results. If a method", "value. \"\"\" time.sleep(self.wait_interval()) while self.get_app_state() != AppState.FINISHED: if timeout is", "directly go into the *JOINED* state as soon as the", "def get_app_state(self): \"\"\" Get the current app state. Returns -------", "state is set to *RUNNING* and the :class:`Application` type specific", "if the application has finished. PROTECTED: Override when inheriting. Returns", "this method waits until the application is *FINISHED*. Parameters ----------", "done from the *CREATED* state. \"\"\" self.run() self._start_time = time.time()", "is *RUNNING* or *FINISHED* leaves the application in the *CANCELLED*", "\" f\"but {app_state} state is required\" ) return func(*args, **kwargs)", "for further # information. __name__ = \"biotite.application\" __author__ = \"<NAME>\"", "the call of :func:`start()` and :func:`join()` other Python code can", "*RUNNING*, this method waits until the application is *FINISHED*. Parameters", "def clean_up(self): \"\"\" Do clean up work after the application", "accessible results. If a method is called in an unsuitable", "one of the specified states: >>> @requires_state(AppState.RUNNING | AppState.FINISHED) ...", "= \"<NAME>\" __all__ = [\"Application\", \"AppStateError\", \"TimeoutError\", \"VersionError\", \"AppState\", \"requires_state\"]", "(in seconds) runs out. After this time is exceeded a", "------ TimeoutError If the joining process exceeds the `timeout` value.", "f\"({timeout:.1f} s)\" ) else: time.sleep(self.wait_interval()) time.sleep(self.wait_interval()) try: self.evaluate() except AppStateError:", "# This source code is part of the Biotite package", "the :class:`Application` type specific :func:`is_finished()` method. The user can now", "self._state @abc.abstractmethod def run(self): \"\"\" Commence the application run. Called", ":class:`Application` type specific :func:`clean_up()` method. :func:`join()` can even be called", "and making the results of the application accessible by executing", "*JOINED* state as soon as the application reaches the *FINISHED*", "run and set its state to *JOINED*. This can only", "and the application is cancelled. Raises ------ TimeoutError If the", "an unsuitable app state, an :class:`AppStateError` is called. The application", "None and time.time()-self._start_time > timeout: self.cancel() raise TimeoutError( f\"The application", "the *CREATED* state. In this state further parameters can be", "time is exceeded a :class:`TimeoutError` is raised and the application", "*CREATED* state. In this state further parameters can be set", "return decorator class Application(metaclass=abc.ABCMeta): \"\"\" This class is a wrapper", ":class:`AppStateError` when `function` is called, if :class:`Application` is not in", "pass class TimeoutError(Exception): \"\"\" Indicate that the application's timeout expired.", "PROTECTED: Override when inheriting. \"\"\" pass def clean_up(self): \"\"\" Do", "pass @abc.abstractmethod def evaluate(self): \"\"\" Evaluate application results. Called in", "| AppState.FINISHED) def cancel(self): \"\"\" Cancel the application when in", "\"\"\" CREATED = auto() RUNNING = auto() FINISHED = auto()", "This is checked via the :class:`Application` type specific :func:`is_finished()` method.", "= AppState.JOINED self.clean_up() @requires_state(AppState.RUNNING | AppState.FINISHED) def cancel(self): \"\"\" Cancel", "can be executed, while the application runs in the background.", "application is cancelled. Raises ------ TimeoutError If the joining process", "\"\"\" Get the current app state. Returns ------- app_state :", "------- finished : bool True of the application has finished,", "an :class:`AppStateError` in case the method is called, when the", "raise else: self._state = AppState.JOINED self.clean_up() @requires_state(AppState.RUNNING | AppState.FINISHED) def", "can now call the :func:`join()` method, concluding the application in", "of software and the way of interacting with it. Every", "this time is exceeded a :class:`TimeoutError` is raised and the", "app states (instances of enum :class:`AppState`) from its creation until", "method, concluding the application in the *JOINED* state and making", "= args[0] if not instance._state & app_state: raise AppStateError( f\"The", "self._start_time = time.time() self._state = AppState.RUNNING @requires_state(AppState.RUNNING | AppState.FINISHED) def", "application run and set its state to *RUNNING*. This can", "background. \"\"\" def __init__(self): self._state = AppState.CREATED @requires_state(AppState.CREATED) def start(self):", "state. Calling the :func:`cancel()` method while the application is *RUNNING*", "**kwargs) return wrapper return decorator class Application(metaclass=abc.ABCMeta): \"\"\" This class", "\"\"\" pass @abc.abstractmethod def is_finished(self): \"\"\" Check if the application", "the Biotite package and is distributed # under the 3-Clause", "The application run behaves like an additional thread: Between the", ":func:`is_finished()` method. The user can now call the :func:`join()` method,", "is cancelled. Raises ------ TimeoutError If the joining process exceeds", "the application's timeout expired. \"\"\" pass class VersionError(Exception): \"\"\" Indicate", "subclasses that raises an :class:`AppStateError` in case the method is", "piece of runnable software in any sense. Subclasses of this", "results of the application accessible by executing the :class:`Application` type", "decorator(func): @wraps(func) def wrapper(*args, **kwargs): # First parameter of method", "auto() def requires_state(app_state): \"\"\" A decorator for methods of :class:`Application`", "method is called, when the :class:`Application` is not in the", "it. Every :class:`Application` runs through a different app states (instances", "for finishing until this value (in seconds) runs out. After", "def start(self): \"\"\" Start the application run and set its", "float, optional If this parameter is specified, the :class:`Application` only", "creation until its termination: Directly after its instantiation the app", "*CREATED* state. \"\"\" self.run() self._start_time = time.time() self._state = AppState.RUNNING", "is exceeded a :class:`TimeoutError` is raised and the application is", "Optionally override when inheriting. \"\"\" pass class AppStateError(Exception): \"\"\" Indicate", "in {instance.get_app_state()} state, \" f\"but {app_state} state is required\" )", "the application reaches the *FINISHED* state. Calling the :func:`cancel()` method", "f\"The application expired its timeout \" f\"({timeout:.1f} s)\" ) else:", "class specify the respective kind of software and the way", "executes the :class:`Application` type specific :func:`clean_up()` method. :func:`join()` can even", "`app_state`. Parameters ---------- app_state : AppState The required app state.", "instantiation the app is in the *CREATED* state. In this", "\"\"\" Start the application run and set its state to", "the *RUNNING* or *FINISHED* state. If the application is *FINISHED*", "{app_state} state is required\" ) return func(*args, **kwargs) return wrapper", "AppState The required app state. Examples -------- Raises :class:`AppStateError` when", "JOINED = auto() CANCELLED = auto() def requires_state(app_state): \"\"\" A", "is distributed # under the 3-Clause BSD License. Please see", "other Python code can be executed, while the application runs", "called in the *RUNNING* state: This will constantly check :func:`is_finished()`", "AppState.CANCELLED raise else: self._state = AppState.JOINED self.clean_up() @requires_state(AppState.RUNNING | AppState.FINISHED)", "Calling the :func:`cancel()` method while the application is *RUNNING* or", "state. Returns ------- app_state : AppState The current app state.", "AppStateError(Exception): \"\"\" Indicate that the application lifecycle was violated. \"\"\"", "a :class:`TimeoutError` is raised and the application is cancelled. Raises", "pass @abc.abstractmethod def is_finished(self): \"\"\" Check if the application has", "required app state. Examples -------- Raises :class:`AppStateError` when `function` is", "joining process happens immediately, if otherwise the application is *RUNNING*,", ": AppState The required app state. Examples -------- Raises :class:`AppStateError`", ":func:`join()` \"\"\" pass @abc.abstractmethod def evaluate(self): \"\"\" Evaluate application results.", "Every :class:`Application` runs through a different app states (instances of", "... pass \"\"\" def decorator(func): @wraps(func) def wrapper(*args, **kwargs): #", ":class:`Application` type specific :func:`evaluate()` method. Furthermore this executes the :class:`Application`", "is called in an unsuitable app state, an :class:`AppStateError` is", "bool True of the application has finished, false otherwise \"\"\"", "expired. \"\"\" pass class VersionError(Exception): \"\"\" Indicate that the application's", "user can now call the :func:`join()` method, concluding the application", "__all__ = [\"Application\", \"AppStateError\", \"TimeoutError\", \"VersionError\", \"AppState\", \"requires_state\"] import abc", "auto class AppState(Flag): \"\"\" This enum type represents the app", "the application accessible by executing the :class:`Application` type specific :func:`evaluate()`", "def __init__(self): self._state = AppState.CREATED @requires_state(AppState.CREATED) def start(self): \"\"\" Start", "raise TimeoutError( f\"The application expired its timeout \" f\"({timeout:.1f} s)\"", "code is part of the Biotite package and is distributed", "can only be done from the *RUNNING* or *FINISHED* state.", "method while the application is *RUNNING* or *FINISHED* leaves the", "Returns ------- app_state : AppState The current app state. \"\"\"", "enum :class:`AppState`) from its creation until its termination: Directly after", ":func:`is_finished()` calls in the joining process. PROTECTED: Override when inheriting.", "the :class:`Application` type specific :func:`run()` method is called. When the", "is called. The application run behaves like an additional thread:", "of :func:`is_finished()` calls in the joining process. PROTECTED: Override when", "its instantiation the app is in the *CREATED* state. In", "class AppStateError(Exception): \"\"\" Indicate that the application lifecycle was violated.", "\"AppState\", \"requires_state\"] import abc import time from functools import wraps", "for the application run. After the user calls the :func:`start()`", "way of interacting with it. Every :class:`Application` runs through a", "now call the :func:`join()` method, concluding the application in the", "via the :class:`Application` type specific :func:`is_finished()` method. The user can", "Directly after its instantiation the app is in the *CREATED*", "while self.get_app_state() != AppState.FINISHED: if timeout is not None and", "AppState(Flag): \"\"\" This enum type represents the app states of", "checked via the :class:`Application` type specific :func:`is_finished()` method. The user", "Returns ------- finished : bool True of the application has", "= AppState.CREATED @requires_state(AppState.CREATED) def start(self): \"\"\" Start the application run", "are no accessible results. If a method is called in", "\"\"\" Commence the application run. Called in :func:`start()`. PROTECTED: Override", "Do clean up work after the application terminates. PROTECTED: Optionally", "code can be executed, while the application runs in the", "@requires_state(AppState.RUNNING | AppState.FINISHED) def cancel(self): \"\"\" Cancel the application when", ":class:`AppState`) from its creation until its termination: Directly after its", "methods of :class:`Application` subclasses that raises an :class:`AppStateError` in case", "Python code can be executed, while the application runs in", ":func:`clean_up()` method, too, but there are no accessible results. If", "out. After this time is exceeded a :class:`TimeoutError` is raised", "user calls the :func:`start()` method, the app state is set", "= time.time() self._state = AppState.RUNNING @requires_state(AppState.RUNNING | AppState.FINISHED) def join(self,", "runs out. After this time is exceeded a :class:`TimeoutError` is", "the *JOINED* state and making the results of the application", "pass class AppStateError(Exception): \"\"\" Indicate that the application lifecycle was", "and the :class:`Application` type specific :func:`run()` method is called. When", "\"\"\" The time interval of :func:`is_finished()` calls in the joining", "time interval of :func:`is_finished()` calls in the joining process. PROTECTED:", "called, if :class:`Application` is not in one of the specified", "return func(*args, **kwargs) return wrapper return decorator class Application(metaclass=abc.ABCMeta): \"\"\"", ":class:`AppState` `app_state`. Parameters ---------- app_state : AppState The required app", "self._state == AppState.RUNNING: if self.is_finished(): self._state = AppState.FINISHED return self._state", "requires_state(app_state): \"\"\" A decorator for methods of :class:`Application` subclasses that", "Override when inheriting. \"\"\" pass @abc.abstractmethod def is_finished(self): \"\"\" Check", "state. \"\"\" self.run() self._start_time = time.time() self._state = AppState.RUNNING @requires_state(AppState.RUNNING", "*RUNNING*. This can only be done from the *CREATED* state.", "BSD License. Please see 'LICENSE.rst' for further # information. __name__", "state. If the application is *FINISHED* the joining process happens", "further # information. __name__ = \"biotite.application\" __author__ = \"<NAME>\" __all__", "inheriting. Returns ------- finished : bool True of the application", "be executed, while the application runs in the background. \"\"\"", "\"\"\" def decorator(func): @wraps(func) def wrapper(*args, **kwargs): # First parameter", "auto() JOINED = auto() CANCELLED = auto() def requires_state(app_state): \"\"\"", "If this parameter is specified, the :class:`Application` only waits for", ":class:`Application` subclasses that raises an :class:`AppStateError` in case the method", "a different app states (instances of enum :class:`AppState`) from its", "= auto() CANCELLED = auto() def requires_state(app_state): \"\"\" A decorator", "TimeoutError( f\"The application expired its timeout \" f\"({timeout:.1f} s)\" )", "\"\"\" self._state = AppState.CANCELLED self.clean_up() def get_app_state(self): \"\"\" Get the", "the respective kind of software and the way of interacting", "and will directly go into the *JOINED* state as soon", "> timeout: self.cancel() raise TimeoutError( f\"The application expired its timeout", "type specific :func:`is_finished()` method. The user can now call the", "required\" ) return func(*args, **kwargs) return wrapper return decorator class", "type specific :func:`run()` method is called. When the application finishes", "Start the application run and set its state to *RUNNING*.", "is_finished(self): \"\"\" Check if the application has finished. PROTECTED: Override", "of method is always 'self' instance = args[0] if not", "*FINISHED* state. \"\"\" self._state = AppState.CANCELLED self.clean_up() def get_app_state(self): \"\"\"", "self.get_app_state() != AppState.FINISHED: if timeout is not None and time.time()-self._start_time", "not instance._state & app_state: raise AppStateError( f\"The application is in", "@abc.abstractmethod def evaluate(self): \"\"\" Evaluate application results. Called in :func:`join()`.", "*RUNNING* or *FINISHED* state. \"\"\" self._state = AppState.CANCELLED self.clean_up() def", "except AppStateError: raise except: self._state = AppState.CANCELLED raise else: self._state", "\"\"\" pass class TimeoutError(Exception): \"\"\" Indicate that the application's timeout", "reaches the *FINISHED* state. Calling the :func:`cancel()` method while the", "abc import time from functools import wraps from enum import", "= AppState.CANCELLED self.clean_up() def get_app_state(self): \"\"\" Get the current app", "= auto() JOINED = auto() CANCELLED = auto() def requires_state(app_state):", "instance._state & app_state: raise AppStateError( f\"The application is in {instance.get_app_state()}", "PROTECTED: Override when inheriting. \"\"\" pass @abc.abstractmethod def is_finished(self): \"\"\"", "auto() FINISHED = auto() JOINED = auto() CANCELLED = auto()", "application when in *RUNNING* or *FINISHED* state. \"\"\" self._state =", "like an additional thread: Between the call of :func:`start()` and", "pass @abc.abstractmethod def wait_interval(self): \"\"\" The time interval of :func:`is_finished()`", "of :func:`is_finished()` in :func:`join()` \"\"\" pass @abc.abstractmethod def evaluate(self): \"\"\"", "application run behaves like an additional thread: Between the call", "this executes the :class:`Application` type specific :func:`clean_up()` method. :func:`join()` can", ":class:`Application` only waits for finishing until this value (in seconds)", "time.sleep(self.wait_interval()) time.sleep(self.wait_interval()) try: self.evaluate() except AppStateError: raise except: self._state =", "wait_interval(self): \"\"\" The time interval of :func:`is_finished()` calls in the", "Evaluate application results. Called in :func:`join()`. PROTECTED: Override when inheriting.", "state, \" f\"but {app_state} state is required\" ) return func(*args,", "finishes the AppState changes to *FINISHED*. This is checked via", "calls of :func:`is_finished()` in :func:`join()` \"\"\" pass @abc.abstractmethod def evaluate(self):", "Flag, auto class AppState(Flag): \"\"\" This enum type represents the", "application terminates. PROTECTED: Optionally override when inheriting. \"\"\" pass class", "results. If a method is called in an unsuitable app", "app states of an application. \"\"\" CREATED = auto() RUNNING", "the :func:`cancel()` method while the application is *RUNNING* or *FINISHED*", "f\"but {app_state} state is required\" ) return func(*args, **kwargs) return", "false otherwise \"\"\" pass @abc.abstractmethod def wait_interval(self): \"\"\" The time", "**kwargs): # First parameter of method is always 'self' instance", "state. \"\"\" self._state = AppState.CANCELLED self.clean_up() def get_app_state(self): \"\"\" Get", "state, an :class:`AppStateError` is called. The application run behaves like", "is set to *RUNNING* and the :class:`Application` type specific :func:`run()`", "set for the application run. After the user calls the", "import Flag, auto class AppState(Flag): \"\"\" This enum type represents", "self._state = AppState.CANCELLED raise else: self._state = AppState.JOINED self.clean_up() @requires_state(AppState.RUNNING", "*RUNNING* and the :class:`Application` type specific :func:`run()` method is called.", "its state to *JOINED*. This can only be done from", "as the application reaches the *FINISHED* state. Calling the :func:`cancel()`", "until its termination: Directly after its instantiation the app is", "enum import Flag, auto class AppState(Flag): \"\"\" This enum type", "of the Biotite package and is distributed # under the", "except: self._state = AppState.CANCELLED raise else: self._state = AppState.JOINED self.clean_up()", "distributed # under the 3-Clause BSD License. Please see 'LICENSE.rst'", ":func:`start()` and :func:`join()` other Python code can be executed, while", "by executing the :class:`Application` type specific :func:`evaluate()` method. Furthermore this", "application is *FINISHED*. Parameters ---------- timeout : float, optional If", "@abc.abstractmethod def run(self): \"\"\" Commence the application run. Called in", "that the application lifecycle was violated. \"\"\" pass class TimeoutError(Exception):", "import time from functools import wraps from enum import Flag,", "parameter is specified, the :class:`Application` only waits for finishing until", "if :class:`Application` is not in one of the specified states:", "return wrapper return decorator class Application(metaclass=abc.ABCMeta): \"\"\" This class is", "software and the way of interacting with it. Every :class:`Application`", "constantly check :func:`is_finished()` and will directly go into the *JOINED*", "the application is *RUNNING* or *FINISHED* leaves the application in", "there are no accessible results. If a method is called", "Check if the application has finished. PROTECTED: Override when inheriting.", "This triggers the :func:`clean_up()` method, too, but there are no", "a method is called in an unsuitable app state, an", "Time (in seconds) between calls of :func:`is_finished()` in :func:`join()` \"\"\"", "cancelled. Raises ------ TimeoutError If the joining process exceeds the", "software in any sense. Subclasses of this abstract base class", "finishing until this value (in seconds) runs out. After this", "This will constantly check :func:`is_finished()` and will directly go into", "the :class:`Application` type specific :func:`evaluate()` method. Furthermore this executes the", "\"\"\" This enum type represents the app states of an", "process happens immediately, if otherwise the application is *RUNNING*, this", "current app state. Returns ------- app_state : AppState The current", "method. The user can now call the :func:`join()` method, concluding", "executing the :class:`Application` type specific :func:`evaluate()` method. Furthermore this executes", "time.sleep(self.wait_interval()) while self.get_app_state() != AppState.FINISHED: if timeout is not None", "'self' instance = args[0] if not instance._state & app_state: raise", "application finishes the AppState changes to *FINISHED*. This is checked", "application in the *JOINED* state and making the results of", "the application run. Called in :func:`start()`. PROTECTED: Override when inheriting.", "from functools import wraps from enum import Flag, auto class", "the :class:`Application` is not in the specified :class:`AppState` `app_state`. Parameters", "inheriting. \"\"\" pass @abc.abstractmethod def is_finished(self): \"\"\" Check if the", "method is called. When the application finishes the AppState changes", "args[0] if not instance._state & app_state: raise AppStateError( f\"The application", "AppState.RUNNING @requires_state(AppState.RUNNING | AppState.FINISHED) def join(self, timeout=None): \"\"\" Conclude the", "the joining process exceeds the `timeout` value. \"\"\" time.sleep(self.wait_interval()) while", "# information. __name__ = \"biotite.application\" __author__ = \"<NAME>\" __all__ =", "PROTECTED: Override when inheriting. Returns ------- interval : float Time", "method is called in an unsuitable app state, an :class:`AppStateError`", "The user can now call the :func:`join()` method, concluding the", "is called, when the :class:`Application` is not in the specified", "This can only be done from the *RUNNING* or *FINISHED*", "in the *JOINED* state and making the results of the", "---------- timeout : float, optional If this parameter is specified,", "application results. Called in :func:`join()`. PROTECTED: Override when inheriting. \"\"\"", "the application in the *CANCELLED* state. This triggers the :func:`clean_up()`", "`timeout` value. \"\"\" time.sleep(self.wait_interval()) while self.get_app_state() != AppState.FINISHED: if timeout", "@requires_state(AppState.CREATED) def start(self): \"\"\" Start the application run and set", "Please see 'LICENSE.rst' for further # information. __name__ = \"biotite.application\"", "`function` is called, if :class:`Application` is not in one of", "always 'self' instance = args[0] if not instance._state & app_state:", "to *RUNNING*. This can only be done from the *CREATED*", "Override when inheriting. Returns ------- interval : float Time (in", "will constantly check :func:`is_finished()` and will directly go into the", "work after the application terminates. PROTECTED: Optionally override when inheriting.", "This enum type represents the app states of an application.", "get_app_state(self): \"\"\" Get the current app state. Returns ------- app_state", "if otherwise the application is *RUNNING*, this method waits until", "its state to *RUNNING*. This can only be done from", "in :func:`join()` \"\"\" pass @abc.abstractmethod def evaluate(self): \"\"\" Evaluate application", "\"\"\" Cancel the application when in *RUNNING* or *FINISHED* state.", "specified, the :class:`Application` only waits for finishing until this value", "was violated. \"\"\" pass class TimeoutError(Exception): \"\"\" Indicate that the", "triggers the :func:`clean_up()` method, too, but there are no accessible", "and set its state to *RUNNING*. This can only be", "is raised and the application is cancelled. Raises ------ TimeoutError", "the results of the application accessible by executing the :class:`Application`", "when `function` is called, if :class:`Application` is not in one", "\"\"\" Indicate that the application lifecycle was violated. \"\"\" pass", "is not None and time.time()-self._start_time > timeout: self.cancel() raise TimeoutError(", "CREATED = auto() RUNNING = auto() FINISHED = auto() JOINED", "specified states: >>> @requires_state(AppState.RUNNING | AppState.FINISHED) ... def function(self): ...", ":func:`start()` method, the app state is set to *RUNNING* and", "when inheriting. \"\"\" pass @abc.abstractmethod def is_finished(self): \"\"\" Check if", "waits until the application is *FINISHED*. Parameters ---------- timeout :", "the application is *FINISHED*. Parameters ---------- timeout : float, optional", "interacting with it. Every :class:`Application` runs through a different app", "in any sense. Subclasses of this abstract base class specify", "is called. When the application finishes the AppState changes to", "the :class:`Application` type specific :func:`clean_up()` method. :func:`join()` can even be", "method. Furthermore this executes the :class:`Application` type specific :func:`clean_up()` method.", "\"\"\" self.run() self._start_time = time.time() self._state = AppState.RUNNING @requires_state(AppState.RUNNING |", "not in one of the specified states: >>> @requires_state(AppState.RUNNING |", "leaves the application in the *CANCELLED* state. This triggers the", "the :class:`Application` only waits for finishing until this value (in", "class TimeoutError(Exception): \"\"\" Indicate that the application's timeout expired. \"\"\"", "is in the *CREATED* state. In this state further parameters", "| AppState.FINISHED) def join(self, timeout=None): \"\"\" Conclude the application run", "Examples -------- Raises :class:`AppStateError` when `function` is called, if :class:`Application`", "try: self.evaluate() except AppStateError: raise except: self._state = AppState.CANCELLED raise", "exceeded a :class:`TimeoutError` is raised and the application is cancelled.", "the app is in the *CREATED* state. In this state", "\"\"\" pass class VersionError(Exception): \"\"\" Indicate that the application's version", "represents the app states of an application. \"\"\" CREATED =", "Biotite package and is distributed # under the 3-Clause BSD", "@abc.abstractmethod def wait_interval(self): \"\"\" The time interval of :func:`is_finished()` calls", "type specific :func:`evaluate()` method. Furthermore this executes the :class:`Application` type", "CANCELLED = auto() def requires_state(app_state): \"\"\" A decorator for methods", "when the :class:`Application` is not in the specified :class:`AppState` `app_state`.", "in the joining process. PROTECTED: Override when inheriting. Returns -------", "process. PROTECTED: Override when inheriting. Returns ------- interval : float", "This can only be done from the *CREATED* state. \"\"\"", "case the method is called, when the :class:`Application` is not", "called in an unsuitable app state, an :class:`AppStateError` is called.", "package and is distributed # under the 3-Clause BSD License.", "float Time (in seconds) between calls of :func:`is_finished()` in :func:`join()`", "to *JOINED*. This can only be done from the *RUNNING*", "\"VersionError\", \"AppState\", \"requires_state\"] import abc import time from functools import", "the application run and set its state to *JOINED*. This", "application is *RUNNING*, this method waits until the application is", "Furthermore this executes the :class:`Application` type specific :func:`clean_up()` method. :func:`join()`", "be done from the *RUNNING* or *FINISHED* state. If the", "state further parameters can be set for the application run.", "be set for the application run. After the user calls", "is a wrapper around an external piece of runnable software", "state. \"\"\" if self._state == AppState.RUNNING: if self.is_finished(): self._state =", "in *RUNNING* or *FINISHED* state. \"\"\" self._state = AppState.CANCELLED self.clean_up()", "this state further parameters can be set for the application", "call of :func:`start()` and :func:`join()` other Python code can be", "*FINISHED* state. If the application is *FINISHED* the joining process", "the :func:`clean_up()` method, too, but there are no accessible results.", "instance = args[0] if not instance._state & app_state: raise AppStateError(", "auto() CANCELLED = auto() def requires_state(app_state): \"\"\" A decorator for", "the method is called, when the :class:`Application` is not in", "------- app_state : AppState The current app state. \"\"\" if", "application lifecycle was violated. \"\"\" pass class TimeoutError(Exception): \"\"\" Indicate", "The time interval of :func:`is_finished()` calls in the joining process.", "from the *CREATED* state. \"\"\" self.run() self._start_time = time.time() self._state", "results. Called in :func:`join()`. PROTECTED: Override when inheriting. \"\"\" pass", "# under the 3-Clause BSD License. Please see 'LICENSE.rst' for", "Subclasses of this abstract base class specify the respective kind", "\"\"\" A decorator for methods of :class:`Application` subclasses that raises", "# First parameter of method is always 'self' instance =", "state. In this state further parameters can be set for", "go into the *JOINED* state as soon as the application", "behaves like an additional thread: Between the call of :func:`start()`", "join(self, timeout=None): \"\"\" Conclude the application run and set its" ]