index
int64
repo_name
string
branch_name
string
path
string
content
string
import_graph
string
4,750
gboquizo/hackathon_optimizacion_entregas_material
refs/heads/master
/app/utils.py
import os import sys from pprint import pprint def dd(variable): pprint(variable) sys.exit()
{"/app/modules/donor.py": ["/app/__init__.py", "/app/models.py"], "/app/schemas.py": ["/app/__init__.py", "/app/models.py"], "/app/__init__.py": ["/app/modules/auth.py", "/app/modules/admin.py", "/app/modules/dealer.py", "/app/modules/donor.py"], "/app/models.py": ["/app/__init__.py"], "/app/modules/admin.py": ["/app/models.py"], "/app/modules/dealer.py": ["/app/__init__.py"], "/main.py": ["/app/__init__.py"], "/app/modules/auth.py": ["/app/__init__.py", "/app/forms.py", "/app/models.py"]}
4,751
gboquizo/hackathon_optimizacion_entregas_material
refs/heads/master
/app/modules/dealer.py
# app/modules/manager.py import os from app import db from flask import render_template, Blueprint, request, flash, redirect, send_file, jsonify from flask_login import login_required, current_user from werkzeug.utils import secure_filename from werkzeug.exceptions import abort # Use modules for each logical domain dealer_bp = Blueprint('dealer', __name__) @dealer_bp.route('/map') def index(): print("Llega") return render_template('dealer/dealer.html', data={})
{"/app/modules/donor.py": ["/app/__init__.py", "/app/models.py"], "/app/schemas.py": ["/app/__init__.py", "/app/models.py"], "/app/__init__.py": ["/app/modules/auth.py", "/app/modules/admin.py", "/app/modules/dealer.py", "/app/modules/donor.py"], "/app/models.py": ["/app/__init__.py"], "/app/modules/admin.py": ["/app/models.py"], "/app/modules/dealer.py": ["/app/__init__.py"], "/main.py": ["/app/__init__.py"], "/app/modules/auth.py": ["/app/__init__.py", "/app/forms.py", "/app/models.py"]}
4,752
gboquizo/hackathon_optimizacion_entregas_material
refs/heads/master
/main.py
# !usr/bin/env python import os from app import create_app app = create_app() if __name__ == "__main__": app.run(debug=os.getenv('FLASK_DEBUG'))
{"/app/modules/donor.py": ["/app/__init__.py", "/app/models.py"], "/app/schemas.py": ["/app/__init__.py", "/app/models.py"], "/app/__init__.py": ["/app/modules/auth.py", "/app/modules/admin.py", "/app/modules/dealer.py", "/app/modules/donor.py"], "/app/models.py": ["/app/__init__.py"], "/app/modules/admin.py": ["/app/models.py"], "/app/modules/dealer.py": ["/app/__init__.py"], "/main.py": ["/app/__init__.py"], "/app/modules/auth.py": ["/app/__init__.py", "/app/forms.py", "/app/models.py"]}
4,753
gboquizo/hackathon_optimizacion_entregas_material
refs/heads/master
/app/modules/auth.py
# app/modules/auth.py """Routes for user authentication.""" from app import login_manager, db from app.forms import LoginForm, RegisterForm from app.models import User from flask import render_template, redirect, flash, url_for, Blueprint, request from flask_login import current_user, login_user, logout_user, login_required from werkzeug.urls import url_parse # Blueprint Configuration auth_bp = Blueprint('auth', __name__) # Middleware to authorization @login_manager.unauthorized_handler def unauthorized(): """Redirect unauthorized users to Login page.""" return redirect(url_for('auth.login')) # Middleware to check if a user is authenticated. @login_manager.user_loader def load_user(user_id): """Check if auth is logged-in on every page load.""" if user_id is not None: return User.query.get(user_id) return None @auth_bp.route('/index') @auth_bp.route('/') def index(): return render_template('auth/index.html', title='Index') # Route to register a user. @auth_bp.route('/register', methods=['GET', 'POST']) def register(): """ User registration page.""" register_form = RegisterForm(request.form) if request.method == 'POST' and register_form.validate_on_submit(): existing_user = User.query.filter_by(email=register_form.email.data).first() if existing_user is None: user = User( email=request.form.get('email'), password=request.form.get('password'), username=request.form.get('username') ) db.session.add(user) db.session.commit() login_user(user) return redirect(url_for('auth.index')) flash('A user already exists with that email address') return redirect(url_for('auth.register')) return render_template('auth/register.html', title='Create an Account | ', form=register_form) # Route to sign in a user. @auth_bp.route('/login', methods=['GET', 'POST']) def login(): """ User login page.""" if current_user.is_authenticated: return redirect(url_for('auth.index')) login_form = LoginForm(request.form) if request.method == 'POST' and login_form.validate_on_submit(): user = User.query.filter_by(email=login_form.email.data).first() if user is None or not user.check_password(login_form.password.data): flash('Invalid username or password') return redirect(url_for('auth.login')) login_user(user, remember=login_form.remember_me.data) next_page = request.args.get('next') if not next_page or url_parse(next_page).netloc != '': next_page = url_for('auth.show') return redirect(next_page) return render_template('auth/login.html', title='Sign in | ', form=login_form) # Route to logout a user. @auth_bp.route('/logout') @login_required def logout(): """User logout logic.""" logout_user() return redirect(url_for('auth.index'))
{"/app/modules/donor.py": ["/app/__init__.py", "/app/models.py"], "/app/schemas.py": ["/app/__init__.py", "/app/models.py"], "/app/__init__.py": ["/app/modules/auth.py", "/app/modules/admin.py", "/app/modules/dealer.py", "/app/modules/donor.py"], "/app/models.py": ["/app/__init__.py"], "/app/modules/admin.py": ["/app/models.py"], "/app/modules/dealer.py": ["/app/__init__.py"], "/main.py": ["/app/__init__.py"], "/app/modules/auth.py": ["/app/__init__.py", "/app/forms.py", "/app/models.py"]}
4,754
gboquizo/hackathon_optimizacion_entregas_material
refs/heads/master
/app/forms.py
from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, BooleanField, SubmitField from wtforms.validators import DataRequired, Email, EqualTo, Length class LoginForm(FlaskForm): """User Login Form.""" email = StringField('Correo electrónico', validators=[ Email('Por favor, introduce un correo electrónico válido.'), DataRequired('Por favor, introduce un correo.') ]) password = PasswordField('Contraseña', validators=[DataRequired('Oh, ¿y la contraseña?')]) remember_me = BooleanField('Recuérdame') submit = SubmitField('Entrar') class RegisterForm(FlaskForm): """User Register Form.""" email = StringField('Email', validators=[ Email('Por favor, introduce un correo electrónico válido.'), DataRequired('Por favor, introduce un correo.') ]) username = StringField('Nombre de usuario', validators=[DataRequired('¡Introduce un nombre de usuario!')]) password = PasswordField('Contraseña', validators=[ DataRequired('Por favor, introduzca una contraseña.'), Length(min=8, message='La contraseña tiene que ser más fuerte. Al menos 8 caracteres.'), EqualTo('password_confirm', message='Las contraseñas tienen que coincidir') ]) password_confirm = PasswordField('Confirma tu contraseña') submit = SubmitField('Registrarme')
{"/app/modules/donor.py": ["/app/__init__.py", "/app/models.py"], "/app/schemas.py": ["/app/__init__.py", "/app/models.py"], "/app/__init__.py": ["/app/modules/auth.py", "/app/modules/admin.py", "/app/modules/dealer.py", "/app/modules/donor.py"], "/app/models.py": ["/app/__init__.py"], "/app/modules/admin.py": ["/app/models.py"], "/app/modules/dealer.py": ["/app/__init__.py"], "/main.py": ["/app/__init__.py"], "/app/modules/auth.py": ["/app/__init__.py", "/app/forms.py", "/app/models.py"]}
4,784
tschuy/gpi-web
refs/heads/master
/gpi/gpi_web/models.py
import os from django.db import models from django.contrib.auth.models import User from semantic_version.django_fields import VersionField def version_file_name(instance, filename): filename = '/'.join( [instance.project.package_name, unicode(instance.version), '{}-{}.tar.gz'.format( instance.project.package_name, unicode(instance.version))]) # remove file if it exists if os.path.exists(filename): os.remove(filename) return filename class Release(models.Model): def __unicode__(self): return unicode(self.version) file = models.FileField(upload_to=version_file_name) version = VersionField() project = models.ForeignKey('Project') created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) class Project(models.Model): def __unicode__(self): return self.name name = models.CharField(max_length=50) package_name = models.CharField(max_length=50) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) owner = models.ForeignKey(User) class Email(models.Model): def __unicode__(self): return self.email email = models.EmailField(unique=True)
{"/gpi/gpi_web/admin.py": ["/gpi/gpi_web/models.py"], "/gpi/gpi_web/serializer.py": ["/gpi/gpi_web/models.py"]}
4,785
tschuy/gpi-web
refs/heads/master
/gpi/gpi_web/views.py
from django.http import JsonResponse from django.shortcuts import get_object_or_404, render from django.views.decorators.http import require_POST from django.core.exceptions import ValidationError from django.core.validators import validate_email from django.db import IntegrityError import json from gpi.gpi_web.models import Release, Project, Email from gpi.gpi_web.serializer import PackageSerializer def project_details(request, name=None): project = get_object_or_404(Project, package_name=name) serializer = PackageSerializer() data = json.loads( serializer.serialize( [project], use_natural_foreign_keys=True )[1:-1] ) return JsonResponse(data) def project_list(request): projects = Project.objects.all() serializer = PackageSerializer() data = json.loads( serializer.serialize( projects, use_natural_foreign_keys=True ) ) return JsonResponse(data, safe=False) def index(request): return render(request, 'index.html', {}) @require_POST def email(request): try: print request.GET.get('email') validate_email(request.GET.get('email')) email = Email.objects.create(email=request.GET.get('email')) except IntegrityError: return JsonResponse( {'status': False, 'errortext': "You've already signed up!"}) except ValidationError: return JsonResponse( {'status': False, 'errortext': 'Invalid email address!'}) else: return JsonResponse({'status': True})
{"/gpi/gpi_web/admin.py": ["/gpi/gpi_web/models.py"], "/gpi/gpi_web/serializer.py": ["/gpi/gpi_web/models.py"]}
4,786
tschuy/gpi-web
refs/heads/master
/gpi/gpi_web/admin.py
from django.contrib import admin from gpi.gpi_web.models import Release, Project class ReleaseAdmin(admin.ModelAdmin): pass class ProjectAdmin(admin.ModelAdmin): pass admin.site.register(Release, ReleaseAdmin) admin.site.register(Project, ProjectAdmin)
{"/gpi/gpi_web/admin.py": ["/gpi/gpi_web/models.py"], "/gpi/gpi_web/serializer.py": ["/gpi/gpi_web/models.py"]}
4,787
tschuy/gpi-web
refs/heads/master
/gpi/gpi_web/serializer.py
from django.core.serializers import json from gpi.gpi_web.models import Project, Release class PackageSerializer(json.Serializer): def get_dump_object(self, obj): self._current['id'] = obj.id if isinstance(obj, Project): self._current['releases'] = [ { 'file': release.file.url, 'version': str(release.version) } for release in sorted( obj.release_set.all(), key=lambda o: o.version, reverse=True) ] self._current['owner'] = obj.owner.username; return self._current
{"/gpi/gpi_web/admin.py": ["/gpi/gpi_web/models.py"], "/gpi/gpi_web/serializer.py": ["/gpi/gpi_web/models.py"]}
4,788
tschuy/gpi-web
refs/heads/master
/gpi/gpi_web/urls.py
from django.conf.urls import patterns from django.conf.urls import url urlpatterns = patterns( '', url(r'^package/(?P<name>[^/]+)/?$', 'gpi.gpi_web.views.project_details', name='package-details'), url(r'^packages/?$', 'gpi.gpi_web.views.project_list', name='package-list'), )
{"/gpi/gpi_web/admin.py": ["/gpi/gpi_web/models.py"], "/gpi/gpi_web/serializer.py": ["/gpi/gpi_web/models.py"]}
4,789
tschuy/gpi-web
refs/heads/master
/gpi/gpi_web/__init__.py
default_app_config = 'gpi.gpi_web.YourAppConfig' from django.apps import AppConfig class YourAppConfig(AppConfig): name = 'gpi.gpi_web' verbose_name = 'GIMP Plugin Installer'
{"/gpi/gpi_web/admin.py": ["/gpi/gpi_web/models.py"], "/gpi/gpi_web/serializer.py": ["/gpi/gpi_web/models.py"]}
4,790
redhat-openstack/octario
refs/heads/master
/plugins/callbacks/debug.py
# Copyright 2016 Red Hat, Inc. # All Rights Reserved. # # 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. """ debug module is the new name of the human_readably module """ from __future__ import (absolute_import, division, print_function) from ansible.plugins.callback.default \ import CallbackModule as CallbackModule_default __metaclass__ = type class CallbackModule(CallbackModule_default): # pylint: \ # disable=too-few-public-methods,no-init ''' Override for the default callback module. Render std err/out outside of the rest of the result which it prints with indentation. ''' CALLBACK_VERSION = 2.0 CALLBACK_TYPE = 'stdout' CALLBACK_NAME = 'debug' def _dump_results(self, result): '''Return the text to output for a result.''' # Enable JSON identation result['_ansible_verbose_always'] = True save = {} for key in ['stdout', 'stdout_lines', 'stderr', 'stderr_lines', 'msg']: if key in result: save[key] = result.pop(key) output = CallbackModule_default._dump_results(self, result) for key in ['stdout', 'stderr', 'msg']: if key in save and save[key]: output += '\n\n%s:\n\n%s\n' % (key.upper(), save[key]) for key, value in save.items(): result[key] = value return output
{"/octario/lib/logger.py": ["/octario/lib/exceptions.py"], "/octario/lib/exceptions.py": ["/octario/lib/tester.py"], "/ir-plugin/osp_version_name.py": ["/octario/lib/component.py"], "/octario/lib/cli.py": ["/octario/lib/component.py", "/octario/lib/tester.py"]}
4,791
redhat-openstack/octario
refs/heads/master
/octario/lib/component.py
#!/usr/bin/env python # Copyright 2016,2019 Red Hat, Inc. # All Rights Reserved. # # 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 octario.lib import exceptions from octario.lib import logger import git import os import re try: from urlparse import urlparse except ImportError: from urllib.parse import urlparse as urlparse LOG = logger.LOG GITREVIEW_FILENAME = ".gitreview" class RepoType(object): """Enumeration for the repository type.""" GIT, NONE = range(2) class Component(object): """Representation of the component to be tested. Args: path (:obj:`str`): Path to directory where component is stored. """ def __init__(self, path): self.path = path utils = ComponentUtils(path) self.component_name = utils.get_component_name() self.rhos_release = utils.get_rhos_release() self.rhos_release_repo = utils.get_rhos_release_repo() def get_name(self): """Return name of the component. Returns: str: component name """ return self.component_name def get_rhos_release(self): """Return numeric value of rhos release of the component. Returns: str: RHOS release version """ return self.rhos_release def get_rhos_release_repo(self): """rhos-release to be enabled based on the component branch name. Returns: str: rhos-release repository name as string """ return self.rhos_release_repo class ComponentUtils(object): """Utils for the component object. Various utils needed to discover information about component. Args: path (:obj:`str`): Path to directory where component is stored. """ def __init__(self, path): self.path = path self.component_name = None self.rhos_release = None self.rhos_release_repo = None self.branch = None self.repo_type = self.__get_repo_type(self.path) def get_component_name(self): """Gets the name of the component. Returns: str: component name if exists or None if it wasn't discovered """ if self.repo_type is RepoType.GIT: if not self.component_name: repo_url, self.branch = \ self.__get_branch_url_from_git(self.path) self.component_name = \ self.__get_component_name_from_git_url(repo_url) return str(self.component_name) def get_rhos_release(self): """Gets the name of the component. Returns: str: RHOS release version or None if it wasn't discovered """ # this allows us to bypass detection algorithm which can fail in # few cases, like cherry picked changes. if 'RHOS_VERSION' in os.environ: return os.environ['RHOS_VERSION'] if self.repo_type is RepoType.GIT: if not self.branch: repo_url, self.branch = \ self.__get_branch_url_from_git(self.path) if not self.rhos_release: self.rhos_release = \ self.__get_rhos_version_from_branch(self.branch) return str(self.rhos_release) def get_rhos_release_repo(self): """Gets the rhos-release repo name Returns: str: rhos-release repository name or None if it wasn't discovered """ if self.repo_type is RepoType.GIT: if not self.branch: repo_url, self.branch = \ self.__get_branch_url_from_git(self.path) if not self.rhos_release: self.rhos_release = \ self.__get_rhos_version_from_branch(self.branch) if 'trunk' in self.branch: self.rhos_release_repo = str(self.rhos_release) + '-trunk' else: self.rhos_release_repo = str(self.rhos_release) return str(self.rhos_release_repo) def __get_repo_type(self, path): """Gets the repository type of the component. Raises: NotValidComponentPathException: If there is no valid path to the supported component type. Returns: (:obj:`RepoType`): Type of repository. """ if os.path.isdir(os.path.join(path, '.git')): LOG.debug('Found GIT repository: %s' % path) return RepoType.GIT raise exceptions.NotValidComponentPathException(path) def __get_component_name_from_git_url(self, url): """Extracts component name from the git url. Name is calculated from last part of the URL by removing .git suffix. Raises: NotValidComponentURL: If there is no valid url found. Returns: str: component name """ url_o = urlparse(url) if not url_o.scheme or not url_o.path or "/" not in url_o.path: raise exceptions.NotValidComponentURL(url) # path may start with /, so strip it r_index = url_o.path.rfind("/") component_name = url_o.path[r_index + 1:] suffix = ".git" if component_name.endswith(suffix): # Remove .git suffix component_name = component_name[:-len(suffix)] LOG.info('Component: %s' % component_name) return component_name def __get_branch_from_gitreview(self, path): """Gets branch from local .gitreview file. Args: path (:obj:`str`): Path to the git directory. Returns: str: branch name or None if branch name was not found """ branch_name = None gitreview_path = os.path.join(path, GITREVIEW_FILENAME) try: with open(gitreview_path, 'r') as f_op: for line in f_op: if 'defaultbranch=' in line: default_branch = line.split("=", 1)[1] r_index = default_branch.rfind("/") branch_name = default_branch[r_index + 1:-1] except IOError as ex: # Log error in debug mode, but do nothing about this # because this is fallback method for getting branch name LOG.debug(ex) LOG.debug('Failed to get branch from %s' % gitreview_path) return branch_name def __get_branch_url_from_git(self, path): """Gets repo_url and branch from local git directory. Raises: NotValidGitRepoException: If there is no git directory found. Args: path (:obj:`str`): Path to the git directory. Returns: touple: repo URL and branch name from local git directory """ repo_url = None branch_name = None try: g = git.Git(path) LOG.debug('Found remotes {}'.format(','.join([remote for remote in g.remote().split('\n')]))) for remote_name in ('rhos', 'patches', 'origin'): if remote_name in g.remote().split('\n'): repo_url = g.config("--get", "remote.{}.url".format(remote_name)) LOG.debug('Using Remote {}'.format(remote_name)) break if repo_url is None: raise exceptions.NotValidGitRepoException(path) repo = git.Repo(path) branch = repo.active_branch branch_name = branch.name except (git.exc.InvalidGitRepositoryError, git.exc.GitCommandNotFound, git.exc.GitCommandError) as git_ex: LOG.error(git_ex) raise exceptions.NotValidGitRepoException(path) except TypeError: # If not found directly from git, try to get the branch name # from .gitreview file which should be pointing to the proper # branch. LOG.debug('Fallback method to get branch name from .gitreview') branch_name = self.__get_branch_from_gitreview(path) if not branch_name: # Git repo is most likely in detached state # Fallback method of getting branch name, much slower LOG.debug('HEAD detached, fallback method to get branch name') head_branch = os.linesep.join( [s for s in g.log('--pretty=%d').splitlines() if s and "tag:" not in s]) r_index = head_branch.rfind("/") branch_name = head_branch[r_index + 1:-1] LOG.debug('Component repository: %s' % repo_url) LOG.debug('Component branch: %s' % branch_name) return repo_url, branch_name def __get_rhos_version_from_branch(self, branch_name): """Gets rhos release version from branch name. Raises: InvalidRhosRelease: No RHOS release found within branch name. Args: branch_name (:obj:`str`): Branch name. Returns: str: RHOS release version """ # bypass for CR branches. if 'RHOS_VERSION' in os.environ: rhos_release = os.environ['RHOS_VERSION'] else: rhos_release = re.findall(r'[0-9][0-9]?\.[0-9]', branch_name) # Unexpected parsing of branch name if len(rhos_release) != 1: raise exceptions.InvalidRhosRelease(branch_name) major_version, minor_version = rhos_release[0].split(".")[:2] if minor_version == '0': rhos_release = major_version else: rhos_release = '%s.%s' % (major_version, minor_version) LOG.info('RHOS release: %s' % rhos_release) return rhos_release
{"/octario/lib/logger.py": ["/octario/lib/exceptions.py"], "/octario/lib/exceptions.py": ["/octario/lib/tester.py"], "/ir-plugin/osp_version_name.py": ["/octario/lib/component.py"], "/octario/lib/cli.py": ["/octario/lib/component.py", "/octario/lib/tester.py"]}
4,792
redhat-openstack/octario
refs/heads/master
/setup.py
#!/usr/bin/env python # Copyright 2016 Red Hat, Inc. # All Rights Reserved. # # 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 octario.lib.release import __AUTHOR__ from octario.lib.release import __VERSION__ import pkg_resources from setuptools import find_packages from setuptools import setup import distro import os with open('requirements.txt', 'r') as fh: reqs = [str(requirement) for requirement in pkg_resources.parse_requirements(fh)] with open("LICENSE") as file: license = file.read() with open("README.md") as file: long_description = file.read() setup( name='octario', version=__VERSION__, author=__AUTHOR__, author_email='rhos-ci@redhat.com', long_description=long_description, license=license, install_requires=reqs, packages=find_packages(), include_package_data=True, entry_points={ 'console_scripts': ['octario = octario.lib.cli:main'] } ) SELINUX_DISTROS = ["fedora", "rhel", "centos"] if distro.linux_distribution(full_distribution_name=False)[0] in SELINUX_DISTROS: # For RedHat based systems, get selinux binding try: import selinux except ImportError as e: new_error = type(e)(e.message + ". check that 'libselinux-python is " "installed'") from distutils import sysconfig import shutil import sys if hasattr(sys, 'real_prefix'): # check for venv VENV_SITE = sysconfig.get_python_lib() SELINUX_PATH = os.path.join( sysconfig.get_python_lib(plat_specific=True, prefix=sys.real_prefix), "selinux") if not os.path.exists(SELINUX_PATH): raise new_error dest = os.path.join(VENV_SITE, "selinux") if os.path.exists(dest): raise new_error # filter precompiled files files = [os.path.join(SELINUX_PATH, f) for f in os.listdir(SELINUX_PATH) if not os.path.splitext(f)[1] in (".pyc", ".pyo")] # add extra file for (libselinux-python) _selinux_file = os.path.join( sysconfig.get_python_lib(plat_specific=True, prefix=sys.real_prefix), "_selinux.so") if os.path.exists(_selinux_file): shutil.copy(_selinux_file, os.path.dirname(dest)) files.append(_selinux_file) os.makedirs(dest) for f in files: shutil.copy(f, dest) else: raise new_error import selinux # noqa
{"/octario/lib/logger.py": ["/octario/lib/exceptions.py"], "/octario/lib/exceptions.py": ["/octario/lib/tester.py"], "/ir-plugin/osp_version_name.py": ["/octario/lib/component.py"], "/octario/lib/cli.py": ["/octario/lib/component.py", "/octario/lib/tester.py"]}
4,793
redhat-openstack/octario
refs/heads/master
/octario/lib/tester.py
#!/usr/bin/env python # Copyright 2016 Red Hat, Inc. # All Rights Reserved. # # 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 octario.lib import exceptions from octario.lib import logger from os.path import basename import glob import os LOG = logger.LOG DEFAULT_TESTERS_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'ansible', 'playbooks') class TesterType(object): """Tester types supported by octario CLI. """ @classmethod def get_supported_testers(cls): """Get list of supported testers as strings. Args: cls (:obj:`TesterType`): Class itself Returns: list: List of supported testers """ supported_testers = [] for playbook in glob.glob(os.path.join(DEFAULT_TESTERS_DIR, "*.yml")): tester = basename(playbook.split(".yml")[0]) supported_testers.append(str(tester)) return sorted(supported_testers) class Tester(object): """Representation of the tester. Object holds information about tester type and relevant attributes required to run tester such as playbook for that tester. Args: tester (:obj:`str`): string value of the tester e.g. 'pep8' """ def __init__(self, tester): self.type = self.__get_tester_type(tester) self.playbook_path = self.__get_playbook_path() def get_type(self): """Gets type of the tester. Returns: (:obj:TesterType): tester type """ return self.type def get_playbook_path(self): """Get path to the playbook for the tester. Returns: str: tester playbook path """ return self.playbook_path def __get_playbook_path(self): """Calculates the playbook path based on the octario module path. Raises: AnsiblePlaybookNotFound: If there is no playbook associated with the tester. Playbook filename must match tester name. Returns: str: tester playbook path """ playbook_path = os.path.join(DEFAULT_TESTERS_DIR, str(self.type) + ".yml") if not os.path.isfile(playbook_path): raise exceptions.AnsiblePlaybookNotFound(playbook_path) LOG.debug("Tester playbook: %s" % playbook_path) return playbook_path def __get_tester_type(self, tester): """Returns tester type based on the passed tester type string. Raises: UnsupportedTester: If the tester is not in the supported testers enumeration. Args: tester (:obj:`str`): string value of the tester e.g. 'pep8' Returns: (:obj:TesterType): tester type """ if not tester: raise exceptions.UnsupportedTester('Unknown') for tester_type in TesterType.get_supported_testers(): if tester.lower() == tester_type.lower(): return tester_type raise exceptions.UnsupportedTester(tester)
{"/octario/lib/logger.py": ["/octario/lib/exceptions.py"], "/octario/lib/exceptions.py": ["/octario/lib/tester.py"], "/ir-plugin/osp_version_name.py": ["/octario/lib/component.py"], "/octario/lib/cli.py": ["/octario/lib/component.py", "/octario/lib/tester.py"]}
4,794
redhat-openstack/octario
refs/heads/master
/components_config/16.2/openstack-tempest/scripts/comment_deps.py
# Copyright 2018 Red Hat, Inc. # All Rights Reserved. # # 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. # This script comments all deps and install_command lines in a tox.ini file # given by argument, f.e.: # $ ./comment_deps.py ./tox.ini from shutil import copyfile import sys if sys.version_info.major == 3: import configparser as configparser else: import ConfigParser as configparser if __name__ == '__main__': copyfile(sys.argv[1], sys.argv[1] + '.orig') cp = configparser.ConfigParser() cp.read(sys.argv[1] + '.orig') for sec in cp.sections(): for opt in cp.options(sec): if opt == 'deps' or opt == 'install_command': value = cp.get(sec, opt) # if the string is multiline, make it singleline value = value.replace('\n', ' ') # remove the uncommented option # and set it back as commented one cp.remove_option(sec, opt) cp.set(sec, "# " + opt, value) with open(sys.argv[1], 'w') as configfile: cp.write(configfile)
{"/octario/lib/logger.py": ["/octario/lib/exceptions.py"], "/octario/lib/exceptions.py": ["/octario/lib/tester.py"], "/ir-plugin/osp_version_name.py": ["/octario/lib/component.py"], "/octario/lib/cli.py": ["/octario/lib/component.py", "/octario/lib/tester.py"]}
4,795
redhat-openstack/octario
refs/heads/master
/octario/lib/logger.py
#!/usr/bin/env python # Borrowed from InfraRed project # Copyright 2016 Red Hat, Inc. # All Rights Reserved. # # 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 logging import sys import traceback import colorlog logger_formatter = colorlog.ColoredFormatter( "%(log_color)s%(levelname)-8s%(message)s", log_colors=dict( DEBUG='blue', INFO='green', WARNING='yellow', ERROR='red', CRITICAL='bold_red,bg_white', ) ) LOGGER_NAME = "OctarioLogger" DEFAULT_LOG_LEVEL = logging.INFO LOG = logging.getLogger(LOGGER_NAME) LOG.setLevel(DEFAULT_LOG_LEVEL) # Create stream handler with debug level sh = logging.StreamHandler() sh.setLevel(logging.DEBUG) # Add the logger_formatter to sh sh.setFormatter(logger_formatter) # Create logger and add handler to it LOG.addHandler(sh) def octario_excepthook(exc_type, exc_value, exc_traceback): """exception hook that sends OctarioException to log and other exceptions to stderr (default excepthook) """ from octario.lib.exceptions import OctarioException # sends full exception with trace to log if not isinstance(exc_value, OctarioException): return sys.__excepthook__(exc_type, exc_value, exc_traceback) if LOG.getEffectiveLevel() <= logging.DEBUG: formated_exception = "".join( traceback.format_exception(exc_type, exc_value, exc_traceback)) LOG.error(formated_exception + exc_value.message) else: LOG.error(exc_value.message) sys.excepthook = octario_excepthook
{"/octario/lib/logger.py": ["/octario/lib/exceptions.py"], "/octario/lib/exceptions.py": ["/octario/lib/tester.py"], "/ir-plugin/osp_version_name.py": ["/octario/lib/component.py"], "/octario/lib/cli.py": ["/octario/lib/component.py", "/octario/lib/tester.py"]}
4,796
redhat-openstack/octario
refs/heads/master
/octario/lib/execute.py
#!/usr/bin/env python # Copyright 2016 Red Hat, Inc. # All Rights Reserved. # # 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 octario.lib import exceptions from octario.lib import logger import logging import os LOG = logger.LOG class AnsibleExecutor(object): """Executor for the ansible playbooks Used to run ansible CLI with the parameters needed for testing component by specified tester. Args: tester (:obj:`Tester`): Supported by octario CLI tester component (:obj:`Component`): Tested component inventory_file (:obj:`str`): Path to inventory file, defaults to 'local_hosts' if file not found. """ def __init__(self, tester, component, inventory_file, path): self.tester = tester self.component = component self.path = os.path.abspath(path) inventory_file_path = self.__get_inventory_file(inventory_file) self.cli_args = self.__get_ansible_playbook_args(inventory_file_path) def run(self): """Runs ansible CLI. Runs ansible CLI using PlaybookCLI and command line arguments stored in the self.cli_args list. Raises: CommandError: If there was error while running the command. Returns: int or list: return from the ansible PlaybookExecutor run() """ # Set the ansible.cfg that will be used by octario octario_ansible_config = self._get_ansible_config_file() if octario_ansible_config: os.environ['ANSIBLE_CONFIG'] = octario_ansible_config # Import must happen after setting ANSIBLE_CONFIG, otherwise # environment variable will not be used. from ansible.cli.playbook import PlaybookCLI ansible_cli = PlaybookCLI(self.cli_args) ansible_cli.parse() results = ansible_cli.run() if results: raise exceptions.CommandError("Failed to run tester: %s" % self.tester.get_playbook_path()) return results def _get_ansible_config_file(self): """Return path to the ansible config file Overrides default ansible config file from: lib/ansible/constants.py:load_config_file() Function returns None if either environment variable ANSIBLE_CONFIG exists or current working dir contains ansible.cfg file. This allows to fallback to default ansible method of gathering ansible.cfg file, while third option to use ansible.cfg from Octario installation path is used if no specific ansible.cfg was provided. Returns: str or None: path to the ansible.cfg cnfiguration file or None if the file was provided via ANSIBLE_CONFIG or it exists in the current working dir. """ ansible_config_env = os.getenv("ANSIBLE_CONFIG", None) if ansible_config_env is not None: ansible_config_env = os.path.expanduser(ansible_config_env) if os.path.isdir(ansible_config_env): ansible_config_env += "/ansible.cfg" # Configuration file was found in the ANSIBLE_CONFIG env # Return None to fallback to standard ansible method if ansible_config_env and os.path.isfile(ansible_config_env): LOG.info('Using ansible config from ANSIBLE_CONFIG env: {}'.format( ansible_config_env)) return None try: ansible_config_env = os.getcwd() + "/ansible.cfg" # Configuration file was found in the current working dir if ansible_config_env and os.path.isfile(ansible_config_env): LOG.info('Using ansible config from current dir: {}'.format( ansible_config_env)) return None except OSError: pass ansible_config_env = os.path.dirname(os.path.abspath(__file__)) ansible_config_env = os.path.join(ansible_config_env, "../ansible/") LOG.debug('Using ansible config from default location: {}'.format( ansible_config_env)) return ansible_config_env def __get_inventory_file(self, inventory_file): """Return path to the inventory file Returns passed inventory file path or the default fallback if the inventory file is not available. Args: inventory_file (:obj:`str`): Path to inventory file, defaults to 'local_hosts' if file not found. Returns: str: path to the inventory file that will be used """ if not os.path.isfile(inventory_file): LOG.warning("Inventory file does not exists: %s" % inventory_file) script_path = os.path.dirname(os.path.abspath(__file__)) inventory_fallback = os.path.join(script_path, "../ansible/", "local_hosts") LOG.warning("Falling back to inventory: %s" % inventory_fallback) return inventory_fallback return inventory_file def __get_ansible_playbook_args(self, inventory_file): """Composes list of all arguments that will be used for running play. Function that gets all arguments that will be passed to the ansible-play CLI. The arguments are based on the tester and component objects and their variables taken from the public functions. To be consistent with the octario run ansible verbosity level is calculated from octario logger level. Args: inventory_file (:obj:`str`): Path to inventory file. Returns: list: arguments for the ansible CLI """ verbose_level = "-vvv" if LOG.getEffectiveLevel() >= logging.INFO: verbose_level = "-v" extra_vars = { 'component': { 'name': self.component.get_name(), 'version': self.component.get_rhos_release(), }, 'test': { 'dir': self.path } } cli_args = ['execute', self.tester.get_playbook_path(), verbose_level, '--inventory', inventory_file, '--extra-vars', extra_vars] LOG.debug('Ansible CLI args: {}'.format(cli_args[1:])) return cli_args
{"/octario/lib/logger.py": ["/octario/lib/exceptions.py"], "/octario/lib/exceptions.py": ["/octario/lib/tester.py"], "/ir-plugin/osp_version_name.py": ["/octario/lib/component.py"], "/octario/lib/cli.py": ["/octario/lib/component.py", "/octario/lib/tester.py"]}
4,797
redhat-openstack/octario
refs/heads/master
/octario/lib/exceptions.py
#!/usr/bin/env python # Copyright 2016 Red Hat, Inc. # All Rights Reserved. # # 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 octario.lib import logger LOG = logger.LOG class OctarioException(Exception): """Base Octario Exception To use this class, inherit from it and define a a 'msg_fmt' property. That msg_fmt will get printf'd with the keyword arguments provided to the constructor. """ msg_fmt = "An unknown exception occurred." def __init__(self, message=None, **kwargs): self.kwargs = kwargs self.message = message if not self.message: try: self.message = self.msg_fmt % kwargs except Exception: # arguments in kwargs doesn't match variables in msg_fmt import six for name, value in six.iteritems(kwargs): LOG.error("%s: %s" % (name, value)) self.message = self.msg_fmt class NotValidGitRepoException(OctarioException): def __init__(self, repo_path): msg = \ "Git Repository not found under: '{}'".format( repo_path) super(self.__class__, self).__init__(msg) class NotValidComponentPathException(OctarioException): def __init__(self, component_path): msg = \ "Component repository not found under: '{}'".format( component_path) super(self.__class__, self).__init__(msg) class NotValidComponentURL(OctarioException): def __init__(self, component_url): msg = \ "Invalid Component URL: '{}'".format( component_url) super(self.__class__, self).__init__(msg) class InvalidRhosRelease(OctarioException): def __init__(self, branch_name): msg = \ "Can't get RHOS version from branch: '{}'".format( branch_name) super(self.__class__, self).__init__(msg) class UnsupportedTester(OctarioException): def __init__(self, tester_type): from octario.lib.tester import TesterType msg = \ "Tester '{}' is not supported by Octario CLI.".format( tester_type) LOG.info("Supported testers: {}".format( TesterType.get_supported_testers())) super(self.__class__, self).__init__(msg) class AnsiblePlaybookNotFound(OctarioException): def __init__(self, playbook_path): msg = \ "Tester playbook not found: '{}'".format( playbook_path) super(self.__class__, self).__init__(msg) class CommandError(OctarioException): def __init__(self, msg): super(self.__class__, self).__init__(msg)
{"/octario/lib/logger.py": ["/octario/lib/exceptions.py"], "/octario/lib/exceptions.py": ["/octario/lib/tester.py"], "/ir-plugin/osp_version_name.py": ["/octario/lib/component.py"], "/octario/lib/cli.py": ["/octario/lib/component.py", "/octario/lib/tester.py"]}
4,798
redhat-openstack/octario
refs/heads/master
/ir-plugin/osp_version_name.py
#!/usr/bin/env python # Copyright 2017 Red Hat, Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import json import logging import os import sys def find_path(direntry): for root, dirs, files in os.walk(os.path.expanduser('~')): files = [f for f in files if not f[0] == '.'] dirs[:] = [d for d in dirs if not d[0] == '.'] for name in dirs: if name == direntry: return(os.path.abspath(os.path.join(root, name))) sys.path.append(find_path('octario')) from octario.lib.component import Component # noqa LOG = logging.getLogger("OctarioLogger") LOG.setLevel(logging.ERROR) def main(component_path): cmpnt = Component(component_path) release = cmpnt.get_rhos_release() repo = cmpnt.get_rhos_release_repo() name = cmpnt.get_name() if release is not None and name is not None: json_out = { 'plugin': 'iroctario', 'name': name, 'version': release, 'repo': repo, } print(json.dumps(json_out)) if __name__ == "__main__": """Helper script used by InfraRed-Octario plugin to discover component name and OSP release number. """ if len(sys.argv) != 2: LOG.error("Improper number of arguments, passed %d instead of 1" % int(len(sys.argv) - 1)) sys.exit(1) main(sys.argv[1])
{"/octario/lib/logger.py": ["/octario/lib/exceptions.py"], "/octario/lib/exceptions.py": ["/octario/lib/tester.py"], "/ir-plugin/osp_version_name.py": ["/octario/lib/component.py"], "/octario/lib/cli.py": ["/octario/lib/component.py", "/octario/lib/tester.py"]}
4,799
redhat-openstack/octario
refs/heads/master
/octario/lib/cli.py
#!/usr/bin/env python # Copyright 2016 Red Hat, Inc. # All Rights Reserved. # # 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 octario.lib import exceptions from octario.lib import execute from octario.lib import logger from octario.lib.component import Component from octario.lib.tester import Tester from octario.lib.tester import TesterType import argparse import datetime import logging import os import sys LOG = logger.LOG class OctarioShell(object): def get_base_parser(self): parser = argparse.ArgumentParser(prog='octario', description='OpenStack Component ' 'Testing Ansible Roles.', add_help=False) parser.add_argument('-?', '-h', '--help', action='help', help='show this help message and exit') parser.add_argument('-v', '--verbose', action='store_true', help='increase output verbosity') if 'ANSIBLE_INVENTORY' in os.environ: default_inventory = os.environ['ANSIBLE_INVENTORY'] else: default_inventory = os.path.join(os.getcwd(), 'hosts') parser.add_argument('-i', '--inventory-file', default=default_inventory, help='specify inventory host path' ' (default=./hosts or ANSIBLE_INVENTORY when' ' defined)') parser.add_argument('-t', '--tester', help='Tester to be ran. Supported testers: ' '{}'.format(TesterType.get_supported_testers())) parser.add_argument('dir', nargs='?', default=os.getcwd(), help='path to component directory') return parser def parse_args(self, argv): parser = self.get_base_parser() args = parser.parse_args(argv) if args.verbose: LOG.setLevel(level=logging.DEBUG) LOG.debug('Octario running in debug mode') if not args.tester: raise exceptions.CommandError("You must provide tester" " via --tester option") LOG.debug('Chosen component directory: %s' % args.dir) LOG.debug('Chosen tester: %s' % args.tester) LOG.debug('Chosen inventory: %s' % args.inventory_file) return args def main(self, argv): parser_args = self.parse_args(argv) tester = Tester(parser_args.tester) component = Component(parser_args.dir) ansible_playbook = execute.AnsibleExecutor(tester, component, parser_args.inventory_file, path=parser_args.dir) ansible_playbook.run() def main(args=None): start_time = datetime.datetime.now() LOG.debug('Started octario: %s' % start_time.strftime('%Y-%m-%d %H:%M:%S')) try: if args is None: args = sys.argv[1:] OctarioShell().main(args) except exceptions.OctarioException as ex: LOG.error(ex.message) sys.exit(1) except Exception: raise sys.exit(1) except KeyboardInterrupt: sys.exit(130) finally: finish_time = datetime.datetime.now() LOG.debug('Finished octario: %s' % finish_time.strftime('%Y-%m-%d %H:%M:%S')) LOG.debug('Run time: %s [H]:[M]:[S].[ms]' % str(finish_time - start_time)) if __name__ == "__main__": main()
{"/octario/lib/logger.py": ["/octario/lib/exceptions.py"], "/octario/lib/exceptions.py": ["/octario/lib/tester.py"], "/ir-plugin/osp_version_name.py": ["/octario/lib/component.py"], "/octario/lib/cli.py": ["/octario/lib/component.py", "/octario/lib/tester.py"]}
4,800
stefan-cross/choraoke
refs/heads/main
/backend/ultimate-api/server/views.py
from server import app from flask import request, jsonify from urllib.parse import urlparse from .tab_parser import dict_from_ultimate_tab SUPPORTED_UG_URI = 'tabs.ultimate-guitar.com' @app.route('/') def index(): return 'hi' @app.route('/tab') def tab(): try: ultimate_url = request.args.get('url') # Ensure sanitized url parsed_url = urlparse(ultimate_url) location = parsed_url.netloc if location != SUPPORTED_UG_URI: raise Exception('unsupported url scheme') except Exception as e: return jsonify({'error': str(e)}), 500 tab_dict = dict_from_ultimate_tab(ultimate_url) return jsonify(tab_dict)
{"/backend/ultimate-api/server/views.py": ["/backend/ultimate-api/server/tab_parser.py"], "/backend/ultimate-api/server/tab_parser.py": ["/backend/ultimate-api/server/parser.py"], "/backend/ultimate-api/server/parser.py": ["/backend/ultimate-api/server/tab.py"]}
4,801
stefan-cross/choraoke
refs/heads/main
/backend/ultimate-api/test.py
## ToDo: - [ ] Add Unit Tests - Test for Ed Sheeran - Perfect - Test for Jason Mraz - I'm Yours (because of the title parsing) - Test for Passenger - Let Her Go
{"/backend/ultimate-api/server/views.py": ["/backend/ultimate-api/server/tab_parser.py"], "/backend/ultimate-api/server/tab_parser.py": ["/backend/ultimate-api/server/parser.py"], "/backend/ultimate-api/server/parser.py": ["/backend/ultimate-api/server/tab.py"]}
4,802
stefan-cross/choraoke
refs/heads/main
/backend/ultimate-api/server/tab_parser.py
import sys import json import requests from .parser import html_tab_to_json_dict def dict_from_ultimate_tab(url: str) -> json: ''' Given a Ultimate Guitar tab url, will return a dictionary representing the song along with the song info ''' html = requests.get(url).content ug_tags = ['js-tab-content', 'js-copy-content'] # tags the tabs are contained in tab_dict = html_tab_to_json_dict(html, ug_tags) return tab_dict def json_from_ultimate_tab(url: str) -> json: ''' Given a Ultimate Guitar tab url, will return a json object representing the song along with the song info ''' tab_dict = dict_from_ultimate_tab(url) data = json.dumps(tab_dict, ensure_ascii=False) return data if __name__ == '__main__': try: url = sys.argv[1] except: print('INCORRECT USAGE\n') print(' Usage:') print(' python %s {url}' % sys.argv[0]) sys.exit() json_data = json_from_ultimate_tab(url) pretty_format_json = json.dumps(json.loads(json_data), indent=4, sort_keys=True) print(pretty_format_json)
{"/backend/ultimate-api/server/views.py": ["/backend/ultimate-api/server/tab_parser.py"], "/backend/ultimate-api/server/tab_parser.py": ["/backend/ultimate-api/server/parser.py"], "/backend/ultimate-api/server/parser.py": ["/backend/ultimate-api/server/tab.py"]}
4,803
stefan-cross/choraoke
refs/heads/main
/backend/ultimate-api/server/tab.py
from typing import Any # tab { # title: "tab name", # artist_name: "", # author: "", # capo: "" (can be null), # Tuning: "" (can be null), # # lines: [ # { # type: "chord" (OR "lyrics", "blank"), # chords: [ # { # note: "G", # pre_spaces: 10 # }, # { # note: "Em", # pre_spaces: 8 # } # ] # }, # { # type: "lyrics", # lyrics: "I found a love for me" # }, # { # type: "blank" # } # ] # } class UltimateTabInfo(object): ''' Represents the info of an ultimate guitar tab. Does not contain any lyrics or chords ''' def __init__(self, title: str, artist: str, author: str, difficulty: str = None, key: str = None, capo: str = None, tuning: str = None): self.title = title self.artist = artist self.author = author # Optionals: self.difficulty = difficulty self.key = key self.capo = capo self.tuning = tuning class UltimateTab(object): ''' Represents an ultimate guitar tab containing Lyrics and Chords A `queue-like` object which will append lines to object and can be parsed to formatted json. ''' JSON_CONTAINER_NAME = 'lines' JSON_KEY_CHORD_ARRAY = 'chords' JSON_KEY_NOTE = 'note' JSON_KEY_LYRIC = 'lyric' JSON_KEY_BLANK = 'blank' JSON_KEY_TYPE = 'type' JOSN_KEY_LEAD_SPACES = 'pre_spaces' def __init__(self): self.lines = [] def _append_new_line(self, type: str, content_tag: str, content: Any) -> None: line = {'type': type} if content_tag is not None: line[content_tag] = content self.lines.append(line) def append_chord_line(self, chords_line: str) -> None: ''' Appends a chord line to the tab. Parameters: - chords_line: A single-line string containing leading spaces and guitar chords (i.e. G, Em, etc.) ''' chords = [] # Array of dictionary of chords leading_spaces = 0 for c in chords_line.split(' '): if not c: # A space character recognized leading_spaces += 1 else: chord = { self.JSON_KEY_NOTE: c, self.JOSN_KEY_LEAD_SPACES: leading_spaces } chords.append(chord) leading_spaces = 1 # reset for next chord to read in - resets to 1 to compensate for `split` self._append_new_line(self.JSON_KEY_CHORD_ARRAY, self.JSON_KEY_CHORD_ARRAY, chords) def append_lyric_line(self, lyric_line: str) -> None: ''' Appends a lyric line to the tab. Parameters: - lyric_line: A single-line string containing lyrics (and any leading spaces needed) ''' self._append_new_line(self.JSON_KEY_LYRIC, self.JSON_KEY_LYRIC, lyric_line) def append_blank_line(self) -> None: ''' Appends a blank line to the tab. ''' self._append_new_line(self.JSON_KEY_BLANK, None, None) def as_json_dictionary(self) -> dict: ''' Returns a dictionary representation of the tab object. Properly formatted for use as a json object. ''' return {self.JSON_CONTAINER_NAME: self.lines}
{"/backend/ultimate-api/server/views.py": ["/backend/ultimate-api/server/tab_parser.py"], "/backend/ultimate-api/server/tab_parser.py": ["/backend/ultimate-api/server/parser.py"], "/backend/ultimate-api/server/parser.py": ["/backend/ultimate-api/server/tab.py"]}
4,804
stefan-cross/choraoke
refs/heads/main
/backend/ultimate-api/server/parser.py
import json from bs4 import BeautifulSoup from .tab import UltimateTab, UltimateTabInfo import re def _tab_info_from_soup(soup: BeautifulSoup) -> UltimateTabInfo: ''' Returns a populated UltimateTabInfo object based on the provided soup. Parses based on UG site construction as of 9/3/17. Parameters: - soup: A BeautifulSoup for a Ultimate Guitar tab's html (or html body) ''' # Get song title and artist try: song_title = soup.find(attrs={'itemprop': 'name'}).text song_title = re.compile(re.escape('chords'), re.IGNORECASE).sub(r'', song_title).strip() # Remove the word 'chords' except: song_title = "UNKNOWN" try: artist_name = soup.find(attrs={'class': 't_autor'}).text.replace('\n', '') artist_name = re.compile(re.escape('by'), re.IGNORECASE).sub(r'', artist_name).strip()# Remove the word 'by' except: artist_name = "UNKNOWN" # Get info - author, capo, tuning, etc. author = "UNKNOWN" difficulty = None key = None capo = None tuning = None try: info_header_text = soup.find(attrs={'class': 't_dt'}).text.replace('\n', '') info_headers = [x.lower() for x in info_header_text.split(' ') if x] # Split string and make lowercase info_header_values = soup.findAll(attrs={'class': 't_dtde'}) for index, header in enumerate(info_headers): try: if header == 'author': author = info_header_values[index].a.text elif header == 'difficulty': difficulty = info_header_values[index].text.strip() elif header == 'key': key = info_header_values[index].text.strip() elif header == 'capo': capo = info_header_values[index].text.strip() elif header == 'tuning': tuning = info_header_values[index].text.strip() except: continue except: pass tab_info = UltimateTabInfo(song_title, artist_name, author, difficulty, key, capo, tuning) return tab_info def html_tab_to_json_dict(html_body: str, pre_class_tags: [str]) -> json: ''' Returns a json form of a 'pre' tag in an untimate guitar html tabs body. Parameters: - html_body: The full html body of an ultimate guitar tab site - pre_class_tags: An array of strings for the class names of a 'pre' tag where the chords are located to parse ''' soup = BeautifulSoup(html_body, "html.parser") # Get UltimateTabInfo object from soup html for artist, title, etc. tab_info = _tab_info_from_soup(soup) # Get tab's content from html (lyrics + chords) tabs_html_content = soup.find('pre', attrs={'class': pre_class_tags}) # Strip `pre` tag and convert to string to parse formatted_tab_string = ''.join(map(str, tabs_html_content.contents)) # Parse each line of the string into json tab = UltimateTab() for tab_line in formatted_tab_string.split('\n'): re_span_tag = re.compile(r'<span[^>]*>|<\/span[^>]*>') if not tab_line: # Line is blank tab.append_blank_line() elif re_span_tag.search(tab_line): # Line contains chords sanitized_tab_line = re_span_tag.sub(r' ', tab_line) tab.append_chord_line(sanitized_tab_line) else: # Line contains lyrics/string #tab_line = tab_line.encode('ascii', 'replace') # Encode as ascii tab.append_lyric_line(tab_line) # Construct full json object json = { 'title': tab_info.title, 'artist_name': tab_info.artist, 'author': tab_info.author } # add tab info if it exists if tab_info.difficulty is not None: json['difficulty'] = tab_info.difficulty if tab_info.key is not None: json['key'] = tab_info.key if tab_info.capo is not None: json['capo'] = tab_info.capo if tab_info.tuning is not None: json['tuning'] = tab_info.tuning json['lines'] = tab.as_json_dictionary()['lines'] # Return constructed json under a single tag return {'tab': json}
{"/backend/ultimate-api/server/views.py": ["/backend/ultimate-api/server/tab_parser.py"], "/backend/ultimate-api/server/tab_parser.py": ["/backend/ultimate-api/server/parser.py"], "/backend/ultimate-api/server/parser.py": ["/backend/ultimate-api/server/tab.py"]}
4,807
ij-knct/.Research
refs/heads/master
/recipict.py
import os import re import json import requests from ibm_watson import VisualRecognitionV3 from ibm_cloud_sdk_core.authenticators import IAMAuthenticator from box import Box from googletrans import Translator import imagePreprocessing class recipicture(): def __init__(self, file_name, threshold): self.authenticator = IAMAuthenticator('ylE7ZMEpzSAAjVlnpUZP1hgyVizaR_XFgxUgcTslGasm') self.visual_recognition = VisualRecognitionV3( version='2018-03-19', authenticator=self.authenticator ) self.visual_recognition.set_service_url( 'https://api.us-south.visual-recognition.watson.cloud.ibm.com' ) print('\nInitializing variable and constant.\n') self.pict_path = file_name self.json_path = os.path.splitext(self.pict_path)[0]+'.json' self.recipe_path = os.path.splitext(self.pict_path)[0]+'_recipe.json' self.images_file = None self.classes = None self.json_file = None self.json_data = None self.boxed_json = None self.sorted_json = None self.j = None self.threshold = threshold self.jp_list = [] self.recipe = None self.name_list = [] self.url = "https://katsuo.herokuapp.com/api?item=" def classing_image(self): if os.path.exists(self.json_path): print("File already exists.") print("Reusing json file.\n") else: with open(self.pict_path, 'rb') as self.images_file: self.classes = self.visual_recognition.classify( images_file=self.images_file, classifier_ids=["food"]).get_result() with open(self.json_path, 'w') as self.json_file: json.dump(self.classes, self.json_file, indent=2) def en2ja(self, phrase): tr = Translator(service_urls=['translate.googleapis.com']) while True: try: text = tr.translate(phrase, dest="ja").text return text except Exception: tr = Translator(service_urls=['translate.googleapis.com']) def filter_score(self): with open(self.json_path, 'r') as self.json_data: self.boxed_json = Box(json.load(self.json_data)) self.sorted_json = sorted(self.boxed_json.images[0].classifiers[0]. classes, key=lambda x: x['score'], reverse=True) for j in self.sorted_json: if j.score >= self.threshold: self.jp_list.append(self.en2ja(j.__getattr__('class'))) i = 0 for l in self.jp_list: l = re.sub('料理', '', l) print('IndexNum {}:{}'.format(i, l)) self.jp_list[i] = l i += 1 def get_recipe_list(self, item): ''' item *String object* ''' if item: url = 'https://katsuo.herokuapp.com/api?item='+item get_url_info = requests.get(url) # print(get_url_info) # print(get_url_info.headers['Content-Type']) jsonData = get_url_info.text.replace('\\u3000', ' ') self.j = json.loads(jsonData.replace('\"', '"')) # print(self.j[0]) # show candidate r_i1 = r'"recipe": "[^"]+"' try: for r_list in self.j: r1 = re.search(r_i1, r_list) s = r1.group() self.name_list.append(s) i = 0 e = self.j[0] print('\nPrinting candidate below.\n') for l in self.name_list: print('IndexNum {}: {}'.format(i, l.replace('"recipe": ', ''))) i += 1 except (AttributeError, IndexError): print('Not matching.') print('Bad word to search.\n') print('Please input manually.\n') print('Sorry for the inconvenience.') exit() if not item: print('Item is empty.') print('No inputs.') def get_ingredients_list(self, index): r_str = r'(?<="ingredients": \[)(.*)' i_str = r'(.*)(?=\])' s_str = r'FoodGroup: [0-9]+, FoodNumber: [a-zA-Z0-9]+, RefNum: [0-9]+, ' moji = self.j[index] mo1 = re.search(r_str, moji) mo2 = re.search(i_str, mo1.group()) self.recipe = re.sub('"', '', mo2.group()) self.recipe = self.recipe.replace('}, {', '\n\n') self.recipe = self.recipe.replace('{', '') self.recipe = self.recipe.replace('}', '') self.recipe = re.sub(s_str, '', self.recipe) print() print(self.recipe) if __name__ == "__main__": directory = r'C:/Users/jinto/Documents/.Research/data' name = '/tomato.jpg' thsh = 0.5 print('THRESHOLD IS {}'.format(thsh)) man = int(input('AUTO DETECT = 0\nUSE MANUALLY = 1\n')) # initialize if not man: cropped = imagePreprocessing.imagePreprocessing(directory+name) food = recipicture(cropped, threshold=thsh) if man: food = recipicture(directory+name, threshold=thsh) # detecting mode # auto mode if not man: print('****************************') print('RUNNING AS AUTO DETECT MODE.') print('****************************\n') # class image and make json file food.classing_image() food.filter_score() # select ingredients index_pict = int(input('\nSelect which is shown in picture.\n')) food.get_recipe_list(food.jp_list[index_pict]) # select recipe index_recipe = int(input('\nSelect which you wanna make.\n')) food.get_ingredients_list(index_recipe) # manual mode if man: print('***********************') print('RUNNING AS MANUAL MODE.') print('***********************\n') # input ingredients from keyboard index_man = input('\nWrite ingredients what you have in Japanese.\n') print('\n') food.get_recipe_list(index_man) # select recipe index_r = int(input('\nSelect which you wanna make.\n')) print('\n') food.get_ingredients_list(index_r)
{"/recipict.py": ["/imagePreprocessing.py"]}
4,808
ij-knct/.Research
refs/heads/master
/imagePreprocessing.py
import os import subprocess import numpy as np import cv2 def imagePreprocessing(fn): filename = fn # get file name without file type filenotype = os.path.splitext(filename)[0] img = cv2.imread(filename) # launch a window to select region to grabcut cv2.namedWindow("Image", 2) # resize it to fit on screen cv2.resizeWindow("Image", 500, 500) r = cv2.selectROI("Image", img, False, False) mask = np.zeros(img.shape[:2], np.uint8) bgdModel = np.zeros((1, 65), np.float64) fgdModel = np.zeros((1, 65), np.float64) rect = r cv2.grabCut(img, mask, rect, bgdModel, fgdModel, 3, cv2.GC_INIT_WITH_RECT) mask2 = np.where((mask == 2)|(mask == 0), 0, 1).astype('uint8') img = img*mask2[:, :, np.newaxis] outputfile = str(filenotype)+'_cropped'+'.png' cv2.imwrite(outputfile, img) cv2.imwrite('grabcut-mask.jpg', mask2) # generate mask from grabcut output cmd = ['C:/Program Files/ImageMagick-7.0.10-Q16/mogrify', '-fuzz', '2%', '-fill', 'white', '-opaque', '#060606', 'grabcut-mask.jpg'] subprocess.call(cmd, shell=True) # apply mask using imagemagick cmd = ['C:/Program Files/ImageMagick-7.0.10-Q16/convert', outputfile, 'grabcut-mask.jpg', '-alpha', 'off', '-compose', 'CopyOpacity', '-composite', '-trim', outputfile] subprocess.call(cmd, shell=True) # cleanup cmd = ['del', 'grabcut-mask.jpg'] subprocess.call(cmd, shell=True) return outputfile
{"/recipict.py": ["/imagePreprocessing.py"]}
4,809
ij-knct/.Research
refs/heads/master
/tempCodeRunnerFile.py
# def get_ingredients_list(self, index): # r_str = r'(?<="ingredients": \[)(.*)' # i_str = r'(.*)(?=\])' # for moji in self.j: # mo1 = re.search(r_str, moji) # mo2 = re.search(i_str, mo1.group()) # s = re.sub('"', '', mo2.group()) #
{"/recipict.py": ["/imagePreprocessing.py"]}
4,843
fipanther/christoffel
refs/heads/master
/christoffel.py
from __future__ import division, print_function import sympy import numpy import scipy class christoffel2: def __init__(self, metric): # takes a Sympy matrix and makes the metric g_{ab} self.metric = metric self.metric_dim = numpy.shape(self.metric) # raise an exception if the metric dimensions are not equal if not self.metric_dim[0]==self.metric_dim[1]: raise ValueError('Metric dimensions must be equal') # takes the metric and calculates the inverse metric g^{ab} self.metric_inverse = self.metric.inv() def calculate(self, symbol_list, idx1, idx2, idx3): # calculate one Christoffel symbol only - \Gamma^{idx1}_{idx2 idx3} self.symbol_list = symbol_list self.idx1 = idx1 self.idx2 = idx2 self.idx3 = idx3 self.i_idx1 = self.symbol_list.index(idx1) self.i_idx2 = self.symbol_list.index(idx2) self.i_idx3 = self.symbol_list.index(idx3) out = 0 # now calculate the desired christoffel symbol for i in range(0, len(self.symbol_list)): out = out + (0.5*(self.metric_inverse[i, self.i_idx1]*(sympy.diff(self.metric[i, self.i_idx2], self.idx3)+sympy.diff(self.metric[i, self.i_idx3], self.idx2)-sympy.diff(self.metric[self.i_idx2, self.i_idx3], self.symbol_list[i])))) return out
{"/christoffeltest.py": ["/christoffel.py"]}
4,844
fipanther/christoffel
refs/heads/master
/christoffeltest.py
from __future__ import division, print_function from christoffel import christoffel2 import sympy from sympy.matrices import Matrix import numpy import scipy r, t = sympy.symbols('r t') metric = Matrix([[1,0],[0,r**2]]) a = christoffel2(metric) christoffel_trt = a.calculate((r, t), t, r, t) christoffel_ttr = a.calculate((r,t), t,t,r) christoffel_trr = a.calculate((r,t), t,r,r) print(christoffel_trt, christoffel_ttr, christoffel_trr)
{"/christoffeltest.py": ["/christoffel.py"]}
4,875
johnatasr/CoolPark
refs/heads/master
/automobilies/tests/tests_models.py
from automobilies.models import Automobilie from django.test import TestCase class AutomobilieModelTest(TestCase): """ Tests of Automobilie in parking.models.py """ def setUp(self): Automobilie.objects.create( plate="ABC-1234", ) def test_create_auto(self): Automobilie.objects.create( plate="CCC-1234", ) park = Automobilie.objects.all() self.assertEquals(park.count(), 2) def test_update_auto(self): Automobilie.objects.create( plate="CCC-1234", ) auto = Automobilie.objects.get(plate="CCC-1234") auto.plate = "AAA-1111" auto.save() self.assertEquals(auto.plate, "AAA-1111")
{"/automobilies/tests/tests_models.py": ["/automobilies/models.py"], "/parking/tests/tests_entities.py": ["/automobilies/entities.py", "/parking/entities.py"], "/parking/validators.py": ["/parking/helpers.py"], "/parking/tests/tests_factories.py": ["/parking/factories.py"], "/parking/tests/tests_helpers.py": ["/parking/helpers.py"], "/automobilies/repositories.py": ["/automobilies/entities.py", "/automobilies/models.py"], "/parking/repository.py": ["/automobilies/repositories.py", "/parking/helpers.py", "/parking/entities.py", "/parking/models.py"], "/parking/urls.py": ["/parking/views.py"], "/parking/tests/tests_models.py": ["/parking/models.py", "/automobilies/models.py"], "/automobilies/tests/tests_repo.py": ["/automobilies/models.py", "/automobilies/entities.py", "/automobilies/repositories.py"], "/parking/tests/tests_interators.py": ["/parking/iterators.py", "/parking/serializers.py", "/parking/validators.py", "/parking/repository.py"], "/parking/tests/tests_validators.py": ["/parking/validators.py"], "/parking/views.py": ["/parking/factories.py"], "/parking/entities.py": ["/automobilies/models.py"], "/parking/models.py": ["/automobilies/models.py"], "/automobilies/tests/tests_entities.py": ["/automobilies/entities.py"], "/parking/tests/tests_serializers.py": ["/parking/entities.py", "/parking/models.py", "/parking/serializers.py", "/automobilies/models.py"], "/parking/factories.py": ["/parking/repository.py", "/parking/iterators.py", "/parking/validators.py", "/parking/serializers.py"], "/parking/tests/tests_repo.py": ["/parking/models.py", "/automobilies/models.py", "/parking/entities.py", "/parking/repository.py"]}
4,876
johnatasr/CoolPark
refs/heads/master
/parking/tests/tests_entities.py
from automobilies.entities import Automobilie from django.test import TestCase from datetime import datetime from parking.entities import ParkingOcurrency class ParkingOcurrencyEnttityTestCase(TestCase): """ Tests of ParkingOcurrency in parking.entities.py """ def setUp(self): self.po_one = ParkingOcurrency( paid=False, left=False, auto=Automobilie(plate="ABC-1234") ) self.po_two = ParkingOcurrency( paid=True, left=True, auto=Automobilie(plate="CBA-4321") ) def test_isistance_object(self): self.assertIsInstance(self.po_one, object) self.assertIsInstance(self.po_two, object) def test_atributes_values_po(self): po1 = { "id": 1, "paid": False, "left": False, "entry": datetime(2021, 6, 10), "exit": datetime(2021, 6, 11), "time": "24 hours", "auto": Automobilie(plate="CBA-4321"), } po2 = { "id": 2, "paid": False, "left": False, "entry": datetime(2021, 6, 10), "exit": datetime(2021, 6, 11), "time": "24 hours", "auto": Automobilie(plate="CBA-4321"), } self.po_one.set_id(1) self.po_one.set_entry(datetime(2021, 6, 10)) self.po_one.set_exit(datetime(2021, 6, 11)) self.po_one.set_time("24 hours") self.po_two.set_id(2) self.po_two.set_entry(datetime(2021, 6, 10)) self.po_two.set_exit(datetime(2021, 6, 12)) self.po_two.set_time("48 hours") self.assertEquals(self.po_one.id, 1) self.assertEquals(self.po_one.id, po1["id"]) self.assertEquals(self.po_one.paid, False) self.assertEquals(self.po_one.paid, po1["paid"]) self.assertEquals(self.po_one.left, False) self.assertEquals(self.po_one.left, po1["left"]) self.assertEquals(self.po_one.entry, datetime(2021, 6, 10)) self.assertEquals(self.po_one.entry, po1["entry"]) self.assertEquals(self.po_one.exit, datetime(2021, 6, 11)) self.assertEquals(self.po_one.exit, po1["exit"]) self.assertEquals(self.po_one.time, "24 hours") self.assertEquals(self.po_one.time, po1["time"]) def test_atributes_type_po(self): self.po_one.set_id(1) self.po_one.set_entry(datetime(2021, 6, 10)) self.po_one.set_exit(datetime(2021, 6, 11)) self.po_one.set_time("24 hours") self.assertIsInstance(self.po_one.id, int) self.assertIsInstance(self.po_one.paid, bool) self.assertIsInstance(self.po_one.left, bool) self.assertIsInstance(self.po_one.entry, object) self.assertIsInstance(self.po_one.exit, object) self.assertIsInstance(self.po_one.time, str) self.assertIsInstance(self.po_one.auto, object) def test_repr_class_po(self): repr: str = "Entity: ParkingOcurrency<id:1, time:24 hours, paid:False, left:False, auto:ABC-1234>" self.po_one.set_id(1) self.po_one.set_entry(datetime(2021, 6, 10)) self.po_one.set_exit(datetime(2021, 6, 11)) self.po_one.set_time("24 hours") self.assertEquals(self.po_one.__str__(), repr)
{"/automobilies/tests/tests_models.py": ["/automobilies/models.py"], "/parking/tests/tests_entities.py": ["/automobilies/entities.py", "/parking/entities.py"], "/parking/validators.py": ["/parking/helpers.py"], "/parking/tests/tests_factories.py": ["/parking/factories.py"], "/parking/tests/tests_helpers.py": ["/parking/helpers.py"], "/automobilies/repositories.py": ["/automobilies/entities.py", "/automobilies/models.py"], "/parking/repository.py": ["/automobilies/repositories.py", "/parking/helpers.py", "/parking/entities.py", "/parking/models.py"], "/parking/urls.py": ["/parking/views.py"], "/parking/tests/tests_models.py": ["/parking/models.py", "/automobilies/models.py"], "/automobilies/tests/tests_repo.py": ["/automobilies/models.py", "/automobilies/entities.py", "/automobilies/repositories.py"], "/parking/tests/tests_interators.py": ["/parking/iterators.py", "/parking/serializers.py", "/parking/validators.py", "/parking/repository.py"], "/parking/tests/tests_validators.py": ["/parking/validators.py"], "/parking/views.py": ["/parking/factories.py"], "/parking/entities.py": ["/automobilies/models.py"], "/parking/models.py": ["/automobilies/models.py"], "/automobilies/tests/tests_entities.py": ["/automobilies/entities.py"], "/parking/tests/tests_serializers.py": ["/parking/entities.py", "/parking/models.py", "/parking/serializers.py", "/automobilies/models.py"], "/parking/factories.py": ["/parking/repository.py", "/parking/iterators.py", "/parking/validators.py", "/parking/serializers.py"], "/parking/tests/tests_repo.py": ["/parking/models.py", "/automobilies/models.py", "/parking/entities.py", "/parking/repository.py"]}
4,877
johnatasr/CoolPark
refs/heads/master
/parking/serializers.py
from .interfaces import ISerializer class DefaultSerializer(ISerializer): def __init__(self, parking: object, msg: str): self.parking = parking self.msg = msg def mount_payload(self): payload: dict = { "id": self.parking.id, "msg": self.msg, "plate": self.parking.auto.plate, } return payload def create_message(self): message = self.mount_payload() return message class HistoricSerializer(ISerializer): def __init__(self, historic: object): self.historic = historic def mount_payload(self): list_historic: list = [] for parking in self.historic.iterator(): histo = { "id": parking["id"], "time": parking["time"], "paid": parking["paid"], "left": parking["left"], } list_historic.append(histo) return list_historic def create_message(self): message: dict = self.mount_payload() return message
{"/automobilies/tests/tests_models.py": ["/automobilies/models.py"], "/parking/tests/tests_entities.py": ["/automobilies/entities.py", "/parking/entities.py"], "/parking/validators.py": ["/parking/helpers.py"], "/parking/tests/tests_factories.py": ["/parking/factories.py"], "/parking/tests/tests_helpers.py": ["/parking/helpers.py"], "/automobilies/repositories.py": ["/automobilies/entities.py", "/automobilies/models.py"], "/parking/repository.py": ["/automobilies/repositories.py", "/parking/helpers.py", "/parking/entities.py", "/parking/models.py"], "/parking/urls.py": ["/parking/views.py"], "/parking/tests/tests_models.py": ["/parking/models.py", "/automobilies/models.py"], "/automobilies/tests/tests_repo.py": ["/automobilies/models.py", "/automobilies/entities.py", "/automobilies/repositories.py"], "/parking/tests/tests_interators.py": ["/parking/iterators.py", "/parking/serializers.py", "/parking/validators.py", "/parking/repository.py"], "/parking/tests/tests_validators.py": ["/parking/validators.py"], "/parking/views.py": ["/parking/factories.py"], "/parking/entities.py": ["/automobilies/models.py"], "/parking/models.py": ["/automobilies/models.py"], "/automobilies/tests/tests_entities.py": ["/automobilies/entities.py"], "/parking/tests/tests_serializers.py": ["/parking/entities.py", "/parking/models.py", "/parking/serializers.py", "/automobilies/models.py"], "/parking/factories.py": ["/parking/repository.py", "/parking/iterators.py", "/parking/validators.py", "/parking/serializers.py"], "/parking/tests/tests_repo.py": ["/parking/models.py", "/automobilies/models.py", "/parking/entities.py", "/parking/repository.py"]}
4,878
johnatasr/CoolPark
refs/heads/master
/parking/validators.py
from configs.exceptions import InvalidPayloadException from .interfaces import IValidator from .helpers import ParkingHelpers class ParkValidator(IValidator): DEFAULT_PLATE_MASK: str = "[A-Z]{3}-[0-9]{4}\Z" def __init__(self): self.helper = ParkingHelpers() @staticmethod def validate(value: bool) -> bool: return value def is_empty_payload(self, payload) -> (bool, Exception): if isinstance(payload, (dict, object, list, bytes)): return True else: raise InvalidPayloadException( source="validator", code="empty_payload", message="Payload in request is empty", ) def validate_only_plate(self, plate: str) -> (bool, Exception): return self.helper.regex_validate(plate, self.DEFAULT_PLATE_MASK) def validate_payload(self, payload) -> list: self.is_empty_payload(payload) if "plate" not in payload: raise InvalidPayloadException( source="validator", code="field_not_exists", message="Field required: plate", ) if len(payload["plate"]) < 8: raise InvalidPayloadException( source="validator", code="field_size_not_allowed", message="Field plate don't should be less than 8", ) if len(payload["plate"]) > 8: raise InvalidPayloadException( source="validator", code="field_size_not_allowed", message="Field plate don't should be major than 8", ) if not self.validate_only_plate(payload["plate"]): raise InvalidPayloadException( source="validator", code="field_not_allowed", message="Wrong format plate. Field should be in this format AAA-9999", ) return self.validate(True)
{"/automobilies/tests/tests_models.py": ["/automobilies/models.py"], "/parking/tests/tests_entities.py": ["/automobilies/entities.py", "/parking/entities.py"], "/parking/validators.py": ["/parking/helpers.py"], "/parking/tests/tests_factories.py": ["/parking/factories.py"], "/parking/tests/tests_helpers.py": ["/parking/helpers.py"], "/automobilies/repositories.py": ["/automobilies/entities.py", "/automobilies/models.py"], "/parking/repository.py": ["/automobilies/repositories.py", "/parking/helpers.py", "/parking/entities.py", "/parking/models.py"], "/parking/urls.py": ["/parking/views.py"], "/parking/tests/tests_models.py": ["/parking/models.py", "/automobilies/models.py"], "/automobilies/tests/tests_repo.py": ["/automobilies/models.py", "/automobilies/entities.py", "/automobilies/repositories.py"], "/parking/tests/tests_interators.py": ["/parking/iterators.py", "/parking/serializers.py", "/parking/validators.py", "/parking/repository.py"], "/parking/tests/tests_validators.py": ["/parking/validators.py"], "/parking/views.py": ["/parking/factories.py"], "/parking/entities.py": ["/automobilies/models.py"], "/parking/models.py": ["/automobilies/models.py"], "/automobilies/tests/tests_entities.py": ["/automobilies/entities.py"], "/parking/tests/tests_serializers.py": ["/parking/entities.py", "/parking/models.py", "/parking/serializers.py", "/automobilies/models.py"], "/parking/factories.py": ["/parking/repository.py", "/parking/iterators.py", "/parking/validators.py", "/parking/serializers.py"], "/parking/tests/tests_repo.py": ["/parking/models.py", "/automobilies/models.py", "/parking/entities.py", "/parking/repository.py"]}
4,879
johnatasr/CoolPark
refs/heads/master
/parking/tests/tests_factories.py
from django.test import TestCase from parking.factories import ParkFactory import unittest class ParkingFactoryTestCase(TestCase): """ Tests of ParkFactory in parking.factories.py """ def setUp(self): self.factory = ParkFactory def test_create_check_in_iterator(self): msg = self.factory.create_check_in_interator({"plate": "ABC-1234"}) self.assertIsInstance(msg, dict) def test_create_check_out_iterator(self): self.factory.create_check_in_interator({"plate": "ABC-1234"}) msg = self.factory.create_check_out_interator(1) self.assertIsInstance(msg, dict) def test_create_do_payment_iterator(self): self.factory.create_check_in_interator({"plate": "ABC-1234"}) msg = self.factory.create_do_payment_interator(1) self.assertIsInstance(msg, dict) def test_create_historic_iterator(self): self.factory.create_check_in_interator({"plate": "ABC-1234"}) msg = self.factory.create_historic_interator("ABC-1234") self.assertIsInstance(msg, list)
{"/automobilies/tests/tests_models.py": ["/automobilies/models.py"], "/parking/tests/tests_entities.py": ["/automobilies/entities.py", "/parking/entities.py"], "/parking/validators.py": ["/parking/helpers.py"], "/parking/tests/tests_factories.py": ["/parking/factories.py"], "/parking/tests/tests_helpers.py": ["/parking/helpers.py"], "/automobilies/repositories.py": ["/automobilies/entities.py", "/automobilies/models.py"], "/parking/repository.py": ["/automobilies/repositories.py", "/parking/helpers.py", "/parking/entities.py", "/parking/models.py"], "/parking/urls.py": ["/parking/views.py"], "/parking/tests/tests_models.py": ["/parking/models.py", "/automobilies/models.py"], "/automobilies/tests/tests_repo.py": ["/automobilies/models.py", "/automobilies/entities.py", "/automobilies/repositories.py"], "/parking/tests/tests_interators.py": ["/parking/iterators.py", "/parking/serializers.py", "/parking/validators.py", "/parking/repository.py"], "/parking/tests/tests_validators.py": ["/parking/validators.py"], "/parking/views.py": ["/parking/factories.py"], "/parking/entities.py": ["/automobilies/models.py"], "/parking/models.py": ["/automobilies/models.py"], "/automobilies/tests/tests_entities.py": ["/automobilies/entities.py"], "/parking/tests/tests_serializers.py": ["/parking/entities.py", "/parking/models.py", "/parking/serializers.py", "/automobilies/models.py"], "/parking/factories.py": ["/parking/repository.py", "/parking/iterators.py", "/parking/validators.py", "/parking/serializers.py"], "/parking/tests/tests_repo.py": ["/parking/models.py", "/automobilies/models.py", "/parking/entities.py", "/parking/repository.py"]}
4,880
johnatasr/CoolPark
refs/heads/master
/parking/migrations/0001_initial.py
# Generated by Django 3.1.7 on 2021-03-21 18:17 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ("automobilies", "0001_initial"), ] operations = [ migrations.CreateModel( name="ParkingOcurrency", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ("entry", models.DateTimeField(auto_created=True)), ( "time", models.CharField( blank=True, max_length=244, null=True, verbose_name="Time elapsed", ), ), ("exit", models.DateTimeField()), ("paid", models.BooleanField(default=False)), ("left", models.BooleanField(default=False)), ( "auto", models.ForeignKey( on_delete=django.db.models.deletion.DO_NOTHING, to="automobilies.automobilie", ), ), ], ), migrations.CreateModel( name="Park", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ( "parking_ocurrencies", models.ManyToManyField(blank=True, to="parking.ParkingOcurrency"), ), ], options={ "abstract": False, }, ), ]
{"/automobilies/tests/tests_models.py": ["/automobilies/models.py"], "/parking/tests/tests_entities.py": ["/automobilies/entities.py", "/parking/entities.py"], "/parking/validators.py": ["/parking/helpers.py"], "/parking/tests/tests_factories.py": ["/parking/factories.py"], "/parking/tests/tests_helpers.py": ["/parking/helpers.py"], "/automobilies/repositories.py": ["/automobilies/entities.py", "/automobilies/models.py"], "/parking/repository.py": ["/automobilies/repositories.py", "/parking/helpers.py", "/parking/entities.py", "/parking/models.py"], "/parking/urls.py": ["/parking/views.py"], "/parking/tests/tests_models.py": ["/parking/models.py", "/automobilies/models.py"], "/automobilies/tests/tests_repo.py": ["/automobilies/models.py", "/automobilies/entities.py", "/automobilies/repositories.py"], "/parking/tests/tests_interators.py": ["/parking/iterators.py", "/parking/serializers.py", "/parking/validators.py", "/parking/repository.py"], "/parking/tests/tests_validators.py": ["/parking/validators.py"], "/parking/views.py": ["/parking/factories.py"], "/parking/entities.py": ["/automobilies/models.py"], "/parking/models.py": ["/automobilies/models.py"], "/automobilies/tests/tests_entities.py": ["/automobilies/entities.py"], "/parking/tests/tests_serializers.py": ["/parking/entities.py", "/parking/models.py", "/parking/serializers.py", "/automobilies/models.py"], "/parking/factories.py": ["/parking/repository.py", "/parking/iterators.py", "/parking/validators.py", "/parking/serializers.py"], "/parking/tests/tests_repo.py": ["/parking/models.py", "/automobilies/models.py", "/parking/entities.py", "/parking/repository.py"]}
4,881
johnatasr/CoolPark
refs/heads/master
/automobilies/migrations/0002_auto_20210322_1803.py
# Generated by Django 3.1.7 on 2021-03-22 21:03 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("automobilies", "0001_initial"), ] operations = [ migrations.AlterField( model_name="automobilie", name="plate", field=models.CharField(max_length=8, verbose_name="Auto Plate"), ), ]
{"/automobilies/tests/tests_models.py": ["/automobilies/models.py"], "/parking/tests/tests_entities.py": ["/automobilies/entities.py", "/parking/entities.py"], "/parking/validators.py": ["/parking/helpers.py"], "/parking/tests/tests_factories.py": ["/parking/factories.py"], "/parking/tests/tests_helpers.py": ["/parking/helpers.py"], "/automobilies/repositories.py": ["/automobilies/entities.py", "/automobilies/models.py"], "/parking/repository.py": ["/automobilies/repositories.py", "/parking/helpers.py", "/parking/entities.py", "/parking/models.py"], "/parking/urls.py": ["/parking/views.py"], "/parking/tests/tests_models.py": ["/parking/models.py", "/automobilies/models.py"], "/automobilies/tests/tests_repo.py": ["/automobilies/models.py", "/automobilies/entities.py", "/automobilies/repositories.py"], "/parking/tests/tests_interators.py": ["/parking/iterators.py", "/parking/serializers.py", "/parking/validators.py", "/parking/repository.py"], "/parking/tests/tests_validators.py": ["/parking/validators.py"], "/parking/views.py": ["/parking/factories.py"], "/parking/entities.py": ["/automobilies/models.py"], "/parking/models.py": ["/automobilies/models.py"], "/automobilies/tests/tests_entities.py": ["/automobilies/entities.py"], "/parking/tests/tests_serializers.py": ["/parking/entities.py", "/parking/models.py", "/parking/serializers.py", "/automobilies/models.py"], "/parking/factories.py": ["/parking/repository.py", "/parking/iterators.py", "/parking/validators.py", "/parking/serializers.py"], "/parking/tests/tests_repo.py": ["/parking/models.py", "/automobilies/models.py", "/parking/entities.py", "/parking/repository.py"]}
4,882
johnatasr/CoolPark
refs/heads/master
/parking/helpers.py
from typing import Type from django.utils import timezone from dateutil import relativedelta from datetime import datetime import re class ParkingHelpers: @staticmethod def transform_date_checkout( start_date: Type[datetime], end_date: Type[datetime] ) -> str: """ " Transform the range of dates in a string representation """ result = relativedelta.relativedelta(end_date, start_date) msg: str = "" if result.hours >= 1: hours = "hours" if result.hours == 1: hours = "hour" msg += f"{result.hours} {hours}, " if result.minutes > 1: minutes = "minutes" else: minutes = "minute" msg += f"{result.minutes} {minutes}" return msg @staticmethod def regex_validate(plate: str, default_mask: str) -> bool: """ " Valid the plate using Regex """ regex = re.compile(default_mask) valid = regex.match(plate) if valid: return True else: raise Exception("Plate don't match with default plate validation") @staticmethod def get_today() -> datetime: """ " Get the time of current system """ return timezone.now()
{"/automobilies/tests/tests_models.py": ["/automobilies/models.py"], "/parking/tests/tests_entities.py": ["/automobilies/entities.py", "/parking/entities.py"], "/parking/validators.py": ["/parking/helpers.py"], "/parking/tests/tests_factories.py": ["/parking/factories.py"], "/parking/tests/tests_helpers.py": ["/parking/helpers.py"], "/automobilies/repositories.py": ["/automobilies/entities.py", "/automobilies/models.py"], "/parking/repository.py": ["/automobilies/repositories.py", "/parking/helpers.py", "/parking/entities.py", "/parking/models.py"], "/parking/urls.py": ["/parking/views.py"], "/parking/tests/tests_models.py": ["/parking/models.py", "/automobilies/models.py"], "/automobilies/tests/tests_repo.py": ["/automobilies/models.py", "/automobilies/entities.py", "/automobilies/repositories.py"], "/parking/tests/tests_interators.py": ["/parking/iterators.py", "/parking/serializers.py", "/parking/validators.py", "/parking/repository.py"], "/parking/tests/tests_validators.py": ["/parking/validators.py"], "/parking/views.py": ["/parking/factories.py"], "/parking/entities.py": ["/automobilies/models.py"], "/parking/models.py": ["/automobilies/models.py"], "/automobilies/tests/tests_entities.py": ["/automobilies/entities.py"], "/parking/tests/tests_serializers.py": ["/parking/entities.py", "/parking/models.py", "/parking/serializers.py", "/automobilies/models.py"], "/parking/factories.py": ["/parking/repository.py", "/parking/iterators.py", "/parking/validators.py", "/parking/serializers.py"], "/parking/tests/tests_repo.py": ["/parking/models.py", "/automobilies/models.py", "/parking/entities.py", "/parking/repository.py"]}
4,883
johnatasr/CoolPark
refs/heads/master
/parking/iterators.py
from configs.exceptions import InteratorException from .interfaces import IIterator from typing import Any """ In Iterators occour all iteration beetween repositories, serializers and validators adding the business rules in process """ class CheckInIterator(IIterator): """ " Interactor responsible for check-in, called by API """ def __init__(self, validator=None, repo=None, serializer=None): self.validator: object = validator self.repo: object = repo() self.serializer: object = serializer def set_params(self, park_payload: dict): self.payload = park_payload return self def execute(self): try: valided_payload = self.validator().validate_payload(self.payload) if valided_payload: plate: str = self.payload["plate"] created_parking_ocurrency = self.repo.create_parking_ocurrency_by_plate( plate=plate ) serialized_return = self.serializer( parking=created_parking_ocurrency, msg="Check-in created" ).create_message() return serialized_return except InteratorException as error: raise InteratorException(error) class CheckOutIterator(IIterator): """ " Interactor responsible for check-out, called by API """ def __init__(self, validator=None, repo=None, serializer=None): self.validator: object = validator self.repo: object = repo() self.serializer: object = serializer def set_params(self, parking_id: Any): self.parking_id = parking_id return self def execute(self): try: if isinstance(self.parking_id, str): self.parking_id = int(self.parking_id) parking: object = self.repo.get_parking_ocurrency_by_id(id=self.parking_id) if parking.exists(): parking: object = parking.first() if parking.paid: if parking.left: serialize = {"msg": "Check-out already done", "id": parking.id} return serialize parking_entity = self.repo.update_parking_ocurrency_checkout( parking ) serialize = self.serializer( parking=parking_entity, msg="Check-out done" ).create_message() return serialize else: serialize = { "msg": "Cannot Check-out, payment not done", "id": parking.id, } return serialize else: serialize = {"msg": f"Parking not found with ID : {self.parking_id}"} return serialize except InteratorException as error: raise InteratorException(error) class DoPaymentIterator(IIterator): """ Interactor responsible for the payment API process """ def __init__(self, validator=None, repo=None, serializer=None): self.validator: object = validator self.repo: object = repo() self.serializer: object = serializer def set_params(self, parking_id: Any): self.parking_id = parking_id return self def execute(self): try: if isinstance(self.parking_id, str): self.parking_id = int(self.parking_id) parking = self.repo.get_parking_ocurrency_by_id(id=self.parking_id) if parking.exists(): parking: object = parking.first() if parking.paid: serialize = {"msg": "Payment already done", "id": parking.id} return serialize parking_entity = self.repo.update_parking_ocurrency_pay(parking) serialize = self.serializer( parking=parking_entity, msg="Payment done" ).create_message() return serialize else: serialize = {"msg": f"Parking not found with ID : {self.parking_id}"} return serialize except InteratorException as error: raise InteratorException(error) class HistoricIterator(IIterator): """ Interactor responsible for the history of parking by the registered license plate """ def __init__(self, validator=None, repo=None, serializer=None): self.validator: object = validator self.repo: object = repo self.serializer: object = serializer def set_params(self, plate: str): self.plate = plate return self def execute(self): try: valided_plate = self.validator().validate_only_plate(self.plate) if valided_plate: historic = self.repo().get_historic_by_plate(self.plate) if historic.exists(): historic_cached = historic serialize = self.serializer(historic_cached).create_message() return serialize else: serialize = {"msg": f"Historic not found with plate : {self.plate}"} return serialize except InteratorException as error: raise InteratorException(error)
{"/automobilies/tests/tests_models.py": ["/automobilies/models.py"], "/parking/tests/tests_entities.py": ["/automobilies/entities.py", "/parking/entities.py"], "/parking/validators.py": ["/parking/helpers.py"], "/parking/tests/tests_factories.py": ["/parking/factories.py"], "/parking/tests/tests_helpers.py": ["/parking/helpers.py"], "/automobilies/repositories.py": ["/automobilies/entities.py", "/automobilies/models.py"], "/parking/repository.py": ["/automobilies/repositories.py", "/parking/helpers.py", "/parking/entities.py", "/parking/models.py"], "/parking/urls.py": ["/parking/views.py"], "/parking/tests/tests_models.py": ["/parking/models.py", "/automobilies/models.py"], "/automobilies/tests/tests_repo.py": ["/automobilies/models.py", "/automobilies/entities.py", "/automobilies/repositories.py"], "/parking/tests/tests_interators.py": ["/parking/iterators.py", "/parking/serializers.py", "/parking/validators.py", "/parking/repository.py"], "/parking/tests/tests_validators.py": ["/parking/validators.py"], "/parking/views.py": ["/parking/factories.py"], "/parking/entities.py": ["/automobilies/models.py"], "/parking/models.py": ["/automobilies/models.py"], "/automobilies/tests/tests_entities.py": ["/automobilies/entities.py"], "/parking/tests/tests_serializers.py": ["/parking/entities.py", "/parking/models.py", "/parking/serializers.py", "/automobilies/models.py"], "/parking/factories.py": ["/parking/repository.py", "/parking/iterators.py", "/parking/validators.py", "/parking/serializers.py"], "/parking/tests/tests_repo.py": ["/parking/models.py", "/automobilies/models.py", "/parking/entities.py", "/parking/repository.py"]}
4,884
johnatasr/CoolPark
refs/heads/master
/parking/tests/tests_helpers.py
from django.test import TestCase from parking.helpers import ParkingHelpers from typing import Any, Type from datetime import datetime from django.utils import timezone import unittest class ParkingHelpersTestCase(TestCase): """ Tests of ParkingHelpers in parking.helpers.py """ def setUp(self): self.helpers = ParkingHelpers self.start_time: Type[datetime] = datetime(2021, 3, 22) self.end_time: Type[datetime] = datetime(2021, 3, 23) self.mask = "[A-Z]{3}-[0-9]{4}\Z" def test_transform_date_checkout_type(self): details: str = self.helpers.transform_date_checkout( self.start_time, self.end_time ) self.assertIsInstance(details, str) def test_transform_date_checkout_value(self): details: str = self.helpers.transform_date_checkout( self.start_time, self.end_time ) self.assertEquals(details, "0 minute") def test_regex_validate_type(self): result = self.helpers.regex_validate("ABC-1234", self.mask) self.assertIsInstance(result, bool) def test_regex_validate_value(self): result = self.helpers.regex_validate("ABC-1234", self.mask) self.assertEquals(result, True) def test_get_today_type(self): result = self.helpers.get_today() self.assertIsInstance(result, datetime)
{"/automobilies/tests/tests_models.py": ["/automobilies/models.py"], "/parking/tests/tests_entities.py": ["/automobilies/entities.py", "/parking/entities.py"], "/parking/validators.py": ["/parking/helpers.py"], "/parking/tests/tests_factories.py": ["/parking/factories.py"], "/parking/tests/tests_helpers.py": ["/parking/helpers.py"], "/automobilies/repositories.py": ["/automobilies/entities.py", "/automobilies/models.py"], "/parking/repository.py": ["/automobilies/repositories.py", "/parking/helpers.py", "/parking/entities.py", "/parking/models.py"], "/parking/urls.py": ["/parking/views.py"], "/parking/tests/tests_models.py": ["/parking/models.py", "/automobilies/models.py"], "/automobilies/tests/tests_repo.py": ["/automobilies/models.py", "/automobilies/entities.py", "/automobilies/repositories.py"], "/parking/tests/tests_interators.py": ["/parking/iterators.py", "/parking/serializers.py", "/parking/validators.py", "/parking/repository.py"], "/parking/tests/tests_validators.py": ["/parking/validators.py"], "/parking/views.py": ["/parking/factories.py"], "/parking/entities.py": ["/automobilies/models.py"], "/parking/models.py": ["/automobilies/models.py"], "/automobilies/tests/tests_entities.py": ["/automobilies/entities.py"], "/parking/tests/tests_serializers.py": ["/parking/entities.py", "/parking/models.py", "/parking/serializers.py", "/automobilies/models.py"], "/parking/factories.py": ["/parking/repository.py", "/parking/iterators.py", "/parking/validators.py", "/parking/serializers.py"], "/parking/tests/tests_repo.py": ["/parking/models.py", "/automobilies/models.py", "/parking/entities.py", "/parking/repository.py"]}
4,885
johnatasr/CoolPark
refs/heads/master
/automobilies/repositories.py
from configs.exceptions import ConflictException from .entities import Automobilie from .models import Automobilie as AutomobilieModel from typing import Any class AutomobiliesRepo: def create_auto_model(self, auto_entity): """ Save the model Automobilie with the Entity created previously """ automobilie = AutomobilieModel.objects.create(plate=auto_entity.plate) automobilie.save() return automobilie def create_auto(self, plate: str): """ Create a Entity Automobilie saving in database the model object """ try: entity = Automobilie(plate=plate) automobilie = self.create_auto_model(entity) return automobilie except ConflictException as err: raise ConflictException( source="repository", code="conflit_in_create", message=f"Não possível skill, erro : {err}", )
{"/automobilies/tests/tests_models.py": ["/automobilies/models.py"], "/parking/tests/tests_entities.py": ["/automobilies/entities.py", "/parking/entities.py"], "/parking/validators.py": ["/parking/helpers.py"], "/parking/tests/tests_factories.py": ["/parking/factories.py"], "/parking/tests/tests_helpers.py": ["/parking/helpers.py"], "/automobilies/repositories.py": ["/automobilies/entities.py", "/automobilies/models.py"], "/parking/repository.py": ["/automobilies/repositories.py", "/parking/helpers.py", "/parking/entities.py", "/parking/models.py"], "/parking/urls.py": ["/parking/views.py"], "/parking/tests/tests_models.py": ["/parking/models.py", "/automobilies/models.py"], "/automobilies/tests/tests_repo.py": ["/automobilies/models.py", "/automobilies/entities.py", "/automobilies/repositories.py"], "/parking/tests/tests_interators.py": ["/parking/iterators.py", "/parking/serializers.py", "/parking/validators.py", "/parking/repository.py"], "/parking/tests/tests_validators.py": ["/parking/validators.py"], "/parking/views.py": ["/parking/factories.py"], "/parking/entities.py": ["/automobilies/models.py"], "/parking/models.py": ["/automobilies/models.py"], "/automobilies/tests/tests_entities.py": ["/automobilies/entities.py"], "/parking/tests/tests_serializers.py": ["/parking/entities.py", "/parking/models.py", "/parking/serializers.py", "/automobilies/models.py"], "/parking/factories.py": ["/parking/repository.py", "/parking/iterators.py", "/parking/validators.py", "/parking/serializers.py"], "/parking/tests/tests_repo.py": ["/parking/models.py", "/automobilies/models.py", "/parking/entities.py", "/parking/repository.py"]}
4,886
johnatasr/CoolPark
refs/heads/master
/parking/migrations/0004_auto_20210322_1803.py
# Generated by Django 3.1.7 on 2021-03-22 21:03 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ("parking", "0003_auto_20210321_1530"), ] operations = [ migrations.RenameModel( old_name="Park", new_name="Parking", ), migrations.AlterModelOptions( name="parking", options={"verbose_name": "Park"}, ), migrations.AlterModelOptions( name="parkingocurrency", options={ "verbose_name": "Parking Ocurrery", "verbose_name_plural": "Parking Ocurrencies", }, ), ]
{"/automobilies/tests/tests_models.py": ["/automobilies/models.py"], "/parking/tests/tests_entities.py": ["/automobilies/entities.py", "/parking/entities.py"], "/parking/validators.py": ["/parking/helpers.py"], "/parking/tests/tests_factories.py": ["/parking/factories.py"], "/parking/tests/tests_helpers.py": ["/parking/helpers.py"], "/automobilies/repositories.py": ["/automobilies/entities.py", "/automobilies/models.py"], "/parking/repository.py": ["/automobilies/repositories.py", "/parking/helpers.py", "/parking/entities.py", "/parking/models.py"], "/parking/urls.py": ["/parking/views.py"], "/parking/tests/tests_models.py": ["/parking/models.py", "/automobilies/models.py"], "/automobilies/tests/tests_repo.py": ["/automobilies/models.py", "/automobilies/entities.py", "/automobilies/repositories.py"], "/parking/tests/tests_interators.py": ["/parking/iterators.py", "/parking/serializers.py", "/parking/validators.py", "/parking/repository.py"], "/parking/tests/tests_validators.py": ["/parking/validators.py"], "/parking/views.py": ["/parking/factories.py"], "/parking/entities.py": ["/automobilies/models.py"], "/parking/models.py": ["/automobilies/models.py"], "/automobilies/tests/tests_entities.py": ["/automobilies/entities.py"], "/parking/tests/tests_serializers.py": ["/parking/entities.py", "/parking/models.py", "/parking/serializers.py", "/automobilies/models.py"], "/parking/factories.py": ["/parking/repository.py", "/parking/iterators.py", "/parking/validators.py", "/parking/serializers.py"], "/parking/tests/tests_repo.py": ["/parking/models.py", "/automobilies/models.py", "/parking/entities.py", "/parking/repository.py"]}
4,887
johnatasr/CoolPark
refs/heads/master
/parking/repository.py
from configs.exceptions import ConflictException from automobilies.repositories import AutomobiliesRepo from .helpers import ParkingHelpers from .entities import ( ParkingOcurrency as ParkingOcurrencyEntity, ) from .models import ParkingOcurrency, Parking from typing import Any, Type class ParkRepo: """ This layer is responsible for interacting with models and entities """ helper: Type[ParkingHelpers] = ParkingHelpers() def get_or_create_parking_base_model(self) -> Type[Parking]: """ Create a Parking model """ try: return Parking().load() except ConflictException as err: raise ConflictException( source="repository", code="conflit_in_create", message=f"Error in load Park objects: {err}", ) def create_parking_ocurrency_model( self, parking_object: object ) -> Type[ParkingOcurrency]: """ Create a Parking Ocurrenvy model """ try: parking_created_model = ParkingOcurrency( paid=parking_object.paid, left=parking_object.left, auto=parking_object.auto, ) parking_created_model.save() return parking_created_model except ConflictException as err: raise ConflictException( source="repository", code="conflit_in_create", message=f"Error in create a ocurreny_model: {err}", ) def create_parking_ocurrency_entity( self, parking_ocurrency: Any, type_object=False ) -> Type[ParkingOcurrencyEntity]: """ Create a Parking Ocurrenvy object Entity """ try: return ParkingOcurrencyEntity( paid=parking_ocurrency.paid if type_object else parking_ocurrency["paid"], left=parking_ocurrency.left if type_object else parking_ocurrency["left"], auto=parking_ocurrency.auto if type_object else parking_ocurrency["auto"], ) except ConflictException as err: raise ConflictException( source="repository", code="conflit_in_create", message=f"Error in create a ocurreny_entity: {err}", ) def create_parking_ocurrency_by_plate( self, plate: str ) -> Type[ParkingOcurrencyEntity]: """ Create a parking ocurrency by plate, this is the main method called by Check-in Api to create a new parking instance """ try: park: Type[Parking] = self.get_or_create_parking_base_model() automobilie = AutomobiliesRepo().create_auto(plate) parking_ocurrency_entity: Type[ ParkingOcurrencyEntity ] = self.create_parking_ocurrency_entity( {"paid": False, "left": False, "auto": automobilie}, type_object=False ) parking_ocurrency = self.create_parking_ocurrency_model( parking_ocurrency_entity ) park.parking_ocurrencies.add(parking_ocurrency) park.save() parking_ocurrency_entity.set_id(parking_ocurrency.id) return parking_ocurrency_entity except ConflictException as err: raise ConflictException( source="repository", code="conflit_in_create", message=f"Error in create a parking by plate : {err}", ) def get_parking_ocurrency_by_id(self, id: int) -> Type[ParkingOcurrency]: """ " Search a parking by Parking Ocurrency model id """ return ParkingOcurrency.objects.filter(id=id) def get_historic_by_plate(self, plate: str) -> Type[ParkingOcurrency]: """ " Search a parking by Automobilie model plate """ return ParkingOcurrency.objects.filter(auto__plate=plate).values( "id", "time", "paid", "left", "auto" ) def update_parking_ocurrency_checkout( self, parking: object ) -> Type[ParkingOcurrencyEntity]: """ " Update the parking ocurrency called by Check-out iterator """ try: exit_datetime = self.helper.get_today() formated_exit_date = self.helper.transform_date_checkout( start_date=parking.entry, end_date=exit_datetime ) parking.left = True parking.exit = exit_datetime parking.time = formated_exit_date parking.save() parking_entity = self.create_parking_ocurrency_entity( parking, type_object=True ) parking_entity.set_id(parking.id) return parking_entity except ConflictException as err: raise ConflictException( source="repository", code="conflit_in_update", message=f"Error in update checkout a ocurreny : {err}", ) def update_parking_ocurrency_pay( self, parking: object ) -> Type[ParkingOcurrencyEntity]: """ " Update the parking ocurrency called by Do-Payment iterator """ try: parking.paid = True parking.save() parking_entity = self.create_parking_ocurrency_entity( parking, type_object=True ) parking_entity.set_id(parking.id) return parking_entity except ConflictException as err: raise ConflictException( source="repository", code="conflit_in_update", message=f"Error in update pay a ocurreny : {err}", )
{"/automobilies/tests/tests_models.py": ["/automobilies/models.py"], "/parking/tests/tests_entities.py": ["/automobilies/entities.py", "/parking/entities.py"], "/parking/validators.py": ["/parking/helpers.py"], "/parking/tests/tests_factories.py": ["/parking/factories.py"], "/parking/tests/tests_helpers.py": ["/parking/helpers.py"], "/automobilies/repositories.py": ["/automobilies/entities.py", "/automobilies/models.py"], "/parking/repository.py": ["/automobilies/repositories.py", "/parking/helpers.py", "/parking/entities.py", "/parking/models.py"], "/parking/urls.py": ["/parking/views.py"], "/parking/tests/tests_models.py": ["/parking/models.py", "/automobilies/models.py"], "/automobilies/tests/tests_repo.py": ["/automobilies/models.py", "/automobilies/entities.py", "/automobilies/repositories.py"], "/parking/tests/tests_interators.py": ["/parking/iterators.py", "/parking/serializers.py", "/parking/validators.py", "/parking/repository.py"], "/parking/tests/tests_validators.py": ["/parking/validators.py"], "/parking/views.py": ["/parking/factories.py"], "/parking/entities.py": ["/automobilies/models.py"], "/parking/models.py": ["/automobilies/models.py"], "/automobilies/tests/tests_entities.py": ["/automobilies/entities.py"], "/parking/tests/tests_serializers.py": ["/parking/entities.py", "/parking/models.py", "/parking/serializers.py", "/automobilies/models.py"], "/parking/factories.py": ["/parking/repository.py", "/parking/iterators.py", "/parking/validators.py", "/parking/serializers.py"], "/parking/tests/tests_repo.py": ["/parking/models.py", "/automobilies/models.py", "/parking/entities.py", "/parking/repository.py"]}
4,888
johnatasr/CoolPark
refs/heads/master
/automobilies/models.py
from django.db import models # Create your models here. class Automobilie(models.Model): plate = models.CharField("Auto Plate", max_length=8, null=False, blank=False) def __str__(self): return self.plate
{"/automobilies/tests/tests_models.py": ["/automobilies/models.py"], "/parking/tests/tests_entities.py": ["/automobilies/entities.py", "/parking/entities.py"], "/parking/validators.py": ["/parking/helpers.py"], "/parking/tests/tests_factories.py": ["/parking/factories.py"], "/parking/tests/tests_helpers.py": ["/parking/helpers.py"], "/automobilies/repositories.py": ["/automobilies/entities.py", "/automobilies/models.py"], "/parking/repository.py": ["/automobilies/repositories.py", "/parking/helpers.py", "/parking/entities.py", "/parking/models.py"], "/parking/urls.py": ["/parking/views.py"], "/parking/tests/tests_models.py": ["/parking/models.py", "/automobilies/models.py"], "/automobilies/tests/tests_repo.py": ["/automobilies/models.py", "/automobilies/entities.py", "/automobilies/repositories.py"], "/parking/tests/tests_interators.py": ["/parking/iterators.py", "/parking/serializers.py", "/parking/validators.py", "/parking/repository.py"], "/parking/tests/tests_validators.py": ["/parking/validators.py"], "/parking/views.py": ["/parking/factories.py"], "/parking/entities.py": ["/automobilies/models.py"], "/parking/models.py": ["/automobilies/models.py"], "/automobilies/tests/tests_entities.py": ["/automobilies/entities.py"], "/parking/tests/tests_serializers.py": ["/parking/entities.py", "/parking/models.py", "/parking/serializers.py", "/automobilies/models.py"], "/parking/factories.py": ["/parking/repository.py", "/parking/iterators.py", "/parking/validators.py", "/parking/serializers.py"], "/parking/tests/tests_repo.py": ["/parking/models.py", "/automobilies/models.py", "/parking/entities.py", "/parking/repository.py"]}
4,889
johnatasr/CoolPark
refs/heads/master
/automobilies/apps.py
from django.apps import AppConfig class AutomobiliesConfig(AppConfig): name = "automobilies"
{"/automobilies/tests/tests_models.py": ["/automobilies/models.py"], "/parking/tests/tests_entities.py": ["/automobilies/entities.py", "/parking/entities.py"], "/parking/validators.py": ["/parking/helpers.py"], "/parking/tests/tests_factories.py": ["/parking/factories.py"], "/parking/tests/tests_helpers.py": ["/parking/helpers.py"], "/automobilies/repositories.py": ["/automobilies/entities.py", "/automobilies/models.py"], "/parking/repository.py": ["/automobilies/repositories.py", "/parking/helpers.py", "/parking/entities.py", "/parking/models.py"], "/parking/urls.py": ["/parking/views.py"], "/parking/tests/tests_models.py": ["/parking/models.py", "/automobilies/models.py"], "/automobilies/tests/tests_repo.py": ["/automobilies/models.py", "/automobilies/entities.py", "/automobilies/repositories.py"], "/parking/tests/tests_interators.py": ["/parking/iterators.py", "/parking/serializers.py", "/parking/validators.py", "/parking/repository.py"], "/parking/tests/tests_validators.py": ["/parking/validators.py"], "/parking/views.py": ["/parking/factories.py"], "/parking/entities.py": ["/automobilies/models.py"], "/parking/models.py": ["/automobilies/models.py"], "/automobilies/tests/tests_entities.py": ["/automobilies/entities.py"], "/parking/tests/tests_serializers.py": ["/parking/entities.py", "/parking/models.py", "/parking/serializers.py", "/automobilies/models.py"], "/parking/factories.py": ["/parking/repository.py", "/parking/iterators.py", "/parking/validators.py", "/parking/serializers.py"], "/parking/tests/tests_repo.py": ["/parking/models.py", "/automobilies/models.py", "/parking/entities.py", "/parking/repository.py"]}
4,890
johnatasr/CoolPark
refs/heads/master
/parking/urls.py
from django.urls import path, include from rest_framework.routers import DefaultRouter from .views import ParkViewSet router = DefaultRouter(trailing_slash=False) router.register("", ParkViewSet, basename="parking") app_name = "parking" urlpatterns = [ path("", include(router.urls)), ]
{"/automobilies/tests/tests_models.py": ["/automobilies/models.py"], "/parking/tests/tests_entities.py": ["/automobilies/entities.py", "/parking/entities.py"], "/parking/validators.py": ["/parking/helpers.py"], "/parking/tests/tests_factories.py": ["/parking/factories.py"], "/parking/tests/tests_helpers.py": ["/parking/helpers.py"], "/automobilies/repositories.py": ["/automobilies/entities.py", "/automobilies/models.py"], "/parking/repository.py": ["/automobilies/repositories.py", "/parking/helpers.py", "/parking/entities.py", "/parking/models.py"], "/parking/urls.py": ["/parking/views.py"], "/parking/tests/tests_models.py": ["/parking/models.py", "/automobilies/models.py"], "/automobilies/tests/tests_repo.py": ["/automobilies/models.py", "/automobilies/entities.py", "/automobilies/repositories.py"], "/parking/tests/tests_interators.py": ["/parking/iterators.py", "/parking/serializers.py", "/parking/validators.py", "/parking/repository.py"], "/parking/tests/tests_validators.py": ["/parking/validators.py"], "/parking/views.py": ["/parking/factories.py"], "/parking/entities.py": ["/automobilies/models.py"], "/parking/models.py": ["/automobilies/models.py"], "/automobilies/tests/tests_entities.py": ["/automobilies/entities.py"], "/parking/tests/tests_serializers.py": ["/parking/entities.py", "/parking/models.py", "/parking/serializers.py", "/automobilies/models.py"], "/parking/factories.py": ["/parking/repository.py", "/parking/iterators.py", "/parking/validators.py", "/parking/serializers.py"], "/parking/tests/tests_repo.py": ["/parking/models.py", "/automobilies/models.py", "/parking/entities.py", "/parking/repository.py"]}
4,891
johnatasr/CoolPark
refs/heads/master
/automobilies/entities.py
class Automobilie: def __init__(self, plate: str): self._id = None self._plate = plate def __repr__(self): return f"Entity: Automobilie<id:{self.id}, plate:{self.plate}>" def __eq__(self, other): return self.__dict__ == other.__dict__ def __ne__(self, other): return not self == other @property def id(self): return self._id def set_id(self, id: int): self._id = id @property def plate(self): return self._plate
{"/automobilies/tests/tests_models.py": ["/automobilies/models.py"], "/parking/tests/tests_entities.py": ["/automobilies/entities.py", "/parking/entities.py"], "/parking/validators.py": ["/parking/helpers.py"], "/parking/tests/tests_factories.py": ["/parking/factories.py"], "/parking/tests/tests_helpers.py": ["/parking/helpers.py"], "/automobilies/repositories.py": ["/automobilies/entities.py", "/automobilies/models.py"], "/parking/repository.py": ["/automobilies/repositories.py", "/parking/helpers.py", "/parking/entities.py", "/parking/models.py"], "/parking/urls.py": ["/parking/views.py"], "/parking/tests/tests_models.py": ["/parking/models.py", "/automobilies/models.py"], "/automobilies/tests/tests_repo.py": ["/automobilies/models.py", "/automobilies/entities.py", "/automobilies/repositories.py"], "/parking/tests/tests_interators.py": ["/parking/iterators.py", "/parking/serializers.py", "/parking/validators.py", "/parking/repository.py"], "/parking/tests/tests_validators.py": ["/parking/validators.py"], "/parking/views.py": ["/parking/factories.py"], "/parking/entities.py": ["/automobilies/models.py"], "/parking/models.py": ["/automobilies/models.py"], "/automobilies/tests/tests_entities.py": ["/automobilies/entities.py"], "/parking/tests/tests_serializers.py": ["/parking/entities.py", "/parking/models.py", "/parking/serializers.py", "/automobilies/models.py"], "/parking/factories.py": ["/parking/repository.py", "/parking/iterators.py", "/parking/validators.py", "/parking/serializers.py"], "/parking/tests/tests_repo.py": ["/parking/models.py", "/automobilies/models.py", "/parking/entities.py", "/parking/repository.py"]}
4,892
johnatasr/CoolPark
refs/heads/master
/parking/tests/tests_models.py
from parking.models import Parking, ParkingOcurrency from automobilies.models import Automobilie from django.test import TestCase class POTest(TestCase): """ Tests of ParkingOcurrency in parking.models.py """ def test_create_po(self): auto = Automobilie.objects.create(plate=f"ABC-1234") parking = ParkingOcurrency.objects.create( paid=False, left=False, time="24 Hours", auto=auto ) parking.save() po = ParkingOcurrency.objects.filter(auto__plate="ABC-1234") self.assertEquals(po.exists(), True) def test_update_po(self): auto = Automobilie.objects.create(plate=f"ABC-1234") parking = ParkingOcurrency.objects.create( paid=False, left=False, time="24 Hours", auto=auto ) parking.save() po = ParkingOcurrency.objects.filter(auto__plate="ABC-1234") po = po.first() po.paid = True po.left = True po.save() self.assertEquals(po.paid, True) self.assertEquals(po.left, True)
{"/automobilies/tests/tests_models.py": ["/automobilies/models.py"], "/parking/tests/tests_entities.py": ["/automobilies/entities.py", "/parking/entities.py"], "/parking/validators.py": ["/parking/helpers.py"], "/parking/tests/tests_factories.py": ["/parking/factories.py"], "/parking/tests/tests_helpers.py": ["/parking/helpers.py"], "/automobilies/repositories.py": ["/automobilies/entities.py", "/automobilies/models.py"], "/parking/repository.py": ["/automobilies/repositories.py", "/parking/helpers.py", "/parking/entities.py", "/parking/models.py"], "/parking/urls.py": ["/parking/views.py"], "/parking/tests/tests_models.py": ["/parking/models.py", "/automobilies/models.py"], "/automobilies/tests/tests_repo.py": ["/automobilies/models.py", "/automobilies/entities.py", "/automobilies/repositories.py"], "/parking/tests/tests_interators.py": ["/parking/iterators.py", "/parking/serializers.py", "/parking/validators.py", "/parking/repository.py"], "/parking/tests/tests_validators.py": ["/parking/validators.py"], "/parking/views.py": ["/parking/factories.py"], "/parking/entities.py": ["/automobilies/models.py"], "/parking/models.py": ["/automobilies/models.py"], "/automobilies/tests/tests_entities.py": ["/automobilies/entities.py"], "/parking/tests/tests_serializers.py": ["/parking/entities.py", "/parking/models.py", "/parking/serializers.py", "/automobilies/models.py"], "/parking/factories.py": ["/parking/repository.py", "/parking/iterators.py", "/parking/validators.py", "/parking/serializers.py"], "/parking/tests/tests_repo.py": ["/parking/models.py", "/automobilies/models.py", "/parking/entities.py", "/parking/repository.py"]}
4,893
johnatasr/CoolPark
refs/heads/master
/parking/tests/tests_views_api.py
from rest_framework import status from rest_framework.test import APITestCase class ParkViewSetTests(APITestCase): """ Tests of ParkViewSet in parking.views.py """ def setUp(self): self.data = {"plate": "ABC-1234"} def test_check_in_with_data(self): response = self.client.post("/parking", data=self.data, format="json") self.assertEqual(response.status_code, status.HTTP_200_OK) def test_check_in_wrong_data(self): data = {"plate": "abc-1234"} response = self.client.post("/parking", data=data, format="json") self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) def test_check_in_no_data(self): response = self.client.post("/parking") self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) def test_check_out_without_pay(self): self.client.post("/parking", data=self.data, format="json") response = self.client.put("/parking/1/out") self.assertEqual(response.status_code, status.HTTP_200_OK) def test_check_out_with_pay(self): self.client.post("/parking", data=self.data, format="json") self.client.put("/parking/1/pay") response = self.client.put("/parking/1/out") self.assertEqual(response.status_code, status.HTTP_200_OK) def test_check_in_without_id(self): self.client.post("/parking", data=self.data, format="json") self.client.put("/parking/1/pay") response = self.client.put("/parking/out") self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) def test_pay_with_id(self): self.client.post("/parking", data=self.data, format="json") response = self.client.put("/parking/1/pay") self.assertEqual(response.status_code, status.HTTP_200_OK) def test_pay_without_id(self): self.client.post("/parking", data=self.data, format="json") response = self.client.put("/parking/pay") self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) def test_pay_already_paid(self): self.client.post("/parking", data=self.data, format="json") self.client.put("/parking/1/pay") response = self.client.put("/parking/1/pay") self.assertEqual(response.status_code, status.HTTP_200_OK) def test_parking_history_with_plate(self): self.client.post("/parking", data=self.data, format="json") self.client.put("/parking/1/pay") self.client.put("/parking/1/out") response = self.client.get("/parking/ABC-1234") self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(len(response.data), 1) def test_parking_history_without_plate(self): self.client.post("/parking", data=self.data, format="json") self.client.put("/parking/1/pay") self.client.put("/parking/1/out") response = self.client.get("/parking/") self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
{"/automobilies/tests/tests_models.py": ["/automobilies/models.py"], "/parking/tests/tests_entities.py": ["/automobilies/entities.py", "/parking/entities.py"], "/parking/validators.py": ["/parking/helpers.py"], "/parking/tests/tests_factories.py": ["/parking/factories.py"], "/parking/tests/tests_helpers.py": ["/parking/helpers.py"], "/automobilies/repositories.py": ["/automobilies/entities.py", "/automobilies/models.py"], "/parking/repository.py": ["/automobilies/repositories.py", "/parking/helpers.py", "/parking/entities.py", "/parking/models.py"], "/parking/urls.py": ["/parking/views.py"], "/parking/tests/tests_models.py": ["/parking/models.py", "/automobilies/models.py"], "/automobilies/tests/tests_repo.py": ["/automobilies/models.py", "/automobilies/entities.py", "/automobilies/repositories.py"], "/parking/tests/tests_interators.py": ["/parking/iterators.py", "/parking/serializers.py", "/parking/validators.py", "/parking/repository.py"], "/parking/tests/tests_validators.py": ["/parking/validators.py"], "/parking/views.py": ["/parking/factories.py"], "/parking/entities.py": ["/automobilies/models.py"], "/parking/models.py": ["/automobilies/models.py"], "/automobilies/tests/tests_entities.py": ["/automobilies/entities.py"], "/parking/tests/tests_serializers.py": ["/parking/entities.py", "/parking/models.py", "/parking/serializers.py", "/automobilies/models.py"], "/parking/factories.py": ["/parking/repository.py", "/parking/iterators.py", "/parking/validators.py", "/parking/serializers.py"], "/parking/tests/tests_repo.py": ["/parking/models.py", "/automobilies/models.py", "/parking/entities.py", "/parking/repository.py"]}
4,894
johnatasr/CoolPark
refs/heads/master
/parking/migrations/0003_auto_20210321_1530.py
# Generated by Django 3.1.7 on 2021-03-21 18:30 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("parking", "0002_auto_20210321_1523"), ] operations = [ migrations.AlterField( model_name="parkingocurrency", name="entry", field=models.DateTimeField(), ), migrations.AlterField( model_name="parkingocurrency", name="exit", field=models.DateTimeField(null=True), ), ]
{"/automobilies/tests/tests_models.py": ["/automobilies/models.py"], "/parking/tests/tests_entities.py": ["/automobilies/entities.py", "/parking/entities.py"], "/parking/validators.py": ["/parking/helpers.py"], "/parking/tests/tests_factories.py": ["/parking/factories.py"], "/parking/tests/tests_helpers.py": ["/parking/helpers.py"], "/automobilies/repositories.py": ["/automobilies/entities.py", "/automobilies/models.py"], "/parking/repository.py": ["/automobilies/repositories.py", "/parking/helpers.py", "/parking/entities.py", "/parking/models.py"], "/parking/urls.py": ["/parking/views.py"], "/parking/tests/tests_models.py": ["/parking/models.py", "/automobilies/models.py"], "/automobilies/tests/tests_repo.py": ["/automobilies/models.py", "/automobilies/entities.py", "/automobilies/repositories.py"], "/parking/tests/tests_interators.py": ["/parking/iterators.py", "/parking/serializers.py", "/parking/validators.py", "/parking/repository.py"], "/parking/tests/tests_validators.py": ["/parking/validators.py"], "/parking/views.py": ["/parking/factories.py"], "/parking/entities.py": ["/automobilies/models.py"], "/parking/models.py": ["/automobilies/models.py"], "/automobilies/tests/tests_entities.py": ["/automobilies/entities.py"], "/parking/tests/tests_serializers.py": ["/parking/entities.py", "/parking/models.py", "/parking/serializers.py", "/automobilies/models.py"], "/parking/factories.py": ["/parking/repository.py", "/parking/iterators.py", "/parking/validators.py", "/parking/serializers.py"], "/parking/tests/tests_repo.py": ["/parking/models.py", "/automobilies/models.py", "/parking/entities.py", "/parking/repository.py"]}
4,895
johnatasr/CoolPark
refs/heads/master
/automobilies/tests/tests_repo.py
from automobilies.models import Automobilie from automobilies.entities import Automobilie as AutoEntity from automobilies.repositories import AutomobiliesRepo from django.test import TestCase class AutoRepoTestCase(TestCase): """ Tests of AutomobiliesRepo in automobilies.repository.py """ def setUp(self): self.repo = AutomobiliesRepo() def test_create_auto_model(self): auto_entity = AutoEntity(plate="ABC-1234") auto = self.repo.create_auto_model(auto_entity) self.assertIsInstance(auto, object) self.assertEquals(auto.plate, "ABC-1234") def test_create_auto(self): auto_entity = self.repo.create_auto(plate="CBA-1234") self.assertIsInstance(auto_entity, object) self.assertEquals(auto_entity.plate, "CBA-1234")
{"/automobilies/tests/tests_models.py": ["/automobilies/models.py"], "/parking/tests/tests_entities.py": ["/automobilies/entities.py", "/parking/entities.py"], "/parking/validators.py": ["/parking/helpers.py"], "/parking/tests/tests_factories.py": ["/parking/factories.py"], "/parking/tests/tests_helpers.py": ["/parking/helpers.py"], "/automobilies/repositories.py": ["/automobilies/entities.py", "/automobilies/models.py"], "/parking/repository.py": ["/automobilies/repositories.py", "/parking/helpers.py", "/parking/entities.py", "/parking/models.py"], "/parking/urls.py": ["/parking/views.py"], "/parking/tests/tests_models.py": ["/parking/models.py", "/automobilies/models.py"], "/automobilies/tests/tests_repo.py": ["/automobilies/models.py", "/automobilies/entities.py", "/automobilies/repositories.py"], "/parking/tests/tests_interators.py": ["/parking/iterators.py", "/parking/serializers.py", "/parking/validators.py", "/parking/repository.py"], "/parking/tests/tests_validators.py": ["/parking/validators.py"], "/parking/views.py": ["/parking/factories.py"], "/parking/entities.py": ["/automobilies/models.py"], "/parking/models.py": ["/automobilies/models.py"], "/automobilies/tests/tests_entities.py": ["/automobilies/entities.py"], "/parking/tests/tests_serializers.py": ["/parking/entities.py", "/parking/models.py", "/parking/serializers.py", "/automobilies/models.py"], "/parking/factories.py": ["/parking/repository.py", "/parking/iterators.py", "/parking/validators.py", "/parking/serializers.py"], "/parking/tests/tests_repo.py": ["/parking/models.py", "/automobilies/models.py", "/parking/entities.py", "/parking/repository.py"]}
4,896
johnatasr/CoolPark
refs/heads/master
/parking/apps.py
from django.apps import AppConfig class ParkConfig(AppConfig): name = "parking"
{"/automobilies/tests/tests_models.py": ["/automobilies/models.py"], "/parking/tests/tests_entities.py": ["/automobilies/entities.py", "/parking/entities.py"], "/parking/validators.py": ["/parking/helpers.py"], "/parking/tests/tests_factories.py": ["/parking/factories.py"], "/parking/tests/tests_helpers.py": ["/parking/helpers.py"], "/automobilies/repositories.py": ["/automobilies/entities.py", "/automobilies/models.py"], "/parking/repository.py": ["/automobilies/repositories.py", "/parking/helpers.py", "/parking/entities.py", "/parking/models.py"], "/parking/urls.py": ["/parking/views.py"], "/parking/tests/tests_models.py": ["/parking/models.py", "/automobilies/models.py"], "/automobilies/tests/tests_repo.py": ["/automobilies/models.py", "/automobilies/entities.py", "/automobilies/repositories.py"], "/parking/tests/tests_interators.py": ["/parking/iterators.py", "/parking/serializers.py", "/parking/validators.py", "/parking/repository.py"], "/parking/tests/tests_validators.py": ["/parking/validators.py"], "/parking/views.py": ["/parking/factories.py"], "/parking/entities.py": ["/automobilies/models.py"], "/parking/models.py": ["/automobilies/models.py"], "/automobilies/tests/tests_entities.py": ["/automobilies/entities.py"], "/parking/tests/tests_serializers.py": ["/parking/entities.py", "/parking/models.py", "/parking/serializers.py", "/automobilies/models.py"], "/parking/factories.py": ["/parking/repository.py", "/parking/iterators.py", "/parking/validators.py", "/parking/serializers.py"], "/parking/tests/tests_repo.py": ["/parking/models.py", "/automobilies/models.py", "/parking/entities.py", "/parking/repository.py"]}
4,897
johnatasr/CoolPark
refs/heads/master
/automobilies/migrations/0001_initial.py
# Generated by Django 3.1.7 on 2021-03-21 18:17 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [] operations = [ migrations.CreateModel( name="Automobilie", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ( "plate", models.CharField(max_length=8, verbose_name="Placa Automóvel"), ), ], ), ]
{"/automobilies/tests/tests_models.py": ["/automobilies/models.py"], "/parking/tests/tests_entities.py": ["/automobilies/entities.py", "/parking/entities.py"], "/parking/validators.py": ["/parking/helpers.py"], "/parking/tests/tests_factories.py": ["/parking/factories.py"], "/parking/tests/tests_helpers.py": ["/parking/helpers.py"], "/automobilies/repositories.py": ["/automobilies/entities.py", "/automobilies/models.py"], "/parking/repository.py": ["/automobilies/repositories.py", "/parking/helpers.py", "/parking/entities.py", "/parking/models.py"], "/parking/urls.py": ["/parking/views.py"], "/parking/tests/tests_models.py": ["/parking/models.py", "/automobilies/models.py"], "/automobilies/tests/tests_repo.py": ["/automobilies/models.py", "/automobilies/entities.py", "/automobilies/repositories.py"], "/parking/tests/tests_interators.py": ["/parking/iterators.py", "/parking/serializers.py", "/parking/validators.py", "/parking/repository.py"], "/parking/tests/tests_validators.py": ["/parking/validators.py"], "/parking/views.py": ["/parking/factories.py"], "/parking/entities.py": ["/automobilies/models.py"], "/parking/models.py": ["/automobilies/models.py"], "/automobilies/tests/tests_entities.py": ["/automobilies/entities.py"], "/parking/tests/tests_serializers.py": ["/parking/entities.py", "/parking/models.py", "/parking/serializers.py", "/automobilies/models.py"], "/parking/factories.py": ["/parking/repository.py", "/parking/iterators.py", "/parking/validators.py", "/parking/serializers.py"], "/parking/tests/tests_repo.py": ["/parking/models.py", "/automobilies/models.py", "/parking/entities.py", "/parking/repository.py"]}
4,898
johnatasr/CoolPark
refs/heads/master
/parking/tests/tests_interators.py
from django.test import TestCase from parking.iterators import ( CheckInIterator, CheckOutIterator, DoPaymentIterator, HistoricIterator, ) from parking.serializers import DefaultSerializer, HistoricSerializer from parking.validators import ParkValidator from parking.repository import ParkRepo class CheckInIteratorTestCase(TestCase): """ Tests of CheckInIterator in parking.iterator.py """ def setUp(self): self.iterator = CheckInIterator( validator=ParkValidator, repo=ParkRepo, serializer=DefaultSerializer ) def test_init(self): self.assertIsInstance(self.iterator, object) self.assertIsInstance(self.iterator.validator, object) self.assertIsInstance(self.iterator.repo, object) self.assertIsInstance(self.iterator.serializer, object) def test_set_params(self): self.iterator.set_params(park_payload={"plate": "ABC-1234"}) self.assertIsInstance(self.iterator.payload, dict) self.assertEquals(self.iterator.payload["plate"], "ABC-1234") def test_execute(self): result = self.iterator.set_params(park_payload={"plate": "ABC-1234"}).execute() self.assertIsInstance(result, dict) self.assertEquals(result["msg"], "Check-in created") self.assertEquals(result["plate"], "ABC-1234") class CheckOutIteratorTestCase(TestCase): """ Tests of CheckOutIterator in parking.iterator.py """ def setUp(self): self.iterator = CheckOutIterator( validator=ParkValidator, repo=ParkRepo, serializer=DefaultSerializer ) def test_init(self): self.assertIsInstance(self.iterator, object) self.assertIsInstance(self.iterator.validator, object) self.assertIsInstance(self.iterator.repo, object) self.assertIsInstance(self.iterator.serializer, object) def test_set_params(self): self.iterator.set_params(1) self.assertIsInstance(self.iterator.parking_id, int) self.assertEquals(self.iterator.parking_id, 1) self.iterator.set_params("1") self.assertIsInstance(self.iterator.parking_id, str) self.assertEquals(self.iterator.parking_id, "1") def test_execute(self): check_in = CheckInIterator( validator=ParkValidator, repo=ParkRepo, serializer=DefaultSerializer ).set_params({"plate": "ABC-1234"}).execute() result = self.iterator.set_params(parking_id=6).execute() self.assertIsInstance(result, dict) def test_execute_payment_not_done(self): CheckInIterator( validator=ParkValidator, repo=ParkRepo, serializer=DefaultSerializer ).set_params({"plate": "ABC-1234"}).execute() result = self.iterator.set_params(1).execute() self.assertIsInstance(result["msg"], str) def test_execute_already_done(self): CheckInIterator( validator=ParkValidator, repo=ParkRepo, serializer=DefaultSerializer ).set_params({"plate": "ABC-1234"}).execute() DoPaymentIterator( validator=ParkValidator, repo=ParkRepo, serializer=DefaultSerializer ).set_params(1).execute() CheckOutIterator( validator=ParkValidator, repo=ParkRepo, serializer=DefaultSerializer ).set_params(1).execute() result = self.iterator.set_params(parking_id=1).execute() self.assertIsInstance(result["msg"], str) def test_execute_wrong_id(self): result = self.iterator.set_params(parking_id=48).execute() self.assertIsInstance(result["msg"], str) class DoPaymentIteratorTestCase(TestCase): """ Tests of DoPaymentIterator in parking.iterator.py """ def setUp(self): self.iterator = DoPaymentIterator( validator=ParkValidator, repo=ParkRepo, serializer=DefaultSerializer ) def test_init(self): self.assertIsInstance(self.iterator, object) self.assertIsInstance(self.iterator.validator, object) self.assertIsInstance(self.iterator.repo, object) self.assertIsInstance(self.iterator.serializer, object) def test_set_params(self): self.iterator.set_params(1) self.assertIsInstance(self.iterator.parking_id, int) self.assertEquals(self.iterator.parking_id, 1) self.iterator.set_params("1") self.assertIsInstance(self.iterator.parking_id, str) self.assertEquals(self.iterator.parking_id, "1") def test_execute(self): CheckInIterator( validator=ParkValidator, repo=ParkRepo, serializer=DefaultSerializer ).set_params({"plate": "ABC-1234"}).execute() result = self.iterator.set_params(parking_id=1).execute() self.assertIsInstance(result, dict) def test_execute_payment_already(self): CheckInIterator( validator=ParkValidator, repo=ParkRepo, serializer=DefaultSerializer ).set_params({"plate": "ABC-1234"}).execute() DoPaymentIterator( validator=ParkValidator, repo=ParkRepo, serializer=DefaultSerializer ).set_params(1).execute() result = self.iterator.set_params(1).execute() self.assertIsInstance(result["msg"], str) def test_execute_wrong_id(self): result = self.iterator.set_params(48).execute() self.assertEquals(result["msg"], "Parking not found with ID : 48") class HistoricIteratorTestCase(TestCase): """ Tests of HistoricIterator in parking.iterator.py """ def setUp(self): self.iterator = HistoricIterator( validator=ParkValidator, repo=ParkRepo, serializer=HistoricSerializer ) def test_init(self): self.assertIsInstance(self.iterator, object) self.assertIsInstance(self.iterator.validator, object) self.assertIsInstance(self.iterator.repo, object) self.assertIsInstance(self.iterator.serializer, object) def test_set_params(self): self.iterator.set_params(plate="ABC-1234") self.assertIsInstance(self.iterator.plate, str) self.assertEquals(self.iterator.plate, "ABC-1234") def test_execute(self): CheckInIterator( validator=ParkValidator, repo=ParkRepo, serializer=DefaultSerializer ).set_params({"plate": "ABC-1234"}).execute() DoPaymentIterator( validator=ParkValidator, repo=ParkRepo, serializer=DefaultSerializer ).set_params(1).execute() CheckOutIterator( validator=ParkValidator, repo=ParkRepo, serializer=DefaultSerializer ).set_params(1).execute() CheckInIterator( validator=ParkValidator, repo=ParkRepo, serializer=DefaultSerializer ).set_params({"plate": "ABC-1234"}).execute() DoPaymentIterator( validator=ParkValidator, repo=ParkRepo, serializer=DefaultSerializer ).set_params(2).execute() CheckOutIterator( validator=ParkValidator, repo=ParkRepo, serializer=DefaultSerializer ).set_params(2).execute() result = self.iterator.set_params(plate="ABC-1234").execute() self.assertIsInstance(result, list) self.assertEquals(len(result), 2) def test_execute_not_fould(self): result = self.iterator.set_params(plate="ASQ-1234").execute() self.assertEquals(result["msg"], "Historic not found with plate : ASQ-1234")
{"/automobilies/tests/tests_models.py": ["/automobilies/models.py"], "/parking/tests/tests_entities.py": ["/automobilies/entities.py", "/parking/entities.py"], "/parking/validators.py": ["/parking/helpers.py"], "/parking/tests/tests_factories.py": ["/parking/factories.py"], "/parking/tests/tests_helpers.py": ["/parking/helpers.py"], "/automobilies/repositories.py": ["/automobilies/entities.py", "/automobilies/models.py"], "/parking/repository.py": ["/automobilies/repositories.py", "/parking/helpers.py", "/parking/entities.py", "/parking/models.py"], "/parking/urls.py": ["/parking/views.py"], "/parking/tests/tests_models.py": ["/parking/models.py", "/automobilies/models.py"], "/automobilies/tests/tests_repo.py": ["/automobilies/models.py", "/automobilies/entities.py", "/automobilies/repositories.py"], "/parking/tests/tests_interators.py": ["/parking/iterators.py", "/parking/serializers.py", "/parking/validators.py", "/parking/repository.py"], "/parking/tests/tests_validators.py": ["/parking/validators.py"], "/parking/views.py": ["/parking/factories.py"], "/parking/entities.py": ["/automobilies/models.py"], "/parking/models.py": ["/automobilies/models.py"], "/automobilies/tests/tests_entities.py": ["/automobilies/entities.py"], "/parking/tests/tests_serializers.py": ["/parking/entities.py", "/parking/models.py", "/parking/serializers.py", "/automobilies/models.py"], "/parking/factories.py": ["/parking/repository.py", "/parking/iterators.py", "/parking/validators.py", "/parking/serializers.py"], "/parking/tests/tests_repo.py": ["/parking/models.py", "/automobilies/models.py", "/parking/entities.py", "/parking/repository.py"]}
4,899
johnatasr/CoolPark
refs/heads/master
/parking/tests/tests_validators.py
from parking.validators import ParkValidator from configs.exceptions import InvalidPayloadException from django.test import TestCase import unittest class ParkValidatorTestCase(TestCase): """ Tests of ParkValidator in parking.validators.py """ def setUp(self): self.validator = ParkValidator() def test_type_regex(self): self.assertEquals(self.validator.DEFAULT_PLATE_MASK, "[A-Z]{3}-[0-9]{4}\Z") def test_validate(self): self.assertEquals(self.validator.validate(True), True) self.assertEquals(self.validator.validate(False), False) def test_is_empty_payload(self): payload = {"plate": "ABC-1234"} result = self.validator.is_empty_payload(payload) self.assertEquals(result, True) def test_validate_only_plate(self): plate = "ABC-1234" result = self.validator.validate_only_plate(plate) self.assertEquals(result, True) def test_validate_payload(self): payload = {"plate": "ABC-1234"} result = self.validator.validate_payload(payload) self.assertEquals(result, True)
{"/automobilies/tests/tests_models.py": ["/automobilies/models.py"], "/parking/tests/tests_entities.py": ["/automobilies/entities.py", "/parking/entities.py"], "/parking/validators.py": ["/parking/helpers.py"], "/parking/tests/tests_factories.py": ["/parking/factories.py"], "/parking/tests/tests_helpers.py": ["/parking/helpers.py"], "/automobilies/repositories.py": ["/automobilies/entities.py", "/automobilies/models.py"], "/parking/repository.py": ["/automobilies/repositories.py", "/parking/helpers.py", "/parking/entities.py", "/parking/models.py"], "/parking/urls.py": ["/parking/views.py"], "/parking/tests/tests_models.py": ["/parking/models.py", "/automobilies/models.py"], "/automobilies/tests/tests_repo.py": ["/automobilies/models.py", "/automobilies/entities.py", "/automobilies/repositories.py"], "/parking/tests/tests_interators.py": ["/parking/iterators.py", "/parking/serializers.py", "/parking/validators.py", "/parking/repository.py"], "/parking/tests/tests_validators.py": ["/parking/validators.py"], "/parking/views.py": ["/parking/factories.py"], "/parking/entities.py": ["/automobilies/models.py"], "/parking/models.py": ["/automobilies/models.py"], "/automobilies/tests/tests_entities.py": ["/automobilies/entities.py"], "/parking/tests/tests_serializers.py": ["/parking/entities.py", "/parking/models.py", "/parking/serializers.py", "/automobilies/models.py"], "/parking/factories.py": ["/parking/repository.py", "/parking/iterators.py", "/parking/validators.py", "/parking/serializers.py"], "/parking/tests/tests_repo.py": ["/parking/models.py", "/automobilies/models.py", "/parking/entities.py", "/parking/repository.py"]}
4,900
johnatasr/CoolPark
refs/heads/master
/parking/views.py
# Create your views here. from rest_framework import viewsets from rest_framework.decorators import action from rest_framework.status import HTTP_200_OK, HTTP_400_BAD_REQUEST from rest_framework.response import Response from parking.factories import ParkFactory # Register your viewsets here. class ParkViewSet(viewsets.GenericViewSet): """ API made using Django Rest Framework """ factory = ParkFactory() http_method_names = ["get", "post", "put"] @action(methods=["POST"], detail=False, url_path="parking") def check_in(self, request): """ Check-in enpoint """ try: check_in_result = self.factory.create_check_in_interator(data=request.data) return Response(check_in_result, status=HTTP_200_OK) except Exception as error: return Response({"msg": error.args[0]}, status=HTTP_400_BAD_REQUEST) @action(methods=["PUT"], detail=False, url_path="parking/(?P<id>[0-9]+)/out") def check_out(self, request, id): """ Enpoint to check-out """ try: check_out_result = self.factory.create_check_out_interator(id=id) return Response(check_out_result, status=HTTP_200_OK) except Exception as error: return Response({"msg": error.args[0]}, status=HTTP_400_BAD_REQUEST) @action(methods=["PUT"], detail=False, url_path="parking/(?P<id>[0-9]+)/pay") def do_payment(self, request, id): """ Enpoint for payments """ try: payment_result = self.factory.create_do_payment_interator(id=id) return Response(payment_result, status=HTTP_200_OK) except Exception as error: return Response({"msg": error.args[0]}, status=HTTP_400_BAD_REQUEST) @action( methods=["GET"], detail=False, url_path="parking/(?P<plate>[A-Z]{3}-[0-9]{4})" ) def parking_history(self, request, plate: str): """ Enpoint of parking history """ try: history_result = self.factory.create_historic_interator(plate=plate) return Response(history_result, status=HTTP_200_OK) except Exception as error: return Response({"msg": error.args[0]}, status=HTTP_400_BAD_REQUEST)
{"/automobilies/tests/tests_models.py": ["/automobilies/models.py"], "/parking/tests/tests_entities.py": ["/automobilies/entities.py", "/parking/entities.py"], "/parking/validators.py": ["/parking/helpers.py"], "/parking/tests/tests_factories.py": ["/parking/factories.py"], "/parking/tests/tests_helpers.py": ["/parking/helpers.py"], "/automobilies/repositories.py": ["/automobilies/entities.py", "/automobilies/models.py"], "/parking/repository.py": ["/automobilies/repositories.py", "/parking/helpers.py", "/parking/entities.py", "/parking/models.py"], "/parking/urls.py": ["/parking/views.py"], "/parking/tests/tests_models.py": ["/parking/models.py", "/automobilies/models.py"], "/automobilies/tests/tests_repo.py": ["/automobilies/models.py", "/automobilies/entities.py", "/automobilies/repositories.py"], "/parking/tests/tests_interators.py": ["/parking/iterators.py", "/parking/serializers.py", "/parking/validators.py", "/parking/repository.py"], "/parking/tests/tests_validators.py": ["/parking/validators.py"], "/parking/views.py": ["/parking/factories.py"], "/parking/entities.py": ["/automobilies/models.py"], "/parking/models.py": ["/automobilies/models.py"], "/automobilies/tests/tests_entities.py": ["/automobilies/entities.py"], "/parking/tests/tests_serializers.py": ["/parking/entities.py", "/parking/models.py", "/parking/serializers.py", "/automobilies/models.py"], "/parking/factories.py": ["/parking/repository.py", "/parking/iterators.py", "/parking/validators.py", "/parking/serializers.py"], "/parking/tests/tests_repo.py": ["/parking/models.py", "/automobilies/models.py", "/parking/entities.py", "/parking/repository.py"]}
4,901
johnatasr/CoolPark
refs/heads/master
/parking/entities.py
from typing import List, Type from datetime import datetime from automobilies.models import Automobilie class ParkingOcurrency: """ Representation in Object of Model ParkingOcurrency """ def __init__(self, paid: bool, left: bool, auto: Type[Automobilie]): self._id = None self._time = None self._entry = None self._exit = None self._paid = paid self._left = left self._auto = auto def __repr__(self): return f"Entity: ParkingOcurrency<id:{self.id}, time:{self.time}, paid:{self.paid}, left:{self.left}, auto:{self.auto.plate}>" def __eq__(self, other): return self.__dict__ == other.__dict__ def __ne__(self, other): return not self == other def __hash__(self): return hash(("id", self.id, "time", self.time)) @property def id(self): return self._id def set_id(self, id: int): self._id = id @property def time(self): return self._time def set_time(self, time_string: str): self._time = time_string @property def entry(self): return self._entry def set_entry(self, entry: Type[datetime]): self._entry = entry @property def exit(self): return self._exit def set_exit(self, exit: Type[datetime]): self._exit = exit @property def paid(self): return self._paid @property def left(self): return self._left @property def auto(self): return self._auto @property def auto_plate(self): return self._auto.plate class Parking: """ Representation in Object of Model Parking """ def __init__(self, park_ocurrencies: List[ParkingOcurrency]): self._id = None self._park_ocurrencies = park_ocurrencies def __eq__(self, other): return self.__dict__ == other.__dict__ def __ne__(self, other): return not self == other @property def id(self): return self._id def set_id(self, id: int): self._id = id @property def park_ocurrencies(self): return self.park_ocurrencies
{"/automobilies/tests/tests_models.py": ["/automobilies/models.py"], "/parking/tests/tests_entities.py": ["/automobilies/entities.py", "/parking/entities.py"], "/parking/validators.py": ["/parking/helpers.py"], "/parking/tests/tests_factories.py": ["/parking/factories.py"], "/parking/tests/tests_helpers.py": ["/parking/helpers.py"], "/automobilies/repositories.py": ["/automobilies/entities.py", "/automobilies/models.py"], "/parking/repository.py": ["/automobilies/repositories.py", "/parking/helpers.py", "/parking/entities.py", "/parking/models.py"], "/parking/urls.py": ["/parking/views.py"], "/parking/tests/tests_models.py": ["/parking/models.py", "/automobilies/models.py"], "/automobilies/tests/tests_repo.py": ["/automobilies/models.py", "/automobilies/entities.py", "/automobilies/repositories.py"], "/parking/tests/tests_interators.py": ["/parking/iterators.py", "/parking/serializers.py", "/parking/validators.py", "/parking/repository.py"], "/parking/tests/tests_validators.py": ["/parking/validators.py"], "/parking/views.py": ["/parking/factories.py"], "/parking/entities.py": ["/automobilies/models.py"], "/parking/models.py": ["/automobilies/models.py"], "/automobilies/tests/tests_entities.py": ["/automobilies/entities.py"], "/parking/tests/tests_serializers.py": ["/parking/entities.py", "/parking/models.py", "/parking/serializers.py", "/automobilies/models.py"], "/parking/factories.py": ["/parking/repository.py", "/parking/iterators.py", "/parking/validators.py", "/parking/serializers.py"], "/parking/tests/tests_repo.py": ["/parking/models.py", "/automobilies/models.py", "/parking/entities.py", "/parking/repository.py"]}
4,902
johnatasr/CoolPark
refs/heads/master
/parking/models.py
from django.db import models from django.core.cache import cache from django.utils import timezone from automobilies.models import Automobilie # Create your models here. class ParkingOcurrency(models.Model): time = models.CharField("Time elapsed", max_length=244, null=True, blank=True) entry = models.DateTimeField() exit = models.DateTimeField(null=True) paid = models.BooleanField(default=False) left = models.BooleanField(default=False) auto = models.ForeignKey(Automobilie, on_delete=models.DO_NOTHING) class Meta: verbose_name = "Parking Ocurrery" verbose_name_plural = "Parking Ocurrencies" def save(self, *args, **kwargs): self.entry = timezone.now() return super(ParkingOcurrency, self).save(*args, **kwargs) class SingletonModel(models.Model): class Meta: abstract = True def set_cache(self): cache.set(self.__class__.__name__, self) def delete(self, *args, **kwargs): pass def save(self, *args, **kwargs): self.pk = 1 super(SingletonModel, self).save(*args, **kwargs) self.set_cache() @classmethod def load(cls): if cache.get(cls.__name__) is None: obj, created = cls.objects.get_or_create(pk=1) if not created: obj.set_cache() return cache.get(cls.__name__) class Parking(SingletonModel): """ " Model base, representation of Parking """ parking_ocurrencies = models.ManyToManyField(ParkingOcurrency, blank=True) class Meta: verbose_name = "Park" def __str__(self): return str(self.id)
{"/automobilies/tests/tests_models.py": ["/automobilies/models.py"], "/parking/tests/tests_entities.py": ["/automobilies/entities.py", "/parking/entities.py"], "/parking/validators.py": ["/parking/helpers.py"], "/parking/tests/tests_factories.py": ["/parking/factories.py"], "/parking/tests/tests_helpers.py": ["/parking/helpers.py"], "/automobilies/repositories.py": ["/automobilies/entities.py", "/automobilies/models.py"], "/parking/repository.py": ["/automobilies/repositories.py", "/parking/helpers.py", "/parking/entities.py", "/parking/models.py"], "/parking/urls.py": ["/parking/views.py"], "/parking/tests/tests_models.py": ["/parking/models.py", "/automobilies/models.py"], "/automobilies/tests/tests_repo.py": ["/automobilies/models.py", "/automobilies/entities.py", "/automobilies/repositories.py"], "/parking/tests/tests_interators.py": ["/parking/iterators.py", "/parking/serializers.py", "/parking/validators.py", "/parking/repository.py"], "/parking/tests/tests_validators.py": ["/parking/validators.py"], "/parking/views.py": ["/parking/factories.py"], "/parking/entities.py": ["/automobilies/models.py"], "/parking/models.py": ["/automobilies/models.py"], "/automobilies/tests/tests_entities.py": ["/automobilies/entities.py"], "/parking/tests/tests_serializers.py": ["/parking/entities.py", "/parking/models.py", "/parking/serializers.py", "/automobilies/models.py"], "/parking/factories.py": ["/parking/repository.py", "/parking/iterators.py", "/parking/validators.py", "/parking/serializers.py"], "/parking/tests/tests_repo.py": ["/parking/models.py", "/automobilies/models.py", "/parking/entities.py", "/parking/repository.py"]}
4,903
johnatasr/CoolPark
refs/heads/master
/automobilies/tests/tests_entities.py
from automobilies.entities import Automobilie from django.test import TestCase class AutomobilieEntityTestCase(TestCase): """ Tests of Automobilie in automobilies.entities.py """ def setUp(self): self.auto_one = Automobilie(plate="ABC-1234") self.auto_two = Automobilie(plate="CBA-4321") def test_isistance_object(self): self.assertIsInstance(self.auto_one, object) self.assertIsInstance(self.auto_two, object) def test_atributes_values_po(self): auto1 = {"id": 1, "plate": "ABC-1234"} auto2 = {"id": 2, "plate": "CBA-4321"} self.auto_one.set_id(1) self.auto_two.set_id(2) self.assertEquals(self.auto_one.id, 1) self.assertEquals(self.auto_one.id, auto1["id"]) self.assertEquals(self.auto_one.plate, "ABC-1234") self.assertEquals(self.auto_one.plate, auto1["plate"]) self.assertEquals(self.auto_two.id, 2) self.assertEquals(self.auto_two.id, auto2["id"]) self.assertEquals(self.auto_two.plate, "CBA-4321") self.assertEquals(self.auto_two.plate, auto2["plate"]) def test_atributes_type_po(self): self.auto_one.set_id(1) self.auto_two.set_id(2) self.assertIsInstance(self.auto_one.id, int) self.assertIsInstance(self.auto_one.plate, str) self.assertIsInstance(self.auto_two.id, int) self.assertIsInstance(self.auto_two.plate, str) def test_repr_class_po(self): self.auto_one.set_id(1) repr: str = "Entity: Automobilie<id:1, plate:ABC-1234>" self.assertEquals(self.auto_one.__str__(), repr)
{"/automobilies/tests/tests_models.py": ["/automobilies/models.py"], "/parking/tests/tests_entities.py": ["/automobilies/entities.py", "/parking/entities.py"], "/parking/validators.py": ["/parking/helpers.py"], "/parking/tests/tests_factories.py": ["/parking/factories.py"], "/parking/tests/tests_helpers.py": ["/parking/helpers.py"], "/automobilies/repositories.py": ["/automobilies/entities.py", "/automobilies/models.py"], "/parking/repository.py": ["/automobilies/repositories.py", "/parking/helpers.py", "/parking/entities.py", "/parking/models.py"], "/parking/urls.py": ["/parking/views.py"], "/parking/tests/tests_models.py": ["/parking/models.py", "/automobilies/models.py"], "/automobilies/tests/tests_repo.py": ["/automobilies/models.py", "/automobilies/entities.py", "/automobilies/repositories.py"], "/parking/tests/tests_interators.py": ["/parking/iterators.py", "/parking/serializers.py", "/parking/validators.py", "/parking/repository.py"], "/parking/tests/tests_validators.py": ["/parking/validators.py"], "/parking/views.py": ["/parking/factories.py"], "/parking/entities.py": ["/automobilies/models.py"], "/parking/models.py": ["/automobilies/models.py"], "/automobilies/tests/tests_entities.py": ["/automobilies/entities.py"], "/parking/tests/tests_serializers.py": ["/parking/entities.py", "/parking/models.py", "/parking/serializers.py", "/automobilies/models.py"], "/parking/factories.py": ["/parking/repository.py", "/parking/iterators.py", "/parking/validators.py", "/parking/serializers.py"], "/parking/tests/tests_repo.py": ["/parking/models.py", "/automobilies/models.py", "/parking/entities.py", "/parking/repository.py"]}
4,904
johnatasr/CoolPark
refs/heads/master
/parking/tests/tests_serializers.py
from parking.entities import ParkingOcurrency from parking.models import ParkingOcurrency as ParkingOcurrencyModel from parking.serializers import DefaultSerializer, HistoricSerializer from automobilies.models import Automobilie from django.test import TestCase class DefaultSerializerTestCase(TestCase): """ Tests of DefaultSerializer in parking.serializer.py """ def setUp(self): self.po = ParkingOcurrency(paid=False, left=False, auto=Automobilie("CBA-4321")) self.po.set_id(1) self.serializer = DefaultSerializer def test_init(self): serializer = self.serializer(parking=self.po, msg="Init test") self.assertIsInstance(serializer.parking, object) self.assertIsInstance(serializer.msg, str) def test_mount_payload(self): serializer = self.serializer(parking=self.po, msg="Mount test") dict_message = serializer.mount_payload() self.assertIsInstance(dict_message, dict) self.assertEquals(dict_message["id"], 1) self.assertEquals(dict_message["msg"], "Mount test") def test_create_message(self): serializer = self.serializer(parking=self.po, msg="Create message test") message = serializer.create_message() self.assertIsInstance(message, dict) class HistoricSerializerTestCase(TestCase): """ Tests of HistoricSerializerTestCase in parking.serializer.py """ def setUp(self): self.serializer = HistoricSerializer auto = Automobilie.objects.create(plate="CBA-1234") auto.save() for i in range(1, 4): park = ParkingOcurrencyModel.objects.create( paid=True, left=True, time=f"3{i} minutes", auto=auto ) park.save() def test_init(self): results = ParkingOcurrencyModel.objects.filter(auto__plate="CBA-1234") serializer = self.serializer(historic=results) self.assertIsInstance(serializer.historic, object) self.assertEquals(serializer.historic.count(), 3) def test_mount_payload(self): results = ParkingOcurrencyModel.objects.filter(auto__plate="CBA-1234").values( "id", "time", "paid", "left" ) serializer = self.serializer(historic=results) list_historic = serializer.mount_payload() self.assertIsInstance(list_historic, list) self.assertEquals(list_historic[0]["time"], "31 minutes") self.assertEquals(list_historic[1]["time"], "32 minutes") def test_create_message(self): results = ParkingOcurrencyModel.objects.filter(auto__plate="CBA-1234").values( "id", "time", "paid", "left" ) serializer = self.serializer(historic=results) list_historic = serializer.mount_payload() self.assertIsInstance(list_historic, list)
{"/automobilies/tests/tests_models.py": ["/automobilies/models.py"], "/parking/tests/tests_entities.py": ["/automobilies/entities.py", "/parking/entities.py"], "/parking/validators.py": ["/parking/helpers.py"], "/parking/tests/tests_factories.py": ["/parking/factories.py"], "/parking/tests/tests_helpers.py": ["/parking/helpers.py"], "/automobilies/repositories.py": ["/automobilies/entities.py", "/automobilies/models.py"], "/parking/repository.py": ["/automobilies/repositories.py", "/parking/helpers.py", "/parking/entities.py", "/parking/models.py"], "/parking/urls.py": ["/parking/views.py"], "/parking/tests/tests_models.py": ["/parking/models.py", "/automobilies/models.py"], "/automobilies/tests/tests_repo.py": ["/automobilies/models.py", "/automobilies/entities.py", "/automobilies/repositories.py"], "/parking/tests/tests_interators.py": ["/parking/iterators.py", "/parking/serializers.py", "/parking/validators.py", "/parking/repository.py"], "/parking/tests/tests_validators.py": ["/parking/validators.py"], "/parking/views.py": ["/parking/factories.py"], "/parking/entities.py": ["/automobilies/models.py"], "/parking/models.py": ["/automobilies/models.py"], "/automobilies/tests/tests_entities.py": ["/automobilies/entities.py"], "/parking/tests/tests_serializers.py": ["/parking/entities.py", "/parking/models.py", "/parking/serializers.py", "/automobilies/models.py"], "/parking/factories.py": ["/parking/repository.py", "/parking/iterators.py", "/parking/validators.py", "/parking/serializers.py"], "/parking/tests/tests_repo.py": ["/parking/models.py", "/automobilies/models.py", "/parking/entities.py", "/parking/repository.py"]}
4,905
johnatasr/CoolPark
refs/heads/master
/parking/factories.py
from .repository import ParkRepo from .iterators import ( CheckInIterator, CheckOutIterator, DoPaymentIterator, HistoricIterator, ) from .validators import ParkValidator from .serializers import DefaultSerializer, HistoricSerializer from typing import Any class ParkFactory: @staticmethod def create_check_in_interator(data: dict): return ( CheckInIterator( validator=ParkValidator, repo=ParkRepo, serializer=DefaultSerializer ) .set_params(park_payload=data) .execute() ) @staticmethod def create_check_out_interator(id: Any): return ( CheckOutIterator(repo=ParkRepo, serializer=DefaultSerializer) .set_params(parking_id=id) .execute() ) @staticmethod def create_do_payment_interator(id: Any): return ( DoPaymentIterator(repo=ParkRepo, serializer=DefaultSerializer) .set_params(parking_id=id) .execute() ) @staticmethod def create_historic_interator(plate: str): return ( HistoricIterator( validator=ParkValidator, repo=ParkRepo, serializer=HistoricSerializer ) .set_params(plate=plate) .execute() )
{"/automobilies/tests/tests_models.py": ["/automobilies/models.py"], "/parking/tests/tests_entities.py": ["/automobilies/entities.py", "/parking/entities.py"], "/parking/validators.py": ["/parking/helpers.py"], "/parking/tests/tests_factories.py": ["/parking/factories.py"], "/parking/tests/tests_helpers.py": ["/parking/helpers.py"], "/automobilies/repositories.py": ["/automobilies/entities.py", "/automobilies/models.py"], "/parking/repository.py": ["/automobilies/repositories.py", "/parking/helpers.py", "/parking/entities.py", "/parking/models.py"], "/parking/urls.py": ["/parking/views.py"], "/parking/tests/tests_models.py": ["/parking/models.py", "/automobilies/models.py"], "/automobilies/tests/tests_repo.py": ["/automobilies/models.py", "/automobilies/entities.py", "/automobilies/repositories.py"], "/parking/tests/tests_interators.py": ["/parking/iterators.py", "/parking/serializers.py", "/parking/validators.py", "/parking/repository.py"], "/parking/tests/tests_validators.py": ["/parking/validators.py"], "/parking/views.py": ["/parking/factories.py"], "/parking/entities.py": ["/automobilies/models.py"], "/parking/models.py": ["/automobilies/models.py"], "/automobilies/tests/tests_entities.py": ["/automobilies/entities.py"], "/parking/tests/tests_serializers.py": ["/parking/entities.py", "/parking/models.py", "/parking/serializers.py", "/automobilies/models.py"], "/parking/factories.py": ["/parking/repository.py", "/parking/iterators.py", "/parking/validators.py", "/parking/serializers.py"], "/parking/tests/tests_repo.py": ["/parking/models.py", "/automobilies/models.py", "/parking/entities.py", "/parking/repository.py"]}
4,906
johnatasr/CoolPark
refs/heads/master
/parking/tests/tests_repo.py
from parking.models import ParkingOcurrency as ParkingOcurrencyModel from automobilies.models import Automobilie from parking.entities import ParkingOcurrency from parking.repository import ParkRepo from django.test import TestCase class ParkingRepoTestCase(TestCase): """ Tests of ParkRepo in parking.repository.py """ def setUp(self): self.auto = Automobilie.objects.create(plate="ABC-1234") self.auto.save() self.po_model = ParkingOcurrencyModel.objects.create( paid=False, left=False, auto=self.auto ) self.po_model.save() self.po = ParkingOcurrency(paid=False, left=False, auto=self.auto) self.repo = ParkRepo() def test_get_or_create_park_model(self): park: object = self.repo.get_or_create_parking_base_model() self.assertIsInstance(park, object) def test_create_parking_ocurrency_model(self): po = {"paid": True, "left": False, "auto": Automobilie(plate="ABC-1234")} po_entity = self.repo.create_parking_ocurrency_entity(parking_ocurrency=po) self.assertIsInstance(po_entity, object) self.assertEquals(po_entity.paid, po["paid"]) self.assertEquals(po_entity.left, po["left"]) self.assertEquals(po_entity.auto_plate, po["auto"].plate) def test_create_parking_ocurrency_by_plate(self): po_entity = self.repo.create_parking_ocurrency_by_plate("ABC-1234") self.assertIsInstance(po_entity, object) self.assertEquals(po_entity.paid, False) self.assertEquals(po_entity.left, False) self.assertEquals(po_entity.auto_plate, "ABC-1234") def test_get_parking_ocurrency_by_id(self): po_searched = self.repo.get_parking_ocurrency_by_id(1) self.assertIsInstance(po_searched, object) def test_get_historic_by_plate(self): self.repo.create_parking_ocurrency_by_plate("CBA-4444") self.repo.create_parking_ocurrency_by_plate("CBA-4444") historic = self.repo.get_historic_by_plate("CBA-4444") self.assertEquals(historic.count(), 2) self.assertEquals(historic[0]["paid"], False) self.assertEquals(historic[1]["paid"], False) def test_update_parking_ocurrency_checkout(self): po_model = ParkingOcurrencyModel.objects.create( paid=True, left=False, auto=self.auto ) po_entity = self.repo.update_parking_ocurrency_checkout(parking=po_model) self.assertIsInstance(po_entity, object) self.assertEquals(po_entity.paid, True) self.assertEquals(po_entity.left, True) self.assertEquals(po_entity.auto_plate, "ABC-1234") def test_update_parking_ocurrency_pay(self): po_model = ParkingOcurrencyModel.objects.create( paid=False, left=False, auto=self.auto ) po_entity = self.repo.update_parking_ocurrency_pay(parking=po_model) self.assertIsInstance(po_entity, object) self.assertEquals(po_entity.paid, True) self.assertEquals(po_entity.left, False) self.assertEquals(po_entity.auto_plate, "ABC-1234")
{"/automobilies/tests/tests_models.py": ["/automobilies/models.py"], "/parking/tests/tests_entities.py": ["/automobilies/entities.py", "/parking/entities.py"], "/parking/validators.py": ["/parking/helpers.py"], "/parking/tests/tests_factories.py": ["/parking/factories.py"], "/parking/tests/tests_helpers.py": ["/parking/helpers.py"], "/automobilies/repositories.py": ["/automobilies/entities.py", "/automobilies/models.py"], "/parking/repository.py": ["/automobilies/repositories.py", "/parking/helpers.py", "/parking/entities.py", "/parking/models.py"], "/parking/urls.py": ["/parking/views.py"], "/parking/tests/tests_models.py": ["/parking/models.py", "/automobilies/models.py"], "/automobilies/tests/tests_repo.py": ["/automobilies/models.py", "/automobilies/entities.py", "/automobilies/repositories.py"], "/parking/tests/tests_interators.py": ["/parking/iterators.py", "/parking/serializers.py", "/parking/validators.py", "/parking/repository.py"], "/parking/tests/tests_validators.py": ["/parking/validators.py"], "/parking/views.py": ["/parking/factories.py"], "/parking/entities.py": ["/automobilies/models.py"], "/parking/models.py": ["/automobilies/models.py"], "/automobilies/tests/tests_entities.py": ["/automobilies/entities.py"], "/parking/tests/tests_serializers.py": ["/parking/entities.py", "/parking/models.py", "/parking/serializers.py", "/automobilies/models.py"], "/parking/factories.py": ["/parking/repository.py", "/parking/iterators.py", "/parking/validators.py", "/parking/serializers.py"], "/parking/tests/tests_repo.py": ["/parking/models.py", "/automobilies/models.py", "/parking/entities.py", "/parking/repository.py"]}
4,907
JackLorentz/Genetic-K-means-with-Spark
refs/heads/master
/Main.py
from Kmeans import Kmeans from Genetic_Kmeans import Genetic_Kmeans, Chromosome import sys import random import numpy as np import pandas as pd import matplotlib.pyplot as plt import matplotlib.colors as colors from sklearn import datasets from sklearn.decomposition import PCA from sklearn.preprocessing import StandardScaler from sklearn.metrics import davies_bouldin_score, fowlkes_mallows_score, jaccard_similarity_score, silhouette_score, adjusted_rand_score random.seed(0) ALGO = 0 def load_abalone(): df = pd.read_csv('data/abalone.csv') data = np.zeros([4177, 8]) data[:, 0] = df['sex'].values data[:, 1] = df['length'].values data[:, 2] = df['diameter'].values data[:, 3] = df['height'].values data[:, 4] = df['whole_weight'].values data[:, 5] = df['shucked_weight'].values data[:, 6] = df['viscera_weight'].values data[:, 7] = df['shell_weight'].values labels = df['label'].values for i in range(len(labels)): if labels[i] == 28: labels[i] -= 1 return data, labels def purity_score(y_true, y_pred): # compute contingency matrix (also called confusion matrix) contingency_matrix = metrics.cluster.contingency_matrix(y_true, y_pred) # return purity return np.sum(np.amax(contingency_matrix, axis=0)) / np.sum(contingency_matrix) def show_performance_indices(data, labels, predicts, sse, spend_time, name): output = "Final SSE: " + str(sse) output += "\nSpend Time: " + spend_time output += "\n[External Index]" output += "\nAdjusted Rand Index: " + str(adjusted_rand_score(labels, predicts)) output += "\nJaccard Index: " + str(jaccard_similarity_score(labels, predicts)) output += "\nFowlkes Mallows Index: " + str(fowlkes_mallows_score(labels, predicts)) output += "\n[External Index]" output += "\nSilhouette Index: " + str(silhouette_score(data, predicts)) output += "\nDavies Bouldin Index:" + str(davies_bouldin_score(data, predicts)) print(output) file = open("reports/" + name + "_performance_report.txt", "w") file.write(output) file.close() def main(argv): if len(argv) < 4: print('Please select your clustering algorithm (ka / gka) , dataset (iris / abalone) , and iteration !') quit() #選擇演算法 if argv[1] == "KA" or argv[1] == "ka": ALGO = 0 elif argv[1] == "GKA" or argv[1] == "gka": ALGO = 1 else: print("You can't select this algorithm .") quit() #設定散布圖顏色 color = ['r', 'g', 'b'] palette = [] for i,c in enumerate(colors.cnames): palette.append(c) color_index = random.sample(range(100), 100) for i in range(len(color_index)): if palette[color_index[i]] != 'red' and palette[color_index[i]] != 'green' and palette[color_index[i]] != 'blue': color.append(palette[color_index[i]]) iterations = int(argv[3]) #選擇分群數 if ALGO == 0: KA = Kmeans() if argv[2] == 'iris': iris = datasets.load_iris() data = iris['data'] labels = iris['target'] num_cluster = 3 cen, predicts, cen_his, sse, c_init, spend_time = KA.fit(X_train=data, num_of_centers=num_cluster, nIter=iterations) label_centers = np.zeros([3, data.shape[1]]) #更新每一群重心 for c in range(num_cluster): temp = np.zeros([1, data.shape[1]]) count = 0 for r in range(data.shape[0]): temp += int(labels[r] == c)*data[r] count += int(labels[r] == c) label_centers[c] = temp.reshape(-1,) / count pca = PCA(n_components=2, random_state=1) pca.fit(data) new_data = pca.transform(data) final_center = pca.transform(cen) new_label_centers = pca.transform(label_centers) target_color = ['a' for i in range(len(labels))] predict_color = ['a' for i in range(len(labels))] for c in range(num_cluster): for r in range(len(labels)): if labels[r] == c: target_color[r] = color[c] if predicts[r] == c: predict_color[r] = color[c] print("[Predict]") #畫預測分群 print(predicts) show_performance_indices(data, labels, predicts, sse[len(sse)-1], spend_time, "ka_iris") #畫SSE plt.plot(range(iterations), sse) plt.ylabel('Sum of Square Error') plt.xlabel('Iterations') #畫散布圖 plt.figure(figsize=(21,7)) #121: 共有1列2行, 這個圖表在第一個位置 plt.subplot(121) plt.scatter(new_data[:,0], new_data[:,1], c=target_color) yellow = plt.scatter(new_label_centers[:,0], new_label_centers[:,1], s=75, c='black', label='label cen') black = plt.scatter(final_center[:,0], final_center[:,1], s=100, c='orange', label='predict cen') plt.legend(handles=[yellow, black]) plt.title('Actual labels and final centroids') plt.subplot(122) plt.scatter(new_data[:,0], new_data[:,1], c=predict_color) plt.scatter(new_label_centers[:,0], new_label_centers[:,1], s=75, c='black', label='label cen') plt.scatter(final_center[:,0], final_center[:,1], s=100, c='orange', label='predict cen') plt.legend(handles=[yellow, black]) plt.title('Clustered labels and final centroids') plt.show() elif argv[2] == 'abalone': data, labels = load_abalone() num_cluster = 28 cen, predicts, cen_his, sse, c_init, spend_time = KA.fit(X_train=data, num_of_centers=num_cluster, nIter=iterations) label_centers = np.zeros([28, data.shape[1]]) #更新每一群重心 for c in range(num_cluster): temp = np.zeros([1, data.shape[1]]) count = 0 for r in range(data.shape[0]): temp += int(labels[r] == c)*data[r] count += int(labels[r] == c) label_centers[c] = temp.reshape(-1,) / count pca = PCA(n_components=2, random_state=1) pca.fit(data) new_data = pca.transform(data) final_center = pca.transform(cen) new_label_centers = pca.transform(label_centers) target_color = ['a' for i in range(len(labels))] predict_color = ['a' for i in range(len(labels))] for c in range(num_cluster): for r in range(len(labels)): if labels[r] == c: target_color[r] = color[c] if predicts[r] == c: predict_color[r] = color[c] print("[Predict]") #畫預測分群 print(predicts) show_performance_indices(data, labels, predicts, sse[len(sse)-1], spend_time, "ka_abalone") #畫SSE plt.plot(range(iterations), sse) plt.ylabel('Sum of Square Error') plt.xlabel('Iterations') #畫散布圖 plt.figure(figsize=(21,7)) #121: 共有1列2行, 這個圖表在第一個位置 plt.subplot(121) plt.scatter(new_data[:,0], new_data[:,1], color = target_color) yellow = plt.scatter(new_label_centers[:,0], new_label_centers[:,1], s=75, color='black', label='label cen') black = plt.scatter(final_center[:,0], final_center[:,1], s=100, color='orange', label='predict cen') plt.legend(handles=[yellow, black]) plt.title('Actual labels and final centroids') plt.subplot(122) plt.scatter(new_data[:,0], new_data[:,1], color = predict_color) plt.scatter(new_label_centers[:,0], new_label_centers[:,1], s=75, color='black', label='label cen') plt.scatter(final_center[:,0], final_center[:,1], s=100, color='orange', label='predict cen') plt.legend(handles=[yellow, black]) plt.title('Clustered labels and final centroids') plt.show() elif ALGO == 1: if argv[2] == 'iris': iris = datasets.load_iris() data = iris['data'] labels = iris['target'] num_cluster = 3 GKA = Genetic_Kmeans(num_cluster=num_cluster, MAX_GEN=iterations) chromosome, fitness_his, sse_his, spend_time = GKA.fit(data, labels) label_centers = np.zeros([3, data.shape[1]]) #更新每一群重心 for c in range(num_cluster): temp = np.zeros([1, data.shape[1]]) count = 0 for r in range(data.shape[0]): temp += int(labels[r] == c)*data[r] count += int(labels[r] == c) label_centers[c] = temp.reshape(-1,) / count pca = PCA(n_components=2, random_state=1) pca.fit(data) new_data = pca.transform(data) final_center = pca.transform(chromosome.center) new_label_centers = pca.transform(label_centers) target_color = ['a' for i in range(len(labels))] predict_color = ['a' for i in range(len(labels))] for c in range(num_cluster): for r in range(len(labels)): if labels[r] == c: target_color[r] = color[c] if chromosome.sol[r] == c: predict_color[r] = color[c] print("[Predict]") #畫預測分群 print(chromosome.sol) show_performance_indices(data, labels, chromosome.sol, sse_his[len(sse_his)-1], spend_time, "gka_iris") plt.figure(figsize=(21, 7)) #畫SSE plt.subplot(121) plt.plot(range(iterations), sse_his) plt.ylabel('Sum of Square Error') plt.xlabel('Generation') #畫適應值 plt.subplot(122) plt.plot(range(iterations), fitness_his) plt.ylabel('Fitness value') plt.xlabel('Generation') #畫散布圖 plt.figure(figsize=(21, 7)) #121: 共有1列2行, 這個圖表在第一個位置 plt.subplot(121) plt.scatter(new_data[:,0], new_data[:,1], c=target_color) yellow = plt.scatter(new_label_centers[:,0], new_label_centers[:,1], s=75, c='black', label='label cen') black = plt.scatter(final_center[:,0], final_center[:,1], s=100, c='orange', label='predict cen') plt.legend(handles=[yellow, black]) plt.title('Actual labels and final centroids') plt.subplot(122) plt.scatter(new_data[:,0], new_data[:,1], c=predict_color) plt.scatter(new_label_centers[:,0], new_label_centers[:,1], s=75, c='black', label='label cen') plt.scatter(final_center[:,0], final_center[:,1], s=100, c='orange', label='predict cen') plt.legend(handles=[yellow, black]) plt.title('Clustered labels and final centroids') plt.show() elif argv[2] == 'abalone': data, labels = load_abalone() num_cluster = 28 GKA = Genetic_Kmeans(num_cluster=num_cluster, MAX_GEN=iterations) chromosome, fitness_his, sse_his, spend_time = GKA.fit(data, labels) label_centers = np.zeros([28, data.shape[1]]) #更新每一群重心 for c in range(num_cluster): temp = np.zeros([1, data.shape[1]]) count = 0 for r in range(data.shape[0]): temp += int(labels[r] == c)*data[r] count += int(labels[r] == c) label_centers[c] = temp.reshape(-1,) / count pca = PCA(n_components=2, random_state=1) pca.fit(data) new_data = pca.transform(data) final_center = pca.transform(chromosome.center) new_label_centers = pca.transform(label_centers) target_color = ['a' for i in range(len(labels))] predict_color = ['a' for i in range(len(labels))] for c in range(num_cluster): for r in range(len(labels)): if labels[r] == c: target_color[r] = color[c] if chromosome.sol[r] == c: predict_color[r] = color[c] print("[Predict]") #畫預測分群 print(chromosome.sol) show_performance_indices(data, labels, chromosome.sol, sse_his[len(sse_his)-1], spend_time, "gka_abalone") #畫SSE plt.plot(range(iterations), sse_his) plt.ylabel('Sum of Square Error') plt.xlabel('Generation') #畫適應值 plt.plot(range(iterations), fitness_his) plt.ylabel('Fitness value') plt.xlabel('Generation') #畫散布圖 plt.figure(figsize=(21,7)) #121: 共有1列2行, 這個圖表在第一個位置 plt.subplot(121) plt.scatter(new_data[:,0], new_data[:,1], color = target_color) yellow = plt.scatter(new_label_centers[:,0], new_label_centers[:,1], s=75, color='black', label='label cen') black = plt.scatter(final_center[:,0], final_center[:,1], s=100, color='orange', label='predict cen') plt.legend(handles=[yellow, black]) plt.title('Actual labels and final centroids') plt.subplot(122) plt.scatter(new_data[:,0], new_data[:,1], color = predict_color) plt.scatter(new_label_centers[:,0], new_label_centers[:,1], s=75, color='black', label='label cen') plt.scatter(final_center[:,0], final_center[:,1], s=100, color='orange', label='predict cen') plt.legend(handles=[yellow, black]) plt.title('Clustered labels and final centroids') plt.show() else: quit() if __name__ == '__main__': main(sys.argv)
{"/Main.py": ["/Kmeans.py", "/Genetic_Kmeans.py"]}
4,908
JackLorentz/Genetic-K-means-with-Spark
refs/heads/master
/GKA_spark_testing.py
#import findspark #findspark.init() import sys import pyspark from pyspark import SparkContext, SparkConf #from pyspark.sql import SparkSession conf = SparkConf().setAppName("GKA_test").setMaster("local[*]") sc = SparkContext(conf=conf) import pandas as pd import numpy as np import random import math import time import matplotlib.colors as colors from sklearn import datasets from sklearn.preprocessing import normalize from sklearn.metrics import davies_bouldin_score from sklearn.metrics.cluster import adjusted_rand_score, silhouette_score iris = datasets.load_iris() data = iris['data'] labels = iris['target'] m = data.shape[0] dim = data.shape[1] population_size = 10 num_cluster = 3 MAX_GEN = 10 random.seed(0) def load_abalone(): df = pd.read_csv('./abalone.csv') data = np.zeros([4177, 8]) data[:, 0] = df['sex'].values data[:, 1] = df['length'].values data[:, 2] = df['diameter'].values data[:, 3] = df['height'].values data[:, 4] = df['whole_weight'].values data[:, 5] = df['shucked_weight'].values data[:, 6] = df['viscera_weight'].values data[:, 7] = df['shell_weight'].values labels = df['label'].values for i in range(len(labels)): if labels[i] == 28: labels[i] -= 1 return data, labels class Chromosome(): def __init__(self, data, num_cluster): #初始化參數 self.kmax = num_cluster self.data_num = data.shape[0] self.dim = data.shape[1] self.center = self.init_center(data) self.sol = None #隨機選num_cluster個中心點 def init_center(self, data): center = [] selected = random.sample(range(self.data_num), self.kmax) for i in range(self.kmax): center.append(data[selected[i]]) return center #對於每一個染色體,隨機產生一組解 => 每一個等位基因代表對應的群 => shape=(150, 1) def cal_solution(self, rdd): self.sol = np.array(rdd.map(lambda p: self.closestPoint(p, self.center)).take(self.data_num)) def distance(self, a, b): return np.sum((a-b)*(a-b)) #這個函數的目的就是求取該點應該分到哪個中心點的集合去,返回的是序號 def closestPoint(self, p, centers): bestIndex = 0 closest = float("+inf") for i in range(len(centers)): tempDist = np.sum((p - centers[i]) ** 2) if tempDist < closest: closest = tempDist bestIndex = i return bestIndex def cal_fitness(self, data): return silhouette_score(data, self.sol) def cal_SSE(self, data): sse = 0.0 for i in range(len(self.sol)): square_error = self.distance(data[i], self.center[self.sol[i]]) sse += square_error return sse def KMO(self, rdd): #計算每一筆資料跟行星的距離 #對所有資料執行map過程,最終生成的是(index, (point, 1))的rdd closest = rdd.map(lambda p: (self.closestPoint(p, self.center), (p, 1))) sol_tmp = closest.take(self.data_num) #執行reduce過程,該過程的目的是重新求取中心點,生成的也是rdd pointStats = closest.reduceByKey(lambda p1_c1, p2_c2: (p1_c1[0] + p2_c2[0], p1_c1[1] + p2_c2[1])) #生成新的中心點 newPoints = pointStats.map(lambda st: (st[0], st[1][0] / st[1][1])).collect() #設置新的中心點 for (iK, p) in newPoints: self.center[iK] = p #更新分群解 for i in range(len(sol_tmp)): self.sol[i] = sol_tmp[i][0] #更新SSE #self.SSE = self.cal_SSE() #適者生存 def selection(chromosomes, Ps, data): size = len(chromosomes) new_populations = [] #計算個染色體的適應值,並統計存活率 for i in range(size): chromosomes[i].fitness = chromosomes[i].cal_fitness(data) #存活率 print('survival rate:', Ps*100, '%') print('Before Selection:') chromosomes = sorted(chromosomes, reverse=True, key=lambda elem: elem.fitness) for i in range(len(chromosomes)): print('chromosome', i, "'s fitness value", chromosomes[i].fitness) #找出(存活率*個體數)個適應值的染色體 #適應值越大越容易存活 for i in range(int(population_size*Ps)): new_populations.append(chromosomes[i]) #填滿染色體數 while len(new_populations) < size: idx = random.randint(0, 4) new_populations.append(chromosomes[idx]) print('After Selection:') new_populations = sorted(new_populations, reverse=True, key=lambda elem: elem.fitness) for i in range(len(new_populations)): print('chromosome', i, "'s fitness value", new_populations[i].fitness) return new_populations #交配 def crossover(data, chromosomes, Pc): numOfInd = len(chromosomes) #根據交配得到數量並隨機選出染色體 index = random.sample(range(0, numOfInd - 1), int(Pc * numOfInd)) new_chromosomes = [] for i in range(len(index)): # do how many time new_chromosomes = doCrossover(data, chromosomes, i, index) return new_chromosomes def doCrossover(data, chromosomes, i, index): length = chromosomes[0].sol.shape[0] cut = random.randint(1, length - 2) #依取樣順序跟隔壁交換基因(每一筆資料的分群) => sol為基因 parent1 = chromosomes[index[i]] parent2 = chromosomes[index[(i + 1) % len(index)] % length] child1 = Chromosome(data, num_cluster) child2 = Chromosome(data, num_cluster) p1 = list(parent1.sol) p2 = list(parent2.sol) c1 = p1[0:cut] + p2[cut:length] c2 = p1[cut:length] + p2[0:cut] child1.sol = np.array(c1) child2.sol = np.array(c2) # 計算child適應值 child1.fitness = child1.cal_fitness(data) child2.fitness = child2.cal_fitness(data) #父子兩代在競爭一次,留下適應值大的 listA = [] listA.append(parent1) listA.append(parent2) listA.append(child1) listA.append(child2) #依適應值反向排序 listA = sorted(listA, reverse=True, key=lambda elem: elem.fitness) #留下最大的兩個 chromosomes[index[i]] = listA[0] chromosomes[index[(i + 1) % len(index)] % length] = listA[1] return sorted(chromosomes, reverse=True, key=lambda elem: elem.fitness) if __name__ == '__main__': if len(sys.argv) != 4: print("Usage: kmeans <iris/abalone> <k> <iterations>", file=sys.stderr) sys.exit(-1) fitness_his = [] sse_his = [] ari_his = [] cen_his = [] population = [] if sys.argv[1] == 'abalone': data, labels = load_abalone() num_cluster = int(sys.argv[2]) MAX_GEN = int(sys.argv[3]) tic = time.perf_counter() rdd = sc.parallelize(data) rdd.cache() for i in range(population_size): population.append(Chromosome(data, num_cluster)) #population[i].center = rdd.takeSample(False, num_cluster, 1) population[i].cal_solution(rdd) print('<the', i+1, 'th chromosome has been initialized.>') #for each generation for i in range(MAX_GEN): print('[the', i+1, 'th generation]') population = selection(population, 0.8, data) population = crossover(data, population, 0.8) print('After Crossover:') for i in range(len(population)): print('chromosome', i, "'s fitness value", population[i].fitness) #for each chromosome for j in range(population_size): #population[j].mutation() population[j].KMO(rdd) print('the', j+1, "'s KMO has been finished.") #找出最大適應值的染色體 population = sorted(population, reverse=True, key=lambda elem: elem.fitness) print() print('Fitness value:', population[0].fitness) print('=======================================') toc = time.perf_counter() ari = adjusted_rand_score(labels, population[0].sol) spend_time = str(1000*(toc - tic)) print('=======================================') print('Adjusted Rand Index:', ari) print('Sum of Square Error:', population[0].cal_SSE(data)) print("Comuptation Time: " + spend_time + "ms") print('=======================================')
{"/Main.py": ["/Kmeans.py", "/Genetic_Kmeans.py"]}
4,909
JackLorentz/Genetic-K-means-with-Spark
refs/heads/master
/kmeans_spark_testing.py
from __future__ import print_function import sys import time import numpy as np from pyspark.sql import SparkSession from pyspark import SparkContext from pyspark import SparkConf def parseVector(line): return np.array([float(x) for x in line.split(',')]) def closestPoint(p, centers): bestIndex = 0 closest = float("+inf") for i in range(len(centers)): tempDist = np.sum((p - centers[i]) ** 2) if tempDist < closest: closest = tempDist bestIndex = i return bestIndex def dist(center_point,p): return np.sum(np.square(center_point[p[0]]-p[1][0])) if __name__ == "__main__": if len(sys.argv) != 4: print("Usage: kmeans <file> <k> <iteration>", file=sys.stderr) sys.exit(-1) temp=np.loadtxt(sys.argv[1],dtype=np.float,delimiter=",") spark = SparkSession\ .builder\ .appName("PythonKMeans")\ .getOrCreate() sc = SparkContext.getOrCreate(SparkConf().setMaster("local[*]")) #sys.argv[1]sys.argv[2] ''' lines = spark.read.text(sys.argv[1]).rdd.map(lambda r: r[0]) data = lines.map(parseVector).cache() ''' data=sc.parallelize(temp).persist() K =int(sys.argv[2])#28 iteration = int(sys.argv[3])#10 tic = time.perf_counter() kPoints = data.takeSample(False, K, 1) #tempDist = 1.0 for i in range(iteration): closest = data.map( lambda p: (closestPoint(p, kPoints), (p,1))) pointStats = closest.reduceByKey( lambda p1_c1, p2_c2: (p1_c1[0] + p2_c2[0], p1_c1[1] + p2_c2[1])) newPoints = pointStats.map( lambda st: (st[0], st[1][0] / st[1][1])).collect() #tempDist = sum(np.sum((kPoints[iK] - p) ** 2) for (iK, p) in newPoints) #dist(newPoints,closest) #sse=np.sum(newPoi) for (iK, p) in newPoints: kPoints[iK] = p toc = time.perf_counter() spend_time = str(1000*(toc - tic)) print("==================================================================================================================") print("Comuptation Time: " + spend_time + "ms") print("==================================================================================================================") temp=closest.collect() dists=[dist(kPoints,temp[i]) for i in range(len(temp))] sse=np.sum(dists) print("==================================================================================================================") print("sse:",sse) print("==================================================================================================================") print("Final centers: " + str(kPoints)) print("==================================================================================================================") spark.stop()
{"/Main.py": ["/Kmeans.py", "/Genetic_Kmeans.py"]}
4,910
JackLorentz/Genetic-K-means-with-Spark
refs/heads/master
/Genetic_Kmeans.py
import pandas as pd import numpy as np import random import math import time import matplotlib.colors as colors from sklearn import datasets from sklearn.preprocessing import normalize from sklearn.metrics import davies_bouldin_score from sklearn.metrics.cluster import adjusted_rand_score, silhouette_score random.seed(0) class Cluster(): def __init__(self, data): self.data self.dim = data.shape[1] self.centroid = np.zeros([1, self.dim]).reshape(-1,) self.data_points = [] def distance(self, a, b): return np.sum((a-b)*(a-b)) # this method finds the average distance of all elements in cluster to its centroid def computeS(self): points = np.array(self.data_points) num = points.shape[0] dis_sum = 0.0 #計算每一筆資料跟行星的距離 for i in range(num): dis_sum += math.sqrt(self.distance(self.data[i], self.centroid)) return dis_sum / num class Chromosome(): def __init__(self, data, num_cluster): #初始化參數 self.data = data self.kmax = num_cluster self.data_num = data.shape[0] self.dim = data.shape[1] self.center = self.init_center() self.sol = self.init_sol() #每次都會更新的參數 self.fitness = 0.0 self.mutation_rate = [0.0] * data.shape[0] self.sse = 0.0 #隨機選n個中心點 def init_center(self): center = np.empty([self.kmax, self.dim]) selected = random.sample(range(self.data_num), self.kmax) for i in range(self.kmax): center[i] = self.data[selected[i]] return center #對於每一個染色體,隨機產生一組解 => 每一個等位基因代表對應的群 => shape=(150, 1) def init_sol(self): dis = np.zeros([self.data_num, self.kmax]) #計算每一筆資料跟行星的距離 for r in range(self.data_num): for c in range(self.kmax): dis[r][c] = self.distance(self.data[r], self.center[c]) #分群 sol = (np.argmin(dis, axis=1)).reshape((-1,)) return sol def distance(self, a, b): return np.sum((a-b)*(a-b)) def cal_SSE(self): sse = 0.0 for i in range(len(self.sol)): square_error = self.distance(self.data[i], self.center[self.sol[i]]) sse += square_error return sse def cal_fitness_v2(self, max_fitness, c): return c*max_fitness - self.fitness def cal_fitness(self): ''' clusters = [Cluster()]*self.kmax for c in range(self.kmax): clusters[c] = Cluster(data) for c in range(self.kmax): clusters[c].centroid = self.center[c] for r in range(self.data_num): if self.sol[r] == c: clusters[c].data_points.append(self.data[r]) ''' #dbi = davies_bouldin_score(data, self.sol) silhouette = silhouette_score(self.data, self.sol) #ari = adjusted_rand_score(labels, self.sol) return silhouette def daviesBouldin(self, clusters): sigmaR = 0.0 nc = self.kmax for i in range(nc): sigmaR += self.computeR(clusters, i, clusters[i]) #print(sigmaR) DBIndex = float(sigmaR) / float(nc) #print('DBI:', DBIndex) return DBIndex def computeR(self, clusters, i, iCluster): listR = [] for j, jCluster in enumerate(clusters): if(i != j): temp = self.computeRij(iCluster, jCluster) listR.append(temp) #print(max(listR)) return max(listR) def computeRij(self, iCluster, jCluster): Rij = 0 d = math.sqrt(self.distance(iCluster.centroid, jCluster.centroid)) Rij = (iCluster.computeS() + jCluster.computeS()) / d return Rij def mutation(self): sol_distribution = sorted(self.sol) '''step 1 : choose the value to mutate''' for i in range(self.data_num): self.mutation_rate[i] = 0.02 #print('mutation rate:', self.mutation_rate[i]) sign = random.uniform(0.0, 1.0) if(sign < self.mutation_rate[i]): '''step 2 : do mutation on chosen point by wheel''' self.sol[i] = random.choice(sol_distribution) '''step 3 : update center node''' for c in range(self.kmax): temp = np.zeros([1, self.dim]) count = 0 for r in range(self.data_num): temp += int(self.sol[r] == c)*self.data[r] count += int(self.sol[r] == c) self.center[c] = temp.reshape(-1,) / count def KMO(self): dis = np.zeros([self.data_num, self.kmax]) #計算每一筆資料跟行星的距離 for r in range(self.data_num): for c in range(self.kmax): dis[r][c] = self.distance(self.data[r], self.center[c]) #分群 #self.sol = (np.argmin(dis, axis=1)).reshape((-1,)) sol_tmp = (np.argmin(dis, axis=1)).reshape((-1,)) silhouette = silhouette_score(self.data, sol_tmp) if silhouette > self.fitness: self.sol = sol_tmp self.fitness = silhouette #更新每一群重心 for c in range(self.kmax): temp = np.zeros([1, self.dim]) count = 0 for r in range(self.data_num): temp += int(self.sol[r] == c)*self.data[r] count += int(self.sol[r] == c) self.center[c] = temp.reshape(-1,) / count #更新SSE self.SSE = self.cal_SSE() class Genetic_Kmeans: def __init__(self, population_size=10, num_cluster=3, MAX_GEN=10, Ps=0.8, Pc=0.8): self.population_size = population_size self.num_cluster = num_cluster self.MAX_GEN = MAX_GEN self.Ps = Ps self.Pc = Pc def fit(self, data, labels): self.data = data self.labels = labels tic = time.perf_counter() fitness_his = [] sse_his = [] ari_his = [] cen_his = [] population = [] for i in range(self.population_size): population.append(Chromosome(data, self.num_cluster)) #for each generation for i in range(self.MAX_GEN): print('[the', i+1, 'th generation]') population = self.selection(population, self.Ps) population = self.crossover(population, self.Pc) print('After Crossover:') for i in range(len(population)): print('chromosome', i, "'s fitness value", population[i].fitness) #for each chromosome for j in range(self.population_size): #population[j].mutation() population[j].KMO() #找出最大適應值的染色體 population = sorted(population, reverse=True, key=lambda elem: elem.fitness) ari = adjusted_rand_score(labels, population[0].sol) print('Fitness value:', population[0].fitness) print('Sum of Square Error:', population[0].SSE) print('Adjusted Rand Index:', ari) print('=======================================') fitness_his.append(population[0].fitness) sse_his.append(population[0].SSE) ari_his.append(ari) cen_his.append(population[0].center) toc = time.perf_counter() spend_time = str(1000*(toc - tic)) print("Comuptation Time: " + spend_time + "ms") return population[0], fitness_his, sse_his, spend_time #適者生存 def selection(self, chromosomes, Ps): size = len(chromosomes) new_populations = [] #計算個染色體的適應值,並統計存活率 for i in range(size): chromosomes[i].fitness = chromosomes[i].cal_fitness() #存活率 chosen_rate = Ps print('survival rate:', chosen_rate*100, '%') print('Before Selection:') chromosomes = sorted(chromosomes, reverse=True, key=lambda elem: elem.fitness) for i in range(len(chromosomes)): print('chromosome', i, "'s fitness value", chromosomes[i].fitness) #找出(存活率*個體數)個適應值的染色體 #適應值越大越容易存活 for i in range(8): new_populations.append(chromosomes[i]) #填滿染色體數 while len(new_populations) < size: idx = random.randint(0, 4) new_populations.append(chromosomes[idx]) print('After Selection:') new_populations = sorted(new_populations, reverse=True, key=lambda elem: elem.fitness) for i in range(len(new_populations)): print('chromosome', i, "'s fitness value", new_populations[i].fitness) return new_populations #交配 def crossover(self, chromosomes, Pc): numOfInd = len(chromosomes) #根據交配得到數量並隨機選出染色體 index = random.sample(range(0, numOfInd - 1), int(Pc * numOfInd)) new_chromosomes = [] for i in range(len(index)): # do how many time new_chromosomes = self.doCrossover(chromosomes, i, index) return new_chromosomes def doCrossover(self, chromosomes, i, index): length = chromosomes[0].sol.shape[0] cut = random.randint(1, length - 2) #依取樣順序跟隔壁交換基因(每一筆資料的分群) => sol為基因 parent1 = chromosomes[index[i]] parent2 = chromosomes[index[(i + 1) % len(index)] % length] child1 = Chromosome(self.data, self.num_cluster) child2 = Chromosome(self.data, self.num_cluster) p1 = list(parent1.sol) p2 = list(parent2.sol) c1 = p1[0:cut] + p2[cut:length] c2 = p1[cut:length] + p2[0:cut] child1.sol = np.array(c1) child2.sol = np.array(c2) # 計算child適應值 child1.fitness = child1.cal_fitness() child2.fitness = child2.cal_fitness() #父子兩代在競爭一次,留下適應值大的 listA = [] listA.append(parent1) listA.append(parent2) listA.append(child1) listA.append(child2) #依適應值反向排序 listA = sorted(listA, reverse=True, key=lambda elem: elem.fitness) #留下最大的兩個 chromosomes[index[i]] = listA[0] chromosomes[index[(i + 1) % len(index)] % length] = listA[1] return sorted(chromosomes, reverse=True, key=lambda elem: elem.fitness)
{"/Main.py": ["/Kmeans.py", "/Genetic_Kmeans.py"]}
4,911
JackLorentz/Genetic-K-means-with-Spark
refs/heads/master
/Kmeans.py
import numpy as np # linear algebra import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) import time import random import copy from math import sqrt random.seed(0) class Kmeans: def cen_init(self, k, x): center = np.empty([k, x.shape[1]]) selected = random.sample(range(x.shape[0]), k) for i in range(len(selected)): center[i] = x[selected[i]] return center def distance(self, t, c): return sqrt(np.sum((t-c)*(t-c))),np.sum((t-c)*(t-c)) def fit(self, X_train=None, nIter=10, num_of_centers=3): tic = time.perf_counter() #Step1: 隨機初始化 #資料數 m = X_train.shape[0] c_init = self.cen_init(num_of_centers, X_train) #print(c_init) cen=copy.deepcopy(c_init) #cen=c_init dim=X_train.shape[1] #行星數 k = cen.shape[0] #每筆資料跟行星距離 dis = np.zeros([m,k]) cen_ass = np.zeros([m,]) sse_dis = np.zeros([m,k]) #行星位置歷史紀錄 cen_his = cen temp = np.zeros([k,dim]) count = 0 # sse=[] for t in range(nIter): #Step2: 計算每一筆資料跟行星的距離 for r in range(0,m): for c in range(0,k): dis[r][c],sse_dis[r][c] = self.distance(X_train[r],cen[c]) cen_ass = (np.argmin(dis, axis=1)).reshape((-1,)) #記錄每次迭代的行星位置 cen_his = np.concatenate((cen_his, cen)) sse.append(0) for i in range(m): sse[t]=sse[t]+sse_dis[i][cen_ass[i]] print('[the', t+1, 'th iteration] SSE:', sse[t]) #print() #print("center:",cen) temp = np.zeros([1,dim]) count = 0 for i in range(num_of_centers): temp = np.zeros([1,dim]) count = 0 for r in range(0,m): temp = temp + 1.0*(cen_ass[r]==i)*X_train[r]#+(0.02)*(cen_ass[r]!=c)*X_train[r] count = count + 1.0*(cen_ass[r]==i)#+(0.02)*(cen_ass[r]!=c) cen[i] = temp.reshape(-1,)/count toc = time.perf_counter() spend_time = str(1000*(toc - tic)) print("Comuptation Time: " + spend_time + "ms") return cen, cen_ass, cen_his, sse, c_init, spend_time
{"/Main.py": ["/Kmeans.py", "/Genetic_Kmeans.py"]}
4,912
Sreehariskj/djangoTodo
refs/heads/master
/core/urls.py
from django.urls import path from .views import home,update,delete urlpatterns=[ path('',home,name ='home'), path('update/<int:todo_id>/',update, name ='update'), path('delete/<int:todo_id>/',delete, name = 'delete'), ]
{"/core/urls.py": ["/core/views.py"], "/core/views.py": ["/core/forms.py"]}
4,913
Sreehariskj/djangoTodo
refs/heads/master
/core/views.py
from django.shortcuts import render,redirect from core.forms import TodoForm from core.models import Todo def home(request): form = TodoForm() todos = Todo.objects.all() if request.method == 'POST': form = TodoForm(request.POST) if form.is_valid(): form.save() return redirect('home') return render(request,'home.html',{'form':form,'todos':todos}) def update(request,todo_id): todo = Todo.objects.get(id = todo_id) form = TodoForm(instance = todo) if request.method == 'POST': form = TodoForm(request.POST, instance = todo) if form.is_valid(): form.save() return redirect('home') return render(request,'update.html',{'form':form}) def delete(request,todo_id): todo =Todo.objects.get(id = todo_id) todo.delete() return redirect('home')
{"/core/urls.py": ["/core/views.py"], "/core/views.py": ["/core/forms.py"]}
4,914
Sreehariskj/djangoTodo
refs/heads/master
/core/forms.py
from django import forms from core.models import Todo class TodoForm(forms.ModelForm): class Meta: model =Todo fields = '__all__' widgets = { 'title': forms.TextInput(attrs={'class': 'form-control'}), }
{"/core/urls.py": ["/core/views.py"], "/core/views.py": ["/core/forms.py"]}
4,936
konitaku/unit-converter
refs/heads/master
/converter.py
from decimal import Decimal, ROUND_HALF_UP def convert(num: float, init_unit: str, change_unit: str) -> int: result = 0 if init_unit == "m": cv_rate = { "m": 1, "mile": 1/1609, "yard": 1.09, "feet": 3.281, "inch": 39.370 } result = num * cv_rate[change_unit] result = Decimal(str(result)).quantize(Decimal('0.0001'), rounding=ROUND_HALF_UP) if init_unit == "mile": cv_rate = { "m": 1609, "mile": 1, "yard": 1760, "feet": 5280, "inch": 63360 } result = num * cv_rate[change_unit] result = Decimal(str(result)).quantize(Decimal('0.1'), rounding=ROUND_HALF_UP) if init_unit == "yard": cv_rate = { "m": 1/1.094, "mile": 1/1760, "yard": 1, "feet": 3, "inch": 36 } result = num * cv_rate[change_unit] result = Decimal(str(result)).quantize(Decimal('0.0000001'), rounding=ROUND_HALF_UP) if init_unit == "feet": cv_rate = { "m": 1/3.281, "mile": 1/5280, "yard": 1/3, "feet": 1, "inch": 12 } result = num * cv_rate[change_unit] result = Decimal(str(result)).quantize(Decimal('0.0000000001'), rounding=ROUND_HALF_UP) if init_unit == "inch": cv_rate = { "m": 1/39.37, "mile": 1/63360, "yard": 1/36, "feet": 1/12, "inch": 1 } result = num * cv_rate[change_unit] result = Decimal(str(result)).quantize(Decimal('0.0000000001'), rounding=ROUND_HALF_UP) return result
{"/server.py": ["/converter.py"]}
4,937
konitaku/unit-converter
refs/heads/master
/server.py
from flask import Flask, render_template from flask_wtf import FlaskForm from wtforms import StringField, SelectField from wtforms.validators import DataRequired from converter import convert import os app = Flask(__name__) app.config["SECRET_KEY"] = os.environ.get("SECRET_KEY") class ConvertForm(FlaskForm): number = StringField(validators=[DataRequired()], render_kw={"placeholder": "数字を入力"}) unit_select1 = SelectField( choices=[("m", "メートル"), ("mile", "マイル"), ("yard", "ヤード"), ("feet", "フィート"), ("inch", "インチ")], validators=[DataRequired()] ) unit_select2 = SelectField( choices=[("m", "メートル"), ("mile", "マイル"), ("yard", "ヤード"), ("feet", "フィート"), ("inch", "インチ")], validators=[DataRequired()] ) @app.route("/", methods=["POST", "GET"]) def home(): form = ConvertForm() result = 0 if form.validate_on_submit(): result = convert(float(form.number.data), form.unit_select1.data, form.unit_select2.data) form = ConvertForm( number=form.number.data, unit_select1=form.unit_select1.data, unit_select2=form.unit_select2.data ) return render_template("index.html", form=form, pagename="home", result=result) @app.route("/other") def other(): return render_template("other.html") if __name__ == "__main__": app.run(debug=True)
{"/server.py": ["/converter.py"]}
4,939
bioinfoUQAM/CASTOR_KRFE
refs/heads/master
/analyzer.py
########################################################################################## ### Resources ### ### https://biopython.org/docs/1.75/api/Bio.pairwise2.html ### ### https://biocheminsider.com/difference-between-local-and-global-sequence-alignment/ ### ########################################################################################## ############### ### Imports ### ############### import os import re import data import kmers import numpy import statistics import pandas as pd from Bio import SeqIO from Bio import motifs from Bio.Seq import Seq from Bio import Align from Bio import pairwise2 from Bio.Seq import transcribe from joblib import Parallel, delayed from Bio.pairwise2 import format_alignment ################################################################################################################################# ### Function to compute perfect local pairwise sequence alignment to identify the sequences that contain the original pattern ### ################################################################################################################################# def perfectLocalPairwiseSequenceAlignment(data, query): # Get the identifier sequence_id = data[0] # Get the current sequence sequence = data[1] # If the pattern is present in the sequence if sequence.count(query): # Get the position of the k-mer index = sequence.find(query) # Return the informations return {"id": sequence_id, "type": data[2], "pattern": query, "position": index} # If the pattern is not present in the sequence else: return {"id": sequence_id, "type": data[2], "pattern": None, "position": None} ######################################################################################### ### Function to compute local pairwise sequence alignment to identify mutated pattern ### ######################################################################################### def localPairwiseSequenceAlignmentMutatededMotif(records, data, query, position): # Iterate through sequence records for record in records: # Check the corresponding sequence if record["id"] == data[0]: # If the information are not complete if record["pattern"] == None: # Compute the margin margin = int(len(data[1]) * 10 / 100) # Correct margin if it is too large if margin > 1000 and len(data[1]) < 100000: margin = 1000 if margin > 1000 and len(data[1]) >= 100000: margin = 2500 # Get the position of interest start = position - margin end = position + margin # Correct position if out of range if start < 0: start = 0 if end > len(data[1]): end = len(data[1]) # Get the subsequence sequence = data[1][start:end] # Try to identify subsitution alignments = pairwise2.align.localms(sequence, query, 5, -2, -100, -0.1) # Get the length of the alignement alignment_length = len(alignments[0].seqA[alignments[0].start:alignments[0].end]) # Set the maximum number of substitutions that can occur maximum_subsitutions_number = 3 # Compute the threshold score threshold_score = (len(query) - maximum_subsitutions_number) * 5 - (maximum_subsitutions_number * 5) ################################## ### Perfect case subsititution ### ################################## if alignment_length == len(query) and alignments[0].score >= threshold_score: # Get the mutated k-mer pattern = alignments[0].seqA[alignments[0].start:alignments[0].end] # Get the position of the mutated k-mers position = data[1].find(pattern) # Return the informations return {"id": record["id"], "type": data[2], "pattern": pattern, "position":position} ########################### ### If one substitution ### ########################### elif (len(query) - alignment_length == 1 and alignments[0].score >= threshold_score - 5): # Get the index to localise where are the subsititution index = query.find(alignments[0].seqB[alignments[0].start:alignments[0].end]) start = alignments[0].start - index end = start + len(query) pattern = alignments[0].seqA[start:end] # Get the position of the mutated k-mers position = data[1].find(pattern) return {"id": record["id"], "type": data[2], "pattern": pattern, "position": position} ############################ ### If two substitutions ### ############################ elif (len(query) - alignment_length == 2 and alignments[0].score >= threshold_score - 10): # Get the index to localise where are the subsititution index = query.find(alignments[0].seqB[alignments[0].start:alignments[0].end]) start = alignments[0].start - index end = start + len(query) pattern = alignments[0].seqA[start:end] # Get the position of the mutated k-mers position = data[1].find(pattern) return {"id": record["id"], "type": data[2], "pattern": pattern, "position": position} ############################################################ ### If no solution, try to identify deletion / insertion ### ############################################################ else: # Try to identify deletion / insertion alignments = pairwise2.align.localms(sequence, query, 1, -2, -5, -0.1) # Perfect deletion/insertion if (alignments[0].end - alignments[0].start) == len(query) and alignments[0].score > (len(query)/2 -2): position = data[1].find(alignments[0].seqA.replace("-", "")) + alignments[0].start return {"id": record["id"], "type": data[2], "pattern": alignments[0].seqA[alignments[0].start:alignments[0].end], "position": position} # Deletion/Insertion at the begining/ending of the sequence elif (alignments[0].seqA[alignments[0].start:alignments[0].end] == alignments[0].seqB[alignments[0].start:alignments[0].end] and alignments[0].score > len(alignments[0].seqA[alignments[0].start:alignments[0].end]) - 1): index_subsequence = query.find(alignments[0].seqA[alignments[0].start:alignments[0].end]) n_start_gap = index_subsequence n_end_gap = len(query) - (n_start_gap + len(alignments[0].seqA[alignments[0].start:alignments[0].end])) subsequence = '-' * n_start_gap + alignments[0].seqA[alignments[0].start:alignments[0].end] + '-' * n_end_gap position = data[1].find(alignments[0].seqA.replace("-", "")) + alignments[0].start return {"id": record["id"], "type": data[2], "pattern": subsequence, "position": position} # If no result else: return {"id": record["id"], "type": data[2], "pattern": None, "position": None} # If the information are already complete else: return record ########################################################## ### Function to indentify mutation at amino acid level ### ########################################################## def getMutation(seqA, seqB): mutations = [] alignments = pairwise2.align.globalms(seqA, seqB.replace('*',''), 2, -1, -10, -10) # Silent mutation if seqA == seqB.replace('*',''): mutations.append("Silent mutation") # If mutattion else: #print(format_alignment(*alignments[0])) for i, aa in enumerate(range(0, len(alignments[0].seqA))): # Insertion if alignments[0].seqA[i] != alignments[0].seqB[i] and alignments[0].seqA[i] == "-": mutations.append("Insertion: " + str(i + 1) + " (" + alignments[0].seqB[i] + ")") # Deletion elif alignments[0].seqA[i] != alignments[0].seqB[i] and alignments[0].seqB[i] == "-": mutations.append("Deletion: " + str(i + 1)) # Substitution elif alignments[0].seqA[i] != alignments[0].seqB[i]: mutations.append("Substitution: " + alignments[0].seqA[i] + str(i + 1) + alignments[0].seqB[i]) else: pass # Return mutations return mutations ##################################################################################### ### Function to indentify perfect matches between initial signature and sequences ### ##################################################################################### def identifyPerfectMatch(parameters): # Display information print("\nIndentify perfect matches...") # Initialize the results list Results = {} # Get the discriminative motifs Kmers = kmers.loadKmers(str(parameters["k_mers_path"])) # Get the sequence dataset Data = data.loadData(str(parameters["training_fasta"])) # Add the reference sequence Data = data.loadReferenceSequence(Data, str(parameters["refence_sequence_genbank"])) # Iterate through the k-mers for kmer in Kmers: # Display the current motif print("Signature: " + kmer) # Get the current k-mer query = kmer # Check if there is perfect pairwise alignment of the current kmer with each sequence using parallelization informations = Parallel(n_jobs = -1)(delayed(perfectLocalPairwiseSequenceAlignment)(data, query) for data in Data) # Save the informations of each sequence according to the current kmer Results[kmer] = informations # Return the list of dictionary return Results ######################################################################################### ### Function to indentify variations with sequences not associated with perfect match ### ######################################################################################### def identifyVariations(Results, parameters): # Display information print("\nIndentify variations...") # Get the sequence dataset Data = data.loadData(str(parameters["training_fasta"])) # Add the reference sequence Data = data.loadReferenceSequence(Data, str(parameters["refence_sequence_genbank"])) # Iterate through the actual sequences records for key, records in Results.items(): print("Signature: " + key) # Get the current k-mer query = key # Compute the average position of the k-mers to prune the search for mutated k-mers positions = [] for record in records: if record["position"] != None: positions.append(record["position"]) average_position = int(statistics.mean(positions)) # Compute the pairwise alignment of the amplified motif with each sequence to identify mutated motifs using parallelization informations = Parallel(n_jobs = -1)(delayed(localPairwiseSequenceAlignmentMutatededMotif)(records, data, query, average_position) for data in Data) # Save the updated informations of each sequence according to the current kmer Results[key] = informations # Dictionary of mutated motif (s) and associated postion(s) return Results ########################################################## ### Function to indentify mutation at amino acid level ### ########################################################## def indentifyMutationInformation(record, reference_sequence_informations): # If same pattern as reference sequence if record["pattern"] == reference_sequence_informations["pattern"]: # Save the information associated to the reference pattern return [record["id"], reference_sequence_informations["organisme"], record["type"], reference_sequence_informations["pattern"], None, reference_sequence_informations["gene"], None, record["position"]] # If different pattern as reference sequence else: # If a pattern variation has been identified if record["pattern"] != None: # Get the position of the initial pattern start = reference_sequence_informations["position_gene_sequence"] end = reference_sequence_informations["position_gene_sequence"] + len(record["pattern"]) # Generate the mutated sequence mutated_squence = "" mutated_squence = mutated_squence + reference_sequence_informations["nucleotide_sequence"][0:start] mutated_squence = mutated_squence + record["pattern"].replace("-", "") mutated_squence = mutated_squence + reference_sequence_informations["nucleotide_sequence"][end:] rna_sequence = transcribe(mutated_squence) aa_sequence = str(rna_sequence.translate()) # Get the mutation mutations = getMutation(reference_sequence_informations["amino_acid_sequence"], aa_sequence) if len(mutations) <= 5: return[record["id"], reference_sequence_informations["organisme"],record["type"],reference_sequence_informations["pattern"], record["pattern"], reference_sequence_informations["gene"],mutations,record["position"]] else: return[record["id"], reference_sequence_informations["organisme"], record["type"], reference_sequence_informations["pattern"], "Not identified", "Not identified", "Not identified", "Not identified"] # If unidentified pattern else: return[record["id"], reference_sequence_informations["organisme"], record["type"], reference_sequence_informations["pattern"], "Not identified", "Not identified", "Not identified", "Not identified"] ############################################################## ### Function to indentify infornation related to variation ### ############################################################## def extractRelatedInformation (Results, parameters): # Display information print("\nExtract information related to signatures/variations...") # Get the reference fil path gb_reference_file = str(parameters["refence_sequence_genbank"]) # Check if genbank file exists file_exists = os.path.exists(gb_reference_file) # If there is genbank file if file_exists == True: # Open the reference sequence genbank file for gb_record in SeqIO.parse(open(gb_reference_file, "r"), "genbank"): # Iterate through the sequences records for each pattern for key, records in Results.items(): print("Signature: " + key) # Variable to check if cds was found isCDS = False # Iterate through the sequences records for record in records: # Find the reference sequence to get the informations if record["id"] == gb_record.annotations["accessions"][0]: # Initialize the dict of reference sequence abd save initial informations reference_sequence_informations = {} reference_sequence_informations["id"] = record["id"] reference_sequence_informations["pattern"] = record["pattern"] reference_sequence_informations["position"] = record["position"] reference_sequence_informations["mutated_pattern"] = None reference_sequence_informations["mutation"] = None # Iterate through the features of the reference sequence for feature in gb_record.features: # Get the organisme informations if feature.type == "source": try: reference_sequence_informations["organisme"] = feature.qualifiers["organism"][0] except: reference_sequence_informations["organisme"] = None # If the feature is CDS if feature.type == "CDS": # Get the nucleotide sequence associated to to the CDS cds = feature.location.extract(gb_record.seq) # If the nucleotide sequence contains the pattern if cds.find(record["pattern"]) != -1: # Set is CDS to true isCDS = True # Initialize list of data to save data = [] # Get the informations try: reference_sequence_informations["gene"] = feature.qualifiers["gene"][0] except: reference_sequence_informations["gene"] = None try: reference_sequence_informations["nucleotide_sequence"] = feature.location.extract(gb_record.seq) except: reference_sequence_informations["nucleotide_sequence"] = None try: reference_sequence_informations["position_gene_sequence"] = reference_sequence_informations["nucleotide_sequence"].find(record["pattern"]) except: reference_sequence_informations["position_gene_sequence"] = None try: reference_sequence_informations["amino_acid_sequence"] = feature.qualifiers["translation"][0] except: reference_sequence_informations["amino_acid_sequence"] = None # Iterate through the sequences records to complte the infornations according to the reference informations data = Parallel(n_jobs = -1)(delayed(indentifyMutationInformation)(record, reference_sequence_informations) for record in records) # Compute the frequency for d1 in data: organisme_type = d1[2] pattern = d1[4] n_total = 0 n_pattern = 0 for d2 in data: if organisme_type == d2[2]: n_total = n_total + 1 if pattern == d2[4]: n_pattern = n_pattern + 1 frequency = int(n_pattern / n_total * 100) d1.append(frequency) # Convert data to dataframe df = pd.DataFrame(data, columns = ["SEQUENCE ID", "ORGANISM", "TYPE", "INITIAL PATTERN", "MUTATED PATTERN", "GENE", "MUTATIONS", "LOCATION", "FREQUENCY"]) # Save the dataframe to excel file df.to_excel("output/" + key + "_gene_" + reference_sequence_informations["gene"] + ".xlsx") # Check for other features if isCDS == False: data = [] # Iterate through the features of the reference sequence for feature in gb_record.features: seq = feature.location.extract(gb_record.seq) # If the nucleotide sequence contains the pattern if seq.find(record["pattern"]) != -1: # Save informations if feature.type == "rep_origin" or feature.type == "gene" or feature.type == "misc_feature" or feature.type == "repeat_region": if feature.type == "gene": try: reference_sequence_informations["gene"] = feature.qualifiers["gene"][0] except: reference_sequence_informations["gene"] = "None" elif feature.type == "repeat_region": try: reference_sequence_informations["gene"] = "Repeat region" except: reference_sequence_informations["gene"] = "None" else: try: reference_sequence_informations["gene"] = feature.qualifiers["note"][0] except: reference_sequence_informations["gene"] = "None" # If no feature identified if "gene" not in reference_sequence_informations: reference_sequence_informations["gene"] = "None" # Iterate through the sequences records to complete the infornations according to the reference informations for record in records: # If same pattern as reference sequence if record["pattern"] == reference_sequence_informations["pattern"]: data.append([record["id"], reference_sequence_informations["organisme"], record["type"], reference_sequence_informations["pattern"], None, reference_sequence_informations["gene"], None, record["position"]]) # If different pattern as reference sequence else: if record["pattern"] != None: data.append([record["id"], reference_sequence_informations["organisme"], record["type"],reference_sequence_informations["pattern"],record["pattern"], reference_sequence_informations["gene"], "No CDS",record["position"]]) # If unidentified pattern else: data.append([record["id"], reference_sequence_informations["organisme"], record["type"], reference_sequence_informations["pattern"], "Not identified", "Not identified", "Not identified", "Not identified"]) # Compute the frequency for d1 in data: organisme_type = d1[2] pattern = d1[4] n_total = 0 n_pattern = 0 for d2 in data: if organisme_type == d2[2]: n_total = n_total + 1 if pattern == d2[4]: n_pattern = n_pattern + 1 frequency = int(n_pattern / n_total * 100) d1.append(frequency) # Convert data to dataframe df = pd.DataFrame(data, columns = ["SEQUENCE ID", "ORGANISM", "TYPE", "INITIAL PATTERN", "MUTATED PATTERN", "GENE", "MUTATIONS", "LOCATION", "FREQUENCY"]) # Save the dataframe to excel file df.to_excel("output/" + key + "_gene_" + reference_sequence_informations["gene"] + ".xlsx") # If no genbank reference sequence else: # Iterate through the sequences records for each pattern for key, records in Results.items(): data = [] # Iterate through the sequences records for record in records: data.append([record["id"], None, record["type"], key, record["pattern"], None, None, record["position"]]) # Compute the frequency for d1 in data: organisme_type = d1[2] pattern = d1[4] n_total = 0 n_pattern = 0 for d2 in data: if organisme_type == d2[2]: n_total = n_total + 1 if pattern == d2[4]: n_pattern = n_pattern + 1 frequency = int(n_pattern / n_total * 100) d1.append(frequency) # Convert data to dataframe df = pd.DataFrame(data, columns = ["SEQUENCE ID", "ORGANISM", "TYPE", "INITIAL PATTERN", "MUTATED PATTERN", "GENE", "MUTATIONS", "LOCATION", "FREQUENCY"]) # Save the dataframe to excel file df.to_excel("output/" + key + ".xlsx")
{"/analyzer.py": ["/data.py", "/kmers.py"], "/main.py": ["/ml.py", "/krfe.py", "/analyzer.py", "/configuration.py"], "/krfe.py": ["/ml.py", "/data.py", "/kmers.py", "/matrix.py"], "/ml.py": ["/data.py", "/kmers.py", "/matrix.py"]}
4,940
bioinfoUQAM/CASTOR_KRFE
refs/heads/master
/matrix.py
import numpy from joblib import Parallel, delayed from collections import defaultdict # Function to compute the count of each k-mer in a sequence def computeSequenceVector(d, k): sequence = d[1] vector = defaultdict(int) for j in range(len(sequence) - k + 1): kmer = sequence[j:j+k] vector[kmer] += 1 return [d, vector] # Function to generate the feature matrix X and target vector y from a list of sequences D, a dictionary of k-mers K, and a k-mer length k def generateSamplesTargets(D, K, k): # Compute the k-mer counts for each sequence in parallel using joblib data_with_sequence_vector = Parallel(n_jobs=-1)(delayed(computeSequenceVector)(d, k) for d in D) # Extract the feature matrix X and target vector y from the sequence vectors and the original data X = [] y = [] for d in data_with_sequence_vector: # Create a list of k-mer counts with 0 for missing k-mers sequence_vector = [d[1][kmer] for kmer in K.keys()] X.append(sequence_vector) y.append(d[0][2]) # Convert X and y to numpy arrays for use with scikit-learn X = numpy.array(X) y = numpy.array(y) return X, y
{"/analyzer.py": ["/data.py", "/kmers.py"], "/main.py": ["/ml.py", "/krfe.py", "/analyzer.py", "/configuration.py"], "/krfe.py": ["/ml.py", "/data.py", "/kmers.py", "/matrix.py"], "/ml.py": ["/data.py", "/kmers.py", "/matrix.py"]}
4,941
bioinfoUQAM/CASTOR_KRFE
refs/heads/master
/main.py
# Imports import ml import sys import krfe import analyzer import configuration # Main program loop while(True): # Display the menu print("\n#######################") print("##### CASTOR-KRFE #####") print("#######################") print("\n1) Extract k-mers\n2) Fit a model\n3) Predict a sequences\n4) Motif analyzer (New)\n5) Exit/Quit") # Get the selected option option = int(input("\nSelect an option: ")) # Get/Update the parameters parameters = configuration.getParameters(configuration_file = sys.argv[1]) # Extract the discriminating k-mers if option == 1: print("\nCASTOR-KRFE: extraction mode\n") krfe.extract(parameters) # Fit a model using a set of k-mers elif option == 2: print("\nCASTOR-KRFE: training mode\n") ml.fit(parameters) # Predict a set of sequences elif option == 3: print("\nCASTOR-KRFE: testing mode\n") ml.predict(parameters) # Analyzer the identified k-mers elif option == 4: print("\nCASTOR-KRFE: motif analyzer mode\n") Results = analyzer.identifyPerfectMatch(parameters) Results = analyzer.identifyVariations(Results, parameters) Results = analyzer.extractRelatedInformation(Results, parameters) # Quit the program elif option == 5: print("Program exit") sys.exit(0) # If the mode specified is not valid else: print("The specified option is not valid")
{"/analyzer.py": ["/data.py", "/kmers.py"], "/main.py": ["/ml.py", "/krfe.py", "/analyzer.py", "/configuration.py"], "/krfe.py": ["/ml.py", "/data.py", "/kmers.py", "/matrix.py"], "/ml.py": ["/data.py", "/kmers.py", "/matrix.py"]}
4,942
bioinfoUQAM/CASTOR_KRFE
refs/heads/master
/krfe.py
# Imports import ml import sys import data import kmers import numpy import time import matrix import matplotlib.pyplot as plt from operator import itemgetter from sklearn.model_selection import cross_validate from sklearn.metrics import make_scorer, f1_score from sklearn.feature_selection import SelectFromModel from sklearn.feature_selection import RFE, VarianceThreshold from sklearn.model_selection import StratifiedKFold, cross_val_predict # Function to extract the discriminating k-mers def extract(parameters): history = [] # Initialize the maximum score max_score = 0 # Initialize the best identified score best_score = 0 # Initialize the best set of k-mers score best_k_mers = [] # Initialize the best length of k best_k_length = 0 # Initialize the best number of features best_features_number = 0 # Get the parameters T = float(parameters["T"]) k_min = int(parameters["k_min"]) k_max = int(parameters["k_max"]) k_mers_path = str(parameters["k_mers_path"]) file_path = str(parameters["training_fasta"]) # Load the training data D = data.loadData(file_path) # If the target values are not given if len(D[0]) != 3: print("Target values are not given") sys.exit(0) # Iterate through the length of k-mers to explore for k in range(k_min, k_max + 1): # Displays the current analysis print("Analysis of the " + str(k) + "-mers") # Get the k-mers existing in the sequences print("Get k-mers...") K = kmers.getKmers(D, k) # Generate the samples matrix (X) and the target values (y) print("Compute matrices...") X, y = matrix.generateSamplesTargets(D, K , k) # Scale the features between 0 and 1 print("Scaling...") X = ml.minMaxScaler(X) # If it is possible to apply a variance filter try: # Instancies the filter method print("VarianceThreshold...") varianceThreshold = VarianceThreshold(threshold = 0.01) # Apply the filter X = varianceThreshold.fit_transform(X) # Compute the list of k-mers indices to retain indices = [i for i, value in enumerate(varianceThreshold.get_support()) if value == True] # Update the list of k-mers K = dict.fromkeys(list(itemgetter(*indices)(list(K.keys()))), 0) # Clear the indices list indices.clear() # If not, pass on except: pass print("Reducing number of features with SelectFromModel...") # Instantiate a linear svm classifier clf = ml.svm() # Select from model if len(X[0]) > 100 : selectFromModel = SelectFromModel(estimator = clf, max_features = 100).fit(X, y) indices = [i for i, value in enumerate(selectFromModel.get_support()) if value == True] X = X[:,indices] # Update the list of k-mers K = dict.fromkeys(list(itemgetter(*indices)(list(K.keys()))), 0) indices.clear() else: pass # Get the number of features n_features = numpy.size(X, 1) # List of scores related to each subset of features scores = [] # List of number features related to each subset of features n_features = [] # List of indices related to each subset of features selected_features = [] # Initialize the empty list of indices indices = numpy.empty(0, int) # Apply recursive feature elimination rfe = RFE(estimator = clf , n_features_to_select = 1, step = 1).fit(X, y) # Iterate through the subset of features for i in range(1, rfe.ranking_.max()): # Merge the indices of this iteration to the list of indices indices = numpy.concatenate((indices, numpy.where(rfe.ranking_ == i)[0]), axis = None) # Save the indices related to the actual subset of features selected_features.append(indices) # Split the data using stratified K-Folds cross-validator skf = StratifiedKFold(n_splits = 5, random_state = 1, shuffle = True) # Perform the cross-validation for the actual subset of features cv_results = cross_validate(clf, X[:,indices], y, cv=skf, scoring={'f1_macro': make_scorer(f1_score, average='macro')}, n_jobs=-1) # Compute the F1 score of the actual subset of features score = cv_results['test_f1_macro'].mean() # Save the score of the actual subset of features scores.append(score) # Save the number of features of the actual subset of features n_features.append(len(indices)) # Compute evaluation and save results for all features skf = StratifiedKFold(n_splits = 5, random_state = 0, shuffle = True) y_pred = cross_val_predict(clf, X, y, cv = skf, n_jobs = -1) score = ml.compute_f1_score(y, y_pred) scores.append(score) n_features.append(X.shape[1]) selected_features.append(numpy.where(rfe.ranking_ != 0)[0]) # Get the best solution for this length of k-mers (Better score with lesser number of features) if max(scores) > max_score: max_score = max(scores) best_score = max_score best_k_length = k best_features_number = n_features[scores.index(max(scores))] best_k_mers = [list(K.keys())[i] for i in selected_features[ n_features.index(best_features_number)]] # Get best solution according to the threshold T for s, n in zip(scores, n_features): if s >= max_score*T and n <= best_features_number: best_score = s best_k_length = k best_features_number = n best_k_mers = [list(K.keys())[i] for i in selected_features[n_features.index(best_features_number)]] # Save the history history.append(scores) # Plot the history for i, h in enumerate(history): label = str(list(range(k_min, k_max + 1))[i]) + "-mers" plt.plot(list(range(1, len(h) + 1))[0:100], h[0:100], label = label) plt.axvline(best_features_number, linestyle=':', color='r') plt.suptitle("Distribution of F1-scores according to the length of k and the number of features", fontsize = 12) plt.title("Solution: F1 score = " + str(round(best_score, 2)) + ", Number of features = " + str(best_features_number) + ", Length of k = " + str(best_k_length), fontsize = 10) plt.xlabel('Number of features', fontsize = 10) plt.ylabel('F1 score', fontsize = 10) plt.legend() plt.show() # Save the extracted k-mers kmers.saveExtractedKmers(k_mers_path, best_k_mers) # Dipslay the solution print("\nIdentified solution:") print("Evaluation score (F1 score) =", best_score) print("Length of k =", best_k_length) print("Number of k-mers =", best_features_number) print("Extracted k-mers =", best_k_mers) print("Extracted k-mers saved at the path:", k_mers_path)
{"/analyzer.py": ["/data.py", "/kmers.py"], "/main.py": ["/ml.py", "/krfe.py", "/analyzer.py", "/configuration.py"], "/krfe.py": ["/ml.py", "/data.py", "/kmers.py", "/matrix.py"], "/ml.py": ["/data.py", "/kmers.py", "/matrix.py"]}
4,943
bioinfoUQAM/CASTOR_KRFE
refs/heads/master
/data.py
# Import import Bio.SeqIO # Function to load test data from a fasta file def loadData(file_path): # Initialize the data matrix D = [] # Iterate through the fasta file for record in Bio.SeqIO.parse(file_path, "fasta"): # If there is a class label, save id, sequence and class label in the data list try: indexes = [i for i, c in enumerate(record.description) if c == "|"] D.append([record.description, str(record.seq.upper()).replace('N',''), record.description[indexes[len(indexes)-1] +1 :]]) # If there is a no class label, save id and sequence in the data list except: D.append([record.descrition, str(record.seq.upper())]) # Return the data matrix return D # Function to load test data from a fasta file def loadReferenceSequence(D, reference_sequence_file): # Iterate through the genbank file try: for gb_record in Bio.SeqIO.parse(open(reference_sequence_file,"r"), "genbank"): D = [[gb_record.annotations["accessions"][0], str(gb_record.seq.upper()), "Reference_sequence"]] + D except: pass # Return the data matrix return D
{"/analyzer.py": ["/data.py", "/kmers.py"], "/main.py": ["/ml.py", "/krfe.py", "/analyzer.py", "/configuration.py"], "/krfe.py": ["/ml.py", "/data.py", "/kmers.py", "/matrix.py"], "/ml.py": ["/data.py", "/kmers.py", "/matrix.py"]}
4,944
bioinfoUQAM/CASTOR_KRFE
refs/heads/master
/ml.py
# Imports import data import kmers import joblib import matrix from sklearn.svm import SVC from sklearn.metrics import f1_score from sklearn.preprocessing import MinMaxScaler from sklearn.metrics import classification_report from sklearn.ensemble import RandomForestClassifier # Function to instantiate a linear svm classifier def svm(): # Return a linear svm classifier return SVC(kernel = 'linear', C = 1, cache_size = 1000) # Function to instantiate a random forest classifier def randomForest(): # Return a random forest classifier return RandomForestClassifier(n_estimators = 200, max_depth = None, random_state = 0, n_jobs = -1) # Function to Compute the F1 score def compute_f1_score(y, y_pred): # Return the computed F1 score return f1_score(y, y_pred, average ="weighted") # Function to transform features by scaling each feature between 0 and 1 def minMaxScaler(X): # Return scaled features return MinMaxScaler(feature_range = (0, 1), copy = False).fit_transform(X) # Function to fit a model using a set of k-mers def fit(parameters): # Get the parameters model_path = str(parameters["model_path"]) # Get the path of the k-mers file k_mers_path = str(parameters["k_mers_path"]) # Get the path of the training fasta file file_path = str(parameters["training_fasta"]) # Load the training data D = data.loadData(file_path) # Get the set of k-mers K = kmers.loadKmers(k_mers_path) # Get the k-mers length k = len(list(K.keys())[0]) # Generate the samples matrix (X) and the target values (y) X, y = matrix.generateSamplesTargets(D, K , k) # Instantiate a linear svm classifier clf = svm() # Fit the classifier clf.fit(X, y) # Save the model joblib.dump(clf, model_path) # Displays a confirmation message print("Model saved at the path:", model_path) # Function to predict a set of sequences def predict(parameters): # Get the path of the model file model_path = str(parameters["model_path"]) # Get the path of the k-mers file k_mers_path = str(parameters["k_mers_path"]) # Get the testing fasta file file_path = str(parameters["testing_fasta"]) # Get the prediction file path prediction_path = str(parameters["prediction_path"]) # Get the evaluation mode evaluation_mode = str(parameters["evaluation_mode"]) # Load the training data D = data.loadData(file_path) # Get the set of k-mers K = kmers.loadKmers(k_mers_path) # Get the k-mers length k = len(list(K.keys())[0]) # Generate the samples matrix (X) and the target values (y) X, y = matrix.generateSamplesTargets(D, K , k) # Load the classifier clf = joblib.load(model_path) # Predict the sequences y_pred = clf.predict(X) # If evaluation mode is egal to True if evaluation_mode == "True": # If the target values list is empty if len(y) == 0: print("Evaluation cannot be performed because target values are not given") # Else display the classification report else: print("Classification report \n", classification_report(y, y_pred)) # Save the predictions f = open(prediction_path, "w") # Write the header f.write("id,y_pred\n") # Iterate through the predictions for i, y in enumerate(y_pred): # Save the current prediction f.write(D[i][0] + "," + y + "\n") # Close the file f.close() # Displays a confirmation message print("Predictions saved at the path:", prediction_path)
{"/analyzer.py": ["/data.py", "/kmers.py"], "/main.py": ["/ml.py", "/krfe.py", "/analyzer.py", "/configuration.py"], "/krfe.py": ["/ml.py", "/data.py", "/kmers.py", "/matrix.py"], "/ml.py": ["/data.py", "/kmers.py", "/matrix.py"]}
4,945
bioinfoUQAM/CASTOR_KRFE
refs/heads/master
/kmers.py
# Import import re import Bio.SeqIO from collections import defaultdict from joblib import Parallel, delayed # Define a function to count the occurrences of k-mers in a single sequence def count_seq(seq, k): # Create an empty dictionary to store the counts for each k-mer counts = defaultdict(int) # Iterate through the sequence, considering k-mer windows of length k for j in range(len(seq) - k + 1): # Extract the k-mer from the sequence kmer = seq[j:j+k] # Increment the count for this k-mer counts[kmer] += 1 # Return the dictionary of k-mer counts return counts # Define a function to get the k-mers from a list of sequences def getKmers(D, k): # Use the Parallel function to parallelize the counting of k-mers # This will speed up the computation on multi-core CPUs counts = Parallel(n_jobs=-1)(delayed(count_seq)(d[1], k) for d in D) # Merge the counts into a single dictionary, with 0 as the default value all_counts = defaultdict(int) for count in counts: all_counts.update(count) # Return the dictionary of all k-mer counts return all_counts # Function to save the extracted k-mers def saveExtractedKmers(k_mers_path, k_mers): # Open file file = open(k_mers_path, "w") # Iterate through the k-mers for i, k in enumerate(k_mers): # Save the current k-mer file.write(">" + str(i) + "\n" + k + "\n") # Close the file file.close() # Function to load the set of k-mers from a fasta file def loadKmers(k_mers_path): # Initialize an empty dictionary for the k-mers K = {} # Iterate through the k-mers for record in Bio.SeqIO.parse(k_mers_path, "fasta"): # Save the current k-mer K[str(record.seq.upper())] = 0 # Return the dictionary of k-mers return K
{"/analyzer.py": ["/data.py", "/kmers.py"], "/main.py": ["/ml.py", "/krfe.py", "/analyzer.py", "/configuration.py"], "/krfe.py": ["/ml.py", "/data.py", "/kmers.py", "/matrix.py"], "/ml.py": ["/data.py", "/kmers.py", "/matrix.py"]}
4,946
bioinfoUQAM/CASTOR_KRFE
refs/heads/master
/configuration.py
# Import import configparser # Fonction to get the parameters from the configuration file def getParameters(configuration_file): # Initialize the parser configurationParser = configparser.ConfigParser() # Read the configuration file configurationParser.read(configuration_file) # Get the parameters parameters = dict() parameters["T"] = configurationParser.get("parameters", "T") parameters["k_min"] = configurationParser.get("parameters", "k_min") parameters["k_max"] = configurationParser.get("parameters", "k_max") parameters["model_path"] = configurationParser.get("parameters", "model_path") parameters["k_mers_path"] = configurationParser.get("parameters", "k_mers_path") parameters["testing_fasta"] = configurationParser.get("parameters", "testing_fasta") parameters["training_fasta"] = configurationParser.get("parameters", "training_fasta") parameters["refence_sequence_genbank"] = configurationParser.get("parameters", "reference_sequence") parameters["prediction_path"] = configurationParser.get("parameters", "prediction_path") parameters["evaluation_mode"] = configurationParser.get("parameters", "evaluation_mode") # Return the parameter dictionary return parameters
{"/analyzer.py": ["/data.py", "/kmers.py"], "/main.py": ["/ml.py", "/krfe.py", "/analyzer.py", "/configuration.py"], "/krfe.py": ["/ml.py", "/data.py", "/kmers.py", "/matrix.py"], "/ml.py": ["/data.py", "/kmers.py", "/matrix.py"]}
4,947
fginter/document-dedup
refs/heads/master
/idx_pbank.py
import get_text import argparse import dedup import scipy.sparse import gzip import json import re parser = argparse.ArgumentParser(description='Index') parser.add_argument("--section", default=0, type=int, help='Which part to ask 0...N-1 (default %(default)d)') parser.add_argument("--all", default=10, type=int, help='N (default %(default)d)') parser.add_argument("--batch", default=100000, type=int, help='batchsize (default %(default)d)') parser.add_argument("--preverts", default="/home/mjluot/preverts", help='preverts file (default %(default)s)') parser.add_argument("outfile", help="outfile.batchnum.npz will be the matrices and outfile.batchnum.json.gz will be the data") args = parser.parse_args() markup_re=re.compile("""^<doc.*?langdiff=.*?>|<gap chars=".*?" />|<p heading="[0-9]+">|</p>|</doc>""") for batch_num, (docs,indices) in enumerate(get_text.get_text(args.section,args.all,args.preverts,args.batch)): docs_to_index=[] for d in docs: d=markup_re.sub("",d) docs_to_index.append(d) sparse_m=dedup.documents2sparse(docs_to_index) scipy.sparse.save_npz("{}.batch_{}.npz".format(args.outfile,batch_num),sparse_m) with gzip.open("{}.batch_{}.json.gz".format(args.outfile,batch_num),"wt") as f: json.dump((docs,indices),f) print("Batch {} done".format(batch_num))
{"/idx_pbank.py": ["/dedup.py"]}
4,948
fginter/document-dedup
refs/heads/master
/dedup.py
import six assert six.PY3, "Run me with Python3" import numpy as np import scipy.sparse import csr_csc_dot as ccd import time import sys import re from sklearn.feature_extraction.text import HashingVectorizer discard_re=re.compile(r"[^a-zA-ZåäöÅÄÖ0-9 ]") #regex to discard characters which are not of our interest wspace_re=re.compile(r"\s+") #regex to discard characters which are not of our interest def documents2sparse(documents,ngram=4,n_features=10**7): """ documents: iterable yielding docs ngram: how long ngrams to consider for deduplication? n_features: used as modulo after hash, so all ngrams willbe mapped to this many features. Cannot be made too large because we will also need a feature x document sparse matrix. 10**6 or 10**7 are good values. Returns a sparse matrix. This can be saved with: scipy.sparse.save_npz("matrix_file.npz",sparse_m) """ vectorizer=HashingVectorizer(lowercase=True, ngram_range=(ngram,ngram), n_features=n_features,norm=None,dtype=np.float32) #use float32 because this is what I need later docs=[] for d in documents: d=discard_re.sub(" ",d) d=wspace_re.sub(" ",d) docs.append(d) sparse_m=np.abs(vectorizer.transform(docs)) #CSR matrix (one row for document, sparse columns for features) return sparse_m def duplicates_matrix_pair(m1,m2,slice_width=10000,m2_csc=None,cut=0.98): """ Find duplicates between m1 and m2. m1: document-by-feature CSR sparse matrix (as produced eg by scikit vectorizers) m2: document-by-feature CSR sparse matrix slice: sort of minibatch size - how many m1 rows are compared to m2 at once m2_csc: if None, will be calcuated as m2_csc=m2.tocsc() - provide if you happen to have it cached """ # Inspired here # https://github.com/scipy/scipy/blob/v0.14.0/scipy/sparse/data.py#L86 # # Diagonal values of m1.dot(m1) and m2.dot(m2) so we know what the maximum is diagonal1=m1._with_data(np.square(m1.data),copy=True).sum(-1) diagonal2=m2._with_data(np.square(m2.data),copy=True).sum(-1) if m2_csc is None: m2_csc=m2.tocsc() for slice_idx in np.arange(0,m1.shape[0],slice_width): out=np.zeros((slice_width,m2.shape[0]),np.float32) ccd.csr_csc_dot_f(slice_idx,slice_width,m1,m2_csc,out) #Now `out` is filled with the dot products out=np.square(out) out/=diagonal1 out/=diagonal2 #Now any value in `out` which is above something like 0.95 is a near-duplicate rows,cols=np.where(out>cut) for row,col in zip(rows,cols): yield row,col if __name__=="__main__": import argparse parser = argparse.ArgumentParser(description='Process some integers.') parser.add_argument('integers', metavar='N', type=int, nargs='+', help='an integer for the accumulator') args = parser.parse_args()
{"/idx_pbank.py": ["/dedup.py"]}
4,955
oooleemandy/hogwarts_lg4
refs/heads/master
/podemo1/page/index_page.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from selenium.webdriver.common.by import By from podemo1.page.addmemberpage import AddMemberPage from podemo1.page.base_page import BasePage class IndexPage(BasePage): _base_url = "https://work.weixin.qq.com/wework_admin/frame#" def click_add_member(self): self.find(By.CSS_SELECTOR, ".index_service_cnt_itemWrap:nth-child(1)").click() return AddMemberPage(self.driver)
{"/podemo1/page/index_page.py": ["/podemo1/page/addmemberpage.py"], "/page/Register.py": ["/page/base_page.py"], "/page/main.py": ["/page/Register.py", "/page/base_page.py"], "/testcase/test_register.py": ["/page/main.py"]}
4,956
oooleemandy/hogwarts_lg4
refs/heads/master
/test_selenium/test_js.py
from time import sleep from selenium import webdriver class TestJs(): def setup(self): self.driver = webdriver.Chrome() self.driver.implicitly_wait(5) self.driver.maximize_window() def teardown(self): self.driver.quit() def test_js_scroll(self): self.driver.get("https://www.baidu.com/") self.driver.find_element_by_id("kw").send_keys("selenium测试") '''js方式获取”百度一下“按钮,找到后返回给element''' element = self.driver.execute_script("return document.getElementById('su')") element.click() '''滑动到最低端,再点击下一页''' self.driver.execute_script("document.documentElement.scrollTop=10000") sleep(3) self.driver.find_element_by_xpath("//*[@id='page']/div/a[10]").click() sleep(3) '''打印title,打印性能数据''' for code in [ 'return document.title','return JSON.stringify(performance.timing)' ]: print(self.driver.execute_script(code)) def test_datetime(self): #12306首页 self.driver.get("https://www.12306.cn/index/") #定位时间控件,移除元素的readonly属性,使其可以被修改 time_element = self.driver.execute_script("a = document.getElementById('train_date')","a.removeAttribute('readonly')") #给时间控件赋值新value self.driver.execute_script("document.getElementById('train_date').value='2020-12-31'") sleep(3)
{"/podemo1/page/index_page.py": ["/podemo1/page/addmemberpage.py"], "/page/Register.py": ["/page/base_page.py"], "/page/main.py": ["/page/Register.py", "/page/base_page.py"], "/testcase/test_register.py": ["/page/main.py"]}
4,957
oooleemandy/hogwarts_lg4
refs/heads/master
/test_pytest/tests/test_calc.py
import yaml from test_pytest.core.calc import Calc import pytest import allure '''yaml文件驱动''' def load_data(path='data.yaml'): with open(path) as f: data = yaml.safe_load(f) keys = ",".join(data[0].keys()) values = [d.values() for d in data] return {'keys':keys,'values':values} class TestCalc: #类执行的时候初始化一次 def setup_class(cls): cls.calc=Calc() @allure.step def simple_step(self, step_param1, step_param2=None): pass #乘法的参数化 @pytest.mark.parametrize(load_data()['keys'],load_data()['values']) #乘法方法 @allure.story("乘法模块正向用例") def test_mult(self,a,b,c): #加入图片地址,图片名称,图片类型 allure.attach.file( r'C:\Users\limandi\Pictures\pic\Screenshot.jpg', "测试图片", allure.attachment_type.JPG ) self.simple_step(f'{a} {b} {c}') assert self.calc.mul(a,b) == c @pytest.mark.parametrize('a,b,c', [ [1, 2, 3], [-1, -1, -1], [1, 0, 1] ]) # 乘法方法 @allure.story("乘法模块逆向用例") def test_mulf(self, a, b, c): assert self.calc.mul(a, b) == c @pytest.mark.parametrize('a,b,c', [ [1, 2, "jj"], ["*", -1, -1], ]) # 乘法方法 @allure.story("乘法模块异常用例") def test_mule(self, a, b, c): with pytest.raises(Exception): assert self.calc.mul(a, b) == c #除法的参数化 @pytest.mark.parametrize('d,e,f',[ [4,2,2], [0.2,0.1,2], [0,2,0], ]) #除法方法 @allure.story("除法模块正向用例") def test_divt(self,d,e,f): assert self.calc.div(d,e) == f @pytest.mark.parametrize('d,e,f', [ [36, 6, 4], [-10,-2,-5], [2.2, 2, 1] ]) # 除法方法 @allure.story("除法模块逆向用例") def test_divf(self, d, e, f): assert self.calc.div(d, e) == f #除数为0 #除法的参数化 @pytest.mark.parametrize('d,e,', [ [2,0], [0.2, 0], [0,0], ]) # 除法方法 @allure.story("除数为0的异常处理") def test_dive(self, d, e): #返回除数为0的异常 with pytest.raises(ZeroDivisionError): assert self.calc.div(d, e) #流程用例,比如成乘法和除法的两个用例是有调用流程的 @allure.story("流程用例") def test_process(self): r1=self.calc.mul(1,2) r2=self.calc.div(2,1) assert r1 == 2 assert r2 == 2
{"/podemo1/page/index_page.py": ["/podemo1/page/addmemberpage.py"], "/page/Register.py": ["/page/base_page.py"], "/page/main.py": ["/page/Register.py", "/page/base_page.py"], "/testcase/test_register.py": ["/page/main.py"]}
4,958
oooleemandy/hogwarts_lg4
refs/heads/master
/test_selenium/test_cssss.py
from selenium import webdriver from selenium.webdriver.common.by import By class TestCSSS(): def setup(self): self.driver = webdriver.Chrome() self.driver.get("https://www.baidu.com/") def test_fnd(self): self.driver.find_element(By.XPATH, '//*[@id="kw"]').send_keys("Hogwarts") self.driver.find_element(By.XPATH, '//*[@id="su"]').click()
{"/podemo1/page/index_page.py": ["/podemo1/page/addmemberpage.py"], "/page/Register.py": ["/page/base_page.py"], "/page/main.py": ["/page/Register.py", "/page/base_page.py"], "/testcase/test_register.py": ["/page/main.py"]}
4,959
oooleemandy/hogwarts_lg4
refs/heads/master
/201024homework/Class12345.py
# 1、定义人类 属性有姓名年龄体重 方法有吃饭睡觉加班 class Person(): def __init__(self,name,age,weight): self.name = name self.age = age self.weight = weight def eat(self): print(f"{self.name}在吃饭") def work(self): print(f"{self.name}在加班") def sleep(self): print(f"{self.name}在睡觉") p = Person('Mark',30,150) p.eat() p.work() p.sleep() # 2、定义一个箱子类,属性有颜色和大小 方法有装食品装物品 class Box: def __init__(self,color, size): self.color =color self.size = size def food(self): print(f"{self.size}{self.color}的箱子用来装吃的") def obj(self): print(f"{self.size}{self.color}的箱子用来装物品") bfood = Box('红色','大的') bobj = Box('蓝色','小的') bfood.food() bobj.obj() #3、定义机票类 属性有出发地 目的地和历经时间 class Ticket: def __init__(self,departure,destination,time): self.departure = departure self.destination = destination self.time = time def p(self): print(f"由{self.departure}飞往{self.destination}的飞机历时{self.time}到达") t = Ticket('杭州', '深圳','2小时') t.p() #4、定义一个学生类 属性有班级学号分数 方法有期末考试 class Student: def __init__(self,grade,no,score): self.grade = grade self.no = no self.score = score def exam(self): print(f"{self.grade}班的学号为{self.no}的同学本次考试成绩为{self.score}") s = Student('11','19190808','150') s.exam() #5、定义一个书类 书的属性有书名 作者 序列号,有新增图书和借出图书方法 class Book: def __init__(self,name,author,index): self.name = name self.author = author self.index = index def addbook(self): print(f"新增一本{self.name}图书,作者为{self.author},序号为{self.index}") def lendbook(self): print(f"{self.name}图书,作者为{self.author},序列号为{self.index}被借出去啦") class Library(Book): print("这里是图书馆") libadd = Library('哈利波特与魔法石','J.K.Rowling','85533') liblend = Library("哈利波特与死亡圣器",'J.K.Rowling','85566') libadd.addbook() liblend.lendbook()
{"/podemo1/page/index_page.py": ["/podemo1/page/addmemberpage.py"], "/page/Register.py": ["/page/base_page.py"], "/page/main.py": ["/page/Register.py", "/page/base_page.py"], "/testcase/test_register.py": ["/page/main.py"]}
4,960
oooleemandy/hogwarts_lg4
refs/heads/master
/test_selenium/test_alert.py
from time import sleep from selenium.webdriver import ActionChains from test_pytest.base import Base class TestAlert(Base): def test_alert(self): self.driver.get("https://www.runoob.com/try/try.php?filename=jqueryui-api-droppable") #切换frame,找到”请拖拽我“这个元素所在的frame,用id取出 self.driver.switch_to.frame("iframeResult") #找到要拖拽的两个元素 drag = self.driver.find_element_by_id("draggable") drop = self.driver.find_element_by_id("droppable") action = ActionChains(self.driver) #需要把drag拖拽到drop中 action.drag_and_drop(drag,drop).perform() sleep(3) ''' 拖拽完以后会有弹框,需要切换到弹框页面再点击确认 ''' self.driver.switch_to.alert.accept() ''' alert点击确认后再返回到默认的frame下,然后点击运行 ''' self.driver.switch_to.default_content() self.driver.find_element_by_id("submitBTN").click() sleep(3)
{"/podemo1/page/index_page.py": ["/podemo1/page/addmemberpage.py"], "/page/Register.py": ["/page/base_page.py"], "/page/main.py": ["/page/Register.py", "/page/base_page.py"], "/testcase/test_register.py": ["/page/main.py"]}
4,961
oooleemandy/hogwarts_lg4
refs/heads/master
/test_selenium/test_file.py
from time import sleep from test_pytest.base import Base class TestFile(Base): def test_file(self): ''' 1、进入百度图库首页 2、点击加图片按钮 ''' self.driver.get("https://image.baidu.com/") self.driver.find_element_by_xpath("//*[@id='sttb']/img[1]").click() self.driver.find_element_by_id("uploadImg").send_keys(r"C:\Users\limandi\PycharmProjects\hogwarts_lg4\image\Screenshot.jpg") sleep(3)
{"/podemo1/page/index_page.py": ["/podemo1/page/addmemberpage.py"], "/page/Register.py": ["/page/base_page.py"], "/page/main.py": ["/page/Register.py", "/page/base_page.py"], "/testcase/test_register.py": ["/page/main.py"]}
4,962
oooleemandy/hogwarts_lg4
refs/heads/master
/page/Register.py
''' 注册页面 ''' from selenium.webdriver.common.by import By from page.base_page import BasePage class Register(BasePage): def register(self): self.find(By.ID, "corp_name").send_keys("填写企业名称") self.find(By.ID,"manager_name").send_keys("管理员姓名") return True
{"/podemo1/page/index_page.py": ["/podemo1/page/addmemberpage.py"], "/page/Register.py": ["/page/base_page.py"], "/page/main.py": ["/page/Register.py", "/page/base_page.py"], "/testcase/test_register.py": ["/page/main.py"]}
4,963
oooleemandy/hogwarts_lg4
refs/heads/master
/page/base_page.py
''' 放一些公共的方法。页面的一些都会用到的操作 ''' from selenium import webdriver from selenium.webdriver.remote.webdriver import WebDriver class BasePage: #访问的url _base_url="" #初始化 #构造方法 会自动调用 def __init__(self,driver:WebDriver=None): #如果不传driver,每个页面都要初始化一次driver。下面复用driver,而不是每次调用。当testcase很多时不用每次都新初始化driver if driver is None: self._driver=webdriver.Chrome() else: self._driver=driver #封装url 加一个判断,如果url不为空,就进行一个访问 if self._base_url !="": self._driver.get(self._base_url) #封装一个find方法,传一个by一个定位 def find(self,by,locator): return self._driver.find_element(by,locator)
{"/podemo1/page/index_page.py": ["/podemo1/page/addmemberpage.py"], "/page/Register.py": ["/page/base_page.py"], "/page/main.py": ["/page/Register.py", "/page/base_page.py"], "/testcase/test_register.py": ["/page/main.py"]}
4,964
oooleemandy/hogwarts_lg4
refs/heads/master
/test_selenium/test_testclick.py
# Generated by Selenium IDE import shelve from selenium import webdriver from time import sleep from selenium.webdriver.common.by import By class TestTestclick(): def setup_method(self, method): self.driver = webdriver.Chrome() self.vars = {} self.driver.implicitly_wait(5) def teardown_method(self, method): self.driver.quit() def test_testclick(self): self.driver.get("https://ceshiren.com/") self.driver.find_element(By.LINK_TEXT, "所有分类").click() element=self.driver.find_element(By.LINK_TEXT, "所有分类") result= element.get_attribute("class") assert 'active' ==result # self.driver.find_element(By.CSS_SELECTOR, "#ember129 .category-name").click() # self.driver.execute_script("window.scrollTo(0,0)") self.driver.close() def test_wx(self): self.driver.get("https://work.weixin.qq.com/wework_admin/loginpage_wx?from=myhome") sleep(10) def test_case2(self): # shelve python 自带的对象持久化存储 db = shelve.open('cookies') db['cookies'] = []
{"/podemo1/page/index_page.py": ["/podemo1/page/addmemberpage.py"], "/page/Register.py": ["/page/base_page.py"], "/page/main.py": ["/page/Register.py", "/page/base_page.py"], "/testcase/test_register.py": ["/page/main.py"]}
4,965
oooleemandy/hogwarts_lg4
refs/heads/master
/10thstep/test_demo2.py
import requests from requests.auth import HTTPBasicAuth class Api: data={ "method":"get", "url":"url", "headers":None, } #data 是一个请求信息 def send(self,data:dict): requests.request(method=data["method"] , url =data["url"] ,headers = data["headers"] )
{"/podemo1/page/index_page.py": ["/podemo1/page/addmemberpage.py"], "/page/Register.py": ["/page/base_page.py"], "/page/main.py": ["/page/Register.py", "/page/base_page.py"], "/testcase/test_register.py": ["/page/main.py"]}
4,966
oooleemandy/hogwarts_lg4
refs/heads/master
/test_selenium/test_window.py
from time import sleep from test_pytest.base import Base class TestWindow(Base): ''' 百度首页-点击登陆-点击立刻注册 ''' def test_window(self): self.driver.get("https://www.baidu.com/") self.driver.find_element_by_link_text("登录").click() #打印出当前窗口 print(self.driver.current_window_handle) self.driver.find_element_by_link_text("立即注册").click() #跳出新的窗口需要在新的窗口里找 print(self.driver.current_window_handle) #打印所有窗口 print(self.driver.window_handles) #定义当前的所有窗口 windows=self.driver.window_handles #此时形成一个窗口列表,去倒数第一个窗口里找 self.driver.switch_to_window(windows[-1]) #输入用户名密码 self.driver.find_element_by_id("TANGRAM__PSP_4__userName").send_keys("oooleemandy") self.driver.find_element_by_id("TANGRAM__PSP_4__phone").send_keys("15566274527") #再切换回登陆的窗口,第一个窗口 self.driver.switch_to_window(windows[0]) #点击用户名登陆 self.driver.find_element_by_id("TANGRAM__PSP_11__footerULoginBtn").click() #输入用户名密码 self.driver.find_element_by_id("TANGRAM__PSP_11__userName").send_keys("oooleemandy") self.driver.find_element_by_id("TANGRAM__PSP_11__password").send_keys("limandi940905") #点击登陆 self.driver.find_element_by_id("TANGRAM__PSP_11__submit").click() sleep(3)
{"/podemo1/page/index_page.py": ["/podemo1/page/addmemberpage.py"], "/page/Register.py": ["/page/base_page.py"], "/page/main.py": ["/page/Register.py", "/page/base_page.py"], "/testcase/test_register.py": ["/page/main.py"]}
4,967
oooleemandy/hogwarts_lg4
refs/heads/master
/test_selenium/test_wait.py
''' 打开测试人网站 点击分类 查看“最新“是否出现 如果出现了就点击热门 ''' from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions from selenium.webdriver.support.wait import WebDriverWait class TestWait: def setup(self): self.driver=webdriver.Chrome() self.driver.get("https://ceshiren.com/") #隐式等待 self.driver.implicitly_wait(3) def test_wait(self): self.driver.find_element(By.XPATH, '//*[@id="ember41"]/a').click() #直到可被点击 WebDriverWait(self.driver, 10).until(expected_conditions.element_to_be_clickable(By.XPATH, '//*[class=""table-heading]')) #元素是否可见. 当我们需要找到元素,并且该元素也可见。 WebDriverWait(self.driver, 10).until(expected_conditions.visibility_of_element_located(By.XPATH, '//*[class=""table-heading]')) #当我们不关心元素是否可见,只关心元素是否存在在页面中。 WebDriverWait(self.driver, 10).until(expected_conditions.presence_of_element_located(By.XPATH, '//*[class=""table-heading]')) self.driver.find_element(By.XPATH, "//*[@id='ember195']/a").click()
{"/podemo1/page/index_page.py": ["/podemo1/page/addmemberpage.py"], "/page/Register.py": ["/page/base_page.py"], "/page/main.py": ["/page/Register.py", "/page/base_page.py"], "/testcase/test_register.py": ["/page/main.py"]}
4,968
oooleemandy/hogwarts_lg4
refs/heads/master
/201024homework/XuZhu.py
""" 定义一个XuZhu类,继承于童姥。虚竹宅心仁厚不想打架。所以虚竹只有一个read(念经)的方法。每次调用都会打印“罪过罪过” """ class XuZhu(TongLao): def read(self): print("罪过罪过") tl = XuZhu(1000,200) tl.see_people('WYZ') tl.see_people('李秋水') tl.see_people('丁春秋') tl.fight_zms(1000,200) tl.read()
{"/podemo1/page/index_page.py": ["/podemo1/page/addmemberpage.py"], "/page/Register.py": ["/page/base_page.py"], "/page/main.py": ["/page/Register.py", "/page/base_page.py"], "/testcase/test_register.py": ["/page/main.py"]}
4,969
oooleemandy/hogwarts_lg4
refs/heads/master
/python_practice/python_class/python_opp.py
#面向对象 class House: #静态属性 类变量(在类之中,在方法之外) door = "red" floor = "white" #构造函数,在类实例化时直接执行了 def __init__(self): #在方法中调用类变量,需要加self. print(self.door) #实例变量,类当中,方法中,"self.变量名"定义 self.kitchen = "cook" #定义动态方法 def sleep(self): #普通变量 在类中 方法中,并且没有self bed = "ximengsi" self.table = "桌子可以放东西" print(f"在房子里可以躺在{bed}上睡觉") def cook(self): print(self.kitchen) print(self.table) print("在房子里做饭") #把类实例化 #北欧风 north_house = House() north_house.cook() #中式风 china_house = House() #用类名调用类属性 # print(House.door) # #修改类属性 # House.door = "white" # print(House.door) # # # # #用实例对象调用类属性 # print(north_house.door) # # # north_house = "black" # print(north_house.door)
{"/podemo1/page/index_page.py": ["/podemo1/page/addmemberpage.py"], "/page/Register.py": ["/page/base_page.py"], "/page/main.py": ["/page/Register.py", "/page/base_page.py"], "/testcase/test_register.py": ["/page/main.py"]}
4,970
oooleemandy/hogwarts_lg4
refs/heads/master
/10thstep/test_requests.py
import requests def test_demo(): url ="http://httpbin.ceshiren.com/cookies" header = { 'User-Agent': 'hogwarts' } cookie_data={ "hogwarts": "school", "teacher":"AD" } r=requests.get(url = url,headers = header,cookies=cookie_data) print(r.request.headers)
{"/podemo1/page/index_page.py": ["/podemo1/page/addmemberpage.py"], "/page/Register.py": ["/page/base_page.py"], "/page/main.py": ["/page/Register.py", "/page/base_page.py"], "/testcase/test_register.py": ["/page/main.py"]}
4,971
oooleemandy/hogwarts_lg4
refs/heads/master
/python1029_alluredemo/result/test_alluredemo_link_issue_case.py
import allure @allure.link("https://www.baidu.com") def test_with_link(): print(("这是一条加了链接的测试")) pass
{"/podemo1/page/index_page.py": ["/podemo1/page/addmemberpage.py"], "/page/Register.py": ["/page/base_page.py"], "/page/main.py": ["/page/Register.py", "/page/base_page.py"], "/testcase/test_register.py": ["/page/main.py"]}