zip
stringlengths
19
109
filename
stringlengths
4
185
contents
stringlengths
0
30.1M
type_annotations
sequencelengths
0
1.97k
type_annotation_starts
sequencelengths
0
1.97k
type_annotation_ends
sequencelengths
0
1.97k
archives/0mars_monoskel.zip
packages/injector_provider/tests/test_injector_provider.py
from unittest.mock import patch from injector import Injector, Module from injector_provider.providers import InjectorProvider class TestObjectGraphBuilder: def test_can_build_without_any_configurations(self): provider = InjectorProvider() assert isinstance(provider.get_injector(), Injector) @patch('injector_provider.providers.Injector.__init__') def test_add_class(self, mocked_injector_init): mocked_injector_init.return_value = None provider = InjectorProvider() class Configurator(Module): pass configurator1 = Configurator() provider.add_configurator(configurator1) provider.get_injector() mocked_injector_init.assert_called_once_with([configurator1])
[]
[]
[]
archives/0mars_monoskel.zip
packages/meerkat/setup.py
from glob import glob from os.path import abspath, dirname, join as pjoin import pkg_resources from setuptools import setup, find_packages root = dirname(abspath(__file__)) def execfile(fname, globs, locs=None): locs = locs or globs exec(compile(open(fname).read(), fname, "exec"), globs, locs) source_path = 'src' packages = find_packages(source_path) root_packages = [ package for package in packages if "." not in package ] assert len(root_packages) == 1 package = root_packages[0] package_directory = pjoin(root, source_path, package) def get_variable_from_file(filepath, variable): filepath_in_package = pjoin(package_directory, filepath) globs = {} execfile(filepath_in_package, globs) variable_value = globs[variable] return variable_value version = get_variable_from_file('_version.py', '__version__') with open('requirements.txt') as f: required = f.read().splitlines() required = [requirement for requirement in required if 'http' not in requirement] setup( name=package, version=version, python_requires='>=3.6', author="PyMedPhys Contributors", author_email="developers@pymedphys.com", description='', classifiers=[ 'Development Status :: 4 - Beta', 'License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)', 'Programming Language :: Python :: 3.7', 'Topic :: Scientific/Engineering :: Medical Science Apps.', 'Topic :: Scientific/Engineering :: Physics', 'Intended Audience :: Science/Research', 'Intended Audience :: Healthcare Industry' ], install_requires=required, packages=packages, package_dir={'': source_path}, include_package_data=True, package_data={package: []}, license='AGPL-3.0-or-later', extras_require={ 'test': [ 'pytest' ] } )
[]
[]
[]
archives/0mars_monoskel.zip
packages/meerkat/src/meerkat/__init__.py
# project/__init__.py
[]
[]
[]
archives/0mars_monoskel.zip
packages/meerkat/src/meerkat/_version.py
version_info = [0, 0, 1] __version__ = "0.0.1"
[]
[]
[]
archives/0mars_monoskel.zip
packages/meerkat/src/meerkat/configurations/__init__.py
[]
[]
[]
archives/0mars_monoskel.zip
packages/meerkat/src/meerkat/configurations/app/__init__.py
[]
[]
[]
archives/0mars_monoskel.zip
packages/meerkat/src/meerkat/configurations/app/main.py
import falcon from meerkat.configurations.app import settings from falcon_marshmallow import JSONEnforcer, EmptyRequestDropper from meerkat.configurations.app.middlewares import RequestLoader from injector_provider import InjectorProvider from registry.services import Container, Registry app = falcon.API(middleware=[ JSONEnforcer(), EmptyRequestDropper(), RequestLoader() ]) container = Container() container.set(settings.Props.DI_PROVIDER, InjectorProvider()) container.set(settings.Props.FALCON, app) service_registry = Registry() for service in settings.services: service_registry.register(service) service_registry.boot(container)
[]
[]
[]
archives/0mars_monoskel.zip
packages/meerkat/src/meerkat/configurations/app/middlewares.py
import logging import falcon from falcon import HTTPUnprocessableEntity, HTTPBadRequest from falcon_marshmallow import Marshmallow from falcon_marshmallow.middleware import get_stashed_content from marshmallow import ValidationError, Schema log = logging.getLogger(__name__) class HTTPValidationError(falcon.HTTPError): """ HTTPError that stores a dictionary of validation error messages. """ def __init__(self, status, errors=None, *args, **kwargs): self.errors = errors super().__init__(status, *args, **kwargs) def to_dict(self, *args, **kwargs): """ Override `falcon.HTTPError` to include error messages in responses. """ ret = super().to_dict(*args, **kwargs) if self.errors is not None: ret['errors'] = self.errors return ret class RequestLoader(Marshmallow): def process_resource(self, *args, **kwargs): try: self.process_resource_inner(*args, **kwargs) except ValidationError as err: raise HTTPValidationError(status=falcon.status_codes.HTTP_400, errors=err.messages) except ValueError as err: raise falcon.HTTPError(status=falcon.status_codes.HTTP_400, title='Validation Error', description=str(err)) def process_resource_inner(self, req, resp, resource, params): # type: (Request, Response, object, dict) -> None """Deserialize request body with any resource-specific schemas Store deserialized data on the ``req.context`` object under the ``req_key`` provided to the class constructor or on the ``json`` key if none was provided. If a Marshmallow schema is defined on the passed ``resource``, use it to deserialize the request body. If no schema is defined and the class was instantiated with ``force_json=True``, request data will be deserialized with any ``json_module`` passed to the class constructor or ``simplejson`` by default. :param falcon.Request req: the request object :param falcon.Response resp: the response object :param object resource: the resource object :param dict params: any parameters parsed from the url :rtype: None :raises falcon.HTTPBadRequest: if the data cannot be deserialized or decoded """ log.debug( 'Marshmallow.process_resource(%s, %s, %s, %s)', req, resp, resource, params ) if req.content_length in (None, 0): return sch = self._get_schema(resource, req.method, 'request') if sch is not None: if not isinstance(sch, Schema): raise TypeError( 'The schema and <method>_schema properties of a resource ' 'must be instantiated Marshmallow schemas.' ) try: body = get_stashed_content(req) parsed = self._json.loads(body) except UnicodeDecodeError: raise HTTPBadRequest('Body was not encoded as UTF-8') except self._json.JSONDecodeError: raise HTTPBadRequest('Request must be valid JSON') log.info(sch) data = sch.load(parsed) req.context[self._req_key] = data elif self._force_json: body = get_stashed_content(req) try: req.context[self._req_key] = self._json.loads(body) except (ValueError, UnicodeDecodeError): raise HTTPBadRequest( description=( 'Could not decode the request body, either because ' 'it was not valid JSON or because it was not encoded ' 'as UTF-8.' ) )
[]
[]
[]
archives/0mars_monoskel.zip
packages/meerkat/src/meerkat/configurations/app/settings.py
from meerkat.configurations.infrastructure.db import DataBaseService from meerkat.configurations.infrastructure.di.service import DiService from meerkat.configurations.infrastructure.environment import EnvironmentService from meerkat.configurations.infrastructure.logging import LoggingService from meerkat.configurations.infrastructure.rest.health.registry import HealthService from meerkat.configurations.infrastructure.rest.swagger.registry import SwaggerService from meerkat.entrypoints.rest.post.registry import PostService from registry.services import Props as BaseProps services = [ LoggingService(), EnvironmentService(), DataBaseService(), DiService(), PostService(), HealthService(), SwaggerService() ] class Props(BaseProps): DI_PROVIDER = 0 FALCON = 1 APP_URL = 'APP_URL' MONGO_HOST = 'MONGO_HOST' MONGO_PORT = 'MONGO_PORT' MONGO_DB = 'MONGO_DB'
[]
[]
[]
archives/0mars_monoskel.zip
packages/meerkat/src/meerkat/configurations/infrastructure/db/__init__.py
from registry.services import BootableService, Container from mongoengine import connect class DataBaseService(BootableService): def boot(self, container: Container): from meerkat.configurations.app.settings import Props host = container.get(Props.MONGO_HOST) port = int(container.get(Props.MONGO_PORT)) db = container.get(Props.MONGO_DB) connect(db, host=host, port=port)
[ "Container" ]
[ 162 ]
[ 171 ]
archives/0mars_monoskel.zip
packages/meerkat/src/meerkat/configurations/infrastructure/di/__init__.py
[]
[]
[]
archives/0mars_monoskel.zip
packages/meerkat/src/meerkat/configurations/infrastructure/di/domain.py
from buslane.events import EventBus from injector import singleton, provider, Module from meerkat.data_providers.database.mongo import PostMongoRepository from meerkat.domain.post.use_cases import AddNewPostUseCase, PublishPostUseCase class UseCasesConfigurator(Module): @singleton @provider def add_new(self) -> AddNewPostUseCase: return AddNewPostUseCase(self.__injector__.get(PostMongoRepository), self.__injector__.get(EventBus)) @singleton @provider def publish(self) -> PublishPostUseCase: return PublishPostUseCase(self.__injector__.get(PostMongoRepository), self.__injector__.get(EventBus))
[]
[]
[]
archives/0mars_monoskel.zip
packages/meerkat/src/meerkat/configurations/infrastructure/di/service.py
from meerkat.configurations.app import settings from meerkat.configurations.infrastructure.di.domain import UseCasesConfigurator from registry.services import BootableService, Container class DiService(BootableService): def boot(self, container: Container): provider = container.get(settings.Props.DI_PROVIDER) provider.add_configurator(UseCasesConfigurator)
[ "Container" ]
[ 252 ]
[ 261 ]
archives/0mars_monoskel.zip
packages/meerkat/src/meerkat/configurations/infrastructure/environment/__init__.py
import os from registry.services import BootableService, Container class EnvironmentService(BootableService): def boot(self, container: Container): from meerkat.configurations.app.settings import Props container.set(Props.APP_URL, os.environ.get(Props.APP_URL.value)) container.set(Props.MONGO_HOST, os.environ.get(Props.MONGO_HOST.value)) container.set(Props.MONGO_PORT, os.environ.get(Props.MONGO_PORT.value)) container.set(Props.MONGO_DB, os.environ.get(Props.MONGO_DB.value))
[ "Container" ]
[ 144 ]
[ 153 ]
archives/0mars_monoskel.zip
packages/meerkat/src/meerkat/configurations/infrastructure/logging/__init__.py
import logging as registry_logging import sys import registry.services class LoggingService(registry.services.BootableService): def boot(self, app: registry.services.Container): registry_logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=registry_logging.DEBUG) registry_logging.getLogger().addHandler(registry_logging.StreamHandler(sys.stdout))
[ "registry.services.Container" ]
[ 155 ]
[ 182 ]
archives/0mars_monoskel.zip
packages/meerkat/src/meerkat/configurations/infrastructure/rest/__init__.py
[]
[]
[]
archives/0mars_monoskel.zip
packages/meerkat/src/meerkat/configurations/infrastructure/rest/health/__init__.py
import falcon import json from marshmallow import Schema, fields # schema class HealthSchema(Schema): status: fields.Str = fields.Str(required=True) message: fields.Str = fields.Str(required=True) class HealthCheck: # Handles GET requests def on_get(self, req, resp): """Get app health --- summary: Check application health responses: 200: description: status response schema: HealthSchema """ resp.status = falcon.HTTP_200 resp.body = json.dumps({"status": resp.status, "message": "healthy"})
[]
[]
[]
archives/0mars_monoskel.zip
packages/meerkat/src/meerkat/configurations/infrastructure/rest/health/definitions.py
from injector import Module, singleton, provider from meerkat.configurations.infrastructure.rest.health import HealthCheck class HealthConfigurator(Module): @singleton @provider def provide_health_check_resource(self) -> HealthCheck: return HealthCheck()
[]
[]
[]
archives/0mars_monoskel.zip
packages/meerkat/src/meerkat/configurations/infrastructure/rest/health/registry.py
from meerkat.configurations.app import settings from meerkat.configurations.infrastructure.rest.health import HealthCheck from meerkat.configurations.infrastructure.rest.health.definitions import HealthConfigurator from registry.services import BootableService, Container class HealthService(BootableService): def boot(self, container: Container): provider = container.get(settings.Props.DI_PROVIDER) provider.add_configurator(HealthConfigurator()) def post_boot(self, container): falcon = container.get(settings.Props.FALCON) provider = container.get(settings.Props.DI_PROVIDER) injector = provider.get_injector() health_check = injector.get(HealthCheck) falcon.add_route("/api", health_check) falcon.add_route("/api/health", health_check)
[ "Container" ]
[ 342 ]
[ 351 ]
archives/0mars_monoskel.zip
packages/meerkat/src/meerkat/configurations/infrastructure/rest/swagger/__init__.py
import json import falcon from apispec import APISpec from apispec.ext.marshmallow import MarshmallowPlugin from falcon import Request from falcon.response import Response from falcon_apispec import FalconPlugin from meerkat.configurations.infrastructure.rest.health import HealthSchema, HealthCheck from meerkat.entrypoints.rest.post.resources import PostCollection, Post from meerkat.entrypoints.rest.post.schemas import PostSchema class SwaggerResource: def __init__(self): from meerkat.configurations.app.settings import Props from meerkat.configurations.app.main import app from meerkat.configurations.app.main import container # todo: should be moved to env vars self.spec = APISpec(title='meerkat', version='1.0.0', openapi_version='2.0', plugins=[ FalconPlugin(app), MarshmallowPlugin(), ]) injector = container.get(Props.DI_PROVIDER).get_injector() self.spec.components.schema('Health', schema=injector.get(HealthSchema)) self.spec.path(resource=injector.get(HealthCheck)) self.spec.components.schema('Post', schema=injector.get(PostSchema)) self.spec.path(resource=injector.get(PostCollection)) self.spec.path(resource=injector.get(Post)) def on_get(self, req: Request, resp: Response): resp.status = falcon.HTTP_200 resp.body = json.dumps(self.spec.to_dict(), ensure_ascii=False)
[ "Request", "Response" ]
[ 1451, 1466 ]
[ 1458, 1474 ]
archives/0mars_monoskel.zip
packages/meerkat/src/meerkat/configurations/infrastructure/rest/swagger/registry.py
from registry.services import BootableService, Container from falcon_swagger_ui import register_swaggerui_app class SwaggerService(BootableService): def post_boot(self, container): from meerkat.configurations.app import settings from meerkat.configurations.infrastructure.rest.swagger import SwaggerResource falcon = container.get(settings.Props.FALCON) swagger_resource = SwaggerResource() falcon.add_route('/v1/swagger.json', swagger_resource) page_title = 'Swagger UI' favicon_url = 'https://falconframework.org/favicon-32x32.png' swagger_ui_url = '/v1/docs' # without trailing slash schema_url = '{}/v1/swagger.json'.format(container.get(settings.Props.APP_URL)) register_swaggerui_app( falcon, swagger_ui_url, schema_url, page_title=page_title, favicon_url=favicon_url, config={'supportedSubmitMethods': ['get', 'post', 'put'], } ) def boot(self, container: Container): pass
[ "Container" ]
[ 1014 ]
[ 1023 ]
archives/0mars_monoskel.zip
packages/meerkat/src/meerkat/data_providers/__init__.py
[]
[]
[]
archives/0mars_monoskel.zip
packages/meerkat/src/meerkat/data_providers/database/__init__.py
[]
[]
[]
archives/0mars_monoskel.zip
packages/meerkat/src/meerkat/data_providers/database/mongo/__init__.py
# public interfaces from .repositories import PostMongoRepository
[]
[]
[]
archives/0mars_monoskel.zip
packages/meerkat/src/meerkat/data_providers/database/mongo/documents.py
from mongoengine import Document from mongoengine.fields import StringField, UUIDField, BooleanField class PostDocument(Document): id = UUIDField(binary=False, primary_key=True) title = StringField(max_length=512, required=True) body = StringField(max_length=1024, required=True) published = BooleanField()
[]
[]
[]
archives/0mars_monoskel.zip
packages/meerkat/src/meerkat/data_providers/database/mongo/repositories.py
from injector import inject from meerkat.domain.post.data_providers import PostDataProvider from meerkat.domain.post.entities import Post from meerkat.domain.post.value_objects import Id from meerkat.domain.post.data_providers.exceptions import EntityNotFoundException from meerkat.data_providers.database.mongo.transformers import PostDocumentTransformer from meerkat.data_providers.database.mongo.documents import PostDocument class PostMongoRepository(PostDataProvider): @inject def __init__(self, transformer: PostDocumentTransformer): self.transformer = transformer def save(self, post: Post): post_document = self.transformer.transform_to_document(post) post_document.save() def get(self, id: Id) -> Post: posts = PostDocument.objects(id=id.value) if posts.count() < 1: raise EntityNotFoundException('Cannot find document with id #{}'.format(str(id))) return self.transformer.transform_to_domain_object(next(posts))
[ "PostDocumentTransformer", "Post", "Id" ]
[ 525, 616, 744 ]
[ 548, 620, 746 ]
archives/0mars_monoskel.zip
packages/meerkat/src/meerkat/data_providers/database/mongo/transformers.py
from meerkat.data_providers.database.mongo.documents import PostDocument from meerkat.domain.post.entities import Post from meerkat.domain.post.value_objects import Id, Title, Body class PostDocumentTransformer: def transform_to_document(self, post: Post) -> PostDocument: return PostDocument(id=post.id.value, title=post.title.value, body=post.body.value, published=post.is_published()) def transform_to_domain_object(self, post_document: PostDocument) -> Post: post = Post.create(Id(post_document.id), Title(post_document.title), Body(post_document.body)) post.published = post_document.published return post
[ "Post", "PostDocument" ]
[ 256, 487 ]
[ 260, 499 ]
archives/0mars_monoskel.zip
packages/meerkat/src/meerkat/domain/__init__.py
[]
[]
[]
archives/0mars_monoskel.zip
packages/meerkat/src/meerkat/domain/exceptions.py
class DomainException(Exception): pass
[]
[]
[]
archives/0mars_monoskel.zip
packages/meerkat/src/meerkat/domain/post/__init__.py
[]
[]
[]
archives/0mars_monoskel.zip
packages/meerkat/src/meerkat/domain/post/data_providers/__init__.py
import abc from meerkat.domain.post.entities.post import Post from meerkat.domain.post.value_objects import Id class PostDataProvider(metaclass=abc.ABCMeta): @abc.abstractmethod def save(self, post: Post): """ Saves the post to the data-store Args: post (Post): The post entity Returns: None """ pass @abc.abstractmethod def get(self, id: Id) -> Post: """ Saves the post to the data-store Args: id (Id): post id Returns: None Raises: EntityNotFoundException: if the specified entity cannot be found """ pass
[ "Post", "Id" ]
[ 210, 440 ]
[ 214, 442 ]
archives/0mars_monoskel.zip
packages/meerkat/src/meerkat/domain/post/data_providers/exceptions.py
class EntityNotFoundException(Exception): pass
[]
[]
[]
archives/0mars_monoskel.zip
packages/meerkat/src/meerkat/domain/post/entities/__init__.py
from .post import Post
[]
[]
[]
archives/0mars_monoskel.zip
packages/meerkat/src/meerkat/domain/post/entities/exceptions/__init__.py
from meerkat.domain.exceptions import DomainException class PublishingFailedException(DomainException): pass
[]
[]
[]
archives/0mars_monoskel.zip
packages/meerkat/src/meerkat/domain/post/entities/post.py
from meerkat.domain.post.entities.exceptions import PublishingFailedException from meerkat.domain.post.value_objects import Title, Body, Id class Post: id: Id title: Title body: Body published: bool = False @staticmethod def create(id: Id, title: Title, body: Body): instance = Post() instance.id = id instance.title = title instance.body = body return instance def publish(self): if not self.title.is_valid(): raise PublishingFailedException('title is invalid') if not self.id.is_valid(): raise PublishingFailedException('Id is invalid') self.published = True def is_published(self) -> bool: return self.published ''' todo slugify title '''
[ "Id", "Title", "Body" ]
[ 263, 274, 287 ]
[ 265, 279, 291 ]
archives/0mars_monoskel.zip
packages/meerkat/src/meerkat/domain/post/events/__init__.py
from .post_created import PostCreated from .post_published import PostPublished
[]
[]
[]
archives/0mars_monoskel.zip
packages/meerkat/src/meerkat/domain/post/events/post_created.py
from dataclasses import dataclass from buslane.events import Event from meerkat.domain.post.entities.post import Post @dataclass(frozen=True) class PostCreated(Event): post: Post
[]
[]
[]
archives/0mars_monoskel.zip
packages/meerkat/src/meerkat/domain/post/events/post_published.py
from dataclasses import dataclass from buslane.events import Event from meerkat.domain.post.entities.post import Post @dataclass(frozen=True) class PostPublished(Event): post: Post
[]
[]
[]
archives/0mars_monoskel.zip
packages/meerkat/src/meerkat/domain/post/use_cases/__init__.py
from .add_new_post import AddNewPostUseCase from .publish_post import PublishPostUseCase
[]
[]
[]
archives/0mars_monoskel.zip
packages/meerkat/src/meerkat/domain/post/use_cases/add_new_post.py
import uuid from buslane.events import EventBus from dataclasses import dataclass from meerkat.domain.post.data_providers import PostDataProvider from meerkat.domain.post.entities import Post from meerkat.domain.post.events import PostCreated from meerkat.domain.post.value_objects import Title, Body, Id @dataclass(frozen=True) class AddNewPostCommand: title: str body: str class AddNewPostUseCase: def __init__(self, data_provider: PostDataProvider, event_bus: EventBus): self.data_provider = data_provider self.event_bus = event_bus def exec(self, command: AddNewPostCommand) -> Post: post = Post.create(Id(uuid.uuid4()), Title(command.title), Body(command.body)) self.data_provider.save(post) self.event_bus.publish(PostCreated(post)) return post
[ "PostDataProvider", "EventBus", "AddNewPostCommand" ]
[ 451, 480, 598 ]
[ 467, 488, 615 ]
archives/0mars_monoskel.zip
packages/meerkat/src/meerkat/domain/post/use_cases/publish_post.py
from buslane.events import EventBus from dataclasses import dataclass from meerkat.domain.post.data_providers import PostDataProvider from meerkat.domain.post.events import PostPublished from meerkat.domain.post.value_objects import Id @dataclass(frozen=True) class PublishPostCommand: id: Id class PublishPostUseCase: def __init__(self, data_provider: PostDataProvider, event_bus: EventBus): self.data_provider = data_provider self.event_bus = event_bus def exec(self, command: PublishPostCommand) -> None: post = self.data_provider.get(command.id) post.publish() self.data_provider.save(post) self.event_bus.publish(PostPublished(post))
[ "PostDataProvider", "EventBus", "PublishPostCommand" ]
[ 366, 395, 513 ]
[ 382, 403, 531 ]
archives/0mars_monoskel.zip
packages/meerkat/src/meerkat/domain/post/value_objects/__init__.py
from .title import Title from .body import Body from .id import Id
[]
[]
[]
archives/0mars_monoskel.zip
packages/meerkat/src/meerkat/domain/post/value_objects/body.py
from dataclasses import dataclass @dataclass(frozen=True) class Body: value: str def is_valid(self): return len(self.value) > 0 def __str__(self): return self.value
[]
[]
[]
archives/0mars_monoskel.zip
packages/meerkat/src/meerkat/domain/post/value_objects/id.py
from uuid import UUID class Id: value: UUID def __init__(self, value: UUID): self.value = value def is_valid(self): return len(str(self)) > 0 def __str__(self): return str(self.value)
[ "UUID" ]
[ 81 ]
[ 85 ]
archives/0mars_monoskel.zip
packages/meerkat/src/meerkat/domain/post/value_objects/title.py
class Title: value: str def __init__(self, value): self.value = value def is_valid(self): return len(self.value) > 0 def __str__(self): return self.value
[]
[]
[]
archives/0mars_monoskel.zip
packages/meerkat/src/meerkat/entrypoints/rest/__init__.py
[]
[]
[]
archives/0mars_monoskel.zip
packages/meerkat/src/meerkat/entrypoints/rest/core/errors.py
# -*- coding: utf-8 -*- import json import falcon try: from collections import OrderedDict except ImportError: OrderedDict = dict OK = {"status": falcon.HTTP_200, "code": 200} ERR_UNKNOWN = {"status": falcon.HTTP_500, "code": 500, "title": "Unknown Error"} ERR_AUTH_REQUIRED = { "status": falcon.HTTP_401, "code": 99, "title": "Authentication Required", } ERR_INVALID_PARAMETER = { "status": falcon.HTTP_400, "code": 88, "title": "Invalid Parameter", } ERR_DATABASE_ROLLBACK = { "status": falcon.HTTP_500, "code": 77, "title": "Database Rollback Error", } ERR_NOT_SUPPORTED = {"status": falcon.HTTP_404, "code": 10, "title": "Not Supported"} ERR_USER_NOT_EXISTS = { "status": falcon.HTTP_404, "code": 21, "title": "User Not Exists", } ERR_PASSWORD_NOT_MATCH = { "status": falcon.HTTP_400, "code": 22, "title": "Password Not Match", } class AppError(Exception): def __init__(self, error=ERR_UNKNOWN, description=None): self.error = error self.error["description"] = description @property def code(self): return self.error["code"] @property def title(self): return self.error["title"] @property def status(self): return self.error["status"] @property def description(self): return self.error["description"] @staticmethod def handle(exception, req, res, error=None): res.status = exception.status meta = OrderedDict() meta["code"] = exception.code meta["message"] = exception.title if exception.description: meta["description"] = exception.description res.body = json.dumps({"meta": meta}) class InvalidParameterError(AppError): def __init__(self, description=None): super().__init__(ERR_INVALID_PARAMETER) self.error["description"] = description class DatabaseError(AppError): def __init__(self, error, args=None, params=None): super().__init__(error) obj = OrderedDict() obj["details"] = ", ".join(args) obj["params"] = str(params) self.error["description"] = obj class NotSupportedError(AppError): def __init__(self, method=None, url=None): super().__init__(ERR_NOT_SUPPORTED) if method and url: self.error["description"] = "method: %s, url: %s" % (method, url) class UserNotExistsError(AppError): def __init__(self, description=None): super().__init__(ERR_USER_NOT_EXISTS) self.error["description"] = description class PasswordNotMatch(AppError): def __init__(self, description=None): super().__init__(ERR_PASSWORD_NOT_MATCH) self.error["description"] = description class UnauthorizedError(AppError): def __init__(self, description=None): super().__init__(ERR_AUTH_REQUIRED) self.error["description"] = description
[]
[]
[]
archives/0mars_monoskel.zip
packages/meerkat/src/meerkat/entrypoints/rest/post/__init__.py
[]
[]
[]
archives/0mars_monoskel.zip
packages/meerkat/src/meerkat/entrypoints/rest/post/definitions.py
from injector import singleton, provider, Module from meerkat.domain.post.use_cases import AddNewPostUseCase, PublishPostUseCase from meerkat.entrypoints.rest.post.resources import PostCollection, Post class PostConfigurator(Module): @singleton @provider def post_collection(self) -> PostCollection: return PostCollection(self.__injector__.get(AddNewPostUseCase)) @singleton @provider def post_item(self) -> Post: return Post(self.__injector__.get(PublishPostUseCase))
[]
[]
[]
archives/0mars_monoskel.zip
packages/meerkat/src/meerkat/entrypoints/rest/post/registry.py
from meerkat.configurations.app import settings from meerkat.entrypoints.rest.post.definitions import PostConfigurator from meerkat.entrypoints.rest.post.resources import PostCollection, Post from registry.services import BootableService, Container class PostService(BootableService): def boot(self, container: Container): provider = container.get(settings.Props.DI_PROVIDER) provider.add_configurator(PostConfigurator) def post_boot(self, container): falcon = container.get(settings.Props.FALCON) provider = container.get(settings.Props.DI_PROVIDER) injector = provider.get_injector() falcon.add_route("/v1/posts", injector.get(PostCollection)) falcon.add_route("/v1/posts/{id}/publish", injector.get(Post))
[ "Container" ]
[ 317 ]
[ 326 ]
archives/0mars_monoskel.zip
packages/meerkat/src/meerkat/entrypoints/rest/post/resources.py
import json import logging import uuid import falcon from meerkat.configurations.app.middlewares import HTTPValidationError from meerkat.domain.post.use_cases import AddNewPostUseCase, PublishPostUseCase from meerkat.domain.post.use_cases.add_new_post import AddNewPostCommand from meerkat.domain.post.use_cases.publish_post import PublishPostCommand from meerkat.domain.post.value_objects import Id from meerkat.entrypoints.rest.post.schemas import PostSchema, AddNewPostSchema class PostCollection: schema = PostSchema() post_schema = AddNewPostSchema() def __init__(self, add_new_post: AddNewPostUseCase): self.add_new_post = add_new_post def on_post(self, req, resp): """Add new a post --- tags: - Posts summary: Add new post consumes: - application/json produces: - application/json parameters: - in: body schema: AddNewPostSchema responses: 201: description: post added schema: PostSchema 415: description: Unsupported Media Type """ # PostCollection.schema = AddNewPostSchema try: request_json = req.context['json'] except KeyError: raise HTTPValidationError(status=falcon.status_codes.HTTP_400, errors=["Empty request body"]) command = AddNewPostCommand(**request_json) post = self.add_new_post.exec(command) resp.status = falcon.HTTP_201 resp.body = json.dumps(PostSchema.from_domain_object(post)) class Post: schema = PostSchema() def __init__(self, publish_post: PublishPostUseCase): self.publish_post_usecase = publish_post def on_put(self, req: falcon.Request, resp: falcon.Response, id: str) -> None: """ --- summary: Publish post tags: - Posts parameters: - in: path name: id produces: - application/json responses: 204: description: post published """ command = PublishPostCommand(Id(uuid.UUID(id))) self.publish_post_usecase.exec(command) resp.status = falcon.HTTP_204
[ "AddNewPostUseCase", "PublishPostUseCase", "falcon.Request", "falcon.Response", "str" ]
[ 606, 1905, 2002, 2024, 2045 ]
[ 623, 1923, 2016, 2039, 2048 ]
archives/0mars_monoskel.zip
packages/meerkat/src/meerkat/entrypoints/rest/post/schemas.py
from marshmallow import fields, Schema from meerkat.domain.post.entities import Post class PostSchema(Schema): class Meta: ordered = True id: fields.Str = fields.Str() title: fields.Str = fields.Str(required=True) body: fields.Str = fields.Str(required=True) @classmethod def from_domain_object(cls, post: Post): object = cls() return object.load({ "id": str(post.id), "title": str(post.title), "body": str(post.body) }) class AddNewPostSchema(Schema): class Meta: ordered = True title: fields.Str = fields.Str(required=True) body: fields.Str = fields.Str(required=True)
[ "Post" ]
[ 343 ]
[ 347 ]
archives/0mars_monoskel.zip
packages/meerkat/tests/__init__.py
import sys import os sys.path.append(os.path.realpath(os.path.dirname(__file__) + "/../src/"))
[]
[]
[]
archives/0mars_monoskel.zip
packages/meerkat/tests/meerkat/__init__.py
[]
[]
[]
archives/0mars_monoskel.zip
packages/meerkat/tests/meerkat/domain/__init__.py
[]
[]
[]
archives/0mars_monoskel.zip
packages/meerkat/tests/meerkat/domain/post/__init__.py
[]
[]
[]
archives/0mars_monoskel.zip
packages/meerkat/tests/meerkat/domain/post/use_cases/__init__.py
[]
[]
[]
archives/0mars_monoskel.zip
packages/meerkat/tests/meerkat/domain/post/use_cases/test_add_new_post.py
import uuid from unittest import mock from meerkat.domain.post.events import PostCreated from meerkat.domain.post.use_cases.add_new_post import AddNewPostUseCase, AddNewPostCommand class TestCreatePost: @mock.patch('meerkat.domain.post.use_cases.add_new_post.uuid.uuid4') def test_can_add_new_post(self, uuid4_mock): uuid4_mock.return_value = uuid.uuid4() data_provider_mock = mock.Mock() event_bus_mock = mock.Mock() use_case = AddNewPostUseCase(data_provider_mock, event_bus_mock) command = AddNewPostCommand(title='title1', body='body1') use_case.exec(command) data_provider_mock.save.assert_called_once() post = self.first_called_arg(data_provider_mock.save) assert str(post.id) == str(uuid4_mock.return_value) assert post.title.value == command.title assert post.body.value == command.body assert post.is_published() is False post_created_event = self.first_called_arg(event_bus_mock.publish) assert isinstance(post_created_event, PostCreated) assert post_created_event.post == post def first_called_arg(self, method_mock): return method_mock.call_args_list[0][0][0]
[]
[]
[]
archives/0mars_monoskel.zip
packages/meerkat/tests/meerkat/domain/post/use_cases/test_publish_post.py
import uuid from unittest import mock from meerkat.domain.post.entities import Post from meerkat.domain.post.events import PostPublished from meerkat.domain.post.use_cases import PublishPostUseCase from meerkat.domain.post.use_cases.publish_post import PublishPostCommand from meerkat.domain.post.value_objects import Title, Body, Id class TestCreatePost: @mock.patch('meerkat.domain.post.use_cases.add_new_post.uuid.uuid4') def test_can_publish_post(self, uuid4_mock): id = Id(uuid.uuid4()) post = Post.create(id, Title('post title'), Body('post body')) data_provider_mock = mock.Mock() event_bus_mock = mock.Mock() def get(id: Id): return post data_provider_mock.get.side_effect = get use_case = PublishPostUseCase(data_provider_mock, event_bus_mock) assert post.is_published() is False command = PublishPostCommand(id) use_case.exec(command) data_provider_mock.save.assert_called_once_with(post) published_post = self.first_called_arg(data_provider_mock.save) assert published_post.is_published() is True post_published_event = self.first_called_arg(event_bus_mock.publish) assert isinstance(post_published_event, PostPublished) assert post_published_event.post == published_post def first_called_arg(self, method_mock): return method_mock.call_args_list[0][0][0]
[ "Id" ]
[ 682 ]
[ 684 ]
archives/0mars_monoskel.zip
packages/monomanage/setup.py
from glob import glob from os.path import abspath, dirname, join as pjoin from setuptools import setup, find_packages root = dirname(abspath(__file__)) def execfile(fname, globs, locs=None): locs = locs or globs exec(compile(open(fname).read(), fname, "exec"), globs, locs) source_path = 'src' packages = find_packages(source_path) root_packages = [ package for package in packages if "." not in package ] assert len(root_packages) == 1 package = root_packages[0] package_directory = pjoin(root, source_path, package) def get_variable_from_file(filepath, variable): filepath_in_package = pjoin(package_directory, filepath) globs = {} execfile(filepath_in_package, globs) variable_value = globs[variable] return variable_value version = get_variable_from_file('_version.py', '__version__') install_requires = get_variable_from_file( '_install_requires.py', 'install_requires') setup( name=package, version=version, python_requires='>=3.6', author="Simon Biggs", author_email="me@simonbiggs.net", description='', classifiers=[ 'Development Status :: 4 - Beta', 'Programming Language :: Python :: 3.6', ], packages=packages, package_dir={'': source_path}, include_package_data=True, package_data={package: []}, license='Apache License 2.0', install_requires=install_requires, extras_require={ 'test': [ 'pytest' ] } )
[]
[]
[]
archives/0mars_monoskel.zip
packages/monomanage/src/monomanage/__init__.py
[]
[]
[]
archives/0mars_monoskel.zip
packages/monomanage/src/monomanage/_install_requires.py
install_requires = [ "networkx", "semver", "stdlib_list" ]
[]
[]
[]
archives/0mars_monoskel.zip
packages/monomanage/src/monomanage/_version.py
version_info = [0, 10, 0, 'dev0'] __version__ = "0.10.0dev0"
[]
[]
[]
archives/0mars_monoskel.zip
packages/monomanage/src/monomanage/app/__init__.py
from .api import package_wheels
[]
[]
[]
archives/0mars_monoskel.zip
packages/monomanage/src/monomanage/app/api.py
# Copyright (C) 2019 Simon Biggs # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os from .wheels import build_wheels_with_yarn, copy_wheels def package_wheels(pymedphys_dir): app_directory = os.path.join(pymedphys_dir, 'app') wheels_directory = os.path.join(app_directory, 'public', 'python-wheels') packages_directory = os.path.join(pymedphys_dir, 'packages') build_wheels_with_yarn() copy_wheels(packages_directory, wheels_directory)
[]
[]
[]
archives/0mars_monoskel.zip
packages/monomanage/src/monomanage/app/wheels.py
# Copyright (C) 2019 Simon Biggs # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import shutil from glob import glob import subprocess import json WHITELIST = ( 'pymedphys_base', 'pymedphys_coordsandscales', 'pymedphys_dicom', 'pymedphys_fileformats', 'pymedphys_utilities', 'pymedphys_mudensity', 'pymedphys_gamma', 'pymedphys') def build_wheels_with_yarn(): yarn = shutil.which("yarn") subprocess.call([yarn, "pypi:clean"]) for package in WHITELIST: subprocess.call( [yarn, "lerna", "run", "pypi:build", "--scope={}".format(package)]) def copy_wheels(packages_dir, new_dir): wheel_filepaths = glob(os.path.join(packages_dir, '*', 'dist', '*.whl')) pymedphys_wheel_urls = [] for filepath in wheel_filepaths: filename = os.path.basename(filepath) if not filename.split('-')[0] in WHITELIST: continue pymedphys_wheel_urls.append(filename) new_filepath = os.path.join(new_dir, filename) shutil.copy(filepath, new_filepath) filenames_filepath = os.path.join(new_dir, 'paths.json') with open(filenames_filepath, 'w') as filenames_file: json.dump(pymedphys_wheel_urls, filenames_file)
[]
[]
[]
archives/0mars_monoskel.zip
packages/monomanage/src/monomanage/clean/__init__.py
[]
[]
[]
archives/0mars_monoskel.zip
packages/monomanage/src/monomanage/clean/core.py
import shutil try: shutil.rmtree('dist') except FileNotFoundError: pass try: shutil.rmtree('build') except FileNotFoundError: pass
[]
[]
[]
archives/0mars_monoskel.zip
packages/monomanage/src/monomanage/docs/__init__.py
from .api import pre_docs_build
[]
[]
[]
archives/0mars_monoskel.zip
packages/monomanage/src/monomanage/docs/api.py
# Copyright (C) 2019 Simon Biggs # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os from ..draw import draw_all from .graphs import write_graphs_rst def pre_docs_build(pymedphys_dir): docs_directory = os.path.join(pymedphys_dir, 'docs') docs_graphs = os.path.join(docs_directory, 'graphs') draw_all(docs_graphs) write_graphs_rst(docs_graphs)
[]
[]
[]
archives/0mars_monoskel.zip
packages/monomanage/src/monomanage/docs/graphs.py
# Copyright (C) 2019 Simon Biggs # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import textwrap from glob import glob from ..draw.utilities import remove_postfix ROOT = os.getcwd() def write_graphs_rst(save_directory): search_string = os.path.join(save_directory, "*.svg") svg_files = [ os.path.basename(filepath) for filepath in sorted(glob(search_string), key=os.path.splitext) ] modules = [remove_postfix(filepath, '.svg') for filepath in svg_files] images_paths = ["../graphs/{}.svg".format(module) for module in modules] sections = ".. This is automatically generated. DO NOT DIRECTLY EDIT.\n\n" for module, images_path in zip(modules, images_paths): header_border = '*' * len(module) sections += textwrap.dedent("""\ {0} {1} {0} `Back to pymedphys <#pymedphys>`_ .. raw:: html :file: {2} """.format(header_border, module, images_path)) save_file = os.path.join(save_directory, 'graphs.rst') with open(save_file, 'w') as file: file.write(sections)
[]
[]
[]
archives/0mars_monoskel.zip
packages/monomanage/src/monomanage/draw/__init__.py
from .api import draw_all
[]
[]
[]
archives/0mars_monoskel.zip
packages/monomanage/src/monomanage/draw/api.py
# Copyright (C) 2019 Simon Biggs # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from .packages import draw_packages from .directories import draw_directory_modules from .files import draw_file_modules def draw_all(save_directory): draw_packages(save_directory) draw_directory_modules(save_directory) draw_file_modules(save_directory)
[]
[]
[]
archives/0mars_monoskel.zip
packages/monomanage/src/monomanage/draw/directories.py
# Copyright (C) 2019 Simon Biggs # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import networkx as nx from copy import copy from ..tree import PackageTree from .utilities import ( save_dot_file, remove_prefix, get_levels, create_labels, create_href) ROOT = os.getcwd() def draw_directory_modules(save_directory): package_tree = PackageTree(os.path.join(ROOT, 'packages')) internal_packages = copy(package_tree.roots) internal_packages.remove('pymedphys') module_paths = [ item for package in internal_packages for item in package_tree.digraph.neighbors(package) ] modules = { item: os.path.splitext(item)[0].replace(os.sep, '.') for item in module_paths } dependencies = { module.replace(os.sep, '.'): { '.'.join(item.split('.')[0:2]) for item in package_tree.descendants_dependencies(module)['internal_module'] + package_tree.descendants_dependencies(module)['internal_package'] # package_tree.descendants_dependencies(module)['internal_file'] + # list(package_tree.imports[module]['internal_module']) + # list(package_tree.imports[module]['internal_package']) + # list(package_tree.imports[module]['internal_file']) } for module in modules.keys() } dependents = { # type: ignore key: set() for key in dependencies.keys() } try: for key, values in dependencies.items(): for item in values: dependents[item].add(key) # type: ignore except KeyError: print("\n{}".format(dependents.keys())) print("\n{}".format(dependencies)) raise for package in internal_packages: build_graph_for_a_module( package, package_tree, dependencies, dependents, save_directory) def build_graph_for_a_module(graphed_package, package_tree, dependencies, dependents, save_directory): print(graphed_package) current_modules = sorted([ item.replace(os.sep, '.') for item in package_tree.digraph.neighbors(graphed_package) ]) outfilepath = os.path.join( save_directory, "{}.svg".format(graphed_package.replace(os.sep, '.'))) if not current_modules: dot_file_contents = """ strict digraph {{ subgraph cluster_0 {{ ""; label = "{}"; style = dashed; }} }} """.format(graphed_package) save_dot_file(dot_file_contents, outfilepath) return module_internal_relationships = { module.replace(os.sep, '.'): [ '.'.join(item.split('.')[0:2]) for item in package_tree.descendants_dependencies(module)['internal_module'] ] for module in sorted(list(package_tree.digraph.neighbors(graphed_package))) } levels = get_levels(module_internal_relationships) internal_nodes = sorted(list(set(module_internal_relationships.keys()))) external_nodes = set() for module in current_modules: external_nodes |= dependencies[module] external_nodes |= dependents[module] external_nodes = sorted(list(external_nodes)) all_nodes = internal_nodes + external_nodes def simplify(text): text = remove_prefix(text, "{}.".format(graphed_package)) text = remove_prefix(text, 'pymedphys_') return text label_map = { node: simplify(node) for node in all_nodes } nodes = "" for level in range(max(levels.keys()) + 1): if levels[level]: grouped_packages = '"; "'.join(sorted(list(levels[level]))) nodes += """ {{ rank = same; "{}"; }} """.format(grouped_packages) edges = "" current_packages = "" current_dependents = set() current_dependencies = set() for module in current_modules: current_packages += '"{}";\n'.format(module) for dependency in sorted(list(dependencies[module])): edges += '"{}" -> "{}";\n'.format(module, dependency) if not dependency in current_modules: current_dependencies.add(dependency) for dependent in sorted(list(dependents[module])): edges += '"{}" -> "{}";\n'.format(dependent, module) if not dependent in current_modules: current_dependents.add(dependent) external_ranks = "" if current_dependents: grouped_dependents = '"; "'.join(sorted(list(current_dependents))) external_ranks += '{{ rank = same; "{}"; }}\n'.format( grouped_dependents) if current_dependencies: grouped_dependencies = '"; "'.join(sorted(list(current_dependencies))) external_ranks += '{{ rank = same; "{}"; }}\n'.format( grouped_dependencies) external_labels = create_labels(label_map) dot_file_contents = """ strict digraph {{ rankdir = LR; subgraph cluster_0 {{ {} label = "{}"; URL = "{}"; style = dashed; {} }} {} {} {} }} """.format( current_packages, graphed_package, create_href(graphed_package), nodes, external_labels, external_ranks, edges) save_dot_file(dot_file_contents, outfilepath)
[]
[]
[]
archives/0mars_monoskel.zip
packages/monomanage/src/monomanage/draw/files.py
# Copyright (C) 2019 Simon Biggs # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import textwrap import networkx as nx from copy import copy from ..tree import PackageTree from .utilities import ( save_dot_file, remove_prefix, get_levels, remove_prefix, remove_postfix, convert_path_to_package, create_labels, create_href) ROOT = os.getcwd() def draw_file_modules(save_directory): package_tree = PackageTree(os.path.join(ROOT, 'packages')) internal_packages = copy(package_tree.roots) internal_packages.remove('pymedphys') directory_module_paths = [ module_path for package in internal_packages for module_path in package_tree.digraph.neighbors(package) ] file_module_paths = [ item for directory_module_path in directory_module_paths for item in package_tree.digraph.neighbors(directory_module_path) ] module_map = { item: convert_path_to_package(item) for item in directory_module_paths + file_module_paths } dependencies = { convert_path_to_package(module): { key: [ convert_path_to_package(item) for item in descendants_dependencies ] for key, descendants_dependencies in package_tree.imports[module].items() } for module in module_map.keys() } dependents = { key: [] for key in dependencies.keys() } for file_module, dependency_map in dependencies.items(): for where, values in dependency_map.items(): for item in values: try: dependents[item].append(file_module) except KeyError: pass for directory_module_path in directory_module_paths: directory_module = convert_path_to_package(directory_module_path) print(directory_module) package_name = directory_module.split('.')[0] current_modules = [ convert_path_to_package(item) for item in package_tree.digraph.neighbors(directory_module_path) ] + [directory_module] outfilepath = os.path.join( save_directory, "{}.svg".format(directory_module)) if len(current_modules) <= 1: dot_file_contents = """ strict digraph {{ subgraph cluster_0 {{ ""; label = "{}"; style = dashed; }} }} """.format(directory_module) save_dot_file(dot_file_contents, outfilepath) continue all_current_dependencies = { module: dependencies[module] for module in current_modules } keys_to_keep = {'internal_package', 'internal_module', 'internal_file'} current_dependencies = { module: [ item for key, values in dependencies[module].items() if key in keys_to_keep for item in values ] for module in current_modules } current_dependents = { module: dependents[module] for module in current_modules } all_nodes = sorted(list(set([ *current_dependencies.keys(), *[ item for a_list in current_dependencies.values() for item in a_list], *current_dependents.keys(), *[ item for a_list in current_dependents.values() for item in a_list] ]))) internal_dependencies = { key: [ value for value in values if value in current_modules ] for key, values in current_dependencies.items() if key in current_modules } internal_ranks = "" levels = get_levels(internal_dependencies) for level in range(max(levels.keys()) + 1): if levels[level]: grouped_packages = '"; "'.join(sorted(list(levels[level]))) internal_ranks += textwrap.dedent("""\ {{ rank = same; "{}"; }} """.format(grouped_packages)) in_same_module_other_dir = [ node for node in all_nodes if node.startswith(package_name) and not node.startswith(directory_module)] if in_same_module_other_dir: in_same_module_other_dir_string = '"{}";'.format( '";\n"'.join(in_same_module_other_dir)) else: in_same_module_other_dir_string = '' def simplify(text): text = remove_prefix(text, "{}.".format(package_name)) text = remove_prefix(text, 'pymedphys_') return text label_map = { node: simplify(node) for node in all_nodes } label_map_str = "" for node, label in label_map.items(): label_map_str += '"{}" [label="{}"] {};\n'.format( node, label, get_github_url(node)) edges = "" for module in sorted(current_modules): for dependency in sorted(list(current_dependencies[module])): edges += '"{}" -> "{}";\n'.format(module, dependency) for dependent in sorted(list(current_dependents[module])): edges += '"{}" -> "{}";\n'.format(dependent, module) dot_file_contents = textwrap.dedent("""\ strict digraph {{ rankdir = LR; subgraph cluster_0 {{ {} label = "{}"; URL = "{}"; style = dashed; subgraph cluster_1 {{ {} label = "{}"; URL = "{}" }} }} {} {}}} """).format( in_same_module_other_dir_string, package_name, create_href(package_name), textwrap.indent(internal_ranks, ' '*12), directory_module, create_href(directory_module), textwrap.indent(label_map_str, ' '*4), textwrap.indent(edges, ' '*4)) save_dot_file(dot_file_contents, outfilepath) def get_github_url(module): url_module = module.replace('.', '/') split_module = url_module.split('/') if len(split_module) == 3: url_module += '.py' top_level_package = split_module[0] url = "https://github.com/pymedphys/pymedphys/blob/master/packages/{}/src/{}".format( top_level_package, url_module ) hyperlink = '[URL="{}"]'.format(url) return hyperlink
[]
[]
[]
archives/0mars_monoskel.zip
packages/monomanage/src/monomanage/draw/packages.py
# Copyright (C) 2019 Simon Biggs # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import networkx as nx from ..tree.build import PackageTree from .utilities import save_dot_file, create_link ROOT = os.getcwd() def draw_packages(save_directory): print('pymedphys') tree = PackageTree('packages').package_dependencies_dict tree.pop('pymedphys') internal_packages = tuple(tree.keys()) keys = list(tree.keys()) keys.sort(reverse=True) dag = nx.DiGraph() for key in keys: values = tree[key] dag.add_node(key) dag.add_nodes_from(values['internal']) edge_tuples = [ (key, value) for value in values['internal'] ] dag.add_edges_from(edge_tuples) levels = get_levels(dag, internal_packages) dot_contents = build_dot_contents(dag, levels) save_dot_file(dot_contents, os.path.join(save_directory, 'pymedphys.svg')) def get_levels(dag, internal_packages): topological = list(nx.topological_sort(dag)) level_map = {} for package in topological[::-1]: if package not in internal_packages: level_map[package] = 0 else: depencencies = nx.descendants(dag, package) levels = {0} for dependency in depencencies: if dependency in internal_packages: try: levels.add(level_map[dependency]) except KeyError: pass max_level = max(levels) level_map[package] = max_level + 1 levels = { level: [] for level in range(max(level_map.values()) + 1) } for package, level in level_map.items(): levels[level].append(package) return levels def remove_prefix(text, prefix): if text.startswith(prefix): return text[len(prefix):] else: raise ValueError("Prefix not found.") def build_dot_contents(dag, levels): nodes = "" for level in range(max(levels.keys()) + 1): if levels[level]: trimmed_nodes = [ '"{}" {}'.format( remove_prefix(node, 'pymedphys_'), create_link(node)) for node in levels[level] ] grouped_packages = '; '.join(trimmed_nodes) nodes += """ {{ rank = same; {}; }} """.format(grouped_packages) edges = "" for edge in dag.edges(): trimmed_edge = [ remove_prefix(node, 'pymedphys_') for node in edge ] edges += "{} -> {};\n".format(*trimmed_edge) dot_file_contents = """ strict digraph {{ rankdir = LR; {}\n{} }} """.format(nodes, edges) return dot_file_contents
[]
[]
[]
archives/0mars_monoskel.zip
packages/monomanage/src/monomanage/draw/utilities.py
# Copyright (C) 2019 Simon Biggs # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import shutil import subprocess import networkx as nx def save_dot_file(dot_contents, outfilepath): tred = shutil.which("tred") dot = shutil.which("dot") if not tred or not dot: print( "Graph not drawn, please install graphviz and add it to " "your path.\nOn Windows this is done with " "`choco install graphviz.portable`.\n") return with open("temp.dot", 'w') as file: file.write(dot_contents) try: tred_process = subprocess.Popen( [tred, 'temp.dot'], stdout=subprocess.PIPE) data = tred_process.stdout.read() tred_process.wait() with open("temp_reduced.dot", 'wb') as file: file.write(data) output = subprocess.check_output( [dot, '-Tsvg', 'temp_reduced.dot', '-o', 'temp.svg']) shutil.move("temp.svg", outfilepath) shutil.move("temp_reduced.dot", os.path.splitext( outfilepath)[0] + ".dot") finally: os.remove("temp.dot") def remove_prefix(text, prefix): if text.startswith(prefix): return text[len(prefix):] else: return text def get_levels(dependency_map): dag = dag_from_hashmap_of_lists(dependency_map) topological = list(nx.topological_sort(dag)) level_map = {} for package in topological[::-1]: dependencies = nx.descendants(dag, package) levels = {0} for dependency in sorted(list(dependencies)): try: levels.add(level_map[dependency]) except KeyError: pass max_level = max(levels) level_map[package] = max_level + 1 levels = { level: [] for level in range(max(level_map.values()) + 1) } for package, level in level_map.items(): levels[level].append(package) return levels def dag_from_hashmap_of_lists(dictionary): keys = list(dictionary.keys()) keys.sort(reverse=True) dag = nx.DiGraph() for key in keys: values = sorted(dictionary[key], reverse=True) dag.add_node(key) dag.add_nodes_from(values) edge_tuples = [ (key, value) for value in values ] dag.add_edges_from(edge_tuples) return dag def remove_postfix(text, postfix): if text.endswith(postfix): return text[:-len(postfix)] else: return text def convert_path_to_package(path): return remove_postfix(path.replace(os.sep, '.'), '.py') def create_href(text): return '#{}'.format(text.replace('_', '-').replace('.', '-')) def create_link(text): return '[URL="{}"]'.format(create_href(text)) def create_labels(label_map): labels = "" for node, label in label_map.items(): labels += '"{}" [label="{}"] {};\n'.format( node, label, create_link(node)) return labels
[]
[]
[]
archives/0mars_monoskel.zip
packages/monomanage/src/monomanage/parse/__init__.py
[]
[]
[]
archives/0mars_monoskel.zip
packages/monomanage/src/monomanage/parse/imports.py
# Copyright (C) 2019 Simon Biggs # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import ast from stdlib_list import stdlib_list STDLIB = set(stdlib_list()) IMPORT_TYPES = { type(ast.parse('import george').body[0]), # type: ignore type(ast.parse('import george as macdonald').body[0])} # type: ignore IMPORT_FROM_TYPES = { type(ast.parse('from george import macdonald').body[0]) # type: ignore } ALL_IMPORT_TYPES = IMPORT_TYPES.union(IMPORT_FROM_TYPES) CONVERSIONS = { 'attr': 'attrs', 'PIL': 'Pillow', 'Image': 'Pillow', 'mpl_toolkits': 'matplotlib', 'dateutil': 'python_dateutil' } def get_imports(filepath, relative_filepath, internal_packages, depth): with open(filepath, 'r') as file: data = file.read() parsed = ast.parse(data) imports = [ node for node in ast.walk(parsed) if type(node) in ALL_IMPORT_TYPES] stdlib_imports = set() external_imports = set() internal_package_imports = set() internal_module_imports = set() internal_file_imports = set() def get_base_converted_module(name): name = name.split('.')[0] try: name = CONVERSIONS[name] except KeyError: pass return name def add_level_0(name): base_converted = get_base_converted_module(name) if base_converted in STDLIB: stdlib_imports.add(base_converted) elif base_converted in internal_packages: internal_package_imports.add(name) else: external_imports.add(base_converted) for an_import in imports: if type(an_import) in IMPORT_TYPES: for alias in an_import.names: add_level_0(alias.name) elif type(an_import) in IMPORT_FROM_TYPES: if an_import.level == 0: add_level_0(an_import.module) elif an_import.level == 1 and depth == 2: module_path = ( relative_filepath.split(os.sep)[0:2] + [an_import.module]) internal_file_imports.add('.'.join(module_path)) elif ( (an_import.level == 1 and depth == 1) or (an_import.level == 2 and depth == 2)): module_path = ( relative_filepath.split(os.sep)[0:1] + [an_import.module]) internal_module_imports.add('.'.join(module_path)) else: raise ValueError( "Unexpected depth and import level of relative " "import") else: raise TypeError("Unexpected import type") return { 'stdlib': stdlib_imports, 'external': external_imports, 'internal_package': internal_package_imports, 'internal_module': internal_module_imports, 'internal_file': internal_file_imports }
[]
[]
[]
archives/0mars_monoskel.zip
packages/monomanage/src/monomanage/propagate/__init__.py
[]
[]
[]
archives/0mars_monoskel.zip
packages/monomanage/src/monomanage/propagate/dependencies.py
# Copyright (C) 2019 Simon Biggs # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import textwrap import json from glob import glob ROOT = os.getcwd() def main(): with open(os.path.join(ROOT, 'dependencies.json'), 'r') as file: dependencies_data = json.load(file) tree = dependencies_data['tree'] pypi_pins = dependencies_data['pins']['pypi'] npm_pins = dependencies_data['pins']['npm'] internal_packages = [ os.path.basename(filepath) for filepath in glob(os.path.join(ROOT, 'packages', '*')) ] try: assert set(internal_packages) == set(tree.keys()) except AssertionError: print("Internal packages not in tree: {}".format( set(internal_packages).difference(set(tree.keys())))) print("Tree packages not in internal: {}".format( set(tree.keys()).difference(set(internal_packages)))) raise try: assert set(internal_packages) == set(pypi_pins['internal'].keys()) except AssertionError: internal = set(internal_packages) pypi = set(pypi_pins['internal'].keys()) print("Internal packages not in pinned: {}".format( internal.difference(pypi))) print("Pinned packages not in internal: {}".format( pypi.difference(internal))) raise assert set(internal_packages) == set(npm_pins['internal'].keys()) for package, dependency_store in tree.items(): install_requires = [] keys_to_keep = {'internal', 'external'} for where, dependencies in dependency_store.items(): if where in keys_to_keep: for dependency in dependencies: try: pin = " " + pypi_pins[where][dependency] except KeyError: pin = "" requirement_string = dependency + pin install_requires.append(requirement_string) install_requires.sort() install_requires_filepath = os.path.join( ROOT, "packages", package, "src", package, "_install_requires.py") install_requires_contents = textwrap.dedent("""\ install_requires = {} """).format(json.dumps(install_requires, indent=4)) with open(install_requires_filepath, 'w') as file: file.write(install_requires_contents) for package, dependency_store in tree.items(): internal_dependencies = { dependency: npm_pins['internal'][dependency] for dependency in dependency_store['internal'] } package_json_filepath = os.path.join( ROOT, "packages", package, "package.json") with open(package_json_filepath, 'r') as file: data = json.load(file) try: external_dependencies = { package: pin for package, pin in data['dependencies'].items() if package not in internal_packages } except KeyError: external_dependencies = {} data['dependencies'] = { **internal_dependencies, **external_dependencies } with open(package_json_filepath, 'w') as file: json.dump(data, file, indent=2, sort_keys=True) if __name__ == "__main__": main()
[]
[]
[]
archives/0mars_monoskel.zip
packages/monomanage/src/monomanage/propagate/versions.py
# Copyright (C) 2019 Simon Biggs # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import json from glob import glob import textwrap import semver ROOT = os.path.dirname(os.path.dirname(os.path.abspath(os.getcwd()))) def main(): version_filepath = glob(os.path.join( "src", "*", "_version.py"))[0] package_name = os.path.split(os.path.dirname(version_filepath))[-1] with open('package.json', 'r') as file: data = json.load(file) semver_string = data['version'] loaded_version_info = semver_string.replace( '.', ' ').replace('-', ' ').split(' ') version_info = [ int(number) for number in loaded_version_info[0:3] ] + [''.join(loaded_version_info[3::])] # type: ignore __version__ = '.'.join( map(str, version_info[:3])) + ''.join(version_info[3:]) # type: ignore version_file_contents = textwrap.dedent("""\ version_info = {} __version__ = "{}" """.format(version_info, __version__)) with open(version_filepath, 'w') as file: file.write(version_file_contents) semver_parsed = semver.parse(semver_string) if semver_parsed['major'] == 0: upper_limit = semver.bump_minor(semver_string) npm_version_prepend = "~" else: upper_limit = semver.bump_major(semver_string) npm_version_prepend = "^" dependencies_filepath = os.path.join(ROOT, "dependencies.json") with open(dependencies_filepath, 'r') as file: dependencies_data = json.load(file) dependencies_data['pins']['pypi']['internal'][package_name] = ( ">= {}, < {}".format(__version__, upper_limit)) dependencies_data['pins']['npm']['internal'][package_name] = ( "{}{}".format(npm_version_prepend, semver_string)) with open(dependencies_filepath, 'w') as file: json.dump(dependencies_data, file, indent=2, sort_keys=True) if __name__ == "__main__": main()
[]
[]
[]
archives/0mars_monoskel.zip
packages/monomanage/src/monomanage/tree/__init__.py
from .build import build_tree, test_tree, PackageTree from .check import is_imports_json_up_to_date, update_imports_json
[]
[]
[]
archives/0mars_monoskel.zip
packages/monomanage/src/monomanage/tree/build.py
# Copyright (C) 2019 Simon Biggs # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import json from copy import copy, deepcopy import difflib import networkx as nx from ..parse.imports import get_imports DEPENDENCIES_JSON_FILEPATH = 'dependencies.json' DEFAULT_EXCLUDE_DIRS = {'node_modules', '__pycache__', 'dist', '.tox', 'build'} DEFAULT_EXCLUDE_FILES = {'__init__.py', '_version.py', '_install_requires.py'} DEFAULT_KEYS_TO_KEEP = {'stdlib', 'internal', 'external'} class PackageTree: def __init__(self, directory, exclude_dirs=None, exclude_files=None): if exclude_dirs is None: exclude_dirs = DEFAULT_EXCLUDE_DIRS if exclude_files is None: exclude_files = DEFAULT_EXCLUDE_FILES self.exclude_dirs = exclude_dirs self.exclude_files = exclude_files self.directory = directory def trim_path(self, path): relpath = os.path.relpath(path, self.directory) split = relpath.split(os.sep) assert split[0] == split[2] assert split[1] == 'src' if split[-1] == '__init__.py': split = split[:-1] return os.path.join(*split[2:]) def expand_path(self, path): split = path.split(os.sep) relpath = os.path.join(split[0], 'src', path) if not relpath.endswith('.py'): relpath = os.path.join(relpath, '__init__.py') return os.path.join(self.directory, relpath) def build_directory_digraph(self): digraph = nx.DiGraph() depth = {} for root, dirs, files in os.walk(self._directory, topdown=True): dirs[:] = [d for d in dirs if d not in self.exclude_dirs] if '__init__.py' in files: module = self.trim_path(os.path.join(root, '__init__.py')) current_depth = module.count(os.sep) + 1 files[:] = [f for f in files if f not in self.exclude_files] digraph.add_node(module) depth[module] = current_depth parent_init = os.path.join( os.path.dirname(root), '__init__.py') if os.path.exists(parent_init): digraph.add_edge(self.trim_path(parent_init), module) for f in files: if f.endswith('.py'): filepath = self.trim_path(os.path.join(root, f)) digraph.add_node(filepath) depth[filepath] = current_depth digraph.add_edge(module, filepath) if not digraph.nodes: raise ValueError('Directory provided does not contain modules') self.digraph = digraph self.depth = depth self.calc_properties() def calc_properties(self): self.roots = [n for n, d in self.digraph.in_degree() if d == 0] self.imports = { filepath: get_imports( self.expand_path(filepath), filepath, self.roots, self.depth[filepath]) for filepath in self.digraph.nodes() } self._cache = {} self._cache['descendants_dependencies'] = {} @property def directory(self): return self._directory @directory.setter def directory(self, value): self._directory = value self.build_directory_digraph() def descendants_dependencies(self, filepath): try: return self._cache['descendants_dependencies'][filepath] except KeyError: dependencies = deepcopy(self.imports[filepath]) for descendant in nx.descendants(self.digraph, filepath): for key in dependencies: dependencies[key] |= self.imports[descendant][key] for key in dependencies: dependencies[key] = list(dependencies[key]) dependencies[key].sort() self._cache['descendants_dependencies'][filepath] = dependencies return dependencies @property def package_dependencies_dict(self): try: return self._cache['package_dependencies_dict'] except KeyError: key_map = { 'internal_package': 'internal', 'external': 'external', 'stdlib': 'stdlib' } tree = { package: { key_map[key]: sorted( list({package.split('.')[0] for package in packages})) for key, packages in self.descendants_dependencies(package).items() if key in key_map.keys() } for package in self.roots } self._cache['package_dependencies_dict'] = tree return tree @property def package_dependencies_digraph(self): try: return self._cache['package_dependencies_digraph'] except KeyError: dag = nx.DiGraph() for key, values in self.package_dependencies_dict.items(): dag.add_node(key) dag.add_nodes_from(values['internal']) edge_tuples = [ (key, value) for value in values['internal'] ] dag.add_edges_from(edge_tuples) self._cache['package_dependencies_digraph'] = dag return dag def is_acyclic(self): return nx.is_directed_acyclic_graph(self.package_dependencies_digraph) def build_tree(directory): with open(DEPENDENCIES_JSON_FILEPATH, 'r') as file: data = json.load(file) data['tree'] = PackageTree(directory).package_dependencies_dict with open(DEPENDENCIES_JSON_FILEPATH, 'w') as file: json.dump(data, file, indent=2, sort_keys=True) def test_tree(directory): package_tree = PackageTree(directory) assert package_tree.is_acyclic() assert_tree_unchanged(package_tree.package_dependencies_dict) def assert_tree_unchanged(tree): with open(DEPENDENCIES_JSON_FILEPATH, 'r') as file: data = json.load(file) file_data = json.dumps(data['tree'], sort_keys=True, indent=2) calced_data = json.dumps(tree, sort_keys=True, indent=2) if file_data != calced_data: diff = difflib.unified_diff( file_data.split('\n'), calced_data.split('\n')) print('\n'.join(diff)) raise AssertionError
[]
[]
[]
archives/0mars_monoskel.zip
packages/monomanage/src/monomanage/tree/check.py
# Copyright (C) 2019 Simon Biggs # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import sys import json import subprocess import shutil from .build import PackageTree def serialise_imports(imports): new_imports = {} for module_path_raw, values in imports.items(): module_path = module_path_raw.replace(os.sep, '/') new_imports[module_path] = {} for where, a_set in values.items(): new_imports[module_path][where] = sorted(list(a_set)) return json.dumps(new_imports, sort_keys=True, indent=2) def is_imports_json_up_to_date(directory): packages = os.path.join(directory, 'packages') imports_json = os.path.join(directory, 'imports.json') with open(imports_json) as file: data = json.load(file) file_data = json.dumps(data, sort_keys=True, indent=2) calced_data = serialise_imports(PackageTree(packages).imports) return file_data == calced_data def commit_hook(directory): if not is_imports_json_up_to_date(directory): print( "\n \033[1;31;1mThe dependency tree is out of date." "\033[1;32;1m Will now run `yarn tree` to update.\n" " \033[1;34;1mYou will need to rerun `git commit` after " "this is complete.\033[0;0m\n" ) sys.stdout.flush() yarn = shutil.which("yarn") git = shutil.which("git") subprocess.call([yarn, "tree"]) subprocess.call([git, "add", "imports.json"]) subprocess.call([git, "add", "dependencies.json"]) subprocess.call([git, "add", "*package.json"]) subprocess.call([git, "add", "*_install_requires.py"]) subprocess.call([git, "add", "*.dot"]) subprocess.call([git, "status"]) print( "\n \033[1;31;1mThe dependency tree was out of date.\n" " \033[1;32;1mThe command `yarn tree` has been run for " "you.\n" " \033[1;34;1mPlease rerun your commit.\033[0;0m\n" " To prevent this message in the future run `yarn tree` " "whenever you change the dependency structure of " "PyMedPhys.\n") sys.exit(1) def update_imports_json(directory): packages = os.path.join(directory, 'packages') imports_json = os.path.join(directory, 'imports.json') with open(imports_json, 'w') as file: file.write(serialise_imports(PackageTree(packages).imports))
[]
[]
[]
archives/0mars_monoskel.zip
packages/registry/setup.py
from os.path import abspath, dirname, join as pjoin from setuptools import setup, find_packages root = dirname(abspath(__file__)) def execfile(fname, globs, locs=None): locs = locs or globs exec(compile(open(fname).read(), fname, "exec"), globs, locs) source_path = 'src' packages = find_packages(source_path) root_packages = [ package for package in packages if "." not in package ] assert len(root_packages) == 1 package = root_packages[0] package_directory = pjoin(root, source_path, package) def get_variable_from_file(filepath, variable): filepath_in_package = pjoin(package_directory, filepath) globs = {} execfile(filepath_in_package, globs) variable_value = globs[variable] return variable_value version = get_variable_from_file('_version.py', '__version__') setup( name=package, version=version, python_requires='>=3.6', description='', classifiers=[ 'Development Status :: Stable', 'License :: OSI Approved :: General Public License v3 or later (AGPLv3+)', 'Programming Language :: Python :: 3.7', 'Intended Audience :: Developers' ], packages=packages, package_dir={'': source_path}, include_package_data=True, package_data={package: []}, license='AGPL-3.0-or-later', extras_require={ 'test': [ 'pytest' ] } )
[]
[]
[]
archives/0mars_monoskel.zip
packages/registry/src/registry/__init__.py
from . import services
[]
[]
[]
archives/0mars_monoskel.zip
packages/registry/src/registry/_version.py
version_info = [0, 1, 0] __version__ = "0.1.0"
[]
[]
[]
archives/0mars_monoskel.zip
packages/registry/src/registry/services.py
from abc import ABC, abstractmethod from enum import Enum class Props(Enum): pass class Container(object): def __init__(self): self.vars = {} def set(self, prop: Props, value): self.vars[prop] = value def get(self, key: Props): return self.vars[key] class BootableService(ABC): @abstractmethod def boot(self, container: Container): raise NotImplemented('Service not implemented') def post_boot(self, container): pass class Registry(object): """ Service registry is where to register bootable services to be booted """ def __init__(self): self.services: list = [] def register(self, service: BootableService): self.services.append(service) def boot(self, container: Container): for service in self.services: service.boot(container) for service in self.services: service.post_boot(container)
[ "Props", "Props", "Container", "BootableService", "Container" ]
[ 188, 259, 378, 698, 785 ]
[ 193, 264, 387, 713, 794 ]
archives/1098994933_python.zip
arithmetic_analysis/bisection.py
import math def bisection(function, a, b): # finds where the function becomes 0 in [a,b] using bolzano start = a end = b if function(a) == 0: # one of the a or b is a root for the function return a elif function(b) == 0: return b elif function(a) * function(b) > 0: # if none of these are root and they are both positive or negative, # then his algorithm can't find the root print("couldn't find root in [a,b]") return else: mid = start + (end - start) / 2.0 while abs(start - mid) > 10**-7: # until we achieve precise equals to 10^-7 if function(mid) == 0: return mid elif function(mid) * function(start) < 0: end = mid else: start = mid mid = start + (end - start) / 2.0 return mid def f(x): return math.pow(x, 3) - 2*x - 5 if __name__ == "__main__": print(bisection(f, 1, 1000))
[]
[]
[]
archives/1098994933_python.zip
arithmetic_analysis/in_static_equilibrium.py
""" Checks if a system of forces is in static equilibrium. python/black : true flake8 : passed mypy : passed """ from numpy import array, cos, sin, radians, cross # type: ignore from typing import List def polar_force( magnitude: float, angle: float, radian_mode: bool = False ) -> List[float]: """ Resolves force along rectangular components. (force, angle) => (force_x, force_y) >>> polar_force(10, 45) [7.0710678118654755, 7.071067811865475] >>> polar_force(10, 3.14, radian_mode=True) [-9.999987317275394, 0.01592652916486828] """ if radian_mode: return [magnitude * cos(angle), magnitude * sin(angle)] return [magnitude * cos(radians(angle)), magnitude * sin(radians(angle))] def in_static_equilibrium( forces: array, location: array, eps: float = 10 ** -1 ) -> bool: """ Check if a system is in equilibrium. It takes two numpy.array objects. forces ==> [ [force1_x, force1_y], [force2_x, force2_y], ....] location ==> [ [x1, y1], [x2, y2], ....] >>> force = array([[1, 1], [-1, 2]]) >>> location = array([[1, 0], [10, 0]]) >>> in_static_equilibrium(force, location) False """ # summation of moments is zero moments: array = cross(location, forces) sum_moments: float = sum(moments) return abs(sum_moments) < eps if __name__ == "__main__": # Test to check if it works forces = array( [ polar_force(718.4, 180 - 30), polar_force(879.54, 45), polar_force(100, -90) ]) location = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) # Problem 1 in image_data/2D_problems.jpg forces = array( [ polar_force(30 * 9.81, 15), polar_force(215, 180 - 45), polar_force(264, 90 - 30), ] ) location = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) # Problem in image_data/2D_problems_1.jpg forces = array([[0, -2000], [0, -1200], [0, 15600], [0, -12400]]) location = array([[0, 0], [6, 0], [10, 0], [12, 0]]) assert in_static_equilibrium(forces, location) import doctest doctest.testmod()
[ "float", "float", "array", "array" ]
[ 252, 266, 808, 825 ]
[ 257, 271, 813, 830 ]
archives/1098994933_python.zip
arithmetic_analysis/intersection.py
import math def intersection(function,x0,x1): #function is the f we want to find its root and x0 and x1 are two random starting points x_n = x0 x_n1 = x1 while True: x_n2 = x_n1-(function(x_n1)/((function(x_n1)-function(x_n))/(x_n1-x_n))) if abs(x_n2 - x_n1) < 10**-5: return x_n2 x_n=x_n1 x_n1=x_n2 def f(x): return math.pow(x , 3) - (2 * x) -5 if __name__ == "__main__": print(intersection(f,3,3.5))
[]
[]
[]
archives/1098994933_python.zip
arithmetic_analysis/lu_decomposition.py
"""Lower-Upper (LU) Decomposition.""" # lower–upper (LU) decomposition - https://en.wikipedia.org/wiki/LU_decomposition import numpy def LUDecompose(table): # Table that contains our data # Table has to be a square array so we need to check first rows, columns = numpy.shape(table) L = numpy.zeros((rows, columns)) U = numpy.zeros((rows, columns)) if rows != columns: return [] for i in range(columns): for j in range(i - 1): sum = 0 for k in range(j - 1): sum += L[i][k] * U[k][j] L[i][j] = (table[i][j] - sum) / U[j][j] L[i][i] = 1 for j in range(i - 1, columns): sum1 = 0 for k in range(i - 1): sum1 += L[i][k] * U[k][j] U[i][j] = table[i][j] - sum1 return L, U if __name__ == "__main__": matrix = numpy.array([[2, -2, 1], [0, 1, 2], [5, 3, 1]]) L, U = LUDecompose(matrix) print(L) print(U)
[]
[]
[]
archives/1098994933_python.zip
arithmetic_analysis/newton_method.py
"""Newton's Method.""" # Newton's Method - https://en.wikipedia.org/wiki/Newton%27s_method # function is the f(x) and function1 is the f'(x) def newton(function, function1, startingInt): x_n = startingInt while True: x_n1 = x_n - function(x_n) / function1(x_n) if abs(x_n - x_n1) < 10**-5: return x_n1 x_n = x_n1 def f(x): return (x**3) - (2 * x) - 5 def f1(x): return 3 * (x**2) - 2 if __name__ == "__main__": print(newton(f, f1, 3))
[]
[]
[]
archives/1098994933_python.zip
arithmetic_analysis/newton_raphson_method.py
# Implementing Newton Raphson method in Python # Author: Syed Haseeb Shah (github.com/QuantumNovice) from sympy import diff from decimal import Decimal def NewtonRaphson(func, a): ''' Finds root from the point 'a' onwards by Newton-Raphson method ''' while True: c = Decimal(a) - ( Decimal(eval(func)) / Decimal(eval(str(diff(func)))) ) a = c # This number dictates the accuracy of the answer if abs(eval(func)) < 10**-15: return c # Let's Execute if __name__ == '__main__': # Find root of trigonometric function # Find value of pi print('sin(x) = 0', NewtonRaphson('sin(x)', 2)) # Find root of polynomial print('x**2 - 5*x +2 = 0', NewtonRaphson('x**2 - 5*x +2', 0.4)) # Find Square Root of 5 print('x**2 - 5 = 0', NewtonRaphson('x**2 - 5', 0.1)) # Exponential Roots print('exp(x) - 1 = 0', NewtonRaphson('exp(x) - 1', 0))
[]
[]
[]
archives/1098994933_python.zip
backtracking/all_combinations.py
# -*- coding: utf-8 -*- """ In this problem, we want to determine all possible combinations of k numbers out of 1 ... n. We use backtracking to solve this problem. Time complexity: O(C(n,k)) which is O(n choose k) = O((n!/(k! * (n - k)!))) """ def generate_all_combinations(n: int, k: int) -> [[int]]: """ >>> generate_all_combinations(n=4, k=2) [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]] """ result = [] create_all_state(1, n, k, [], result) return result def create_all_state(increment, total_number, level, current_list, total_list): if level == 0: total_list.append(current_list[:]) return for i in range(increment, total_number - level + 2): current_list.append(i) create_all_state(i + 1, total_number, level - 1, current_list, total_list) current_list.pop() def print_all_state(total_list): for i in total_list: print(*i) if __name__ == '__main__': n = 4 k = 2 total_list = generate_all_combinations(n, k) print_all_state(total_list)
[ "int", "int" ]
[ 283, 291 ]
[ 286, 294 ]
archives/1098994933_python.zip
backtracking/all_permutations.py
''' In this problem, we want to determine all possible permutations of the given sequence. We use backtracking to solve this problem. Time complexity: O(n! * n), where n denotes the length of the given sequence. ''' def generate_all_permutations(sequence): create_state_space_tree(sequence, [], 0, [0 for i in range(len(sequence))]) def create_state_space_tree(sequence, current_sequence, index, index_used): ''' Creates a state space tree to iterate through each branch using DFS. We know that each state has exactly len(sequence) - index children. It terminates when it reaches the end of the given sequence. ''' if index == len(sequence): print(current_sequence) return for i in range(len(sequence)): if not index_used[i]: current_sequence.append(sequence[i]) index_used[i] = True create_state_space_tree(sequence, current_sequence, index + 1, index_used) current_sequence.pop() index_used[i] = False ''' remove the comment to take an input from the user print("Enter the elements") sequence = list(map(int, input().split())) ''' sequence = [3, 1, 2, 4] generate_all_permutations(sequence) sequence = ["A", "B", "C"] generate_all_permutations(sequence)
[]
[]
[]
archives/1098994933_python.zip
backtracking/all_subsequences.py
''' In this problem, we want to determine all possible subsequences of the given sequence. We use backtracking to solve this problem. Time complexity: O(2^n), where n denotes the length of the given sequence. ''' def generate_all_subsequences(sequence): create_state_space_tree(sequence, [], 0) def create_state_space_tree(sequence, current_subsequence, index): ''' Creates a state space tree to iterate through each branch using DFS. We know that each state has exactly two children. It terminates when it reaches the end of the given sequence. ''' if index == len(sequence): print(current_subsequence) return create_state_space_tree(sequence, current_subsequence, index + 1) current_subsequence.append(sequence[index]) create_state_space_tree(sequence, current_subsequence, index + 1) current_subsequence.pop() ''' remove the comment to take an input from the user print("Enter the elements") sequence = list(map(int, input().split())) ''' sequence = [3, 1, 2, 4] generate_all_subsequences(sequence) sequence = ["A", "B", "C"] generate_all_subsequences(sequence)
[]
[]
[]
archives/1098994933_python.zip
backtracking/minimax.py
import math ''' Minimax helps to achieve maximum score in a game by checking all possible moves depth is current depth in game tree. nodeIndex is index of current node in scores[]. if move is of maximizer return true else false leaves of game tree is stored in scores[] height is maximum height of Game tree ''' def minimax (Depth, nodeIndex, isMax, scores, height): if Depth == height: return scores[nodeIndex] if isMax: return (max(minimax(Depth + 1, nodeIndex * 2, False, scores, height), minimax(Depth + 1, nodeIndex * 2 + 1, False, scores, height))) return (min(minimax(Depth + 1, nodeIndex * 2, True, scores, height), minimax(Depth + 1, nodeIndex * 2 + 1, True, scores, height))) if __name__ == "__main__": scores = [90, 23, 6, 33, 21, 65, 123, 34423] height = math.log(len(scores), 2) print("Optimal value : ", end = "") print(minimax(0, 0, True, scores, height))
[]
[]
[]
archives/1098994933_python.zip
backtracking/n_queens.py
''' The nqueens problem is of placing N queens on a N * N chess board such that no queen can attack any other queens placed on that chess board. This means that one queen cannot have any other queen on its horizontal, vertical and diagonal lines. ''' solution = [] def isSafe(board, row, column): ''' This function returns a boolean value True if it is safe to place a queen there considering the current state of the board. Parameters : board(2D matrix) : board row ,column : coordinates of the cell on a board Returns : Boolean Value ''' for i in range(len(board)): if board[row][i] == 1: return False for i in range(len(board)): if board[i][column] == 1: return False for i,j in zip(range(row,-1,-1),range(column,-1,-1)): if board[i][j] == 1: return False for i,j in zip(range(row,-1,-1),range(column,len(board))): if board[i][j] == 1: return False return True def solve(board, row): ''' It creates a state space tree and calls the safe function untill it receives a False Boolean and terminates that brach and backtracks to the next poosible solution branch. ''' if row >= len(board): ''' If the row number exceeds N we have board with a successful combination and that combination is appended to the solution list and the board is printed. ''' solution.append(board) printboard(board) print() return for i in range(len(board)): ''' For every row it iterates through each column to check if it is feesible to place a queen there. If all the combinations for that particaular branch are successfull the board is reinitialized for the next possible combination. ''' if isSafe(board,row,i): board[row][i] = 1 solve(board,row+1) board[row][i] = 0 return False def printboard(board): ''' Prints the boards that have a successfull combination. ''' for i in range(len(board)): for j in range(len(board)): if board[i][j] == 1: print("Q", end = " ") else : print(".", end = " ") print() #n=int(input("The no. of queens")) n = 8 board = [[0 for i in range(n)]for j in range(n)] solve(board, 0) print("The total no. of solutions are :", len(solution))
[]
[]
[]