index
int64
repo_name
string
branch_name
string
path
string
content
string
import_graph
string
53,015
daldal-Mango/Miracle30
refs/heads/main
/main/views.py
from django.shortcuts import render, redirect from django.utils import * from .models import Goal from datetime import datetime import datetime def main_login(request): return render(request, 'main/main_login.html') def main_logout(request): return render(request, 'main/main_logout.html') def goal_main(request): today = datetime.date.today() goals = Goal.objects.filter(deadline__gte=today) return render(request, 'main/goal_main.html', {'goals':goals}) def goal_detail(request, goal_id): goal = Goal.objects.get(pk=goal_id) isMember = request.user in goal.member.all() context = { 'goal' : goal, 'isMember' : isMember } return render(request, 'main/goal_detail.html', context) def add_goal(request): return render(request, 'main/add_goal.html') def create_goal(request): new_goal = Goal() new_goal.category = request.POST['category'] new_goal.certify_method = request.POST['certify_method'] new_goal.manager = request.user new_goal.name = request.POST['name'] new_goal.description = request.POST['description'] new_goal.created = timezone.now() new_goal.deadline = request.POST['deadline'] new_goal.start_date = request.POST['start_date'] new_goal.fee = request.POST['fee'] new_goal.member_limit = request.POST['member_limit'] request.user.profile.cash -= 500 request.user.profile.save() # 인증 방식이 수치인 경우 인증 기준의 값과 단위를 db에 저장 if request.POST['certify_method'] == 'figure': new_goal.criteria = request.POST['criteria'] new_goal.value = request.POST['value'] new_goal.unit = request.POST['unit'] new_goal.save() return redirect('main:goal_main') def update_goal(request, goal_id): goal = Goal.objects.get(pk=goal_id) if request.method == "POST": goal.category = request.POST['category'] goal.certify_method = request.POST['certify_method'] goal.manager = request.user goal.name = request.POST['name'] goal.description = request.POST['description'] goal.created = timezone.now() goal.deadline = request.POST['deadline'] goal.start_date = request.POST['start_date'] goal.fee = request.POST['fee'] goal.member_limit = request.POST['member_limit'] # 인증 방식이 수치인 경우 인증 기준의 값과 단위를 db에 저장 if request.POST['certify_method'] == 'figure': goal.criteria = request.POST['criteria'] goal.value = request.POST['value'] goal.unit = request.POST['unit'] goal.save() return redirect('main:goal_detail', goal_id) return render(request, 'main/update_goal.html', {'goal':goal}) def delete_goal(request, goal_id): goal = Goal.objects.get(pk=goal_id) goal.delete() return redirect('main:goal_main') def participate_goal(request, goal_id): goal = Goal.objects.get(pk=goal_id) isMember = request.user in goal.member.all() if isMember: request.user.members.remove(goal) else: request.user.members.add(goal) request.user.profile.cash -= goal.fee request.user.profile.save() return redirect('main:goal_detail', goal_id)
{"/groups/admin.py": ["/groups/models.py"], "/groups/views.py": ["/main/models.py", "/groups/models.py"], "/groups/models.py": ["/main/models.py"], "/main/admin.py": ["/main/models.py"], "/users/views.py": ["/main/models.py"], "/main/views.py": ["/main/models.py"]}
53,016
daldal-Mango/Miracle30
refs/heads/main
/main/migrations/0001_initial.py
# Generated by Django 3.2.5 on 2021-08-02 02:40 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Goal', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('category', models.CharField(choices=[('study', 'study'), ('hobby', 'hobby'), ('etc', 'etc')], max_length=50)), ('certify_method', models.CharField(choices=[('image', 'image'), ('text', 'text'), ('figure', 'figure')], max_length=50)), ('name', models.CharField(max_length=100)), ('description', models.TextField()), ('created', models.DateField()), ('start_date', models.DateField()), ('fee', models.IntegerField(default=500)), ('value', models.IntegerField(blank=True, null=True)), ('unit', models.CharField(blank=True, max_length=10, null=True)), ('criteria', models.BooleanField(default=True)), ('manager', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ('member', models.ManyToManyField(related_name='members', to=settings.AUTH_USER_MODEL)), ], ), ]
{"/groups/admin.py": ["/groups/models.py"], "/groups/views.py": ["/main/models.py", "/groups/models.py"], "/groups/models.py": ["/main/models.py"], "/main/admin.py": ["/main/models.py"], "/users/views.py": ["/main/models.py"], "/main/views.py": ["/main/models.py"]}
53,017
daldal-Mango/Miracle30
refs/heads/main
/groups/migrations/0003_auto_20210809_2345.py
# Generated by Django 3.2.5 on 2021-08-09 23:45 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('main', '0002_alter_goal_value'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('groups', '0002_alter_certifyfigure_figure'), ] operations = [ migrations.CreateModel( name='Certify', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created', models.DateField()), ('image', models.ImageField(blank=True, null=True, upload_to='certify_image/')), ('text', models.TextField(blank=True, null=True)), ('figure', models.FloatField(blank=True, null=True)), ('achievement', models.BooleanField(default=False)), ('goal', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='certifies', to='main.goal')), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), migrations.RemoveField( model_name='certifyimage', name='goal', ), migrations.RemoveField( model_name='certifyimage', name='user', ), migrations.RemoveField( model_name='certifytext', name='goal', ), migrations.RemoveField( model_name='certifytext', name='user', ), migrations.DeleteModel( name='CertifyFigure', ), migrations.DeleteModel( name='CertifyImage', ), migrations.DeleteModel( name='CertifyText', ), ]
{"/groups/admin.py": ["/groups/models.py"], "/groups/views.py": ["/main/models.py", "/groups/models.py"], "/groups/models.py": ["/main/models.py"], "/main/admin.py": ["/main/models.py"], "/users/views.py": ["/main/models.py"], "/main/views.py": ["/main/models.py"]}
53,018
daldal-Mango/Miracle30
refs/heads/main
/main/urls.py
from django.urls import path from . import views app_name = 'main' urlpatterns = [ path('', views.main_logout, name="main_logout"), path('login/', views.main_login, name="main_login"), path('goal_main/', views.goal_main, name="goal_main"), path('goal_detail/<int:goal_id>', views.goal_detail, name="goal_detail"), path('add_goal/', views.add_goal, name="add_goal"), path('create_goal/', views.create_goal, name="create_goal"), path('update_goal/<int:goal_id>', views.update_goal, name="update_goal"), path('delete_goal/<int:goal_id>', views.delete_goal, name="delete_goal"), path('participate_goal/<int:goal_id>', views.participate_goal, name="participate_goal"), ]
{"/groups/admin.py": ["/groups/models.py"], "/groups/views.py": ["/main/models.py", "/groups/models.py"], "/groups/models.py": ["/main/models.py"], "/main/admin.py": ["/main/models.py"], "/users/views.py": ["/main/models.py"], "/main/views.py": ["/main/models.py"]}
53,019
daldal-Mango/Miracle30
refs/heads/main
/groups/templatetags/index.py
from django import template register = template.Library() @register.filter def index_1(indexable, i): return indexable[i] @register.filter def index_2(indexable, i): return indexable[i+10] @register.filter def index_3(indexable, i): return indexable[i+20]
{"/groups/admin.py": ["/groups/models.py"], "/groups/views.py": ["/main/models.py", "/groups/models.py"], "/groups/models.py": ["/main/models.py"], "/main/admin.py": ["/main/models.py"], "/users/views.py": ["/main/models.py"], "/main/views.py": ["/main/models.py"]}
53,020
mi-magda/WebMonitor
refs/heads/master
/components/logger.py
import logging class Logger: # Log format FORMAT = '%(asctime)-15s %(message)s' def __init__(self): logging.basicConfig(level=logging.INFO) self.log_operator = logging.getLogger(__name__) self.log_operator.propagate = False self.handler = logging.FileHandler('log_file.log') self.log_setup() # Defines how logs would look like def log_setup(self): self.log_operator.setLevel(logging.INFO) self.handler.setFormatter(logging.Formatter(Logger.FORMAT)) self.handler.setLevel(logging.INFO) self.log_operator.addHandler(self.handler)
{"/components/scrap_handler.py": ["/components/logger.py"], "/app.py": ["/components/CONFIG.py", "/components/scrap_handler.py"]}
53,021
mi-magda/WebMonitor
refs/heads/master
/components/scrap_handler.py
from bs4 import BeautifulSoup from components.logger import Logger import urllib.request from time import time """ Class which is responsible for performing operations connected with site status management. """ class ScrapOperator(Logger): START = None END = None URL = None def __init__(self, sites): super().__init__() self.log_setup() self.site_status = {web: "UNKNOWN" for web in sites} # Returns loaded site HTML @staticmethod def load_site(url): ScrapOperator.URL = url ScrapOperator.START = time() data = urllib.request.urlopen(url).read() ScrapOperator.END = time() return data # Returns raw data @staticmethod def parse_site(site): ScrapOperator.START = time() data = BeautifulSoup(site, 'html.parser') ScrapOperator.END = time() return data # Returns list, if item wasn't found the list would be empty @staticmethod def find_element(tuple_data, info): element, el_type, key = tuple_data # Find by text if element == "text": return info.body.find_all(text=key) # Find by other parameters e.g. (p, class, text) else: return info.body.find_all(element, {el_type: key}) # Checks if list was empty (it means element wasn't found) and creates proper info in log def check_condition(self, element): if not element: result = "Element NOT found!" status = "ERROR" else: result = "Element found" status = "OK" self.status_generator(status) message = self.build_log_message(result) self.log_operator.info(message) # Maps site url with its status def status_generator(self, status): self.site_status[ScrapOperator.URL] = status @staticmethod # Returns page load time def calculate_time(start, end): return end - start # Creates message inserted to log file def build_log_message(self, result, error=False): # Error means that there's a problem with web site so loading time is negligible if error: calculated_time = "Site error" # In other case calculate time else: calculated_time = self.calculate_time(ScrapOperator.START, ScrapOperator.END) # {site url} {result of checking operation} {time} return "{} {} {}".format( ScrapOperator.URL, result, calculated_time)
{"/components/scrap_handler.py": ["/components/logger.py"], "/app.py": ["/components/CONFIG.py", "/components/scrap_handler.py"]}
53,022
mi-magda/WebMonitor
refs/heads/master
/app.py
from flask import Flask, render_template import time import sys import _thread from components.CONFIG import CONTENT_REQUIREMENTS, REFRESH_RATE from components.scrap_handler import ScrapOperator scrap_operator = ScrapOperator(CONTENT_REQUIREMENTS.keys()) ''' A function which is responsible of looping through all sites saved in CONFIG file and checking if elements specified in this file are met ''' def thread_function(): while True: for key, value in CONTENT_REQUIREMENTS.items(): try: site = scrap_operator.load_site(key) parse = scrap_operator.parse_site(site) find = scrap_operator.find_element(value, parse) scrap_operator.check_condition(find) except: message = scrap_operator.build_log_message(sys.exc_info()[0], error=True) scrap_operator.log_operator.info(message) scrap_operator.status_generator("ERROR") time.sleep(REFRESH_RATE) app = Flask(__name__) ''' Basic flask implementation ''' @app.route("/") def index(): return render_template('index.html', title="Sites statuses", sites=scrap_operator.site_status) if __name__ == "__main__": _thread.start_new_thread(thread_function, ()) app.run(debug=False)
{"/components/scrap_handler.py": ["/components/logger.py"], "/app.py": ["/components/CONFIG.py", "/components/scrap_handler.py"]}
53,023
mi-magda/WebMonitor
refs/heads/master
/components/CONFIG.py
# Checking sites interval REFRESH_RATE = 5 """ MANUAL CONTENT_REQUIREMENTS = { #search using element# "SITE_URL": ("ELEMENT", "CLASS", "EXPECTED_VALUE"}, #search by text# "SITE_URL": ("TEXT", "EMPTY_STRING", "EXPECTED_VALUE") } """ CONTENT_REQUIREMENTS = { "https://b3ta.com/404": ("a", "class", "gb1"), "https://www.facebook.com/": ("div", "class", "Najlepsze ¿yczenia dla przedsiêbiorców z okazji Dnia Ma³ych i ¦rednich Firm"), "https://aryaboudaie.com/python/technical/educational/web/flask/2018/10/17/flask.html": ("text", "", "Terefere"), "https://dzone.com/articles/python-flask-generating-a-static-html-page": ("li", "class", "rss-icon"), "https://pl.simplesite.com/pages/service-login.aspx": ("a", "href", "//pl.simplesite.com/go/cms/features/features"), "https://www.interia.pl/": ("a", "class", "header-a") }
{"/components/scrap_handler.py": ["/components/logger.py"], "/app.py": ["/components/CONFIG.py", "/components/scrap_handler.py"]}
53,024
faridi2017/django241018
refs/heads/master
/victorcalls/victorjango/crm/serializers.py
from rest_framework import serializers from .models import Documents, Company, Aspnetusers, Leads, Project, Integrations,\ Leaditems, Aspnetroles, Location, Attendance, Refreshtokens, Companytype class DocumentsSerializer(serializers.ModelSerializer): class Meta: model = Documents fields = '__all__' #fields = ('name',) class CompanySerializer(serializers.ModelSerializer): class Meta: model = Company fields = '__all__' class CompanytypeSerializer(serializers.ModelSerializer): class Meta: model = Companytype fields = '__all__' class AspnetusersSerializer(serializers.ModelSerializer): class Meta: model = Aspnetusers fields = '__all__' # fields = [ # 'id', # 'username', # 'user_id', # 'password', # 'cid' # ] class LeadsSerializer(serializers.ModelSerializer): class Meta: model = Leads fields = '__all__' class ProjectSerializer(serializers.ModelSerializer): class Meta: model = Project fields = '__all__' class IntegrationsSerializer(serializers.ModelSerializer): class Meta: model = Integrations fields = '__all__' class LocationSerializer(serializers.ModelSerializer): class Meta: model = Location fields = '__all__' class LeaditemsSerializer(serializers.ModelSerializer): class Meta: model = Leaditems fields = '__all__' class AspnetrolesSerializer(serializers.ModelSerializer): class Meta: model = Aspnetroles fields = '__all__'
{"/victorcalls/victorjango/crm/views.py": ["/victorcalls/victorjango/crm/serializers.py"]}
53,025
faridi2017/django241018
refs/heads/master
/victorcalls/victorjango/crm/urls.py
from django.conf.urls import url from . import views from django.urls import path from rest_framework import routers from rest_framework.urlpatterns import format_suffix_patterns router = routers.DefaultRouter() urlpatterns = [ path('companies/', views.CompanyList.as_view()), # get all , post one path('company/companyid/<int:company_id>', views.Company_company_id_get_update_delete.as_view()), # GUD operations path('users/', views.AspnetusersList.as_view()), # get all, post one path('user/userid/<int:user_id>', views.Aspnetusers_get_update_delete.as_view()), # GUD operations path('users/companyid/<int:company_id>', views.Aspnetusers_of_companyList.as_view()), # get company's users path('users/username/<str:user_name>', views.Aspnetusers_of_username.as_view()), # get user by user name path('users/roles/', views.AspnetrolesList.as_view()), # get all roles, post one path('projects/', views.ProjectList.as_view()), # get all, post one path('project/projectid/<int:project_id>', views.Project_project_id_get_update_delete.as_view()), # GUD operations path('projects/companyid/<int:company_id>', views.Projects_of_company.as_view()), # get projects of company path('documents/', views.DocumentsList.as_view()), # get all, post one path('documents/project/<int:project_id>', views.Documents_of_project_List.as_view()), path('document/project/<int:project_id>/<int:document_id>', views.Document_with_projectid_documentid.as_view()), path('leads/', views.LeadsList.as_view()), path('join/', views.UsersJoinList.as_view()), path('join/test/<str:user_name>', views.Aspnetusers_join_aspnetroles.as_view()), path('fileupload/', views.UploadFiles.as_view()), ] urlpatterns = format_suffix_patterns(urlpatterns)
{"/victorcalls/victorjango/crm/views.py": ["/victorcalls/victorjango/crm/serializers.py"]}
53,026
faridi2017/django241018
refs/heads/master
/victorcalls/victorjango/crm/views.py
from django.shortcuts import render import flask_excel as excel from werkzeug.utils import secure_filename from flask import Flask, request import pyexcel import pandas as pd from rest_framework.response import Response from rest_framework.views import APIView from .models import * from .serializers import * from django.http import Http404 from rest_framework import status import psycopg2 import json from psycopg2.extras import RealDictCursor con = psycopg2.connect(dbname='leadpoliceb', user='postgres', host='localhost', password='Bismillah@123') from django.http import HttpResponseRedirect from django.shortcuts import render #from .forms import UploadFileForm # Imaginary function to handle an uploaded file. #from somewhere import handle_uploaded_file def open(): global con #cur = con.cursor() con = psycopg2.connect(dbname='leadpoliceb', user='postgres', host='localhost', password='Bismillah@123') cur = con.cursor(cursor_factory=RealDictCursor) return cur def close(cur): global con con.commit() cur.close() con.close() return True class DocumentsList(APIView): def get(self,request): records = Documents.objects.all() serializer = DocumentsSerializer(records,many=True) return Response(serializer.data) def post(self, request): serializer = DocumentsSerializer(data=request.data) print(request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class Documents_of_project_List(APIView): def get(self,request, project_id): records = Documents.objects.filter(projectid= project_id) serializer = DocumentsSerializer(records,many=True) return Response(serializer.data) class Document_with_projectid_documentid(APIView): def get(self,request, project_id,document_id): records = Documents.objects.filter(projectid= project_id,id=document_id) serializer = DocumentsSerializer(records,many=True) return Response(serializer.data) class CompanyList(APIView): def get(self,request): records = Company.objects.all() serializer = CompanySerializer(records,many=True) return Response(serializer.data) def post(self, request): serializer = CompanySerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class Company_company_id_get_update_delete(APIView): def get(self,request,company_id, Format=None): records = Company.objects.get(pk=company_id) serializer = CompanySerializer(records) return Response(serializer.data) def put(self,request,company_id, Format=None): records = Company.objects.get(pk=company_id) serializer = CompanySerializer(records,data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def delete(self, request, company_id, format=None): user = Company.objects.get(pk=company_id) user.delete() return Response(status=status.HTTP_204_NO_CONTENT) class AspnetusersList(APIView): def get(self,request): documents = Aspnetusers.objects.all() serializer = AspnetusersSerializer(documents,many=True) return Response(serializer.data) def post(self, request): serializer = AspnetusersSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class Aspnetusers_get_update_delete(APIView): """ update or delete a user instance. """ def get(self, request, user_id, format=None): user = Aspnetusers.objects.get(pk=user_id) serializer = AspnetusersSerializer(user) return Response(serializer.data) def put(self, request, user_id, format=None): user = Aspnetusers.objects.get(pk=user_id) serializer = AspnetusersSerializer(user, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def delete(self, request, user_id, format=None): user = Aspnetusers.objects.get(pk=user_id) user.delete() return Response(status=status.HTTP_204_NO_CONTENT) class Aspnetusers_of_companyList(APIView): def get(self,request,company_id): documents = Aspnetusers.objects.filter(companyid=company_id) serializer = AspnetusersSerializer(documents,many=True) return Response(serializer.data) class Aspnetusers_of_username(APIView): def get(self,request,user_name): documents = Aspnetusers.objects.filter(username=user_name) serializer = AspnetusersSerializer(documents,many=True) return Response(serializer.data) class AspnetrolesList(APIView): def get(self,request): documents = Aspnetroles.objects.all() serializer = AspnetrolesSerializer(documents,many=True) return Response(serializer.data) def post(self, request, Format=None): serializer = AspnetrolesSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class ProjectList(APIView): def get(self,request): records = Project.objects.all() serializer = ProjectSerializer(records,many=True) return Response(serializer.data) def post(self, request, format=None): serializer = ProjectSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class Project_project_id_get_update_delete(APIView): def get(self,request,project_id,Format=None): records = Project.objects.get(pk=project_id) serializer = ProjectSerializer(records) return Response(serializer.data) def put(self,request,project_id, Format=None): record = Project.objects.get(pk=project_id) serializer = ProjectSerializer(record,data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def delete(self, request, project_id, format=None): record = Project.objects.get(pk=project_id) record.delete() return Response(status=status.HTTP_204_NO_CONTENT) class Projects_of_company(APIView): def get(self,request,company_id): records = Project.objects.filter(companyid=company_id) serializer = ProjectSerializer(records,many=True) return Response(serializer.data) class UsersJoinList(APIView): def get(self,request): cursor = open() query = "SELECT documents.projectid FROM documents INNER JOIN project on documents.projectid = project.projectid" cursor.execute(query) records = cursor.fetchall() r = json.dumps(records) loaded_r = json.loads(r) return Response(loaded_r) class Aspnetusers_join_aspnetroles(APIView): def get(self,request, user_name): cursor = open() join_query = "select r.name, U.* from (select * from aspnetusers where companyid in " \ "(select companyid from aspnetusers where username=" + "'" + user_name + "'" + "limit 1)) as U " \ "join aspnetroles r on CAST(U.roleid AS INTEGER)=r.id;" cursor.execute(join_query) records = cursor.fetchall() dump_records = json.dumps(records,sort_keys=True, default=str) loaded_records = json.loads(dump_records) return Response(loaded_records) class LeadsList(APIView): def get(self,request): documents = Leads.objects.all() serializer = LeadsSerializer(documents,many=True) return Response(serializer.data) def post(self, request, format=None): serializer = LeadsSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) # Create your views here. class UploadFiles(APIView): def post(self,request): f = request.FILES['file'] print(f.name) myfile = pd.read_excel(f) #print(myfile.to_json(orient='records')) serializer = LeadsSerializer(data=myfile.to_json(orient='records')) if serializer.is_valid(): serializer.save() #print(myfile.head()) return Response('success') # Create your views here. from django.shortcuts import render # Create your views here.
{"/victorcalls/victorjango/crm/views.py": ["/victorcalls/victorjango/crm/serializers.py"]}
53,045
roybaroes/PorePressurePrediction
refs/heads/master
/porepressureprediction/velocity/basic/survey.py
# -*- coding: utf-8 -*- """ Created on Fri Dec 11 20:24:38 2015 @author: yuhao """ from __future__ import division, print_function import numpy as np class Survey(object): """a survey is a combination of seismic and well logs """ def __init__(self, cube): self.wells = list() self.seisCube = cube self.wells_loc = dict() def _tie(self, well): w_east = well.loc[0] w_north = well.loc[1] gamma_x = (self.seisCube.east_B - self.seisCube.east_A) / \ (self.seisCube.crline_B - self.seisCube.crline_A) beta_x = (self.seisCube.east_C - self.seisCube.east_B) / \ (self.seisCube.inline_C - self.seisCube.inline_B) alpha_x = self.seisCube.east_A - \ beta_x * self.seisCube.inline_A - \ gamma_x * self.seisCube.crline_A gamma_y = (self.seisCube.north_B - self.seisCube.north_A) / \ (self.seisCube.crline_B - self.seisCube.crline_A) beta_y = (self.seisCube.north_C - self.seisCube.north_B) / \ (self.seisCube.inline_C - self.seisCube.inline_B) alpha_y = self.seisCube.north_A - \ beta_y * self.seisCube.inline_A - \ gamma_y * self.seisCube.crline_A d = np.matrix([[w_east - alpha_x], [w_north - alpha_y]]) G = np.matrix([[beta_x, gamma_x], [beta_y, gamma_y]]) m = G.I * d m = m.astype(int) # w_inline, w_xline = m[0][0], m[1][0] inline, crline = int(m[0][0]), int(m[1][0]) param_in = (inline - self.seisCube.startInline) // \ self.seisCube.stepInline + \ ((inline - self.seisCube.startInline) % self.seisCube.stepInline) // \ (self.seisCube.stepInline / 2) inline = self.seisCube.startInline + \ self.seisCube.stepInline * param_in param_cr = (crline - self.seisCube.startCrline) // \ self.seisCube.stepCrline + \ ((inline - self.seisCube.startCrline) % self.seisCube.stepCrline) // \ (self.seisCube.stepCrline) crline = self.seisCube.startCrline + \ self.seisCube.stepCrline * param_cr return (inline, crline) def add_well(self, well): loc = self._tie(well) self.wells.append(well) self.wells_loc[well.name] = loc def get_seis(self, well_name, attr): if well_name in self.wells_loc.keys(): loc = self.wells_loc[well_name] data = self.seisCube.get_cdp(loc, attr) return data else: print("Well not found! return None") return None def sparse_mesh(self, depth, log_name): depth_range = range(self.seisCube.startDepth, (self.seisCube.endDepth + 1), self.seisCube.stepDepth) if depth > self.seisCube.endDepth: print("input depth larger than maximum depth") # depth = self.seisCube.endDepth elif depth < self.seisCube.startDepth: print("input depth smaller than minimum depth") # depth = self.seisCube.startDepth elif depth not in depth_range: print("return values on nearest depth") else: pass depth = min(depth_range, key=lambda x: abs(x-depth)) mesh = np.array([np.nan] * self.seisCube.nNorth * self.seisCube.nEast) mesh.shape = (self.seisCube.nNorth, self.seisCube.nEast) for we in self.wells: log_depth = we.get_log("depth") log_data = we.get_log(log_name) log_index = range(len(log_depth)) d = log_data[min(log_index, key=lambda x: abs(log_depth[x]-depth))] # print("d = ", d) w_inline = self.wells_loc[we.name][0] w_crline = self.wells_loc[we.name][1] a = (w_crline - self.seisCube.startCrline) // \ self.seisCube.stepCrline b = (w_inline - self.seisCube.startInline) // \ self.seisCube.stepInline mesh[a, b] = d return mesh def get_sparse_list(self, depth, log_name): depth_range = range(self.seisCube.startDepth, (self.seisCube.endDepth + 1), self.seisCube.stepDepth) if depth > self.seisCube.endDepth: print("input depth larger than maximum depth") # depth = self.seisCube.endDepth elif depth < self.seisCube.startDepth: print("input depth smaller than minimum depth") # depth = self.seisCube.startDepth elif depth not in depth_range: print("return values on nearest depth") else: pass depth = min(depth_range, key=lambda x: abs(x-depth)) sparse_list = list() for we in self.wells: log_depth = we.get_log("depth") log_data = we.get_log(log_name) log_index = range(len(log_depth)) d = log_data[min(log_index, key=lambda x: abs(log_depth[x]-depth))] # print("d = ", d) w_inline = self.wells_loc[we.name][0] w_crline = self.wells_loc[we.name][1] a = (w_crline - self.seisCube.startCrline) // \ self.seisCube.stepCrline b = (w_inline - self.seisCube.startInline) // \ self.seisCube.stepInline sparse_list.append([w_inline, w_crline, d]) return sparse_list # region Store # def _cal_setting(self): # self.nNorth = (self.endCrline - self.startCrline) // \ # self.stepCrline + 1 # self.nEast = (self.endInline - self.startInline) // \ # self.stepInline + 1 # self.stepEast = np.sqrt((self.north_C - self.north_B)**2 + # (self.east_C - east_B)**2) / \ # ((self.inline_C - self.inline_B) // # self.stepInline) # self.stepNorth = np.sqrt((self.north_B - self.north_A)**2 + # (self.east_B - east_A)**2) / \ # ((self.crline_B - self.crline_A) // # self.stepCrline) # # point D helps make ABCD a rectangle # inline_D = self.inline_C # crline_D = self.crline_A # east_D = east_A + east_C - east_B # north_D = north_A + north_C - north_B # angleNorth = self._angle(east_A, north_A, east_B, north_B) # angleEast = self._angle(east_A, north_A, east_D, north_D) # def _angle(self, x1, y1, x2, y2): # angle = 0 # x = x2 - x1 # y = y2 - y1 # arctanAngle = np.arctan(y / x) # if x > 0 and y > 0: # angle = arctanAngle # elif x > 0 and y < 0: # angle = 2 * np.pi + arctanAngle # elif x < 0 and y > 0: # angle = np.pi + arctanAngle # elif x < 0 and y < 0: # angle = np.pi + arctanAngle # return angle # endregion if __name__ == "__main__": from seiSQL import SeisCube from laSQL import Well chx = Well(js="../testFile/TWT1.json", db="../testFile/TWT1.db") cube = SeisCube("../velocity_2.db", "../survey.json") sur = Survey(cube) sur.add_well(chx) print(sur.wells_loc) tdk = sur.get_seis(chx.name) print(type(tdk), tdk[:10], sep=',') me = sur.sparse_mesh(1600, 'ac') print("shape:", me.shape) for m in me: for n in m: if not np.isnan(n): print(n)
{"/porepressureprediction/__init__.py": ["/porepressureprediction/velocity/basic/laSQL.py", "/porepressureprediction/velocity/basic/seiSQL.py", "/porepressureprediction/velocity/basic/survey.py", "/porepressureprediction/velocity/reader.py", "/porepressureprediction/stochastic/krig.py", "/porepressureprediction/velocity/conversion.py"]}
53,046
roybaroes/PorePressurePrediction
refs/heads/master
/porepressureprediction/velocity/basic/laSQL.py
# -*- coding: utf-8 -*- from __future__ import division import numpy as np from las import LASReader import json import sqlite3 import os class Well(object): """class for storing well log data with database file This Well class stores the well log data in associated database files, stores the well information in associated json files, and provides methods for accessing these external data. Attributes ---------- db_file : string the address of database file storing the log data sellSetting : string the address of json file storing well information Methods ------- add_log(log, name) Add an array of log data to the Well object drop_log(name) delete the log named 'name' logs() display existing logs in the database get_log(name) retrieve specific log Notes ----- Raises ------ """ def __init__(self, js=None, db=None): self.db_file = 'new_db.db' if db is None else db self.json_file = 'new_json.json' if js is None else js self._check_file() self.las_file = None self.existing_logs = None self._parse_existing_logs() self.name = None self.loc = None self.start = None self.stop = None self.step = None self._read_setting() def __str__(self): return "a well" def __repr__(self): pass def _parse_existing_logs(self): try: conn = sqlite3.connect(self.db_file) cur = conn.cursor() cur.execute("SELECT name FROM curves") temp = cur.fetchall() conn.close() self.existing_logs = [curv[0].lower() for curv in temp] except: print("Problem happened.") pass def _check_file(self): if not self.db_file.endswith('.db'): raise Exception("`db` should be .db file, " + "or use None instead") if not os.path.exists(self.db_file): try: fDB = open(self.db_file, 'w') fDB.close() except: print("Error: Database file cannot be created!") if not self.json_file.endswith('.json'): raise Exception("`json` should be .josn file, " + "or use None instead") if not os.path.exists(self.json_file): try: fJSON = open(self.json_file, 'w') fJSON.close() except: print("Error: JSON file cannot be created!") def _feet_2_meter(self, item_in_feet): """converts feet to meters """ # vfunc_model = np.vectorize(spherical) try: return item_in_feet / 3.28084 except TypeError: return float(item_in_feet) / 3.28084 def _rolling_window(self, a, window): a = np.array(a) shape = a.shape[:-1] + (a.shape[-1] - window + 1, window) strides = a.strides + (a.strides[-1],) rolled = np.lib.stride_tricks.as_strided( a, shape=shape, strides=strides) return rolled def _despike(self, curve, curve_sm, max_clip): spikes = np.where(curve - curve_sm > max_clip)[0] spukes = np.where(curve_sm - curve > max_clip)[0] out = np.copy(curve) out[spikes] = curve_sm[spikes] + max_clip out[spukes] = curve_sm[spukes] - max_clip return out def _read_setting(self): try: with open(self.json_file, 'r') as fin: jsStruct = json.load(fin) location = jsStruct['LOC']['data'].split() self.loc = (float(location[2]), float(location[5])) self.start = jsStruct['STRT']['data'] self.stop = jsStruct['STOP']['data'] self.step = jsStruct['STEP']['data'] self.name = jsStruct['WELL']['data'] if self.step == 0: self.step = 0.1 except: print("cannot open json file") pass def get_log(self, name, window=None): if name not in self.existing_logs: raise Exception("no log named {}!".format(name)) conn = sqlite3.connect(self.db_file) cur = conn.cursor() cur.execute("SELECT {} FROM data".format(name)) log = cur.fetchall() conn.close() log = [d[0] for d in log] if window is None: return log else: log_sm = np.median(self._rolling_window(log, window), -1) log_sm = np.pad(log_sm, window / 2, mode='edge') def update_log(self, name, data): if name not in self.existing_logs: raise Exception("no log named {}!".format(name)) conn = sqlite3.connect(self.db_file) cur = conn.cursor() dTuple = [(d,) for d in data] for i in xrange(len(dTuple)): cur.execute("UPDATE data SET {} = ? WHERE \ id = {}".format(name, i), dTuple[i]) conn.commit() conn.close() def add_log(self, name, data): """save log data into the database """ conn = sqlite3.connect(self.db_file) cur = conn.cursor() cur.execute() conn.close() def drop_log(self, name): """remove log from the database """ pass def logs(self): """display all existing logs in the database""" conn = sqlite3.connect(self.db_file) cur = conn.cursor() cur.execute("SELECT * FROM curves") dataTuples = cur.fetchall() conn.close() return [{"id": a[0], "name": a[1], "units": a[2], "descr": a[3]} for a in dataTuples] def _change_file_name(self): project_folder = os.getcwd() json_name = os.path.basename(self.json_file) json_folder = os.path.abspath(os.path.dirname(self.json_file)) json_name_new = self.well_name + os.path.extsep +\ self.json_file.split('.')[1] os.chdir(json_folder) os.rename(json_name, json_name_new) os.chdir(project_folder) self.json_file = os.path.join(json_folder, json_name_new) db_name = os.path.basename(self.db_file) db_folder = os.path.abspath(os.path.dirname(self.db_file)) db_name_new = self.well_name + os.path.extsep +\ self.db_file.split('.')[1] os.chdir(db_folder) os.rename(db_name, db_name_new) os.chdir(project_folder) self.db_file = os.path.join(db_folder, db_name_new) def read_las(self, las_file=None): self.las_file = las_file if self.las_file is None: self.las_file = '../data/wells/TWT1.las' las = LASReader(self.las_file, null_subs=np.nan) self.well_name = las.well.items['WELL'].data self._change_file_name() self.existing_logs = [] jsonDict = las.well.items.copy() for key in jsonDict.keys(): jsonDict[key] = {} jsonDict[key]['units'] = las.well.items[key].units jsonDict[key]['data'] = las.well.items[key].data jsonDict[key]['descr'] = las.well.items[key].descr with open(self.json_file, 'w') as fout: json.dump(jsonDict, fout, indent=4, sort_keys=False) sqlList = [] for litem in las.curves.items.values(): sqlTuple = [] tempList = litem.descr.split('=') sqlTuple.append(tempList[0].split()[0]) sqlTuple.append(litem.name) self.existing_logs.append(litem.name.lower()) sqlTuple.append(litem.units) sqlTuple.append(tempList[-1][1:]) sqlTuple = tuple(sqlTuple) sqlList.append(sqlTuple) sqlList.sort(key=lambda x: x[0]) conn = sqlite3.connect(self.db_file) cur = conn.cursor() cur.execute("""CREATE TABLE curves ( id INTEGER, name TEXT, units TEXT, decr TEXT )""") cur.executemany("INSERT INTO curves VALUES (?, ?, ?, ?)", sqlList) template = "" nameList = [a[1].lower() + " REAL" for a in sqlList] nameList.insert(0, "id INTEGER PRIMARY KEY") template = (',\n\t\t').join(nameList) cur.execute("CREATE TABLE data (\n\t\t{}\n\t)".format(template)) for i in xrange(int(las.data2d.shape[0])): temp = list(las.data2d[i]) temp.insert(0, i+1) temp = tuple(temp) cur.execute("INSERT INTO data \ VALUES (" + ','.join(['?'] * len(temp)) + ")", temp) conn.commit() conn.close() self._read_setting() self._parse_existing_logs() def rolling_window(a, window): a = np.array(a) shape = a.shape[:-1] + (a.shape[-1] - window + 1, window) strides = a.strides + (a.strides[-1],) rolled = np.lib.stride_tricks.as_strided( a, shape=shape, strides=strides) return rolled def despike(curve, curve_sm, max_clip): spikes = np.where(curve - curve_sm > max_clip)[0] spukes = np.where(curve_sm - curve > max_clip)[0] out = np.copy(curve) out[spikes] = curve_sm[spikes] + max_clip out[spukes] = curve_sm[spukes] - max_clip return out def smooth(log, window=3003): """ Parameter --------- log : 1-d array log to smooth window : scalar window size of the median filter Return ------ smoothed log : 1-d array smoothed log """ log_sm = np.median(rolling_window(log, window), -1) log_sm = np.pad(log_sm, window // 2, mode="edge") return log_sm if __name__ == '__main__': well = Well(js="../testFile/TWT1.json", db="../testFile/TWT1.db") print(well.loc) # well = Well() # well.read_las("../data/wells/TWT3.las") d1 = well.get_log("ac") # d2 = list(np.random.rand(len(d1))) # well.update_log('ac', d2) # print well.get_log('ac')[:10] print(d1[:10]) # print(well.existing_logs)
{"/porepressureprediction/__init__.py": ["/porepressureprediction/velocity/basic/laSQL.py", "/porepressureprediction/velocity/basic/seiSQL.py", "/porepressureprediction/velocity/basic/survey.py", "/porepressureprediction/velocity/reader.py", "/porepressureprediction/stochastic/krig.py", "/porepressureprediction/velocity/conversion.py"]}
53,047
roybaroes/PorePressurePrediction
refs/heads/master
/porepressureprediction/velocity/conversion.py
from __future__ import division import numpy as np from scipy import interpolate def rms2int(twt, rms): """ Convert rms velocity to interval velocity Parameters ---------- twt : 1-d ndarray input two-way-time array rms : 1-d nadarray rms velocity array Returns ------- v_int : 1-d ndarray interval velocity array with the same length of twt and rms Notes ----- This routine uses Dix equation to comput inverval velocity. .. math:: V_{int}[i]^2 = \\frac{V_{rms}[i]^2 t_{i} - V_{rms}[i-1]^2 \ t_{i-1}}{t_{i}-t_{i-1}} twt and rms should be of the same length of more than 2. Examples -------- >>> a = np.arange(10) >>> twt = np.arange(10) >>> rms2int(twt, a) array([ 0. , 1. , 2.64575131, 4.35889894, 6.08276253, 7.81024968, 9.53939201, 11.26942767, 13. , 14.73091986]) """ v_int = np.ones((len(twt), )) v_int[0] = rms[0] v_int[1:] = np.sqrt((rms[1:]**2 * twt[1:] - rms[:-1]**2 * twt[:-1]) / (twt[1:] - twt[:-1])) return v_int def int2rms(twt, v_int): """ Parameters ---------- twt : 1-d ndarray v_int : 1-d ndarray Returns ------- v_rms : 1-d ndarray """ v_rms = np.ones((len(twt), )) v_rms[0] = v_int[0] v_rms[1:] = np.sqrt( (v_int[1:]**2 * (twt[:-1] - twt[1:]) + v_rms[:-1]**2 * twt[:-1]) / twt[1:] ) return v_rms def int2avg(twt, v_int): """ Parameters ---------- twt : 1-d ndarray v_int : 1-d ndarray Returns ------- v_avg : 1-d ndarray Notes ----- .. math:: V_{int}[i](t[i] - t[i-1]) = V_{avg}[i] t[i] - V_{avg}[i-1] t[i-1] """ v_avg = np.ones((len(twt), )) v_avg[0] = v_int[0] v_avg[1:] = (v_avg[:-1] * twt[:-1] + v_int[1:] * (twt[1:] - twt[:-1])) /\ twt[1:] return v_avg def avg2int(twt, v_avg): """ Parameters ---------- twt : 1-d ndarray v_avg : 1-d ndarray Returns ------- v_int : 1-d ndarray """ v_int = np.ones((len(twt), )) v_int[0] = v_avg[0] v_int[1:] = (v_avg[1:]*twt[1:] - v_avg[:-1]*twt[:-1]) /\ (twt[1:] - twt[:-1]) return v_int def twt2depth(twt, v_avg, stepDepth, startDepth=None, endDepth=None): """ Parameters ---------- twt : 1-d ndarray v_avg : 1-d ndarray stepDepth : scalar startDpeth (optional): scalar endDepth (optional): scalar Returns ------- newDepth : 1-d ndarray new depth array new_v_avg : 1-d ndarray average velocity in depth domain """ depth = np.ones((len(twt), )) depth[:] = twt[:] * v_avg[:] startDepth = depth[0] if startDepth is None else startDepth endDepth = depth[-1] if endDepth is None else endDepth newDepth = np.arange(startDepth, endDepth, stepDepth) f = interpolate.interp1d(depth, v_avg, kind='cubic') new_v_avg = f(newDepth) return (newDepth, new_v_avg) if __name__ == "__main__": import doctest doctest.testmod()
{"/porepressureprediction/__init__.py": ["/porepressureprediction/velocity/basic/laSQL.py", "/porepressureprediction/velocity/basic/seiSQL.py", "/porepressureprediction/velocity/basic/survey.py", "/porepressureprediction/velocity/reader.py", "/porepressureprediction/stochastic/krig.py", "/porepressureprediction/velocity/conversion.py"]}
53,048
roybaroes/PorePressurePrediction
refs/heads/master
/porepressureprediction/velocity/basic/seiSQL.py
# -*- coding: utf-8 -*- from __future__ import division, print_function import sqlite3 import os import json import numpy as np class SeisCube(): def __init__(self, db, js): self.db_file = db self.json_file = js if self.json_file is not None: self._readJSON() self.attr = None if self.attr is None: self._get_existing_attr() def _info(self): return "A seismic Data Cube\n" +\ 'In-line range: {} - {} - {}\n'.format( self.startInline, self.endInline, self.stepInline) +\ 'Cross-line range: {} - {} - {}\n'.format( self.startCrline, self.endCrline, self.stepCrline) +\ 'Z range: {} - {} - {}\n'.format( self.startDepth, self.endDepth, self.stepDepth) +\ "SQL file location : {}\n".format(os.path.abspath(self.db_file)) def __str__(self): return self._info() def __repr__(self): return self._info() def _readJSON(self): # fin = open(self.json_file, 'r') with open(self.json_file, 'r') as fin: json_setting = json.load(fin) self.startInline = json_setting['inline'][0] self.endInline = json_setting['inline'][1] self.stepInline = json_setting['inline'][2] self.startCrline = json_setting['crline'][0] self.endCrline = json_setting['crline'][1] self.stepCrline = json_setting['crline'][2] self.startDepth = json_setting['depth'][0] self.endDepth = json_setting['depth'][1] self.stepDepth = json_setting['depth'][2] self.inline_A = json_setting['Coordinate'][0][0] self.crline_A = json_setting['Coordinate'][0][1] self.east_A = json_setting['Coordinate'][0][2] self.north_A = json_setting['Coordinate'][0][3] self.inline_B = json_setting['Coordinate'][1][0] self.crline_B = json_setting['Coordinate'][1][1] self.east_B = json_setting['Coordinate'][1][2] self.north_B = json_setting['Coordinate'][1][3] self.inline_C = json_setting['Coordinate'][2][0] self.crline_C = json_setting['Coordinate'][2][1] self.east_C = json_setting['Coordinate'][2][2] self.north_C = json_setting['Coordinate'][2][3] self.nEast = (self.endInline - self.startInline) // \ self.stepInline + 1 self.nNorth = (self.endCrline - self.startCrline) // \ self.stepCrline + 1 self._coordinate_conversion() def _coordinate_conversion(self): self.gamma_x = (self.east_B - self.east_A) / \ (self.crline_B - self.crline_A) self.beta_x = (self.east_C - self.east_B) / \ (self.inline_C - self.inline_B) self.alpha_x = self.east_A - \ self.beta_x * self.inline_A - \ self.gamma_x * self.crline_A self.gamma_y = (self.north_B - self.north_A) / \ (self.crline_B - self.crline_A) self.beta_y = (self.north_C - self.north_B) / \ (self.inline_C - self.inline_B) self.alpha_y = self.north_A - \ self.beta_y * self.inline_A - \ self.gamma_y * self.crline_A def _get_existing_attr(self): conn = sqlite3.connect(self.db_file) cur = conn.cursor() cur.execute("""SELECT name FROM sqlite_master WHERE type='table' ORDER BY name""") temp = cur.fetchall() self.attr = tuple([item[0] for item in temp]) conn.close() def coord_2_line(self, coordinate): x = coordinate[0] y = coordinate[1] d = np.matrix([[x - self.alpha_x], [y - self.alpha_y]]) G = np.matrix([[self.beta_x, self.gamma_x], [self.beta_y, self.gamma_y]]) m = G.I * d # m = m.astype(int) inline, crline = m[0][0], m[1][0] param_in = (inline - self.startInline) // self.stepInline + \ ((inline - self.startInline) % self.stepInline) // \ (self.stepInline / 2) inline = self.startInline + self.stepInline * param_in param_cr = (crline - self.startCrline) // self.stepCrline + \ ((inline - self.startCrline) % self.stepCrline) // \ (self.stepCrline) crline = self.startCrline + self.stepCrline * param_cr return (inline, crline) def line_2_coord(self, inline, crline): x = self.alpha_x + self.beta_x * inline + self.gamma_x * crline y = self.alpha_y + self.beta_y * inline + self.gamma_y * crline return (x, y) def get_inline(self, inline, attr): if attr in self.attr: conn = sqlite3.connect(self.db_file) cur = conn.cursor() # cur.execute("""SELECT attribute FROM {table} # WHERE inline=:il # ORDER BY crline""".format(table=attr), # {"il": inl}) cur.execute("""SELECT attribute FROM position JOIN {table} ON position.id = {table}.id WHERE inline = {inl}""".format(table=attr, inl=inline)) vv = cur.fetchall() conn.close() vv = [v[0] for v in vv] return vv else: pass def get_crline(self, crline, attr): conn = sqlite3.connect(self.db_file) cur = conn.cursor() # cur.execute("""SELECT vel FROM velocity WHERE # crline=:xl ORDER BY inline""", # {"xl": crl}) cur.execute("""SELECT attribute FROM position JOIN {table} ON position.id = {table}.id WHERE crline = {crl}""".format(table=attr, crl=crline)) vv = cur.fetchall() conn.close() vv = [v[0] for v in vv] return vv def get_depth(self, depth, attr): conn = sqlite3.connect(self.db_file) cur = conn.cursor() # cur.execute("""SELECT vel FROM velocity WHERE # twt=:dp ORDER BY crline""", # {"dp": depth}) cur.execute("""SELECT attribute FROM position JOIN {table} ON position.id = {table}.id WHERE twt = {d}""".format(table=attr, d=depth)) vv = cur.fetchall() conn.close() vv = [v[0] for v in vv] return vv def get_cdp(self, CDP, attr): il = CDP[0] cl = CDP[1] conn = sqlite3.connect(self.db_file) cur = conn.cursor() # cur.execute("""SELECT vel FROM velocity WHERE # inline=:inl AND crline=:xl ORDER BY twt""", # {"inl": il, "xl": cl}) cur.execute("""SELECT attribute FROM position JOIN {table} ON position.id = {table}.id WHERE inline = {inl} AND crline = {crl} """.format(table=attr, inl=il, crl=cl)) vv = cur.fetchall() conn.close() vv = [v[0] for v in vv] return vv def set_inline(self, inline, attr, vel): val = [(v[0],) for v in vel] conn = sqlite3.connect(self.db_file) cur = conn.cursor() cur.executemany("""UPDATE {table} SET attribute = ? WHERE inline={inl} """.format(table=attr, inl=inline), val) conn.commit() conn.close() def set_crline(self, crline, attr, vel): val = [(v[0],) for v in vel] conn = sqlite3.connect(self.db_file) cur = conn.cursor() cur.executemany("""UPDATE {table} SET attribute = ? WHERE crline={crl} """.format(table=attr, crl=crline), val) conn.commit() conn.close() def set_depth(self, depth, attr, vel): val = [(v[0],) for v in vel] conn = sqlite3.connect(self.db_file) cur = conn.cursor() cur.executemany("""UPDATE {table} SET attribute = ? WHERE twt={d}""".format(table=attr, d=depth), val) conn.commit() conn.close() def set_cdp(self, CDP, attr, vel): il = CDP[0] cl = CDP[1] val = [(v[0],) for v in vel] conn = sqlite3.connect(self.db_file) cur = conn.cursor() cur.executemany("""UPDATE {table} SET attribute = ? WHERE inlne={inl} AND crline={crl} """.format(table=attr, inl=il, crl=cl), val) conn.commit() conn.close() def export_od(self, attr, fname): try: with open(fname, 'w') as fout: fout.write("{}\t{}\t{}\n".format( self.stepInline, self.stepCrline, self.stepDepth)) conn = sqlite3.connect(self.db_file) cur = conn.cursor() for inl in range(self.startInline, self.endInline+1, self.stepInline): for crl in range(self.startCrline, self.endCrline+1, self.stepCrline): cur.execute('''SELECT attribute FROM {table} WHERE inline=:inl AND crline=:xl ORDER BY twt'''.format(talbe=attr), {'inl': inl, 'xl': crl}) temp = cur.fetchall() if len(temp) == 0: continue else: tempStr = list() for i in range(len(temp)): tempStr.append(str(temp[i][0])) data = '\t'.join(tempStr) + '\n' string = str(inl) + '\t' + str(crl) + '\t' fout.write(string + data) except: print("failed to export") if __name__ == "__main__": # a = SeisCube(os.path.join(os.path.pardir, "velocity_2.db"), # os.path.join(os.path.pardir, "survey.json")) # data1 = a.get_Inline(1620) # data2 = a.get_Crline(5680) # data3 = a.get_Cdp((1620, 5680)) # data4 = a.get_Depth(2400) # print(a) # print(a.nInline) # print(a.alpha_x, a.beta_x, a.gamma_x, sep=' ', end='\n') pass
{"/porepressureprediction/__init__.py": ["/porepressureprediction/velocity/basic/laSQL.py", "/porepressureprediction/velocity/basic/seiSQL.py", "/porepressureprediction/velocity/basic/survey.py", "/porepressureprediction/velocity/reader.py", "/porepressureprediction/stochastic/krig.py", "/porepressureprediction/velocity/conversion.py"]}
53,049
roybaroes/PorePressurePrediction
refs/heads/master
/porepressureprediction/stochastic/FFT_MA.py
''' 1. Building of the sampled covariance C (Fig. 1). 2. Generation of the normal deviates z on the grid. 3. Calculation of the Fourier transforms of z and C, giving Z and the power spectrum S, respectively. 4. Derivation of G from S. 5. Multiplication of G by Z. 6. Inverse Fourier transform of (G * Z) giving g*z. 7. Derivation of y from Equation (4). ''' import numpy as np import matplotlib.pyplot as plt from numpy.fft import fft2, ifft2 from autocorrelation import autocorrelation_func def fft_ma(m, n, a, b, r, dx, dy): C = np.zeros((m, n)) au = autocorrelation_func(a, b) for i in xrange(m): for j in xrange(n): C[i, j] = au.gaussian((i-(m-1)/2.)*dy, (j-(n-1)/2.)*dx) S = fft2(C) # power spectral density z = np.random.randn(m, n) Z = fft2(z) G = np.sqrt(dx * S) GZ = G * Z gz = ifft2(GZ) A = np.real(gz) K = np.real(A) return K if __name__ == "__main__": m = 200 n = 200 a = 20 b = 20 r = 1 vp0 = 1500 variance = 0.08 dx = 3 dy = 3 field = fft_ma(m, n, a, b, r, dx, dy) fig, ax = plt.subplots() ax.imshow(field) fig.savefig('temp.png', dpi=200)
{"/porepressureprediction/__init__.py": ["/porepressureprediction/velocity/basic/laSQL.py", "/porepressureprediction/velocity/basic/seiSQL.py", "/porepressureprediction/velocity/basic/survey.py", "/porepressureprediction/velocity/reader.py", "/porepressureprediction/stochastic/krig.py", "/porepressureprediction/velocity/conversion.py"]}
53,050
roybaroes/PorePressurePrediction
refs/heads/master
/porepressureprediction/__init__.py
from porepressureprediction.velocity.basic.laSQL import Well from porepressureprediction.velocity.basic.seiSQL import SeisCube from porepressureprediction.velocity.basic.survey import Survey from porepressureprediction.velocity.reader import Reader from porepressureprediction.velocity.smoothing import smooth, smooth_2d from porepressureprediction.stochastic.krig import Krig from porepressureprediction.velocity.conversion import rms2int, int2rms, int2avg, avg2int, twt2depth from porepressureprediction.velocity.interpolation import interp_DW, spline_1d
{"/porepressureprediction/__init__.py": ["/porepressureprediction/velocity/basic/laSQL.py", "/porepressureprediction/velocity/basic/seiSQL.py", "/porepressureprediction/velocity/basic/survey.py", "/porepressureprediction/velocity/reader.py", "/porepressureprediction/stochastic/krig.py", "/porepressureprediction/velocity/conversion.py"]}
53,051
roybaroes/PorePressurePrediction
refs/heads/master
/porepressureprediction/stochastic/krig.py
# -*- coding: utf-8 -*- from __future__ import division import numpy as np from scipy.spatial.distance import pdist, squareform from scipy.optimize import leastsq import matplotlib.pyplot as plt import matplotlib class Krig(object): def __init__(self, mesh, points, model='spherical', bw=500, info=None): self.model = model self.mesh = mesh self.points = points self.covfunc = None self.kriged_value = None self.kriged_variance = None self.bw = bw self.hs = None self.sv = None self.info = {"startInline": 2000, "endInline": 3600, "stepInline": 20, "startCrline": 8000, "endCrline": 9000, "stepCrline": 40 } def __str__(): pass def __repr__(): pass def train(self): if self.hs is None: _max = pdist(self.points[:, :2]).max() # / 2 self.hs = np.arange(0, _max, self.bw) if self.covfunc is None: if self.model == 'spherical': vfunc_model = np.vectorize(self._spherical) self.covfunc = self._cvmodel(self.points, vfunc_model, self.hs, self.bw) self.sv = self._SV(self.points, self.hs, self.bw) def krig(self): # X0, X1 = self.points[:, 0].min(), self.points[:, 0].max() # Y0, Y1 = self.points[:, 1].min(), self.points[:, 1].max() n, m = self.mesh.shape # dx, dy = (X1 - X0) / n, (Y1 - Y0) / m dx = self.info["stepInline"] dy = self.info["stepCrline"] x0 = self.info["startInline"] y0 = self.info["startCrline"] self.kriged_value = np.zeros(self.mesh.shape) self.kriged_variance = np.zeros(self.mesh.shape) m, n = int(m), int(n) for i in xrange(m): percent = int(i / m * 100) print('[' + percent * '=' + (100 - percent) * ' ' + '] ' + str(percent) + '%') for j in xrange(n): self.kriged_value[i, j], self.kriged_variance[i, j] = \ self._krige( self.points, self.covfunc, self.hs, self.bw, (x0 + dx * i, y0 + dy * j), 16) print('[' + 100 * '=' + '] ' + '100%' + '\nCompleted!') def semivariogram(self, savefig=False): fig2, ax2 = plt.subplots() ax2.plot(self.sv[0], self.sv[1], '.-') ax2.plot(self.sv[0], self.covfunc(self.sv[0])) ax2.set_title('Spherical Model') ax2.set_ylabel('Semivariance') ax2.set_xlabel('Lag [m]') if savefig is True: fig2.savefig('semivariogram_model.png', fmt='png', dpi=200) def plot(self, savefig=False): cdict = {'red': ((0.0, 1.0, 1.0), (0.5, 225 / 255., 225 / 255.), (0.75, 0.141, 0.141), (1.0, 0.0, 0.0)), 'green': ((0.0, 1.0, 1.0), (0.5, 57 / 255., 57 / 255.), (0.75, 0.0, 0.0), (1.0, 0.0, 0.0)), 'blue': ((0.0, 0.376, 0.376), (0.5, 198 / 255., 198 / 255.), (0.75, 1.0, 1.0), (1.0, 0.0, 0.0))} my_cmap = matplotlib.colors.LinearSegmentedColormap( 'my_colormap', cdict, 256) fig, ax = plt.subplots() H = np.zeros_like(self.kriged_value) for i in xrange(self.kriged_value.shape[0]): for j in xrange(self.kriged_value.shape[1]): H[i, j] = np.round(self.kriged_value[i, j] * 3) ax.matshow(H, cmap=my_cmap, interpolation='nearest') ax.scatter(self.points[:][0] / 200.0, self.points[:][1] / 200.0, facecolor='none', linewidths=0.75, s=50) ax.set_xlim(0, 99) ax.set_ylim(0, 80) ax.set_xticks([25, 50, 75], [5000, 10000, 15000]) ax.set_yticks([25, 50, 75], [5000, 10000, 15000]) if savefig is True: fig.savefig('krigingpurple.png', fmt='png', dpi=200) # figx, axx = plt.subplots() # HV = np.zeros_like(V) # for i in range(V.shape[0]): # for j in range(V.shape[1]): # HV[i, j] = np.round(V[i, j] * 3) # axx.matshow(HV, cmap=my_cmap, interpolation='nearest') # axx.scatter(z.x/200.0, z.y/200.0, # facecolor='none', linewidths=0.75, s=50) # axx.set_xlim(0, 99) # axx.set_ylim(0, 80) # axx.set_xticks([25, 50, 75], [5000, 10000, 15000]) # axx.set_yticks([25, 50, 75], [5000, 10000, 15000]) # if savefig is True: # figx.savefig('krigingpurple2.png', fmt='png', dpi=200) def _spherical(self, h, a, c0): if h <= a: return c0 * (1.5 * h / a - 0.5 * (h / a)**3.0) else: return c0 def _opt(self, fct, x, y, c0, parameterRange=None, meshSize=1000): ''' Parameters ---------- fct : callable functions to minimize x : ndarray input x array y : ndarray input y array c0 : scalar covariance Returns ------- a : scalar the best fitting coefficient ''' if parameterRange is None: parameterRange = [x[1], x[-1]] def residuals(pp, yy, xx): a = pp err = yy - fct(xx, a, c0) return err p0 = x[1] plsq = leastsq(residuals, p0, args=(y, x)) return plsq[0][0] def _SVh(self, P, h, bw): ''' Experimental semivariogram for a single lag ''' pd = squareform(pdist(P[:, :2])) N = pd.shape[0] Z = list() for i in xrange(N): for j in xrange(i + 1, N): if pd[i, j] >= h - bw and pd[i, j] <= h + bw: Z.append((P[i, 2] - P[j, 2])**2.0) return np.sum(Z) / (2.0 * len(Z)) def _SV(self, P, hs, bw): ''' Experimental variogram for a collection of lags ''' sv = list() for h in hs: sv.append(self._SVh(P, h, bw)) sv = [[hs[i], sv[i]] for i in range(len(hs)) if sv[i] > 0] return np.array(sv).T def _C(self, P, h, bw): """ calculate nugget covariance of the variogram Parameters ---------- P : ndarray samples h : scalar lag bw : scalar bandwidth Returns ------- c0 : number nugget variance """ c0 = np.var(P[:, 2]) # sill variance, which is a priori variance if h == 0: return c0 return c0 - self._SVh(P, h, bw) def _cvmodel(self, P, model, hs, bw): ''' Parameters ---------- P : ndarray data model : callable modeling function - spherical - exponential - gaussian hs : ndarray distances bw : scalar bandwidth Returns ------- covfct : callable the optimized function modeling the semivariogram ''' sv = self._SV(P, hs, bw) # calculate the semivariogram C0 = self._C(P, hs[0], bw) # calculate the nugget param = self._opt(model, sv[0], sv[1], C0) def covfct(h, a=param): return model(h, a, C0) # covfct = partial(model, a=param, c0=C0) return covfct def _krige(self, P, model, hs, bw, u, N): ''' Parameters ---------- P : ndarray data model : callable modeling function (spherical, exponential, gaussian) hs: kriging distances bw: kriging bandwidth u: unsampled point N: number of neighboring points to consider Returns ------- estimate : scalar krigged value ''' # covfct = cvmodel(P, model, hs, bw) # covariance function covfct = model mu = np.mean(P[:, 2]) # mean of the variable # distance between u and each data point in P d = np.sqrt((P[:, 0] - u[0])**2.0 + (P[:, 1] - u[1])**2.0) P = np.vstack((P.T, d)).T # add these distances to P # sort P by these distances # take the first N of them P = P[d.argsort()[:N]] k = covfct(P[:, 3]) # apply the covariance model to the distances k = np.matrix(k).T # cast as a matrix # form a matrix of distances between existing data points K = squareform(pdist(P[:, :2])) # apply the covariance model to these distances K = covfct(K.ravel()) K = np.array(K) K = K.reshape(N, N) K = np.matrix(K) # calculate the kriging weights weights = np.linalg.inv(K) * k weights = np.array(weights) variance_sample = np.var(P[:, 2]) variance = variance_sample - np.dot(k.T, weights) residuals = P[:, 2] - mu # calculate the residuals # calculate the estimation estimation = np.dot(weights.T, residuals) + mu return float(estimation), float(variance) if __name__ == '__main__': pass
{"/porepressureprediction/__init__.py": ["/porepressureprediction/velocity/basic/laSQL.py", "/porepressureprediction/velocity/basic/seiSQL.py", "/porepressureprediction/velocity/basic/survey.py", "/porepressureprediction/velocity/reader.py", "/porepressureprediction/stochastic/krig.py", "/porepressureprediction/velocity/conversion.py"]}
53,052
roybaroes/PorePressurePrediction
refs/heads/master
/porepressureprediction/stochastic/autocorrelation.py
''' different kind of autocorrelation functions ''' import numpy as np def autocorrelation_fuction(x, z, a, b, r): return np.exp(-(x**2/a**2+z**2/b**2)**(1.0/(r+1))) def exponential(x, z, a, b): return np.exp(-(x**2/a**2+z**2/b**2)**(1./2.)) def gaussian(x, z, a, b): return np.exp(-(x**2/a**2+z**2/b**2)) def spherical(): pass def stable(): pass class autocorrelation_func: def __init__(self, lc_a, lc_b): self.a = lc_a self.b = lc_b def exponential(self, x, z): return np.exp(-(x**2/self.a**2+z**2/self.b**2)**(1./2.)) def gaussian(self, x, z): return np.exp(-(x**2/self.a**2+z**2/self.b**2)) def spherical(self, x): v = 0 if x <= self.a: v = 1 - 1.5 * x / self.a + 0.5 * x**3 / self.a**3 return v def stable(self, x, z, r): return np.exp(-(x**r/self.a**r+z**r/self.b**r)**(1./r)) if __name__ == '__main__': pass
{"/porepressureprediction/__init__.py": ["/porepressureprediction/velocity/basic/laSQL.py", "/porepressureprediction/velocity/basic/seiSQL.py", "/porepressureprediction/velocity/basic/survey.py", "/porepressureprediction/velocity/reader.py", "/porepressureprediction/stochastic/krig.py", "/porepressureprediction/velocity/conversion.py"]}
53,053
roybaroes/PorePressurePrediction
refs/heads/master
/porepressureprediction/velocity/basic/__init__.py
__all__ = ['laSQL', 'seiSQL', 'survey']
{"/porepressureprediction/__init__.py": ["/porepressureprediction/velocity/basic/laSQL.py", "/porepressureprediction/velocity/basic/seiSQL.py", "/porepressureprediction/velocity/basic/survey.py", "/porepressureprediction/velocity/reader.py", "/porepressureprediction/stochastic/krig.py", "/porepressureprediction/velocity/conversion.py"]}
53,054
roybaroes/PorePressurePrediction
refs/heads/master
/porepressureprediction/velocity/reader.py
import sqlite3 class Reader(object): """class to create sqlite database with text file """ def __init__(self, db_name=None): self.db_file = str(db_name) + ".db" if db_name is not None \ else "new_db.db" self._create_db() def _create_db(self): f = open(self.db_file, 'w') f.close() conn = sqlite3.connect(self.db_file) cur = conn.cursor() cur.execute('''CREATE TABLE position( id INTEGER PRIMARY KEY, inline INTEGER, crline INTEGER, twt REAL )''') conn.commit() conn.close() def _update_db(self, vel, attr): # po = [[v[0], v[1], v[2]] for v in vel] # at = [[v[3]] for v in vel] n = len(vel) # for i in xrange(n): # po[i].insert(0, i) # at[i].insert(0, i) po = [tuple([i, vel[i][0], vel[i][1], vel[i][2]]) for i in xrange(n)] at = [tuple([i, vel[i][3]]) for i in xrange(n)] conn = sqlite3.connect(self.db_file) cur = conn.cursor() cur.executemany("INSERT INTO position VALUES (?, ?, ?, ?)", po) # for i in xrange(n): # temp = po[i] # temp.insert(0, i) # cur.execute("INSERT INTO position VALUES (?, ?, ?, ?)", # tuple(temp)) cur.execute("""CREATE TABLE {}( id INTEGER PRIMARY KEY, attribute REAL )""".format(attr)) cur.executemany("INSERT INTO {} VALUES (?, ?)".format(attr), at) # for i in xrange(n): # temp = at[i] # temp.insert(0, i) # cur.execute("INSERT INTO {} VALUES (?, ?)".format(attr), # tuple(temp)) conn.commit() conn.close() def read_HRS(self, textfile, attr): velocity = list() with open(textfile, 'r') as textVel: for line in textVel: temp = line.split() temp = [float(t) for t in temp] del temp[2] del temp[2] velocity.append(temp) self._update_db(velocity, attr) def read_od(self, textfile, attr): velocity = list() with open(textfile, 'r') as textVel: info = textVel.readline() fileInfo = info.split() startTwt = float(fileInfo[0]) stepTwt = float(fileInfo[1]) nTwt = int(fileInfo[-1]) for line in textVel: data = line.split() inline = int(data[0]) crline = int(data[1]) for i in range(2, nTwt + 2): velocity.append([ inline, crline, startTwt + (i-2) * stepTwt, float(data[i])]) self._update_db(velocity, attr)
{"/porepressureprediction/__init__.py": ["/porepressureprediction/velocity/basic/laSQL.py", "/porepressureprediction/velocity/basic/seiSQL.py", "/porepressureprediction/velocity/basic/survey.py", "/porepressureprediction/velocity/reader.py", "/porepressureprediction/stochastic/krig.py", "/porepressureprediction/velocity/conversion.py"]}
53,055
roybaroes/PorePressurePrediction
refs/heads/master
/porepressureprediction/pressure/pore_pressure.py
"""routines to assist velocity data processing. """ import numpy as np def bowers(v, obp, v0=5000, a=9.18448, b=0.764984): """ Compute pressure using Bowers equation. Parameters ---------- v : 1-d ndarray velocity array whose unit is m/s. obp : 1-d ndarray Overburden pressure whose unit is Pa. v0 : float, optional the velocity of unconsolidated regolith whose unit is ft/s. a : float, optional coefficient a b : float, optional coefficient b Notes ----- .. math:: P = OBP - [\\frac{(V-V_{0})}{a}]^{\\frac{1}{b}} """ ves = ((v * 3.2808300 - v0) / a)**(1.0 / b) pressure = obp - ves * 6894.75729 return pressure def eaton(v, vn, vesn, obp, a=0.785213, b=1.49683): """ Compute pore pressure using Eaton equation. Parameters ---------- v : 1-d ndarray velocity array whose unit is m/s. vn : 1-d ndarray normal velocity array whose unit is m/s. vesn : 1-d ndarray vertical effective stress under normal compaction array whose unit is m/s. obp : 1-d ndarray Overburden pressure whose unit is Pa. v0 : float, optional the velocity of unconsolidated regolith whose unit is ft/s. a : float, optional coefficient a b : float, optional coefficient b Notes ----- .. math:: P = OBP - VES_{n}* a (\\frac{V}{V_{n}})^{b} """ ves = vesn * a * (v / vn)**b pressure = obp - ves return pressure def fillipino(): pass def gardner(v, c, d): """ Convert velocity to density Parameters ---------- v : 1-d ndarray interval velocity array c : float, optional coefficient a d : float, optional coefficient d Returns ------- out : 1-d ndarray density array """ rho = c * v**d return rho if __name__ == '__main__': pass
{"/porepressureprediction/__init__.py": ["/porepressureprediction/velocity/basic/laSQL.py", "/porepressureprediction/velocity/basic/seiSQL.py", "/porepressureprediction/velocity/basic/survey.py", "/porepressureprediction/velocity/reader.py", "/porepressureprediction/stochastic/krig.py", "/porepressureprediction/velocity/conversion.py"]}
53,056
OverYoung/WidebandSatelliteFlowMonitor
refs/heads/master
/mail.py
#!/usr/bin/python3 # -*- coding: utf-8 -*- # @Time : 2018-11-09 11:18 # @Author : Yangzan # @File : main.py from email import encoders from email.header import Header from email.mime.text import MIMEText from email.utils import parseaddr, formataddr import smtplib import os import traceback import configparser def getMailConfig(logger): # --------------------------读取配置文件------------------------# try: # 拼接配置文件路径 logger.info('开始读取配置文件信息') localPath = os.getcwd() configPath = os.path.join(localPath, 'config/config.conf') configPath = os.path.abspath(configPath) # 获取配置文件信息 configFile = configparser.ConfigParser() configFile.read(configPath) logger.info('配置文件载入完成') mailConfig = [] mailConfig.append(configFile.get("mail", "mail_username")) mailConfig.append(configFile.get("mail", "mail_password")) mailConfig.append(configFile.get("mail", "smtp_server")) return mailConfig except Exception: logger.error('Exception occurred, check the error.log to read the detail') traceback.print_exc(limit=None, file=open('log/error.log', 'a+'), chain=True) def _format_addr(s): name, addr = parseaddr(s) return formataddr(( \ Header(name, 'utf-8').encode(), \ addr.encode('utf-8') if isinstance(addr, encoders.unicode) else addr)) from_addr = '' password = '' to_addr = 'yangzan@mail.bdsmc.net' smtp_server = '' msg = MIMEText('hello, send by Python...', 'plain', 'utf-8') msg['From'] = Header("菜鸟教程", 'utf-8') msg['To'] = Header("测试", 'utf-8') msg['Subject'] = Header(u'来自SMTP的问候……', 'utf-8').encode() server = smtplib.SMTP(smtp_server, 25) server.set_debuglevel(1) server.login(from_addr, password) server.sendmail(from_addr, [to_addr], msg.as_string()) server.quit()
{"/main.py": ["/log.py", "/configLoad.py", "/satelliteFlow.py", "/database.py"], "/satelliteFlow.py": ["/log.py"]}
53,057
OverYoung/WidebandSatelliteFlowMonitor
refs/heads/master
/log.py
#!/usr/bin/python3 # -*- coding: utf-8 -*- # @Time : 2018-11-07 10:58 # @Author : Yangzan # @File : log.py import logging import datetime import logging.handlers class myLogger(): #-----------------初始化日志类------------------# def __init__(self, loggerName): #创建一个logger self.logger = logging.getLogger(loggerName) self.logger.setLevel(logging.DEBUG) #创建一个handler用于写入所有级别的日志,使用TimedRotatingFileHandler可以实现日志按天进行切割 handler_all = logging.handlers.TimedRotatingFileHandler('log/all.log', when='midnight', interval=1, backupCount=7, encoding='utf-8', atTime=datetime.time(0, 0, 0, 0)) handler_all.setFormatter(logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")) #创建一个handler,用于写入Error级别的日志 handler_error = logging.FileHandler('log/error.log', encoding='utf-8') handler_error.setLevel(logging.ERROR) handler_error.setFormatter( logging.Formatter("%(asctime)s - %(levelname)s - %(filename)s[:%(lineno)d] - %(message)s")) self.logger.addHandler(handler_all) self.logger.addHandler(handler_error) # ----------------------------------------------# #-----------------插入不同类型的日志------------------# def debug(self, msg): self.logger.debug(msg) def info(self, msg): self.logger.info(msg) def warning(self, msg): self.logger.warning(msg) def error(self, msg): self.logger.error(msg) def critical(self, msg): self.logger.critical(msg)
{"/main.py": ["/log.py", "/configLoad.py", "/satelliteFlow.py", "/database.py"], "/satelliteFlow.py": ["/log.py"]}
53,058
OverYoung/WidebandSatelliteFlowMonitor
refs/heads/master
/configLoad.py
#!/usr/bin/python3 # -*- coding: utf-8 -*- # @Time : 2018-11-08 11:46 # @Author : Yangzan # @File : configLoad.py import os import configparser import traceback def getConfig(logger): # --------------------------读取配置文件------------------------# # 拼接配置文件路径 logger.info('开始读取配置文件信息') localPath = os.getcwd() configPath = os.path.join(localPath, 'config/config.conf') configPath = os.path.abspath(configPath) # 获取配置文件信息 configFile = configparser.ConfigParser() configFile.read(configPath, encoding='UTF-8') logger.info('配置文件载入完成') # 参数读取: try: # 网页相关参数 url = configFile.get("login", "loginUrl") xpath_username = configFile.get("xpath", "xpath_username") xpath_password = configFile.get("xpath", "xpath_password") xpath_verificationCodePic = configFile.get("xpath", "xpath_verificationCodePic") xpath_verificationCode = configFile.get("xpath", "xpath_verificationCode") xpath_loginButton = configFile.get("xpath", "xpath_loginButton") xpath_search = configFile.get("xpath", "xpath_search") xpath_package = configFile.get("xpath", "xpath_package") xpath_balance = configFile.get("xpath", "xpath_balance") xpath_spend = configFile.get("xpath", "xpath_spend") xpath_limit = configFile.get("xpath", "xpath_limit") xpath_logoff = configFile.get("xpath", "xpath_logoff") xpath_logoffconfirm = configFile.get("xpath", "xpath_logoffconfirm") # 数据库相关参数 dbhost = configFile.get("database", "host") dbport = configFile.getint("database", "port") db = configFile.get("database", "db") dbuser = configFile.get("database", "username") dbpasswd = configFile.get("database", "passwd") dbcharset = configFile.get("database", "charset") # 设置图片文件名 pic_name_login = 'loginPic' pic_name_code = 'codePic' config = [url, xpath_username, xpath_password, xpath_verificationCodePic, xpath_verificationCode, xpath_loginButton, xpath_search, xpath_package, xpath_balance, xpath_spend, xpath_limit, xpath_logoff, xpath_logoffconfirm, pic_name_login, pic_name_code, dbhost, dbport, db, dbuser, dbpasswd, dbcharset] return config except Exception: logger.error('Exception occurred, check the error.log to read the detail') traceback.print_exc(limit=None, file=open('log/error.log', 'a+'), chain=True) logger.info('配置文件信息读取完毕')
{"/main.py": ["/log.py", "/configLoad.py", "/satelliteFlow.py", "/database.py"], "/satelliteFlow.py": ["/log.py"]}
53,059
OverYoung/WidebandSatelliteFlowMonitor
refs/heads/master
/main.py
#!/usr/bin/python3 # -*- coding: utf-8 -*- # @Time : 2018-11-08 11:18 # @Author : Yangzan # @File : main.py import time import log import traceback import configLoad import satelliteFlow import database #初始化log对象 logger = log.myLogger('log') logger.info('程序启动') localtime = time.localtime(time.time()) localhour = localtime.tm_hour localmin = localtime.tm_min localsec = localtime.tm_sec #每六小时进行一次查询 while True: #只有整点进行查询 if localhour % 11 == 0 and localmin == 21 and localsec >=0 and localsec <=50: # 读取配置文件信息 config = configLoad.getConfig(logger) print(config) dbhost = config[15] dbport = config[16] db = config[17] dbuser = config[18] dbpasswd = config[19] dbcharset = config[20] url = config[0] # 启动浏览器 driver = satelliteFlow.startBrowser(url, logger) accountNum = 0 accountusername = [] accountpassword = [] #从数据库获取卫通的账号 try: dbConn = database.DBconnect(dbhost, dbuser, dbpasswd, db, dbport, dbcharset) logger.info('连接数据库完成') dbCur = dbConn.cursor() sql = "SELECT `id`, `username`, `password` FROM Account;" dbCur.execute(sql) dbConn.commit() account = dbCur.fetchall() accountNum = dbCur.rowcount for num in range(0, accountNum): accountusername.append(account[num][1]) accountpassword.append(account[num][2]) database.DBclose(dbConn, dbCur) logger.info('与数据库断开连接') except Exception: logger.error('Exception occurred, check the error.log to read the detail') traceback.print_exc(limit=None, file=open('log/error.log', 'a+'), chain=True) logger.error('发生错误,终止本次循环') continue #循环获取每一个账号的流量情况 for num in range(0, accountNum): username = accountusername[num] password = accountpassword[num] #流量情况获取 data = satelliteFlow.search(driver, config, username, password, logger) #print(data) #插入数据至数据库 try: dbConn = database.DBconnect(dbhost, dbuser, dbpasswd, db, dbport, dbcharset) logger.info('连接数据库完成') dbCur = dbConn.cursor() sql = "insert into Flow(`accountId`, `package`, `limit`, `spend`, `balance`) values(%s, %s, %s, %s, %s);" try: dbCur.execute(sql, data) dbConn.commit() logger.info('数据插入完成') except Exception: # 发生错误进行回滚 dbConn.rollback() database.DBclose(dbConn, dbCur) logger.info('与数据库断开连接') except Exception: logger.error('Exception occurred, check the error.log to read the detail') traceback.print_exc(limit=None, file=open('log/error.log', 'a+'), chain=True) logger.error('发生错误,终止本次循环') continue else: print('未达到查询执行条件:每六小时准点执行一次') pass #更新时间 localtime = time.localtime(time.time()) localhour = localtime.tm_hour localmin = localtime.tm_min localsec = localtime.tm_sec #还需要添加邮件提醒
{"/main.py": ["/log.py", "/configLoad.py", "/satelliteFlow.py", "/database.py"], "/satelliteFlow.py": ["/log.py"]}
53,060
OverYoung/WidebandSatelliteFlowMonitor
refs/heads/master
/database.py
#!/usr/bin/python3 # -*- coding: utf-8 -*- # @Time : 2018-11-07 9:59 # @Author : Yangzan # @File : database.py import pymysql import traceback import configparser def DBconnect(host, user, passwd, db, port, charset): conn = pymysql.connect(host=host, user=user, passwd=passwd, db=db, port=port, charset=charset) return conn def DBclose(conn, cur): cur.close() conn.close()
{"/main.py": ["/log.py", "/configLoad.py", "/satelliteFlow.py", "/database.py"], "/satelliteFlow.py": ["/log.py"]}
53,061
OverYoung/WidebandSatelliteFlowMonitor
refs/heads/master
/satelliteFlow.py
#!/usr/bin/python3 # -*- coding: utf-8 -*- # @Time : 2018-11-06 11:08 # @Author : Yangzan # @File : satelliteFlow.py import time import pytesseract from selenium import webdriver from PIL import Image import configparser import os import traceback import log def startBrowser(url, logger): # 浏览器设置 logger.info('启动浏览器') try: driver = webdriver.Chrome() # Optional argument, if not specified will search path. driver.maximize_window() logger.info('浏览器窗口最大化') driver.get(url) logger.info('进入登录网页') except Exception: logger.error('Exception occurred, check the error.log to read the detail') traceback.print_exc(limit=None, file=open('log/error.log', 'a+'), chain=True) return driver def search(driver, config, username, password, logger): url = config[0] xpath_username = config[1] xpath_password = config[2] xpath_verificationCodePic = config[3] xpath_verificationCode = config[4] xpath_loginButton = config[5] xpath_search = config[6] xpath_package = config[7] xpath_balance = config[8] xpath_spend = config[9] xpath_limit = config[10] xpath_logoff = config[11] xpath_logoffconfirm = config[12] pic_name_login = config[13] pic_name_code = config[14] # 输入用户名和密码 try: find_username = driver.find_element_by_xpath(xpath_username) find_username.send_keys(username) time.sleep(1) logger.info('输入用户名完成') find_password = driver.find_element_by_xpath(xpath_password) find_password.send_keys(password) time.sleep(1) logger.info('输入密码完成') except Exception: logger.error('Exception occurred, check the error.log to read the detail') traceback.print_exc(limit=None, file=open('log/error.log', 'a+'), chain=True) # 找出验证码 try: find_verificationCodePic = driver.find_element_by_xpath(xpath_verificationCodePic) left = find_verificationCodePic.location['x'] # 找出验证码的位置 top = find_verificationCodePic.location['y'] right = find_verificationCodePic.location['x'] + find_verificationCodePic.size['width'] bottom = find_verificationCodePic.location['y'] + find_verificationCodePic.size['height'] logger.info('寻找验证码及确定图片大小完成') driver.save_screenshot(pic_name_login + '.png') # 全屏截图 logger.info('全屏截图并保存图片') im = Image.open(pic_name_login + '.png') im = im.crop((left, top, right, bottom)) im.save(pic_name_code + '.png') logger.info('在截取的全屏图片中截取验证码图片') verificationCode = pytesseract.image_to_string(im) # 识别验证码 logger.info('验证码识别完成') except Exception: logger.error('Exception occurred when find the position of verification code') traceback.print_exc(limit=None, file=open('log/error.log', 'a+'), chain=True) # 输入验证码并登录 try: find_verificationCode = driver.find_element_by_xpath(xpath_verificationCode) find_verificationCode.send_keys(verificationCode) logger.info('输入验证码完成') find_login = driver.find_element_by_xpath(xpath_loginButton) find_login.click() logger.info('登录成功') time.sleep(1) except Exception: logger.error('Exception occurred when input the verification code') traceback.print_exc(limit=None, file=open('log/error.log', 'a+'), chain=True) # 进入查询界面 try: find_search = driver.find_element_by_xpath(xpath_search) find_search.click() time.sleep(1) logger.info('进入查询页面') except Exception: logger.error('Exception occurred, check the error.log to read the detail') traceback.print_exc(limit=None, file=open('log/error.log', 'a+'), chain=True) time.sleep(2) package = driver.find_element_by_xpath(xpath_package).text # 套餐 limit = driver.find_element_by_xpath(xpath_limit).text # 总额 limit = float(limit[:-2]) spend = driver.find_element_by_xpath(xpath_spend).text # 已消费 spend = float(spend[:-2]) balance = driver.find_element_by_xpath(xpath_balance).text # 剩余流量 balance = float(balance[:-2]) time.sleep(2) # Let the user actually see something! logger.info('读取流量信息完成') data = [] data.append(1) data.append(package) data.append(limit) data.append(spend) data.append(balance) # 注销账号 try: time.sleep(1) find_logoff = driver.find_element_by_xpath(xpath_logoff) find_logoff.click() logger.info('准备注销账号') time.sleep(1) find_logoffconfirm = driver.find_element_by_xpath(xpath_logoffconfirm) find_logoffconfirm.click() logger.info('账号注销完成') # 新开一个窗口,通过执行js来新开一个窗口打开卫通登录页 js = 'window.open("'+url+'");' driver.execute_script(js) #关闭第一个窗口 handles = driver.window_handles driver.switch_to_window(handles[0]) driver.close() logger.info('标签页已关闭') #刷新窗口信息并切换到当前的第一个标签页 handles = driver.window_handles driver.switch_to_window(handles[0]) time.sleep(1) except Exception: logger.error('Exception occurred, check the error.log to read the detail') traceback.print_exc(limit=None, file=open('log/error.log', 'a+'), chain=True) return data def stopBrowser(driver, logger): time.sleep(2) driver.quit() logger.info('浏览器已退出')
{"/main.py": ["/log.py", "/configLoad.py", "/satelliteFlow.py", "/database.py"], "/satelliteFlow.py": ["/log.py"]}
53,171
pyarun/djsaas
refs/heads/master
/code/dbmail/mail.py
''' Created on 07-May-2012 @author: arun ''' from django.core.mail import EmailMultiAlternatives, mail_admins, mail_managers from django.template.loader import get_template from django.template import Context, Template from django.conf import settings from models import MailTemplate class DbSendMail: """ Manager for sending preset mails """ def __init__( self, mail_code ): self.mail = MailTemplate.objects.get( code=mail_code ) def sendmail(self, recipient_list, context, bcc=None, cc=None): """ @recipient_list: recievers email addresses context: dict. values to be updated in template """ self._feed_mail_contents( context ) subject = self.mail.subject from_email = self.mail.sender or settings.DEFAULT_FROM_EMAIL msg = EmailMultiAlternatives( subject, self.plain_content, from_email, recipient_list ,bcc=bcc, cc=cc) if self.html_content: msg.attach_alternative( self.html_content, "text/html" ) msg.send() def _feed_mail_contents( self, context ): plain_content = Template( self.mail.plain_content ) self.plain_content = plain_content.render( Context( context ) ) if self.mail.html_content: html_content = Template( self.mail.html_content ) self.html_content = html_content.render( Context( context ) ) else: self.html_content = None def mail_admins( self, context ): self._feed_mail_contents( context ) subject = self.mail.subject # from_email = self.mail.sender msg = self.plain_content mail_admins( subject, msg ) def mail_managers( self, context ): self._feed_mail_contents( context ) subject = self.mail.subject # from_email = self.mail.sender msg = self.plain_content mail_managers( subject, msg )
{"/code/registration/views.py": ["/code/registration/forms.py"], "/code/registration/forms.py": ["/code/registration/models.py"], "/code/registration/urls.py": ["/code/registration/views.py"]}
53,172
pyarun/djsaas
refs/heads/master
/code/saas/middleware.py
''' Created on 24-Jun-2013 @author: arun ''' from django.utils.functional import SimpleLazyObject from django.contrib.sites.models import RequestSite from saas.models import Tenant class OrganizationMiddleware(object): def process_request(self, request): request.tenant = SimpleLazyObject(lambda: self.get_tenant(request)) def get_tenant(self, request): if not hasattr(request, "_cached_tenant"): request._cached_tenant = self._get_tenant(request) return request._cached_tenant def _get_tenant(self, request): site = RequestSite(request) subdomain = self._get_subdomain(site) try: tenant = Tenant.objects.get(domain_name=subdomain) except Tenant.DoesNotExist: tenant = None return tenant def _get_subdomain(self, site): """ Takes site object as argument. if the current request is being made from sub-domain(tenant) then this will extract the subdomain name, else None """ splited_domain_name = site.domain.split(".") subdomain = splited_domain_name[0] if len(splited_domain_name) >=3 else "" return subdomain
{"/code/registration/views.py": ["/code/registration/forms.py"], "/code/registration/forms.py": ["/code/registration/models.py"], "/code/registration/urls.py": ["/code/registration/views.py"]}
53,173
pyarun/djsaas
refs/heads/master
/code/registration/views.py
# Create your views here. from django.views.generic import FormView, TemplateView from .forms import RegistrationForm from django.core.urlresolvers import reverse_lazy from django.contrib.auth import get_user_model User = get_user_model() class RegistrationView(FormView): template_name = "registration_form.html" def get_form_class(self): return RegistrationForm def form_valid(self, form): self._profile = form.register_tenant() return FormView.form_valid(self, form) def get_success_url(self): return reverse_lazy("registration_thankyou", args=(self._profile.user.pk)) class RegistrationThankyouTemplateView(TemplateView): template_name = "registration_thankyoupage.html" def get_context_data(self, **kwargs): kwargs = TemplateView.get_context_data(self, **kwargs) userpk = kwargs["userpk"] kwargs["user_obj"] = User.objects.get(pk=userpk) return kwargs
{"/code/registration/views.py": ["/code/registration/forms.py"], "/code/registration/forms.py": ["/code/registration/models.py"], "/code/registration/urls.py": ["/code/registration/views.py"]}
53,174
pyarun/djsaas
refs/heads/master
/code/dbmail/models.py
from django.db import models # Create your models here. class MailTemplate( models.Model ): """ Templates for Mails --fields-- code: unique string-value to access the record. title: human readable name for the mail template subject: Subject for the mail plain_content: plain text content of the mail html_content: Alternative html based content for mail sender: email address to be user to send mail using this template, if empty mail is sent using settings.EMAIL_HOST_USER context: list of context variables that can be used in Content Body """ code = models.CharField( max_length=5, unique=True, help_text="To be used by developers" ) title = models.CharField( max_length=50, help_text="Human readable name of the template" ) subject = models.CharField( max_length=200, help_text="Subject for the mail(max:200 Characters)" ) plain_content = models.TextField( blank=True, null=True, help_text="Content of the mail") html_content = models.TextField( blank=True, null=True, help_text="HTML version of Content" ) sender = models.EmailField(blank=True, null=True) context = models.TextField(blank=True, null=True, help_text="Values listed here can be used in Content body as django template variables. Values will be set from the current context. Example usage: {{name}}") def __unicode__( self ): return self.code
{"/code/registration/views.py": ["/code/registration/forms.py"], "/code/registration/forms.py": ["/code/registration/models.py"], "/code/registration/urls.py": ["/code/registration/views.py"]}
53,175
pyarun/djsaas
refs/heads/master
/code/registration/models.py
from django.db import models from django.contrib.auth import get_user_model # Create your models here. import hashlib, random User = get_user_model() class RegistrationProfileManager(models.Manager): def create_profile(self, user): """ """ salt = hashlib.sha1(str(random.random())).hexdigest()[:5] activation_key = hashlib.sha1(user.email+salt).hexdigest() profile = self.create(user=user, activation_key=activation_key) return profile class RegistrationProfile(models.Model): """ Profile to store activation key for use during account registrations """ activation_key = models.CharField(max_length=100) user = models.ForeignKey(User) objects = RegistrationProfileManager()
{"/code/registration/views.py": ["/code/registration/forms.py"], "/code/registration/forms.py": ["/code/registration/models.py"], "/code/registration/urls.py": ["/code/registration/views.py"]}
53,176
pyarun/djsaas
refs/heads/master
/code/registration/forms.py
''' Created on 26-Jun-2013 @author: arun ''' from django import forms from django.utils.translation import ugettext, ugettext_lazy as _ from saas.models import Tenant, User from django.core.exceptions import ValidationError from .models import RegistrationProfile from django.conf import settings def unique_domain_name_validator(value): if Tenant.objects.filter(domain_name=value).exists(): raise ValidationError("{} is already used. Please choose different Domain Name".format(value)) def unique_email_validator(value): if User.objects.filter(email=value).exists(): raise ValidationError("User already registered with email {}. Please use different email".format(value)) class RegistrationForm(forms.Form): """ To be Used for tenant Registrations """ _manager_role = "tmanager" name = forms.CharField(label=_("Company Name"), max_length=25, required=True, help_text=_("Name of the Company")) email = forms.EmailField(label=_("Email"), required =True, validators=[unique_email_validator]) domain_name = forms.CharField(_('Subdomain'), required=True, validators=[unique_domain_name_validator], help_text=_("Subdomain name to be used for setting up customized access url.")) address = forms.CharField(max_length=150, ) phone = forms.CharField(max_length=15) def _generate_password(self): """ Returns a randome string of six characters as password """ import random, string return "".join( random.sample(string.letters+string.digits, 6)) def register_tenant(self): """ Create a Tenant Record and send a verification mail to Manager """ if hasattr(self, "cleaned_data"): data = self.cleaned_data tenant = Tenant() for k,v in data.items(): if hasattr(tenant, k): setattr(tenant, k, v) tenant.save() manager = User.objects.create_user(data["email"], self._manager_role, self._generate_password()) tenant.users.add(manager) tenant.save() #create profile profile = RegistrationProfile.objects.create_profile(manager) self.send_activation_mail(profile) return profile else: raise RuntimeError( "Its required to call form's is_valid method before a call to register_tenant") def send_activation_mail(self, profile): """ Send a mail to tenant manager with a link to activate the account """ if "dbmail" in settings.INSTALLED_APPS: from dbmail.mail import DbSendMail mailer = DbSendMail("TAAM") context = dict(name=profile.user.get_full_name(), activation_key=profile.activation_key) mailer.sendmail([profile.user.email], context) else: from django.core.exceptions import ImproperlyConfigured ImproperlyConfigured("to Use mail service, its required to install dbmail app. Download from {}".format("https://bitbucket.org/pyarun/dbmail", )) # profile.user.email_user(subject, message)
{"/code/registration/views.py": ["/code/registration/forms.py"], "/code/registration/forms.py": ["/code/registration/models.py"], "/code/registration/urls.py": ["/code/registration/views.py"]}
53,177
pyarun/djsaas
refs/heads/master
/code/registration/urls.py
''' Created on 24-Jun-2013 @author: arun ''' from django.conf.urls import patterns, include, url from .views import RegistrationView, RegistrationThankyouTemplateView urlpatterns = patterns("", url('^register$', RegistrationView.as_view(), name="tenant_registration_form"), url('^register/thanks/(?P<userpk>\d*)$', RegistrationThankyouTemplateView.as_view(), name="registration_thankyou"), )
{"/code/registration/views.py": ["/code/registration/forms.py"], "/code/registration/forms.py": ["/code/registration/models.py"], "/code/registration/urls.py": ["/code/registration/views.py"]}
53,178
pyarun/djsaas
refs/heads/master
/code/dbmail/migrations/0001_initial.py
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'MailTemplate' db.create_table(u'dbmail_mailtemplate', ( (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('code', self.gf('django.db.models.fields.CharField')(unique=True, max_length=5)), ('title', self.gf('django.db.models.fields.CharField')(max_length=50)), ('subject', self.gf('django.db.models.fields.CharField')(max_length=200)), ('plain_content', self.gf('django.db.models.fields.TextField')(null=True, blank=True)), ('html_content', self.gf('django.db.models.fields.TextField')(null=True, blank=True)), ('sender', self.gf('django.db.models.fields.EmailField')(max_length=75, null=True, blank=True)), ('context', self.gf('django.db.models.fields.TextField')(null=True, blank=True)), )) db.send_create_signal(u'dbmail', ['MailTemplate']) def backwards(self, orm): # Deleting model 'MailTemplate' db.delete_table(u'dbmail_mailtemplate') models = { u'dbmail.mailtemplate': { 'Meta': {'object_name': 'MailTemplate'}, 'code': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '5'}), 'context': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'html_content': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'plain_content': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'sender': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'null': 'True', 'blank': 'True'}), 'subject': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '50'}) } } complete_apps = ['dbmail']
{"/code/registration/views.py": ["/code/registration/forms.py"], "/code/registration/forms.py": ["/code/registration/models.py"], "/code/registration/urls.py": ["/code/registration/views.py"]}
53,179
pyarun/djsaas
refs/heads/master
/code/saas/views.py
# Create your views here. from django.views.decorators.debug import sensitive_post_parameters from django.views.decorators.csrf import csrf_protect from django.views.decorators.cache import never_cache from django.contrib.auth import REDIRECT_FIELD_NAME , login as auth_login from django.shortcuts import resolve_url from django.utils.http import is_safe_url from django.conf import settings from django.http import HttpResponseRedirect from django.template.response import TemplateResponse from django.contrib.sites.models import get_current_site from saas.forms import SaasAuthenticationForm @sensitive_post_parameters() @csrf_protect @never_cache def login(request, template_name='client_login.html', redirect_field_name=REDIRECT_FIELD_NAME, authentication_form=SaasAuthenticationForm, current_app=None, extra_context=None): """ Displays the login form and handles the login action. """ redirect_to = request.REQUEST.get(redirect_field_name, '') if request.method == "POST": form = authentication_form(request, data=request.POST) if form.is_valid(): # Ensure the user-originating redirection url is safe. if not is_safe_url(url=redirect_to, host=request.get_host()): redirect_to = resolve_url(settings.LOGIN_REDIRECT_URL) # Okay, security check complete. Log the user in. auth_login(request, form.get_user()) if request.session.test_cookie_worked(): request.session.delete_test_cookie() return HttpResponseRedirect(redirect_to) else: form = authentication_form(request) request.session.set_test_cookie() current_site = get_current_site(request) context = { 'form': form, redirect_field_name: redirect_to, 'site': current_site, 'site_name': current_site.name, } if extra_context is not None: context.update(extra_context) return TemplateResponse(request, template_name, context, current_app=current_app)
{"/code/registration/views.py": ["/code/registration/forms.py"], "/code/registration/forms.py": ["/code/registration/models.py"], "/code/registration/urls.py": ["/code/registration/views.py"]}
53,180
pyarun/djsaas
refs/heads/master
/code/saas/admin.py
''' Created on 19-Jun-2013 @author: arun ''' from django.contrib import admin, auth from django.utils.translation import ugettext, ugettext_lazy as _ from django import forms from django.db import models from saas.models import User, Tenant, TenantAccountManager from django.contrib.admin.options import TabularInline from saas import forms as saas_forms class SaasUserAdmin(auth.admin.UserAdmin): readonly_fields = ('last_login',) form = saas_forms.UserChangeForm add_form = saas_forms.UserCreationForm fieldsets = ( (None, {'fields': ('email', 'password')}), (_('Personal info'), {'fields': (('first_name', 'last_name'), 'avatar')}), (_('Permissions'), {'fields': ('role', 'is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions')}), (_('Important dates'), {'fields': ('last_login', 'date_joined')}), ) add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('email', 'role', 'password1', 'password2')} ), ) # form = UserChangeForm # add_form = UserCreationForm # change_password_form = AdminPasswordChangeForm list_display = ('email', 'first_name', 'last_name','role', 'is_staff') list_filter = ('is_staff', 'is_superuser', 'is_active', 'groups') search_fields = ('first_name', 'last_name', 'email') ordering = ('email', 'role') filter_horizontal = ('groups', 'user_permissions',) # fieldsets = auth.admin.UserAdmin.fieldsets + (("abc", {'fields': ('role', 'avatar')}),) # add_fieldsets = ((None, {'fields':('email', 'role', 'password1', 'password2')}),) admin.site.register( User, SaasUserAdmin) # class TenantManagerAdmin(SaasUserAdmin): # # # # fields = ( ( "first_name", "last_name"), # # ( "email", "password"), # # ( "username","groups",), # # ( "avatar", "role",), # # ) # # readonly_fields = ('last_login','date_joined', 'username') # # # formfield_overrides = { # # models.CharField: {'widget': forms.Select(attrs={"disabled":"disabled"})}, # # } # # form = saas_forms.UserChangeForm # add_form = saas_forms.UserCreationForm # # def get_form(self, request, obj=None, **kwargs): # """ # Override the base function to set the Role as Tenant Manager # """ # form = SaasUserAdmin.get_form(self, request, obj=obj, **kwargs) # try: # form.base_fields["role"].initial = "tmanager" # except: # pass # this is an add form # return form # # # def queryset(self, request): # # """ # # Returns Users Who are account managers # # """ # # qs = super(TenantManagerAdmin, self).queryset(request) # # return qs.filter(role="tmanager") # # # admin.site.register(TenantAccountManager, TenantManagerAdmin) # class TenantManagerInlineForm(forms.ModelForm): fields = ("username", "email", "password") class UserTabularInline(admin.TabularInline): model = Tenant.users.through extra = 1 max_num = 1 def formfield_for_manytomany(self, db_field, request=None, **kwargs): if db_field.name == "users": kwargs["queryset"] = User.objects.filter(role="tmanager") return admin.TabularInline.formfield_for_manytomany(self, db_field, request=request, **kwargs) class TenantAdmin(admin.ModelAdmin): pass # inlines = [ # UserTabularInline, # ] admin.site.register( Tenant, TenantAdmin)
{"/code/registration/views.py": ["/code/registration/forms.py"], "/code/registration/forms.py": ["/code/registration/models.py"], "/code/registration/urls.py": ["/code/registration/views.py"]}
53,181
pyarun/djsaas
refs/heads/master
/code/accounts/views.py
# Create your views here. from django.shortcuts import render from django.contrib.sites.models import RequestSite def user_home(request): """ Renders Users home page. Content will be based on the permissions users have on the tenant data """ context = dict() return render(request, 'user_home.html', context)
{"/code/registration/views.py": ["/code/registration/forms.py"], "/code/registration/forms.py": ["/code/registration/models.py"], "/code/registration/urls.py": ["/code/registration/views.py"]}
53,182
pyarun/djsaas
refs/heads/master
/code/saas/models.py
from django.db import models # Create your models here. from django.contrib import auth from django.db.models.signals import post_save, pre_save from django.dispatch import receiver from django.utils.translation import ugettext_lazy as _ import string, random from django.utils import timezone from django.core.mail import send_mail ROLES = ( ( "dev-admin", _("Developer Admin")), ( "superadmin", _("Super Admin")), ( "tmanager", _("Tenant Manager")), ( "tadmin", _("Tenant Admin")), ( "user", _("User")) ) # from django.db.models.signals import class_prepared # @receiver(class_prepared) # def set_default_username(sender, **kwargs): # """ # This function is a reciever of class_prepared signal. # It is used to set the default value for username, in User Table. # Username is a unique and dynamically generated key. Whenever a new user instance is created, # a unique username is set by default. # """ # def generate_new_username(): # while True: # sample = "".join(random.sample(string.letters.lower() + string.digits, 6)) # if not User.objects.filter(username = sample).exists():break # return sample # # if sender.__name__ == "User" and sender.__module__== __name__: # sender._meta.get_field("username").default = generate_new_username class SaasUserManager(auth.models.BaseUserManager): def create_user(self, email, role, password=None, **extra_fields): """ Creates and saves a User with the given username, email and password. """ now = timezone.now() if not email: raise ValueError('The given email must be set') email = SaasUserManager.normalize_email(email) user = self.model(email=email, role=role, is_staff=False, is_active=True, is_superuser=False, last_login=now, date_joined=now, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password, **extra_fields): role = extra_fields.pop("role", 'user') if extra_fields.has_key("role") else "user" u = self.create_user( email, role, password, **extra_fields) u.is_staff = True u.is_active = True u.is_superuser = True u.save(using=self._db) return u class User(auth.models.AbstractBaseUser, auth.models.PermissionsMixin): first_name = models.CharField(_('first name'), max_length=30, blank=True) last_name = models.CharField(_('last name'), max_length=30, blank=True) email = models.EmailField(_('email address'), blank=True, unique=True) avatar = models.ImageField(upload_to="avatar", blank=True, null=True) role = models.CharField(max_length=15, choices=ROLES) is_staff = models.BooleanField(_('staff status'), default=False, help_text=_('Designates whether the user can log into this admin ' 'site.')) is_active = models.BooleanField(_('active'), default=True, help_text=_('Designates whether this user should be treated as ' 'active. Unselect this instead of deleting accounts.')) date_joined = models.DateTimeField(_('date joined'), default=timezone.now) objects = SaasUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [ 'role'] class Meta: verbose_name = _('user') verbose_name_plural = _('users') objects = SaasUserManager() def get_full_name(self): """ Returns the first_name plus the last_name, with a space in between. """ full_name = '%s %s' % (self.first_name, self.last_name) return full_name.strip() def get_short_name(self): "Returns the short name for the user." return self.first_name def email_user(self, subject, message, from_email=None): """ Sends an email to this User. """ send_mail(subject, message, from_email, [self.email]) def is_tmanager(self): """ returns True if the given users Role is tmanager """ return self.role == "tmanager" #Classes for Tenant's Account Manager class TenantAccountManagers_Manager(SaasUserManager): def get_query_set(self): queryset = SaasUserManager.get_query_set(self) return queryset.filter(role="tmanager") class TenantAccountManager(User): objects = TenantAccountManagers_Manager() class Meta: proxy=True #Classes for Tenant Records class TenantModelManager(models.Manager): def create_tenant_manager(self, sender, **kwargs): """ creates a tenant manager user and adds to the tenant """ is_created = kwargs.get("created") instance = kwargs.get("instance") if is_created: data_set = dict(username="{}-admin".format(instance.name), email="admin@some.com", password="12345") tadmin = User.objects.create_user(**data_set) instance.users.add(tadmin) def create_tenant(self): """ Create/Add a Tenant Manager Associate a Manager to Tenant Create a Group Set Permissions to the Group """ def generate_unique_slug(): while True: slug = "".join(random.sample(string.letters, 6)) if not Tenant.objects.filter(slug=slug).exists(): break return slug def logo_storage(obj, filename): """ generates unique path for logo storage """ return "{}/logo/{}".format(obj.slug, filename) class Tenant(models.Model): """ Holds Basic Information about the Tenant for SaaS application. This model should hold very basic information that can be used with any type of SAAS application. For Detailed Product(application) specific information about the tenant, its recommended to add a TenantProfile Model, Just like we have User and UserProfile Relation When a Tenant is created, a Tenant owner account should also be created """ name = models.CharField( max_length=50, help_text="Company's Display Name", db_index=True) logo = models.ImageField( upload_to=logo_storage, blank=True, null=True) domain_name = models.CharField( max_length=25, unique=True, help_text="Domain Name to be set", db_index=True) active = models.BooleanField( default=False) users = models.ManyToManyField( User, blank=True, null=True) slug = models.SlugField( max_length=6, default=generate_unique_slug, db_index=True, unique=True ) objects = TenantModelManager() def __unicode__(self): return "{}-{}".format(self.name, self.slug)
{"/code/registration/views.py": ["/code/registration/forms.py"], "/code/registration/forms.py": ["/code/registration/models.py"], "/code/registration/urls.py": ["/code/registration/views.py"]}
53,183
pyarun/djsaas
refs/heads/master
/code/dbmail/admin.py
from django.contrib import admin from models import MailTemplate class MailTemplateAdmin(admin.ModelAdmin): list_display = ("code", "title", "sender") # fields = ('code', 'title', 'sender', 'subject', 'context', 'plain_content', 'html_content') # field_options = { # "fields": (('code', 'title'), 'sender', 'subject', 'context', 'plain_content', 'html_content') # } # fieldsets = ((None, {"fields": (('code', 'title'),)} ), ("Details", {"fields": ('sender', 'subject', 'context', 'plain_content', 'html_content')}), ) admin.site.register(MailTemplate, MailTemplateAdmin)
{"/code/registration/views.py": ["/code/registration/forms.py"], "/code/registration/forms.py": ["/code/registration/models.py"], "/code/registration/urls.py": ["/code/registration/views.py"]}
53,184
pyarun/djsaas
refs/heads/master
/code/accounts/urls.py
''' Created on 24-Jun-2013 @author: arun ''' from django.conf.urls import patterns, include, url urlpatterns = patterns("", url("^home$", "accounts.views.user_home", name="user_home_page"), # url("^login$", "accounts.views.client_login", name="client_login"), # # url("^dlogin$", "saas.views.login", {"template_name":"client_login.html", "authentication_form":SaasAuthenticationForm}, name="dlogin") )
{"/code/registration/views.py": ["/code/registration/forms.py"], "/code/registration/forms.py": ["/code/registration/models.py"], "/code/registration/urls.py": ["/code/registration/views.py"]}
53,186
initrc/myhadoop
refs/heads/master
/MyHadoop/myhadoop/utils/hadoopfile.py
''' Created on Dec 10, 2011 @author: david ''' import os import tempfile import shutil import subprocess import time from django.conf import settings class HadoopFile(object): ''' upload files ''' def __init__(self, source): ''' constructor ''' self.source = source self.APP_DIR = os.path.realpath(os.path.join(settings.PROJECT_PATH, "myhadoop")) self.INPUT_DIR = os.path.realpath(os.path.join(self.APP_DIR, "input")) self.OUTPUT_DIR = os.path.realpath(os.path.join(self.APP_DIR, "static", "output")) self.SCRIPT = os.path.realpath(os.path.join(self.APP_DIR, "scripts", "hadoop.sh")) def execute(self): _, filepath = tempfile.mkstemp(prefix=self.source.name, dir=self.INPUT_DIR) with open(filepath, 'wb') as dest: shutil.copyfileobj(self.source, dest) print(filepath) print(self.OUTPUT_DIR) # call script filename = os.path.basename(filepath) + ".tar.gz" subprocess.call([self.SCRIPT, filename, filepath, self.OUTPUT_DIR]) # check if output file has been created while not os.path.exists(os.path.join(self.OUTPUT_DIR, filename)): time.sleep(1) result = filename return result
{"/MyHadoop/myhadoop/views.py": ["/MyHadoop/myhadoop/utils/hadoopfile.py"]}
53,187
initrc/myhadoop
refs/heads/master
/MyHadoop/myhadoop/urls.py
from django.conf.urls.defaults import patterns, url urlpatterns = patterns('myhadoop.views', url(r'^$', 'index'), url(r'^upload/$', 'upload'), url(r'^result/$', 'result'), )
{"/MyHadoop/myhadoop/views.py": ["/MyHadoop/myhadoop/utils/hadoopfile.py"]}
53,188
initrc/myhadoop
refs/heads/master
/MyHadoop/myhadoop/views.py
from django.shortcuts import render_to_response from MyHadoop.myhadoop.utils.hadoopfile import HadoopFile from django.template.context import RequestContext from django.http import Http404 def index(request): return render_to_response('myhadoop/index.html', context_instance=RequestContext(request)) def upload(request): if request.method == 'POST': if 'file' not in request.FILES: return render_to_response('myhadoop/error.html', {'msg': "No file is uploaded"}, context_instance=RequestContext(request)) hadoopfile = HadoopFile(request.FILES['file']) result = hadoopfile.execute() return render_to_response('myhadoop/result.html', {'result': result}, context_instance=RequestContext(request)) else: raise Http404
{"/MyHadoop/myhadoop/views.py": ["/MyHadoop/myhadoop/utils/hadoopfile.py"]}
53,192
AbhishekPednekar84/personal-portfolio
refs/heads/master
/browser_automation/pages/contact_page.py
from browser_automation.pages.base_page import BasePage from browser_automation.pages.base_element import BaseElement from selenium.webdriver.common.by import By from browser_automation.pages.locator import Locator class ContactPage(BasePage): url = "https://www.abhishekpednekar.com/contact" @property def name_input(self): locator = Locator(by=By.CSS_SELECTOR, value="input#username") return BaseElement(driver=self.driver, locator=locator) @property def email_input(self): locator = Locator(by=By.CSS_SELECTOR, value="input#email") return BaseElement(driver=self.driver, locator=locator) @property def subject_input(self): locator = Locator(by=By.CSS_SELECTOR, value="input#subject") return BaseElement(driver=self.driver, locator=locator) @property def message_input(self): locator = Locator(by=By.CSS_SELECTOR, value="textarea#message") return BaseElement(driver=self.driver, locator=locator) @property def submit_button(self): locator = Locator(by=By.CSS_SELECTOR, value="input#submit") return BaseElement(driver=self.driver, locator=locator)
{"/browser_automation/pages/contact_page.py": ["/browser_automation/pages/base_page.py", "/browser_automation/pages/base_element.py", "/browser_automation/pages/locator.py"], "/browser_automation/pages/home_page.py": ["/browser_automation/pages/base_page.py", "/browser_automation/pages/base_element.py", "/browser_automation/pages/locator.py"], "/views/blog.py": ["/models/blog.py", "/app.py"], "/browser_automation/pages/portfolio_page.py": ["/browser_automation/pages/base_element.py", "/browser_automation/pages/base_page.py", "/browser_automation/pages/locator.py"], "/utilities/tasks.py": ["/celery_app.py"], "/app.py": ["/config.py", "/api/search.py"], "/views/contact.py": ["/forms/contact.py", "/utilities/tasks.py", "/app.py"], "/views/portfolio.py": ["/app.py"], "/browser_automation/automation_tests.py": ["/browser_automation/pages/home_page.py", "/browser_automation/pages/portfolio_page.py", "/browser_automation/pages/contact_page.py", "/browser_automation/__init__.py"], "/tests/test_app.py": ["/models/blog.py", "/app.py", "/config.py"], "/api/search.py": ["/models/blog.py"]}
53,193
AbhishekPednekar84/personal-portfolio
refs/heads/master
/browser_automation/__init__.py
import random # Test data for the contact page first_names = [ "Hilary", "Alfie", "Elna", "Emalia", "Hermine", "Pansie", "Brigitte", "Vanda", "Chalmers", "Maurine", "Lazar", "Jilly", "Lenore", "Waylen", "Daphne", "Corri", "Ody", "Skippy", "Feliza", "Philly", "Shanda", "Clair", "Dacie", "Darn", "Spence", "Allin", "Crosby", "Fanny", "Delores", "Shea", "Kaylil", "Trumann", "Penn", "Cirilo", "Renato", "Ettie", "Eddy", "Cecily", "Tootsie", "Britni", "Garrard", "Olivero", "Evita", "Sullivan", "Yolande", "Alysia", "Waylon", "Zia", "Willi", "Gale", ] last_names = [ "Sallenger", "Snowding", "Sandever", "Garford", "Jull", "Knowlden", "Laying", "Lawty", "Waleworke", "Calcutt", "Ivankov", "Dummer", "Moscone", "Munns", "McGonagle", "Slyman", "Peakman", "Coverdale", "Karolczyk", "Orrow", "Bohl", "Heckner", "O'Neal", "Rafter", "Gaitley", "Marzello", "Klesl", "Twaite", "Borrow", "Lambourn", "ducarme", "Asson", "Jodkowski", "Pinchen", "McMeanma", "Vasenkov", "Scutching", "Le Friec", "Itzik", "Hendren", "Rangeley", "McGroarty", "Goodlet", "Fouracre", "Austins", "McShea", "Allingham", "Saye", "Ropartz", "Odam", ] messages = [ "evolve best-of-breed interfaces", "repurpose rich content", "evolve bleeding-edge communities", "reintermediate collaborative methodologies", "recontextualize open-source e-commerce", "seize back-end infrastructures", "deliver leading-edge deliverables", "reinvent real-time methodologies", "drive innovative technologies", "incentivize mission-critical deliverables", "synthesize one-to-one metrics", "exploit proactive technologies", "e-enable customized systems", "envisioneer frictionless vortals", "orchestrate visionary applications", "maximize customized architectures", "integrate best-of-breed solutions", "recontextualize intuitive schemas", "scale holistic relationships", "aggregate synergistic functionalities", "enable vertical applications", "syndicate viral niches", "harness holistic vortals", "visualize back-end mindshare", "unleash frictionless niches", ] # Random test data first_name = random.choice(first_names) last_name = random.choice(last_names) name = f"{first_name} {last_name}" email = f"{first_name}_{last_name}@fakemail.com" message = random.choices(messages, k=2) message = f"{message[0]} {message[-1]} \n\nThis message was generated by an automated program"
{"/browser_automation/pages/contact_page.py": ["/browser_automation/pages/base_page.py", "/browser_automation/pages/base_element.py", "/browser_automation/pages/locator.py"], "/browser_automation/pages/home_page.py": ["/browser_automation/pages/base_page.py", "/browser_automation/pages/base_element.py", "/browser_automation/pages/locator.py"], "/views/blog.py": ["/models/blog.py", "/app.py"], "/browser_automation/pages/portfolio_page.py": ["/browser_automation/pages/base_element.py", "/browser_automation/pages/base_page.py", "/browser_automation/pages/locator.py"], "/utilities/tasks.py": ["/celery_app.py"], "/app.py": ["/config.py", "/api/search.py"], "/views/contact.py": ["/forms/contact.py", "/utilities/tasks.py", "/app.py"], "/views/portfolio.py": ["/app.py"], "/browser_automation/automation_tests.py": ["/browser_automation/pages/home_page.py", "/browser_automation/pages/portfolio_page.py", "/browser_automation/pages/contact_page.py", "/browser_automation/__init__.py"], "/tests/test_app.py": ["/models/blog.py", "/app.py", "/config.py"], "/api/search.py": ["/models/blog.py"]}
53,194
AbhishekPednekar84/personal-portfolio
refs/heads/master
/models/blog.py
from extensions import db from sqlalchemy.dialects.postgresql import TSVECTOR class Blog(db.Model): __tablename__ = "blog" id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(100)) url = db.Column(db.String(100)) description = db.Column(db.String(1000)) description_token = db.Column(TSVECTOR) def __repr__(self): return f"Blog({self.id}, {self.title}, {self.url}, {self.description})"
{"/browser_automation/pages/contact_page.py": ["/browser_automation/pages/base_page.py", "/browser_automation/pages/base_element.py", "/browser_automation/pages/locator.py"], "/browser_automation/pages/home_page.py": ["/browser_automation/pages/base_page.py", "/browser_automation/pages/base_element.py", "/browser_automation/pages/locator.py"], "/views/blog.py": ["/models/blog.py", "/app.py"], "/browser_automation/pages/portfolio_page.py": ["/browser_automation/pages/base_element.py", "/browser_automation/pages/base_page.py", "/browser_automation/pages/locator.py"], "/utilities/tasks.py": ["/celery_app.py"], "/app.py": ["/config.py", "/api/search.py"], "/views/contact.py": ["/forms/contact.py", "/utilities/tasks.py", "/app.py"], "/views/portfolio.py": ["/app.py"], "/browser_automation/automation_tests.py": ["/browser_automation/pages/home_page.py", "/browser_automation/pages/portfolio_page.py", "/browser_automation/pages/contact_page.py", "/browser_automation/__init__.py"], "/tests/test_app.py": ["/models/blog.py", "/app.py", "/config.py"], "/api/search.py": ["/models/blog.py"]}
53,195
AbhishekPednekar84/personal-portfolio
refs/heads/master
/browser_automation/pages/home_page.py
from browser_automation.pages.base_page import BasePage from browser_automation.pages.base_element import BaseElement from selenium.webdriver.common.by import By from browser_automation.pages.locator import Locator class HomePage(BasePage): url = "https://abhishekpednekar.com" @property def click_nav_bar(self): locator = Locator(by=By.CSS_SELECTOR, value="div.menu-btn") return BaseElement(driver=self.driver, locator=locator) @property def nav_link(self): locator = Locator(by=By.XPATH, value="//a[text()='Portfolio']") return BaseElement(driver=self.driver, locator=locator)
{"/browser_automation/pages/contact_page.py": ["/browser_automation/pages/base_page.py", "/browser_automation/pages/base_element.py", "/browser_automation/pages/locator.py"], "/browser_automation/pages/home_page.py": ["/browser_automation/pages/base_page.py", "/browser_automation/pages/base_element.py", "/browser_automation/pages/locator.py"], "/views/blog.py": ["/models/blog.py", "/app.py"], "/browser_automation/pages/portfolio_page.py": ["/browser_automation/pages/base_element.py", "/browser_automation/pages/base_page.py", "/browser_automation/pages/locator.py"], "/utilities/tasks.py": ["/celery_app.py"], "/app.py": ["/config.py", "/api/search.py"], "/views/contact.py": ["/forms/contact.py", "/utilities/tasks.py", "/app.py"], "/views/portfolio.py": ["/app.py"], "/browser_automation/automation_tests.py": ["/browser_automation/pages/home_page.py", "/browser_automation/pages/portfolio_page.py", "/browser_automation/pages/contact_page.py", "/browser_automation/__init__.py"], "/tests/test_app.py": ["/models/blog.py", "/app.py", "/config.py"], "/api/search.py": ["/models/blog.py"]}
53,196
AbhishekPednekar84/personal-portfolio
refs/heads/master
/browser_automation/pages/base_page.py
class BasePage(object): url = None def __init__(self, driver): self.driver = driver def go(self): self.driver.get(self.url) def scroll(self, x: int, y: int): script = f"window.scrollTo({x}, {y})" self.driver.execute_script(script) def switch(self, tab: int): self.driver.switch_to.window(self.driver.window_handles[tab]) def close_tab(self): self.driver.close()
{"/browser_automation/pages/contact_page.py": ["/browser_automation/pages/base_page.py", "/browser_automation/pages/base_element.py", "/browser_automation/pages/locator.py"], "/browser_automation/pages/home_page.py": ["/browser_automation/pages/base_page.py", "/browser_automation/pages/base_element.py", "/browser_automation/pages/locator.py"], "/views/blog.py": ["/models/blog.py", "/app.py"], "/browser_automation/pages/portfolio_page.py": ["/browser_automation/pages/base_element.py", "/browser_automation/pages/base_page.py", "/browser_automation/pages/locator.py"], "/utilities/tasks.py": ["/celery_app.py"], "/app.py": ["/config.py", "/api/search.py"], "/views/contact.py": ["/forms/contact.py", "/utilities/tasks.py", "/app.py"], "/views/portfolio.py": ["/app.py"], "/browser_automation/automation_tests.py": ["/browser_automation/pages/home_page.py", "/browser_automation/pages/portfolio_page.py", "/browser_automation/pages/contact_page.py", "/browser_automation/__init__.py"], "/tests/test_app.py": ["/models/blog.py", "/app.py", "/config.py"], "/api/search.py": ["/models/blog.py"]}
53,197
AbhishekPednekar84/personal-portfolio
refs/heads/master
/views/main.py
from flask import Blueprint, render_template main_blueprint = Blueprint("main", __name__, template_folder="templates") @main_blueprint.route("/") @main_blueprint.route("/main") def main(): """ View method to render the home.html page - https://www.abhishekpednekar.com/ Returns ------- home.html: html / jinja2 template """ return render_template("home.html")
{"/browser_automation/pages/contact_page.py": ["/browser_automation/pages/base_page.py", "/browser_automation/pages/base_element.py", "/browser_automation/pages/locator.py"], "/browser_automation/pages/home_page.py": ["/browser_automation/pages/base_page.py", "/browser_automation/pages/base_element.py", "/browser_automation/pages/locator.py"], "/views/blog.py": ["/models/blog.py", "/app.py"], "/browser_automation/pages/portfolio_page.py": ["/browser_automation/pages/base_element.py", "/browser_automation/pages/base_page.py", "/browser_automation/pages/locator.py"], "/utilities/tasks.py": ["/celery_app.py"], "/app.py": ["/config.py", "/api/search.py"], "/views/contact.py": ["/forms/contact.py", "/utilities/tasks.py", "/app.py"], "/views/portfolio.py": ["/app.py"], "/browser_automation/automation_tests.py": ["/browser_automation/pages/home_page.py", "/browser_automation/pages/portfolio_page.py", "/browser_automation/pages/contact_page.py", "/browser_automation/__init__.py"], "/tests/test_app.py": ["/models/blog.py", "/app.py", "/config.py"], "/api/search.py": ["/models/blog.py"]}
53,198
AbhishekPednekar84/personal-portfolio
refs/heads/master
/views/blog.py
from flask import Blueprint, render_template, request from extensions import db from models.blog import Blog from app import get_current_year blog_blueprint = Blueprint("blog", __name__, template_folder="templates") @blog_blueprint.route("/blog") def blog(): """ View method to render the blog.html page - https://www.abhishekpednekar.com/blog Returns ------- blog.html: html / jinja2 template """ page = request.args.get("page", 1, type=int) blogs = ( db.session.query(Blog.id, Blog.title, Blog.url, Blog.description) .order_by(Blog.id.desc()) .paginate(page=page, per_page=7) ) return render_template( "blog.html", title="Blog", blogs=blogs, year=get_current_year() )
{"/browser_automation/pages/contact_page.py": ["/browser_automation/pages/base_page.py", "/browser_automation/pages/base_element.py", "/browser_automation/pages/locator.py"], "/browser_automation/pages/home_page.py": ["/browser_automation/pages/base_page.py", "/browser_automation/pages/base_element.py", "/browser_automation/pages/locator.py"], "/views/blog.py": ["/models/blog.py", "/app.py"], "/browser_automation/pages/portfolio_page.py": ["/browser_automation/pages/base_element.py", "/browser_automation/pages/base_page.py", "/browser_automation/pages/locator.py"], "/utilities/tasks.py": ["/celery_app.py"], "/app.py": ["/config.py", "/api/search.py"], "/views/contact.py": ["/forms/contact.py", "/utilities/tasks.py", "/app.py"], "/views/portfolio.py": ["/app.py"], "/browser_automation/automation_tests.py": ["/browser_automation/pages/home_page.py", "/browser_automation/pages/portfolio_page.py", "/browser_automation/pages/contact_page.py", "/browser_automation/__init__.py"], "/tests/test_app.py": ["/models/blog.py", "/app.py", "/config.py"], "/api/search.py": ["/models/blog.py"]}
53,199
AbhishekPednekar84/personal-portfolio
refs/heads/master
/migrations/versions/1c581a07c81f_.py
"""empty message Revision ID: 1c581a07c81f Revises: Create Date: 2019-11-25 14:58:22.016437 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql # revision identifiers, used by Alembic. revision = "1c581a07c81f" down_revision = None branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column( "blog", sa.Column("description_token", postgresql.TSVECTOR(), nullable=True), ) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_column("blog", "description_token") # ### end Alembic commands ###
{"/browser_automation/pages/contact_page.py": ["/browser_automation/pages/base_page.py", "/browser_automation/pages/base_element.py", "/browser_automation/pages/locator.py"], "/browser_automation/pages/home_page.py": ["/browser_automation/pages/base_page.py", "/browser_automation/pages/base_element.py", "/browser_automation/pages/locator.py"], "/views/blog.py": ["/models/blog.py", "/app.py"], "/browser_automation/pages/portfolio_page.py": ["/browser_automation/pages/base_element.py", "/browser_automation/pages/base_page.py", "/browser_automation/pages/locator.py"], "/utilities/tasks.py": ["/celery_app.py"], "/app.py": ["/config.py", "/api/search.py"], "/views/contact.py": ["/forms/contact.py", "/utilities/tasks.py", "/app.py"], "/views/portfolio.py": ["/app.py"], "/browser_automation/automation_tests.py": ["/browser_automation/pages/home_page.py", "/browser_automation/pages/portfolio_page.py", "/browser_automation/pages/contact_page.py", "/browser_automation/__init__.py"], "/tests/test_app.py": ["/models/blog.py", "/app.py", "/config.py"], "/api/search.py": ["/models/blog.py"]}
53,200
AbhishekPednekar84/personal-portfolio
refs/heads/master
/celery_app.py
from flask import Flask from utilities.factory import make_celery def create_celery_app(): """ Returns a celery instance Returns ------- celery: object """ app = Flask(__name__) celery = make_celery(app) return celery
{"/browser_automation/pages/contact_page.py": ["/browser_automation/pages/base_page.py", "/browser_automation/pages/base_element.py", "/browser_automation/pages/locator.py"], "/browser_automation/pages/home_page.py": ["/browser_automation/pages/base_page.py", "/browser_automation/pages/base_element.py", "/browser_automation/pages/locator.py"], "/views/blog.py": ["/models/blog.py", "/app.py"], "/browser_automation/pages/portfolio_page.py": ["/browser_automation/pages/base_element.py", "/browser_automation/pages/base_page.py", "/browser_automation/pages/locator.py"], "/utilities/tasks.py": ["/celery_app.py"], "/app.py": ["/config.py", "/api/search.py"], "/views/contact.py": ["/forms/contact.py", "/utilities/tasks.py", "/app.py"], "/views/portfolio.py": ["/app.py"], "/browser_automation/automation_tests.py": ["/browser_automation/pages/home_page.py", "/browser_automation/pages/portfolio_page.py", "/browser_automation/pages/contact_page.py", "/browser_automation/__init__.py"], "/tests/test_app.py": ["/models/blog.py", "/app.py", "/config.py"], "/api/search.py": ["/models/blog.py"]}
53,201
AbhishekPednekar84/personal-portfolio
refs/heads/master
/browser_automation/pages/locator.py
from collections import namedtuple Locator = namedtuple("Locator", ["by", "value"])
{"/browser_automation/pages/contact_page.py": ["/browser_automation/pages/base_page.py", "/browser_automation/pages/base_element.py", "/browser_automation/pages/locator.py"], "/browser_automation/pages/home_page.py": ["/browser_automation/pages/base_page.py", "/browser_automation/pages/base_element.py", "/browser_automation/pages/locator.py"], "/views/blog.py": ["/models/blog.py", "/app.py"], "/browser_automation/pages/portfolio_page.py": ["/browser_automation/pages/base_element.py", "/browser_automation/pages/base_page.py", "/browser_automation/pages/locator.py"], "/utilities/tasks.py": ["/celery_app.py"], "/app.py": ["/config.py", "/api/search.py"], "/views/contact.py": ["/forms/contact.py", "/utilities/tasks.py", "/app.py"], "/views/portfolio.py": ["/app.py"], "/browser_automation/automation_tests.py": ["/browser_automation/pages/home_page.py", "/browser_automation/pages/portfolio_page.py", "/browser_automation/pages/contact_page.py", "/browser_automation/__init__.py"], "/tests/test_app.py": ["/models/blog.py", "/app.py", "/config.py"], "/api/search.py": ["/models/blog.py"]}
53,202
AbhishekPednekar84/personal-portfolio
refs/heads/master
/forms/search.py
from flask_wtf import FlaskForm from wtforms import StringField, SubmitField from wtforms.validators import DataRequired class Search(FlaskForm): search_post = StringField("Search Post", validators=[DataRequired()]) submit = SubmitField("Search") def __repr__(self): return f"Search(Search Post: {self.search_post})"
{"/browser_automation/pages/contact_page.py": ["/browser_automation/pages/base_page.py", "/browser_automation/pages/base_element.py", "/browser_automation/pages/locator.py"], "/browser_automation/pages/home_page.py": ["/browser_automation/pages/base_page.py", "/browser_automation/pages/base_element.py", "/browser_automation/pages/locator.py"], "/views/blog.py": ["/models/blog.py", "/app.py"], "/browser_automation/pages/portfolio_page.py": ["/browser_automation/pages/base_element.py", "/browser_automation/pages/base_page.py", "/browser_automation/pages/locator.py"], "/utilities/tasks.py": ["/celery_app.py"], "/app.py": ["/config.py", "/api/search.py"], "/views/contact.py": ["/forms/contact.py", "/utilities/tasks.py", "/app.py"], "/views/portfolio.py": ["/app.py"], "/browser_automation/automation_tests.py": ["/browser_automation/pages/home_page.py", "/browser_automation/pages/portfolio_page.py", "/browser_automation/pages/contact_page.py", "/browser_automation/__init__.py"], "/tests/test_app.py": ["/models/blog.py", "/app.py", "/config.py"], "/api/search.py": ["/models/blog.py"]}
53,203
AbhishekPednekar84/personal-portfolio
refs/heads/master
/browser_automation/pages/portfolio_page.py
from browser_automation.pages.base_element import BaseElement from browser_automation.pages.base_page import BasePage from selenium.webdriver.common.by import By from browser_automation.pages.locator import Locator class PortfolioPage(BasePage): url = "https://www.abhishekpednekar.com/portfolio" @property def cv_button(self): locator = Locator(by=By.CSS_SELECTOR, value="a.btn-cv") return BaseElement(driver=self.driver, locator=locator)
{"/browser_automation/pages/contact_page.py": ["/browser_automation/pages/base_page.py", "/browser_automation/pages/base_element.py", "/browser_automation/pages/locator.py"], "/browser_automation/pages/home_page.py": ["/browser_automation/pages/base_page.py", "/browser_automation/pages/base_element.py", "/browser_automation/pages/locator.py"], "/views/blog.py": ["/models/blog.py", "/app.py"], "/browser_automation/pages/portfolio_page.py": ["/browser_automation/pages/base_element.py", "/browser_automation/pages/base_page.py", "/browser_automation/pages/locator.py"], "/utilities/tasks.py": ["/celery_app.py"], "/app.py": ["/config.py", "/api/search.py"], "/views/contact.py": ["/forms/contact.py", "/utilities/tasks.py", "/app.py"], "/views/portfolio.py": ["/app.py"], "/browser_automation/automation_tests.py": ["/browser_automation/pages/home_page.py", "/browser_automation/pages/portfolio_page.py", "/browser_automation/pages/contact_page.py", "/browser_automation/__init__.py"], "/tests/test_app.py": ["/models/blog.py", "/app.py", "/config.py"], "/api/search.py": ["/models/blog.py"]}
53,204
AbhishekPednekar84/personal-portfolio
refs/heads/master
/utilities/tasks.py
import os import smtplib import ssl from email.message import EmailMessage from celery_app import create_celery_app celery = create_celery_app() @celery.task def send_email(caller_name, caller_email, caller_subject, caller_message): """ Method to send an email based on the details provided on the contact me page Parameters ---------- caller_name: name of the individual contacting me caller_email: email of the individual contacting me caller_subject: email subject provided by the individual caller_message: email message provided by the individual """ sender_email = os.getenv("EMAIL_USER") password = os.environ.get("EMAIL_PASS") recipient_email = os.getenv("RECIPIENT_EMAIL") port = 465 smtp_server = "smtp.gmail.com" msg = EmailMessage() msg["From"] = sender_email msg["To"] = recipient_email msg["Subject"] = caller_subject msg.set_content( f"Email from {caller_name} ({caller_email})\n\n{caller_message}" ) context = ssl.create_default_context() with smtplib.SMTP_SSL(smtp_server, port, context=context) as smtp: smtp.login(sender_email, password) smtp.send_message(msg)
{"/browser_automation/pages/contact_page.py": ["/browser_automation/pages/base_page.py", "/browser_automation/pages/base_element.py", "/browser_automation/pages/locator.py"], "/browser_automation/pages/home_page.py": ["/browser_automation/pages/base_page.py", "/browser_automation/pages/base_element.py", "/browser_automation/pages/locator.py"], "/views/blog.py": ["/models/blog.py", "/app.py"], "/browser_automation/pages/portfolio_page.py": ["/browser_automation/pages/base_element.py", "/browser_automation/pages/base_page.py", "/browser_automation/pages/locator.py"], "/utilities/tasks.py": ["/celery_app.py"], "/app.py": ["/config.py", "/api/search.py"], "/views/contact.py": ["/forms/contact.py", "/utilities/tasks.py", "/app.py"], "/views/portfolio.py": ["/app.py"], "/browser_automation/automation_tests.py": ["/browser_automation/pages/home_page.py", "/browser_automation/pages/portfolio_page.py", "/browser_automation/pages/contact_page.py", "/browser_automation/__init__.py"], "/tests/test_app.py": ["/models/blog.py", "/app.py", "/config.py"], "/api/search.py": ["/models/blog.py"]}
53,205
AbhishekPednekar84/personal-portfolio
refs/heads/master
/app.py
from flask import Flask from flask_migrate import Migrate from config import Config from extensions import db from datetime import datetime def create_app(config_class=Config): """ Returns the flask application instance Parameters ---------- config_class: class Returns ------- app: object """ app = Flask(__name__) app.config.from_object(Config) db.init_app(app) migrate = Migrate(app, db) from views import blog from views import contact from views import main from views import portfolio from views import sitemap from api.search import search_blueprint app.register_blueprint(blog.blog_blueprint) app.register_blueprint(contact.contact_blueprint) app.register_blueprint(main.main_blueprint) app.register_blueprint(portfolio.portfolio_blueprint) app.register_blueprint(sitemap.sitemap_blueprint) app.register_blueprint(search_blueprint, url_prefix="/api") return app def get_current_year(): """ Returns the current year that will be displayed on the website footer Returns ------- current_year: int """ current_year = datetime.now().year return current_year if __name__ == "__main__": # pragma: no cover app = create_app() app.run()
{"/browser_automation/pages/contact_page.py": ["/browser_automation/pages/base_page.py", "/browser_automation/pages/base_element.py", "/browser_automation/pages/locator.py"], "/browser_automation/pages/home_page.py": ["/browser_automation/pages/base_page.py", "/browser_automation/pages/base_element.py", "/browser_automation/pages/locator.py"], "/views/blog.py": ["/models/blog.py", "/app.py"], "/browser_automation/pages/portfolio_page.py": ["/browser_automation/pages/base_element.py", "/browser_automation/pages/base_page.py", "/browser_automation/pages/locator.py"], "/utilities/tasks.py": ["/celery_app.py"], "/app.py": ["/config.py", "/api/search.py"], "/views/contact.py": ["/forms/contact.py", "/utilities/tasks.py", "/app.py"], "/views/portfolio.py": ["/app.py"], "/browser_automation/automation_tests.py": ["/browser_automation/pages/home_page.py", "/browser_automation/pages/portfolio_page.py", "/browser_automation/pages/contact_page.py", "/browser_automation/__init__.py"], "/tests/test_app.py": ["/models/blog.py", "/app.py", "/config.py"], "/api/search.py": ["/models/blog.py"]}
53,206
AbhishekPednekar84/personal-portfolio
refs/heads/master
/config.py
import os import dotenv dotenv.load_dotenv() class Config: SECRET_KEY = os.getenv("SECRET_KEY") SQLALCHEMY_DATABASE_URI = os.getenv("SQLALCHEMY_DATABASE_URI") SQLALCHEMY_TRACK_MODIFICATIONS = True RESTPLUS_MASK_SWAGGER = False CELERY_BROKER_URL = os.getenv("CELERY_BROKER_URL") class TestConfig(Config): TESTING = True WTF_CSRF_ENABLED = False DEBUG = False SQLALCHEMY_DATABASE_URI = "sqlite:///:memory:" class DevConfig(Config): DEBUG = True
{"/browser_automation/pages/contact_page.py": ["/browser_automation/pages/base_page.py", "/browser_automation/pages/base_element.py", "/browser_automation/pages/locator.py"], "/browser_automation/pages/home_page.py": ["/browser_automation/pages/base_page.py", "/browser_automation/pages/base_element.py", "/browser_automation/pages/locator.py"], "/views/blog.py": ["/models/blog.py", "/app.py"], "/browser_automation/pages/portfolio_page.py": ["/browser_automation/pages/base_element.py", "/browser_automation/pages/base_page.py", "/browser_automation/pages/locator.py"], "/utilities/tasks.py": ["/celery_app.py"], "/app.py": ["/config.py", "/api/search.py"], "/views/contact.py": ["/forms/contact.py", "/utilities/tasks.py", "/app.py"], "/views/portfolio.py": ["/app.py"], "/browser_automation/automation_tests.py": ["/browser_automation/pages/home_page.py", "/browser_automation/pages/portfolio_page.py", "/browser_automation/pages/contact_page.py", "/browser_automation/__init__.py"], "/tests/test_app.py": ["/models/blog.py", "/app.py", "/config.py"], "/api/search.py": ["/models/blog.py"]}
53,207
AbhishekPednekar84/personal-portfolio
refs/heads/master
/views/contact.py
from flask import Blueprint, flash, redirect, url_for, render_template from forms.contact import ContactForm from utilities.tasks import send_email from app import get_current_year contact_blueprint = Blueprint("contact", __name__, template_folder="templates") @contact_blueprint.route("/contact", methods=["GET", "POST"]) def contact(): """ View method to render the contact.html page - https://www.abhishekpednekar.com/contact Returns ------- contact.html: html / jinja2 template """ form = ContactForm() if form.validate_on_submit(): send_email.delay( form.username.data, form.email.data, form.subject.data, form.message.data, ) flash("Thanks! I will be in touch soon.") return redirect(url_for("contact.contact")) return render_template( "contact.html", title="Contact", form=form, year=get_current_year() )
{"/browser_automation/pages/contact_page.py": ["/browser_automation/pages/base_page.py", "/browser_automation/pages/base_element.py", "/browser_automation/pages/locator.py"], "/browser_automation/pages/home_page.py": ["/browser_automation/pages/base_page.py", "/browser_automation/pages/base_element.py", "/browser_automation/pages/locator.py"], "/views/blog.py": ["/models/blog.py", "/app.py"], "/browser_automation/pages/portfolio_page.py": ["/browser_automation/pages/base_element.py", "/browser_automation/pages/base_page.py", "/browser_automation/pages/locator.py"], "/utilities/tasks.py": ["/celery_app.py"], "/app.py": ["/config.py", "/api/search.py"], "/views/contact.py": ["/forms/contact.py", "/utilities/tasks.py", "/app.py"], "/views/portfolio.py": ["/app.py"], "/browser_automation/automation_tests.py": ["/browser_automation/pages/home_page.py", "/browser_automation/pages/portfolio_page.py", "/browser_automation/pages/contact_page.py", "/browser_automation/__init__.py"], "/tests/test_app.py": ["/models/blog.py", "/app.py", "/config.py"], "/api/search.py": ["/models/blog.py"]}
53,208
AbhishekPednekar84/personal-portfolio
refs/heads/master
/browser_automation/pages/base_element.py
import selenium.webdriver.support.expected_conditions as ec from selenium.webdriver.support.wait import WebDriverWait class BaseElement(object): def __init__(self, driver, locator): self.driver = driver self.locator = locator self.web_element = None self.find() def find(self): element = WebDriverWait(self.driver, 10).until( ec.presence_of_element_located(locator=self.locator) ) self.web_element = element def click(self): element = WebDriverWait(self.driver, 10).until( ec.visibility_of_element_located(locator=self.locator) ) element.click() def text(self): text = self.web_element.text return text def input_text(self, text): self.web_element.send_keys(text) def attribute(self, attr_name): attribute = self.web_element.get_attribute(attr_name) return attribute
{"/browser_automation/pages/contact_page.py": ["/browser_automation/pages/base_page.py", "/browser_automation/pages/base_element.py", "/browser_automation/pages/locator.py"], "/browser_automation/pages/home_page.py": ["/browser_automation/pages/base_page.py", "/browser_automation/pages/base_element.py", "/browser_automation/pages/locator.py"], "/views/blog.py": ["/models/blog.py", "/app.py"], "/browser_automation/pages/portfolio_page.py": ["/browser_automation/pages/base_element.py", "/browser_automation/pages/base_page.py", "/browser_automation/pages/locator.py"], "/utilities/tasks.py": ["/celery_app.py"], "/app.py": ["/config.py", "/api/search.py"], "/views/contact.py": ["/forms/contact.py", "/utilities/tasks.py", "/app.py"], "/views/portfolio.py": ["/app.py"], "/browser_automation/automation_tests.py": ["/browser_automation/pages/home_page.py", "/browser_automation/pages/portfolio_page.py", "/browser_automation/pages/contact_page.py", "/browser_automation/__init__.py"], "/tests/test_app.py": ["/models/blog.py", "/app.py", "/config.py"], "/api/search.py": ["/models/blog.py"]}
53,209
AbhishekPednekar84/personal-portfolio
refs/heads/master
/views/portfolio.py
from flask import Blueprint, render_template from app import get_current_year portfolio_blueprint = Blueprint( "portfolio", __name__, template_folder="templates" ) @portfolio_blueprint.route("/portfolio") def portfolio(): """ View method to render the portfolio.html page - https://www.abhishekpednekar.com/portfolio Returns ------- portfolio.html: html / jinja2 template """ return render_template( "portfolio.html", title="Portfolio", year=get_current_year() )
{"/browser_automation/pages/contact_page.py": ["/browser_automation/pages/base_page.py", "/browser_automation/pages/base_element.py", "/browser_automation/pages/locator.py"], "/browser_automation/pages/home_page.py": ["/browser_automation/pages/base_page.py", "/browser_automation/pages/base_element.py", "/browser_automation/pages/locator.py"], "/views/blog.py": ["/models/blog.py", "/app.py"], "/browser_automation/pages/portfolio_page.py": ["/browser_automation/pages/base_element.py", "/browser_automation/pages/base_page.py", "/browser_automation/pages/locator.py"], "/utilities/tasks.py": ["/celery_app.py"], "/app.py": ["/config.py", "/api/search.py"], "/views/contact.py": ["/forms/contact.py", "/utilities/tasks.py", "/app.py"], "/views/portfolio.py": ["/app.py"], "/browser_automation/automation_tests.py": ["/browser_automation/pages/home_page.py", "/browser_automation/pages/portfolio_page.py", "/browser_automation/pages/contact_page.py", "/browser_automation/__init__.py"], "/tests/test_app.py": ["/models/blog.py", "/app.py", "/config.py"], "/api/search.py": ["/models/blog.py"]}
53,210
AbhishekPednekar84/personal-portfolio
refs/heads/master
/views/sitemap.py
from flask import Blueprint, send_from_directory sitemap_blueprint = Blueprint("sitemap", __name__) @sitemap_blueprint.route("/sitemap.xml") def sitemap_xml(): return send_from_directory(directory="static", filename="sitemap.xml")
{"/browser_automation/pages/contact_page.py": ["/browser_automation/pages/base_page.py", "/browser_automation/pages/base_element.py", "/browser_automation/pages/locator.py"], "/browser_automation/pages/home_page.py": ["/browser_automation/pages/base_page.py", "/browser_automation/pages/base_element.py", "/browser_automation/pages/locator.py"], "/views/blog.py": ["/models/blog.py", "/app.py"], "/browser_automation/pages/portfolio_page.py": ["/browser_automation/pages/base_element.py", "/browser_automation/pages/base_page.py", "/browser_automation/pages/locator.py"], "/utilities/tasks.py": ["/celery_app.py"], "/app.py": ["/config.py", "/api/search.py"], "/views/contact.py": ["/forms/contact.py", "/utilities/tasks.py", "/app.py"], "/views/portfolio.py": ["/app.py"], "/browser_automation/automation_tests.py": ["/browser_automation/pages/home_page.py", "/browser_automation/pages/portfolio_page.py", "/browser_automation/pages/contact_page.py", "/browser_automation/__init__.py"], "/tests/test_app.py": ["/models/blog.py", "/app.py", "/config.py"], "/api/search.py": ["/models/blog.py"]}
53,211
AbhishekPednekar84/personal-portfolio
refs/heads/master
/browser_automation/automation_tests.py
from selenium import webdriver from browser_automation.pages.home_page import HomePage from browser_automation.pages.portfolio_page import PortfolioPage from browser_automation.pages.contact_page import ContactPage from browser_automation import name, email, message browser = webdriver.Chrome() # Tests for the home page try: # Initialize and load the home page home_pg = HomePage(browser) home_pg.go() # Click on the navigation bar and route to the portfolio page home_pg.click_nav_bar.click() home_pg.nav_link.click() # Initialize the portfolio page portfolio_pg = PortfolioPage(browser) portfolio_pg.scroll(1919, 1079) portfolio_pg.scroll(1919, 0) # Click the "View My CV" button portfolio_pg.cv_button.click() # Switch control to the new tab and close it portfolio_pg.switch(-1) portfolio_pg.close_tab() portfolio_pg.switch(0) # Initialize the contact page contact_pg = ContactPage(browser) contact_pg.go() # Fill the contact form and submit contact_pg.name_input.input_text(name) contact_pg.email_input.input_text(email) contact_pg.subject_input.input_text("Automation Test") contact_pg.message_input.input_text(message) contact_pg.submit_button.click() except Exception: # Quit the browser browser.quit() print("There was an error in executing the test") finally: # Quit the browser browser.quit() print("Test execution completed successfully!")
{"/browser_automation/pages/contact_page.py": ["/browser_automation/pages/base_page.py", "/browser_automation/pages/base_element.py", "/browser_automation/pages/locator.py"], "/browser_automation/pages/home_page.py": ["/browser_automation/pages/base_page.py", "/browser_automation/pages/base_element.py", "/browser_automation/pages/locator.py"], "/views/blog.py": ["/models/blog.py", "/app.py"], "/browser_automation/pages/portfolio_page.py": ["/browser_automation/pages/base_element.py", "/browser_automation/pages/base_page.py", "/browser_automation/pages/locator.py"], "/utilities/tasks.py": ["/celery_app.py"], "/app.py": ["/config.py", "/api/search.py"], "/views/contact.py": ["/forms/contact.py", "/utilities/tasks.py", "/app.py"], "/views/portfolio.py": ["/app.py"], "/browser_automation/automation_tests.py": ["/browser_automation/pages/home_page.py", "/browser_automation/pages/portfolio_page.py", "/browser_automation/pages/contact_page.py", "/browser_automation/__init__.py"], "/tests/test_app.py": ["/models/blog.py", "/app.py", "/config.py"], "/api/search.py": ["/models/blog.py"]}
53,212
AbhishekPednekar84/personal-portfolio
refs/heads/master
/forms/contact.py
from flask_wtf import FlaskForm from wtforms import StringField, SubmitField, TextAreaField from wtforms.validators import DataRequired, Length, Email class ContactForm(FlaskForm): username = StringField( "Your Name", validators=[DataRequired(), Length(min=2, max=25)] ) email = StringField("Your Email", validators=[DataRequired(), Email()]) subject = StringField( "Subject", validators=[DataRequired(), Length(min=2, max=20)] ) message = TextAreaField("Your Message", validators=[DataRequired()]) submit = SubmitField("SEND") def __repr__(self): return f"<Name: {self.username} - Email: {self.email} - Subject: {self.subject}>"
{"/browser_automation/pages/contact_page.py": ["/browser_automation/pages/base_page.py", "/browser_automation/pages/base_element.py", "/browser_automation/pages/locator.py"], "/browser_automation/pages/home_page.py": ["/browser_automation/pages/base_page.py", "/browser_automation/pages/base_element.py", "/browser_automation/pages/locator.py"], "/views/blog.py": ["/models/blog.py", "/app.py"], "/browser_automation/pages/portfolio_page.py": ["/browser_automation/pages/base_element.py", "/browser_automation/pages/base_page.py", "/browser_automation/pages/locator.py"], "/utilities/tasks.py": ["/celery_app.py"], "/app.py": ["/config.py", "/api/search.py"], "/views/contact.py": ["/forms/contact.py", "/utilities/tasks.py", "/app.py"], "/views/portfolio.py": ["/app.py"], "/browser_automation/automation_tests.py": ["/browser_automation/pages/home_page.py", "/browser_automation/pages/portfolio_page.py", "/browser_automation/pages/contact_page.py", "/browser_automation/__init__.py"], "/tests/test_app.py": ["/models/blog.py", "/app.py", "/config.py"], "/api/search.py": ["/models/blog.py"]}
53,213
AbhishekPednekar84/personal-portfolio
refs/heads/master
/tests/test_app.py
import unittest from extensions import db from models.blog import Blog from app import create_app from config import TestConfig app = create_app(config_class=TestConfig) app.config.from_object(TestConfig) client = app.test_client() class BaseTestCase(unittest.TestCase): def setUp(self) -> None: ctx = app.app_context() ctx.push() with client: test_blog = Blog( title="Testing a Portfolio site", url="http://localhost:5000/blog", description="This post demonstrates the steps to unit test a Flask application", ) db.create_all() db.session.add(test_blog) db.session.commit() def tearDown(self) -> None: db.session.remove() db.drop_all() class TestCases(BaseTestCase): # Helper methods def contact(self, name, email, subject, message): return client.post( "/contact", data=dict(name=name, email=email, subject=subject, message=message), ) # Test Cases def test_home(self): response = client.get("/") self.assertEqual(response.status_code, 200) self.assertIn(b"Abhishek Pednekar", response.data) # Test title self.assertIn( b"https://github.com/AbhishekPednekar84", response.data ) # Test social link self.assertIn(b"Portfolio", response.data) def test_portfolio(self): response = client.get("/portfolio") self.assertEqual(response.status_code, 200) self.assertIn(b"BIO", response.data) self.assertIn(b"Skills", response.data) self.assertIn(b"CodeDisciples.in", response.data) self.assertIn(b"Bangalore", response.data) # Test footer def test_blog(self): response = client.get("/blog") self.assertEqual(response.status_code, 200) self.assertIn(b"Code Disciples", response.data) self.assertIn(b"Testing a Portfolio site", response.data) self.assertIn(b"http://localhost:5000/blog", response.data) self.assertIn( b"This post demonstrates the steps to unit test a Flask application", response.data, ) self.assertIn(b"Bangalore", response.data) # Test footer def test_invalid_page(self): response = client.get("/blog?page=2") self.assertEqual(response.status_code, 404) self.assertIn(b"Not Found", response.data) def test_contact(self): response = client.get("/contact") self.assertEqual(response.status_code, 200) self.assertIn(b"Contact Me", response.data) self.assertIn(b"References", response.data) self.assertIn(b"Bangalore", response.data) # Test footer def test_email_success(self): response = self.contact( "Test Joe", "TestJoe@email.com", "Test Subject", "This is a test message", ) self.assertTrue(b"Thanks! I will be in touch soon.", response.data) def test_email_with_invalid_email(self): response = self.contact( "Test Joe", "TestJoe", "Test Subject", "This is a test message" ) self.assertTrue(b"Invalid email address.", response.data) # def test_search_api_with_id(self): # response = client.get("/api/search/1") # self.assertEqual(response.status_code, 200) # self.assertIn(b"Testing a Portfolio site", response.data) # def test_search_api_for_all_articles(self): # response = client.get("/api/search_all") # self.assertEqual(response.status_code, 308)
{"/browser_automation/pages/contact_page.py": ["/browser_automation/pages/base_page.py", "/browser_automation/pages/base_element.py", "/browser_automation/pages/locator.py"], "/browser_automation/pages/home_page.py": ["/browser_automation/pages/base_page.py", "/browser_automation/pages/base_element.py", "/browser_automation/pages/locator.py"], "/views/blog.py": ["/models/blog.py", "/app.py"], "/browser_automation/pages/portfolio_page.py": ["/browser_automation/pages/base_element.py", "/browser_automation/pages/base_page.py", "/browser_automation/pages/locator.py"], "/utilities/tasks.py": ["/celery_app.py"], "/app.py": ["/config.py", "/api/search.py"], "/views/contact.py": ["/forms/contact.py", "/utilities/tasks.py", "/app.py"], "/views/portfolio.py": ["/app.py"], "/browser_automation/automation_tests.py": ["/browser_automation/pages/home_page.py", "/browser_automation/pages/portfolio_page.py", "/browser_automation/pages/contact_page.py", "/browser_automation/__init__.py"], "/tests/test_app.py": ["/models/blog.py", "/app.py", "/config.py"], "/api/search.py": ["/models/blog.py"]}
53,214
AbhishekPednekar84/personal-portfolio
refs/heads/master
/api/search.py
import string from flask import request, abort, Blueprint from flask_restplus import Api, Resource, fields from extensions import db from models.blog import Blog from sqlalchemy.exc import ProgrammingError, OperationalError search_blueprint = Blueprint("search_api", __name__) api = Api( search_blueprint, doc="/apidoc", title="Code Disciples Search API", description="API endpoints to search posts listed on CodeDisciples.in", default="Code Disciples Blog Search - ", default_label="Search blog posts on CodeDisciples.in", ) model = api.model( "SearchModel", { "title": fields.String, "url": fields.String, "description": fields.String, }, ) # Search blog post by id @api.route("/search/<int:id>") class Search(Resource): @api.marshal_with(model, envelope="blog_posts") def get(self, id): """ Get method to return a blog post by the id column in the blog model Example - https://www.abhishekpednekar.com/api/search/1 Returns ------- blog: dict Raises ------ HTTP 400: Bad request """ try: result = Blog.query.get(id) return ( { "title": result.title, "url": result.url, "description": result.description, }, 200, ) except Exception: abort(400, "Sorry! But that article does not exist yet") # Search all posts @api.route("/search_all/") class SearchAll(Resource): @api.marshal_with(model) def get(self): """ Get method to return all the blog posts blog model URL: https://www.abhishekpednekar.com/api/search_all/ Returns ------- blog: dict Raises ------ HTTP 404: Articles not found """ blog_results = [] try: results = Blog.query.all() for result in results: blog_results.append(result) return blog_results, 200 except Exception: abort(404) # Search by keyword @api.route("/search") class SearchAll(Resource): @api.marshal_with(model) @api.param("q", "A keyword to search with (Ex: Python, Python-Docker)") def get(self): """ Get method to perform a full text search based on the description_token column in the blog model Example - https://www.abhishekpednekar.com/api/search?q=Python Returns ------- blog: dict Raises ------ HTTP 400: Bad request """ blog_results = [] q = str(request.args.get("q", type=str)) special_chars = set(string.punctuation.replace("&", " ")) if not q.isalnum(): for char_ in special_chars: if char_ in q: q = q.replace(char_, "|") else: q = q + ":*" try: results = db.session.query(Blog).filter( Blog.description_token.match(q) ) for result in results: blog_results.append(result) return blog_results except ProgrammingError: abort( 400, "Sorry! You sent a request that the API could not understand", ) except OperationalError: abort( 400, "Sorry! You sent a request that the API could not understand", )
{"/browser_automation/pages/contact_page.py": ["/browser_automation/pages/base_page.py", "/browser_automation/pages/base_element.py", "/browser_automation/pages/locator.py"], "/browser_automation/pages/home_page.py": ["/browser_automation/pages/base_page.py", "/browser_automation/pages/base_element.py", "/browser_automation/pages/locator.py"], "/views/blog.py": ["/models/blog.py", "/app.py"], "/browser_automation/pages/portfolio_page.py": ["/browser_automation/pages/base_element.py", "/browser_automation/pages/base_page.py", "/browser_automation/pages/locator.py"], "/utilities/tasks.py": ["/celery_app.py"], "/app.py": ["/config.py", "/api/search.py"], "/views/contact.py": ["/forms/contact.py", "/utilities/tasks.py", "/app.py"], "/views/portfolio.py": ["/app.py"], "/browser_automation/automation_tests.py": ["/browser_automation/pages/home_page.py", "/browser_automation/pages/portfolio_page.py", "/browser_automation/pages/contact_page.py", "/browser_automation/__init__.py"], "/tests/test_app.py": ["/models/blog.py", "/app.py", "/config.py"], "/api/search.py": ["/models/blog.py"]}
53,215
wahahahaya/CycleGAN-Male2Female
refs/heads/main
/train.py
import torchvision.transforms as transforms from torchvision.utils import save_image, make_grid from torch.utils.data import DataLoader from torchvision import datasets from torch.autograd import Variable import torch.nn as nn import torch.nn.functional as F import torch from model import ResNetGenerator, Discriminator from data import * from utils import * import os import numpy as np import math import itertools def train(): # Parameters epochs = 5 # 這邊根據你上次train完的epoch決定 last_epoch = 0 decay_epoch = 1 sample_interval = 100 dataset_name = "male2female" img_height = 256 img_width = 256 channels = 3 input_shape = (channels, img_height, img_width) device = "cuda" if torch.cuda.is_available() else "cpu" #print('GPU State:', device) Tensor = torch.cuda.FloatTensor if device=='cuda' else torch.Tensor # image transformations # resize (100,100) 會間接影響到Discriminator的輸出size 如果要改 model.py 麻煩也要改 data_process_steps = [ transforms.Resize((100,100)), transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)), ] # 路徑麻煩你們自己改 然後dataset格式一定要像下面那樣 # data loader # gender # |-testA # |-testB # |-trainA # |-trainB train_data = DataLoader( ImageDataset( "C:/Users/a8701/NTUST_dissertation/dataset/horse2zebra/male2female", transforms_=data_process_steps, unaligned=True, ), batch_size=1, #shuffle=True, num_workers=4, ) test_data = DataLoader( ImageDataset( "C:/Users/a8701/NTUST_dissertation/dataset/horse2zebra/male2female", transforms_=data_process_steps, unaligned=True, mode="test", ), batch_size=5, #shuffle=True, num_workers=4, ) # Build Model Gen_AB = ResNetGenerator(input_shape).to(device) Gen_BA = ResNetGenerator(input_shape).to(device) Dis_A = Discriminator(input_shape).to(device) Dis_B = Discriminator(input_shape).to(device) # Loss Function criterion_GAN = torch.nn.MSELoss() criterion_cycle = torch.nn.L1Loss() criterion_identity = torch.nn.L1Loss() # Optimizer opt_G = torch.optim.Adam( itertools.chain(Gen_AB.parameters(),Gen_BA.parameters()), lr=0.00001 ) opt_D_A = torch.optim.Adam( Dis_A.parameters(), lr = 0.00001 ) opt_D_B = torch.optim.Adam( Dis_B.parameters(), lr = 0.00001 ) # Learning rate update schedulers lr_scheduler_G = torch.optim.lr_scheduler.LambdaLR( opt_G, lr_lambda=LambdaLR(epochs, last_epoch, decay_epoch).step ) lr_scheduler_D_A = torch.optim.lr_scheduler.LambdaLR( opt_D_A, lr_lambda=LambdaLR(epochs, last_epoch, decay_epoch).step ) lr_scheduler_D_B = torch.optim.lr_scheduler.LambdaLR( opt_D_B, lr_lambda=LambdaLR(epochs, last_epoch, decay_epoch).step ) # Buffers of previously generated samples fake_A_buffer = ReplayBuffer() fake_B_buffer = ReplayBuffer() #這邊就是輸出的影像 如果要呈現更多影像 改這邊 def sample_images(batches_done): """Saves a generated sample from the test set""" imgs = next(iter(test_data)) Gen_AB.eval() Gen_BA.eval() real_A = Variable(imgs["A"].type(Tensor)) fake_B = Gen_AB(real_A) real_B = Variable(imgs["B"].type(Tensor)) fake_A = Gen_BA(real_B) # Arange images along x-axis real_A = make_grid(real_A, nrow=5, normalize=True) real_B = make_grid(real_B, nrow=5, normalize=True) fake_A = make_grid(fake_A, nrow=5, normalize=True) fake_B = make_grid(fake_B, nrow=5, normalize=True) # Arange images along y-axis image_grid = torch.cat((real_A, fake_B, real_B, fake_A), 1) save_image(image_grid, "Images/%s/%s.png" % (dataset_name, batches_done), normalize=False) # train G_l=[] # load model (如果沒有自己註解掉 這邊的目的是你可以把上次train的參數輸入進去 繼續訓練) Gen_AB.load_state_dict(torch.load("saved_models/male2female/G_AB_%s.pth"%last_epoch)) Gen_BA.load_state_dict(torch.load("saved_models/male2female/G_BA_%s.pth"%last_epoch)) Dis_A.load_state_dict(torch.load("saved_models/male2female/D_A_%s.pth"%last_epoch)) Dis_B.load_state_dict(torch.load("saved_models/male2female/D_B_%s.pth" % last_epoch)) opt_G.load_state_dict(torch.load("saved_models/male2female/opt_G_%s.pth" % last_epoch)) opt_D_A.load_state_dict(torch.load("saved_models/male2female/opt_D_A_%s.pth" % last_epoch)) opt_D_B.load_state_dict(torch.load("saved_models/male2female/opt_D_B_%s.pth" % last_epoch)) for epoch in range(last_epoch+1, epochs): G_ll=[] for i, batch in enumerate(train_data): # Set model input real_A = Variable(batch["A"].type(Tensor)) real_B = Variable(batch["B"].type(Tensor)) # Adversarial ground truths valid = Variable(Tensor(np.ones((real_A.size(0), *Dis_A.output_shape))), requires_grad=False) fake = Variable(Tensor(np.zeros((real_A.size(0), *Dis_A.output_shape))), requires_grad=False) # # Train Generators # Gen_AB.train() Gen_BA.train() opt_G.zero_grad() # Identity loss loss_id_A = criterion_identity(Gen_BA(real_A), real_A) loss_id_B = criterion_identity(Gen_AB(real_B), real_B) loss_identity = (loss_id_A + loss_id_B) / 2 #print(loss_identity) # GAN loss fake_B = Gen_AB(real_A) loss_GAN_AB = criterion_GAN(Dis_B(fake_B), valid) fake_A = Gen_BA(real_B) loss_GAN_BA = criterion_GAN(Dis_A(fake_A), valid) loss_GAN = (loss_GAN_AB + loss_GAN_BA) / 2 # Cycle loss recov_A = Gen_BA(fake_B) loss_cycle_A = criterion_cycle(recov_A, real_A) recov_B = Gen_AB(fake_A) loss_cycle_B = criterion_cycle(recov_B, real_B) loss_cycle = (loss_cycle_A + loss_cycle_B) / 2 # Total loss loss_G = loss_GAN + 10.0 * loss_cycle + 5.0 * loss_identity loss_G.backward() opt_G.step() # # Train Discriminator A # opt_D_A.zero_grad() # Real loss loss_real = criterion_GAN(Dis_A(real_A), valid) # Fake loss (on batch of previously generated samples) fake_A_ = fake_A_buffer.push_and_pop(fake_A) loss_fake = criterion_GAN(Dis_A(fake_A_.detach()), fake) # Total loss loss_D_A = (loss_real + loss_fake) /2 loss_D_A.backward() opt_D_A.step() # # Train Discrimainator B # opt_D_B.zero_grad() # Real loss loss_real = criterion_GAN(Dis_B(real_B), valid) # Fake loss (on batch of previously generated samples) fake_B_ = fake_B_buffer.push_and_pop(fake_B) loss_fake = criterion_GAN(Dis_B(fake_B_.detach()), fake) # Total loss loss_D_B = (loss_real + loss_fake) / 2 loss_D_B.backward() opt_D_B.step() loss_D = (loss_D_A + loss_D_B) / 2 # # Log progress # batches_done = epoch * len(train_data) + i G_ll.append(loss_G.item()) print("Epoch: {}/{}, Batch: {}/{}, D loss: {:.4f}, G loss: {:.4f}, adv loss: {:.4f}, cycle loss: {:.4f}, idenity: {:.4f}".format(epoch,epochs,i,len(train_data),loss_D.item(),loss_G.item(),loss_GAN.item(),loss_cycle.item(),loss_identity.item())) # If at sample interval save image if batches_done % sample_interval == 0: sample_images(batches_done) G_l.append(sum(G_ll) / len(G_ll)) # Update learning rates lr_scheduler_G.step() lr_scheduler_D_A.step() lr_scheduler_D_B.step() torch.save(Gen_AB.state_dict(), "saved_models/%s/G_AB_%d.pth" % (dataset_name, epoch)) torch.save(Gen_BA.state_dict(), "saved_models/%s/G_BA_%d.pth" % (dataset_name, epoch)) torch.save(Dis_A.state_dict(), "saved_models/%s/D_A_%d.pth" % (dataset_name, epoch)) torch.save(Dis_B.state_dict(), "saved_models/%s/D_B_%d.pth" % (dataset_name, epoch)) torch.save(opt_G.state_dict(), "saved_models/%s/opt_G_%d.pth" % (dataset_name, epoch)) torch.save(opt_D_A.state_dict(), "saved_models/%s/opt_D_A_%d.pth" % (dataset_name, epoch)) torch.save(opt_D_B.state_dict(), "saved_models/%s/opt_D_B_%d.pth" % (dataset_name, epoch)) with open("loss.txt", "w") as f: for i in G_l: f.write("%f " % i) if __name__ == "__main__": train()
{"/train.py": ["/model.py"]}
53,216
wahahahaya/CycleGAN-Male2Female
refs/heads/main
/model.py
import torch import numpy as np class ResidualBlock(torch.nn.Module): def __init__(self, in_channel): super(ResidualBlock, self).__init__() self.conv1 = torch.nn.Conv2d( in_channels=in_channel, out_channels=in_channel, kernel_size=3, stride=1, padding=1, padding_mode='reflect', ) self.bn1 = torch.nn.InstanceNorm2d(in_channel) self.conv2 = torch.nn.Conv2d( in_channels=in_channel, out_channels=in_channel, kernel_size=3, stride=1, padding=1, padding_mode='reflect', ) self.bn2 = torch.nn.InstanceNorm2d(in_channel) self.relu = torch.nn.ReLU() def forward(self, x): identity = x.clone() x = self.conv1(x) x = self.bn1(x) x = self.relu(x) x = self.conv2(x) x = self.bn2(x) x += identity #x = self.relu(x) return x class ResNetGenerator(torch.nn.Module): def __init__(self, input_shape): super(ResNetGenerator, self).__init__() channels = input_shape[0] self.gen = torch.nn.Sequential( # initial convolution block torch.nn.Conv2d( in_channels=channels, out_channels=64, kernel_size=7, stride=1, padding=3, padding_mode='reflect', ), torch.nn.InstanceNorm2d(64), torch.nn.ReLU(inplace=True), # downsampling torch.nn.Conv2d( in_channels=64, out_channels=128, kernel_size=3, stride=2, padding=1, padding_mode='reflect', ), torch.nn.InstanceNorm2d(128), torch.nn.ReLU(inplace=True), torch.nn.Conv2d( in_channels=128, out_channels=256, kernel_size=3, stride=2, padding=1, padding_mode='reflect', ), torch.nn.InstanceNorm2d(256), torch.nn.ReLU(inplace=True), # residual blocks ResidualBlock(256), ResidualBlock(256), ResidualBlock(256), ResidualBlock(256), ResidualBlock(256), ResidualBlock(256), ResidualBlock(256), ResidualBlock(256), ResidualBlock(256), # upsampling torch.nn.ConvTranspose2d( in_channels=256, out_channels=128, kernel_size=3, stride=2, padding=1, output_padding=1 ), torch.nn.InstanceNorm2d(128), torch.nn.ReLU(inplace=True), torch.nn.ConvTranspose2d( in_channels=128, out_channels=64, kernel_size=3, stride=2, padding=1, output_padding=1, ), torch.nn.InstanceNorm2d(64), torch.nn.ReLU(inplace=True), # output layer torch.nn.Conv2d( in_channels=64, out_channels=3, kernel_size=7, stride=1, padding=3 ), torch.nn.Tanh() ) def forward(self,x): return self.gen(x) class Discriminator(torch.nn.Module): def __init__(self, input_shape): super(Discriminator, self).__init__() channels, height, width = input_shape self.output_shape = (1, 6, 6) self.dis = torch.nn.Sequential( torch.nn.Conv2d( in_channels=channels, out_channels=64, kernel_size=4, stride=2, padding=1, ), torch.nn.LeakyReLU(0.2, True), torch.nn.Conv2d( in_channels=64, out_channels=128, kernel_size=4, stride=2, padding=1, ), torch.nn.InstanceNorm2d(128), torch.nn.LeakyReLU(0.2, True), torch.nn.Conv2d( in_channels=128, out_channels=256, kernel_size=4, stride=2, padding=1, ), torch.nn.InstanceNorm2d(256), torch.nn.LeakyReLU(0.2, True), torch.nn.Conv2d( in_channels=256, out_channels=512, kernel_size=4, stride=2, padding=1, ), torch.nn.InstanceNorm2d(512), torch.nn.LeakyReLU(0.2, True), torch.nn.ZeroPad2d((1,0,1,0)), torch.nn.Conv2d( in_channels=512, out_channels=1, kernel_size=4, padding=1 ) ) def forward(self,x): return self.dis(x) # if __name__ == "__main__": # device = "cuda" if torch.cuda.is_available() else "cpu" # x = torch.randn(3, 3, 224, 224).to(device) # model = Discriminator().to(device) # print(model(x).shape)
{"/train.py": ["/model.py"]}
53,218
montlebalm/BlackjackStrategies
refs/heads/master
/tests/strategies/test_HiLowCardCounter.py
from strategies import HiLowCardCounter from models import Card def test_hits_if_low_score(): s = HiLowCardCounter() hole_cards = [Card(11)] assert s.hit_on(hole_cards, [], None) == True def test_hits_if_high_score_and_low_deck(): s = HiLowCardCounter() hole_cards = [Card(14)] remaining_cards = [Card(2, "2")] assert s.hit_on(hole_cards, remaining_cards, None) == True
{"/tests/strategies/test_HiLowCardCounter.py": ["/strategies/__init__.py", "/models/__init__.py"], "/tests/strategies/test_HitBelow.py": ["/strategies/__init__.py", "/models/__init__.py"], "/strategies/HitBelow.py": ["/strategies/__init__.py", "/helpers/cards.py"], "/tests/models/test_Card.py": ["/models/Card.py"], "/strategies/Psychic.py": ["/strategies/__init__.py", "/helpers/cards.py"], "/tests/models/test_Deck.py": ["/models/Deck.py"], "/strategies/__init__.py": ["/strategies/Strategy.py", "/strategies/Dealer.py", "/strategies/HitBelow.py", "/strategies/Psychic.py", "/strategies/HiLowCardCounter.py"], "/models/__init__.py": ["/models/Card.py", "/models/Deck.py", "/models/Game.py"], "/tests/strategies/test_Dealer.py": ["/strategies/__init__.py", "/models/__init__.py"], "/tests/models/test_Game.py": ["/models/__init__.py", "/strategies/__init__.py"], "/tests/strategies/test_Psychic.py": ["/strategies/__init__.py", "/models/__init__.py"], "/models/Deck.py": ["/models/Card.py"], "/main.py": ["/models/__init__.py", "/strategies/__init__.py"], "/models/Game.py": ["/helpers/cards.py"], "/strategies/HiLowCardCounter.py": ["/strategies/__init__.py", "/helpers/cards.py"], "/strategies/Dealer.py": ["/strategies/__init__.py", "/helpers/cards.py"]}
53,219
montlebalm/BlackjackStrategies
refs/heads/master
/tests/strategies/test_HitBelow.py
from strategies import HitBelow from models import Card def test_hits_below_limit(): s = HitBelow(10) cards = [Card([1]), Card([1])] assert s.hit_on(cards, [], None) == True def test_stays_above_limit(): s = HitBelow(10) cards = [Card([6]), Card([6])] assert s.hit_on(cards, [], None) == False
{"/tests/strategies/test_HiLowCardCounter.py": ["/strategies/__init__.py", "/models/__init__.py"], "/tests/strategies/test_HitBelow.py": ["/strategies/__init__.py", "/models/__init__.py"], "/strategies/HitBelow.py": ["/strategies/__init__.py", "/helpers/cards.py"], "/tests/models/test_Card.py": ["/models/Card.py"], "/strategies/Psychic.py": ["/strategies/__init__.py", "/helpers/cards.py"], "/tests/models/test_Deck.py": ["/models/Deck.py"], "/strategies/__init__.py": ["/strategies/Strategy.py", "/strategies/Dealer.py", "/strategies/HitBelow.py", "/strategies/Psychic.py", "/strategies/HiLowCardCounter.py"], "/models/__init__.py": ["/models/Card.py", "/models/Deck.py", "/models/Game.py"], "/tests/strategies/test_Dealer.py": ["/strategies/__init__.py", "/models/__init__.py"], "/tests/models/test_Game.py": ["/models/__init__.py", "/strategies/__init__.py"], "/tests/strategies/test_Psychic.py": ["/strategies/__init__.py", "/models/__init__.py"], "/models/Deck.py": ["/models/Card.py"], "/main.py": ["/models/__init__.py", "/strategies/__init__.py"], "/models/Game.py": ["/helpers/cards.py"], "/strategies/HiLowCardCounter.py": ["/strategies/__init__.py", "/helpers/cards.py"], "/strategies/Dealer.py": ["/strategies/__init__.py", "/helpers/cards.py"]}
53,220
montlebalm/BlackjackStrategies
refs/heads/master
/strategies/HitBelow.py
from strategies import Strategy from helpers.cards import card_total class HitBelow(Strategy): name = "HitBelow" def __init__(self, limit): self.limit = limit self.name += str(limit) def hit_on(self, cards, remaining_cards, dealer_card): return card_total(cards) < self.limit
{"/tests/strategies/test_HiLowCardCounter.py": ["/strategies/__init__.py", "/models/__init__.py"], "/tests/strategies/test_HitBelow.py": ["/strategies/__init__.py", "/models/__init__.py"], "/strategies/HitBelow.py": ["/strategies/__init__.py", "/helpers/cards.py"], "/tests/models/test_Card.py": ["/models/Card.py"], "/strategies/Psychic.py": ["/strategies/__init__.py", "/helpers/cards.py"], "/tests/models/test_Deck.py": ["/models/Deck.py"], "/strategies/__init__.py": ["/strategies/Strategy.py", "/strategies/Dealer.py", "/strategies/HitBelow.py", "/strategies/Psychic.py", "/strategies/HiLowCardCounter.py"], "/models/__init__.py": ["/models/Card.py", "/models/Deck.py", "/models/Game.py"], "/tests/strategies/test_Dealer.py": ["/strategies/__init__.py", "/models/__init__.py"], "/tests/models/test_Game.py": ["/models/__init__.py", "/strategies/__init__.py"], "/tests/strategies/test_Psychic.py": ["/strategies/__init__.py", "/models/__init__.py"], "/models/Deck.py": ["/models/Card.py"], "/main.py": ["/models/__init__.py", "/strategies/__init__.py"], "/models/Game.py": ["/helpers/cards.py"], "/strategies/HiLowCardCounter.py": ["/strategies/__init__.py", "/helpers/cards.py"], "/strategies/Dealer.py": ["/strategies/__init__.py", "/helpers/cards.py"]}
53,221
montlebalm/BlackjackStrategies
refs/heads/master
/tests/models/test_Card.py
from models.Card import Card def test_stores_values_as_list(): c = Card(1, "Test") assert c.values.pop
{"/tests/strategies/test_HiLowCardCounter.py": ["/strategies/__init__.py", "/models/__init__.py"], "/tests/strategies/test_HitBelow.py": ["/strategies/__init__.py", "/models/__init__.py"], "/strategies/HitBelow.py": ["/strategies/__init__.py", "/helpers/cards.py"], "/tests/models/test_Card.py": ["/models/Card.py"], "/strategies/Psychic.py": ["/strategies/__init__.py", "/helpers/cards.py"], "/tests/models/test_Deck.py": ["/models/Deck.py"], "/strategies/__init__.py": ["/strategies/Strategy.py", "/strategies/Dealer.py", "/strategies/HitBelow.py", "/strategies/Psychic.py", "/strategies/HiLowCardCounter.py"], "/models/__init__.py": ["/models/Card.py", "/models/Deck.py", "/models/Game.py"], "/tests/strategies/test_Dealer.py": ["/strategies/__init__.py", "/models/__init__.py"], "/tests/models/test_Game.py": ["/models/__init__.py", "/strategies/__init__.py"], "/tests/strategies/test_Psychic.py": ["/strategies/__init__.py", "/models/__init__.py"], "/models/Deck.py": ["/models/Card.py"], "/main.py": ["/models/__init__.py", "/strategies/__init__.py"], "/models/Game.py": ["/helpers/cards.py"], "/strategies/HiLowCardCounter.py": ["/strategies/__init__.py", "/helpers/cards.py"], "/strategies/Dealer.py": ["/strategies/__init__.py", "/helpers/cards.py"]}
53,222
montlebalm/BlackjackStrategies
refs/heads/master
/strategies/Strategy.py
class Strategy(object): name = "None" def hit_on(self, cards, remaining_cards, dealer_card): raise def __str__(self): return self.name
{"/tests/strategies/test_HiLowCardCounter.py": ["/strategies/__init__.py", "/models/__init__.py"], "/tests/strategies/test_HitBelow.py": ["/strategies/__init__.py", "/models/__init__.py"], "/strategies/HitBelow.py": ["/strategies/__init__.py", "/helpers/cards.py"], "/tests/models/test_Card.py": ["/models/Card.py"], "/strategies/Psychic.py": ["/strategies/__init__.py", "/helpers/cards.py"], "/tests/models/test_Deck.py": ["/models/Deck.py"], "/strategies/__init__.py": ["/strategies/Strategy.py", "/strategies/Dealer.py", "/strategies/HitBelow.py", "/strategies/Psychic.py", "/strategies/HiLowCardCounter.py"], "/models/__init__.py": ["/models/Card.py", "/models/Deck.py", "/models/Game.py"], "/tests/strategies/test_Dealer.py": ["/strategies/__init__.py", "/models/__init__.py"], "/tests/models/test_Game.py": ["/models/__init__.py", "/strategies/__init__.py"], "/tests/strategies/test_Psychic.py": ["/strategies/__init__.py", "/models/__init__.py"], "/models/Deck.py": ["/models/Card.py"], "/main.py": ["/models/__init__.py", "/strategies/__init__.py"], "/models/Game.py": ["/helpers/cards.py"], "/strategies/HiLowCardCounter.py": ["/strategies/__init__.py", "/helpers/cards.py"], "/strategies/Dealer.py": ["/strategies/__init__.py", "/helpers/cards.py"]}
53,223
montlebalm/BlackjackStrategies
refs/heads/master
/models/Card.py
class Card(object): def __init__(self, values, name=""): self.name = name try: # Try to treat the value as a list first self.values = list(values) except: self.values = [values]
{"/tests/strategies/test_HiLowCardCounter.py": ["/strategies/__init__.py", "/models/__init__.py"], "/tests/strategies/test_HitBelow.py": ["/strategies/__init__.py", "/models/__init__.py"], "/strategies/HitBelow.py": ["/strategies/__init__.py", "/helpers/cards.py"], "/tests/models/test_Card.py": ["/models/Card.py"], "/strategies/Psychic.py": ["/strategies/__init__.py", "/helpers/cards.py"], "/tests/models/test_Deck.py": ["/models/Deck.py"], "/strategies/__init__.py": ["/strategies/Strategy.py", "/strategies/Dealer.py", "/strategies/HitBelow.py", "/strategies/Psychic.py", "/strategies/HiLowCardCounter.py"], "/models/__init__.py": ["/models/Card.py", "/models/Deck.py", "/models/Game.py"], "/tests/strategies/test_Dealer.py": ["/strategies/__init__.py", "/models/__init__.py"], "/tests/models/test_Game.py": ["/models/__init__.py", "/strategies/__init__.py"], "/tests/strategies/test_Psychic.py": ["/strategies/__init__.py", "/models/__init__.py"], "/models/Deck.py": ["/models/Card.py"], "/main.py": ["/models/__init__.py", "/strategies/__init__.py"], "/models/Game.py": ["/helpers/cards.py"], "/strategies/HiLowCardCounter.py": ["/strategies/__init__.py", "/helpers/cards.py"], "/strategies/Dealer.py": ["/strategies/__init__.py", "/helpers/cards.py"]}
53,224
montlebalm/BlackjackStrategies
refs/heads/master
/strategies/Psychic.py
from strategies import Strategy from helpers.cards import card_total class Psychic(Strategy): name = "Psychic" def hit_on(self, cards, remaining_cards, dealer_card): # Cheat by looking at the next card to see if we'll bust return card_total(cards + [remaining_cards[-1]]) <= 21
{"/tests/strategies/test_HiLowCardCounter.py": ["/strategies/__init__.py", "/models/__init__.py"], "/tests/strategies/test_HitBelow.py": ["/strategies/__init__.py", "/models/__init__.py"], "/strategies/HitBelow.py": ["/strategies/__init__.py", "/helpers/cards.py"], "/tests/models/test_Card.py": ["/models/Card.py"], "/strategies/Psychic.py": ["/strategies/__init__.py", "/helpers/cards.py"], "/tests/models/test_Deck.py": ["/models/Deck.py"], "/strategies/__init__.py": ["/strategies/Strategy.py", "/strategies/Dealer.py", "/strategies/HitBelow.py", "/strategies/Psychic.py", "/strategies/HiLowCardCounter.py"], "/models/__init__.py": ["/models/Card.py", "/models/Deck.py", "/models/Game.py"], "/tests/strategies/test_Dealer.py": ["/strategies/__init__.py", "/models/__init__.py"], "/tests/models/test_Game.py": ["/models/__init__.py", "/strategies/__init__.py"], "/tests/strategies/test_Psychic.py": ["/strategies/__init__.py", "/models/__init__.py"], "/models/Deck.py": ["/models/Card.py"], "/main.py": ["/models/__init__.py", "/strategies/__init__.py"], "/models/Game.py": ["/helpers/cards.py"], "/strategies/HiLowCardCounter.py": ["/strategies/__init__.py", "/helpers/cards.py"], "/strategies/Dealer.py": ["/strategies/__init__.py", "/helpers/cards.py"]}
53,225
montlebalm/BlackjackStrategies
refs/heads/master
/tests/models/test_Deck.py
from models.Deck import Deck def test_contains_52_cards(): d = Deck() assert len(d.cards) == 52 def test_cards_are_shuffled(): d1 = Deck() d2 = Deck() # Find all the indexes where cards from d1 and d2 are identical dupes = [c.values == d2.cards[i] for i, c in enumerate(d1.cards)] # all() should return False if any of the indexes didn't match assert all(dupes) == False def test_contains_4_of_each_card(): d = Deck() counts = {c.name: 0 for c in d.cards} for card in d.cards: counts[card.name] += 1 for name in counts: assert counts[name] == 4 def test_returns_next_card(): d = Deck() assert d.next_card() == d.get_next_card()
{"/tests/strategies/test_HiLowCardCounter.py": ["/strategies/__init__.py", "/models/__init__.py"], "/tests/strategies/test_HitBelow.py": ["/strategies/__init__.py", "/models/__init__.py"], "/strategies/HitBelow.py": ["/strategies/__init__.py", "/helpers/cards.py"], "/tests/models/test_Card.py": ["/models/Card.py"], "/strategies/Psychic.py": ["/strategies/__init__.py", "/helpers/cards.py"], "/tests/models/test_Deck.py": ["/models/Deck.py"], "/strategies/__init__.py": ["/strategies/Strategy.py", "/strategies/Dealer.py", "/strategies/HitBelow.py", "/strategies/Psychic.py", "/strategies/HiLowCardCounter.py"], "/models/__init__.py": ["/models/Card.py", "/models/Deck.py", "/models/Game.py"], "/tests/strategies/test_Dealer.py": ["/strategies/__init__.py", "/models/__init__.py"], "/tests/models/test_Game.py": ["/models/__init__.py", "/strategies/__init__.py"], "/tests/strategies/test_Psychic.py": ["/strategies/__init__.py", "/models/__init__.py"], "/models/Deck.py": ["/models/Card.py"], "/main.py": ["/models/__init__.py", "/strategies/__init__.py"], "/models/Game.py": ["/helpers/cards.py"], "/strategies/HiLowCardCounter.py": ["/strategies/__init__.py", "/helpers/cards.py"], "/strategies/Dealer.py": ["/strategies/__init__.py", "/helpers/cards.py"]}
53,226
montlebalm/BlackjackStrategies
refs/heads/master
/strategies/__init__.py
from strategies.Strategy import * from strategies.Dealer import * from strategies.HitBelow import * from strategies.Psychic import * from strategies.HiLowCardCounter import *
{"/tests/strategies/test_HiLowCardCounter.py": ["/strategies/__init__.py", "/models/__init__.py"], "/tests/strategies/test_HitBelow.py": ["/strategies/__init__.py", "/models/__init__.py"], "/strategies/HitBelow.py": ["/strategies/__init__.py", "/helpers/cards.py"], "/tests/models/test_Card.py": ["/models/Card.py"], "/strategies/Psychic.py": ["/strategies/__init__.py", "/helpers/cards.py"], "/tests/models/test_Deck.py": ["/models/Deck.py"], "/strategies/__init__.py": ["/strategies/Strategy.py", "/strategies/Dealer.py", "/strategies/HitBelow.py", "/strategies/Psychic.py", "/strategies/HiLowCardCounter.py"], "/models/__init__.py": ["/models/Card.py", "/models/Deck.py", "/models/Game.py"], "/tests/strategies/test_Dealer.py": ["/strategies/__init__.py", "/models/__init__.py"], "/tests/models/test_Game.py": ["/models/__init__.py", "/strategies/__init__.py"], "/tests/strategies/test_Psychic.py": ["/strategies/__init__.py", "/models/__init__.py"], "/models/Deck.py": ["/models/Card.py"], "/main.py": ["/models/__init__.py", "/strategies/__init__.py"], "/models/Game.py": ["/helpers/cards.py"], "/strategies/HiLowCardCounter.py": ["/strategies/__init__.py", "/helpers/cards.py"], "/strategies/Dealer.py": ["/strategies/__init__.py", "/helpers/cards.py"]}
53,227
montlebalm/BlackjackStrategies
refs/heads/master
/models/__init__.py
from models.Card import * from models.Deck import * from models.Game import *
{"/tests/strategies/test_HiLowCardCounter.py": ["/strategies/__init__.py", "/models/__init__.py"], "/tests/strategies/test_HitBelow.py": ["/strategies/__init__.py", "/models/__init__.py"], "/strategies/HitBelow.py": ["/strategies/__init__.py", "/helpers/cards.py"], "/tests/models/test_Card.py": ["/models/Card.py"], "/strategies/Psychic.py": ["/strategies/__init__.py", "/helpers/cards.py"], "/tests/models/test_Deck.py": ["/models/Deck.py"], "/strategies/__init__.py": ["/strategies/Strategy.py", "/strategies/Dealer.py", "/strategies/HitBelow.py", "/strategies/Psychic.py", "/strategies/HiLowCardCounter.py"], "/models/__init__.py": ["/models/Card.py", "/models/Deck.py", "/models/Game.py"], "/tests/strategies/test_Dealer.py": ["/strategies/__init__.py", "/models/__init__.py"], "/tests/models/test_Game.py": ["/models/__init__.py", "/strategies/__init__.py"], "/tests/strategies/test_Psychic.py": ["/strategies/__init__.py", "/models/__init__.py"], "/models/Deck.py": ["/models/Card.py"], "/main.py": ["/models/__init__.py", "/strategies/__init__.py"], "/models/Game.py": ["/helpers/cards.py"], "/strategies/HiLowCardCounter.py": ["/strategies/__init__.py", "/helpers/cards.py"], "/strategies/Dealer.py": ["/strategies/__init__.py", "/helpers/cards.py"]}
53,228
montlebalm/BlackjackStrategies
refs/heads/master
/tests/strategies/test_Dealer.py
from strategies import Dealer from models import Card def test_hits_below_limit(): s = Dealer() cards = [Card([16])] assert s.hit_on(cards, [], None) == True def test_stays_at_limit(): s = Dealer() cards = [Card([17])] assert s.hit_on(cards, [], None) == False def test_stays_above_limit(): s = Dealer() cards = [Card([17]), Card([1])] assert s.hit_on(cards, [], None) == False
{"/tests/strategies/test_HiLowCardCounter.py": ["/strategies/__init__.py", "/models/__init__.py"], "/tests/strategies/test_HitBelow.py": ["/strategies/__init__.py", "/models/__init__.py"], "/strategies/HitBelow.py": ["/strategies/__init__.py", "/helpers/cards.py"], "/tests/models/test_Card.py": ["/models/Card.py"], "/strategies/Psychic.py": ["/strategies/__init__.py", "/helpers/cards.py"], "/tests/models/test_Deck.py": ["/models/Deck.py"], "/strategies/__init__.py": ["/strategies/Strategy.py", "/strategies/Dealer.py", "/strategies/HitBelow.py", "/strategies/Psychic.py", "/strategies/HiLowCardCounter.py"], "/models/__init__.py": ["/models/Card.py", "/models/Deck.py", "/models/Game.py"], "/tests/strategies/test_Dealer.py": ["/strategies/__init__.py", "/models/__init__.py"], "/tests/models/test_Game.py": ["/models/__init__.py", "/strategies/__init__.py"], "/tests/strategies/test_Psychic.py": ["/strategies/__init__.py", "/models/__init__.py"], "/models/Deck.py": ["/models/Card.py"], "/main.py": ["/models/__init__.py", "/strategies/__init__.py"], "/models/Game.py": ["/helpers/cards.py"], "/strategies/HiLowCardCounter.py": ["/strategies/__init__.py", "/helpers/cards.py"], "/strategies/Dealer.py": ["/strategies/__init__.py", "/helpers/cards.py"]}
53,229
montlebalm/BlackjackStrategies
refs/heads/master
/helpers/cards.py
def card_total(cards): return sum([c.values[0] for c in cards])
{"/tests/strategies/test_HiLowCardCounter.py": ["/strategies/__init__.py", "/models/__init__.py"], "/tests/strategies/test_HitBelow.py": ["/strategies/__init__.py", "/models/__init__.py"], "/strategies/HitBelow.py": ["/strategies/__init__.py", "/helpers/cards.py"], "/tests/models/test_Card.py": ["/models/Card.py"], "/strategies/Psychic.py": ["/strategies/__init__.py", "/helpers/cards.py"], "/tests/models/test_Deck.py": ["/models/Deck.py"], "/strategies/__init__.py": ["/strategies/Strategy.py", "/strategies/Dealer.py", "/strategies/HitBelow.py", "/strategies/Psychic.py", "/strategies/HiLowCardCounter.py"], "/models/__init__.py": ["/models/Card.py", "/models/Deck.py", "/models/Game.py"], "/tests/strategies/test_Dealer.py": ["/strategies/__init__.py", "/models/__init__.py"], "/tests/models/test_Game.py": ["/models/__init__.py", "/strategies/__init__.py"], "/tests/strategies/test_Psychic.py": ["/strategies/__init__.py", "/models/__init__.py"], "/models/Deck.py": ["/models/Card.py"], "/main.py": ["/models/__init__.py", "/strategies/__init__.py"], "/models/Game.py": ["/helpers/cards.py"], "/strategies/HiLowCardCounter.py": ["/strategies/__init__.py", "/helpers/cards.py"], "/strategies/Dealer.py": ["/strategies/__init__.py", "/helpers/cards.py"]}
53,230
montlebalm/BlackjackStrategies
refs/heads/master
/tests/models/test_Game.py
from nose.tools import raises from models import Deck, Game from strategies import Dealer, HitBelow @raises(Exception) def test_raises_with_no_dealer(): gamblers = [HitBelow(1)] Game(None, gamblers, Deck) @raises(Exception) def test_raises_with_no_gamblers(): Game(Dealer(), [], Deck) @raises(Exception) def test_raises_without_deck_factory(): gamblers = [HitBelow(1)] Game(Dealer(), gamblers, None)
{"/tests/strategies/test_HiLowCardCounter.py": ["/strategies/__init__.py", "/models/__init__.py"], "/tests/strategies/test_HitBelow.py": ["/strategies/__init__.py", "/models/__init__.py"], "/strategies/HitBelow.py": ["/strategies/__init__.py", "/helpers/cards.py"], "/tests/models/test_Card.py": ["/models/Card.py"], "/strategies/Psychic.py": ["/strategies/__init__.py", "/helpers/cards.py"], "/tests/models/test_Deck.py": ["/models/Deck.py"], "/strategies/__init__.py": ["/strategies/Strategy.py", "/strategies/Dealer.py", "/strategies/HitBelow.py", "/strategies/Psychic.py", "/strategies/HiLowCardCounter.py"], "/models/__init__.py": ["/models/Card.py", "/models/Deck.py", "/models/Game.py"], "/tests/strategies/test_Dealer.py": ["/strategies/__init__.py", "/models/__init__.py"], "/tests/models/test_Game.py": ["/models/__init__.py", "/strategies/__init__.py"], "/tests/strategies/test_Psychic.py": ["/strategies/__init__.py", "/models/__init__.py"], "/models/Deck.py": ["/models/Card.py"], "/main.py": ["/models/__init__.py", "/strategies/__init__.py"], "/models/Game.py": ["/helpers/cards.py"], "/strategies/HiLowCardCounter.py": ["/strategies/__init__.py", "/helpers/cards.py"], "/strategies/Dealer.py": ["/strategies/__init__.py", "/helpers/cards.py"]}
53,231
montlebalm/BlackjackStrategies
refs/heads/master
/tests/strategies/test_Psychic.py
from strategies import Psychic from models import Card def test_hits_if_wont_bust(): s = Psychic() cards = [Card([19])] assert s.hit_on(cards, [Card(2)], None) == True def test_stays_if_will_bust(): s = Psychic() cards = [Card([20])] assert s.hit_on(cards, [Card(2)], None) == False
{"/tests/strategies/test_HiLowCardCounter.py": ["/strategies/__init__.py", "/models/__init__.py"], "/tests/strategies/test_HitBelow.py": ["/strategies/__init__.py", "/models/__init__.py"], "/strategies/HitBelow.py": ["/strategies/__init__.py", "/helpers/cards.py"], "/tests/models/test_Card.py": ["/models/Card.py"], "/strategies/Psychic.py": ["/strategies/__init__.py", "/helpers/cards.py"], "/tests/models/test_Deck.py": ["/models/Deck.py"], "/strategies/__init__.py": ["/strategies/Strategy.py", "/strategies/Dealer.py", "/strategies/HitBelow.py", "/strategies/Psychic.py", "/strategies/HiLowCardCounter.py"], "/models/__init__.py": ["/models/Card.py", "/models/Deck.py", "/models/Game.py"], "/tests/strategies/test_Dealer.py": ["/strategies/__init__.py", "/models/__init__.py"], "/tests/models/test_Game.py": ["/models/__init__.py", "/strategies/__init__.py"], "/tests/strategies/test_Psychic.py": ["/strategies/__init__.py", "/models/__init__.py"], "/models/Deck.py": ["/models/Card.py"], "/main.py": ["/models/__init__.py", "/strategies/__init__.py"], "/models/Game.py": ["/helpers/cards.py"], "/strategies/HiLowCardCounter.py": ["/strategies/__init__.py", "/helpers/cards.py"], "/strategies/Dealer.py": ["/strategies/__init__.py", "/helpers/cards.py"]}
53,232
montlebalm/BlackjackStrategies
refs/heads/master
/models/Deck.py
from models.Card import Card from random import shuffle class Deck(object): def __init__(self): suit = [ Card(2, "2"), Card(3, "3"), Card(4, "4"), Card(5, "5"), Card(6, "6"), Card(7, "7"), Card(8, "8"), Card(9, "9"), Card(10, "10"), Card(10, "J"), Card(10, "K"), Card(10, "Q"), Card([11, 1], "A"), ] self.cards = suit * 4 # Shuffle the deck shuffle(self.cards) def get_next_card(self): return self.cards.pop() def next_card(self): return self.cards[-1]
{"/tests/strategies/test_HiLowCardCounter.py": ["/strategies/__init__.py", "/models/__init__.py"], "/tests/strategies/test_HitBelow.py": ["/strategies/__init__.py", "/models/__init__.py"], "/strategies/HitBelow.py": ["/strategies/__init__.py", "/helpers/cards.py"], "/tests/models/test_Card.py": ["/models/Card.py"], "/strategies/Psychic.py": ["/strategies/__init__.py", "/helpers/cards.py"], "/tests/models/test_Deck.py": ["/models/Deck.py"], "/strategies/__init__.py": ["/strategies/Strategy.py", "/strategies/Dealer.py", "/strategies/HitBelow.py", "/strategies/Psychic.py", "/strategies/HiLowCardCounter.py"], "/models/__init__.py": ["/models/Card.py", "/models/Deck.py", "/models/Game.py"], "/tests/strategies/test_Dealer.py": ["/strategies/__init__.py", "/models/__init__.py"], "/tests/models/test_Game.py": ["/models/__init__.py", "/strategies/__init__.py"], "/tests/strategies/test_Psychic.py": ["/strategies/__init__.py", "/models/__init__.py"], "/models/Deck.py": ["/models/Card.py"], "/main.py": ["/models/__init__.py", "/strategies/__init__.py"], "/models/Game.py": ["/helpers/cards.py"], "/strategies/HiLowCardCounter.py": ["/strategies/__init__.py", "/helpers/cards.py"], "/strategies/Dealer.py": ["/strategies/__init__.py", "/helpers/cards.py"]}
53,233
montlebalm/BlackjackStrategies
refs/heads/master
/main.py
from models import Deck, Game from strategies import Dealer, HitBelow, Psychic, HiLowCardCounter def report(player, wins, rounds): pct = game.wins[player] * 100 // rounds print("%s: %d%%" % (player.name, pct)) if __name__ == "__main__": rounds = 10000 dealer = Dealer() strats = [ HitBelow(17), HiLowCardCounter(), Psychic(), ] for strategy in strats: game = Game(dealer, strategy, Deck) for i in range(rounds): game.do_round() # Report report(dealer, game.wins[dealer], rounds) report(strategy, game.wins[strategy], rounds) print("")
{"/tests/strategies/test_HiLowCardCounter.py": ["/strategies/__init__.py", "/models/__init__.py"], "/tests/strategies/test_HitBelow.py": ["/strategies/__init__.py", "/models/__init__.py"], "/strategies/HitBelow.py": ["/strategies/__init__.py", "/helpers/cards.py"], "/tests/models/test_Card.py": ["/models/Card.py"], "/strategies/Psychic.py": ["/strategies/__init__.py", "/helpers/cards.py"], "/tests/models/test_Deck.py": ["/models/Deck.py"], "/strategies/__init__.py": ["/strategies/Strategy.py", "/strategies/Dealer.py", "/strategies/HitBelow.py", "/strategies/Psychic.py", "/strategies/HiLowCardCounter.py"], "/models/__init__.py": ["/models/Card.py", "/models/Deck.py", "/models/Game.py"], "/tests/strategies/test_Dealer.py": ["/strategies/__init__.py", "/models/__init__.py"], "/tests/models/test_Game.py": ["/models/__init__.py", "/strategies/__init__.py"], "/tests/strategies/test_Psychic.py": ["/strategies/__init__.py", "/models/__init__.py"], "/models/Deck.py": ["/models/Card.py"], "/main.py": ["/models/__init__.py", "/strategies/__init__.py"], "/models/Game.py": ["/helpers/cards.py"], "/strategies/HiLowCardCounter.py": ["/strategies/__init__.py", "/helpers/cards.py"], "/strategies/Dealer.py": ["/strategies/__init__.py", "/helpers/cards.py"]}
53,234
montlebalm/BlackjackStrategies
refs/heads/master
/models/Game.py
from helpers.cards import card_total class Game(object): def __init__(self, dealer, gambler, deck_factory): if dealer is None: raise Exception("You must have a dealer") if gambler is None: raise Exception("You must have a gambler") if deck_factory is None: raise Exception("You must have a deck factory") self.__dealer = dealer self.__player = gambler self.__players = [self.__dealer, gambler] self.__deck_factory = deck_factory self.__deck = None self.wins = {p: 0 for p in self.__players} def do_round(self): """Play a round of Blackjack with all players """ # Get every player's cards first hole_cards = {p: list(self.__next_cards(2)) for p in self.__players} dealer_card = hole_cards[self.__dealer][0] # Let players hit until they're satisfied final_cards = {p: self.__player_turn(p, hole_cards[p], dealer_card) for p in hole_cards} # Figure out who won winner = self.__get_winner(final_cards) if winner is not None: self.wins[winner] += 1 def __next_cards(self, count): """Get n number of cards from the deck """ for i in range(count): # Make sure we have a deck with enough cards if self.__deck is None or len(self.__deck.cards) == 0: self.__deck = self.__deck_factory() yield self.__deck.get_next_card() def __player_turn(self, player, hole_cards, dealer_card): """Employ the player's strategy to get the highest hand score """ cards = hole_cards[:] # Let players hit until they're satisfied or they bust while card_total(cards) < 21: # Make sure we have cards left in the deck if not self.__deck.cards: self.__deck = self.__deck_factory() if player.hit_on(cards, self.__deck.cards, dealer_card): cards += self.__next_cards(1) else: break return cards def __get_winner(self, player_cards): """Figure out who won based on the hands """ player_score = card_total(player_cards[self.__player]) player_count = len(player_cards[self.__player]) dealer_score = card_total(player_cards[self.__dealer]) dealer_count = len(player_cards[self.__dealer]) # Check who busted if dealer_score > 21 and player_score > 21: return None elif player_score > 21: return self.__dealer elif dealer_score > 21: return self.__player player_blackjack = player_score == 21 and player_count == 2 dealer_blackjack = dealer_score == 21 and dealer_count == 2 # Check for blackjacks if dealer_blackjack and player_blackjack: return None elif player_blackjack: return self.__player elif dealer_blackjack: return self.__dealer # Check "5-card rule" if dealer_count >= 5 and player_count >= 5: return None elif player_count >= 5: return self.__player elif dealer_count >= 5: return self.__dealer # Check point values if player_score == dealer_score: return None if player_score > dealer_score: return self.__player elif dealer_score > player_score: return self.__dealer
{"/tests/strategies/test_HiLowCardCounter.py": ["/strategies/__init__.py", "/models/__init__.py"], "/tests/strategies/test_HitBelow.py": ["/strategies/__init__.py", "/models/__init__.py"], "/strategies/HitBelow.py": ["/strategies/__init__.py", "/helpers/cards.py"], "/tests/models/test_Card.py": ["/models/Card.py"], "/strategies/Psychic.py": ["/strategies/__init__.py", "/helpers/cards.py"], "/tests/models/test_Deck.py": ["/models/Deck.py"], "/strategies/__init__.py": ["/strategies/Strategy.py", "/strategies/Dealer.py", "/strategies/HitBelow.py", "/strategies/Psychic.py", "/strategies/HiLowCardCounter.py"], "/models/__init__.py": ["/models/Card.py", "/models/Deck.py", "/models/Game.py"], "/tests/strategies/test_Dealer.py": ["/strategies/__init__.py", "/models/__init__.py"], "/tests/models/test_Game.py": ["/models/__init__.py", "/strategies/__init__.py"], "/tests/strategies/test_Psychic.py": ["/strategies/__init__.py", "/models/__init__.py"], "/models/Deck.py": ["/models/Card.py"], "/main.py": ["/models/__init__.py", "/strategies/__init__.py"], "/models/Game.py": ["/helpers/cards.py"], "/strategies/HiLowCardCounter.py": ["/strategies/__init__.py", "/helpers/cards.py"], "/strategies/Dealer.py": ["/strategies/__init__.py", "/helpers/cards.py"]}
53,235
montlebalm/BlackjackStrategies
refs/heads/master
/strategies/HiLowCardCounter.py
from strategies import Strategy from helpers.cards import card_total class HiLowCardCounter(Strategy): name = "HiLowCardCounter" # http://www.blackjackinfo.com/blackjack-school/blackjack-lesson-04.php pluses = ["2", "3", "4", "5", "6"] minuses = ["10", "J", "Q", "K", "A"] def hit_on(self, cards, remaining_cards, dealer_card): total = card_total(cards) # Always hit if we're too low if total <= 11: return True count = self.__card_count(remaining_cards) # Hit if the deck is stacked with low cards if total <= 15 and count > 0: return True return False def __card_count(self, cards): """Total up a count for the remaining cards. A positive value means the deck is full of low cards while negative means there are lots of highs. """ count = 0 for card in cards: if card.name in self.pluses: count += 1 elif card.name in self.minuses: count -= 1 return count
{"/tests/strategies/test_HiLowCardCounter.py": ["/strategies/__init__.py", "/models/__init__.py"], "/tests/strategies/test_HitBelow.py": ["/strategies/__init__.py", "/models/__init__.py"], "/strategies/HitBelow.py": ["/strategies/__init__.py", "/helpers/cards.py"], "/tests/models/test_Card.py": ["/models/Card.py"], "/strategies/Psychic.py": ["/strategies/__init__.py", "/helpers/cards.py"], "/tests/models/test_Deck.py": ["/models/Deck.py"], "/strategies/__init__.py": ["/strategies/Strategy.py", "/strategies/Dealer.py", "/strategies/HitBelow.py", "/strategies/Psychic.py", "/strategies/HiLowCardCounter.py"], "/models/__init__.py": ["/models/Card.py", "/models/Deck.py", "/models/Game.py"], "/tests/strategies/test_Dealer.py": ["/strategies/__init__.py", "/models/__init__.py"], "/tests/models/test_Game.py": ["/models/__init__.py", "/strategies/__init__.py"], "/tests/strategies/test_Psychic.py": ["/strategies/__init__.py", "/models/__init__.py"], "/models/Deck.py": ["/models/Card.py"], "/main.py": ["/models/__init__.py", "/strategies/__init__.py"], "/models/Game.py": ["/helpers/cards.py"], "/strategies/HiLowCardCounter.py": ["/strategies/__init__.py", "/helpers/cards.py"], "/strategies/Dealer.py": ["/strategies/__init__.py", "/helpers/cards.py"]}
53,236
montlebalm/BlackjackStrategies
refs/heads/master
/strategies/Dealer.py
from strategies import Strategy from helpers.cards import card_total class Dealer(Strategy): name = "Dealer" def hit_on(self, cards, remaining_cards, dealer_card=None): return card_total(cards) < 17
{"/tests/strategies/test_HiLowCardCounter.py": ["/strategies/__init__.py", "/models/__init__.py"], "/tests/strategies/test_HitBelow.py": ["/strategies/__init__.py", "/models/__init__.py"], "/strategies/HitBelow.py": ["/strategies/__init__.py", "/helpers/cards.py"], "/tests/models/test_Card.py": ["/models/Card.py"], "/strategies/Psychic.py": ["/strategies/__init__.py", "/helpers/cards.py"], "/tests/models/test_Deck.py": ["/models/Deck.py"], "/strategies/__init__.py": ["/strategies/Strategy.py", "/strategies/Dealer.py", "/strategies/HitBelow.py", "/strategies/Psychic.py", "/strategies/HiLowCardCounter.py"], "/models/__init__.py": ["/models/Card.py", "/models/Deck.py", "/models/Game.py"], "/tests/strategies/test_Dealer.py": ["/strategies/__init__.py", "/models/__init__.py"], "/tests/models/test_Game.py": ["/models/__init__.py", "/strategies/__init__.py"], "/tests/strategies/test_Psychic.py": ["/strategies/__init__.py", "/models/__init__.py"], "/models/Deck.py": ["/models/Card.py"], "/main.py": ["/models/__init__.py", "/strategies/__init__.py"], "/models/Game.py": ["/helpers/cards.py"], "/strategies/HiLowCardCounter.py": ["/strategies/__init__.py", "/helpers/cards.py"], "/strategies/Dealer.py": ["/strategies/__init__.py", "/helpers/cards.py"]}
53,260
alexdy2007/reidentification_hacky
refs/heads/master
/model/crop_face_from_image.py
from PIL import Image import face_recognition def crop_face_from_image(image_path): if isinstance(image_path, str): image = face_recognition.load_image_file(image_path) else: image = image_path faces_location = _get_face_locations_from_image(image_path) if len(faces_location) != 0: faces_location = faces_location[0] face_image = image[faces_location[0]:faces_location[2], faces_location[3]:faces_location[1]] pil_image = Image.fromarray(face_image,mode="RGB") return pil_image return None def _get_face_locations_from_image(image): face_locations = face_recognition.face_locations(image) return face_locations
{"/tests/db_tests/crud_test.py": ["/db_connection/PeopleDB.py"], "/tests/db_tests/test_insert_person_seen_from_camera.py": ["/sockets/PictureRecSocket.py", "/db_connection/Crud.py", "/model/compare_single_to_known_faces.py", "/model/get_feature_encoded_list.py"], "/webserver/main.py": ["/webserver/person/person.py", "/webserver/take_pictures/take_pictures.py", "/db_connection/PeopleDB.py", "/db_connection/MontageDB.py", "/webserver/apis/montage_api.py", "/sockets/PictureRecSocket.py", "/model/montage/montage.py"], "/webserver/apis/montage_api.py": ["/model/montage/montage.py", "/model/montage/create_montage_from_photos.py"], "/model/compare_single_to_known_faces.py": ["/model/encode_image.py", "/db_connection/Crud.py"], "/tests/model_tests/test_match_person.py": ["/db_connection/Crud.py", "/model/get_feature_encoded_list.py", "/model/compare_single_to_known_faces.py"], "/db_connection/PeopleDB.py": ["/db_connection/Crud.py"], "/webserver/person/person.py": ["/db_connection/PeopleDB.py"], "/tests/model_tests/test_get_encoding_list.py": ["/db_connection/Crud.py", "/model/get_feature_encoded_list.py"], "/pre_processing/insert_test_data.py": ["/db_connection/Crud.py"], "/webserver/take_pictures/take_pictures.py": ["/model/compare_single_to_known_faces.py", "/model/get_feature_encoded_list.py", "/model/montage/create_montage_from_photos.py"], "/db_connection/Crud.py": ["/tests/db_tests/test_data.py"], "/tests/model_tests/montage/test_match_all_photos.py": ["/model/montage/montage.py", "/model/montage/create_montage_from_photos.py"], "/tests/socket/test_picsocket.py": ["/sockets/PictureRecSocket.py", "/db_connection/Crud.py", "/model/compare_single_to_known_faces.py", "/model/crop_face_from_image.py", "/model/get_feature_encoded_list.py"], "/model/montage/montage.py": ["/db_connection/MontageDB.py", "/model/encode_image.py", "/model/montage/check_person_in_photo.py"], "/tests/model_tests/test_encode_image.py": ["/db_connection/Crud.py", "/model/crop_face_from_image.py", "/model/encode_image.py"], "/db_connection/MontageDB.py": ["/db_connection/Crud.py"], "/tests/model_tests/test_crop_image.py": ["/model/crop_face_from_image.py"], "/tests/preprocessing_tests/test_encode_test_images.py": ["/model/crop_face_from_image.py", "/pre_processing/insert_test_data.py", "/pre_processing/encode_test_data.py", "/db_connection/Crud.py"], "/pre_processing/encode_test_data.py": ["/db_connection/Crud.py", "/model/encode_image.py"], "/model/get_feature_encoded_list.py": ["/db_connection/PeopleDB.py"]}
53,261
alexdy2007/reidentification_hacky
refs/heads/master
/tests/db_tests/crud_test.py
from unittest import TestCase from db_connection.PeopleDB import PeopleDB class TestDB(TestCase): def setUp(self): self.crud = PeopleDB() def test_insert_testdata(self): number_inserted = self.crud.insert_test_data() self.assertEqual(number_inserted, 5, "5 people should have been inserted") def test_find_alex(self): persons_found = self.crud.get_person({"name":"Alex Young"}) self.assertEqual(persons_found[0]["name"], "Alex Young") def test_update(self): PoI = {"name":"Alex Young"} update = {"role" : "test"} update2 = {"role" : "test2"} self.crud.update_person(PoI, update) person = self.crud.get_person(PoI) self.assertEqual(person[0]["role"], "test") self.crud.update_person(PoI, update2) person = self.crud.get_person(PoI) self.assertEqual(person[0]["role"], "test2")
{"/tests/db_tests/crud_test.py": ["/db_connection/PeopleDB.py"], "/tests/db_tests/test_insert_person_seen_from_camera.py": ["/sockets/PictureRecSocket.py", "/db_connection/Crud.py", "/model/compare_single_to_known_faces.py", "/model/get_feature_encoded_list.py"], "/webserver/main.py": ["/webserver/person/person.py", "/webserver/take_pictures/take_pictures.py", "/db_connection/PeopleDB.py", "/db_connection/MontageDB.py", "/webserver/apis/montage_api.py", "/sockets/PictureRecSocket.py", "/model/montage/montage.py"], "/webserver/apis/montage_api.py": ["/model/montage/montage.py", "/model/montage/create_montage_from_photos.py"], "/model/compare_single_to_known_faces.py": ["/model/encode_image.py", "/db_connection/Crud.py"], "/tests/model_tests/test_match_person.py": ["/db_connection/Crud.py", "/model/get_feature_encoded_list.py", "/model/compare_single_to_known_faces.py"], "/db_connection/PeopleDB.py": ["/db_connection/Crud.py"], "/webserver/person/person.py": ["/db_connection/PeopleDB.py"], "/tests/model_tests/test_get_encoding_list.py": ["/db_connection/Crud.py", "/model/get_feature_encoded_list.py"], "/pre_processing/insert_test_data.py": ["/db_connection/Crud.py"], "/webserver/take_pictures/take_pictures.py": ["/model/compare_single_to_known_faces.py", "/model/get_feature_encoded_list.py", "/model/montage/create_montage_from_photos.py"], "/db_connection/Crud.py": ["/tests/db_tests/test_data.py"], "/tests/model_tests/montage/test_match_all_photos.py": ["/model/montage/montage.py", "/model/montage/create_montage_from_photos.py"], "/tests/socket/test_picsocket.py": ["/sockets/PictureRecSocket.py", "/db_connection/Crud.py", "/model/compare_single_to_known_faces.py", "/model/crop_face_from_image.py", "/model/get_feature_encoded_list.py"], "/model/montage/montage.py": ["/db_connection/MontageDB.py", "/model/encode_image.py", "/model/montage/check_person_in_photo.py"], "/tests/model_tests/test_encode_image.py": ["/db_connection/Crud.py", "/model/crop_face_from_image.py", "/model/encode_image.py"], "/db_connection/MontageDB.py": ["/db_connection/Crud.py"], "/tests/model_tests/test_crop_image.py": ["/model/crop_face_from_image.py"], "/tests/preprocessing_tests/test_encode_test_images.py": ["/model/crop_face_from_image.py", "/pre_processing/insert_test_data.py", "/pre_processing/encode_test_data.py", "/db_connection/Crud.py"], "/pre_processing/encode_test_data.py": ["/db_connection/Crud.py", "/model/encode_image.py"], "/model/get_feature_encoded_list.py": ["/db_connection/PeopleDB.py"]}
53,262
alexdy2007/reidentification_hacky
refs/heads/master
/tests/db_tests/test_data.py
TEST_DATA = [ { "name": "Alex Young", "title": "Data Scientist", "photo_location":"Alex_Young.jpg" }, { "name": "Gary", "title": "Boss Man", "photo_location": "Gary.jpg" }, { "name": "Rishabh", "title": "Architect", "photo_location": "Rishabh.jpg" }, { "name": "Frank", "title": "Data Scientist", "photo_location": "Frank.jpg" }, { "name": "Mathew", "title": "Find the money", "photo_location": "Mathew.jpg" } ]
{"/tests/db_tests/crud_test.py": ["/db_connection/PeopleDB.py"], "/tests/db_tests/test_insert_person_seen_from_camera.py": ["/sockets/PictureRecSocket.py", "/db_connection/Crud.py", "/model/compare_single_to_known_faces.py", "/model/get_feature_encoded_list.py"], "/webserver/main.py": ["/webserver/person/person.py", "/webserver/take_pictures/take_pictures.py", "/db_connection/PeopleDB.py", "/db_connection/MontageDB.py", "/webserver/apis/montage_api.py", "/sockets/PictureRecSocket.py", "/model/montage/montage.py"], "/webserver/apis/montage_api.py": ["/model/montage/montage.py", "/model/montage/create_montage_from_photos.py"], "/model/compare_single_to_known_faces.py": ["/model/encode_image.py", "/db_connection/Crud.py"], "/tests/model_tests/test_match_person.py": ["/db_connection/Crud.py", "/model/get_feature_encoded_list.py", "/model/compare_single_to_known_faces.py"], "/db_connection/PeopleDB.py": ["/db_connection/Crud.py"], "/webserver/person/person.py": ["/db_connection/PeopleDB.py"], "/tests/model_tests/test_get_encoding_list.py": ["/db_connection/Crud.py", "/model/get_feature_encoded_list.py"], "/pre_processing/insert_test_data.py": ["/db_connection/Crud.py"], "/webserver/take_pictures/take_pictures.py": ["/model/compare_single_to_known_faces.py", "/model/get_feature_encoded_list.py", "/model/montage/create_montage_from_photos.py"], "/db_connection/Crud.py": ["/tests/db_tests/test_data.py"], "/tests/model_tests/montage/test_match_all_photos.py": ["/model/montage/montage.py", "/model/montage/create_montage_from_photos.py"], "/tests/socket/test_picsocket.py": ["/sockets/PictureRecSocket.py", "/db_connection/Crud.py", "/model/compare_single_to_known_faces.py", "/model/crop_face_from_image.py", "/model/get_feature_encoded_list.py"], "/model/montage/montage.py": ["/db_connection/MontageDB.py", "/model/encode_image.py", "/model/montage/check_person_in_photo.py"], "/tests/model_tests/test_encode_image.py": ["/db_connection/Crud.py", "/model/crop_face_from_image.py", "/model/encode_image.py"], "/db_connection/MontageDB.py": ["/db_connection/Crud.py"], "/tests/model_tests/test_crop_image.py": ["/model/crop_face_from_image.py"], "/tests/preprocessing_tests/test_encode_test_images.py": ["/model/crop_face_from_image.py", "/pre_processing/insert_test_data.py", "/pre_processing/encode_test_data.py", "/db_connection/Crud.py"], "/pre_processing/encode_test_data.py": ["/db_connection/Crud.py", "/model/encode_image.py"], "/model/get_feature_encoded_list.py": ["/db_connection/PeopleDB.py"]}
53,263
alexdy2007/reidentification_hacky
refs/heads/master
/tests/db_tests/test_insert_person_seen_from_camera.py
from unittest import TestCase from sockets.PictureRecSocket import SocketClient from sockets.PictureRecSocket import SocketClient from db_connection.Crud import Crud from model.compare_single_to_known_faces import compare_face_to_known from model.get_feature_encoded_list import get_feature_encoding_list import os class TestPersonSeen(TestCase): def setUp(self): self.sc = SocketClient() self.crud = Crud() def test_identify_and_insert_alex(self): picture = self.sc.get_picture() known_faces = get_feature_encoding_list() people_similar = compare_face_to_known(picture, known_faces, True) if people_similar is not None: most_similar = people_similar[0] self.assertEqual(most_similar["name"], "Alex Young") self.crud.person_seen_db_insert(most_similar) person_seen = self.crud.find_someone_seen_in_last_x_seconds(2) self.assertEqual(person_seen[0],"Alex Young") else: self.fail("No faces found")
{"/tests/db_tests/crud_test.py": ["/db_connection/PeopleDB.py"], "/tests/db_tests/test_insert_person_seen_from_camera.py": ["/sockets/PictureRecSocket.py", "/db_connection/Crud.py", "/model/compare_single_to_known_faces.py", "/model/get_feature_encoded_list.py"], "/webserver/main.py": ["/webserver/person/person.py", "/webserver/take_pictures/take_pictures.py", "/db_connection/PeopleDB.py", "/db_connection/MontageDB.py", "/webserver/apis/montage_api.py", "/sockets/PictureRecSocket.py", "/model/montage/montage.py"], "/webserver/apis/montage_api.py": ["/model/montage/montage.py", "/model/montage/create_montage_from_photos.py"], "/model/compare_single_to_known_faces.py": ["/model/encode_image.py", "/db_connection/Crud.py"], "/tests/model_tests/test_match_person.py": ["/db_connection/Crud.py", "/model/get_feature_encoded_list.py", "/model/compare_single_to_known_faces.py"], "/db_connection/PeopleDB.py": ["/db_connection/Crud.py"], "/webserver/person/person.py": ["/db_connection/PeopleDB.py"], "/tests/model_tests/test_get_encoding_list.py": ["/db_connection/Crud.py", "/model/get_feature_encoded_list.py"], "/pre_processing/insert_test_data.py": ["/db_connection/Crud.py"], "/webserver/take_pictures/take_pictures.py": ["/model/compare_single_to_known_faces.py", "/model/get_feature_encoded_list.py", "/model/montage/create_montage_from_photos.py"], "/db_connection/Crud.py": ["/tests/db_tests/test_data.py"], "/tests/model_tests/montage/test_match_all_photos.py": ["/model/montage/montage.py", "/model/montage/create_montage_from_photos.py"], "/tests/socket/test_picsocket.py": ["/sockets/PictureRecSocket.py", "/db_connection/Crud.py", "/model/compare_single_to_known_faces.py", "/model/crop_face_from_image.py", "/model/get_feature_encoded_list.py"], "/model/montage/montage.py": ["/db_connection/MontageDB.py", "/model/encode_image.py", "/model/montage/check_person_in_photo.py"], "/tests/model_tests/test_encode_image.py": ["/db_connection/Crud.py", "/model/crop_face_from_image.py", "/model/encode_image.py"], "/db_connection/MontageDB.py": ["/db_connection/Crud.py"], "/tests/model_tests/test_crop_image.py": ["/model/crop_face_from_image.py"], "/tests/preprocessing_tests/test_encode_test_images.py": ["/model/crop_face_from_image.py", "/pre_processing/insert_test_data.py", "/pre_processing/encode_test_data.py", "/db_connection/Crud.py"], "/pre_processing/encode_test_data.py": ["/db_connection/Crud.py", "/model/encode_image.py"], "/model/get_feature_encoded_list.py": ["/db_connection/PeopleDB.py"]}
53,264
alexdy2007/reidentification_hacky
refs/heads/master
/webserver/main.py
from flask import Flask, request, jsonify, Response import os from webserver.person.person import Person from flask_restful import Api import threading from werkzeug.utils import secure_filename from webserver.take_pictures.take_pictures import take_pictures from db_connection.PeopleDB import PeopleDB from db_connection.MontageDB import MontageDB from time import sleep from webserver.apis.montage_api import montage_page from sockets.PictureRecSocket import SocketClient from model.montage.montage import Montage CURRENT_DIR = os.path.dirname(os.path.realpath(__file__)) DATA_DIR = CURRENT_DIR + os.sep + ".." + os.sep + "data" + os.sep PICTURE_DIR = CURRENT_DIR + os.sep + ".." + os.sep + "webface" + os.sep + "src" + os.sep + "assets" + os.sep + "pictures" + os.sep UPLOAD_FOLDER = PICTURE_DIR ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif']) TIME_BETWEEN_PICTURES = 4 PEOPLE_VIS_IN_LAST_SECS = 12 app = Flask(__name__) app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER app.register_blueprint(montage_page) api = Api(app) api.add_resource(Person,"/api") peopleDB = PeopleDB() montageDB = MontageDB() montage = Montage() def allowed_file(filename): return '.' in filename and \ filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS @app.route('/comparefile', methods=["POST"]) def comparefile(): if 'file' not in request.files: return Response("Can't read or detect image sent", status=502, mimetype='application/json') file = request.files['file'] if file and allowed_file(file.filename): filename = secure_filename(file.filename) file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) file_path = UPLOAD_FOLDER + os.sep + filename else: return "NO IMAGE FOUND" @app.route('/api/addperson', methods=["POST", "OPTIONS"]) def addperson(): def count_current_photos_of_person(person_dir): dir_to_check = PICTURE_DIR + person_dir if not os.path.exists(dir_to_check): os.makedirs(dir_to_check) number_of_photos_of_person = len(os.listdir(dir_to_check)) n = number_of_photos_of_person + 1 n_str = str(n) if n < 10: prefix = "000" + n_str else: prefix = "00" + n_str return prefix if 'uploadFile' not in request.files: return Response("Can't read or detect image sent", status=502, mimetype='application/json') first_name = request.values["name"].capitalize() last_name = request.values["lastName"].capitalize() if request.values["role"] == "": role = "Not Specified" else: role = request.values["role"].capitalize() file = request.files['uploadFile'] file_name = file.filename file_type = file_name.split(".")[1] folder_dir = first_name + "_" + last_name if file and allowed_file(file_name): n = count_current_photos_of_person(folder_dir) new_file_name = first_name + "_" + last_name + "_" + n + "." + file_type filename = secure_filename(new_file_name) final_path = folder_dir + os.sep + filename file.save(os.path.join(app.config['UPLOAD_FOLDER'], final_path)) person_data = { "name": folder_dir, "role": role, "photo_location": PICTURE_DIR + final_path, "has_encodings": False } peopleDB.insert_person(person_data) print("OK") return "Success" @app.route('/api/peoplevisable', methods=["GET"]) def peoplevisable(): people_seen = peopleDB.find_someone_seen_in_last_x_seconds(PEOPLE_VIS_IN_LAST_SECS) if len(people_seen)!=0: query = {"name": {'$in':people_seen}} people_profiles = peopleDB.get_person(query) for p in people_profiles: if "encoded_face" in p: del p["encoded_face"] del p["_id"] if "photo_location" in p: split_path = p["photo_location"].split("/") split_pt = split_path.index("assets") p["photo_location"] = "/".join(split_path[split_pt:]) return jsonify(people_profiles) else: return jsonify([]) def run_web(): app.run() def repeat_picture_capture(sc, crud): while True: make_montage = True take_pictures(sc, crud, montage, make_montage) sleep(2) if __name__ == '__main__': # run_web() threads = [] sc = SocketClient() t1 = threading.Thread(target=repeat_picture_capture, args=(sc,peopleDB)) t2 = threading.Thread(target=run_web) threads.append(t1) threads.append(t2) for t in threads: t.start() while True: pass
{"/tests/db_tests/crud_test.py": ["/db_connection/PeopleDB.py"], "/tests/db_tests/test_insert_person_seen_from_camera.py": ["/sockets/PictureRecSocket.py", "/db_connection/Crud.py", "/model/compare_single_to_known_faces.py", "/model/get_feature_encoded_list.py"], "/webserver/main.py": ["/webserver/person/person.py", "/webserver/take_pictures/take_pictures.py", "/db_connection/PeopleDB.py", "/db_connection/MontageDB.py", "/webserver/apis/montage_api.py", "/sockets/PictureRecSocket.py", "/model/montage/montage.py"], "/webserver/apis/montage_api.py": ["/model/montage/montage.py", "/model/montage/create_montage_from_photos.py"], "/model/compare_single_to_known_faces.py": ["/model/encode_image.py", "/db_connection/Crud.py"], "/tests/model_tests/test_match_person.py": ["/db_connection/Crud.py", "/model/get_feature_encoded_list.py", "/model/compare_single_to_known_faces.py"], "/db_connection/PeopleDB.py": ["/db_connection/Crud.py"], "/webserver/person/person.py": ["/db_connection/PeopleDB.py"], "/tests/model_tests/test_get_encoding_list.py": ["/db_connection/Crud.py", "/model/get_feature_encoded_list.py"], "/pre_processing/insert_test_data.py": ["/db_connection/Crud.py"], "/webserver/take_pictures/take_pictures.py": ["/model/compare_single_to_known_faces.py", "/model/get_feature_encoded_list.py", "/model/montage/create_montage_from_photos.py"], "/db_connection/Crud.py": ["/tests/db_tests/test_data.py"], "/tests/model_tests/montage/test_match_all_photos.py": ["/model/montage/montage.py", "/model/montage/create_montage_from_photos.py"], "/tests/socket/test_picsocket.py": ["/sockets/PictureRecSocket.py", "/db_connection/Crud.py", "/model/compare_single_to_known_faces.py", "/model/crop_face_from_image.py", "/model/get_feature_encoded_list.py"], "/model/montage/montage.py": ["/db_connection/MontageDB.py", "/model/encode_image.py", "/model/montage/check_person_in_photo.py"], "/tests/model_tests/test_encode_image.py": ["/db_connection/Crud.py", "/model/crop_face_from_image.py", "/model/encode_image.py"], "/db_connection/MontageDB.py": ["/db_connection/Crud.py"], "/tests/model_tests/test_crop_image.py": ["/model/crop_face_from_image.py"], "/tests/preprocessing_tests/test_encode_test_images.py": ["/model/crop_face_from_image.py", "/pre_processing/insert_test_data.py", "/pre_processing/encode_test_data.py", "/db_connection/Crud.py"], "/pre_processing/encode_test_data.py": ["/db_connection/Crud.py", "/model/encode_image.py"], "/model/get_feature_encoded_list.py": ["/db_connection/PeopleDB.py"]}
53,265
alexdy2007/reidentification_hacky
refs/heads/master
/model/montage/check_person_in_photo.py
import face_recognition def is_in_photo(encoded_face, encoded_faces_in_photo): face_distances = face_recognition.face_distance(encoded_faces_in_photo, encoded_face) for idx, distance in enumerate(face_distances): if distance<0.55: return distance return None
{"/tests/db_tests/crud_test.py": ["/db_connection/PeopleDB.py"], "/tests/db_tests/test_insert_person_seen_from_camera.py": ["/sockets/PictureRecSocket.py", "/db_connection/Crud.py", "/model/compare_single_to_known_faces.py", "/model/get_feature_encoded_list.py"], "/webserver/main.py": ["/webserver/person/person.py", "/webserver/take_pictures/take_pictures.py", "/db_connection/PeopleDB.py", "/db_connection/MontageDB.py", "/webserver/apis/montage_api.py", "/sockets/PictureRecSocket.py", "/model/montage/montage.py"], "/webserver/apis/montage_api.py": ["/model/montage/montage.py", "/model/montage/create_montage_from_photos.py"], "/model/compare_single_to_known_faces.py": ["/model/encode_image.py", "/db_connection/Crud.py"], "/tests/model_tests/test_match_person.py": ["/db_connection/Crud.py", "/model/get_feature_encoded_list.py", "/model/compare_single_to_known_faces.py"], "/db_connection/PeopleDB.py": ["/db_connection/Crud.py"], "/webserver/person/person.py": ["/db_connection/PeopleDB.py"], "/tests/model_tests/test_get_encoding_list.py": ["/db_connection/Crud.py", "/model/get_feature_encoded_list.py"], "/pre_processing/insert_test_data.py": ["/db_connection/Crud.py"], "/webserver/take_pictures/take_pictures.py": ["/model/compare_single_to_known_faces.py", "/model/get_feature_encoded_list.py", "/model/montage/create_montage_from_photos.py"], "/db_connection/Crud.py": ["/tests/db_tests/test_data.py"], "/tests/model_tests/montage/test_match_all_photos.py": ["/model/montage/montage.py", "/model/montage/create_montage_from_photos.py"], "/tests/socket/test_picsocket.py": ["/sockets/PictureRecSocket.py", "/db_connection/Crud.py", "/model/compare_single_to_known_faces.py", "/model/crop_face_from_image.py", "/model/get_feature_encoded_list.py"], "/model/montage/montage.py": ["/db_connection/MontageDB.py", "/model/encode_image.py", "/model/montage/check_person_in_photo.py"], "/tests/model_tests/test_encode_image.py": ["/db_connection/Crud.py", "/model/crop_face_from_image.py", "/model/encode_image.py"], "/db_connection/MontageDB.py": ["/db_connection/Crud.py"], "/tests/model_tests/test_crop_image.py": ["/model/crop_face_from_image.py"], "/tests/preprocessing_tests/test_encode_test_images.py": ["/model/crop_face_from_image.py", "/pre_processing/insert_test_data.py", "/pre_processing/encode_test_data.py", "/db_connection/Crud.py"], "/pre_processing/encode_test_data.py": ["/db_connection/Crud.py", "/model/encode_image.py"], "/model/get_feature_encoded_list.py": ["/db_connection/PeopleDB.py"]}
53,266
alexdy2007/reidentification_hacky
refs/heads/master
/webserver/apis/montage_api.py
from flask import Blueprint, request, Response from model.montage.montage import Montage from werkzeug.utils import secure_filename import os from model.montage.create_montage_from_photos import create_montage montage_page = Blueprint('montage', __name__, template_folder='templates') CURRENT_DIR = os.path.dirname(os.path.realpath(__file__)) UPLOAD_FOLDER = CURRENT_DIR + os.sep + ".." + os.sep + "static" + os.sep + "tmp" +os.sep montage = Montage() @montage_page.route('/api/getmontage', methods=["POST", "OPTIONS"]) def getmontage(): if 'uploadFile' not in request.files: return Response("Can't read or detect image sent", status=502, mimetype='application/json') file = request.files['uploadFile'] filename = secure_filename(file.filename) file_path_to_tmp_image = UPLOAD_FOLDER + filename file.save(file_path_to_tmp_image) photos = montage.get_all_photos_with_person_in(file_path_to_tmp_image) create_montage(photos) return Response(status=200)
{"/tests/db_tests/crud_test.py": ["/db_connection/PeopleDB.py"], "/tests/db_tests/test_insert_person_seen_from_camera.py": ["/sockets/PictureRecSocket.py", "/db_connection/Crud.py", "/model/compare_single_to_known_faces.py", "/model/get_feature_encoded_list.py"], "/webserver/main.py": ["/webserver/person/person.py", "/webserver/take_pictures/take_pictures.py", "/db_connection/PeopleDB.py", "/db_connection/MontageDB.py", "/webserver/apis/montage_api.py", "/sockets/PictureRecSocket.py", "/model/montage/montage.py"], "/webserver/apis/montage_api.py": ["/model/montage/montage.py", "/model/montage/create_montage_from_photos.py"], "/model/compare_single_to_known_faces.py": ["/model/encode_image.py", "/db_connection/Crud.py"], "/tests/model_tests/test_match_person.py": ["/db_connection/Crud.py", "/model/get_feature_encoded_list.py", "/model/compare_single_to_known_faces.py"], "/db_connection/PeopleDB.py": ["/db_connection/Crud.py"], "/webserver/person/person.py": ["/db_connection/PeopleDB.py"], "/tests/model_tests/test_get_encoding_list.py": ["/db_connection/Crud.py", "/model/get_feature_encoded_list.py"], "/pre_processing/insert_test_data.py": ["/db_connection/Crud.py"], "/webserver/take_pictures/take_pictures.py": ["/model/compare_single_to_known_faces.py", "/model/get_feature_encoded_list.py", "/model/montage/create_montage_from_photos.py"], "/db_connection/Crud.py": ["/tests/db_tests/test_data.py"], "/tests/model_tests/montage/test_match_all_photos.py": ["/model/montage/montage.py", "/model/montage/create_montage_from_photos.py"], "/tests/socket/test_picsocket.py": ["/sockets/PictureRecSocket.py", "/db_connection/Crud.py", "/model/compare_single_to_known_faces.py", "/model/crop_face_from_image.py", "/model/get_feature_encoded_list.py"], "/model/montage/montage.py": ["/db_connection/MontageDB.py", "/model/encode_image.py", "/model/montage/check_person_in_photo.py"], "/tests/model_tests/test_encode_image.py": ["/db_connection/Crud.py", "/model/crop_face_from_image.py", "/model/encode_image.py"], "/db_connection/MontageDB.py": ["/db_connection/Crud.py"], "/tests/model_tests/test_crop_image.py": ["/model/crop_face_from_image.py"], "/tests/preprocessing_tests/test_encode_test_images.py": ["/model/crop_face_from_image.py", "/pre_processing/insert_test_data.py", "/pre_processing/encode_test_data.py", "/db_connection/Crud.py"], "/pre_processing/encode_test_data.py": ["/db_connection/Crud.py", "/model/encode_image.py"], "/model/get_feature_encoded_list.py": ["/db_connection/PeopleDB.py"]}
53,267
alexdy2007/reidentification_hacky
refs/heads/master
/model/compare_single_to_known_faces.py
import face_recognition from model.encode_image import encode_image from db_connection.Crud import Crud def compare_face_to_known(face_to_match, known_face_list, to_match_top=1): # Load a test image and get encondings for it encode_face_to_match = encode_image(face_to_match) encoded_known_faces = known_face_list[1] names_known_faces = known_face_list[0] if len(encode_face_to_match) == 0: return None # See how far apart the test image is from the known faces face_distances = face_recognition.face_distance(encoded_known_faces, encode_face_to_match) person_distance_from_match = list(zip(names_known_faces, face_distances)) person_distance_from_match.sort(key=lambda x: x[1]) similar_people = person_distance_from_match[0:to_match_top] similar_people_records= [] crud = Crud() for person in similar_people: if person[1] < 0.5: person = crud.get_person({"name":person[0]})[0] similar_people_records.append(person) return similar_people_records
{"/tests/db_tests/crud_test.py": ["/db_connection/PeopleDB.py"], "/tests/db_tests/test_insert_person_seen_from_camera.py": ["/sockets/PictureRecSocket.py", "/db_connection/Crud.py", "/model/compare_single_to_known_faces.py", "/model/get_feature_encoded_list.py"], "/webserver/main.py": ["/webserver/person/person.py", "/webserver/take_pictures/take_pictures.py", "/db_connection/PeopleDB.py", "/db_connection/MontageDB.py", "/webserver/apis/montage_api.py", "/sockets/PictureRecSocket.py", "/model/montage/montage.py"], "/webserver/apis/montage_api.py": ["/model/montage/montage.py", "/model/montage/create_montage_from_photos.py"], "/model/compare_single_to_known_faces.py": ["/model/encode_image.py", "/db_connection/Crud.py"], "/tests/model_tests/test_match_person.py": ["/db_connection/Crud.py", "/model/get_feature_encoded_list.py", "/model/compare_single_to_known_faces.py"], "/db_connection/PeopleDB.py": ["/db_connection/Crud.py"], "/webserver/person/person.py": ["/db_connection/PeopleDB.py"], "/tests/model_tests/test_get_encoding_list.py": ["/db_connection/Crud.py", "/model/get_feature_encoded_list.py"], "/pre_processing/insert_test_data.py": ["/db_connection/Crud.py"], "/webserver/take_pictures/take_pictures.py": ["/model/compare_single_to_known_faces.py", "/model/get_feature_encoded_list.py", "/model/montage/create_montage_from_photos.py"], "/db_connection/Crud.py": ["/tests/db_tests/test_data.py"], "/tests/model_tests/montage/test_match_all_photos.py": ["/model/montage/montage.py", "/model/montage/create_montage_from_photos.py"], "/tests/socket/test_picsocket.py": ["/sockets/PictureRecSocket.py", "/db_connection/Crud.py", "/model/compare_single_to_known_faces.py", "/model/crop_face_from_image.py", "/model/get_feature_encoded_list.py"], "/model/montage/montage.py": ["/db_connection/MontageDB.py", "/model/encode_image.py", "/model/montage/check_person_in_photo.py"], "/tests/model_tests/test_encode_image.py": ["/db_connection/Crud.py", "/model/crop_face_from_image.py", "/model/encode_image.py"], "/db_connection/MontageDB.py": ["/db_connection/Crud.py"], "/tests/model_tests/test_crop_image.py": ["/model/crop_face_from_image.py"], "/tests/preprocessing_tests/test_encode_test_images.py": ["/model/crop_face_from_image.py", "/pre_processing/insert_test_data.py", "/pre_processing/encode_test_data.py", "/db_connection/Crud.py"], "/pre_processing/encode_test_data.py": ["/db_connection/Crud.py", "/model/encode_image.py"], "/model/get_feature_encoded_list.py": ["/db_connection/PeopleDB.py"]}
53,268
alexdy2007/reidentification_hacky
refs/heads/master
/tests/model_tests/test_match_person.py
from unittest import TestCase from db_connection.Crud import Crud import os from model.get_feature_encoded_list import get_feature_encoding_list from model.compare_single_to_known_faces import compare_face_to_known CURRENT_DIR = os.path.dirname(os.path.realpath(__file__)) PICTURE_DIR = CURRENT_DIR + os.sep + ".." + os.sep + "pictures" + os.sep class TestMatchPerson(TestCase): def test_person_match(self): to_match_pic = CURRENT_DIR + os.sep + "to_match.jpg" feature_list = get_feature_encoding_list() person_matched = compare_face_to_known(to_match_pic, feature_list) first_person_matched = person_matched[0] self.assertEqual(first_person_matched["name"], "Alex Young")
{"/tests/db_tests/crud_test.py": ["/db_connection/PeopleDB.py"], "/tests/db_tests/test_insert_person_seen_from_camera.py": ["/sockets/PictureRecSocket.py", "/db_connection/Crud.py", "/model/compare_single_to_known_faces.py", "/model/get_feature_encoded_list.py"], "/webserver/main.py": ["/webserver/person/person.py", "/webserver/take_pictures/take_pictures.py", "/db_connection/PeopleDB.py", "/db_connection/MontageDB.py", "/webserver/apis/montage_api.py", "/sockets/PictureRecSocket.py", "/model/montage/montage.py"], "/webserver/apis/montage_api.py": ["/model/montage/montage.py", "/model/montage/create_montage_from_photos.py"], "/model/compare_single_to_known_faces.py": ["/model/encode_image.py", "/db_connection/Crud.py"], "/tests/model_tests/test_match_person.py": ["/db_connection/Crud.py", "/model/get_feature_encoded_list.py", "/model/compare_single_to_known_faces.py"], "/db_connection/PeopleDB.py": ["/db_connection/Crud.py"], "/webserver/person/person.py": ["/db_connection/PeopleDB.py"], "/tests/model_tests/test_get_encoding_list.py": ["/db_connection/Crud.py", "/model/get_feature_encoded_list.py"], "/pre_processing/insert_test_data.py": ["/db_connection/Crud.py"], "/webserver/take_pictures/take_pictures.py": ["/model/compare_single_to_known_faces.py", "/model/get_feature_encoded_list.py", "/model/montage/create_montage_from_photos.py"], "/db_connection/Crud.py": ["/tests/db_tests/test_data.py"], "/tests/model_tests/montage/test_match_all_photos.py": ["/model/montage/montage.py", "/model/montage/create_montage_from_photos.py"], "/tests/socket/test_picsocket.py": ["/sockets/PictureRecSocket.py", "/db_connection/Crud.py", "/model/compare_single_to_known_faces.py", "/model/crop_face_from_image.py", "/model/get_feature_encoded_list.py"], "/model/montage/montage.py": ["/db_connection/MontageDB.py", "/model/encode_image.py", "/model/montage/check_person_in_photo.py"], "/tests/model_tests/test_encode_image.py": ["/db_connection/Crud.py", "/model/crop_face_from_image.py", "/model/encode_image.py"], "/db_connection/MontageDB.py": ["/db_connection/Crud.py"], "/tests/model_tests/test_crop_image.py": ["/model/crop_face_from_image.py"], "/tests/preprocessing_tests/test_encode_test_images.py": ["/model/crop_face_from_image.py", "/pre_processing/insert_test_data.py", "/pre_processing/encode_test_data.py", "/db_connection/Crud.py"], "/pre_processing/encode_test_data.py": ["/db_connection/Crud.py", "/model/encode_image.py"], "/model/get_feature_encoded_list.py": ["/db_connection/PeopleDB.py"]}
53,269
alexdy2007/reidentification_hacky
refs/heads/master
/db_connection/PeopleDB.py
from db_connection.Crud import Crud import os class PeopleDB(Crud): def __init__(self): super().__init__() self.target_db = self.db.person def get_person(self, query): persons_found = self.target_db.find(query) return list(persons_found) def insert_person(self, person): person_col = self.target_db if "name" in person: file_name = self.PICTURE_DIR + person["name"] + os.sep + person["name"] person_col.insert(person) else: return ValueError("No Name Provided") def delete_all_people(self): self.target_db.remove({}) def insert_test_data(self, test_data=None): person_col = self.db.person self.delete_all_people() for per in test_data: self.insert_person(per) return person_col.find({}).count() def update_person(self, find_by, update): """ :param find_by: dict e.g {name:"alex"} :param update: dict of field want to edit {"role":"DBA"} """ self.target_db.update( find_by, {'$set': update} , upsert=False)
{"/tests/db_tests/crud_test.py": ["/db_connection/PeopleDB.py"], "/tests/db_tests/test_insert_person_seen_from_camera.py": ["/sockets/PictureRecSocket.py", "/db_connection/Crud.py", "/model/compare_single_to_known_faces.py", "/model/get_feature_encoded_list.py"], "/webserver/main.py": ["/webserver/person/person.py", "/webserver/take_pictures/take_pictures.py", "/db_connection/PeopleDB.py", "/db_connection/MontageDB.py", "/webserver/apis/montage_api.py", "/sockets/PictureRecSocket.py", "/model/montage/montage.py"], "/webserver/apis/montage_api.py": ["/model/montage/montage.py", "/model/montage/create_montage_from_photos.py"], "/model/compare_single_to_known_faces.py": ["/model/encode_image.py", "/db_connection/Crud.py"], "/tests/model_tests/test_match_person.py": ["/db_connection/Crud.py", "/model/get_feature_encoded_list.py", "/model/compare_single_to_known_faces.py"], "/db_connection/PeopleDB.py": ["/db_connection/Crud.py"], "/webserver/person/person.py": ["/db_connection/PeopleDB.py"], "/tests/model_tests/test_get_encoding_list.py": ["/db_connection/Crud.py", "/model/get_feature_encoded_list.py"], "/pre_processing/insert_test_data.py": ["/db_connection/Crud.py"], "/webserver/take_pictures/take_pictures.py": ["/model/compare_single_to_known_faces.py", "/model/get_feature_encoded_list.py", "/model/montage/create_montage_from_photos.py"], "/db_connection/Crud.py": ["/tests/db_tests/test_data.py"], "/tests/model_tests/montage/test_match_all_photos.py": ["/model/montage/montage.py", "/model/montage/create_montage_from_photos.py"], "/tests/socket/test_picsocket.py": ["/sockets/PictureRecSocket.py", "/db_connection/Crud.py", "/model/compare_single_to_known_faces.py", "/model/crop_face_from_image.py", "/model/get_feature_encoded_list.py"], "/model/montage/montage.py": ["/db_connection/MontageDB.py", "/model/encode_image.py", "/model/montage/check_person_in_photo.py"], "/tests/model_tests/test_encode_image.py": ["/db_connection/Crud.py", "/model/crop_face_from_image.py", "/model/encode_image.py"], "/db_connection/MontageDB.py": ["/db_connection/Crud.py"], "/tests/model_tests/test_crop_image.py": ["/model/crop_face_from_image.py"], "/tests/preprocessing_tests/test_encode_test_images.py": ["/model/crop_face_from_image.py", "/pre_processing/insert_test_data.py", "/pre_processing/encode_test_data.py", "/db_connection/Crud.py"], "/pre_processing/encode_test_data.py": ["/db_connection/Crud.py", "/model/encode_image.py"], "/model/get_feature_encoded_list.py": ["/db_connection/PeopleDB.py"]}