index
int64
repo_name
string
branch_name
string
path
string
content
string
import_graph
string
15,539,171
shivshaktisahoo/Django
refs/heads/main
/july9_django/customer/admin.py
from django.contrib import admin # Register your models here. from .models import Customer # Register your models here. class CustomerAdmin(admin.ModelAdmin): list_display = ('id', 'first_name', 'last_name', 'age','email', 'contactno','photo') list_filter = ('id',) admin.site.register(Customer, CustomerAdmin)
{"/july1_django/accounts/urls.py": ["/july1_django/accounts/views.py"], "/july1_django/accounts/admin.py": ["/july1_django/accounts/models.py"], "/july2_django/regression/views.py": ["/july2_django/regression/models.py"], "/july13_django/manager/admin.py": ["/july13_django/manager/models.py"], "/june30_django/accounts/admin.py": ["/june30_django/accounts/models.py"], "/july2_django/classification/views.py": ["/july2_django/classification/models.py"], "/july2_django/core/views.py": ["/july2_django/core/models.py"], "/july12_django/manytomany/admin.py": ["/july12_django/manytomany/models.py"], "/july1_django/accounts/views.py": ["/july1_django/accounts/models.py"], "/july2_django/regression/urls.py": ["/july2_django/regression/views.py"], "/july16_django/customer/views.py": ["/july16_django/customer/forms.py"], "/july12_django/manytoone/admin.py": ["/july12_django/manytoone/models.py"], "/july6_django/vacation/forms.py": ["/july6_django/vacation/models.py"], "/july2_django/classification/urls.py": ["/july2_django/classification/views.py"], "/july6_django/vacation/admin.py": ["/july6_django/vacation/models.py"], "/july16_django/manager/views.py": ["/july16_django/manager/forms.py"], "/july16_django/main/urls.py": ["/july16_django/main/views.py"], "/july6_django/vacation/views.py": ["/july6_django/vacation/forms.py"], "/july2_django/regression/admin.py": ["/july2_django/regression/models.py"], "/july2_django/classification/admin.py": ["/july2_django/classification/models.py"], "/july12_django/onetoone/admin.py": ["/july12_django/onetoone/models.py"]}
15,539,172
shivshaktisahoo/Django
refs/heads/main
/june30_django/accounts/migrations/0004_auto_20210630_2356.py
# Generated by Django 3.2.4 on 2021-06-30 18:26 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('accounts', '0003_auto_20210630_2216'), ] operations = [ migrations.RemoveField( model_name='designation', name='college', ), migrations.RemoveField( model_name='designation', name='first_name', ), migrations.RemoveField( model_name='designation', name='highschool', ), migrations.RemoveField( model_name='designation', name='last_name', ), migrations.RemoveField( model_name='designation', name='school', ), migrations.RemoveField( model_name='designation', name='schoolfile', ), migrations.RemoveField( model_name='education', name='college', ), migrations.RemoveField( model_name='education', name='college_certificate', ), migrations.RemoveField( model_name='education', name='first_name', ), migrations.RemoveField( model_name='education', name='highschool', ), migrations.RemoveField( model_name='education', name='highschool_certificate', ), migrations.RemoveField( model_name='education', name='last_name', ), ]
{"/july1_django/accounts/urls.py": ["/july1_django/accounts/views.py"], "/july1_django/accounts/admin.py": ["/july1_django/accounts/models.py"], "/july2_django/regression/views.py": ["/july2_django/regression/models.py"], "/july13_django/manager/admin.py": ["/july13_django/manager/models.py"], "/june30_django/accounts/admin.py": ["/june30_django/accounts/models.py"], "/july2_django/classification/views.py": ["/july2_django/classification/models.py"], "/july2_django/core/views.py": ["/july2_django/core/models.py"], "/july12_django/manytomany/admin.py": ["/july12_django/manytomany/models.py"], "/july1_django/accounts/views.py": ["/july1_django/accounts/models.py"], "/july2_django/regression/urls.py": ["/july2_django/regression/views.py"], "/july16_django/customer/views.py": ["/july16_django/customer/forms.py"], "/july12_django/manytoone/admin.py": ["/july12_django/manytoone/models.py"], "/july6_django/vacation/forms.py": ["/july6_django/vacation/models.py"], "/july2_django/classification/urls.py": ["/july2_django/classification/views.py"], "/july6_django/vacation/admin.py": ["/july6_django/vacation/models.py"], "/july16_django/manager/views.py": ["/july16_django/manager/forms.py"], "/july16_django/main/urls.py": ["/july16_django/main/views.py"], "/july6_django/vacation/views.py": ["/july6_django/vacation/forms.py"], "/july2_django/regression/admin.py": ["/july2_django/regression/models.py"], "/july2_django/classification/admin.py": ["/july2_django/classification/models.py"], "/july12_django/onetoone/admin.py": ["/july12_django/onetoone/models.py"]}
15,539,173
shivshaktisahoo/Django
refs/heads/main
/june30_django/accounts/migrations/0002_auto_20210630_2213.py
# Generated by Django 3.2.4 on 2021-06-30 16:43 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('accounts', '0001_initial'), ] operations = [ migrations.RemoveField( model_name='education', name='schoolfile', ), migrations.AddField( model_name='education', name='college_certificate', field=models.FileField(blank=True, null=True, upload_to=''), ), migrations.AddField( model_name='education', name='highschool_certificate', field=models.FileField(blank=True, null=True, upload_to=''), ), migrations.AddField( model_name='education', name='school_certificate', field=models.FileField(blank=True, null=True, upload_to=''), ), ]
{"/july1_django/accounts/urls.py": ["/july1_django/accounts/views.py"], "/july1_django/accounts/admin.py": ["/july1_django/accounts/models.py"], "/july2_django/regression/views.py": ["/july2_django/regression/models.py"], "/july13_django/manager/admin.py": ["/july13_django/manager/models.py"], "/june30_django/accounts/admin.py": ["/june30_django/accounts/models.py"], "/july2_django/classification/views.py": ["/july2_django/classification/models.py"], "/july2_django/core/views.py": ["/july2_django/core/models.py"], "/july12_django/manytomany/admin.py": ["/july12_django/manytomany/models.py"], "/july1_django/accounts/views.py": ["/july1_django/accounts/models.py"], "/july2_django/regression/urls.py": ["/july2_django/regression/views.py"], "/july16_django/customer/views.py": ["/july16_django/customer/forms.py"], "/july12_django/manytoone/admin.py": ["/july12_django/manytoone/models.py"], "/july6_django/vacation/forms.py": ["/july6_django/vacation/models.py"], "/july2_django/classification/urls.py": ["/july2_django/classification/views.py"], "/july6_django/vacation/admin.py": ["/july6_django/vacation/models.py"], "/july16_django/manager/views.py": ["/july16_django/manager/forms.py"], "/july16_django/main/urls.py": ["/july16_django/main/views.py"], "/july6_django/vacation/views.py": ["/july6_django/vacation/forms.py"], "/july2_django/regression/admin.py": ["/july2_django/regression/models.py"], "/july2_django/classification/admin.py": ["/july2_django/classification/models.py"], "/july12_django/onetoone/admin.py": ["/july12_django/onetoone/models.py"]}
15,539,174
shivshaktisahoo/Django
refs/heads/main
/july16_django/manager/forms.py
from django import forms from .models import Manager class ManagerForm(forms.ModelForm): first_name = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control','placeholder':'Enter your First Name'}),label='First Name') last_name = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control','placeholder':'Enter your Last Name'}),label='Last Name') age = forms.IntegerField(widget=forms.NumberInput(attrs={'class':'form-control','placeholder':'Enter your Age'}),label='Age') email = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Enter your Email', 'type': 'email'})) contactno = forms.IntegerField(widget=forms.NumberInput(attrs={'class':'form-control','placeholder':'Enter your Contact No.'}),label='Contact No.') photo = forms.ImageField(widget=forms.FileInput(attrs={'class': 'form-control'})) class Meta: model = Manager fields = "__all__" widgets = { 'room': forms.SelectMultiple(attrs={'class': 'custom-select'}), } labels = { 'room': 'ROOM (multiple option available) :', }
{"/july1_django/accounts/urls.py": ["/july1_django/accounts/views.py"], "/july1_django/accounts/admin.py": ["/july1_django/accounts/models.py"], "/july2_django/regression/views.py": ["/july2_django/regression/models.py"], "/july13_django/manager/admin.py": ["/july13_django/manager/models.py"], "/june30_django/accounts/admin.py": ["/june30_django/accounts/models.py"], "/july2_django/classification/views.py": ["/july2_django/classification/models.py"], "/july2_django/core/views.py": ["/july2_django/core/models.py"], "/july12_django/manytomany/admin.py": ["/july12_django/manytomany/models.py"], "/july1_django/accounts/views.py": ["/july1_django/accounts/models.py"], "/july2_django/regression/urls.py": ["/july2_django/regression/views.py"], "/july16_django/customer/views.py": ["/july16_django/customer/forms.py"], "/july12_django/manytoone/admin.py": ["/july12_django/manytoone/models.py"], "/july6_django/vacation/forms.py": ["/july6_django/vacation/models.py"], "/july2_django/classification/urls.py": ["/july2_django/classification/views.py"], "/july6_django/vacation/admin.py": ["/july6_django/vacation/models.py"], "/july16_django/manager/views.py": ["/july16_django/manager/forms.py"], "/july16_django/main/urls.py": ["/july16_django/main/views.py"], "/july6_django/vacation/views.py": ["/july6_django/vacation/forms.py"], "/july2_django/regression/admin.py": ["/july2_django/regression/models.py"], "/july2_django/classification/admin.py": ["/july2_django/classification/models.py"], "/july12_django/onetoone/admin.py": ["/july12_django/onetoone/models.py"]}
15,594,196
deft727/django_board
refs/heads/master
/accounts/tests/conftest.py
import pytest from django.contrib.auth.models import User from accounts.forms import ReaderForm, SignUpFormReader,SignUpFormBloger from accounts.models import Reader,Bloger # @pytest.mark.django_db from django.contrib.auth import get_user_model @pytest.fixture def reader_data(): return {'username':'test123','password':'djnagoresearchj929',} @pytest.mark.django_db def create_user(): user = User.objects.create(username='teslogin',password='qwerty1234',email='sadasd@gmail.com') return user @pytest.fixture def reader(): user = User.objects.create(username='teslogiqn',password='qwerty1234',email='sadasdq@gmail.com') # obj = Reader.objects.create(user=user,username=user.username) data = { 'username':'testuser', 'email':'asdasdasc@gmail.com' } form = SignUpFormReader(data=data) form.user= user yield form @pytest.fixture def create_reader(reader_data): user_model = get_user_model() user = user_model.objects.create(**reader_data) test_user = Reader(user=user,username=user.username) test_user.user.set_password(reader_data.get('password')) test_user.save() return test_user @pytest.fixture def authenticated_user(reader_data): user_model = get_user_model() user = user_model.objects.create(**reader_data) test_user = Reader(user=user,username=user.username) test_user.user.set_password(reader_data.get('password')) test_user.save() return test_user # @pytest.fixture # def bloger(): # user = User.objects.create(username="james", password="password",email='testbloge@gmail.com') # obj = Bloger.objects.create(user=user,username=user.username) # data = { # 'user':user, # 'username':obj.username, # } # form =SignUpFormBloger(data=data) # yield form
{"/boards/urls.py": ["/boards/views.py", "/boards/export_board.py"], "/accounts/tests/conftest.py": ["/accounts/forms.py", "/accounts/models.py"], "/accounts/views.py": ["/accounts/forms.py", "/accounts/tasks.py", "/accounts/models.py", "/boards/urls.py"], "/boards/views.py": ["/boards/forms.py", "/boards/utils.py", "/accounts/tasks.py"], "/boards/signals.py": ["/accounts/tasks.py"], "/accounts/tests/testdivision.py": ["/accounts/tests/utils.py"], "/accounts/admin.py": ["/accounts/models.py"], "/myproject/context_processors.py": ["/accounts/models.py"], "/boards/utils.py": ["/accounts/models.py", "/boards/forms.py"], "/accounts/forms.py": ["/accounts/models.py"], "/accounts/tests/test_views.py": ["/accounts/models.py", "/accounts/tests/conftest.py"]}
15,594,197
deft727/django_board
refs/heads/master
/accounts/models.py
# from PIL.Image import blend from django.db import models from django.contrib.auth.models import User # from django.db.models.deletion import CASCADE, PROTECT from django.urls import reverse class Interests(models.Model): class Meta: verbose_name = 'Интерес' verbose_name_plural = 'Интересы' ordering = ['title',] title = models.CharField(max_length=250,verbose_name='Интерес') slug = models.SlugField(unique=True) def get_absolute_url(self): return reverse('interests',kwargs={'slug':self.slug}) def __str__(self): return self.title class Category(models.Model): class Meta: verbose_name = 'Категории' verbose_name_plural = 'Категории' ordering = ['name',] name = models.CharField(max_length=250,verbose_name='Имя категории') slug = models.SlugField(unique=True) def get_absolute_url(self): return reverse('category_detail',kwargs={'slug':self.slug}) def __str__(self): return self.name class Bloger(models.Model): class Meta: verbose_name = 'Блогер' verbose_name_plural = 'Блогеры' STATUS_TRUE ='True' STATUS_FALSE='False' STATUS_CHOICES= ( (STATUS_TRUE,'bloger'), (STATUS_FALSE,'isn`t bloger'), ) file = models.ImageField(null=True,blank=True,upload_to='avatar/') category = models.ManyToManyField(Category,verbose_name='Категории',null=True) user = models.ForeignKey(User, verbose_name='блогер', on_delete=models.CASCADE,related_name='bloger') username = models.CharField(blank=True, null=True, default=None, max_length=255, verbose_name='имя') email = models .EmailField(verbose_name='Электороная почта',null=True) birthday = models.DateField(null=True, blank=True,verbose_name='Дата рождения') country = models.CharField(null=True, blank=True, default=None, max_length=255, verbose_name='Город') is_super = models.BooleanField(default=True) status = models.CharField( max_length=100, verbose_name='are you bloger?', choices=STATUS_CHOICES, default=STATUS_TRUE ) class Reader(models.Model): class Meta: verbose_name = 'Читатель' verbose_name_plural = 'Читатели' file = models.ImageField(null=True,blank=True,upload_to='avatar/') user = models.ForeignKey(User, verbose_name='читатель',related_name='reader', on_delete=models.CASCADE) username = models.CharField(blank=True, null=True, max_length=50, verbose_name='имя') is_super = models.BooleanField(default=False) of_age = models.BooleanField(default=False,null=True,blank=True) interests = models.ManyToManyField(Interests,verbose_name='Интересы',null=True, blank=True)
{"/boards/urls.py": ["/boards/views.py", "/boards/export_board.py"], "/accounts/tests/conftest.py": ["/accounts/forms.py", "/accounts/models.py"], "/accounts/views.py": ["/accounts/forms.py", "/accounts/tasks.py", "/accounts/models.py", "/boards/urls.py"], "/boards/views.py": ["/boards/forms.py", "/boards/utils.py", "/accounts/tasks.py"], "/boards/signals.py": ["/accounts/tasks.py"], "/accounts/tests/testdivision.py": ["/accounts/tests/utils.py"], "/accounts/admin.py": ["/accounts/models.py"], "/myproject/context_processors.py": ["/accounts/models.py"], "/boards/utils.py": ["/accounts/models.py", "/boards/forms.py"], "/accounts/forms.py": ["/accounts/models.py"], "/accounts/tests/test_views.py": ["/accounts/models.py", "/accounts/tests/conftest.py"]}
15,594,198
deft727/django_board
refs/heads/master
/accounts/migrations/0004_auto_20210726_1059.py
# Generated by Django 3.2.5 on 2021-07-26 10:59 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('accounts', '0003_auto_20210726_0858'), ] operations = [ migrations.AlterModelOptions( name='bloger', options={'verbose_name': 'Блогер', 'verbose_name_plural': 'Блогеры'}, ), migrations.AlterModelOptions( name='reader', options={'verbose_name': 'Читатель', 'verbose_name_plural': 'Читатели'}, ), migrations.AlterField( model_name='bloger', name='birthday', field=models.DateField(blank=True, null=True, verbose_name='Дата рождения'), ), migrations.AlterField( model_name='bloger', name='country', field=models.CharField(default=None, max_length=255, verbose_name='Город'), ), migrations.AlterField( model_name='bloger', name='email', field=models.EmailField(max_length=254, verbose_name='Электороная почта'), ), migrations.AlterField( model_name='reader', name='interests', field=models.ManyToManyField(to='accounts.Interests', verbose_name='Интересы'), ), ]
{"/boards/urls.py": ["/boards/views.py", "/boards/export_board.py"], "/accounts/tests/conftest.py": ["/accounts/forms.py", "/accounts/models.py"], "/accounts/views.py": ["/accounts/forms.py", "/accounts/tasks.py", "/accounts/models.py", "/boards/urls.py"], "/boards/views.py": ["/boards/forms.py", "/boards/utils.py", "/accounts/tasks.py"], "/boards/signals.py": ["/accounts/tasks.py"], "/accounts/tests/testdivision.py": ["/accounts/tests/utils.py"], "/accounts/admin.py": ["/accounts/models.py"], "/myproject/context_processors.py": ["/accounts/models.py"], "/boards/utils.py": ["/accounts/models.py", "/boards/forms.py"], "/accounts/forms.py": ["/accounts/models.py"], "/accounts/tests/test_views.py": ["/accounts/models.py", "/accounts/tests/conftest.py"]}
15,594,199
deft727/django_board
refs/heads/master
/accounts/views.py
from django.contrib.auth import get_user, login as auth_login,authenticate from django.http import request from django.shortcuts import render, redirect,HttpResponseRedirect from .forms import * from .tasks import send_user_mail_task from django.contrib.auth.decorators import login_required, user_passes_test from django.contrib.auth.models import User from django.urls import reverse_lazy from django.utils.decorators import method_decorator from django.views.generic import UpdateView,View,DetailView from .models import * from django.contrib import messages from boards.urls import get_user_status # import urllib # import urllib.request as urllib2 # import json from django.conf import settings # from boards.utils import send_user_mail from django.contrib import messages @method_decorator(login_required, name='dispatch') class UserUpdateView(UpdateView): template_name = 'my_account.html' success_url = reverse_lazy('my_account') def get_form_class(self): if get_user_status(self.request) is True: self.form_class = BlogerForm else: self.form_class = ReaderForm return self.form_class def get_object(self): if get_user_status(self.request) is True: return Bloger.objects.get(user=self.request.user) else: return Reader.objects.get(user=self.request.user) def form_valid(self, form): form.instance.created_by = self.request.user messages.add_message(self.request,messages.SUCCESS,'account has been updated') return super().form_valid(form) class ChooseSignup(View): def get(self,request,*args,**kwargs): if request.user.is_authenticated: return redirect('home') return render(request, 'choose_signup.html') class RegistrationViewReader(View): def get(self,request,*args,**kwargs): if request.user.is_authenticated: return redirect('home') form= SignUpFormReader(request.POST or None) context = { 'form':form, 'title':'Sign up as reader' } return render(request,'signup.html',context) def post(self,request,*args,**kwargs): if request.method == 'POST': form = SignUpFormReader(request.POST) if form.is_valid(): new_user=form.save(commit=False) new_user.username=form.cleaned_data['username'] new_user.email=form.cleaned_data['email'] new_user.set_password(form.cleaned_data['password']) new_user.save() reader = Reader.objects.create( user=new_user, username=new_user.username, of_age = form.cleaned_data['of_age'] ) reader.save() auth_login(request, new_user, backend='django.contrib.auth.backends.ModelBackend') name = form.cleaned_data['username'] if form.cleaned_data['username'] else 'Anonimous' send_user_mail_task.delay(subject='Hello Reader',content=f'Welcome on our site {name}',email=new_user.email) return redirect('home') else: form = SignUpFormReader() return render(request, 'signup.html', {'form': form}) class RegistrationViewBloger(View): def get(self,request,*args,**kwargs): if request.user.is_authenticated: return redirect('home') form= SignUpFormBloger(request.POST or None) context = { 'form':form, 'title':'Sign up as bloger', } return render(request,'signup.html',context) def post(self,request,backend='django.contrib.auth.backends.ModelBackend',*args,**kwargs): if request.method == 'POST': form = SignUpFormBloger(request.POST) if form.is_valid(): new_bloger=form.save(commit=False) new_bloger.username=form.cleaned_data['username'] new_bloger.email=form.cleaned_data['email'] new_bloger.set_password(form.cleaned_data['password']) new_bloger.save() bloger = Bloger.objects.create( user=new_bloger, username=form.cleaned_data['username'], email=new_bloger.email, birthday = form.cleaned_data['birthday'], country = form.cleaned_data['country'], status = form.cleaned_data['status'] ) bloger.save() bloger.category.add(*form.cleaned_data['category']) auth_login(request, new_bloger, backend='django.contrib.auth.backends.ModelBackend') name = form.cleaned_data['username'] if form.cleaned_data['username'] else 'Anonimous' send_user_mail_task.delay(subject='Hello Bloger',content=f'Welcome on our site {name}',email=new_bloger.email) return redirect ('home') else: form = SignUpFormReader() return render(request, 'signup.html', {'form': form}) class LoginView(View): def get(self,request,*args,**kwargs): if request.user.is_authenticated: messages.add_message(request,messages.ERROR,'Вы уже залогинены') return redirect('home') form = LoginForm(request.POST or None) title = 'Login' context= {'title':title, 'form':form, } return render(request,'login.html',context) def post(self,request,*args,**kwargs): form=LoginForm(request.POST or None) if form.is_valid(): username= form.cleaned_data['username'] password = form.cleaned_data['password'] if '@' in username: user1= User.objects.filter(email=username).first() user= authenticate(username=user1,password=password) else: user= authenticate(username=username,password=password) if user: auth_login(request,user) return HttpResponseRedirect('/') context={'form':form,} return render(request,'login.html',context) class ProfileView(DetailView): template_name='profile.html' allow_empty=False model= User def get_context_data(self,**kwargs): context = super().get_context_data(**kwargs) if self.get_object().bloger.get_queryset(): profile = self.get_object().bloger.get_queryset() status = True else: profile = self.get_object().reader.get_queryset() status = False context['status'] = status context['profile'] = profile context['title'] = f'Profile {self.get_object().username}' return context
{"/boards/urls.py": ["/boards/views.py", "/boards/export_board.py"], "/accounts/tests/conftest.py": ["/accounts/forms.py", "/accounts/models.py"], "/accounts/views.py": ["/accounts/forms.py", "/accounts/tasks.py", "/accounts/models.py", "/boards/urls.py"], "/boards/views.py": ["/boards/forms.py", "/boards/utils.py", "/accounts/tasks.py"], "/boards/signals.py": ["/accounts/tasks.py"], "/accounts/tests/testdivision.py": ["/accounts/tests/utils.py"], "/accounts/admin.py": ["/accounts/models.py"], "/myproject/context_processors.py": ["/accounts/models.py"], "/boards/utils.py": ["/accounts/models.py", "/boards/forms.py"], "/accounts/forms.py": ["/accounts/models.py"], "/accounts/tests/test_views.py": ["/accounts/models.py", "/accounts/tests/conftest.py"]}
15,594,200
deft727/django_board
refs/heads/master
/boards/migrations/0009_topic_is_activ.py
# Generated by Django 3.2.6 on 2021-08-09 07:07 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('boards', '0008_auto_20210805_1254'), ] operations = [ migrations.AddField( model_name='topic', name='is_activ', field=models.BooleanField(blank=True, default=True, null=True), ), ]
{"/boards/urls.py": ["/boards/views.py", "/boards/export_board.py"], "/accounts/tests/conftest.py": ["/accounts/forms.py", "/accounts/models.py"], "/accounts/views.py": ["/accounts/forms.py", "/accounts/tasks.py", "/accounts/models.py", "/boards/urls.py"], "/boards/views.py": ["/boards/forms.py", "/boards/utils.py", "/accounts/tasks.py"], "/boards/signals.py": ["/accounts/tasks.py"], "/accounts/tests/testdivision.py": ["/accounts/tests/utils.py"], "/accounts/admin.py": ["/accounts/models.py"], "/myproject/context_processors.py": ["/accounts/models.py"], "/boards/utils.py": ["/accounts/models.py", "/boards/forms.py"], "/accounts/forms.py": ["/accounts/models.py"], "/accounts/tests/test_views.py": ["/accounts/models.py", "/accounts/tests/conftest.py"]}
15,594,201
deft727/django_board
refs/heads/master
/accounts/migrations/0010_auto_20210804_1528.py
# Generated by Django 3.2.6 on 2021-08-04 15:28 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('accounts', '0009_bloger_status'), ] operations = [ migrations.CreateModel( name='Avatar', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('file', models.ImageField(upload_to='')), ], ), migrations.AddField( model_name='bloger', name='avatar', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.PROTECT, to='accounts.avatar'), ), migrations.AddField( model_name='reader', name='avatar', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.PROTECT, to='accounts.avatar'), ), ]
{"/boards/urls.py": ["/boards/views.py", "/boards/export_board.py"], "/accounts/tests/conftest.py": ["/accounts/forms.py", "/accounts/models.py"], "/accounts/views.py": ["/accounts/forms.py", "/accounts/tasks.py", "/accounts/models.py", "/boards/urls.py"], "/boards/views.py": ["/boards/forms.py", "/boards/utils.py", "/accounts/tasks.py"], "/boards/signals.py": ["/accounts/tasks.py"], "/accounts/tests/testdivision.py": ["/accounts/tests/utils.py"], "/accounts/admin.py": ["/accounts/models.py"], "/myproject/context_processors.py": ["/accounts/models.py"], "/boards/utils.py": ["/accounts/models.py", "/boards/forms.py"], "/accounts/forms.py": ["/accounts/models.py"], "/accounts/tests/test_views.py": ["/accounts/models.py", "/accounts/tests/conftest.py"]}
15,594,202
deft727/django_board
refs/heads/master
/accounts/tasks.py
from celery import shared_task from django.core.mail import send_mail from myproject.celery import app @shared_task def add(x, y): return x + y @app.task def send_user_mail_task(subject,content,email): send_mail(subject, content,'test.blogodvich@gmail.com',[email,], fail_silently=False) @shared_task def xsum(numbers): return sum(numbers)
{"/boards/urls.py": ["/boards/views.py", "/boards/export_board.py"], "/accounts/tests/conftest.py": ["/accounts/forms.py", "/accounts/models.py"], "/accounts/views.py": ["/accounts/forms.py", "/accounts/tasks.py", "/accounts/models.py", "/boards/urls.py"], "/boards/views.py": ["/boards/forms.py", "/boards/utils.py", "/accounts/tasks.py"], "/boards/signals.py": ["/accounts/tasks.py"], "/accounts/tests/testdivision.py": ["/accounts/tests/utils.py"], "/accounts/admin.py": ["/accounts/models.py"], "/myproject/context_processors.py": ["/accounts/models.py"], "/boards/utils.py": ["/accounts/models.py", "/boards/forms.py"], "/accounts/forms.py": ["/accounts/models.py"], "/accounts/tests/test_views.py": ["/accounts/models.py", "/accounts/tests/conftest.py"]}
15,594,203
deft727/django_board
refs/heads/master
/boards/views.py
from datetime import date from decimal import ROUND_UP from math import e import time from django.db.models.expressions import F # from django.http.response import HttpResponseRedirect # from django.utils.translation import pgettext # from xlwt.ExcelMagic import PtgNames # from accounts.models import Bloger,Reader # from os import name from django.core.checks import messages from django.urls.conf import path from .forms import NewTopicForm,PostForm,BoardForm from django.shortcuts import render, get_object_or_404,redirect # from django.http import Http404, request from django.db.models import Count # from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger # from django.http import HttpResponse from .models import Board, Photo, Topic , Post from django.contrib.auth.models import User from django.contrib.auth.decorators import login_required from django.views.generic import View,ListView,UpdateView from django.urls import reverse_lazy,reverse from django.utils import timezone from django.utils.decorators import method_decorator from django.contrib.auth import authenticate,login from django.template.loader import render_to_string from django.http import JsonResponse from .utils import get_user_status,get_image from django.contrib import messages from django.http import HttpResponse, HttpResponseNotFound from django.db.models.signals import post_save from accounts.tasks import send_user_mail_task from django.dispatch import receiver from django.db import transaction import json def new_articles(request): import random randomboard = ['Python','Django','Flask','Docker'] randomname = ['Boris','Kirill','Sasha','Yura','Nikita'] # if request.user.is_authenticated: user = request.user # else: # try: # user = User.objects.create_user(random.choice(randomname), 'randomemail', 'randomemail') # login(request,user) # except: # user = User.objects.filter(username=randomname).first() try: board = Board.objects.get(name=random.choice(randomboard)) except: board = Board.objects.create(name=random.choice(randomboard),description='dfsdfsd') for i in range(100): subject = 'Topic test #{}'.format(i) topic = Topic.objects.create(subject=subject, board=board, starter=user) Post.objects.create(message='Lorem ipsum...', topic=topic, created_by=user) return redirect('home') # @login_required # def new_topic(request, pk): # board = get_object_or_404(Board, pk=pk) # if request.method == 'POST': # form = NewTopicForm(request.POST, request.FILES) # if form.is_valid(): # topic = form.save(commit=False) # topic.board = board # topic.starter = request.user # topic.save() # post = Post.objects.create( # message = form.cleaned_data.get('message'), # topic = topic, # created_by = request.user # ) # photo = Photo.objects.create( # file = form.cleaned_data.get('file'), # topic = topic # ) # photo.save() # href = 'true' # data = {'is_valid': True, 'name': photo.file.name, 'url': photo.file.url,} # else: # form = NewTopicForm() # data = {'is_valid': False} # return render(request, 'new_topic.html', {'board': board,'form':form}) # def photo_delete(request, pk): # board = get_object_or_404(Photo, pk=pk) # data = dict() # boards = Board.objects.all() # form1 = NewTopicForm(request.POST,request.FILES) # if request.method == 'POST': # board.delete() # data['form_is_valid'] = True # data['html_partial_board'] = render_to_string('new_topic.html', 'new_topic.html', {'board': board,'form':form1,'photos':None}) # else: # context = {'board': board} # data['html_form'] = render_to_string('./includes/board_form_delete.html', # context, # request=request, # ) # return JsonResponse(data) @method_decorator(login_required, name='dispatch') class New_topicView(View): def get(self,request,pk): board = get_object_or_404(Board, pk=pk) form1 = NewTopicForm(request.POST,request.FILES) return render(request, 'new_topic.html', {'board': board,'form':form1,'photos':None}) @transaction.atomic def post(self,request,pk,images=[]): time.sleep(1) board = get_object_or_404(Board, pk=pk) form = NewTopicForm(request.POST,request.FILES) if form.is_valid(): if not Topic.objects.filter(subject=form.cleaned_data.get('subject'),board=board): topic = Topic.objects.create( subject=form.cleaned_data.get('subject'), starter= request.user, board = board ) Post.objects.create( message = form.cleaned_data.get('message'), created_by=request.user, topic=topic ) else: topic = Topic.objects.get(subject=form.cleaned_data.get('subject'),board=board) files = request.FILES.getlist('file') for file in images if not files else files: photo = Photo( title = file.name, file = file, topic = topic ) photo.save() data = {'is_valid': True, 'name': photo.title } if not files: return redirect('board_topics', pk=pk) else: photo = request.FILES.get('file') images.append(get_image(photo)) data = {'is_valid': True, 'name': photo.name } return JsonResponse(data) @method_decorator(login_required, name='dispatch') class Reply_topicView(View): def get(self,request, pk, topic_pk): topic = get_object_or_404(Topic, board__pk=pk, pk=topic_pk) form = PostForm() context = { 'topic':topic, 'form':form, } return render(request, 'reply_topic.html',context) def post(self,request, pk, topic_pk): topic = get_object_or_404(Topic, board__pk=pk, pk=topic_pk) form = PostForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.topic = topic post.created_by = request.user post.save() topic.last_updated = timezone.now() topic.save() topic_url = reverse('topic_posts', kwargs={'pk': pk, 'topic_pk': topic_pk}) page = topic.get_page_count() topic_post_url = f'{topic_url}?page={page}' return redirect(topic_post_url) else: context = { 'topic':topic, 'form':form,} return render(request, 'reply_topic.html',context) # @login_required # def reply_topic(request, pk, topic_pk): # topic = get_object_or_404(Topic, board__pk=pk, pk=topic_pk) # if request.method == 'POST': # form = PostForm(request.POST) # if form.is_valid(): # post = form.save(commit=False) # post.topic = topic # post.created_by = request.user # post.save() # topic.last_updated = timezone.now() # topic.save() # topic_url = reverse('topic_posts', kwargs={'pk': pk, 'topic_pk': topic_pk}) # page = topic.get_page_count() # topic_post_url = f'{topic_url}?page={page}' # return redirect(topic_post_url) # else: # form = PostForm() # return render(request, 'reply_topic.html', {'topic': topic, 'form': form}) class BoardListView(ListView): model = Board context_object_name = 'boards' template_name = 'home.html' paginate_by = 10 ordering= ['-id'] def get_context_data(self,**kwargs): # messages.add_message(self.request,messages.SUCCESS,'khftyde') context = super().get_context_data(**kwargs) context['bloger'] = get_user_status(self.request) context['history'] = Board.history.all()[:10] context['boards'] = Board.objects.filter(is_activ=True).prefetch_related('topic_set') return context class TopicListView(ListView): model = Topic context_object_name = 'topics' template_name = 'topics.html' paginate_by = 20 def get_context_data(self, **kwargs): kwargs['board'] = self.board return super().get_context_data(**kwargs) def get_queryset(self): self.board = get_object_or_404(Board, pk=self.kwargs.get('pk')) queryset = self.board.topic_set.all().order_by('-last_updated').annotate(replies=Count('posts') - 1) return queryset def generate_fake_data(request): from model_mommy import mommy mommy.make('boards.TOPIC', _quantity=20) return redirect('boards') class PostListView(ListView): model = Post context_object_name = 'posts' template_name = 'topic_posts.html' paginate_by = 10 def get_context_data(self, **kwargs): session_key = 'viewed_topic_{}'.format(self.topic.pk) if not self.request.session.get(session_key, False): self.topic.views += 1 self.topic.save() self.request.session[session_key] = True kwargs['topic'] = self.topic return super().get_context_data(**kwargs) def get_queryset(self): self.topic = get_object_or_404(Topic, board__pk=self.kwargs.get('pk'), pk=self.kwargs.get('topic_pk')) queryset = self.topic.posts.order_by('created_at') return queryset @method_decorator(login_required, name='dispatch') class PostUpdateView(UpdateView): model = Post fields = ('message', ) template_name = 'edit_post.html' pk_url_kwarg = 'post_pk' context_object_name = 'post' def get_queryset(self): queryset = super().get_queryset() return queryset.filter(created_by=self.request.user) def form_valid(self, form): post = form.save(commit=False) post.updated_by = self.request.user post.updated_at = timezone.now() post.save() return redirect('topic_posts', pk=post.topic.board.pk, topic_pk=post.topic.pk) @login_required def board_create(request): data = dict() if request.method == 'POST': form = BoardForm(request.POST) if form.is_valid(): form.save() data['form_is_valid'] = True boards = Board.objects.all() data['html_partial_board'] = render_to_string('./includes/partial_board.html', { 'boards': boards, 'bloger': get_user_status(request) }) else: data['form_is_valid'] = False else: form = BoardForm() context = {'form': form} data['html_form'] = render_to_string('./includes/board_form.html', context, request=request ) return JsonResponse(data) @login_required def board_update(request,pk): board = get_object_or_404(Board, pk=pk) if request.method == 'POST': form = BoardForm(request.POST, instance=board) else: form = BoardForm(instance=board) return save_board_form(request, form, './includes/board_form_update.html') def save_board_form(request, form, template_name): data = dict() if request.method == 'POST': if form.is_valid(): form.save() data['form_is_valid'] = True boards = Board.objects.all() data['html_partial_board'] = render_to_string('./includes/partial_board.html', { 'boards': boards, 'bloger': get_user_status(request) }) else: data['form_is_valid'] = False context = {'form': form} data['html_form'] = render_to_string(template_name, context, request=request) return JsonResponse(data) @login_required def board_delete(request, pk): board = get_object_or_404(Board, pk=pk) data = dict() boards = Board.objects.all() if request.method == 'POST': board.delete() data['form_is_valid'] = True data['html_partial_board'] = render_to_string('./includes/partial_board.html', { 'boards': boards, 'bloger': get_user_status(request), # 'messages': messages.add_message(request,messages.SUCCESS,'добавлен') }) else: context = {'board': board} data['html_form'] = render_to_string('./includes/board_form_delete.html', context, request=request, ) return JsonResponse(data)
{"/boards/urls.py": ["/boards/views.py", "/boards/export_board.py"], "/accounts/tests/conftest.py": ["/accounts/forms.py", "/accounts/models.py"], "/accounts/views.py": ["/accounts/forms.py", "/accounts/tasks.py", "/accounts/models.py", "/boards/urls.py"], "/boards/views.py": ["/boards/forms.py", "/boards/utils.py", "/accounts/tasks.py"], "/boards/signals.py": ["/accounts/tasks.py"], "/accounts/tests/testdivision.py": ["/accounts/tests/utils.py"], "/accounts/admin.py": ["/accounts/models.py"], "/myproject/context_processors.py": ["/accounts/models.py"], "/boards/utils.py": ["/accounts/models.py", "/boards/forms.py"], "/accounts/forms.py": ["/accounts/models.py"], "/accounts/tests/test_views.py": ["/accounts/models.py", "/accounts/tests/conftest.py"]}
15,594,204
deft727/django_board
refs/heads/master
/accounts/migrations/0013_rename_avatar_bloger_file.py
# Generated by Django 3.2.6 on 2021-08-06 12:15 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('accounts', '0012_auto_20210806_1104'), ] operations = [ migrations.RenameField( model_name='bloger', old_name='avatar', new_name='file', ), ]
{"/boards/urls.py": ["/boards/views.py", "/boards/export_board.py"], "/accounts/tests/conftest.py": ["/accounts/forms.py", "/accounts/models.py"], "/accounts/views.py": ["/accounts/forms.py", "/accounts/tasks.py", "/accounts/models.py", "/boards/urls.py"], "/boards/views.py": ["/boards/forms.py", "/boards/utils.py", "/accounts/tasks.py"], "/boards/signals.py": ["/accounts/tasks.py"], "/accounts/tests/testdivision.py": ["/accounts/tests/utils.py"], "/accounts/admin.py": ["/accounts/models.py"], "/myproject/context_processors.py": ["/accounts/models.py"], "/boards/utils.py": ["/accounts/models.py", "/boards/forms.py"], "/accounts/forms.py": ["/accounts/models.py"], "/accounts/tests/test_views.py": ["/accounts/models.py", "/accounts/tests/conftest.py"]}
15,594,205
deft727/django_board
refs/heads/master
/boards/signals.py
from django.db.models.signals import post_save from django.dispatch import receiver from accounts.tasks import send_user_mail_task from .models import Post from django.db.models import Count @receiver(post_save, sender=Post) def reply_topic(sender, instance, **kwargs): countable = instance.topic.board.topic_set.all().annotate(replies=Count('posts') - 1) if countable[0].replies >= 1: email = instance.topic.starter.email topic_name = instance.topic.subject topic_user = instance.created_by send_user_mail_task.delay(subject=f' replayed topic {topic_name }', content= f' "{topic_user}" replayed your topic "{topic_name}" ',email=email)
{"/boards/urls.py": ["/boards/views.py", "/boards/export_board.py"], "/accounts/tests/conftest.py": ["/accounts/forms.py", "/accounts/models.py"], "/accounts/views.py": ["/accounts/forms.py", "/accounts/tasks.py", "/accounts/models.py", "/boards/urls.py"], "/boards/views.py": ["/boards/forms.py", "/boards/utils.py", "/accounts/tasks.py"], "/boards/signals.py": ["/accounts/tasks.py"], "/accounts/tests/testdivision.py": ["/accounts/tests/utils.py"], "/accounts/admin.py": ["/accounts/models.py"], "/myproject/context_processors.py": ["/accounts/models.py"], "/boards/utils.py": ["/accounts/models.py", "/boards/forms.py"], "/accounts/forms.py": ["/accounts/models.py"], "/accounts/tests/test_views.py": ["/accounts/models.py", "/accounts/tests/conftest.py"]}
15,594,206
deft727/django_board
refs/heads/master
/boards/urls.py
from django.urls import path from .views import * from .export_board import * urlpatterns = [ path('',BoardListView.as_view(), name='home'), path('topics/<int:pk>/', TopicListView.as_view(), name='board_topics'), path('boards/<int:pk>/new/', New_topicView.as_view(), name='new_topic' ,), path('boards/<int:pk>/topics/<int:topic_pk>/', PostListView.as_view(), name='topic_posts'), path('boards/<int:pk>/topics/<int:topic_pk>/reply/',Reply_topicView.as_view(), name='reply_topic'), ###################################################################################################################### path('boards/<int:pk>/topics/<int:topic_pk>/posts/<int:post_pk>/', PostUpdateView.as_view(), name='edit_post'), path('new_articles/',new_articles,name='new_articles'), path('boards/fake/', generate_fake_data, name='generate_fake_data'), path('boards/create/',board_create, name='boards_create'), path('boards/<int:pk>/update/', board_update, name='boards_update'), path('boards/<int:pk>/delete/', board_delete, name='boards_delete'), path('boards/<int:pk>/to-xls/',export_boards_xls,name='to-xls'), path('boards/<int:pk>/to-pdf/',export_boards_pdf,name='to-pdf') ]
{"/boards/urls.py": ["/boards/views.py", "/boards/export_board.py"], "/accounts/tests/conftest.py": ["/accounts/forms.py", "/accounts/models.py"], "/accounts/views.py": ["/accounts/forms.py", "/accounts/tasks.py", "/accounts/models.py", "/boards/urls.py"], "/boards/views.py": ["/boards/forms.py", "/boards/utils.py", "/accounts/tasks.py"], "/boards/signals.py": ["/accounts/tasks.py"], "/accounts/tests/testdivision.py": ["/accounts/tests/utils.py"], "/accounts/admin.py": ["/accounts/models.py"], "/myproject/context_processors.py": ["/accounts/models.py"], "/boards/utils.py": ["/accounts/models.py", "/boards/forms.py"], "/accounts/forms.py": ["/accounts/models.py"], "/accounts/tests/test_views.py": ["/accounts/models.py", "/accounts/tests/conftest.py"]}
15,594,207
deft727/django_board
refs/heads/master
/accounts/migrations/0009_bloger_status.py
# Generated by Django 3.2.5 on 2021-07-28 09:06 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('accounts', '0008_alter_bloger_user'), ] operations = [ migrations.AddField( model_name='bloger', name='status', field=models.CharField(choices=[('True', 'bloger'), ('False', 'isn`t bloger')], default='True', max_length=100, verbose_name='are you bloger?'), ), ]
{"/boards/urls.py": ["/boards/views.py", "/boards/export_board.py"], "/accounts/tests/conftest.py": ["/accounts/forms.py", "/accounts/models.py"], "/accounts/views.py": ["/accounts/forms.py", "/accounts/tasks.py", "/accounts/models.py", "/boards/urls.py"], "/boards/views.py": ["/boards/forms.py", "/boards/utils.py", "/accounts/tasks.py"], "/boards/signals.py": ["/accounts/tasks.py"], "/accounts/tests/testdivision.py": ["/accounts/tests/utils.py"], "/accounts/admin.py": ["/accounts/models.py"], "/myproject/context_processors.py": ["/accounts/models.py"], "/boards/utils.py": ["/accounts/models.py", "/boards/forms.py"], "/accounts/forms.py": ["/accounts/models.py"], "/accounts/tests/test_views.py": ["/accounts/models.py", "/accounts/tests/conftest.py"]}
15,594,208
deft727/django_board
refs/heads/master
/accounts/tests/utils.py
def division(a,b): return a / b
{"/boards/urls.py": ["/boards/views.py", "/boards/export_board.py"], "/accounts/tests/conftest.py": ["/accounts/forms.py", "/accounts/models.py"], "/accounts/views.py": ["/accounts/forms.py", "/accounts/tasks.py", "/accounts/models.py", "/boards/urls.py"], "/boards/views.py": ["/boards/forms.py", "/boards/utils.py", "/accounts/tasks.py"], "/boards/signals.py": ["/accounts/tasks.py"], "/accounts/tests/testdivision.py": ["/accounts/tests/utils.py"], "/accounts/admin.py": ["/accounts/models.py"], "/myproject/context_processors.py": ["/accounts/models.py"], "/boards/utils.py": ["/accounts/models.py", "/boards/forms.py"], "/accounts/forms.py": ["/accounts/models.py"], "/accounts/tests/test_views.py": ["/accounts/models.py", "/accounts/tests/conftest.py"]}
15,594,209
deft727/django_board
refs/heads/master
/boards/migrations/0005_alter_photo_file.py
# Generated by Django 3.2.6 on 2021-08-05 12:32 from django.db import migrations import smartfields.fields class Migration(migrations.Migration): dependencies = [ ('boards', '0004_alter_photo_file'), ] operations = [ migrations.AlterField( model_name='photo', name='file', field=smartfields.fields.ImageField(upload_to=''), ), ]
{"/boards/urls.py": ["/boards/views.py", "/boards/export_board.py"], "/accounts/tests/conftest.py": ["/accounts/forms.py", "/accounts/models.py"], "/accounts/views.py": ["/accounts/forms.py", "/accounts/tasks.py", "/accounts/models.py", "/boards/urls.py"], "/boards/views.py": ["/boards/forms.py", "/boards/utils.py", "/accounts/tasks.py"], "/boards/signals.py": ["/accounts/tasks.py"], "/accounts/tests/testdivision.py": ["/accounts/tests/utils.py"], "/accounts/admin.py": ["/accounts/models.py"], "/myproject/context_processors.py": ["/accounts/models.py"], "/boards/utils.py": ["/accounts/models.py", "/boards/forms.py"], "/accounts/forms.py": ["/accounts/models.py"], "/accounts/tests/test_views.py": ["/accounts/models.py", "/accounts/tests/conftest.py"]}
15,594,210
deft727/django_board
refs/heads/master
/boards/migrations/0006_auto_20210805_1234.py
# Generated by Django 3.2.6 on 2021-08-05 12:34 from django.db import migrations import smartfields.fields class Migration(migrations.Migration): dependencies = [ ('boards', '0005_alter_photo_file'), ] operations = [ migrations.RemoveField( model_name='photo', name='file', ), migrations.AddField( model_name='photo', name='avatar', field=smartfields.fields.ImageField(default=1, upload_to='avatar'), preserve_default=False, ), migrations.AddField( model_name='photo', name='avatar_jpeg', field=smartfields.fields.ImageField(default=1, upload_to='avatar'), preserve_default=False, ), ]
{"/boards/urls.py": ["/boards/views.py", "/boards/export_board.py"], "/accounts/tests/conftest.py": ["/accounts/forms.py", "/accounts/models.py"], "/accounts/views.py": ["/accounts/forms.py", "/accounts/tasks.py", "/accounts/models.py", "/boards/urls.py"], "/boards/views.py": ["/boards/forms.py", "/boards/utils.py", "/accounts/tasks.py"], "/boards/signals.py": ["/accounts/tasks.py"], "/accounts/tests/testdivision.py": ["/accounts/tests/utils.py"], "/accounts/admin.py": ["/accounts/models.py"], "/myproject/context_processors.py": ["/accounts/models.py"], "/boards/utils.py": ["/accounts/models.py", "/boards/forms.py"], "/accounts/forms.py": ["/accounts/models.py"], "/accounts/tests/test_views.py": ["/accounts/models.py", "/accounts/tests/conftest.py"]}
15,594,211
deft727/django_board
refs/heads/master
/boards/migrations/0007_rename_avatar_jpeg_photo_photo.py
# Generated by Django 3.2.6 on 2021-08-05 12:50 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('boards', '0006_auto_20210805_1234'), ] operations = [ migrations.RenameField( model_name='photo', old_name='avatar_jpeg', new_name='photo', ), ]
{"/boards/urls.py": ["/boards/views.py", "/boards/export_board.py"], "/accounts/tests/conftest.py": ["/accounts/forms.py", "/accounts/models.py"], "/accounts/views.py": ["/accounts/forms.py", "/accounts/tasks.py", "/accounts/models.py", "/boards/urls.py"], "/boards/views.py": ["/boards/forms.py", "/boards/utils.py", "/accounts/tasks.py"], "/boards/signals.py": ["/accounts/tasks.py"], "/accounts/tests/testdivision.py": ["/accounts/tests/utils.py"], "/accounts/admin.py": ["/accounts/models.py"], "/myproject/context_processors.py": ["/accounts/models.py"], "/boards/utils.py": ["/accounts/models.py", "/boards/forms.py"], "/accounts/forms.py": ["/accounts/models.py"], "/accounts/tests/test_views.py": ["/accounts/models.py", "/accounts/tests/conftest.py"]}
15,594,212
deft727/django_board
refs/heads/master
/accounts/tests/testdivision.py
import django from .utils import division import pytest from django.contrib.auth.models import User @pytest.mark.parametrize("a,b,expected_result",[(10,2,5), (20,10,2), (30,-3,-10), (5,2,2.5)]) def test_division_good(a,b,expected_result): assert division(a,b) == expected_result @pytest.mark.django_db def test_user_count(): assert User.objects.count() == 0 # class UserTest(): # def setUp(self): # self.username = "testuser" # self.email = "testuser@testbase.com" # self.first_name = "Test" # self.last_name = "User" # self.password = "z" # self.test_user = User.objects.create_user( # username=self.username, # email=self.email, # first_name=self.first_name, # last_name=self.last_name # ) # def test_create_user(self): # assert isinstance(self.test_user, User) # def test_default_user_is_active(self): # assert self.test_user.is_active # def test_default_user_is_staff(self): # assert not self.test_user.is_staff # def test_default_user_is_superuser(self): # assert not self.test_user.is_superuser # def test_get_full_name(self): # assert self.test_user.get_full_name() == 'Test User' # def test_get_short_name(self): # assert self.test_user.get_short_name() == self.email # def test_unicode(self): # assert self.test_user.__unicode__() == self.username
{"/boards/urls.py": ["/boards/views.py", "/boards/export_board.py"], "/accounts/tests/conftest.py": ["/accounts/forms.py", "/accounts/models.py"], "/accounts/views.py": ["/accounts/forms.py", "/accounts/tasks.py", "/accounts/models.py", "/boards/urls.py"], "/boards/views.py": ["/boards/forms.py", "/boards/utils.py", "/accounts/tasks.py"], "/boards/signals.py": ["/accounts/tasks.py"], "/accounts/tests/testdivision.py": ["/accounts/tests/utils.py"], "/accounts/admin.py": ["/accounts/models.py"], "/myproject/context_processors.py": ["/accounts/models.py"], "/boards/utils.py": ["/accounts/models.py", "/boards/forms.py"], "/accounts/forms.py": ["/accounts/models.py"], "/accounts/tests/test_views.py": ["/accounts/models.py", "/accounts/tests/conftest.py"]}
15,594,213
deft727/django_board
refs/heads/master
/accounts/admin.py
from django.contrib import admin from .models import * class RaderAdmin(admin.ModelAdmin): list_display= ( 'id','username','user') list_display_links=('id','username','user') class BlogerAdmin(admin.ModelAdmin): list_display= ( 'id','username','user') list_display_links=('id','username','user') class CategoryAdmin(admin.ModelAdmin): prepopulated_fields = {'slug':("name",)} class InterestsAdmin(admin.ModelAdmin): prepopulated_fields = {'slug':("title",)} admin.site.register(Reader,RaderAdmin) admin.site.register(Bloger,BlogerAdmin) admin.site.register(Category,CategoryAdmin) admin.site.register(Interests,InterestsAdmin)
{"/boards/urls.py": ["/boards/views.py", "/boards/export_board.py"], "/accounts/tests/conftest.py": ["/accounts/forms.py", "/accounts/models.py"], "/accounts/views.py": ["/accounts/forms.py", "/accounts/tasks.py", "/accounts/models.py", "/boards/urls.py"], "/boards/views.py": ["/boards/forms.py", "/boards/utils.py", "/accounts/tasks.py"], "/boards/signals.py": ["/accounts/tasks.py"], "/accounts/tests/testdivision.py": ["/accounts/tests/utils.py"], "/accounts/admin.py": ["/accounts/models.py"], "/myproject/context_processors.py": ["/accounts/models.py"], "/boards/utils.py": ["/accounts/models.py", "/boards/forms.py"], "/accounts/forms.py": ["/accounts/models.py"], "/accounts/tests/test_views.py": ["/accounts/models.py", "/accounts/tests/conftest.py"]}
15,594,214
deft727/django_board
refs/heads/master
/myproject/context_processors.py
from logging import exception from django.template import context_processors from accounts.models import Bloger,Reader def get_avatar(request): if request.user.is_authenticated: try: avatar_image = Bloger.objects.filter(user=request.user).first() if avatar_image is None: raise exception except : avatar_image = Reader.objects.filter(user=request.user).first() return { 'avatar_image':avatar_image } else: return { 'avatar_image':None }
{"/boards/urls.py": ["/boards/views.py", "/boards/export_board.py"], "/accounts/tests/conftest.py": ["/accounts/forms.py", "/accounts/models.py"], "/accounts/views.py": ["/accounts/forms.py", "/accounts/tasks.py", "/accounts/models.py", "/boards/urls.py"], "/boards/views.py": ["/boards/forms.py", "/boards/utils.py", "/accounts/tasks.py"], "/boards/signals.py": ["/accounts/tasks.py"], "/accounts/tests/testdivision.py": ["/accounts/tests/utils.py"], "/accounts/admin.py": ["/accounts/models.py"], "/myproject/context_processors.py": ["/accounts/models.py"], "/boards/utils.py": ["/accounts/models.py", "/boards/forms.py"], "/accounts/forms.py": ["/accounts/models.py"], "/accounts/tests/test_views.py": ["/accounts/models.py", "/accounts/tests/conftest.py"]}
15,594,215
deft727/django_board
refs/heads/master
/accounts/migrations/0015_auto_20210809_1049.py
# Generated by Django 3.2.6 on 2021-08-09 10:49 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('accounts', '0014_auto_20210806_1321'), ] operations = [ migrations.AlterField( model_name='bloger', name='email', field=models.EmailField(max_length=254, null=True, verbose_name='Электороная почта'), ), migrations.AlterField( model_name='reader', name='interests', field=models.ManyToManyField(blank=True, to='accounts.Interests', verbose_name='Интересы'), ), ]
{"/boards/urls.py": ["/boards/views.py", "/boards/export_board.py"], "/accounts/tests/conftest.py": ["/accounts/forms.py", "/accounts/models.py"], "/accounts/views.py": ["/accounts/forms.py", "/accounts/tasks.py", "/accounts/models.py", "/boards/urls.py"], "/boards/views.py": ["/boards/forms.py", "/boards/utils.py", "/accounts/tasks.py"], "/boards/signals.py": ["/accounts/tasks.py"], "/accounts/tests/testdivision.py": ["/accounts/tests/utils.py"], "/accounts/admin.py": ["/accounts/models.py"], "/myproject/context_processors.py": ["/accounts/models.py"], "/boards/utils.py": ["/accounts/models.py", "/boards/forms.py"], "/accounts/forms.py": ["/accounts/models.py"], "/accounts/tests/test_views.py": ["/accounts/models.py", "/accounts/tests/conftest.py"]}
15,594,216
deft727/django_board
refs/heads/master
/accounts/migrations/0019_auto_20210816_1215.py
# Generated by Django 3.2.6 on 2021-08-16 12:15 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('accounts', '0018_auto_20210811_1317'), ] operations = [ migrations.AlterField( model_name='bloger', name='category', field=models.ManyToManyField(null=True, to='accounts.Category', verbose_name='Категории'), ), migrations.AlterField( model_name='reader', name='interests', field=models.ManyToManyField(blank=True, null=True, to='accounts.Interests', verbose_name='Интересы'), ), ]
{"/boards/urls.py": ["/boards/views.py", "/boards/export_board.py"], "/accounts/tests/conftest.py": ["/accounts/forms.py", "/accounts/models.py"], "/accounts/views.py": ["/accounts/forms.py", "/accounts/tasks.py", "/accounts/models.py", "/boards/urls.py"], "/boards/views.py": ["/boards/forms.py", "/boards/utils.py", "/accounts/tasks.py"], "/boards/signals.py": ["/accounts/tasks.py"], "/accounts/tests/testdivision.py": ["/accounts/tests/utils.py"], "/accounts/admin.py": ["/accounts/models.py"], "/myproject/context_processors.py": ["/accounts/models.py"], "/boards/utils.py": ["/accounts/models.py", "/boards/forms.py"], "/accounts/forms.py": ["/accounts/models.py"], "/accounts/tests/test_views.py": ["/accounts/models.py", "/accounts/tests/conftest.py"]}
15,594,217
deft727/django_board
refs/heads/master
/boards/utils.py
from accounts.models import Bloger,Reader # from django.contrib.auth.models import User from social_django import * from social_core import * from .forms import * from PIL import Image from django.core.files.uploadedfile import InMemoryUploadedFile import sys from io import BytesIO def get_image(photo): img3=Image.open(photo) new_img3=img3.convert('RGB') res_img3=new_img3.resize((700,450),Image.ANTIALIAS) filestream= BytesIO() file_=res_img3.save(filestream,'JPEG',quality=90) filestream.seek(0) name= '{}.{}'.format(*photo.name.split('.')) photo = InMemoryUploadedFile( filestream,'ImageFiedl',name,'jpeg/image',sys.getsizeof(filestream), None ) return photo def get_user_status(request): if request.user.is_authenticated: if Bloger.objects.filter(user=request.user).exists(): bloger = True return bloger else : bloger = False else: bloger= False return bloger def create_profile(strategy, details, response, user, *args, **kwargs): if Reader.objects.filter(user=user).exists(): pass else: new_profile = Reader(user=user) new_profile.save() return kwargs # def send_user_mail(request,subject,content,email): # try: # mail=send_mail(subject, content,'test.blogodvich@gmail.com',[email,], # fail_silently=False) # messages.success(request,'Письмо отправлено') # except: # messages.error(request,'Ошибка отправки')
{"/boards/urls.py": ["/boards/views.py", "/boards/export_board.py"], "/accounts/tests/conftest.py": ["/accounts/forms.py", "/accounts/models.py"], "/accounts/views.py": ["/accounts/forms.py", "/accounts/tasks.py", "/accounts/models.py", "/boards/urls.py"], "/boards/views.py": ["/boards/forms.py", "/boards/utils.py", "/accounts/tasks.py"], "/boards/signals.py": ["/accounts/tasks.py"], "/accounts/tests/testdivision.py": ["/accounts/tests/utils.py"], "/accounts/admin.py": ["/accounts/models.py"], "/myproject/context_processors.py": ["/accounts/models.py"], "/boards/utils.py": ["/accounts/models.py", "/boards/forms.py"], "/accounts/forms.py": ["/accounts/models.py"], "/accounts/tests/test_views.py": ["/accounts/models.py", "/accounts/tests/conftest.py"]}
15,594,218
deft727/django_board
refs/heads/master
/boards/migrations/0010_auto_20210809_0710.py
# Generated by Django 3.2.6 on 2021-08-09 07:10 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('boards', '0009_topic_is_activ'), ] operations = [ migrations.RemoveField( model_name='topic', name='is_activ', ), migrations.AddField( model_name='board', name='is_activ', field=models.BooleanField(blank=True, default=True, null=True), ), migrations.AddField( model_name='historicalboard', name='is_activ', field=models.BooleanField(blank=True, default=True, null=True), ), ]
{"/boards/urls.py": ["/boards/views.py", "/boards/export_board.py"], "/accounts/tests/conftest.py": ["/accounts/forms.py", "/accounts/models.py"], "/accounts/views.py": ["/accounts/forms.py", "/accounts/tasks.py", "/accounts/models.py", "/boards/urls.py"], "/boards/views.py": ["/boards/forms.py", "/boards/utils.py", "/accounts/tasks.py"], "/boards/signals.py": ["/accounts/tasks.py"], "/accounts/tests/testdivision.py": ["/accounts/tests/utils.py"], "/accounts/admin.py": ["/accounts/models.py"], "/myproject/context_processors.py": ["/accounts/models.py"], "/boards/utils.py": ["/accounts/models.py", "/boards/forms.py"], "/accounts/forms.py": ["/accounts/models.py"], "/accounts/tests/test_views.py": ["/accounts/models.py", "/accounts/tests/conftest.py"]}
15,594,219
deft727/django_board
refs/heads/master
/boards/export_board.py
from .models import Board import xlwt from django.template.loader import render_to_string from weasyprint import HTML from django.core.files.storage import FileSystemStorage from django.http import HttpResponse from django.shortcuts import redirect from django.contrib import messages def export_boards_pdf(request, pk): board = Board.objects.get(pk=pk) topics = board.topic_set.all() if len(topics)>1: html_string = render_to_string( 'topic_posts_to_pdf.html', { 'topics': topics, 'board': board}) html = HTML(string=html_string) html.write_pdf(target=f'/tmp/{board.name}.pdf') fs = FileSystemStorage('/tmp') with fs.open(f'{board.name}.pdf') as pdf: response = HttpResponse(pdf, content_type='application/pdf') response['Content-Disposition'] = f'attachment; filename="{board.name}.pdf"' return response else: messages.add_message(request,messages.ERROR,'Nothing import top pdf') try: return redirect(request.META.get('HTTP_REFERER','redirect_if_referer_not_found')) except: return redirect('home') def export_boards_xls(request,pk): response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename="TopicsXml.xls"' wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet('Topics') row_num = 0 font_style = xlwt.XFStyle() font_style.font.bold = True columns = ['subject', 'board','starter' ] for col_num in range(len(columns)): ws.write(row_num, col_num, columns[col_num], font_style) font_style = xlwt.XFStyle() rows = Board.objects.get(pk=pk).topic_set.all().values_list('subject', 'board','starter') if len(rows)>1: for row in rows: row_num += 1 for col_num in range(len(row)): ws.write(row_num, col_num, row[col_num], font_style) wb.save(response) return response else: messages.add_message(request,messages.ERROR,'Nothing import to xls') try: return redirect(request.META.get('HTTP_REFERER','redirect_if_referer_not_found')) except: return redirect('home')
{"/boards/urls.py": ["/boards/views.py", "/boards/export_board.py"], "/accounts/tests/conftest.py": ["/accounts/forms.py", "/accounts/models.py"], "/accounts/views.py": ["/accounts/forms.py", "/accounts/tasks.py", "/accounts/models.py", "/boards/urls.py"], "/boards/views.py": ["/boards/forms.py", "/boards/utils.py", "/accounts/tasks.py"], "/boards/signals.py": ["/accounts/tasks.py"], "/accounts/tests/testdivision.py": ["/accounts/tests/utils.py"], "/accounts/admin.py": ["/accounts/models.py"], "/myproject/context_processors.py": ["/accounts/models.py"], "/boards/utils.py": ["/accounts/models.py", "/boards/forms.py"], "/accounts/forms.py": ["/accounts/models.py"], "/accounts/tests/test_views.py": ["/accounts/models.py", "/accounts/tests/conftest.py"]}
15,594,220
deft727/django_board
refs/heads/master
/boards/migrations/0004_alter_photo_file.py
# Generated by Django 3.2.6 on 2021-08-05 10:33 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('boards', '0003_auto_20210803_1411'), ] operations = [ migrations.AlterField( model_name='photo', name='file', field=models.ImageField(upload_to='photos/'), ), ]
{"/boards/urls.py": ["/boards/views.py", "/boards/export_board.py"], "/accounts/tests/conftest.py": ["/accounts/forms.py", "/accounts/models.py"], "/accounts/views.py": ["/accounts/forms.py", "/accounts/tasks.py", "/accounts/models.py", "/boards/urls.py"], "/boards/views.py": ["/boards/forms.py", "/boards/utils.py", "/accounts/tasks.py"], "/boards/signals.py": ["/accounts/tasks.py"], "/accounts/tests/testdivision.py": ["/accounts/tests/utils.py"], "/accounts/admin.py": ["/accounts/models.py"], "/myproject/context_processors.py": ["/accounts/models.py"], "/boards/utils.py": ["/accounts/models.py", "/boards/forms.py"], "/accounts/forms.py": ["/accounts/models.py"], "/accounts/tests/test_views.py": ["/accounts/models.py", "/accounts/tests/conftest.py"]}
15,594,221
deft727/django_board
refs/heads/master
/myproject/settings.py
""" Django settings for myproject project. Generated by 'django-admin startproject' using Django 3.2.5. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from django.contrib.messages import constants as message_constants from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-vg+!!0!7$+!!#n$ezttr=7-aq71ikszh)!oorppt58gmuqqsml' # str(os.environ.get("SECRET_KEY")) # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True # bool(int(os.environ.get("DEBUG", default=1))) ALLOWED_HOSTS = ['*'] # os.environ.get("DJANGO_ALLOWED_HOSTS") CELERY_TIMEZONE = "Europe/Kiev" CELERY_TASK_TRACK_STARTED = True CELERY_TASK_TIME_LIMIT = 30 * 60 CELERY_BROKER_URL = 'amqp://localhost' # 'redis://localhost:6370/0' MESSAGE_LEVEL = message_constants.DEBUG MESSAGE_LEVEL = 10 # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'widget_tweaks', 'crispy_forms', 'accounts', 'boards', 'psycopg2', 'faker', 'smartfields', 'snowpenguin.django.recaptcha2', 'simple_history', 'django.contrib.sites', 'django.contrib.flatpages', # 'social_django', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'social_django.middleware.SocialAuthExceptionMiddleware', 'simple_history.middleware.HistoryRequestMiddleware', ] ROOT_URLCONF = 'myproject.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'templates') ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', 'myproject.context_processors.get_avatar', ], }, }, ] WSGI_APPLICATION = 'myproject.wsgi.application' # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases # DATABASES = { # "default": { # "ENGINE": os.environ.get("SQL_ENGINE", "django.db.backends.sqlite3"), # "NAME": os.environ.get("SQL_NAME", os.path.join(BASE_DIR, "db.sqlite3")), # "USER": os.environ.get("SQL_USER", "user"), # "PASSWORD": os.environ.get("SQL_PASSWORD", "devpass"), # "HOST": os.environ.get("SQL_HOST", "localhost"), # "PORT": os.environ.get("SQL_PORT", "5432"), # } # } # from django.contrib.auth.models import User # from boards.models import Board, Topic, Post # user = User.objects.first() # board = Board.objects.create(name='Docker') # for i in range(100): # subject = 'Topic test #{}'.format(i) # topic = Topic.objects.create(subject=subject, board=board, starter=user) # Post.objects.create(message='Lorem ipsum...', topic=topic, created_by=user) # DATABASES = { # 'default': { # 'ENGINE': 'django.db.backends.postgresql_psycopg2', # 'NAME': 'prod_db', # 'USER': 'admin', # 'PASSWORD': 'devpass', # 'HOST' : 'postgresdb', # 'PORT' : 5432 # } # } DATABASES = {'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] AUTHENTICATION_BACKENDS = ( 'social_core.backends.github.GithubOAuth2', 'social_core.backends.twitter.TwitterOAuth', 'social_core.backends.facebook.FacebookOAuth2', 'social_core.backends.google.GoogleOAuth2', 'django.contrib.auth.backends.ModelBackend', ) # Internationalization # https://docs.djangoproject.com/en/3.2/topics/i18n/ SOCIAL_AUTH_PIPELINE = ( 'social.pipeline.social_auth.social_details', 'social.pipeline.social_auth.social_uid', 'social.pipeline.social_auth.auth_allowed', 'social.pipeline.social_auth.social_user', 'social.pipeline.user.get_username', 'social.pipeline.user.create_user', 'social.pipeline.social_auth.associate_user', 'social.pipeline.social_auth.load_extra_data', 'social.pipeline.user.user_details', 'boards.utils.create_profile' ) LANGUAGE_CODE = 'en' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True LOGIN_REDIRECT_URL = 'home' # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.2/howto/static-files/ # Default primary key field type # https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' # STATIC_URL = '/static/' # STATIC_DIR = os.path.join(BASE_DIR,'static') # STATIC_ROOT = os.path.join(BASE_DIR,'static') STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] # STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR,'media') CRISPY_TEMPLATE_PACK = 'bootstrap4' # django fotolog # if DEBUG: # EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' LOGIN_URL = 'login' LOGIN_REDIRECT_URL = '/' LOGOUT_REDIRECT_URL = '/' LOGIN_REDIRECT_URL = 'my_account' SITE_ID = 1 SOCIAL_AUTH_URL_NAMESPACE = 'social' SOCIAL_AUTH_GITHUB_KEY = 'ac2c81b0f7e251748034' SOCIAL_AUTH_GITHUB_SECRET = 'ac46faf76c240ec910fa0d52e2bcf51f2dd522c1' SOCIAL_AUTH_FACEBOOK_KEY = '868434577098385' SOCIAL_AUTH_FACEBOOK_SECRET = 'e2351fc2821ceefcb601b1e4794c9ef8' SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = '233025016839-029b0a3bsvuu5h97vccm6jdv10ung6hh.apps.googleusercontent.com' SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = 'wPLtnBc7cQzmCVtMM9uV_CZN' # '6LdgxMobAAAAAASmY81cQDAkI6rK8RXp5EYJZdXo' GOOGLE_RECAPTCHA_SECRET_KEY ='6LfS2swbAAAAAJPp0Zu7zK23s__XlLukWvENo_gj' RECAPTCHA_PRIVATE_KEY = '6LfS2swbAAAAAJPp0Zu7zK23s__XlLukWvENo_gj' RECAPTCHA_PUBLIC_KEY = '6LfS2swbAAAAALsPWnB2GOlOBdQiqnXgn9H0Raq0' ADMIN = 'test.blogodvich@gmail.com' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'test.blogodvich@gmail.com' EMAIL_HOST_PASSWORD = 'Kirill99' EMAIL_PORT = 587 EMAIL_HOST_PASSWORD ='nzsietbzmayagzfa'
{"/boards/urls.py": ["/boards/views.py", "/boards/export_board.py"], "/accounts/tests/conftest.py": ["/accounts/forms.py", "/accounts/models.py"], "/accounts/views.py": ["/accounts/forms.py", "/accounts/tasks.py", "/accounts/models.py", "/boards/urls.py"], "/boards/views.py": ["/boards/forms.py", "/boards/utils.py", "/accounts/tasks.py"], "/boards/signals.py": ["/accounts/tasks.py"], "/accounts/tests/testdivision.py": ["/accounts/tests/utils.py"], "/accounts/admin.py": ["/accounts/models.py"], "/myproject/context_processors.py": ["/accounts/models.py"], "/boards/utils.py": ["/accounts/models.py", "/boards/forms.py"], "/accounts/forms.py": ["/accounts/models.py"], "/accounts/tests/test_views.py": ["/accounts/models.py", "/accounts/tests/conftest.py"]}
15,594,222
deft727/django_board
refs/heads/master
/boards/admin.py
from django.contrib import admin from .models import * from .admin_actions import * class BoardAdmin(admin.ModelAdmin): list_display = ["id","name","description"] list_display_links= ["id","name"] actions = [is_not_activ,is_activ,export_boards] class TopicAdmin(admin.ModelAdmin): list_display = ["id","subject","board"] list_display_links= ["id","subject"] class PostAdmin(admin.ModelAdmin): list_display = ["id","message","topic","created_at"] list_display_links= ["id","message","topic",] admin.site.register(Board,BoardAdmin) admin.site.register(Topic,TopicAdmin) admin.site.register(Post,PostAdmin) admin.site.register(Photo)
{"/boards/urls.py": ["/boards/views.py", "/boards/export_board.py"], "/accounts/tests/conftest.py": ["/accounts/forms.py", "/accounts/models.py"], "/accounts/views.py": ["/accounts/forms.py", "/accounts/tasks.py", "/accounts/models.py", "/boards/urls.py"], "/boards/views.py": ["/boards/forms.py", "/boards/utils.py", "/accounts/tasks.py"], "/boards/signals.py": ["/accounts/tasks.py"], "/accounts/tests/testdivision.py": ["/accounts/tests/utils.py"], "/accounts/admin.py": ["/accounts/models.py"], "/myproject/context_processors.py": ["/accounts/models.py"], "/boards/utils.py": ["/accounts/models.py", "/boards/forms.py"], "/accounts/forms.py": ["/accounts/models.py"], "/accounts/tests/test_views.py": ["/accounts/models.py", "/accounts/tests/conftest.py"]}
15,594,223
deft727/django_board
refs/heads/master
/accounts/migrations/0011_auto_20210804_1603.py
# Generated by Django 3.2.6 on 2021-08-04 16:03 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('accounts', '0010_auto_20210804_1528'), ] operations = [ migrations.AlterField( model_name='bloger', name='avatar', field=models.ImageField(null=True, upload_to=''), ), migrations.AlterField( model_name='reader', name='avatar', field=models.ImageField(null=True, upload_to=''), ), migrations.DeleteModel( name='Avatar', ), ]
{"/boards/urls.py": ["/boards/views.py", "/boards/export_board.py"], "/accounts/tests/conftest.py": ["/accounts/forms.py", "/accounts/models.py"], "/accounts/views.py": ["/accounts/forms.py", "/accounts/tasks.py", "/accounts/models.py", "/boards/urls.py"], "/boards/views.py": ["/boards/forms.py", "/boards/utils.py", "/accounts/tasks.py"], "/boards/signals.py": ["/accounts/tasks.py"], "/accounts/tests/testdivision.py": ["/accounts/tests/utils.py"], "/accounts/admin.py": ["/accounts/models.py"], "/myproject/context_processors.py": ["/accounts/models.py"], "/boards/utils.py": ["/accounts/models.py", "/boards/forms.py"], "/accounts/forms.py": ["/accounts/models.py"], "/accounts/tests/test_views.py": ["/accounts/models.py", "/accounts/tests/conftest.py"]}
15,594,224
deft727/django_board
refs/heads/master
/accounts/migrations/0002_auto_20210726_0842.py
# Generated by Django 3.2.5 on 2021-07-26 08:42 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('accounts', '0001_initial'), ] operations = [ migrations.CreateModel( name='Category', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=250, verbose_name='Имя категории')), ('slug', models.SlugField(unique=True)), ], options={ 'verbose_name': 'Категории', 'verbose_name_plural': 'Категории', 'ordering': ['name'], }, ), migrations.CreateModel( name='Interests', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=250, verbose_name='Интерес')), ('slug', models.SlugField(unique=True)), ], options={ 'verbose_name': 'Интерес', 'verbose_name_plural': 'Интересы', 'ordering': ['title'], }, ), migrations.AddField( model_name='bloger', name='last_name', field=models.CharField(blank=True, max_length=50, null=True, verbose_name='фамилия'), ), migrations.AddField( model_name='reader', name='last_name', field=models.CharField(blank=True, max_length=50, null=True, verbose_name='фамилия'), ), migrations.AddField( model_name='reader', name='of_age', field=models.BooleanField(default=False), ), migrations.AlterField( model_name='bloger', name='username', field=models.CharField(default=None, max_length=255, verbose_name='имя'), ), migrations.AlterField( model_name='reader', name='user', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL, verbose_name='читатель'), ), migrations.AlterField( model_name='reader', name='username', field=models.CharField(blank=True, max_length=50, null=True, verbose_name='имя'), ), migrations.AddField( model_name='bloger', name='category', field=models.ManyToManyField(to='accounts.Category', verbose_name='Категории'), ), migrations.AddField( model_name='reader', name='interests', field=models.ManyToManyField(to='accounts.Interests', verbose_name='Категории'), ), ]
{"/boards/urls.py": ["/boards/views.py", "/boards/export_board.py"], "/accounts/tests/conftest.py": ["/accounts/forms.py", "/accounts/models.py"], "/accounts/views.py": ["/accounts/forms.py", "/accounts/tasks.py", "/accounts/models.py", "/boards/urls.py"], "/boards/views.py": ["/boards/forms.py", "/boards/utils.py", "/accounts/tasks.py"], "/boards/signals.py": ["/accounts/tasks.py"], "/accounts/tests/testdivision.py": ["/accounts/tests/utils.py"], "/accounts/admin.py": ["/accounts/models.py"], "/myproject/context_processors.py": ["/accounts/models.py"], "/boards/utils.py": ["/accounts/models.py", "/boards/forms.py"], "/accounts/forms.py": ["/accounts/models.py"], "/accounts/tests/test_views.py": ["/accounts/models.py", "/accounts/tests/conftest.py"]}
15,594,225
deft727/django_board
refs/heads/master
/boards/forms.py
from django import forms # from django.forms import fields # from django.http import request from .models import Post,Board # Photo,Topic class NewTopicForm(forms.Form): subject = forms.CharField(max_length=100) message = forms.CharField( widget=forms.Textarea( attrs={'row':5,'placeholder':'what is your mind?'} ), max_length=4000, help_text='Max length is 4000') file = forms.FileField(required=False,widget=forms.ClearableFileInput(attrs={ 'multiple': True, 'class':'js-upload-photos', 'id':'fileupload', })) class Meta: fields =('subject','message','file') class PostForm(forms.ModelForm): class Meta: model = Post fields = ['message', ] class BoardForm(forms.ModelForm): class Meta: model = Board fields = '__all__'
{"/boards/urls.py": ["/boards/views.py", "/boards/export_board.py"], "/accounts/tests/conftest.py": ["/accounts/forms.py", "/accounts/models.py"], "/accounts/views.py": ["/accounts/forms.py", "/accounts/tasks.py", "/accounts/models.py", "/boards/urls.py"], "/boards/views.py": ["/boards/forms.py", "/boards/utils.py", "/accounts/tasks.py"], "/boards/signals.py": ["/accounts/tasks.py"], "/accounts/tests/testdivision.py": ["/accounts/tests/utils.py"], "/accounts/admin.py": ["/accounts/models.py"], "/myproject/context_processors.py": ["/accounts/models.py"], "/boards/utils.py": ["/accounts/models.py", "/boards/forms.py"], "/accounts/forms.py": ["/accounts/models.py"], "/accounts/tests/test_views.py": ["/accounts/models.py", "/accounts/tests/conftest.py"]}
15,594,226
deft727/django_board
refs/heads/master
/accounts/forms.py
from django import forms # from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User # from django.db.models import fields # from django.forms.widgets import RadioSelect # from django.http import request from django.urls.conf import path from .models import * from snowpenguin.django.recaptcha2.fields import ReCaptchaField from snowpenguin.django.recaptcha2.widgets import ReCaptchaWidget from PIL import Image class SignUpFormReader(forms.ModelForm): confirm_password = forms.CharField(widget=forms.PasswordInput) password=forms.CharField(widget=forms.PasswordInput) email = forms.EmailField(required=True) of_age = forms.BooleanField(required=False) interests = forms.ModelMultipleChoiceField(queryset=Interests.objects.all(), widget=forms.CheckboxSelectMultiple, required=False ) captcha = ReCaptchaField(widget=ReCaptchaWidget()) def __init__(self,*args,**kwargs): super().__init__(*args,**kwargs) self.fields['username'].label='Логин' self.fields['password'].label = 'Пароль' self.fields['email'].label='Электороная почта' self.fields['confirm_password'].label='Подтвердите пароль' self.fields['of_age'].label = 'Есть 18?' self.fields['interests'].label='Интересы' class Meta: model = User fields=['username','email','password','confirm_password','of_age','interests','captcha'] def clean_email(self): if User.objects.filter(email=self.cleaned_data['email']).exists(): raise forms.ValidationError(f'Данный e-mail уже зарегистрован') return self.cleaned_data['email'] def clean_username(self): username= self.cleaned_data['username'] if User.objects.filter(username=username).exists(): raise forms.ValidationError(f'Имя {username} занято') return username def clean_of_age(self): of_age = self.cleaned_data['of_age'] if not of_age: of_age = False else: of_age = True return of_age def clean(self): try : self.cleaned_data['password'] and self.cleaned_data['confirm_password'] except: raise forms.ValidationError('Введите пароль') password = self.cleaned_data['password'] confirm_password= self.cleaned_data['confirm_password'] if password != confirm_password: raise forms.ValidationError('Пароли не совпадают') return self.cleaned_data class DateInput(forms.DateInput): input_type = 'date' class SignUpFormBloger(forms.ModelForm): STATUS_TRUE ='True' STATUS_FALSE='False' STATUS_CHOICES= ( (STATUS_TRUE,'bloger'), (STATUS_FALSE,'isn`t bloger'), ) confirm_password = forms.CharField(widget=forms.PasswordInput,required=True) password=forms.CharField(widget=forms.PasswordInput,required=True) email = forms.EmailField(required=True) birthday = forms.DateField(required=False, widget = DateInput()) country = forms.CharField(max_length=50) category = forms.ModelMultipleChoiceField(queryset=Category.objects.all(), widget=forms.CheckboxSelectMultiple, required=False ) captcha = ReCaptchaField(widget=ReCaptchaWidget()) status = forms.ChoiceField( choices=STATUS_CHOICES, required=False ) def __init__(self,*args,**kwargs): super().__init__(*args,**kwargs) self.fields['username'].label='Логин' self.fields['password'].label = 'Пароль' self.fields['confirm_password'].label='Подтвердите пароль' self.fields['email'].label='Электороная почта' self.fields['country'].label='Город' self.fields['birthday'].label='Дата рождения' self.fields['category'].label='Категории' self.fields['status'].label='status' class Meta: model = User fields = ('username','email','password','confirm_password','birthday','country','category','status','captcha') def clean_email(self): if User.objects.filter(email=self.cleaned_data['email']).exists(): raise forms.ValidationError(f'Данный e-mail уже зарегистрован') return self.cleaned_data['email'] def clean_username(self): username= self.cleaned_data['username'] if User.objects.filter(username=username).exists(): raise forms.ValidationError(f'Имя {username} занято') return username def clean(self): try : self.cleaned_data['password'] and self.cleaned_data['confirm_password'] except: raise forms.ValidationError('Введите пароль') password = self.cleaned_data['password'] confirm_password= self.cleaned_data['confirm_password'] if password != confirm_password: raise forms.ValidationError('Пароли не совпадают') return self.cleaned_data class BlogerForm(forms.ModelForm): birthday = forms.DateField(required=False, widget = DateInput()) category = forms.ModelMultipleChoiceField( queryset=Category.objects.all(), widget=forms.CheckboxSelectMultiple, required=False, ) x = forms.FloatField(widget=forms.HiddenInput(),required=False) y = forms.FloatField(widget=forms.HiddenInput(),required=False) width = forms.FloatField(widget=forms.HiddenInput(),required=False) height = forms.FloatField(widget=forms.HiddenInput(),required=False) class Meta: model = Bloger fields = ['file', 'x', 'y', 'width', 'height','username','email', 'birthday', 'country','category'] exclude = ('user','bloger','is_super',) widgets = { 'file': forms.FileInput(attrs={ 'accept': 'image/*' }) } def save(self): photo = super(BlogerForm, self).save() x = self.cleaned_data.get('x') y = self.cleaned_data.get('y') w = self.cleaned_data.get('width') h = self.cleaned_data.get('height') if x and y and w and h: image = Image.open(photo.file) cropped_image = image.crop((x, y, w+x, h+y)) resized_image = cropped_image.resize((200, 200), Image.ANTIALIAS) resized_image.save(photo.file.path) return photo class ReaderForm(forms.ModelForm): interests = forms.ModelMultipleChoiceField( queryset=Interests.objects.all(), widget=forms.CheckboxSelectMultiple, required=False) x = forms.FloatField(widget=forms.HiddenInput(),required=False) y = forms.FloatField(widget=forms.HiddenInput(),required=False) width = forms.FloatField(widget=forms.HiddenInput(),required=False) height = forms.FloatField(widget=forms.HiddenInput(),required=False) class Meta: model = Reader fields = ['file', 'x', 'y', 'width', 'height','username','of_age', 'interests'] exclude = ('user','reader','is_super',) widgets = { 'file': forms.FileInput(attrs={ 'accept': 'image/*' }) } def save(self): photo = super(ReaderForm, self).save() x = self.cleaned_data.get('x') y = self.cleaned_data.get('y') w = self.cleaned_data.get('width') h = self.cleaned_data.get('height') if x and y and w and h: image = Image.open(photo.file) cropped_image = image.crop((x, y, w+x, h+y)) resized_image = cropped_image.resize((200, 200), Image.ANTIALIAS) photo.username = self.cleaned_data.get('username') resized_image.save(photo.file.path) return photo class LoginForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) # captcha = ReCaptchaField(widget=ReCaptchaWidget()) def __init__(self,*args,**kwargs): super().__init__(*args,**kwargs) self.fields['username'].label='Логин или е-майл' self.fields['password'].label = 'Пароль' def clean(self): try : self.cleaned_data['password'] and self.cleaned_data['username'] except: raise forms.ValidationError('Введите имя и пароль') username= self.cleaned_data['username'] password= self.cleaned_data['password'] if '@' in username: if not User.objects.filter(email=username).exists(): raise forms.ValidationError(f'Пользователь с почтой {username} не найден.') else: if not User.objects.filter(username=username).exists(): raise forms.ValidationError(f'Пользователь с логином {username} не найден.') user = User.objects.filter(username=username).first() user1= User.objects.filter(email=username).first() if user: if not user.check_password(password): raise forms.ValidationError("Неверный пароль") else: if not user1.check_password(password): raise forms.ValidationError("Неверный пароль") return self.cleaned_data class Meta: model=User fields= ['username','password',] # 'captcha' # class SignUpForm(UserCreationForm): # email = forms.CharField(max_length=254, required=False, widget=forms.EmailInput()) # class Meta: # model = User # fields = ('username', 'email', 'password1', 'password2') # class PhotoForm(forms.ModelForm): # x = forms.FloatField(widget=forms.HiddenInput()) # y = forms.FloatField(widget=forms.HiddenInput()) # width = forms.FloatField(widget=forms.HiddenInput()) # height = forms.FloatField(widget=forms.HiddenInput()) # class Meta: # model = Avatar # fields = ('avatar', 'x', 'y', 'width', 'height', ) # def save(self): # avatar = super(PhotoForm, self).save() # x = self.cleaned_data.get('x') # y = self.cleaned_data.get('y') # w = self.cleaned_data.get('width') # h = self.cleaned_data.get('height') # image = Image.open(avatar.file) # cropped_image = image.crop((x, y, w+x, h+y)) # resized_image = cropped_image.resize((200, 200), Image.ANTIALIAS) # resized_image.save(avatar.file.path) # return avatar
{"/boards/urls.py": ["/boards/views.py", "/boards/export_board.py"], "/accounts/tests/conftest.py": ["/accounts/forms.py", "/accounts/models.py"], "/accounts/views.py": ["/accounts/forms.py", "/accounts/tasks.py", "/accounts/models.py", "/boards/urls.py"], "/boards/views.py": ["/boards/forms.py", "/boards/utils.py", "/accounts/tasks.py"], "/boards/signals.py": ["/accounts/tasks.py"], "/accounts/tests/testdivision.py": ["/accounts/tests/utils.py"], "/accounts/admin.py": ["/accounts/models.py"], "/myproject/context_processors.py": ["/accounts/models.py"], "/boards/utils.py": ["/accounts/models.py", "/boards/forms.py"], "/accounts/forms.py": ["/accounts/models.py"], "/accounts/tests/test_views.py": ["/accounts/models.py", "/accounts/tests/conftest.py"]}
15,594,227
deft727/django_board
refs/heads/master
/accounts/tests/test_views.py
from functools import partial from logging import log from django import urls from django.contrib.auth import get_user_model import pytest from django.contrib.auth.models import User from accounts.models import Reader,Bloger from .conftest import create_user from django.shortcuts import redirect from urllib.parse import urlencode @pytest.mark.django_db @pytest.mark.parametrize("param",[ ('home'), ('signup'), ('signup_reader'), ('signup_bloger'), ('login'), ('password_reset'), ]) def test_render_views(client,param): temp_url = urls.reverse(param) resp = client.get(temp_url) assert resp.status_code == 200 def test_an_admin_view(admin_client): response = admin_client.get('/admin/') assert response.status_code == 200 @pytest.mark.django_db def test_user_logout(client, authenticated_user): logout_url = urls.reverse('logout') resp = client.get(logout_url,follow_redirects=False) assert resp.status_code == 302 assert resp.url == urls.reverse('home') @pytest.mark.django_db def test_create_reader(client,create_reader,reader_data): user_model = Reader assert user_model.objects.count() == 1 login_url = urls.reverse('login') print(login_url) resp = client.post(login_url,data=reader_data,follow_redirects=True) assert resp.status_code == 200 # @pytest.mark.django_db # def test_reader_form_with_data(reader): # assert True is not None # assert True == reader.is_valid() # @pytest.mark.django_db # def test_bloger_form_with_data(bloger): # assert True is not None # assert True == bloger.is_valid() # @pytest.mark.django_db # def test_user_signup(client): # user_model = User # reader_model = Reader # print(user_model.objects.count(),' @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@') # print(reader_model.objects.count(),' @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@') # assert reader_model.objects.count() == 0 # user = create_user() # signupurl = client.get(urls.reverse('signup_reader')) # print(signupurl) # print(signupurl) # data = {'user':user, # 'username':user.username, # } # print(data) # resp = client.post(signupurl,data) # print(resp) # # user = create_user() # # # print(reader) # # resp = client.post(signupurl,data = { # # 'password':'qwerty1234', # # 'confirm_password':'qwerty1234', # # 'user':user, # # 'username':user.username, # # }) # # x= resp # # print(x) # # assert user_model.objects.count() == 0 # assert resp.status_code == 302 # @pytest.mark.django_db # def test_context_create_bloger(client): # user_model = User # reader_model = Bloger # assert user_model.objects.count() == 0 # user = create_user() # assert user_model.objects.count() == 1 # assert reader_model.objects.count() == 0 # data = {'username':'test123','password':'djnagoresearchj929','email':'sadasdsa@mail.com','user':user} # url = urls.reverse("signup_bloger") # response = client.post(url, data) # # reader_model.objects.create(user=user,username=response.context['form'].cleaned_data['username']) # # assert reader_model.objects.count() == 1 # assert response.status_code == 302 # user = create_user() # resp = Reader(username=user.username,user=user) # resp.set_password='qwerty1234' # resp.save() # print(resp)
{"/boards/urls.py": ["/boards/views.py", "/boards/export_board.py"], "/accounts/tests/conftest.py": ["/accounts/forms.py", "/accounts/models.py"], "/accounts/views.py": ["/accounts/forms.py", "/accounts/tasks.py", "/accounts/models.py", "/boards/urls.py"], "/boards/views.py": ["/boards/forms.py", "/boards/utils.py", "/accounts/tasks.py"], "/boards/signals.py": ["/accounts/tasks.py"], "/accounts/tests/testdivision.py": ["/accounts/tests/utils.py"], "/accounts/admin.py": ["/accounts/models.py"], "/myproject/context_processors.py": ["/accounts/models.py"], "/boards/utils.py": ["/accounts/models.py", "/boards/forms.py"], "/accounts/forms.py": ["/accounts/models.py"], "/accounts/tests/test_views.py": ["/accounts/models.py", "/accounts/tests/conftest.py"]}
15,594,228
deft727/django_board
refs/heads/master
/accounts/migrations/0018_auto_20210811_1317.py
# Generated by Django 3.2.6 on 2021-08-11 13:17 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('accounts', '0017_rename_imagine_bloger_file'), ] operations = [ migrations.AlterField( model_name='bloger', name='file', field=models.ImageField(blank=True, null=True, upload_to='avatar/'), ), migrations.AlterField( model_name='reader', name='file', field=models.ImageField(blank=True, null=True, upload_to='avatar/'), ), migrations.AlterField( model_name='reader', name='user', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='reader', to=settings.AUTH_USER_MODEL, verbose_name='читатель'), ), ]
{"/boards/urls.py": ["/boards/views.py", "/boards/export_board.py"], "/accounts/tests/conftest.py": ["/accounts/forms.py", "/accounts/models.py"], "/accounts/views.py": ["/accounts/forms.py", "/accounts/tasks.py", "/accounts/models.py", "/boards/urls.py"], "/boards/views.py": ["/boards/forms.py", "/boards/utils.py", "/accounts/tasks.py"], "/boards/signals.py": ["/accounts/tasks.py"], "/accounts/tests/testdivision.py": ["/accounts/tests/utils.py"], "/accounts/admin.py": ["/accounts/models.py"], "/myproject/context_processors.py": ["/accounts/models.py"], "/boards/utils.py": ["/accounts/models.py", "/boards/forms.py"], "/accounts/forms.py": ["/accounts/models.py"], "/accounts/tests/test_views.py": ["/accounts/models.py", "/accounts/tests/conftest.py"]}
15,594,229
deft727/django_board
refs/heads/master
/accounts/migrations/0001_initial.py
# Generated by Django 3.2.5 on 2021-07-26 08:16 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='Reader', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('username', models.CharField(default=None, max_length=255, verbose_name='name')), ('is_super', models.BooleanField(default=False)), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL, verbose_name='читателб')), ], ), migrations.CreateModel( name='Bloger', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('username', models.CharField(default=None, max_length=255, verbose_name='name')), ('email', models.EmailField(max_length=254)), ('birthday', models.DateTimeField(blank=True, null=True)), ('country', models.CharField(default=None, max_length=255, verbose_name='country')), ('is_super', models.BooleanField(default=False)), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL, verbose_name='блогер')), ], ), ]
{"/boards/urls.py": ["/boards/views.py", "/boards/export_board.py"], "/accounts/tests/conftest.py": ["/accounts/forms.py", "/accounts/models.py"], "/accounts/views.py": ["/accounts/forms.py", "/accounts/tasks.py", "/accounts/models.py", "/boards/urls.py"], "/boards/views.py": ["/boards/forms.py", "/boards/utils.py", "/accounts/tasks.py"], "/boards/signals.py": ["/accounts/tasks.py"], "/accounts/tests/testdivision.py": ["/accounts/tests/utils.py"], "/accounts/admin.py": ["/accounts/models.py"], "/myproject/context_processors.py": ["/accounts/models.py"], "/boards/utils.py": ["/accounts/models.py", "/boards/forms.py"], "/accounts/forms.py": ["/accounts/models.py"], "/accounts/tests/test_views.py": ["/accounts/models.py", "/accounts/tests/conftest.py"]}
15,710,610
17343001493/20201024
refs/heads/master
/config.py
HEADERS = {'X-Requested-With': 'XMLHttpRequest'} IP = "http://121.42.15.146:9090"
{"/script/test_order.py": ["/api/loginApi.py"], "/script/test_mtx_login.py": ["/api/loginApi.py"], "/api/loginApi.py": ["/config.py"]}
15,710,611
17343001493/20201024
refs/heads/master
/script/test_mtx_login.py
import requests from api.loginApi import MtxLogin class TestLogin: def setup_class(self): self.session = requests.Session() self.login_obj = MtxLogin() def test_login_success(self): data = {}
{"/script/test_order.py": ["/api/loginApi.py"], "/script/test_mtx_login.py": ["/api/loginApi.py"], "/api/loginApi.py": ["/config.py"]}
15,710,612
17343001493/20201024
refs/heads/master
/tools/__init__.py
''' 这是一个测试脚本 白思小姐的Git 嗨,你好吗 四十四 '''
{"/script/test_order.py": ["/api/loginApi.py"], "/script/test_mtx_login.py": ["/api/loginApi.py"], "/api/loginApi.py": ["/config.py"]}
15,710,613
17343001493/20201024
refs/heads/master
/api/loginApi.py
from config import HEADERS,IP import requests class MtxLogin: pass
{"/script/test_order.py": ["/api/loginApi.py"], "/script/test_mtx_login.py": ["/api/loginApi.py"], "/api/loginApi.py": ["/config.py"]}
15,882,713
j-pool/jpi
HEAD
/jpi/_version.py
__author__ = 'Andrew Hawker <andrew.r.hawker@gmail.com>' __version__ = '0.0.1'
{"/jpi/__init__.py": ["/jpi/scores/scores.py", "/jpi/spreads/spreads.py", "/jpi/games/games.py"], "/jpi/games/games.py": ["/jpi/json_utils.py"], "/run.py": ["/jpi/__init__.py"]}
15,882,714
j-pool/jpi
HEAD
/jpi/json_utils.py
__author__ = 'Andrew Hawker <andrew.r.hawker@gmail.com>' import json import datetime from flask import Response class JPLEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, (datetime.datetime, datetime.date)): return obj.isoformat() return super(JPLEncoder, self).default(obj) def jsonify(*args, **kwargs): payload = json.dumps(dict(*args, **kwargs), cls=JPLEncoder) return Response(payload, mimetype='application/json')
{"/jpi/__init__.py": ["/jpi/scores/scores.py", "/jpi/spreads/spreads.py", "/jpi/games/games.py"], "/jpi/games/games.py": ["/jpi/json_utils.py"], "/run.py": ["/jpi/__init__.py"]}
15,882,715
j-pool/jpi
HEAD
/jpi/games/__init__.py
__author__ = 'Andrew Hawker <andrew.r.hawker@gmail.com>'
{"/jpi/__init__.py": ["/jpi/scores/scores.py", "/jpi/spreads/spreads.py", "/jpi/games/games.py"], "/jpi/games/games.py": ["/jpi/json_utils.py"], "/run.py": ["/jpi/__init__.py"]}
15,882,716
j-pool/jpi
HEAD
/jpi/__init__.py
__author__ = 'Andrew Hawker <andrew.r.hawker@gmail.com>' from flask import Flask, jsonify from werkzeug.exceptions import default_exceptions def json_service_app(app): def jsonify_unhandled_exceptions(e): response = jsonify(message=str(e)) response.status_code = getattr(e, 'code', 500) return response for status_code in default_exceptions.keys(): app.error_handler_spec[None][status_code] = jsonify_unhandled_exceptions return app app = json_service_app(Flask(__name__)) from jpi.games.games import games app.register_blueprint(games)
{"/jpi/__init__.py": ["/jpi/scores/scores.py", "/jpi/spreads/spreads.py", "/jpi/games/games.py"], "/jpi/games/games.py": ["/jpi/json_utils.py"], "/run.py": ["/jpi/__init__.py"]}
15,882,717
j-pool/jpi
HEAD
/jpi/games/games.py
__author__ = 'Andrew Hawker <andrew.r.hawker@gmail.com>' from flask import Blueprint from jpi.json_utils import jsonify from jpi.games.mocks import MOCK_GAMES games = Blueprint('games', __name__, url_prefix='/games') @games.route('/') def get_games(): return jsonify(games=MOCK_GAMES) @games.route('/<int:year>') def get_games_by_year(year): return jsonify(games=MOCK_GAMES[2012-year]) @games.route('/<int:year>/<int:week>') def get_games_by_week(year, week): return jsonify(games=MOCK_GAMES[2012-year][week-1])
{"/jpi/__init__.py": ["/jpi/scores/scores.py", "/jpi/spreads/spreads.py", "/jpi/games/games.py"], "/jpi/games/games.py": ["/jpi/json_utils.py"], "/run.py": ["/jpi/__init__.py"]}
15,882,718
j-pool/jpi
HEAD
/run.py
__author__ = 'Andrew Hawker <andrew.r.hawker@gmail.com>' from jpi import app app.run(debug=True)
{"/jpi/__init__.py": ["/jpi/scores/scores.py", "/jpi/spreads/spreads.py", "/jpi/games/games.py"], "/jpi/games/games.py": ["/jpi/json_utils.py"], "/run.py": ["/jpi/__init__.py"]}
15,982,596
dsPolar/RuinedStats
refs/heads/main
/aram_data_cleaning.py
from riotwatcher import LolWatcher, ApiError import pandas as pd import numpy as np from api_key import key import aram_single_summoner def load_frame(path="csv/aram_games_info.csv"): return pd.read_csv(path, index_col=0) def save_frame(aram_frame, path="csv/aram_games_info.csv"): aram_frame.to_csv(path) def drop_unnamed(aram_frame): return aram_frame.drop(aram_frame.columns[aram_frame.columns.str.contains('unnamed', case = False)], axis=1) def drop_needless(aram_frame): return aram_frame.drop(['platformId', 'queueId', 'mapId', 'gameMode', 'gameType'], axis=1) if __name__ == "__main__": aram_frame = load_frame() #aram_frame = drop_unnamed(aram_frame) aram_frame = drop_needless(aram_frame) save_frame = save_frame(aram_frame)
{"/ruined_stats/cli.py": ["/ruined_stats/models.py"], "/aram_data_cleaning.py": ["/aram_single_summoner.py"], "/aram_personal_stats.py": ["/aram_single_summoner.py", "/data_dragon_handler.py"]}
15,982,597
dsPolar/RuinedStats
refs/heads/main
/aram_personal_stats.py
from riotwatcher import LolWatcher, ApiError import pandas as pd import numpy as np import matplotlib.pyplot as plt from api_key import key import aram_single_summoner from data_dragon_handler import create_champion_id_dict if __name__ == "__main__": frame = pd.read_csv("csv/all_aram_games.csv", index_col=0) champion_ids_dict = create_champion_id_dict() frame["champion"] = frame["champion"].astype(str) frame.replace({"champion": champion_ids_dict}, inplace=True) # Get frequency of champion occurence champion_counts = frame['champion'].value_counts().to_dict() with open("output/champion_counts.txt", "w") as f: print(champion_counts, file=f) f.close() # Create dataframe in the format we want champion_playrate_frame = pd.DataFrame.from_dict({"name":list(champion_ids_dict.values())}) # Find the champions that haven't been played in the range unplayed_champions = [champ for champ in list(champion_ids_dict.values()) if champ not in list(champion_counts.keys())] # Dictionary comprehension to create a name:gameCount pair for each unplayed champion champion_counts.update({key:0 for key in unplayed_champions}) # Add the gameCount column with the champion name mapped to their playcount champion_playrate_frame['gameCount'] = champion_playrate_frame['name'].map(champion_counts) expected_playrate = 1.0 / len(champion_ids_dict.keys()) total_games = len(frame.index) champion_playrate_frame['playrate'] = champion_playrate_frame['gameCount'] / total_games champion_playrate_frame['playrateDelta'] = champion_playrate_frame['playrate'] - expected_playrate champion_playrate_frame['playratePercent'] = pd.Series(["{0:.2f}%".format(val * 100) for val in champion_playrate_frame['playrate']],index = champion_playrate_frame.index) champion_playrate_frame['playrateDeltaPercent'] = pd.Series(["{0:.2f}%".format(val * 100) for val in champion_playrate_frame['playrateDelta']],index = champion_playrate_frame.index) print(champion_playrate_frame.sort_values(by='playratePercent', ascending=False, axis='index')[:10]) print(champion_playrate_frame.sort_values(by='playratePercent', axis='index')[:10])
{"/ruined_stats/cli.py": ["/ruined_stats/models.py"], "/aram_data_cleaning.py": ["/aram_single_summoner.py"], "/aram_personal_stats.py": ["/aram_single_summoner.py", "/data_dragon_handler.py"]}
15,982,598
dsPolar/RuinedStats
refs/heads/main
/aram_single_summoner.py
from riotwatcher import LolWatcher, ApiError import pandas as pd import numpy as np from api_key import key # Make a request to matchv4 api through riot watcher # Make several attempts to achieve result in case of timeouts def game_info_request(region, game_id, lol_watcher, num_retries=3): for num_attempt in range(num_retries): try: game_info = lol_watcher.match.by_id(region, game_id) return game_info except ApiError as err: if err.response.status_code == 400: print("Bad Request") raise elif num_attempt < (num_retries - 1): print("Failed to receive response") print(str(err.response.status_code)) else: raise # Get up to 100 matches in queue for user # Defaults to recency but begin_index can be used to navigate further back def get_hundred_matches(region, user, queue_id, lol_watcher, begin_index=0): try: last_hundred_aram = lol_watcher.match.matchlist_by_account(region, user['accountId'], queue=queue_id, begin_index=begin_index) except ApiError as err: raise summoner_game_frame = pd.DataFrame.from_dict(last_hundred_aram['matches']) summoner_game_frame = summoner_game_frame.drop(["platformId", "queue", ], axis=1) game_dict = {"matches":[]} for row in summoner_game_frame.itertuples(index=False, name="Games"): try: game = game_info_request(region, row.gameId, lol_watcher) game_dict['matches'].append(game) except ApiError as err: raise # Dataframe containing MatchDto objects game_frame = pd.DataFrame.from_dict(game_dict['matches']) game_frame.to_csv("csv/aram_games_begin_" + str(begin_index) + ".csv") return game_frame def get_all_arams(region, user, lol_watcher): begin_index = 0 not_done = True all_aram_dict = {"matches":[]} while not_done: try: hundred_aram = lol_watcher.match.matchlist_by_account(region, user['accountId'], queue="450", begin_index=begin_index) except ApiError as err: raise for game in hundred_aram['matches']: all_aram_dict['matches'].append(game) # If there are less than 100 games in the response then we assume we have reached the end of the history # While the response includes a total_games variable, the api requests to use this method instead if(len(hundred_aram['matches']) < 100): not_done = False else: begin_index += 100 all_aram_frame = pd.DataFrame.from_dict(all_aram_dict['matches']) # all_aram_frame should now contain all arams since queue id changed >patch 7.19 print(str(len(all_aram_frame.index)) + " Total Games Found") all_aram_frame = all_aram_frame.drop(['platformId', 'queue', 'timestamp'], axis=1) all_aram_frame.to_csv("csv/all_aram_games.csv") return all_aram_frame def load_arams(): df = pd.read_csv("csv/all_aram_games.csv") return df def concat_aram_game_info_frames(path): frames = [] for x in range(0,1500,100): frames.append(pd.read_csv(path + str(x) + ".csv")) total_frame = pd.concat(frames) total_frame.to_csv(path + "all.csv") return total_frame def get_full_game_info_for_frame(match_frame, region, lol_watcher): game_dict = {'matches':[]} for row in match_frame.itertuples(index=False, name='Games'): try: game = lol_watcher.match.by_id(region, row.gameId) game_dict['matches'].append(game) except ApiError as err: raise full_game_frame = pd.DataFrame.from_dict(game_dict['matches']) full_game_frame.to_csv("csv/all_aram_full_game_info.csv") return full_game_frame if __name__ == "__main__": lol_watcher = LolWatcher(key) region = "euw1" queue_id = "450" user = lol_watcher.summoner.by_name(region, "CatgirlViegoGF") #get_all_arams(region, user, lol_watcher) #match_frame = load_arams() #full_game_frame = get_full_game_info_for_frame(match_frame, region, lol_watcher) #for begin_index in range(1400,1500,100): # get_hundred_matches(region, user, queue_id, lol_watcher, begin_index=begin_index) #concat_aram_game_info_frames("csv/aram_games_begin_")
{"/ruined_stats/cli.py": ["/ruined_stats/models.py"], "/aram_data_cleaning.py": ["/aram_single_summoner.py"], "/aram_personal_stats.py": ["/aram_single_summoner.py", "/data_dragon_handler.py"]}
16,056,845
aamrani-dev/model_serving
refs/heads/main
/src/triton/triton_inference_engine.py
import sys import os MODEL_RESPOSITORY = os.getenv('MODEL_REPOSITORY') print(MODEL_RESPOSITORY) import sys sys.path.insert(0, os.getenv("MODEL_SERVING")) import numpy as np import time import importlib from src.ModelServing import ModelServing import tritonclient.http as httpclient from tritonclient.utils import InferenceServerException import argparse import asyncio import time import multiprocessing import pickle from functools import partial class Inference_engine(ModelServing): def __init__(self): ''' FLAGS: requiered: model_name: the name of the model to use for inference models_utils: input_tensor_name: name of the model input tensor out_tensor_name: name of the model output tensor output_shape : shape of the model output tensor url: the url where requests will be sent optional: please refer to the doc for the hole FLAGS options ''' super() self.get_flags() self.model_name = self.FLAGS.model_name sys.path.insert(0, MODEL_RESPOSITORY+'/'+self.model_name) self.models_utils = importlib.import_module(self.model_name) self.input_tensor_name = self.FLAGS.input_tensor_name self.output_tensor_name = self.FLAGS.output_tensor_name self.output_shape = int(self.FLAGS.output_shape) try: # We take into account the usage of an SSL communication (for security reasons) if self.FLAGS.ssl: self.triton_client = httpclient.InferenceServerClient( url=self.FLAGS.url, verbose=self.FLAGS.verbose, ssl=True, ssl_context_factory=gevent.ssl._create_unverified_context, insecure=True) else: self.triton_client = httpclient.InferenceServerClient( url=self.FLAGS.url, verbose=self.FLAGS.verbose) # self.setup() except Exception as e: print("channel creation failed: " + str(e)) sys.exit(1) def run_inference(self, data): try: inference_input = self.preprocessing(data) postprocessing_input = self.inference(inference_input) return self.postprocessing(postprocessing_input) except Exception as e: return [{"error": str(e)} for _ in data] def preprocessing(self, data): try: return self.models_utils.preprocessing(data) except Exception as e: print(e) def inference(self, data): ''' data: list of model inputs ''' data = data.astype(np.float32) inputs = [] try: inputs.append(httpclient.InferInput(self.input_tensor_name, list(data.shape), "FP32")) inputs[0].set_data_from_numpy(data, binary_data=False) except Exception as e: print(e) try: outputs = [] outputs.append(httpclient.InferRequestedOutput(self.output_tensor_name, binary_data=False)) results = self.triton_client.infer(self.model_name, inputs = inputs, outputs=outputs, query_params=None, headers=None ) results = results.get_response() outputs = results["outputs"] predictions = outputs[0]["data"] predictions = [predictions[i:i+self.output_shape] for i in range(0, len(predictions), self.output_shape)] return predictions except Exception as e: print(e) def postprocessing(self, predictions): return self.models_utils.postprocessing(predictions) def get_flags(self): # parse the arguments and return them as FLAGS parser = argparse.ArgumentParser() parser.add_argument('-v', '--verbose', action="store_true", required=False, default=False, help='Enable verbose output') parser.add_argument('-u', '--url', type=str, required=False, default='localhost:8000', help='Inference server URL. Default is localhost:8000.') parser.add_argument('-s', '--ssl', action="store_true", required=False, default=False, help='Enable encrypted link to the server using HTTPS') parser.add_argument( '-H', dest='http_headers', metavar="HTTP_HEADER", required=False, action='append', help='HTTP headers to add to inference server requests. ' + 'Format is -H"Header:Value".') parser.add_argument( '--request-compression-algorithm', type=str, required=False, default=None, help= 'The compression algorithm to be used when sending request body to server. Default is None.' ) parser.add_argument( '--response-compression-algorithm', type=str, required=False, default=None, help= 'The compression algorithm to be used when receiving response body from server. Default is None.' ) parser.add_argument( '--model_name', type=str, required=True, default=None, help= 'model name' ) parser.add_argument( '--data', type=str, required=False, default=None, help= 'Pickle file containing a list of inputs' ) parser.add_argument( '--b', type=str, required=False, default=4, help= 'batch size to use. Default: 4' ) parser.add_argument( '--input_tensor_name', type=str, required=True, default=None, help= 'input tensor name' ) parser.add_argument( '--output_tensor_name', type=str, required=True, default=None, help= 'output tensor name' ) parser.add_argument( '--save', type=str, required=False, default=None, help= 'Path where predictions will be saved' ) parser.add_argument( '--output_shape', type=str, required=True, default=None, help= 'Output tensor shape' ) self.FLAGS = parser.parse_args()
{"/src/triton/triton_inference_engine.py": ["/src/ModelServing.py"], "/tests/MNIST.py": ["/src/ray/ray_serving.py"], "/tests/test_mnist_tf.py": ["/src/triton/triton_inference_engine.py"], "/src/ray/ray_serving.py": ["/src/ModelServing.py"], "/src/ray/ray_inference_engine.py": ["/src/ModelServing.py"], "/tests/test_mnist_ray.py": ["/tests/MNIST.py", "/src/ray/ray_inference_engine.py"]}
16,056,846
aamrani-dev/model_serving
refs/heads/main
/src/ModelServing.py
import numpy as np from abc import ABC, abstractmethod import sys import os sys.path.insert(0, os.getenv("MODEL_SERVING")) import argparse import asyncio import time import multiprocessing import pickle from functools import partial class ModelServing(ABC): def __init__(self): self.FLAGS = None self.infer_engine = None @abstractmethod def run_inference(self, data): pass @abstractmethod def get_flags(self): pass def prepare_requests(self, data): ''' data: list of inputs returns a list of list of inputs after spliting the inputs using specified batch size ''' batch_size = int(self.FLAGS.b) requests_data = [data[i * batch_size:(i + 1) * batch_size] for i in range((len(data) + batch_size - 1) // batch_size )] return requests_data def load_data(self): ''' reads data from pickle file ''' infile = open(self.FLAGS.data, 'rb') data = pickle.load(infile) infile.close() return data def save_data(self, data): ''' saves predictions in the specified path in picke format ''' outfile = open(self.FLAGS.save, "wb") pickle.dump(data, outfile) outfile.close()
{"/src/triton/triton_inference_engine.py": ["/src/ModelServing.py"], "/tests/MNIST.py": ["/src/ray/ray_serving.py"], "/tests/test_mnist_tf.py": ["/src/triton/triton_inference_engine.py"], "/src/ray/ray_serving.py": ["/src/ModelServing.py"], "/src/ray/ray_inference_engine.py": ["/src/ModelServing.py"], "/tests/test_mnist_ray.py": ["/tests/MNIST.py", "/src/ray/ray_inference_engine.py"]}
16,056,847
aamrani-dev/model_serving
refs/heads/main
/tests/MNIST.py
import os import sys sys.path.insert(0, os.getenv("MODEL_SERVING")) from src.ray.ray_serving import Ray_serving import ray from ray import serve # import tensorflow.compat.v1 as tf # tf.disable_v2_behavior() import tensorflow as tf from cv2 import imread,imwrite from cv2 import cvtColor from cv2 import COLOR_BGR2RGB import cv2 import numpy as np import operator import time from starlette.responses import JSONResponse # import requests from scipy.ndimage import zoom class MNIST(Ray_serving): def __init__(self, args): self.model = tf.keras.models.load_model(args[0]) async def preprocessing(self, data): return data async def inference(self, data): return [self.model.predict(d) for d in data] async def postprocessing(self, predictions, requests=None): class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot'] res = [] for prediction in predictions: res.append(JSONResponse({"predictions": [class_names[np.argmax(pred)] for pred in prediction]})) return res async def extract_data(self, requests): inputs = [] try: for request in requests: data = await request.json() inputs.append(np.array(data["inputs"])) return inputs except Exception as e: return [{"error": str(e)}]
{"/src/triton/triton_inference_engine.py": ["/src/ModelServing.py"], "/tests/MNIST.py": ["/src/ray/ray_serving.py"], "/tests/test_mnist_tf.py": ["/src/triton/triton_inference_engine.py"], "/src/ray/ray_serving.py": ["/src/ModelServing.py"], "/src/ray/ray_inference_engine.py": ["/src/ModelServing.py"], "/tests/test_mnist_ray.py": ["/tests/MNIST.py", "/src/ray/ray_inference_engine.py"]}
16,056,848
aamrani-dev/model_serving
refs/heads/main
/tests/test_mnist_tf.py
# python3 test_triton.py --model_name POL_FoN --data syraco_data.pickle --input_tensor_name input_1 --output_tensor_name image_predictions/Softmax --save toto.pckl --output_shape 2 import sys import os sys.path.insert(0, os.getenv("TRITON")) from src.triton.triton_inference_engine import Inference_engine from tensorflow import keras import time if __name__ == '__main__': engine = Inference_engine() # engine.setup(FLAGS) fashion_mnist = keras.datasets.fashion_mnist (train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data() test_images = test_images.reshape(test_images.shape[0], 28, 28, 1) requests = engine.prepare_requests(test_images) start = time.time() predictions = [engine.run_inference(req) for req in requests] predictions = [item for batch in predictions for item in batch] end = time.time() print(end-start) for i in range(len(predictions)): print( "predicted: ", predictions[i] ,". Actual : " , test_labels[i])
{"/src/triton/triton_inference_engine.py": ["/src/ModelServing.py"], "/tests/MNIST.py": ["/src/ray/ray_serving.py"], "/tests/test_mnist_tf.py": ["/src/triton/triton_inference_engine.py"], "/src/ray/ray_serving.py": ["/src/ModelServing.py"], "/src/ray/ray_inference_engine.py": ["/src/ModelServing.py"], "/tests/test_mnist_ray.py": ["/tests/MNIST.py", "/src/ray/ray_inference_engine.py"]}
16,056,849
aamrani-dev/model_serving
refs/heads/main
/src/ray/ray_serving.py
from abc import ABC, abstractmethod import sys import os sys.path.insert(0, os.getenv("MODEL_SERVING")) from src.ModelServing import ModelServing import ray from ray import serve class Ray_serving(ABC): @abstractmethod async def preprocessing(self, data): pass @abstractmethod async def inference(self, data): pass @abstractmethod async def postprocessing(self, data): pass @abstractmethod async def extract_data(self, requests): pass @serve.batch(max_batch_size=8, batch_wait_timeout_s=1) async def handler(self, requests): try: data = await self.extract_data(requests) predictions = await self.inference(data) predictions = await self.postprocessing(predictions) return predictions except Exception as e: return [{"error": str(e)} for _ in requests] async def __call__(self, request): return await self.handler(request)
{"/src/triton/triton_inference_engine.py": ["/src/ModelServing.py"], "/tests/MNIST.py": ["/src/ray/ray_serving.py"], "/tests/test_mnist_tf.py": ["/src/triton/triton_inference_engine.py"], "/src/ray/ray_serving.py": ["/src/ModelServing.py"], "/src/ray/ray_inference_engine.py": ["/src/ModelServing.py"], "/tests/test_mnist_ray.py": ["/tests/MNIST.py", "/src/ray/ray_inference_engine.py"]}
16,056,850
aamrani-dev/model_serving
refs/heads/main
/src/ray/ray_inference_engine.py
import sys import os MODEL_RESPOSITORY = os.getenv('MODEL_REPOSITORY') print(MODEL_RESPOSITORY) import sys sys.path.insert(0, os.getenv("MODEL_SERVING")) import numpy as np import time import importlib from src.ModelServing import ModelServing import argparse import asyncio import time import multiprocessing import pickle from functools import partial import ray from ray import serve from concurrent.futures import ThreadPoolExecutor import requests class Inference_engine(ModelServing): def __init__(self, deployed_class, backend_name, *args): ''' FLAGS: requiered: model_name: the name of the model to use for inference models_utils: input_tensor_name: name of the model input tensor out_tensor_name: name of the model output tensor output_shape : shape of the model output tensor url: the url where requests will be sent optional: please refer to the doc for the hole FLAGS options ''' super() self.get_flags() self.backend_name = backend_name self.client = None try: if self.FLAGS.long_live: ray.init(address="auto", namespace="serve") self.client = serve.connect() else: ray.init() self.client = serve.start() try: backend_config = serve.BackendConfig(num_replicas=self.FLAGS.num_replicas) self.client.create_backend(backend_name, deployed_class, args, config=backend_config) self.client.create_endpoint(backend_name, backend=backend_name, route="/"+backend_name, methods=["POST"]) except Exception as e: print(e) print("A model with a same name is already registered. Be sure that there is no conflict") # self.handler = except Exception as e: print("Error: " + str(e)) sys.exit(1) def __send_request(self,inputs): r = requests.post("http://127.0.0.1:8000/"+self.backend_name, json=inputs) return r.text def run_inference(self, data): data = data[:int(3000/self.FLAGS.b)] with ThreadPoolExecutor(max_workers = 3) as executor: results = executor.map(self.__send_request, data) return [r for r in results] def get_flags(self): # parse the arguments and return them as FLAGS parser = argparse.ArgumentParser() parser.add_argument( '--long_live', type=bool, required=False, default=False, help='Launch Ray in long live version') parser.add_argument( '--b', type=int, required=False, default=4, help= 'batch size to use. Default: 4' ) parser.add_argument( '--num_replicas', type=int, required=False, default=4, help= 'number of replicas (workers)' ) self.FLAGS = parser.parse_args()
{"/src/triton/triton_inference_engine.py": ["/src/ModelServing.py"], "/tests/MNIST.py": ["/src/ray/ray_serving.py"], "/tests/test_mnist_tf.py": ["/src/triton/triton_inference_engine.py"], "/src/ray/ray_serving.py": ["/src/ModelServing.py"], "/src/ray/ray_inference_engine.py": ["/src/ModelServing.py"], "/tests/test_mnist_ray.py": ["/tests/MNIST.py", "/src/ray/ray_inference_engine.py"]}
16,056,851
aamrani-dev/model_serving
refs/heads/main
/tests/test_mnist_ray.py
import sys import os sys.path.insert(0, os.getenv("MODEL_SERVING")) import requests from tensorflow import keras from tests.MNIST import MNIST from src.ray.ray_inference_engine import Inference_engine import ray from ray import serve import time import requests PATH_TO_MODEL = "/data/appli_PITSI/users/amrani/model_serving/tests/model_repository/mnist/1/model.savedmodel" MODEL_NAME = "MNIST" if __name__ == '__main__': engine = Inference_engine(MNIST, MODEL_NAME, PATH_TO_MODEL) fashion_mnist = keras.datasets.fashion_mnist (train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data() test_images = test_images.reshape(test_images.shape[0], 28, 28, 1) req = engine.prepare_requests(test_images) req = [{"inputs": r.tolist()} for r in req] start = time.time() predictions = engine.run_inference(req) print(time.time()-start) print(len(predictions))
{"/src/triton/triton_inference_engine.py": ["/src/ModelServing.py"], "/tests/MNIST.py": ["/src/ray/ray_serving.py"], "/tests/test_mnist_tf.py": ["/src/triton/triton_inference_engine.py"], "/src/ray/ray_serving.py": ["/src/ModelServing.py"], "/src/ray/ray_inference_engine.py": ["/src/ModelServing.py"], "/tests/test_mnist_ray.py": ["/tests/MNIST.py", "/src/ray/ray_inference_engine.py"]}
16,056,852
aamrani-dev/model_serving
refs/heads/main
/tests/model_repository/mnist/mnist.py
import numpy as np def preprocessing(data): return data def postprocessing(predictions): class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot'] res = [np.argmax(pred) for pred in predictions] return res
{"/src/triton/triton_inference_engine.py": ["/src/ModelServing.py"], "/tests/MNIST.py": ["/src/ray/ray_serving.py"], "/tests/test_mnist_tf.py": ["/src/triton/triton_inference_engine.py"], "/src/ray/ray_serving.py": ["/src/ModelServing.py"], "/src/ray/ray_inference_engine.py": ["/src/ModelServing.py"], "/tests/test_mnist_ray.py": ["/tests/MNIST.py", "/src/ray/ray_inference_engine.py"]}
16,073,810
kutaslab/mkpy
refs/heads/master
/setup.py
# mkpy is pinned to python 3.6 until other packages support 3.7 # commented out as distutils fades into oblivion # from distutils.core import setup # from distutils.extension import Extension from Cython.Distutils import build_ext from Cython.Build import cythonize from setuptools import find_packages, setup, Extension import numpy as np from pathlib import Path import re from mkpy import get_ver __version__ = get_ver() # enforce conda meta.yaml semantic version == package __init__ jinja_version = f'{{% set version = "{__version__}" %}}' meta_yaml_f = "./conda/meta.yaml" with open(meta_yaml_f) as f: conda_ver = re.match(r"^" + jinja_version, f.read()) if not conda_ver: fail_msg = ( "conda/meta.yaml must start with a jinja variable line exactly" f"like this: {jinja_version}" ) raise Exception(fail_msg) extensions = [ Extension( "mkpy._mkh5", ["mkpy/_mkh5.pyx"], include_dirs=[np.get_include()] ) ] setup( name="mkpy", version=__version__, description="kutaslab eeg data utilities", author="Thomas P. Urbach, Andrey Portnoy, forked from Nathaniel Smith", author_email="turbach@ucsd.edu", url="http://kutaslab.ucsd.edu/people/urbach", packages=find_packages(exclude=["tests"]), # ['mkh5.core', 'mkh5.utils'], scripts=["bin/pygarv"], cmdclass={"build_ext": build_ext}, ext_modules=cythonize(extensions), )
{"/mkpy/mkio.py": ["/mkpy/__init__.py"], "/mkpy/docs/examples/mkh5_basics.py": ["/mkpy/__init__.py"], "/tests/test_io_mkh5eeglab.py": ["/tests/config.py", "/mkpy/mkh5.py"], "/mkpy/docs/examples/mkh5mne/mne_quickstart.py": ["/mkpy/__init__.py"], "/mkpy/io/mkh5mne.py": ["/mkpy/mkh5.py", "/mkpy/__init__.py"], "/mkpy/docs/examples/mkh5mne/from_mkh5.py": ["/mkpy/__init__.py"], "/mkpy/mkh5.py": ["/mkpy/__init__.py", "/mkpy/codetagger.py"], "/mkpy/docs/examples/mkh5mne/how_it_works.py": ["/mkpy/__init__.py"], "/tests/test_bugs.py": ["/tests/config.py", "/mkpy/__init__.py"], "/tests/test_mkio.py": ["/tests/config.py", "/mkpy/__init__.py"], "/tests/test_pyarf.py": ["/tests/config.py", "/mkpy/__init__.py", "/mkpy/pygarv.py"], "/setup.py": ["/mkpy/__init__.py"], "/tests/test_mkh5.py": ["/tests/config.py", "/mkpy/__init__.py"], "/tests/test_epochs.py": ["/tests/config.py", "/mkpy/__init__.py"], "/mkpy/pygarv.py": ["/mkpy/__init__.py"], "/mkpy/docs/examples/mkh5mne_basics.py": ["/mkpy/__init__.py"], "/mkpy/docs/examples/mkh5/mkh5_quickstart.py": ["/mkpy/__init__.py"], "/tests/config.py": ["/mkpy/__init__.py"], "/tests/test_header.py": ["/tests/config.py", "/mkpy/mkh5.py"], "/tests/test_io_mkh5mne.py": ["/mkpy/__init__.py", "/tests/config.py", "/mkpy/mkh5.py", "/mkpy/io/mkh5mne.py"], "/mkpy/dpath/dpath_tests/test_path_paths.py": ["/mkpy/dpath/exceptions.py"], "/mkpy/docs/examples/mkh5eeglab/eeglab_quickstart.py": ["/mkpy/__init__.py"], "/tests/test_yhdr.py": ["/mkpy/__init__.py"], "/tests/test_codemap.py": ["/tests/config.py", "/mkpy/__init__.py", "/mkpy/mkh5.py"], "/mkpy/mkh5viewer.py": ["/mkpy/__init__.py"], "/mkpy/docs/examples/mkh5/append_cals.py": ["/mkpy/__init__.py"], "/tests/test_pygarv.py": ["/mkpy/__init__.py", "/mkpy/pygarv.py", "/tests/config.py"], "/tests/test_h5tools.py": ["/tests/config.py", "/mkpy/__init__.py"], "/tests/test_mkpy.py": ["/mkpy/__init__.py"], "/mkpy/events.py": ["/mkpy/__init__.py"], "/tests/test_event_tables.py": ["/tests/config.py", "/mkpy/__init__.py"]}
16,107,159
daiki-skm/accuracy
refs/heads/master
/getFromFiles.py
import nltk from nltk import sent_tokenize from nltk.tokenize import word_tokenize def getProcessedContentsByLineFromFiles(filep, filen): with open(filep, encoding="utf-8_sig") as fp: linesp = fp.readlines() lineContentsp = [] for line in linesp: sentencesp = sent_tokenize(line.lower()) sep_sentencesp = [] for sentence in sentencesp: tagged_token = word_tokenize(sentence) tagged_words = nltk.pos_tag(tagged_token) sep_sentence = " ".join(w for (w, t) in tagged_words if t.startswith('JJ') or t.startswith('NN') or t.startswith('VB') or t.startswith('RB')) sep_sentencesp.append(sep_sentence) lineContentsp.append(" ".join(sep_sentencesp)) fp.close() with open(filen, encoding="utf-8_sig") as fn: linesn = fn.readlines() lineContentsn = [] for line in linesn: sentencesn = sent_tokenize(line.lower()) sep_sentencesn = [] for sentence in sentencesn: tagged_token = word_tokenize(sentence) tagged_words = nltk.pos_tag(tagged_token) sep_sentence = " ".join(w for (w, t) in tagged_words if t.startswith('JJ') or t.startswith('NN') or t.startswith('VB') or t.startswith('RB')) sep_sentencesn.append(sep_sentence) lineContentsn.append(" ".join(sep_sentencesn)) fn.close() input_documents = lineContentsp + lineContentsn return input_documents, lineContentsp, lineContentsn
{"/main.py": ["/getFromFiles.py", "/build.py", "/caltfidf.py", "/getidxtfidf.py", "/createData.py", "/analysis.py"]}
16,107,160
daiki-skm/accuracy
refs/heads/master
/analysis.py
from sklearn.svm import SVC from sklearn.metrics import accuracy_score def analysis(train, test, width): print('Modeling and Analysis...') x_train = [x[1:width + 1] for x in train] x_test = [x[1:width + 1] for x in test] y_train = [y[0] for y in train] y_test = [y[0] for y in test] # from sklearn.model_selection import train_test_split # X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0) # Create Model by SVM print("Modeling by SVM") model = SVC(kernel='linear', random_state=None) model.fit(x_train, y_train) # Testing... preout = model.predict(x_test) print('Using test data set, Accuracy = ', accuracy_score(y_test, preout))
{"/main.py": ["/getFromFiles.py", "/build.py", "/caltfidf.py", "/getidxtfidf.py", "/createData.py", "/analysis.py"]}
16,195,966
odenypeter/3dImagemodel
refs/heads/main
/imagemodelapp/admin.py
from django.contrib import admin from .models import * """ Register models to admin console To see the admin console run: python manage.py createsuperuser then follow the prompts and login at http://localhost:8000/admin """ @admin.register(GeneratedFile) class GeneratedFileAdmin(admin.ModelAdmin): list_display = ('file_name', 'file',) @admin.register(Image) class GeneratedFileAdmin(admin.ModelAdmin): list_display = ('generated_file', 'image',) list_filter = ('generated_file',)
{"/imagemodelapp/admin.py": ["/imagemodelapp/models.py"], "/imagemodelapp/views.py": ["/imagemodelapp/models.py"]}
16,195,967
odenypeter/3dImagemodel
refs/heads/main
/imagemodelapp/models.py
from django.db import models class GeneratedFile(models.Model): """ Model to hold information about the created 3D model """ file_name = models.CharField(null=True, blank=True, max_length=250) file = models.FileField(upload_to='final_models', null=True, blank=True) def __str__(self): return f'{self.file_name or self. id}' class Image(models.Model): """ Model for the individual images for building a 3D model """ generated_file = models.ForeignKey(GeneratedFile, related_name='model_images', on_delete=models.CASCADE) image = models.ImageField(upload_to='images') def __str__(self): return f'{self.generated_file or self.id}'
{"/imagemodelapp/admin.py": ["/imagemodelapp/models.py"], "/imagemodelapp/views.py": ["/imagemodelapp/models.py"]}
16,195,968
odenypeter/3dImagemodel
refs/heads/main
/imagemodelapp/migrations/0001_initial.py
# Generated by Django 3.1.7 on 2021-03-21 09:23 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='GeneratedFile', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('file_name', models.CharField(blank=True, max_length=250, null=True)), ('file', models.FileField(blank=True, null=True, upload_to='final_models')), ], ), migrations.CreateModel( name='Image', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('image', models.ImageField(upload_to='images')), ('generated_file', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='imagemodelapp.generatedfile')), ], ), ]
{"/imagemodelapp/admin.py": ["/imagemodelapp/models.py"], "/imagemodelapp/views.py": ["/imagemodelapp/models.py"]}
16,195,969
odenypeter/3dImagemodel
refs/heads/main
/imagemodelapp/utils/epipolar_geometry.py
import numpy as np from numpy.linalg import inv from numpy.linalg import svd from numpy.linalg import eig from scipy.optimize import leastsq, least_squares, fmin class EpipolarGeometry: ''' Class that implements basic epipolar geometry operations ''' def fundamental_matrix(self, view1_feat2D, view2_feat2D, optimize): ''' Method to computes the fundamental matrix betwen two images. Args: view1_feat2D: 2D feature coordinates in view 1 view2_feat2D: 2D feature coordinates in view 2 optimize: optimize the F estimation using non-linear least squares Returns: the fundamendal matrix F ''' number_of_features = view1_feat2D.shape[1] # convert to homogeneous coordinates view1_feat2D = np.vstack((view1_feat2D, np.ones(number_of_features))) view2_feat2D = np.vstack((view2_feat2D, np.ones(number_of_features))) # create a homogeneous system Af=0 (f : elements of fundamental matrix), using mFm'=0 A = np.zeros((number_of_features, 9)) A[:, 0] = np.transpose(view2_feat2D[0, :]) * (view1_feat2D[0, :]) A[:, 1] = np.transpose(view2_feat2D[0, :]) * (view1_feat2D[1, :]) A[:, 2] = np.transpose(view2_feat2D[0, :]) A[:, 3] = np.transpose(view1_feat2D[0, :]) * (view1_feat2D[1, :]) A[:, 4] = np.transpose(view2_feat2D[1, :]) * (view1_feat2D[1, :]) A[:, 5] = np.transpose(view2_feat2D[1, :]) A[:, 6] = np.transpose(view1_feat2D[0, :]) A[:, 7] = np.transpose(view1_feat2D[1, :]) A[:, 8] = np.ones(number_of_features) # use the eigenvector that corresponds to the smallest eigenvalue as initial estimate for F. U, s, Vh = svd(A) V = np.transpose(Vh) # fundamental matrix is now the eigenvector corresponding to the smallest eigen value. F = np.reshape(V[:, 8], (3, 3)) # make sure that fundamental matrix is of rank 2 U, s, V = svd(F); s[2] = 0 S = np.diag(s) F = np.dot(U, np.dot(S, V)) if optimize == 1: # Optimize initial estimate using the algebraic error f = np.append(np.concatenate((F[0, :], F[1, :]), axis=0), F[2, 0]) / F[2, 2] result = least_squares(self.fundamental_matrix_error, f, args=(view1_feat2D[0:2, :], view2_feat2D[0:2, :])) f = result.x F = np.asarray([np.transpose(f[0:3]), np.transpose(f[3:6]), [f[6], -( -f[0] * f[4] + f[6] * f[2] * f[4] + f[3] * f[1] - f[6] * f[1] * f[5]) / ( -f[3] * f[2] + f[0] * f[5]), 1]]); F = F / sum(sum(F)) * 9; return F def fundamental_matrix_error(self, f, view1_feat2D, view2_feat2D): ''' Method to compute the fundamental matrix error based on the epipolar constraint (mFm'=0) Args: f : a vector with the elements of the fundamental matrix view1_feat2D: 2D feature coordinates in view 1 view2_feat2D: 2D feature coordinates in view 2 Returns: the error based on mFm'=0 ''' F = np.asarray([np.transpose(f[0:3]), np.transpose(f[3:6]), [f[6], -( -f[0] * f[4] + f[6] * f[2] * f[4] + f[3] * f[1] - f[6] * f[1] * f[5]) / ( -f[3] * f[2] + f[0] * f[5]), 1]]); number_of_features = view1_feat2D.shape[1] # convert to homogeneous coordinates view1_feat2D = np.vstack((view1_feat2D, np.ones(number_of_features))) view2_feat2D = np.vstack((view2_feat2D, np.ones(number_of_features))) # compute error error = np.zeros((number_of_features, 1)) for i in range(0, number_of_features): error[i] = np.dot(view2_feat2D[:, i], np.dot(F, np.transpose(view1_feat2D[:, i]))); return error.flatten() def get_epipole(self, F): ''' Method to return the epipole from the fundamental matrix Args: F: the fundamental matrix Retruns: the epipole ''' u, v = eig(F) dd = np.square(u); min_index = np.argmin(np.abs(dd)) # SOS: These are complex numbers, so compare their modulus epipole = v[:, min_index] epipole = epipole / epipole[2] return epipole.real def compute_homography(self, epipole, F): ''' Method that computes the homograhpy [epipole]x[F] Args: epipole: the epipole F : the fundamental matrix Returns: the homography H ''' e_12 = np.asarray([[0, -epipole[2], epipole[1]], [epipole[2], 0, -epipole[0]], [-epipole[1], epipole[0], 0]]); H = np.dot(e_12, F) H = H * np.sign(np.trace(H)) return H def triangulate_points(self, view1_feat2D, view2_feat2D, P1, P2): ''' Method that triangulates using two projection matrices, and the normalized 2D features coordinates. Args: view1_feat2D: 2D feature coordinates in view 1 view2_feat2D: 2D feature coordinates in view 2 P1: projection matrix for view 1 P2: projection matrix for view 2 Returns: the 3D points ''' A = np.zeros((4, 4)); A[0, :] = P1[2, :] * view1_feat2D[0] - P1[0, :] A[1, :] = P1[2, :] * view1_feat2D[1] - P1[1, :] A[2, :] = P2[2, :] * view2_feat2D[0] - P2[0, :] A[3, :] = P2[2, :] * view2_feat2D[1] - P2[1, :] U, s, Vh = svd(A) V = np.transpose(Vh) feat3D = V[:, V.shape[0] - 1] feat3D = feat3D / feat3D[3] return feat3D def compute_L_R(self, view_feat2D, epipole): ''' Utility method used in polynomial triangulation ''' L = np.eye(3); L[0:2, 2] = -view_feat2D; th = np.arctan(-(epipole[1] - epipole[2] * view_feat2D[1]) / (epipole[0] - epipole[2] * view_feat2D[0])); R = np.eye(3) R[0, 0] = np.cos(th) R[1, 1] = np.cos(th) R[0, 1] = -np.sin(th) R[1, 0] = np.sin(th) return L, R def polynomial_triangulation(self, feat1, feat2, epipole_1, epipole_2, F, P1, P2): ''' Method to perform 'polynomial' triangulation, as suggested in R. Hartley and P. Sturm, "Triangulation", Computer Vision and Image Understanding, 68(2):146-157, 1997 The method searches for the epipolar line which fits best to both feature points, and then project both points on tis line. Triangulation is then performed on these new points. (This now happens through SVD since the error will be zero) Args: feat1: 2D feature coordinates in view 1 feat2: 2D feature coordinates in view 2 epipole_1: the epipole of view 1 epipole_2: the epipole of view 2 F: the fundamental matrix P1: projection matrix for view 1 P2: projection matrix for view 2 Returns: the 3D points ''' L1, R1 = self.compute_L_R(feat1, epipole_1) L2, R2 = self.compute_L_R(feat2, epipole_2) F1 = R2.dot(np.transpose(inv(L2))).dot(F).dot(inv(L1)).dot(np.transpose(R1)) a = F1[1, 1]; b = F1[1, 2]; c = F1[2, 1]; d = F1[2, 2]; f1 = -F1[1, 0] / b; f2 = -F1[0, 1] / c; p = np.zeros(7); p[0] = -2 * np.power(f1, 4) * np.power(a, 2) * c * d + 2 * np.power(f1, 4) * a * np.power(c, 2) * b; p[1] = 2 * np.power(a, 4) + 2 * np.power(f2, 4) * np.power(c, 4) - 2 * np.power(f1, 4) * np.power(a, 2) * np.power( d, 2) + 2 * np.power(f1, 4) * np.power(b, 2) * np.power(c, 2) + 4 * np.power(a, 2) * np.power(f2, 2) * np.power( c, 2); p[2] = 8 * np.power(f2, 4) * d * np.power(c, 3) + 8 * b * np.power(a, 3) + 8 * b * a * np.power(f2, 2) * np.power(c, 2) + 8 * np.power( f2, 2) * d * c * np.power(a, 2) - 4 * np.power(f1, 2) * np.power(a, 2) * c * d + 4 * np.power(f1, 2) * a * np.power( c, 2) * b - 2 * np.power(f1, 4) * b * np.power(d, 2) * a + 2 * np.power(f1, 4) * np.power(b, 2) * d * c; p[3] = -4 * np.power(f1, 2) * np.power(a, 2) * np.power(d, 2) + 4 * np.power(f1, 2) * np.power(b, 2) * np.power( c, 2) + 4 * np.power(b, 2) * np.power(f2, 2) * np.power(c, 2) + 16 * b * a * np.power(f2, 2) * d * c + 12 * np.power( f2, 4) * np.power(d, 2) * np.power(c, 2) + 12 * np.power(b, 2) * np.power(a, 2) + 4 * np.power(f2, 2) * np.power( d, 2) * np.power(a, 2); p[4] = 8 * np.power(f2, 4) * np.power(d, 3) * c + 8 * np.power(b, 2) * np.power(f2, 2) * d * c + 8 * np.power( f2, 2) * np.power(d, 2) * b * a - 4 * np.power(f1, 2) * b * np.power(d, 2) * a + 4 * np.power(f1, 2) * np.power( b, 2) * d * c + 2 * a * np.power(c, 2) * b + 8 * np.power(b, 3) * a - 2 * np.power(a, 2) * c * d; p[5] = 4 * np.power(b, 2) * np.power(f2, 2) * np.power(d, 2) + 2 * np.power(f2, 4) * np.power(d, 4) + 2 * np.power( b, 2) * np.power(c, 2) - 2 * np.power(a, 2) * np.power(d, 2) + 2 * np.power(b, 4); p[6] = -2 * b * d * (a * d - b * c); r = np.roots(p) y = np.polyval(p, r) aa = max(y) i = 0; ii = 0; for i in range(0, 6): if ((np.imag(r[i]) == 0) and (abs(y[i]) < aa)): aa = abs(y[i]); ii = i; i = i + 1; t = r[ii].real; # get the refined feature coordinates u = np.asarray([f1, 1 / t, 1]); v = np.asarray([-1 / f1, t, 1]); s = inv([[u[0], -v[0]], [u[1], -v[1]]]).dot([1 / f1, 0]) refined_feat1 = np.asarray([u[0] * s[0], u[1] * s[0], 1]) u = F1.dot([0, t, 1]); u = u / u[2]; v = [1 / u[0], -1 / u[1], 1]; s = inv([[u[0], -v[0]], [u[1], -v[1]]]).dot([1 / f2, 0]); refined_feat2 = np.asarray([u[0] * s[0], u[1] * s[0], 1]); refined_feat1 = inv(L1).dot(np.transpose(R1)).dot(refined_feat1); refined_feat2 = inv(L2).dot(np.transpose(R2)).dot(refined_feat2); # normalize to get homogeneous coordinates refined_feat1 = refined_feat1 / refined_feat1[2] refined_feat2 = refined_feat2 / refined_feat2[2] return self.triangulate_points(refined_feat1, refined_feat2, P1, P2); def compute_reprojection_error_point(self, P, point3D, view_feat2D): ''' Method to compute the reprojection error of a 3D point on a particular view Args: P: the projection matrix of the view point3D: the 3D point coordinates view_feat2D: 2D feature coordinates for that point in that view Returns: the reprojection error ''' return np.power((P[0:2, :].dot(point3D) / P[2, :].dot(point3D) - view_feat2D), 2) def compute_reprojection_error_points(self, P, feat3D, view_feat2D): ''' Method that returns the reprojection error for a cloud of 3D points. Args: P: the projection matrix of the view feat3D: the 3D point cloud coordinates view_feat2D: 2D feature coordinates for all the 3D points in that view Returns: the reprojection error ''' reproj_feature = P.dot(np.transpose(feat3D)) reproj_feature = reproj_feature / reproj_feature[2, :] error = sum(sum(np.power((view_feat2D - reproj_feature[0:2, :]), 2))) return error def refine_projection_matrix(self, VV, feat3D, view_feat2D): ''' Utility method, used to optimize the projection matrix estimation Args: VV: vector containing elements of the projection matrix of the i-th view feat3D: 3D point cloud coordinates view_feat2D: 2D feature coordinate for all the feature points in the i-th view ''' # construct the projection matrix P = np.zeros(shape=[3, 4]); P[0, :] = VV[0:4] P[1, :] = VV[4:8] P[2, :] = np.append(np.append(VV[8:10], 1), VV[10]) return self.compute_reprojection_error_points(P, feat3D, view_feat2D) def overall_reprojection_error(self, X, feat2d): ''' Method to compute the overall reprojection error by reprojecting the 3D model back to each images. This is used in bundle adustment to optimize the structure (i.e. 3D points), and the motion (i.e. projection matrices) The Args: X: vector containing the projection matrices and the 3D coordinates (all concatenated in one vector) feat2D: 2D feature coordinates for all the features for all views Returns: the overall reprojection error ''' number_of_features = feat2d.shape[2] sequence_length = feat2d.shape[0] error_vector = []; for img_number in range(0, sequence_length): for feat_id in range(0, number_of_features): img_feat = feat2d[img_number, :, feat_id] a = np.transpose(X[(0 + img_number * 11):(4 + img_number * 11)]) a1 = np.transpose(X[(4 + img_number * 11):(8 + img_number * 11)]) b = np.append(X[(0 + sequence_length * 11 + feat_id * 3):(3 + sequence_length * 11 + feat_id * 3)], 1) c = np.append(X[8 + img_number * 11:10 + img_number * 11], 1) c = np.append(c, X[10 + img_number * 11]); c = np.transpose(c); error_x = img_feat[0] - a.dot(b) / c.dot(b) error_y = img_feat[1] - a1.dot(b) / c.dot(b) error_vector.append(error_x) error_vector.append(error_y) return np.asarray(error_vector)
{"/imagemodelapp/admin.py": ["/imagemodelapp/models.py"], "/imagemodelapp/views.py": ["/imagemodelapp/models.py"]}
16,195,970
odenypeter/3dImagemodel
refs/heads/main
/imagemodelapp/views.py
from django.conf import settings from django.shortcuts import render from .models import (Image, GeneratedFile) from .utils.uncalibrated_rec import (construct_3d_model,) from os.path import join def index(request): """ Renders the index.html :param request: :return: """ # Handle for posting if request.method == 'POST': data = request.POST files = request.FILES file_name = data.get('file_name', None) if file_name: # save the information about the model to be created generated_model = GeneratedFile.objects.create(file_name=file_name) # save the individual images if generated_model: images = files.getlist('images') # save the individual images if images: for image in images: saved_image = Image(generated_file=generated_model, image=image) saved_image.save() # Construct the 3D model construct_3d_model(generated_model) # render available 3D models for listing on the table return render(request, 'index.html', { 'generated_files': GeneratedFile.objects.prefetch_related('model_images').all() })
{"/imagemodelapp/admin.py": ["/imagemodelapp/models.py"], "/imagemodelapp/views.py": ["/imagemodelapp/models.py"]}
16,195,971
odenypeter/3dImagemodel
refs/heads/main
/imagemodelapp/utils/model.py
from numpy.linalg import inv from numpy.linalg import svd from numpy.linalg import eig from numpy.linalg import det from scipy.optimize import leastsq, least_squares, fmin import pandas as pd import numpy as np from stl import mesh from scipy.spatial import Delaunay class RecModel: """ Class to hold all the result of a reconstruction """ def __init__(self): self._P = 0 # projection matrices for each view self._R = 0 # rotation matrices for each view self._t = 0 # translation vectors for each view self._points3D = 0 # 3D points in metric space self._Tm = 0 # Transformation matrix from projective to metric @property def P(self): return self._P @P.setter def P(self, val): # self._R, self._t = self.extract_rotation_translation(P) self._P = val @property def points3D(self): return self._points3D @points3D.setter def points3D(self, val): self._points3D = val # def extract_rotation_translation(self, P): # ''' # Method to extract the rotation matrices and translation vectors from the projection matrices # ''' # sequence_length = P.shape[2] # R = np.zeros((3, 3, self._sequence_length)) # t = np.zeros((3, self._sequence_length)) # print('Sequence:::::', K) # # for i in range(1, self._sequence_length): # PP = inv(K[:, :, i]).dot(P[:, :, i]); # R[:, :, i] = np.transpose(PP[0:3, 0:3]) # t[:, i] = -inv(np.transpose(R[:, :, i])).dot(PP[0:3, 3]) # return R, t def export_stl_file(self, filename): """ Method that generates an .stl file with the generated model """ vertices = self.points3D[:, 0:3]; faces = Delaunay(vertices[:, 0:2], incremental=1) faces = faces.simplices wireframe = mesh.Mesh(np.zeros(faces.shape[0], dtype=mesh.Mesh.dtype)) for i, f in enumerate(faces): for j in range(3): wireframe.vectors[i][j] = vertices[f[j], :] wireframe.save(filename)
{"/imagemodelapp/admin.py": ["/imagemodelapp/models.py"], "/imagemodelapp/views.py": ["/imagemodelapp/models.py"]}
16,203,675
GauBen/perfect-aim
refs/heads/main
/players/yourplayer.py
""" Stratégie de l'équipe Les Meilleurs. <Ajoutez ici une notice de copyright> """ from game import Action, Game, Player class BestPlayer(Player): """Stratégie de l'équipe Les Meilleurs.""" NAME = "n - Les Meilleurs" def play(self, game: Game) -> Action: """Choisit la meilleure action possible dans la situation donnée en paramètre.""" return Action.WAIT
{"/players/randomplayer.py": ["/game.py"], "/main.py": ["/gui.py"], "/entities.py": ["/gamegrid.py", "/game.py"], "/players/zidane.py": ["/entities.py", "/game.py"], "/game.py": ["/entities.py", "/gamegrid.py"], "/gui.py": ["/entities.py", "/game.py", "/players/__init__.py", "/gamegrid.py"], "/players/anousleflouz.py": ["/game.py"], "/players/lepirejoueur.py": ["/entities.py", "/gamegrid.py", "/game.py"], "/players/__init__.py": ["/game.py"], "/players/gangsterino.py": ["/game.py", "/entities.py"], "/players/yourplayer.py": ["/game.py"]}
16,231,483
systemonachip/systemonachip
refs/heads/main
/systemonachip/test/test_periph_timer.py
#nmigen: UnusedElaboratable=no import unittest from nmigen import * from nmigen.back.pysim import * from ._wishbone import * from ..periph.timer import TimerPeripheral def simulation_test(dut, process): with Simulator(dut, vcd_file=open("test.vcd", "w")) as sim: sim.add_clock(1e-6) sim.add_sync_process(process) sim.run() reload_addr = 0x00 >> 2 en_addr = 0x04 >> 2 ctr_addr = 0x08 >> 2 ev_status_addr = 0x10 >> 2 ev_pending_addr = 0x14 >> 2 ev_enable_addr = 0x18 >> 2 class TimerPeripheralTestCase(unittest.TestCase): def test_invalid_width(self): with self.assertRaisesRegex(ValueError, r"Counter width must be a non-negative integer, not 'foo'"): dut = TimerPeripheral(width="foo") def test_invalid_width_32(self): with self.assertRaisesRegex(ValueError, r"Counter width cannot be greater than 32 \(was: 33\)"): dut = TimerPeripheral(width=33) def test_simple(self): dut = TimerPeripheral(width=4) def process(): yield from wb_write(dut.bus, addr=ctr_addr, data=15, sel=0xf) yield ctr = yield from wb_read(dut.bus, addr=ctr_addr, sel=0xf) self.assertEqual(ctr, 15) yield yield from wb_write(dut.bus, addr=en_addr, data=1, sel=0xf) yield for i in range(16): yield ctr = yield from wb_read(dut.bus, addr=ctr_addr, sel=0xf) self.assertEqual(ctr, 0) simulation_test(dut, process) def test_irq(self): dut = TimerPeripheral(width=4) def process(): yield from wb_write(dut.bus, addr=ctr_addr, data=15, sel=0xf) yield yield from wb_write(dut.bus, addr=ev_enable_addr, data=1, sel=0xf) yield yield from wb_write(dut.bus, addr=en_addr, data=1, sel=0xf) yield done = False for i in range(16): if (yield dut.irq): self.assertFalse(done) done = True ctr = yield from wb_read(dut.bus, addr=ctr_addr, sel=0xf) self.assertEqual(ctr, 0) yield self.assertTrue(done) simulation_test(dut, process) def test_reload(self): dut = TimerPeripheral(width=4) def process(): yield from wb_write(dut.bus, addr=reload_addr, data=15, sel=0xf) yield yield from wb_write(dut.bus, addr=ctr_addr, data=15, sel=0xf) yield yield from wb_write(dut.bus, addr=ev_enable_addr, data=1, sel=0xf) yield yield from wb_write(dut.bus, addr=en_addr, data=1, sel=0xf) yield irqs = 0 for i in range(32): if (yield dut.irq): irqs += 1 yield from wb_write(dut.bus, addr=ev_pending_addr, data=1, sel=0xf) yield # not an accurate measure, since each call to wb_write() adds a few cycles, # but we can at least check that reloading the timer works. self.assertEqual(irqs, 2) simulation_test(dut, process)
{"/systemonachip/test/test_periph_timer.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/test/test_periph_base.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/register/readwrite.py": ["/systemonachip/register/base.py"], "/systemonachip/peripheral/timer.py": ["/systemonachip/peripheral/__init__.py", "/systemonachip/event/__init__.py", "/systemonachip/register/__init__.py"], "/systemonachip/soc/cpu.py": ["/systemonachip/soc/base.py", "/systemonachip/cpu/__init__.py", "/systemonachip/peripheral/memory.py", "/systemonachip/peripheral/timer.py"], "/systemonachip/peripheral/base.py": ["/systemonachip/register/__init__.py", "/systemonachip/event/__init__.py"], "/systemonachip/register/__init__.py": ["/systemonachip/register/static.py", "/systemonachip/register/readwrite.py", "/systemonachip/register/config.py", "/systemonachip/register/variable.py", "/systemonachip/register/event.py"], "/systemonachip/register/event.py": ["/systemonachip/register/base.py"], "/systemonachip/soc/base.py": ["/systemonachip/peripheral/__init__.py"], "/examples/basic.py": ["/systemonachip/bus/decoder.py", "/systemonachip/cpu/minerva.py", "/systemonachip/peripheral/memory.py", "/systemonachip/peripheral/timer.py", "/systemonachip/soc/cpu.py"], "/systemonachip/peripheral/__init__.py": ["/systemonachip/peripheral/base.py"], "/systemonachip/test/test_periph_sram.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/test/test_periph_serial.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/bus/__init__.py": ["/systemonachip/bus/decoder.py"], "/systemonachip/cpu/minerva.py": ["/systemonachip/cpu/__init__.py"]}
16,231,484
systemonachip/systemonachip
refs/heads/main
/systemonachip/test/test_periph_base.py
# nmigen: UnusedElaboratable=no import unittest from nmigen import * from nmigen.back.pysim import * from ._wishbone import * from ..periph.base import Peripheral, CSRBank, PeripheralBridge def simulation_test(dut, process): with Simulator(dut, vcd_file=open("test.vcd", "w")) as sim: sim.add_clock(1e-6) sim.add_sync_process(process) sim.run() class PeripheralTestCase(unittest.TestCase): def test_name(self): class Wrapper(Peripheral): def __init__(self): super().__init__() periph_0 = Wrapper() periph_1 = Peripheral(name="periph_1") self.assertEqual(periph_0.name, "periph_0") self.assertEqual(periph_1.name, "periph_1") def test_periph_name_wrong(self): with self.assertRaisesRegex(TypeError, r"Name must be a string, not 2"): periph = Peripheral(name=2) def test_set_bus_wrong(self): periph = Peripheral(src_loc_at=0) with self.assertRaisesRegex(TypeError, r"Bus interface must be an instance of wishbone.Interface, not 'foo'"): periph.bus = "foo" def test_get_bus_wrong(self): periph = Peripheral(src_loc_at=0) with self.assertRaisesRegex(NotImplementedError, r"Peripheral <.*> does not have a bus interface"): periph.bus def test_set_irq_wrong(self): periph = Peripheral(src_loc_at=0) with self.assertRaisesRegex(TypeError, r"IRQ line must be an instance of IRQLine, not 'foo'"): periph.irq = "foo" def test_get_irq_wrong(self): periph = Peripheral(src_loc_at=0) with self.assertRaisesRegex(NotImplementedError, r"Peripheral <.*> does not have an IRQ line"): periph.irq def test_iter_csr_banks(self): periph = Peripheral(src_loc_at=0) bank_0 = periph.csr_bank() bank_1 = periph.csr_bank(addr=0x4, alignment=2) self.assertEqual(list(periph.iter_csr_banks()), [ (bank_0, None, None), (bank_1, 0x4, 2), ]) def test_iter_windows(self): periph = Peripheral(src_loc_at=0) win_0 = periph.window(addr_width=2, data_width=8) win_1 = periph.window(addr_width=4, data_width=8, addr=0x4, sparse=True) self.assertEqual(list(periph.iter_windows()), [ (win_0, None, None), (win_1, 0x4, True), ]) def test_iter_events(self): periph = Peripheral(src_loc_at=0) ev_0 = periph.event() ev_1 = periph.event(mode="rise") self.assertEqual((ev_0.name, ev_0.mode), ("ev_0", "level")) self.assertEqual((ev_1.name, ev_1.mode), ("ev_1", "rise")) self.assertEqual(list(periph.iter_events()), [ ev_0, ev_1, ]) class CSRBankTestCase(unittest.TestCase): def test_csr_name(self): bank = CSRBank(name_prefix="foo") bar = bank.csr(1, "r") self.assertEqual(bar.name, "foo_bar") def test_csr_name_wrong(self): bank = CSRBank() with self.assertRaisesRegex(TypeError, r"Name must be a string, not 2"): bank.csr(1, "r", name=2) def test_iter_csr_regs(self): bank = CSRBank() csr_0 = bank.csr(1, "r") csr_1 = bank.csr(8, "rw", addr=0x4, alignment=2) self.assertEqual(list(bank.iter_csr_regs()), [ (csr_0, None, None), (csr_1, 0x4, 2), ]) class PeripheralBridgeTestCase(unittest.TestCase): def test_periph_wrong(self): with self.assertRaisesRegex(TypeError, r"Peripheral must be an instance of Peripheral, not 'foo'"): PeripheralBridge('foo', data_width=8, granularity=8, features=(), alignment=0) class PeripheralSimulationTestCase(unittest.TestCase): def test_csrs(self): class DummyPeripheral(Peripheral, Elaboratable): def __init__(self): super().__init__() bank = self.csr_bank(addr=0x100) self._csr_0 = bank.csr(8, "r") self._csr_1 = bank.csr(8, "r", addr=0x8, alignment=4) self._csr_2 = bank.csr(8, "rw") self.win_0 = self.window(addr_width=1, data_width=8, sparse=True, addr=0x000) self.win_1 = self.window(addr_width=1, data_width=32, granularity=8, addr=0x200) self._bridge = self.bridge(data_width=32, granularity=8, alignment=2) self.bus = self._bridge.bus def elaborate(self, platform): m = Module() m.submodules.bridge = self._bridge m.d.comb += [ self._csr_0.r_data.eq(0xa), self._csr_1.r_data.eq(0xb), ] with m.If(self._csr_2.w_stb): m.d.sync += self._csr_2.r_data.eq(self._csr_2.w_data) return m dut = DummyPeripheral() def process(): self.assertEqual((yield from wb_read(dut.bus, addr=0x100 >> 2, sel=0xf)), 0xa) yield self.assertEqual((yield from wb_read(dut.bus, addr=0x108 >> 2, sel=0xf)), 0xb) yield yield from wb_write(dut.bus, addr=0x118 >> 2, data=0xc, sel=0xf) yield self.assertEqual((yield from wb_read(dut.bus, addr=0x118 >> 2, sel=0xf)), 0xc) yield yield dut.bus.cyc.eq(1) yield dut.bus.adr.eq(0x000 >> 2) yield Delay(1e-7) self.assertEqual((yield dut.win_0.cyc), 1) yield dut.bus.adr.eq(0x200 >> 2) yield Delay(1e-7) self.assertEqual((yield dut.win_1.cyc), 1) simulation_test(dut, process) def test_events(self): class DummyPeripheral(Peripheral, Elaboratable): def __init__(self): super().__init__() self.ev_0 = self.event() self.ev_1 = self.event(mode="rise") self.ev_2 = self.event(mode="fall") self._bridge = self.bridge(data_width=8) self.bus = self._bridge.bus self.irq = self._bridge.irq def elaborate(self, platform): m = Module() m.submodules.bridge = self._bridge return m dut = DummyPeripheral() ev_status_addr = 0x0 ev_pending_addr = 0x1 ev_enable_addr = 0x2 def process(): yield dut.ev_0.stb.eq(1) yield dut.ev_1.stb.eq(0) yield dut.ev_2.stb.eq(1) yield self.assertEqual((yield dut.irq), 0) self.assertEqual((yield from wb_read(dut.bus, ev_status_addr, sel=0xf)), 0b101) yield yield from wb_write(dut.bus, ev_enable_addr, data=0b111, sel=0xf) yield self.assertEqual((yield dut.irq), 1) yield from wb_write(dut.bus, ev_pending_addr, data=0b001, sel=0xf) yield self.assertEqual((yield from wb_read(dut.bus, ev_pending_addr, sel=0xf)), 0b001) yield self.assertEqual((yield dut.irq), 1) yield dut.ev_0.stb.eq(0) yield from wb_write(dut.bus, ev_pending_addr, data=0b001, sel=0xf) yield self.assertEqual((yield dut.irq), 0) yield dut.ev_1.stb.eq(1) yield self.assertEqual((yield from wb_read(dut.bus, ev_pending_addr, sel=0xf)), 0b010) yield self.assertEqual((yield dut.irq), 1) yield from wb_write(dut.bus, ev_pending_addr, data=0b010, sel=0xf) yield self.assertEqual((yield dut.irq), 0) yield dut.ev_2.stb.eq(0) yield self.assertEqual((yield from wb_read(dut.bus, ev_pending_addr, sel=0xf)), 0b100) yield self.assertEqual((yield dut.irq), 1) yield from wb_write(dut.bus, ev_pending_addr, data=0b100, sel=0xf) yield self.assertEqual((yield dut.irq), 0) simulation_test(dut, process)
{"/systemonachip/test/test_periph_timer.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/test/test_periph_base.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/register/readwrite.py": ["/systemonachip/register/base.py"], "/systemonachip/peripheral/timer.py": ["/systemonachip/peripheral/__init__.py", "/systemonachip/event/__init__.py", "/systemonachip/register/__init__.py"], "/systemonachip/soc/cpu.py": ["/systemonachip/soc/base.py", "/systemonachip/cpu/__init__.py", "/systemonachip/peripheral/memory.py", "/systemonachip/peripheral/timer.py"], "/systemonachip/peripheral/base.py": ["/systemonachip/register/__init__.py", "/systemonachip/event/__init__.py"], "/systemonachip/register/__init__.py": ["/systemonachip/register/static.py", "/systemonachip/register/readwrite.py", "/systemonachip/register/config.py", "/systemonachip/register/variable.py", "/systemonachip/register/event.py"], "/systemonachip/register/event.py": ["/systemonachip/register/base.py"], "/systemonachip/soc/base.py": ["/systemonachip/peripheral/__init__.py"], "/examples/basic.py": ["/systemonachip/bus/decoder.py", "/systemonachip/cpu/minerva.py", "/systemonachip/peripheral/memory.py", "/systemonachip/peripheral/timer.py", "/systemonachip/soc/cpu.py"], "/systemonachip/peripheral/__init__.py": ["/systemonachip/peripheral/base.py"], "/systemonachip/test/test_periph_sram.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/test/test_periph_serial.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/bus/__init__.py": ["/systemonachip/bus/decoder.py"], "/systemonachip/cpu/minerva.py": ["/systemonachip/cpu/__init__.py"]}
16,231,485
systemonachip/systemonachip
refs/heads/main
/systemonachip/register/readwrite.py
from nmigen import Record from nmigen_soc import csr from .base import Register class Word(Register): def __init__(self, address, *, reset=0x00000000): pass class Bit(Register): def __init__(self, address, position, *, reset=False): self._address = address self._position = position def __get__(self, obj, type=None): if not isinstance(obj._memory_window, Record): return (obj._memory_window[self._address + self._position // 8] & (1 << (self._position % 8))) != 0 key = (self._address, self._position) if not hasattr(obj, "_csr"): obj._csr = {} elif key in obj._csr: return obj._csr[key] print("create bit", self._name) elem = csr.Element(1, "rw", name=self._name) obj._csr[key] = elem return elem def __set__(self, obj, type=None): if not isinstance(obj._memory_window, Record): obj._memory_window[self._address + self._position // 8] |= (1 << (self._position % 8)) return raise RuntimeError("Cannot set value when elaborating")
{"/systemonachip/test/test_periph_timer.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/test/test_periph_base.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/register/readwrite.py": ["/systemonachip/register/base.py"], "/systemonachip/peripheral/timer.py": ["/systemonachip/peripheral/__init__.py", "/systemonachip/event/__init__.py", "/systemonachip/register/__init__.py"], "/systemonachip/soc/cpu.py": ["/systemonachip/soc/base.py", "/systemonachip/cpu/__init__.py", "/systemonachip/peripheral/memory.py", "/systemonachip/peripheral/timer.py"], "/systemonachip/peripheral/base.py": ["/systemonachip/register/__init__.py", "/systemonachip/event/__init__.py"], "/systemonachip/register/__init__.py": ["/systemonachip/register/static.py", "/systemonachip/register/readwrite.py", "/systemonachip/register/config.py", "/systemonachip/register/variable.py", "/systemonachip/register/event.py"], "/systemonachip/register/event.py": ["/systemonachip/register/base.py"], "/systemonachip/soc/base.py": ["/systemonachip/peripheral/__init__.py"], "/examples/basic.py": ["/systemonachip/bus/decoder.py", "/systemonachip/cpu/minerva.py", "/systemonachip/peripheral/memory.py", "/systemonachip/peripheral/timer.py", "/systemonachip/soc/cpu.py"], "/systemonachip/peripheral/__init__.py": ["/systemonachip/peripheral/base.py"], "/systemonachip/test/test_periph_sram.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/test/test_periph_serial.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/bus/__init__.py": ["/systemonachip/bus/decoder.py"], "/systemonachip/cpu/minerva.py": ["/systemonachip/cpu/__init__.py"]}
16,231,486
systemonachip/systemonachip
refs/heads/main
/systemonachip/peripheral/timer.py
from nmigen import * from . import Peripheral from ..event import * from ..register import * __all__ = ["Timer"] class Timer(Peripheral, Elaboratable): """Timer peripheral. A general purpose down-counting timer peripheral.""" creator_id = StaticHalfWord(0x0, 0x1248) """Creator id for Scott Shawcroft: 0x1248""" creation_id = StaticHalfWord(0x2, 0x0000) """Creation id: 0x0000""" reload_ = VariableWidth(0x4) """Reload value of counter. When `ctr` reaches 0, it is automatically reloaded with this value. If the written value is larger than the timer width, only the bits within the timer's range will be kept.""" enable = Bit(0x8, 0x0) """Counter enable.""" value = VariableWidth(0xc) """Counter value.""" event_enable = AggregateEventEnable(0x10) """Enables interrupt generation out of the peripheral.""" event_status = AggregateEventStatus(0x14) """Aggregate event status, write 0 to any bit to turn the interrupt off.""" width = Config(0x18, "_width") """Configured width of the timer. Read-only""" zero = Event(0x14, 0x0, mode="rise") """Counter value reached 0. Event bit 0.""" aggregate_event = AggregateEvent() """High signal when any individual event is active and enabled.""" def __init__(self, memory_window, *, width=None): """Parameters ---------- width : int Counter width. Attributes ---------- bus : :class:`nmigen_soc.wishbone.Interface` Wishbone bus interface. irq : :class:`IRQLine` Interrupt request. """ super().__init__(memory_window) if isinstance(memory_window, Record): if not isinstance(memory_window, csr.Interface): raise ValueError("Timer must connect to csr.Interface") if not isinstance(width, int) or width < 0: raise ValueError("Counter width must be a non-negative integer, not {!r}" .format(width)) if width > 32: raise ValueError("Counter width cannot be greater than 32 (was: {})" .format(width)) self._width = width # bank = self.csr_bank() # self._reload = bank.csr(width, "rw") # self._en = bank.csr( 1, "rw") # self._ctr = bank.csr(width, "rw") # self._zero_ev = self.event(mode="rise") # self._bridge = self.bridge(data_width=32, granularity=8, alignment=2) # self.bus = self._bridge.bus #self.irq = self._bridge.irq def elaborate(self, platform): m = Module() with m.If(self.enable.r_data): with m.If(self.value.r_data == 0): m.d.comb += self.zero.eq(1) m.d.sync += self.value.r_data.eq(self.reload_.r_data) with m.Else(): m.d.sync += self.value.r_data.eq(self.value.r_data - 1) with m.If(self.reload_.w_stb): m.d.sync += self.reload_.r_data.eq(self.reload_.w_data) with m.If(self.enable.w_stb): m.d.sync += self.enable.r_data.eq(self.enable.w_data) with m.If(self.value.w_stb): m.d.sync += self.value.r_data.eq(self.value.w_data) m.submodules.peripheral = super().elaborate(platform) return m if __name__ == "__main__": from nmigen.back.pysim import Simulator from nmigen.back import verilog bus = csr.Interface(addr_width=14, data_width=8, name="csr") t = Timer(bus, width=4) class SimulatorBus: def __init__(self, sim, bus): self._sim = sim self._bus = bus self._read_address = None self._read_data = None self._write_address = None self._write_data = None def actions(self): while True: if self._read_address is not None: yield self._bus.addr.eq(self._read_address) yield self._bus.r_stb.eq(1) yield yield self._bus.r_stb.eq(0) yield self._read_data = yield self._bus.r_data self._read_address = None elif self._write_address is not None and self._write_data is not None: yield bus.addr.eq(self._write_address) yield bus.w_data.eq(self._write_data) yield bus.w_stb.eq(1) yield yield bus.w_stb.eq(0) yield yield self._write_address = None self._write_data = None else: yield def __getitem__(self, index): #print("get", index, sim, bus) self._read_address = index while self._read_data is None: self._sim.advance() data = self._read_data self._read_data = None return data def __setitem__(self, index, value): print("set", index, sim, bus) self._write_address = index self._write_data = value while self._write_data is not None: self._sim.advance() sim = Simulator(t) sbus = SimulatorBus(sim, bus) sim.add_clock(1e-6) sim.add_sync_process(sbus.actions) timer0 = Timer(sbus) with sim.write_vcd("timer.vcd"): print(timer0.width) # Should be 2 timer0.reload_ = 0xf timer0.value = 0xe print(timer0.enable) # Should be False timer0.enable = True for _ in range(50): sim.advance() print(timer0.enable) print(timer0.value) # wait 5 cycles print(timer0.zero) print(timer0.value) with open("timer.v", "w") as f: f.write(verilog.convert(t))
{"/systemonachip/test/test_periph_timer.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/test/test_periph_base.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/register/readwrite.py": ["/systemonachip/register/base.py"], "/systemonachip/peripheral/timer.py": ["/systemonachip/peripheral/__init__.py", "/systemonachip/event/__init__.py", "/systemonachip/register/__init__.py"], "/systemonachip/soc/cpu.py": ["/systemonachip/soc/base.py", "/systemonachip/cpu/__init__.py", "/systemonachip/peripheral/memory.py", "/systemonachip/peripheral/timer.py"], "/systemonachip/peripheral/base.py": ["/systemonachip/register/__init__.py", "/systemonachip/event/__init__.py"], "/systemonachip/register/__init__.py": ["/systemonachip/register/static.py", "/systemonachip/register/readwrite.py", "/systemonachip/register/config.py", "/systemonachip/register/variable.py", "/systemonachip/register/event.py"], "/systemonachip/register/event.py": ["/systemonachip/register/base.py"], "/systemonachip/soc/base.py": ["/systemonachip/peripheral/__init__.py"], "/examples/basic.py": ["/systemonachip/bus/decoder.py", "/systemonachip/cpu/minerva.py", "/systemonachip/peripheral/memory.py", "/systemonachip/peripheral/timer.py", "/systemonachip/soc/cpu.py"], "/systemonachip/peripheral/__init__.py": ["/systemonachip/peripheral/base.py"], "/systemonachip/test/test_periph_sram.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/test/test_periph_serial.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/bus/__init__.py": ["/systemonachip/bus/decoder.py"], "/systemonachip/cpu/minerva.py": ["/systemonachip/cpu/__init__.py"]}
16,231,487
systemonachip/systemonachip
refs/heads/main
/systemonachip/soc/cpu.py
from .base import * from ..cpu import CPU from ..peripheral.interrupt import InterruptController from ..peripheral.memory import RandomAccessMemory from ..peripheral.serial import AsyncSerial from ..peripheral.timer import Timer __all__ = ["CPUSoC", "BIOSBuilder"] class CPUSoC(SoC): cpu = socproperty(CPU) intc = socproperty(InterruptController) rom = socproperty(RandomAccessMemory) ram = socproperty(RandomAccessMemory) # TODO: abstract class for storage peripherals. timer = socproperty(Timer) # TODO: implement a CRG peripheral and expose clock frequencies through CSRs. clk_freq = socproperty(int) def build(self, name=None, build_dir="build/soc", do_build=True, do_init=False): """TODO """ plan = BIOSBuilder().prepare(self, build_dir, name) if not do_build: return plan products = plan.execute_local(build_dir) if not do_init: return products # with products.extract("bios.bin") as bios_filename: # with open(bios_filename, "rb") as f: # words = iter(lambda: f.read(self.cpu.data_width // 8), b'') # bios = [int.from_bytes(w, self.cpu.byteorder) for w in words] self.rom.init = bytearray(400) class BIOSBuilder(ConfigBuilder): file_templates = { **ConfigBuilder.file_templates, "{{name}}.config": r""" # {{autogenerated}} CONFIG_CPU_{{soc.cpu.name.upper()}}=y CONFIG_CPU_RESET_ADDR={{hex(soc.cpu.reset_addr)}} CONFIG_CPU_BYTEORDER="{{soc.cpu.byteorder}}" CONFIG_ARCH_{{soc.cpu.arch.upper()}}=y {% if soc.cpu.muldiv == "soft" %} CONFIG_{{soc.cpu.arch.upper()}}_MULDIV_SOFT=y {% else %} CONFIG_{{soc.cpu.arch.upper()}}_MULDIV_SOFT=n {% endif %} CONFIG_ROM_START={{hex(periph_addr(soc.rom))}} CONFIG_ROM_SIZE={{hex(soc.rom.size)}} CONFIG_RAM_START={{hex(periph_addr(soc.ram))}} CONFIG_RAM_SIZE={{hex(soc.ram.size)}} CONFIG_TIMER_START={{hex(periph_addr(soc.timer))}} CONFIG_TIMER_IRQNO={{soc.intc.find_index(soc.timer.irq)}} CONFIG_TIMER_CTR_WIDTH={{soc.timer.width}} CONFIG_CLOCK_FREQ={{soc.clk_freq}} """, } command_templates = [ *ConfigBuilder.command_templates, ] def prepare(self, soc, build_dir, name): if not isinstance(soc, CPUSoC): raise TypeError("SoC must be an instance of CPUSoC, not {!r}" .format(soc)) return super().prepare(soc, build_dir, name)
{"/systemonachip/test/test_periph_timer.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/test/test_periph_base.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/register/readwrite.py": ["/systemonachip/register/base.py"], "/systemonachip/peripheral/timer.py": ["/systemonachip/peripheral/__init__.py", "/systemonachip/event/__init__.py", "/systemonachip/register/__init__.py"], "/systemonachip/soc/cpu.py": ["/systemonachip/soc/base.py", "/systemonachip/cpu/__init__.py", "/systemonachip/peripheral/memory.py", "/systemonachip/peripheral/timer.py"], "/systemonachip/peripheral/base.py": ["/systemonachip/register/__init__.py", "/systemonachip/event/__init__.py"], "/systemonachip/register/__init__.py": ["/systemonachip/register/static.py", "/systemonachip/register/readwrite.py", "/systemonachip/register/config.py", "/systemonachip/register/variable.py", "/systemonachip/register/event.py"], "/systemonachip/register/event.py": ["/systemonachip/register/base.py"], "/systemonachip/soc/base.py": ["/systemonachip/peripheral/__init__.py"], "/examples/basic.py": ["/systemonachip/bus/decoder.py", "/systemonachip/cpu/minerva.py", "/systemonachip/peripheral/memory.py", "/systemonachip/peripheral/timer.py", "/systemonachip/soc/cpu.py"], "/systemonachip/peripheral/__init__.py": ["/systemonachip/peripheral/base.py"], "/systemonachip/test/test_periph_sram.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/test/test_periph_serial.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/bus/__init__.py": ["/systemonachip/bus/decoder.py"], "/systemonachip/cpu/minerva.py": ["/systemonachip/cpu/__init__.py"]}
16,231,488
systemonachip/systemonachip
refs/heads/main
/systemonachip/peripheral/base.py
from nmigen import * from nmigen import tracer from nmigen.utils import log2_int from nmigen_soc import csr, wishbone from nmigen_soc.memory import MemoryMap from nmigen_soc.csr.wishbone import WishboneCSRBridge from ..register import AutoRegister from ..event import * __all__ = ["Peripheral"] class Peripheral: """ """ def __init__(self, memory_window): self._memory_window = memory_window if isinstance(self._memory_window, Record): self._bus = self._memory_window # def window(self, *, addr_width, data_width, granularity=None, features=frozenset(), # alignment=0, addr=None, sparse=None): # """Request a window to a subordinate bus. # See :meth:`nmigen_soc.wishbone.Decoder.add` for details. # Returns # ------------ # An instance of :class:`nmigen_soc.wishbone.Interface`. # """ # window = wishbone.Interface(addr_width=addr_width, data_width=data_width, # granularity=granularity, features=features) # granularity_bits = log2_int(data_width // window.granularity) # window.memory_map = MemoryMap(addr_width=addr_width + granularity_bits, # data_width=window.granularity, alignment=alignment) # self._windows.append((window, addr, sparse)) # return window def elaborate(self, platform): m = Module() if hasattr(self, "_events"): print("events") for key in self._events: print(key, self._events[key]) print() for name in dir(self): class_ = self.__class__ if hasattr(class_, name): v = getattr(self.__class__, name) if isinstance(v, AutoRegister): print(name, v) if isinstance(v, Event): print("event", name, v) if hasattr(self, "_csr"): csr_mux = csr.Multiplexer(addr_width=8, data_width=8, alignment=0) csr_mux._bus = self._bus print("csrs") for key in self._csr: addr, bit = key csr_mux.add(self._csr[key], addr=addr, alignment=0, extend=False) print(key, self._csr[key]) print() m.submodules["csr_multiplexer"] = csr_mux # TODO: Only create this bridge if we were passed in a wishbone bus. # m.submodules["wishbone_to_csr_bridge"] = WishboneCSRBridge(csr_mux.bus, data_width=8) return m class PeripheralBridge(Elaboratable): """Peripheral bridge. A bridge providing access to the registers and windows of a peripheral, and support for interrupt requests from its event sources. Event managment is performed by an :class:`InterruptSource` submodule. Parameters ---------- periph : :class:`Peripheral` The peripheral whose resources are exposed by this bridge. data_width : int Data width. See :class:`nmigen_soc.wishbone.Interface`. granularity : int or None Granularity. See :class:`nmigen_soc.wishbone.Interface`. features : iter(str) Optional signal set. See :class:`nmigen_soc.wishbone.Interface`. alignment : int Resource alignment. See :class:`nmigen_soc.memory.MemoryMap`. Attributes ---------- bus : :class:`nmigen_soc.wishbone.Interface` Wishbone bus providing access to the resources of the peripheral. irq : :class:`IRQLine`, out Interrupt request. It is raised if any event source is enabled and has a pending notification. """ def __init__(self, periph, *, data_width, granularity, features, alignment): if not isinstance(periph, Peripheral): raise TypeError("Peripheral must be an instance of Peripheral, not {!r}" .format(periph)) self._wb_decoder = wishbone.Decoder(addr_width=1, data_width=data_width, granularity=granularity, features=features, alignment=alignment) self._csr_subs = [] for bank, bank_addr, bank_alignment in periph.iter_csr_banks(): if bank_alignment is None: bank_alignment = alignment csr_mux = csr.Multiplexer(addr_width=1, data_width=8, alignment=bank_alignment) for elem, elem_addr, elem_alignment in bank.iter_csr_regs(): if elem_alignment is None: elem_alignment = alignment csr_mux.add(elem, addr=elem_addr, alignment=elem_alignment, extend=True) csr_bridge = WishboneCSRBridge(csr_mux.bus, data_width=data_width) self._wb_decoder.add(csr_bridge.wb_bus, addr=bank_addr, extend=True) self._csr_subs.append((csr_mux, csr_bridge)) for window, window_addr, window_sparse in periph.iter_windows(): self._wb_decoder.add(window, addr=window_addr, sparse=window_sparse, extend=True) events = list(periph.iter_events()) if len(events) > 0: self._int_src = InterruptSource(events, name="{}_ev".format(periph.name)) self.irq = self._int_src.irq csr_mux = csr.Multiplexer(addr_width=1, data_width=8, alignment=alignment) csr_mux.add(self._int_src.status, extend=True) csr_mux.add(self._int_src.pending, extend=True) csr_mux.add(self._int_src.enable, extend=True) csr_bridge = WishboneCSRBridge(csr_mux.bus, data_width=data_width) self._wb_decoder.add(csr_bridge.wb_bus, extend=True) self._csr_subs.append((csr_mux, csr_bridge)) else: self._int_src = None self.irq = None self.bus = self._wb_decoder.bus def elaborate(self, platform): m = Module() for i, (csr_mux, csr_bridge) in enumerate(self._csr_subs): m.submodules[ "csr_mux_{}".format(i)] = csr_mux m.submodules["csr_bridge_{}".format(i)] = csr_bridge if self._int_src is not None: m.submodules._int_src = self._int_src m.submodules.wb_decoder = self._wb_decoder return m
{"/systemonachip/test/test_periph_timer.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/test/test_periph_base.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/register/readwrite.py": ["/systemonachip/register/base.py"], "/systemonachip/peripheral/timer.py": ["/systemonachip/peripheral/__init__.py", "/systemonachip/event/__init__.py", "/systemonachip/register/__init__.py"], "/systemonachip/soc/cpu.py": ["/systemonachip/soc/base.py", "/systemonachip/cpu/__init__.py", "/systemonachip/peripheral/memory.py", "/systemonachip/peripheral/timer.py"], "/systemonachip/peripheral/base.py": ["/systemonachip/register/__init__.py", "/systemonachip/event/__init__.py"], "/systemonachip/register/__init__.py": ["/systemonachip/register/static.py", "/systemonachip/register/readwrite.py", "/systemonachip/register/config.py", "/systemonachip/register/variable.py", "/systemonachip/register/event.py"], "/systemonachip/register/event.py": ["/systemonachip/register/base.py"], "/systemonachip/soc/base.py": ["/systemonachip/peripheral/__init__.py"], "/examples/basic.py": ["/systemonachip/bus/decoder.py", "/systemonachip/cpu/minerva.py", "/systemonachip/peripheral/memory.py", "/systemonachip/peripheral/timer.py", "/systemonachip/soc/cpu.py"], "/systemonachip/peripheral/__init__.py": ["/systemonachip/peripheral/base.py"], "/systemonachip/test/test_periph_sram.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/test/test_periph_serial.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/bus/__init__.py": ["/systemonachip/bus/decoder.py"], "/systemonachip/cpu/minerva.py": ["/systemonachip/cpu/__init__.py"]}
16,231,489
systemonachip/systemonachip
refs/heads/main
/systemonachip/register/__init__.py
from .static import * from .readwrite import * from .config import * from .variable import * from .event import *
{"/systemonachip/test/test_periph_timer.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/test/test_periph_base.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/register/readwrite.py": ["/systemonachip/register/base.py"], "/systemonachip/peripheral/timer.py": ["/systemonachip/peripheral/__init__.py", "/systemonachip/event/__init__.py", "/systemonachip/register/__init__.py"], "/systemonachip/soc/cpu.py": ["/systemonachip/soc/base.py", "/systemonachip/cpu/__init__.py", "/systemonachip/peripheral/memory.py", "/systemonachip/peripheral/timer.py"], "/systemonachip/peripheral/base.py": ["/systemonachip/register/__init__.py", "/systemonachip/event/__init__.py"], "/systemonachip/register/__init__.py": ["/systemonachip/register/static.py", "/systemonachip/register/readwrite.py", "/systemonachip/register/config.py", "/systemonachip/register/variable.py", "/systemonachip/register/event.py"], "/systemonachip/register/event.py": ["/systemonachip/register/base.py"], "/systemonachip/soc/base.py": ["/systemonachip/peripheral/__init__.py"], "/examples/basic.py": ["/systemonachip/bus/decoder.py", "/systemonachip/cpu/minerva.py", "/systemonachip/peripheral/memory.py", "/systemonachip/peripheral/timer.py", "/systemonachip/soc/cpu.py"], "/systemonachip/peripheral/__init__.py": ["/systemonachip/peripheral/base.py"], "/systemonachip/test/test_periph_sram.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/test/test_periph_serial.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/bus/__init__.py": ["/systemonachip/bus/decoder.py"], "/systemonachip/cpu/minerva.py": ["/systemonachip/cpu/__init__.py"]}
16,231,490
systemonachip/systemonachip
refs/heads/main
/systemonachip/register/base.py
class Register: """Core register used for configuration and status info. 32bit registers may take multiple bus cycles to read to save footprint. By default, registers must be read during elaboration to exist.""" def __set_name__(self, owner, name): self._name = name class AutoRegister(Register): """Register that will be auto-created and doesn't need to be read during elaboration.""" pass
{"/systemonachip/test/test_periph_timer.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/test/test_periph_base.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/register/readwrite.py": ["/systemonachip/register/base.py"], "/systemonachip/peripheral/timer.py": ["/systemonachip/peripheral/__init__.py", "/systemonachip/event/__init__.py", "/systemonachip/register/__init__.py"], "/systemonachip/soc/cpu.py": ["/systemonachip/soc/base.py", "/systemonachip/cpu/__init__.py", "/systemonachip/peripheral/memory.py", "/systemonachip/peripheral/timer.py"], "/systemonachip/peripheral/base.py": ["/systemonachip/register/__init__.py", "/systemonachip/event/__init__.py"], "/systemonachip/register/__init__.py": ["/systemonachip/register/static.py", "/systemonachip/register/readwrite.py", "/systemonachip/register/config.py", "/systemonachip/register/variable.py", "/systemonachip/register/event.py"], "/systemonachip/register/event.py": ["/systemonachip/register/base.py"], "/systemonachip/soc/base.py": ["/systemonachip/peripheral/__init__.py"], "/examples/basic.py": ["/systemonachip/bus/decoder.py", "/systemonachip/cpu/minerva.py", "/systemonachip/peripheral/memory.py", "/systemonachip/peripheral/timer.py", "/systemonachip/soc/cpu.py"], "/systemonachip/peripheral/__init__.py": ["/systemonachip/peripheral/base.py"], "/systemonachip/test/test_periph_sram.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/test/test_periph_serial.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/bus/__init__.py": ["/systemonachip/bus/decoder.py"], "/systemonachip/cpu/minerva.py": ["/systemonachip/cpu/__init__.py"]}
16,231,491
systemonachip/systemonachip
refs/heads/main
/systemonachip/register/static.py
class StaticHalfWord: def __init__(self, address, value): pass
{"/systemonachip/test/test_periph_timer.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/test/test_periph_base.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/register/readwrite.py": ["/systemonachip/register/base.py"], "/systemonachip/peripheral/timer.py": ["/systemonachip/peripheral/__init__.py", "/systemonachip/event/__init__.py", "/systemonachip/register/__init__.py"], "/systemonachip/soc/cpu.py": ["/systemonachip/soc/base.py", "/systemonachip/cpu/__init__.py", "/systemonachip/peripheral/memory.py", "/systemonachip/peripheral/timer.py"], "/systemonachip/peripheral/base.py": ["/systemonachip/register/__init__.py", "/systemonachip/event/__init__.py"], "/systemonachip/register/__init__.py": ["/systemonachip/register/static.py", "/systemonachip/register/readwrite.py", "/systemonachip/register/config.py", "/systemonachip/register/variable.py", "/systemonachip/register/event.py"], "/systemonachip/register/event.py": ["/systemonachip/register/base.py"], "/systemonachip/soc/base.py": ["/systemonachip/peripheral/__init__.py"], "/examples/basic.py": ["/systemonachip/bus/decoder.py", "/systemonachip/cpu/minerva.py", "/systemonachip/peripheral/memory.py", "/systemonachip/peripheral/timer.py", "/systemonachip/soc/cpu.py"], "/systemonachip/peripheral/__init__.py": ["/systemonachip/peripheral/base.py"], "/systemonachip/test/test_periph_sram.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/test/test_periph_serial.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/bus/__init__.py": ["/systemonachip/bus/decoder.py"], "/systemonachip/cpu/minerva.py": ["/systemonachip/cpu/__init__.py"]}
16,231,492
systemonachip/systemonachip
refs/heads/main
/systemonachip/peripheral/memory.py
from nmigen import * from nmigen.utils import log2_int from nmigen_soc import wishbone from nmigen_soc.memory import MemoryMap from nmigen import tracer __all__ = ["RandomAccessMemory"] class RandomAccessMemory(Elaboratable): """SRAM storage peripheral. Parameters ---------- size : int Memory size in bytes. data_width : int Bus data width. granularity : int Bus granularity. writable : bool Memory is writable. Attributes ---------- bus : :class:`nmigen_soc.wishbone.Interface` Wishbone bus interface. """ # TODO raise bus.err if read-only and a bus write is attempted. def __init__(self, memory_window, *, size, name=None, src_loc_at=1, data_width=32, granularity=8, writable=True): super().__init__() if name is not None and not isinstance(name, str): raise TypeError("Name must be a string, not {!r}".format(name)) self.name = name or tracer.get_var_name(depth=2 + src_loc_at).lstrip("_") if not isinstance(size, int) or size <= 0 or size & size-1: raise ValueError("Size must be an integer power of two, not {!r}" .format(size)) if size < data_width // granularity: raise ValueError("Size {} cannot be lesser than the data width/granularity ratio " "of {} ({} / {})" .format(size, data_width // granularity, data_width, granularity)) self._mem = Memory(depth=(size * granularity) // data_width, width=data_width, name=self.name) if isinstance(memory_window, wishbone.Interface): if not hasattr(memory_window, "bte"): raise ValueError("Incoming wishbone.Interface must support burst") self.bus = memory_window self.bus.memory_map.add_resource(self._mem, size=size) self.size = size self.granularity = granularity self.writable = writable @property def init(self): return self._mem.init @init.setter def init(self, init): self._mem.init = init def elaborate(self, platform): m = Module() incr = Signal.like(self.bus.adr) with m.Switch(self.bus.bte): with m.Case(wishbone.BurstTypeExt.LINEAR): m.d.comb += incr.eq(self.bus.adr + 1) with m.Case(wishbone.BurstTypeExt.WRAP_4): m.d.comb += incr[:2].eq(self.bus.adr[:2] + 1) m.d.comb += incr[2:].eq(self.bus.adr[2:]) with m.Case(wishbone.BurstTypeExt.WRAP_8): m.d.comb += incr[:3].eq(self.bus.adr[:3] + 1) m.d.comb += incr[3:].eq(self.bus.adr[3:]) with m.Case(wishbone.BurstTypeExt.WRAP_16): m.d.comb += incr[:4].eq(self.bus.adr[:4] + 1) m.d.comb += incr[4:].eq(self.bus.adr[4:]) m.submodules.mem_rp = mem_rp = self._mem.read_port() m.d.comb += self.bus.dat_r.eq(mem_rp.data) with m.If(self.bus.ack): m.d.sync += self.bus.ack.eq(0) with m.If(self.bus.cyc & self.bus.stb): m.d.sync += self.bus.ack.eq(1) with m.If((self.bus.cti == wishbone.CycleType.INCR_BURST) & self.bus.ack): m.d.comb += mem_rp.addr.eq(incr) with m.Else(): m.d.comb += mem_rp.addr.eq(self.bus.adr) if self.writable: m.submodules.mem_wp = mem_wp = self._mem.write_port(granularity=self.granularity) m.d.comb += mem_wp.addr.eq(mem_rp.addr) m.d.comb += mem_wp.data.eq(self.bus.dat_w) with m.If(self.bus.cyc & self.bus.stb & self.bus.we): m.d.comb += mem_wp.en.eq(self.bus.sel) return m
{"/systemonachip/test/test_periph_timer.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/test/test_periph_base.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/register/readwrite.py": ["/systemonachip/register/base.py"], "/systemonachip/peripheral/timer.py": ["/systemonachip/peripheral/__init__.py", "/systemonachip/event/__init__.py", "/systemonachip/register/__init__.py"], "/systemonachip/soc/cpu.py": ["/systemonachip/soc/base.py", "/systemonachip/cpu/__init__.py", "/systemonachip/peripheral/memory.py", "/systemonachip/peripheral/timer.py"], "/systemonachip/peripheral/base.py": ["/systemonachip/register/__init__.py", "/systemonachip/event/__init__.py"], "/systemonachip/register/__init__.py": ["/systemonachip/register/static.py", "/systemonachip/register/readwrite.py", "/systemonachip/register/config.py", "/systemonachip/register/variable.py", "/systemonachip/register/event.py"], "/systemonachip/register/event.py": ["/systemonachip/register/base.py"], "/systemonachip/soc/base.py": ["/systemonachip/peripheral/__init__.py"], "/examples/basic.py": ["/systemonachip/bus/decoder.py", "/systemonachip/cpu/minerva.py", "/systemonachip/peripheral/memory.py", "/systemonachip/peripheral/timer.py", "/systemonachip/soc/cpu.py"], "/systemonachip/peripheral/__init__.py": ["/systemonachip/peripheral/base.py"], "/systemonachip/test/test_periph_sram.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/test/test_periph_serial.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/bus/__init__.py": ["/systemonachip/bus/decoder.py"], "/systemonachip/cpu/minerva.py": ["/systemonachip/cpu/__init__.py"]}
16,231,493
systemonachip/systemonachip
refs/heads/main
/systemonachip/test/_wishbone.py
def wb_read(bus, addr, sel, timeout=32): yield bus.cyc.eq(1) yield bus.stb.eq(1) yield bus.adr.eq(addr) yield bus.sel.eq(sel) yield cycles = 0 while not (yield bus.ack): yield if cycles >= timeout: raise RuntimeError("Wishbone transaction timed out") cycles += 1 data = (yield bus.dat_r) yield bus.cyc.eq(0) yield bus.stb.eq(0) return data def wb_write(bus, addr, data, sel, timeout=32): yield bus.cyc.eq(1) yield bus.stb.eq(1) yield bus.adr.eq(addr) yield bus.we.eq(1) yield bus.sel.eq(sel) yield bus.dat_w.eq(data) yield cycles = 0 while not (yield bus.ack): yield if cycles >= timeout: raise RuntimeError("Wishbone transaction timed out") cycles += 1 yield bus.cyc.eq(0) yield bus.stb.eq(0) yield bus.we.eq(0)
{"/systemonachip/test/test_periph_timer.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/test/test_periph_base.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/register/readwrite.py": ["/systemonachip/register/base.py"], "/systemonachip/peripheral/timer.py": ["/systemonachip/peripheral/__init__.py", "/systemonachip/event/__init__.py", "/systemonachip/register/__init__.py"], "/systemonachip/soc/cpu.py": ["/systemonachip/soc/base.py", "/systemonachip/cpu/__init__.py", "/systemonachip/peripheral/memory.py", "/systemonachip/peripheral/timer.py"], "/systemonachip/peripheral/base.py": ["/systemonachip/register/__init__.py", "/systemonachip/event/__init__.py"], "/systemonachip/register/__init__.py": ["/systemonachip/register/static.py", "/systemonachip/register/readwrite.py", "/systemonachip/register/config.py", "/systemonachip/register/variable.py", "/systemonachip/register/event.py"], "/systemonachip/register/event.py": ["/systemonachip/register/base.py"], "/systemonachip/soc/base.py": ["/systemonachip/peripheral/__init__.py"], "/examples/basic.py": ["/systemonachip/bus/decoder.py", "/systemonachip/cpu/minerva.py", "/systemonachip/peripheral/memory.py", "/systemonachip/peripheral/timer.py", "/systemonachip/soc/cpu.py"], "/systemonachip/peripheral/__init__.py": ["/systemonachip/peripheral/base.py"], "/systemonachip/test/test_periph_sram.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/test/test_periph_serial.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/bus/__init__.py": ["/systemonachip/bus/decoder.py"], "/systemonachip/cpu/minerva.py": ["/systemonachip/cpu/__init__.py"]}
16,231,494
systemonachip/systemonachip
refs/heads/main
/systemonachip/test/test_periph_event.py
# nmigen: UnusedElaboratable=no import unittest from nmigen import * from nmigen.back.pysim import * from ..periph.event import * def simulation_test(dut, process): with Simulator(dut, vcd_file=open("test.vcd", "w")) as sim: sim.add_clock(1e-6) sim.add_sync_process(process) sim.run() class EventSourceTestCase(unittest.TestCase): def test_simple(self): ev = EventSource() self.assertEqual(ev.name, "ev") self.assertEqual(ev.mode, "level") def test_name_wrong(self): with self.assertRaisesRegex(TypeError, r"Name must be a string, not 2"): EventSource(name=2) def test_mode_wrong(self): with self.assertRaisesRegex(ValueError, r"Invalid trigger mode 'foo'; must be one of level, rise, fall"): ev = EventSource(mode="foo") class InterruptSourceTestCase(unittest.TestCase): def test_simple(self): ev_0 = EventSource() ev_1 = EventSource() dut = InterruptSource((ev_0, ev_1)) self.assertEqual(dut.name, "dut") self.assertEqual(dut.status.width, 2) self.assertEqual(dut.pending.width, 2) self.assertEqual(dut.enable.width, 2) def test_name_wrong(self): with self.assertRaisesRegex(TypeError, r"Name must be a string, not 2"): InterruptSource((), name=2) def test_event_wrong(self): with self.assertRaisesRegex(TypeError, r"Event source must be an instance of EventSource, not 'foo'"): dut = InterruptSource(("foo",)) def test_events(self): ev_0 = EventSource(mode="level") ev_1 = EventSource(mode="rise") ev_2 = EventSource(mode="fall") dut = InterruptSource((ev_0, ev_1, ev_2)) def process(): yield ev_0.stb.eq(1) yield ev_1.stb.eq(0) yield ev_2.stb.eq(1) yield self.assertEqual((yield dut.irq), 0) yield dut.status.r_stb.eq(1) yield yield dut.status.r_stb.eq(0) yield self.assertEqual((yield dut.status.r_data), 0b101) yield yield dut.enable.w_stb.eq(1) yield dut.enable.w_data.eq(0b111) yield yield dut.enable.w_stb.eq(0) yield yield self.assertEqual((yield dut.irq), 1) yield dut.pending.w_stb.eq(1) yield dut.pending.w_data.eq(0b001) yield yield dut.pending.w_stb.eq(0) yield yield dut.pending.r_stb.eq(1) yield yield dut.pending.r_stb.eq(0) yield self.assertEqual((yield dut.pending.r_data), 0b001) self.assertEqual((yield dut.irq), 1) yield yield ev_0.stb.eq(0) yield dut.pending.w_stb.eq(1) yield dut.pending.w_data.eq(0b001) yield yield dut.pending.w_stb.eq(0) yield yield self.assertEqual((yield dut.irq), 0) yield ev_1.stb.eq(1) yield dut.pending.r_stb.eq(1) yield yield dut.pending.r_stb.eq(0) yield self.assertEqual((yield dut.pending.r_data), 0b010) self.assertEqual((yield dut.irq), 1) yield dut.pending.w_stb.eq(1) yield dut.pending.w_data.eq(0b010) yield yield dut.pending.w_stb.eq(0) yield yield self.assertEqual((yield dut.irq), 0) yield ev_2.stb.eq(0) yield yield dut.pending.r_stb.eq(1) yield yield dut.pending.r_stb.eq(0) yield self.assertEqual((yield dut.pending.r_data), 0b100) self.assertEqual((yield dut.irq), 1) yield dut.pending.w_stb.eq(1) yield dut.pending.w_data.eq(0b100) yield yield dut.pending.w_stb.eq(0) yield yield self.assertEqual((yield dut.irq), 0) simulation_test(dut, process)
{"/systemonachip/test/test_periph_timer.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/test/test_periph_base.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/register/readwrite.py": ["/systemonachip/register/base.py"], "/systemonachip/peripheral/timer.py": ["/systemonachip/peripheral/__init__.py", "/systemonachip/event/__init__.py", "/systemonachip/register/__init__.py"], "/systemonachip/soc/cpu.py": ["/systemonachip/soc/base.py", "/systemonachip/cpu/__init__.py", "/systemonachip/peripheral/memory.py", "/systemonachip/peripheral/timer.py"], "/systemonachip/peripheral/base.py": ["/systemonachip/register/__init__.py", "/systemonachip/event/__init__.py"], "/systemonachip/register/__init__.py": ["/systemonachip/register/static.py", "/systemonachip/register/readwrite.py", "/systemonachip/register/config.py", "/systemonachip/register/variable.py", "/systemonachip/register/event.py"], "/systemonachip/register/event.py": ["/systemonachip/register/base.py"], "/systemonachip/soc/base.py": ["/systemonachip/peripheral/__init__.py"], "/examples/basic.py": ["/systemonachip/bus/decoder.py", "/systemonachip/cpu/minerva.py", "/systemonachip/peripheral/memory.py", "/systemonachip/peripheral/timer.py", "/systemonachip/soc/cpu.py"], "/systemonachip/peripheral/__init__.py": ["/systemonachip/peripheral/base.py"], "/systemonachip/test/test_periph_sram.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/test/test_periph_serial.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/bus/__init__.py": ["/systemonachip/bus/decoder.py"], "/systemonachip/cpu/minerva.py": ["/systemonachip/cpu/__init__.py"]}
16,231,495
systemonachip/systemonachip
refs/heads/main
/systemonachip/test/test_periph_intc.py
#nmigen: UnusedElaboratable=no import unittest from nmigen import * from nmigen.back.pysim import * from ..periph import IRQLine from ..periph.intc import * class InterruptControllerTestCase(unittest.TestCase): def test_add_irq_wrong_line(self): intc = InterruptController() with self.assertRaisesRegex(TypeError, r"IRQ line must be an instance of IRQLine, not 'foo'"): intc.add_irq("foo", 0) def test_add_irq_wrong_index(self): intc = InterruptController() with self.assertRaisesRegex(ValueError, r"IRQ index must be a non-negative integer, not 'bar'"): intc.add_irq(IRQLine(name="foo"), "bar") with self.assertRaisesRegex(ValueError, r"IRQ index must be a non-negative integer, not -1"): intc.add_irq(IRQLine(name="foo"), -1) def test_add_irq_line_twice(self): intc = InterruptController() line = IRQLine() with self.assertRaisesRegex(ValueError, r"IRQ line \(sig line\) has already been mapped to IRQ index 0"): intc.add_irq(line, 0) intc.add_irq(line, 1) def test_add_irq_index_twice(self): intc = InterruptController() line_0 = IRQLine() line_1 = IRQLine() with self.assertRaisesRegex(ValueError, r"IRQ index 0 has already been mapped to IRQ line \(sig line_0\)"): intc.add_irq(line_0, 0) intc.add_irq(line_1, 0) def test_iter_irqs(self): intc = InterruptController() line_0 = IRQLine() line_1 = IRQLine() intc.add_irq(line_0, 0) intc.add_irq(line_1, 1) self.assertEqual(list(intc.iter_irqs()), [ (0, line_0), (1, line_1), ]) def test_find_index(self): intc = InterruptController() line_0 = IRQLine() line_1 = IRQLine() intc.add_irq(line_0, 0) intc.add_irq(line_1, 1) self.assertEqual(intc.find_index(line_0), 0) self.assertEqual(intc.find_index(line_1), 1) def test_find_index_absent(self): intc = InterruptController() line = IRQLine() with self.assertRaises(KeyError): intc.find_index(line) class GenericInterruptControllerTestCase(unittest.TestCase): def test_wrong_width(self): with self.assertRaisesRegex(ValueError, r"Width must be a strictly positive integer, not 'foo'"): intc = GenericInterruptController(width="foo") with self.assertRaisesRegex(ValueError, r"Width must be a strictly positive integer, not 0"): intc = GenericInterruptController(width=0) def test_add_irq_wrong_index(self): intc = GenericInterruptController(width=8) line = IRQLine() with self.assertRaisesRegex(ValueError, r"IRQ index must be an integer ranging from 0 to 7, not 8"): intc.add_irq(line, 8) def test_passthrough(self): dut = GenericInterruptController(width=8) line_0 = IRQLine() line_1 = IRQLine() dut.add_irq(line_0, 0) dut.add_irq(line_1, 1) def process(): self.assertEqual((yield dut.ip), 0b00) yield line_0.eq(1) yield Delay(1e-6) self.assertEqual((yield dut.ip), 0b01) yield line_1.eq(1) yield Delay(1e-6) self.assertEqual((yield dut.ip), 0b11) with Simulator(dut, vcd_file=open("test.vcd", "w")) as sim: sim.add_process(process) sim.run()
{"/systemonachip/test/test_periph_timer.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/test/test_periph_base.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/register/readwrite.py": ["/systemonachip/register/base.py"], "/systemonachip/peripheral/timer.py": ["/systemonachip/peripheral/__init__.py", "/systemonachip/event/__init__.py", "/systemonachip/register/__init__.py"], "/systemonachip/soc/cpu.py": ["/systemonachip/soc/base.py", "/systemonachip/cpu/__init__.py", "/systemonachip/peripheral/memory.py", "/systemonachip/peripheral/timer.py"], "/systemonachip/peripheral/base.py": ["/systemonachip/register/__init__.py", "/systemonachip/event/__init__.py"], "/systemonachip/register/__init__.py": ["/systemonachip/register/static.py", "/systemonachip/register/readwrite.py", "/systemonachip/register/config.py", "/systemonachip/register/variable.py", "/systemonachip/register/event.py"], "/systemonachip/register/event.py": ["/systemonachip/register/base.py"], "/systemonachip/soc/base.py": ["/systemonachip/peripheral/__init__.py"], "/examples/basic.py": ["/systemonachip/bus/decoder.py", "/systemonachip/cpu/minerva.py", "/systemonachip/peripheral/memory.py", "/systemonachip/peripheral/timer.py", "/systemonachip/soc/cpu.py"], "/systemonachip/peripheral/__init__.py": ["/systemonachip/peripheral/base.py"], "/systemonachip/test/test_periph_sram.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/test/test_periph_serial.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/bus/__init__.py": ["/systemonachip/bus/decoder.py"], "/systemonachip/cpu/minerva.py": ["/systemonachip/cpu/__init__.py"]}
16,231,496
systemonachip/systemonachip
refs/heads/main
/systemonachip/register/event.py
"""Event related registers""" from .base import AutoRegister class AggregateEventEnable(AutoRegister): def __init__(self, address): pass class AggregateEventStatus(AutoRegister): def __init__(self, address): pass
{"/systemonachip/test/test_periph_timer.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/test/test_periph_base.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/register/readwrite.py": ["/systemonachip/register/base.py"], "/systemonachip/peripheral/timer.py": ["/systemonachip/peripheral/__init__.py", "/systemonachip/event/__init__.py", "/systemonachip/register/__init__.py"], "/systemonachip/soc/cpu.py": ["/systemonachip/soc/base.py", "/systemonachip/cpu/__init__.py", "/systemonachip/peripheral/memory.py", "/systemonachip/peripheral/timer.py"], "/systemonachip/peripheral/base.py": ["/systemonachip/register/__init__.py", "/systemonachip/event/__init__.py"], "/systemonachip/register/__init__.py": ["/systemonachip/register/static.py", "/systemonachip/register/readwrite.py", "/systemonachip/register/config.py", "/systemonachip/register/variable.py", "/systemonachip/register/event.py"], "/systemonachip/register/event.py": ["/systemonachip/register/base.py"], "/systemonachip/soc/base.py": ["/systemonachip/peripheral/__init__.py"], "/examples/basic.py": ["/systemonachip/bus/decoder.py", "/systemonachip/cpu/minerva.py", "/systemonachip/peripheral/memory.py", "/systemonachip/peripheral/timer.py", "/systemonachip/soc/cpu.py"], "/systemonachip/peripheral/__init__.py": ["/systemonachip/peripheral/base.py"], "/systemonachip/test/test_periph_sram.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/test/test_periph_serial.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/bus/__init__.py": ["/systemonachip/bus/decoder.py"], "/systemonachip/cpu/minerva.py": ["/systemonachip/cpu/__init__.py"]}
16,231,497
systemonachip/systemonachip
refs/heads/main
/systemonachip/register/variable.py
"""Dynamically sized registers""" from nmigen_soc import csr from nmigen import Record class VariableWidth: def __init__(self, address, *, variable="_width"): """Variable width register that depends on instance state in the given `variable`. `variable` must start with `_` so it doesn't conflict with the register.""" self._address = address self._width_variable = variable def __set_name__(self, owner, name): self._name = name def __get__(self, obj, type=None): if obj == None: return self if isinstance(obj._memory_window, Record): key = (self._address, None) if not hasattr(obj, "_csr"): obj._csr = {} elif key in obj._csr: return obj._csr[key] elem = csr.Element(getattr(obj, self._width_variable), "rw", name=self._name) obj._csr[key] = elem return elem return obj._memory_window[self._address] def __set__(self, obj, value): if not isinstance(obj._memory_window, Record): obj._memory_window[self._address] = value return raise RuntimeError("Cannot set value when elaborating")
{"/systemonachip/test/test_periph_timer.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/test/test_periph_base.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/register/readwrite.py": ["/systemonachip/register/base.py"], "/systemonachip/peripheral/timer.py": ["/systemonachip/peripheral/__init__.py", "/systemonachip/event/__init__.py", "/systemonachip/register/__init__.py"], "/systemonachip/soc/cpu.py": ["/systemonachip/soc/base.py", "/systemonachip/cpu/__init__.py", "/systemonachip/peripheral/memory.py", "/systemonachip/peripheral/timer.py"], "/systemonachip/peripheral/base.py": ["/systemonachip/register/__init__.py", "/systemonachip/event/__init__.py"], "/systemonachip/register/__init__.py": ["/systemonachip/register/static.py", "/systemonachip/register/readwrite.py", "/systemonachip/register/config.py", "/systemonachip/register/variable.py", "/systemonachip/register/event.py"], "/systemonachip/register/event.py": ["/systemonachip/register/base.py"], "/systemonachip/soc/base.py": ["/systemonachip/peripheral/__init__.py"], "/examples/basic.py": ["/systemonachip/bus/decoder.py", "/systemonachip/cpu/minerva.py", "/systemonachip/peripheral/memory.py", "/systemonachip/peripheral/timer.py", "/systemonachip/soc/cpu.py"], "/systemonachip/peripheral/__init__.py": ["/systemonachip/peripheral/base.py"], "/systemonachip/test/test_periph_sram.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/test/test_periph_serial.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/bus/__init__.py": ["/systemonachip/bus/decoder.py"], "/systemonachip/cpu/minerva.py": ["/systemonachip/cpu/__init__.py"]}
16,231,498
systemonachip/systemonachip
refs/heads/main
/systemonachip/soc/base.py
import os import re import textwrap import jinja2 from nmigen import tracer from nmigen_soc.memory import MemoryMap from nmigen.build.run import * from .. import software from ..peripheral import Peripheral __all__ = ["socproperty", "SoC", "ConfigBuilder"] def socproperty(cls, src_loc_at=0): name = tracer.get_var_name(depth=2 + src_loc_at) __name = "__{}".format(name) def getter(self): assert isinstance(self, SoC) attr = getattr(self, __name, None) if attr is None: raise NotImplementedError("SoC {!r} does not have a {}" .format(self, name)) return attr def setter(self, value): assert isinstance(self, SoC) if not isinstance(value, cls): raise TypeError("{} must be an instance of {}, not {!r}" .format(name, cls.__name__, value)) setattr(self, __name, value) return property(getter, setter) class SoC: memory_map = socproperty(MemoryMap) def build(self, build_dir="build/soc", do_build=True, name=None): plan = ConfigBuilder().prepare(self, build_dir, name) if not do_build: return plan products = plan.execute_local(build_dir) return products class ConfigBuilder: file_templates = { "build_{{name}}.sh": r""" # {{autogenerated}} set -e {{emit_commands()}} """, "{{name}}_resources.csv": r""" # {{autogenerated}} # <resource name>, <start address>, <end address>, <access width> {% for resource, (start, end, width) in soc.memory_map.all_resources() -%} {{resource.name}}, {{hex(start)}}, {{hex(end)}}, {{width}} {% endfor %} """, } command_templates = [] def prepare(self, soc, build_dir, name): name = name or type(soc).__name__.lower() autogenerated = "Automatically generated by LambdaSoC {}. Do not edit.".format(0) def periph_addr(periph): print("p", periph) assert isinstance(periph, Peripheral) periph_map = periph.bus.memory_map for window, (start, end, ratio) in soc.memory_map.windows(): if periph_map is window: return start raise KeyError(periph) def periph_csrs(periph): assert isinstance(periph, Peripheral) periph_map = periph.bus.memory_map for resource, (start, end, width) in periph_map.all_resources(): if isinstance(resource, csr.Element): yield resource, (start, end, width) def emit_commands(): commands = [] for index, command_tpl in enumerate(self.command_templates): command = render(command_tpl, origin="<command#{}>".format(index + 1)) command = re.sub(r"\s+", " ", command) commands.append(command) return "\n".join(commands) def render(source, origin): print(source) try: source = textwrap.dedent(source).strip() compiled = jinja2.Template(source, trim_blocks=True, lstrip_blocks=True) except jinja2.TemplateSyntaxError as e: e.args = ("{} (at {}:{})".format(e.message, origin, e.lineno),) raise return compiled.render({ "autogenerated": autogenerated, "build_dir": os.path.abspath(build_dir), "emit_commands": emit_commands, "hex": hex, "name": name, "periph_addr": periph_addr, "periph_csrs": periph_csrs, "soc": soc, "software_dir": os.path.dirname(software.__file__), }) plan = BuildPlan(script="build_{}".format(name)) for filename_tpl, content_tpl in self.file_templates.items(): plan.add_file(render(filename_tpl, origin=filename_tpl), render(content_tpl, origin=content_tpl)) return plan
{"/systemonachip/test/test_periph_timer.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/test/test_periph_base.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/register/readwrite.py": ["/systemonachip/register/base.py"], "/systemonachip/peripheral/timer.py": ["/systemonachip/peripheral/__init__.py", "/systemonachip/event/__init__.py", "/systemonachip/register/__init__.py"], "/systemonachip/soc/cpu.py": ["/systemonachip/soc/base.py", "/systemonachip/cpu/__init__.py", "/systemonachip/peripheral/memory.py", "/systemonachip/peripheral/timer.py"], "/systemonachip/peripheral/base.py": ["/systemonachip/register/__init__.py", "/systemonachip/event/__init__.py"], "/systemonachip/register/__init__.py": ["/systemonachip/register/static.py", "/systemonachip/register/readwrite.py", "/systemonachip/register/config.py", "/systemonachip/register/variable.py", "/systemonachip/register/event.py"], "/systemonachip/register/event.py": ["/systemonachip/register/base.py"], "/systemonachip/soc/base.py": ["/systemonachip/peripheral/__init__.py"], "/examples/basic.py": ["/systemonachip/bus/decoder.py", "/systemonachip/cpu/minerva.py", "/systemonachip/peripheral/memory.py", "/systemonachip/peripheral/timer.py", "/systemonachip/soc/cpu.py"], "/systemonachip/peripheral/__init__.py": ["/systemonachip/peripheral/base.py"], "/systemonachip/test/test_periph_sram.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/test/test_periph_serial.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/bus/__init__.py": ["/systemonachip/bus/decoder.py"], "/systemonachip/cpu/minerva.py": ["/systemonachip/cpu/__init__.py"]}
16,231,499
systemonachip/systemonachip
refs/heads/main
/examples/basic.py
import argparse import importlib from nmigen import * from nmigen_soc import wishbone from nmigen.back import verilog from systemonachip.bus.decoder import Decoder from systemonachip.bus.bridge import WishboneCSRBridge from systemonachip.cpu.minerva import MinervaCPU from systemonachip.peripheral.interrupt import GenericInterruptController from systemonachip.peripheral.serial import AsyncSerial from systemonachip.peripheral.memory import RandomAccessMemory from systemonachip.peripheral.timer import Timer from systemonachip.soc.cpu import CPUSoC __all__ = ["Basic"] class Basic(Elaboratable): def __init__(self, *, clock_frequency, rom_size, ram_size): self._arbiter = wishbone.Arbiter(addr_width=30, data_width=32, granularity=8, features={"cti", "bte"}) self.bus = wishbone.Interface(addr_width=30, data_width=32, granularity=8, features={"cti", "bte"}) self._decoder = Decoder(self.bus, 0x10000000) # Every 0x10000000 """Memory decoder that splits the 32-bit address space into 16 0x10000000 byte chunks. Each chunk can be passed into a sub-bus or peripheral.""" self.cpu = MinervaCPU(reset_address=0x00000000, instruction_bus=self._arbiter, data_bus=self._arbiter) """Central processing unit.""" self.rom = RandomAccessMemory(self._decoder[0x0], size=rom_size, writable=False) """Core read-only memory. At 0x00000000.""" self.ram = RandomAccessMemory(self._decoder[0x2], size=ram_size) """Single random access memory. At 0x20000000.""" # self.uart = AsyncSerial(self._decoder[0x3], divisor=uart_divisor, pins=uart_pins) """Simple async serial. At 0x30000000.""" self.timer_bus = WishboneCSRBridge(self._decoder[0x4]) self.timer = Timer(self.timer_bus.csr_bus, width=32) """Simple 32-bit timer. At 0x40000000.""" # self.intc = GenericInterruptController(width=len(self.cpu.ip)) # self.intc.add_irq(self.timer.irq, 0) # self.intc.add_irq(self.uart .irq, 1) self.memory_map = self._decoder.bus.memory_map self.clk_freq = clock_frequency def elaborate(self, platform): m = Module() for name in dir(self): attr = getattr(self, name) if isinstance(attr, Elaboratable): setattr(m.submodules, name, attr) # print(self._decoder.bus) m.d.comb += [ self._arbiter.bus.connect(self._decoder.bus), # self.cpu.ip.eq(self.intc.ip), ] return m if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("platform", type=str, help="target platform (e.g. 'nmigen_boards.arty_a7.ArtyA7Platform')") parser.add_argument("--baudrate", type=int, default=9600, help="UART baudrate (default: 9600)") args = parser.parse_args() def get_platform(platform_name): module_name, class_name = platform_name.rsplit(".", 1) module = importlib.import_module(name=module_name) platform_class = getattr(module, class_name) return platform_class() platform = get_platform(args.platform) uart_divisor = int(platform.default_clk_frequency // args.baudrate) #uart_pins = platform.request("uart", 0) soc = Basic(clock_frequency=int(platform.default_clk_frequency), rom_size=0x4000,ram_size=0x1000) with open("basic_soc.v", "w") as f: f.write(verilog.convert(soc)) platform.build(soc)
{"/systemonachip/test/test_periph_timer.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/test/test_periph_base.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/register/readwrite.py": ["/systemonachip/register/base.py"], "/systemonachip/peripheral/timer.py": ["/systemonachip/peripheral/__init__.py", "/systemonachip/event/__init__.py", "/systemonachip/register/__init__.py"], "/systemonachip/soc/cpu.py": ["/systemonachip/soc/base.py", "/systemonachip/cpu/__init__.py", "/systemonachip/peripheral/memory.py", "/systemonachip/peripheral/timer.py"], "/systemonachip/peripheral/base.py": ["/systemonachip/register/__init__.py", "/systemonachip/event/__init__.py"], "/systemonachip/register/__init__.py": ["/systemonachip/register/static.py", "/systemonachip/register/readwrite.py", "/systemonachip/register/config.py", "/systemonachip/register/variable.py", "/systemonachip/register/event.py"], "/systemonachip/register/event.py": ["/systemonachip/register/base.py"], "/systemonachip/soc/base.py": ["/systemonachip/peripheral/__init__.py"], "/examples/basic.py": ["/systemonachip/bus/decoder.py", "/systemonachip/cpu/minerva.py", "/systemonachip/peripheral/memory.py", "/systemonachip/peripheral/timer.py", "/systemonachip/soc/cpu.py"], "/systemonachip/peripheral/__init__.py": ["/systemonachip/peripheral/base.py"], "/systemonachip/test/test_periph_sram.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/test/test_periph_serial.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/bus/__init__.py": ["/systemonachip/bus/decoder.py"], "/systemonachip/cpu/minerva.py": ["/systemonachip/cpu/__init__.py"]}
16,231,500
systemonachip/systemonachip
refs/heads/main
/setup.py
from setuptools import setup, find_packages def scm_version(): def local_scheme(version): if version.tag and not version.distance: return version.format_with("") else: return version.format_choice("+{node}", "+{node}.dirty") return { "relative_to": __file__, "version_scheme": "guess-next-dev", "local_scheme": local_scheme } setup( name="systemonachip", use_scm_version=scm_version(), author="Scott Shawcroft", author_email="scott@chickadee.tech", description="A framework for building system-on-a-chips with nMigen", #long_description="""TODO""", license="BSD", setup_requires=["setuptools_scm"], install_requires=[ "nmigen>=0.1,<0.3", ], packages=find_packages(), include_package_data=True, project_urls={ "Source Code": "https://github.com/tannewt/systemonachip", "Bug Tracker": "https://github.com/tannwet/systemonachip/issues", }, )
{"/systemonachip/test/test_periph_timer.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/test/test_periph_base.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/register/readwrite.py": ["/systemonachip/register/base.py"], "/systemonachip/peripheral/timer.py": ["/systemonachip/peripheral/__init__.py", "/systemonachip/event/__init__.py", "/systemonachip/register/__init__.py"], "/systemonachip/soc/cpu.py": ["/systemonachip/soc/base.py", "/systemonachip/cpu/__init__.py", "/systemonachip/peripheral/memory.py", "/systemonachip/peripheral/timer.py"], "/systemonachip/peripheral/base.py": ["/systemonachip/register/__init__.py", "/systemonachip/event/__init__.py"], "/systemonachip/register/__init__.py": ["/systemonachip/register/static.py", "/systemonachip/register/readwrite.py", "/systemonachip/register/config.py", "/systemonachip/register/variable.py", "/systemonachip/register/event.py"], "/systemonachip/register/event.py": ["/systemonachip/register/base.py"], "/systemonachip/soc/base.py": ["/systemonachip/peripheral/__init__.py"], "/examples/basic.py": ["/systemonachip/bus/decoder.py", "/systemonachip/cpu/minerva.py", "/systemonachip/peripheral/memory.py", "/systemonachip/peripheral/timer.py", "/systemonachip/soc/cpu.py"], "/systemonachip/peripheral/__init__.py": ["/systemonachip/peripheral/base.py"], "/systemonachip/test/test_periph_sram.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/test/test_periph_serial.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/bus/__init__.py": ["/systemonachip/bus/decoder.py"], "/systemonachip/cpu/minerva.py": ["/systemonachip/cpu/__init__.py"]}
16,231,501
systemonachip/systemonachip
refs/heads/main
/systemonachip/cpu/__init__.py
from abc import ABCMeta, abstractproperty __all__ = ["CPU"] class CPU(metaclass=ABCMeta): """TODO """ name = abstractproperty() arch = abstractproperty() byteorder = abstractproperty() data_width = abstractproperty() reset_addr = abstractproperty() muldiv = abstractproperty()
{"/systemonachip/test/test_periph_timer.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/test/test_periph_base.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/register/readwrite.py": ["/systemonachip/register/base.py"], "/systemonachip/peripheral/timer.py": ["/systemonachip/peripheral/__init__.py", "/systemonachip/event/__init__.py", "/systemonachip/register/__init__.py"], "/systemonachip/soc/cpu.py": ["/systemonachip/soc/base.py", "/systemonachip/cpu/__init__.py", "/systemonachip/peripheral/memory.py", "/systemonachip/peripheral/timer.py"], "/systemonachip/peripheral/base.py": ["/systemonachip/register/__init__.py", "/systemonachip/event/__init__.py"], "/systemonachip/register/__init__.py": ["/systemonachip/register/static.py", "/systemonachip/register/readwrite.py", "/systemonachip/register/config.py", "/systemonachip/register/variable.py", "/systemonachip/register/event.py"], "/systemonachip/register/event.py": ["/systemonachip/register/base.py"], "/systemonachip/soc/base.py": ["/systemonachip/peripheral/__init__.py"], "/examples/basic.py": ["/systemonachip/bus/decoder.py", "/systemonachip/cpu/minerva.py", "/systemonachip/peripheral/memory.py", "/systemonachip/peripheral/timer.py", "/systemonachip/soc/cpu.py"], "/systemonachip/peripheral/__init__.py": ["/systemonachip/peripheral/base.py"], "/systemonachip/test/test_periph_sram.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/test/test_periph_serial.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/bus/__init__.py": ["/systemonachip/bus/decoder.py"], "/systemonachip/cpu/minerva.py": ["/systemonachip/cpu/__init__.py"]}
16,231,502
systemonachip/systemonachip
refs/heads/main
/systemonachip/peripheral/__init__.py
from .base import * from .event import *
{"/systemonachip/test/test_periph_timer.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/test/test_periph_base.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/register/readwrite.py": ["/systemonachip/register/base.py"], "/systemonachip/peripheral/timer.py": ["/systemonachip/peripheral/__init__.py", "/systemonachip/event/__init__.py", "/systemonachip/register/__init__.py"], "/systemonachip/soc/cpu.py": ["/systemonachip/soc/base.py", "/systemonachip/cpu/__init__.py", "/systemonachip/peripheral/memory.py", "/systemonachip/peripheral/timer.py"], "/systemonachip/peripheral/base.py": ["/systemonachip/register/__init__.py", "/systemonachip/event/__init__.py"], "/systemonachip/register/__init__.py": ["/systemonachip/register/static.py", "/systemonachip/register/readwrite.py", "/systemonachip/register/config.py", "/systemonachip/register/variable.py", "/systemonachip/register/event.py"], "/systemonachip/register/event.py": ["/systemonachip/register/base.py"], "/systemonachip/soc/base.py": ["/systemonachip/peripheral/__init__.py"], "/examples/basic.py": ["/systemonachip/bus/decoder.py", "/systemonachip/cpu/minerva.py", "/systemonachip/peripheral/memory.py", "/systemonachip/peripheral/timer.py", "/systemonachip/soc/cpu.py"], "/systemonachip/peripheral/__init__.py": ["/systemonachip/peripheral/base.py"], "/systemonachip/test/test_periph_sram.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/test/test_periph_serial.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/bus/__init__.py": ["/systemonachip/bus/decoder.py"], "/systemonachip/cpu/minerva.py": ["/systemonachip/cpu/__init__.py"]}
16,231,503
systemonachip/systemonachip
refs/heads/main
/systemonachip/register/config.py
"""Static variable dependent on instance state.""" class Config: def __init__(self, address, variable): pass
{"/systemonachip/test/test_periph_timer.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/test/test_periph_base.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/register/readwrite.py": ["/systemonachip/register/base.py"], "/systemonachip/peripheral/timer.py": ["/systemonachip/peripheral/__init__.py", "/systemonachip/event/__init__.py", "/systemonachip/register/__init__.py"], "/systemonachip/soc/cpu.py": ["/systemonachip/soc/base.py", "/systemonachip/cpu/__init__.py", "/systemonachip/peripheral/memory.py", "/systemonachip/peripheral/timer.py"], "/systemonachip/peripheral/base.py": ["/systemonachip/register/__init__.py", "/systemonachip/event/__init__.py"], "/systemonachip/register/__init__.py": ["/systemonachip/register/static.py", "/systemonachip/register/readwrite.py", "/systemonachip/register/config.py", "/systemonachip/register/variable.py", "/systemonachip/register/event.py"], "/systemonachip/register/event.py": ["/systemonachip/register/base.py"], "/systemonachip/soc/base.py": ["/systemonachip/peripheral/__init__.py"], "/examples/basic.py": ["/systemonachip/bus/decoder.py", "/systemonachip/cpu/minerva.py", "/systemonachip/peripheral/memory.py", "/systemonachip/peripheral/timer.py", "/systemonachip/soc/cpu.py"], "/systemonachip/peripheral/__init__.py": ["/systemonachip/peripheral/base.py"], "/systemonachip/test/test_periph_sram.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/test/test_periph_serial.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/bus/__init__.py": ["/systemonachip/bus/decoder.py"], "/systemonachip/cpu/minerva.py": ["/systemonachip/cpu/__init__.py"]}
16,231,504
systemonachip/systemonachip
refs/heads/main
/systemonachip/test/test_periph_sram.py
#nmigen: UnusedElaboratable=no import unittest from nmigen import * from nmigen.utils import log2_int from nmigen.back.pysim import * from nmigen_soc.wishbone import CycleType, BurstTypeExt from ._wishbone import * from ..periph.sram import SRAMPeripheral def simulation_test(dut, process): with Simulator(dut, vcd_file=open("test.vcd", "w")) as sim: sim.add_clock(1e-6) sim.add_sync_process(process) sim.run() def _burst_type(wrap): if wrap == 0: return BurstTypeExt.LINEAR if wrap == 4: return BurstTypeExt.WRAP_4 if wrap == 8: return BurstTypeExt.WRAP_8 if wrap == 16: return BurstTypeExt.WRAP_16 assert False class SRAMPeripheralTestCase(unittest.TestCase): def read_incr(self, dut, *, addr, count, wrap=0): # FIXME clean data = [] yield dut.bus.cyc.eq(1) yield dut.bus.stb.eq(1) yield dut.bus.adr.eq(addr) yield dut.bus.bte.eq(_burst_type(wrap)) yield dut.bus.cti.eq(CycleType.END_OF_BURST if count == 0 else CycleType.INCR_BURST) yield self.assertFalse((yield dut.bus.ack)) for i in range(count): yield self.assertTrue((yield dut.bus.ack)) data.append((yield dut.bus.dat_r)) if wrap == 0: yield dut.bus.adr.eq((yield dut.bus.adr) + 1) else: yield dut.bus.adr[:log2_int(wrap)].eq((yield dut.bus.adr[:log2_int(wrap)]) + 1) yield dut.bus.cti.eq(CycleType.END_OF_BURST if i == count-1 else CycleType.INCR_BURST) yield dut.bus.cyc.eq(0) yield dut.bus.stb.eq(0) return data def test_bus(self): dut = SRAMPeripheral(size=16, data_width=32, granularity=8) self.assertEqual(dut.bus.addr_width, 2) self.assertEqual(dut.bus.data_width, 32) self.assertEqual(dut.bus.granularity, 8) def test_invalid_size(self): with self.assertRaisesRegex(ValueError, r"Size must be an integer power of two, not 'foo'"): dut = SRAMPeripheral(size='foo') with self.assertRaisesRegex(ValueError, r"Size must be an integer power of two, not 3"): dut = SRAMPeripheral(size=3) def test_invalid_size_ratio(self): with self.assertRaisesRegex(ValueError, r"Size 2 cannot be lesser than the data width/granularity ratio of " r"4 \(32 / 8\)"): dut = SRAMPeripheral(size=2, data_width=32, granularity=8) def test_read(self): dut = SRAMPeripheral(size=4, data_width=8, writable=False) dut.init = [0x00, 0x01, 0x02, 0x03] def process(): for i in range(4): data = (yield from wb_read(dut.bus, addr=i, sel=1)) self.assertEqual(data, dut.init[i]) yield simulation_test(dut, process) def test_read_incr_linear(self): dut = SRAMPeripheral(size=8, data_width=8, writable=False) dut.init = [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07] def process(): data = (yield from self.read_incr(dut, addr=0x00, count=6)) self.assertEqual(data, dut.init[:6]) yield data = (yield from self.read_incr(dut, addr=0x06, count=2)) self.assertEqual(data, dut.init[6:]) simulation_test(dut, process) def test_read_incr_wrap_4(self): dut = SRAMPeripheral(size=8, data_width=8, writable=False) dut.init = [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07] def process(): data = (yield from self.read_incr(dut, addr=0x01, count=8, wrap=4)) self.assertEqual(data, 2*(dut.init[1:4] + [dut.init[0]])) simulation_test(dut, process) def test_read_incr_wrap_8(self): dut = SRAMPeripheral(size=8, data_width=8, writable=False) dut.init = [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07] def process(): data = (yield from self.read_incr(dut, addr=0x06, count=16, wrap=8)) self.assertEqual(data, 2*(dut.init[6:] + dut.init[:6])) simulation_test(dut, process) def test_read_incr_wrap_16(self): dut = SRAMPeripheral(size=16, data_width=8, writable=False) dut.init = [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f] def process(): data = (yield from self.read_incr(dut, addr=0x06, count=32, wrap=16)) self.assertEqual(data, 2*(dut.init[6:] + dut.init[:6])) simulation_test(dut, process) def test_write(self): dut = SRAMPeripheral(size=4, data_width=8) def process(): data = [0x00, 0x01, 0x02, 0x03] for i in range(len(data)): yield from wb_write(dut.bus, addr=i, data=data[i], sel=1) yield for i in range(len(data)): b = yield from wb_read(dut.bus, addr=i, sel=1) yield self.assertEqual(b, data[i]) simulation_test(dut, process) def test_write_sel(self): dut = SRAMPeripheral(size=4, data_width=16, granularity=8) def process(): yield from wb_write(dut.bus, addr=0x0, data=0x5aa5, sel=0b01) yield yield from wb_write(dut.bus, addr=0x1, data=0x5aa5, sel=0b10) yield self.assertEqual((yield from wb_read(dut.bus, addr=0x0, sel=1)), 0x00a5) yield self.assertEqual((yield from wb_read(dut.bus, addr=0x1, sel=1)), 0x5a00) simulation_test(dut, process) # TODO test write bursts
{"/systemonachip/test/test_periph_timer.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/test/test_periph_base.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/register/readwrite.py": ["/systemonachip/register/base.py"], "/systemonachip/peripheral/timer.py": ["/systemonachip/peripheral/__init__.py", "/systemonachip/event/__init__.py", "/systemonachip/register/__init__.py"], "/systemonachip/soc/cpu.py": ["/systemonachip/soc/base.py", "/systemonachip/cpu/__init__.py", "/systemonachip/peripheral/memory.py", "/systemonachip/peripheral/timer.py"], "/systemonachip/peripheral/base.py": ["/systemonachip/register/__init__.py", "/systemonachip/event/__init__.py"], "/systemonachip/register/__init__.py": ["/systemonachip/register/static.py", "/systemonachip/register/readwrite.py", "/systemonachip/register/config.py", "/systemonachip/register/variable.py", "/systemonachip/register/event.py"], "/systemonachip/register/event.py": ["/systemonachip/register/base.py"], "/systemonachip/soc/base.py": ["/systemonachip/peripheral/__init__.py"], "/examples/basic.py": ["/systemonachip/bus/decoder.py", "/systemonachip/cpu/minerva.py", "/systemonachip/peripheral/memory.py", "/systemonachip/peripheral/timer.py", "/systemonachip/soc/cpu.py"], "/systemonachip/peripheral/__init__.py": ["/systemonachip/peripheral/base.py"], "/systemonachip/test/test_periph_sram.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/test/test_periph_serial.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/bus/__init__.py": ["/systemonachip/bus/decoder.py"], "/systemonachip/cpu/minerva.py": ["/systemonachip/cpu/__init__.py"]}
16,231,505
systemonachip/systemonachip
refs/heads/main
/systemonachip/bus/decoder.py
import math from nmigen_soc import wishbone from nmigen_soc import memory class DecoderWindow: def __init__(self, parent_window, address, bin_size): self._parent = parent_window self._address = address self._bin_size = bin_size def __getitem__(self, index): if index > bin_size or index < -bin_size: raise IndexError() if index < 0: index += bin_size return self._parent[self._address + index] def __setitem__(self, index, value): if index > bin_size or index < -bin_size: raise IndexError() if index < 0: index += bin_size self._parent[self._address + index] = value class Decoder(wishbone.Decoder): """A decoder splits the incoming address space into evenly spaced chunks of the given window_size. Each chunk is accessible by index.""" def __init__(self, memory_window, window_size, *, cycle_type=True, burst_type=True): self.features = [] if cycle_type: self.features.append("cti") if burst_type: self.features.append("bte") super().__init__(addr_width=memory_window.addr_width, data_width=memory_window.data_width, features=self.features) self.memory_window_bits = 32 self.start_address = 0 self.bin_size = window_size self._sub_bus_address_bits = int(math.log2(window_size)) self._bins = [None] * (2 ** (self.memory_window_bits - self._sub_bus_address_bits)) self._memory_window = memory_window def __getitem__(self, index): if index > len(self._bins): raise IndexError("Invalid bin") if self._bins[index]: return self._bins[index] bin_address = self.start_address + index * self.bin_size if isinstance(self._memory_window, wishbone.Interface): window = wishbone.Interface(addr_width=self._sub_bus_address_bits, data_width=self._memory_window.data_width, features=self.features) window.memory_map = memory.MemoryMap(addr_width=self._sub_bus_address_bits, data_width=self._memory_window.data_width) self.add(window, addr=bin_address, extend=True) else: window = DecoderWindow(self._memory_window, bin_address, self.bin_size) self._bins[index] = window return window
{"/systemonachip/test/test_periph_timer.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/test/test_periph_base.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/register/readwrite.py": ["/systemonachip/register/base.py"], "/systemonachip/peripheral/timer.py": ["/systemonachip/peripheral/__init__.py", "/systemonachip/event/__init__.py", "/systemonachip/register/__init__.py"], "/systemonachip/soc/cpu.py": ["/systemonachip/soc/base.py", "/systemonachip/cpu/__init__.py", "/systemonachip/peripheral/memory.py", "/systemonachip/peripheral/timer.py"], "/systemonachip/peripheral/base.py": ["/systemonachip/register/__init__.py", "/systemonachip/event/__init__.py"], "/systemonachip/register/__init__.py": ["/systemonachip/register/static.py", "/systemonachip/register/readwrite.py", "/systemonachip/register/config.py", "/systemonachip/register/variable.py", "/systemonachip/register/event.py"], "/systemonachip/register/event.py": ["/systemonachip/register/base.py"], "/systemonachip/soc/base.py": ["/systemonachip/peripheral/__init__.py"], "/examples/basic.py": ["/systemonachip/bus/decoder.py", "/systemonachip/cpu/minerva.py", "/systemonachip/peripheral/memory.py", "/systemonachip/peripheral/timer.py", "/systemonachip/soc/cpu.py"], "/systemonachip/peripheral/__init__.py": ["/systemonachip/peripheral/base.py"], "/systemonachip/test/test_periph_sram.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/test/test_periph_serial.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/bus/__init__.py": ["/systemonachip/bus/decoder.py"], "/systemonachip/cpu/minerva.py": ["/systemonachip/cpu/__init__.py"]}
16,231,506
systemonachip/systemonachip
refs/heads/main
/systemonachip/event/__init__.py
from nmigen import Record, Signal class Event: def __init__(self, address, bit, *, mode="rise"): self._address = address self._mode = mode self._bit = bit def __set_name__(self, owner, name): self._name = name def __get__(self, obj, type=None): if obj == None: return self if isinstance(obj._memory_window, Record): key = (self._bit, self._mode) if not hasattr(obj, "_events"): obj._events = {} elif key in obj._events: return obj._events[key] event = Signal(name="{}_stb".format(self._name)) obj._events[key] = event return event return (obj._memory_window[self._address] & (1 << self._bit)) != 0 class AggregateEvent: pass
{"/systemonachip/test/test_periph_timer.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/test/test_periph_base.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/register/readwrite.py": ["/systemonachip/register/base.py"], "/systemonachip/peripheral/timer.py": ["/systemonachip/peripheral/__init__.py", "/systemonachip/event/__init__.py", "/systemonachip/register/__init__.py"], "/systemonachip/soc/cpu.py": ["/systemonachip/soc/base.py", "/systemonachip/cpu/__init__.py", "/systemonachip/peripheral/memory.py", "/systemonachip/peripheral/timer.py"], "/systemonachip/peripheral/base.py": ["/systemonachip/register/__init__.py", "/systemonachip/event/__init__.py"], "/systemonachip/register/__init__.py": ["/systemonachip/register/static.py", "/systemonachip/register/readwrite.py", "/systemonachip/register/config.py", "/systemonachip/register/variable.py", "/systemonachip/register/event.py"], "/systemonachip/register/event.py": ["/systemonachip/register/base.py"], "/systemonachip/soc/base.py": ["/systemonachip/peripheral/__init__.py"], "/examples/basic.py": ["/systemonachip/bus/decoder.py", "/systemonachip/cpu/minerva.py", "/systemonachip/peripheral/memory.py", "/systemonachip/peripheral/timer.py", "/systemonachip/soc/cpu.py"], "/systemonachip/peripheral/__init__.py": ["/systemonachip/peripheral/base.py"], "/systemonachip/test/test_periph_sram.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/test/test_periph_serial.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/bus/__init__.py": ["/systemonachip/bus/decoder.py"], "/systemonachip/cpu/minerva.py": ["/systemonachip/cpu/__init__.py"]}
16,231,507
systemonachip/systemonachip
refs/heads/main
/systemonachip/test/test_periph_serial.py
import unittest from nmigen import * from nmigen.lib.io import pin_layout from nmigen.back.pysim import * from ._wishbone import * from ..periph.serial import AsyncSerialPeripheral divisor_addr = 0x00 >> 2 rx_data_addr = 0x04 >> 2 rx_rdy_addr = 0x08 >> 2 rx_err_addr = 0x0c >> 2 tx_data_addr = 0x10 >> 2 tx_rdy_addr = 0x14 >> 2 ev_status_addr = 0x20 >> 2 ev_pending_addr = 0x24 >> 2 ev_enable_addr = 0x28 >> 2 class AsyncSerialPeripheralTestCase(unittest.TestCase): def test_loopback(self): pins = Record([("rx", pin_layout(1, dir="i")), ("tx", pin_layout(1, dir="o"))]) dut = AsyncSerialPeripheral(divisor=5, pins=pins) m = Module() m.submodules.serial = dut m.d.comb += pins.rx.i.eq(pins.tx.o) def process(): # enable rx_rdy event yield from wb_write(dut.bus, addr=ev_enable_addr, data=0b001, sel=0xf) yield tx_rdy = yield from wb_read(dut.bus, addr=tx_rdy_addr, sel=0xf) self.assertEqual(tx_rdy, 1) yield yield from wb_write(dut.bus, addr=tx_data_addr, data=0xab, sel=0xf) yield for i in range(10): yield self.assertTrue((yield dut.irq)) rx_rdy = yield from wb_read(dut.bus, addr=rx_rdy_addr, sel=0xf) self.assertEqual(rx_rdy, 1) yield rx_data = yield from wb_read(dut.bus, addr=rx_data_addr, sel=0xf) self.assertEqual(rx_data, 0xab) yield with Simulator(m, vcd_file=open("test.vcd", "w")) as sim: sim.add_clock(1e-6) sim.add_sync_process(process) sim.run()
{"/systemonachip/test/test_periph_timer.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/test/test_periph_base.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/register/readwrite.py": ["/systemonachip/register/base.py"], "/systemonachip/peripheral/timer.py": ["/systemonachip/peripheral/__init__.py", "/systemonachip/event/__init__.py", "/systemonachip/register/__init__.py"], "/systemonachip/soc/cpu.py": ["/systemonachip/soc/base.py", "/systemonachip/cpu/__init__.py", "/systemonachip/peripheral/memory.py", "/systemonachip/peripheral/timer.py"], "/systemonachip/peripheral/base.py": ["/systemonachip/register/__init__.py", "/systemonachip/event/__init__.py"], "/systemonachip/register/__init__.py": ["/systemonachip/register/static.py", "/systemonachip/register/readwrite.py", "/systemonachip/register/config.py", "/systemonachip/register/variable.py", "/systemonachip/register/event.py"], "/systemonachip/register/event.py": ["/systemonachip/register/base.py"], "/systemonachip/soc/base.py": ["/systemonachip/peripheral/__init__.py"], "/examples/basic.py": ["/systemonachip/bus/decoder.py", "/systemonachip/cpu/minerva.py", "/systemonachip/peripheral/memory.py", "/systemonachip/peripheral/timer.py", "/systemonachip/soc/cpu.py"], "/systemonachip/peripheral/__init__.py": ["/systemonachip/peripheral/base.py"], "/systemonachip/test/test_periph_sram.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/test/test_periph_serial.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/bus/__init__.py": ["/systemonachip/bus/decoder.py"], "/systemonachip/cpu/minerva.py": ["/systemonachip/cpu/__init__.py"]}
16,231,508
systemonachip/systemonachip
refs/heads/main
/systemonachip/bus/__init__.py
from .decoder import *
{"/systemonachip/test/test_periph_timer.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/test/test_periph_base.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/register/readwrite.py": ["/systemonachip/register/base.py"], "/systemonachip/peripheral/timer.py": ["/systemonachip/peripheral/__init__.py", "/systemonachip/event/__init__.py", "/systemonachip/register/__init__.py"], "/systemonachip/soc/cpu.py": ["/systemonachip/soc/base.py", "/systemonachip/cpu/__init__.py", "/systemonachip/peripheral/memory.py", "/systemonachip/peripheral/timer.py"], "/systemonachip/peripheral/base.py": ["/systemonachip/register/__init__.py", "/systemonachip/event/__init__.py"], "/systemonachip/register/__init__.py": ["/systemonachip/register/static.py", "/systemonachip/register/readwrite.py", "/systemonachip/register/config.py", "/systemonachip/register/variable.py", "/systemonachip/register/event.py"], "/systemonachip/register/event.py": ["/systemonachip/register/base.py"], "/systemonachip/soc/base.py": ["/systemonachip/peripheral/__init__.py"], "/examples/basic.py": ["/systemonachip/bus/decoder.py", "/systemonachip/cpu/minerva.py", "/systemonachip/peripheral/memory.py", "/systemonachip/peripheral/timer.py", "/systemonachip/soc/cpu.py"], "/systemonachip/peripheral/__init__.py": ["/systemonachip/peripheral/base.py"], "/systemonachip/test/test_periph_sram.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/test/test_periph_serial.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/bus/__init__.py": ["/systemonachip/bus/decoder.py"], "/systemonachip/cpu/minerva.py": ["/systemonachip/cpu/__init__.py"]}
16,231,509
systemonachip/systemonachip
refs/heads/main
/systemonachip/cpu/minerva.py
from nmigen import * from nmigen_soc import wishbone from minerva.core import Minerva from . import CPU __all__ = ["MinervaCPU"] class MinervaCPU(CPU, Elaboratable): name = "minerva" arch = "riscv" byteorder = "little" data_width = 32 def __init__(self, instruction_bus, data_bus, **kwargs): super().__init__() self._cpu = Minerva(**kwargs) self.ibus = wishbone.Interface(addr_width=30, data_width=32, granularity=8, features={"err", "cti", "bte"}) self.dbus = wishbone.Interface(addr_width=30, data_width=32, granularity=8, features={"err", "cti", "bte"}) self.ip = Signal.like(self._cpu.external_interrupt) @property def reset_addr(self): return self._cpu.reset_address @property def muldiv(self): return "hard" if self._cpu.with_muldiv else "soft" def elaborate(self, platform): m = Module() m.submodules.minerva = self._cpu m.d.comb += [ self._cpu.ibus.connect(self.ibus), self._cpu.dbus.connect(self.dbus), self._cpu.external_interrupt.eq(self.ip), ] return m
{"/systemonachip/test/test_periph_timer.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/test/test_periph_base.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/register/readwrite.py": ["/systemonachip/register/base.py"], "/systemonachip/peripheral/timer.py": ["/systemonachip/peripheral/__init__.py", "/systemonachip/event/__init__.py", "/systemonachip/register/__init__.py"], "/systemonachip/soc/cpu.py": ["/systemonachip/soc/base.py", "/systemonachip/cpu/__init__.py", "/systemonachip/peripheral/memory.py", "/systemonachip/peripheral/timer.py"], "/systemonachip/peripheral/base.py": ["/systemonachip/register/__init__.py", "/systemonachip/event/__init__.py"], "/systemonachip/register/__init__.py": ["/systemonachip/register/static.py", "/systemonachip/register/readwrite.py", "/systemonachip/register/config.py", "/systemonachip/register/variable.py", "/systemonachip/register/event.py"], "/systemonachip/register/event.py": ["/systemonachip/register/base.py"], "/systemonachip/soc/base.py": ["/systemonachip/peripheral/__init__.py"], "/examples/basic.py": ["/systemonachip/bus/decoder.py", "/systemonachip/cpu/minerva.py", "/systemonachip/peripheral/memory.py", "/systemonachip/peripheral/timer.py", "/systemonachip/soc/cpu.py"], "/systemonachip/peripheral/__init__.py": ["/systemonachip/peripheral/base.py"], "/systemonachip/test/test_periph_sram.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/test/test_periph_serial.py": ["/systemonachip/test/_wishbone.py"], "/systemonachip/bus/__init__.py": ["/systemonachip/bus/decoder.py"], "/systemonachip/cpu/minerva.py": ["/systemonachip/cpu/__init__.py"]}
16,269,947
CeeEffEff/DQNExploration
refs/heads/main
/dqn_my_policy.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from tf_agents.policies import q_policy tf.compat.v1.enable_v2_behavior() from dqn_ma_env import TF_MAEnv from dqn_q_network import MyQNetwork class MyPolicy(q_policy.QPolicy): def __init__(self): tf_env = TF_MAEnv() action_spec = tf_env.action_spec() num_actions = action_spec.maximum - action_spec.minimum + 1 # As our action spec is defined on N observation_spec = tf_env.observation_spec() time_step_spec = tf_env.time_step_spec() my_q_network = MyQNetwork( input_tensor_spec=observation_spec, action_spec=action_spec, num_actions = num_actions) super().__init__(time_step_spec, action_spec, my_q_network)
{"/optuna_agent_driver.py": ["/dqn_agent_driver.py"], "/dqn_my_agent.py": ["/dqn_my_env.py"], "/test_agent_driver.py": ["/dqn_agent_driver.py"], "/dqn_agent_driver.py": ["/dqn_my_agent.py"]}
16,269,948
CeeEffEff/DQNExploration
refs/heads/main
/optuna_agent_driver.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import matplotlib.pyplot as plt import os from datetime import datetime import numpy as np import tensorflow as tf tf.compat.v1.enable_v2_behavior() from dqn_agent_driver import AgentDriver import optuna # Setup VISUALISATIONS_DIR = "visualisations" if not os.path.exists(VISUALISATIONS_DIR): os.makedirs(VISUALISATIONS_DIR) visual_subdir = os.path.join(VISUALISATIONS_DIR, datetime.now().strftime("%Y-%m-%d_%H-%M-%S")) if not os.path.exists(visual_subdir): os.makedirs(visual_subdir) graph_file_name_prefix = os.path.join(visual_subdir, "AverageReturn_") random_seed = 123123 n_trials = 100 # Debug input_bool = False input_frequency = 0 evaluate_before_train = False def pause_input(message:str, iteration:int): if input_frequency == 0: return if iteration % input_frequency == 0 and input_bool: input(message) def plot_average_returns(average_returns, iteration): plt.plot(average_returns) plt.title('Average Return of Target per Iteration') plt.xlabel('Iteration') plt.ylabel('Average Return') plt.savefig(f"{graph_file_name_prefix}__{iteration}.png") def objective(trail:optuna.Trial): # HYPER_PARAMETERS params = { #num_iterations = trail.suggest_int("num_iterations", 30, 100) "num_iterations" : 20, #num_collect_episodes = 10 "num_collect_episodes" : trail.suggest_int("num_collect_episodes", 2, 20), "num_eval_episodes" : 10, #"num_eval_episodes" : trail.suggest_int("num_eval_episodes", 2, 10), #replay_buffer_capacity = 10000 "replay_buffer_capacity" : trail.suggest_int("replay_buffer_capacity", 1000, 10000, step = 1000), #learning_rate = 0.0001 "learning_rate" : trail.suggest_float("learning_rate", 1e-6, 1e-1, log=True), #train_steps = 100 "train_steps" : trail.suggest_int("train_steps", 50, 500, step = 10), #sample_batch_size = 16 "sample_batch_size" : trail.suggest_int("sample_batch_size", 4, 128), # "fc_layer_units" : (20,10) # orig "fc_layer_units" : trail.suggest_int("fc_layer_units", 10, 30, 2), #fc_layer_depth "fc_layer_depth" : trail.suggest_int("fc_layer_depth", 1, 5) } return run_test(**params) def run_test(num_iterations, num_collect_episodes, num_eval_episodes, replay_buffer_capacity, learning_rate, train_steps, sample_batch_size, fc_layer_units, fc_layer_depth): iterations = list(range(0, num_iterations + 1)) average_returns = [] tf.random.set_seed(random_seed) np.random.seed(random_seed) driver = AgentDriver( num_collect_episodes=num_collect_episodes, num_eval_episodes=num_eval_episodes, replay_buffer_capacity=replay_buffer_capacity, learning_rate=learning_rate, fc_layer_units = fc_layer_units, fc_layer_depth = fc_layer_depth, verbose_env=True, show_summary=input_bool ) print("Initialising target...") _, average_return = driver.run_target(verbose=True) average_returns.append(average_return) if input_bool: input("Initialised, PRESS ENTER to continue") else: print("Initialised, PRESS ENTER to continue") for i in iterations[1:]: pause_input("Press ENTER to explore using collect policy", i) print("Iteration", i) print("Exploring...") driver.run_collect(verbose=True) if (evaluate_before_train): pause_input("Press ENTER to evaluate target before training", i) print("Before training, evaluating target...") driver.run_target(verbose=True) pause_input("Press ENTER to train", i) print("Training...") iteration_losses = driver.train_target(train_steps=train_steps, sample_batch_size=sample_batch_size, verbose=True) print() pause_input("Press ENTER to evaluate target after training", i) print("Evaluating target...") num_episodes, average_return = driver.run_target(verbose=True) pause_input("Press ENTER continue after the above evaluation", i) average_returns.append(average_return) plot_average_returns(average_returns, i) return average_return study = optuna.create_study(direction="maximize") study.optimize(objective, n_trials=n_trials) print(f"Optimised average return: {study.best_value}") with open(os.path.join(visual_subdir, "results.txt"), "w") as results_file: results_file.write(f"Best params: {study.best_params}\n") results_file.write(f"Best trial: {study.best_trial}\n") results_file.write(f"Best value: {study.best_value}\n") results_file.write(f"Param importances: {str(optuna.importance.get_param_importances(study))}") with open(os.path.join(visual_subdir, "results.csv"), "w") as results_file: results_file.write("study.best_params,study.best_trial,study.best_value,param_importances\n") results_file.write(f"{study.best_params},{study.best_trial},{study.best_value}, {str(optuna.importance.get_param_importances(study))}") input("Complete")
{"/optuna_agent_driver.py": ["/dqn_agent_driver.py"], "/dqn_my_agent.py": ["/dqn_my_env.py"], "/test_agent_driver.py": ["/dqn_agent_driver.py"], "/dqn_agent_driver.py": ["/dqn_my_agent.py"]}
16,269,949
CeeEffEff/DQNExploration
refs/heads/main
/dqn_my_env.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import abc import tensorflow as tf import numpy as np from tf_agents.environments import py_environment from tf_agents.environments import tf_environment from tf_agents.environments import tf_py_environment from tf_agents.environments import utils from tf_agents.specs import array_spec from tf_agents.environments import wrappers from tf_agents.environments import suite_gym from tf_agents.trajectories import time_step as ts tf.compat.v1.enable_v2_behavior() class MyPyEnv(py_environment.PyEnvironment): def __init__(self, verbose_env=False): super().__init__() self._action_spec = array_spec.BoundedArraySpec( shape=(), dtype=np.int32, minimum=0, maximum=2, name='action') self._num_prices = 5 np.random.seed(123123) #self.random_seed = random_seed self._observation_spec = { 'price':array_spec.BoundedArraySpec(shape=(self._num_prices,4), dtype=np.float64, minimum=0, name='obs_price'), 'pos':array_spec.BoundedArraySpec(shape=(2,), dtype=np.int32, minimum=0, maximum=1, name='obs_pos'), 'pos_price':array_spec.BoundedArraySpec(shape=(1,), dtype=np.float64, minimum=0, maximum=1, name='obs_pos_price'), 'time':array_spec.BoundedArraySpec(shape=(1,), dtype=np.int32, minimum=0, maximum=1, name='obs_time') } self.data_length = 1000 self.largest_av_length = 200 self.total_length = self.data_length + self.largest_av_length #price self.init_prices() #pos self._short_pos = np.int32(0) self._long_pos = np.int32(0) #time self._step_no = np.int32(0) self._bar_number = self._step_no + self._num_prices self.set_current_bar_prices() self.max_steps = 10 self._state = self.get_state() self._episode_ended = False self._epi_counter = 0 def set_current_bar_prices(self): index = self._bar_number self._price = self._prices[index] self._MA_slow = self._MA_slows[index] self._MA_fast = self._MA_fasts[index] self._MA_close = self._MA_closes[index] def init_prices(self): self._prices = np.empty(shape=(self.total_length,)) #self._prices[0] = np.random.uniform(low=0.0, high=100.0) self._prices[0] = np.random.uniform(low=200.0, high=300.0) self._MA_slows = np.zeros_like(self._prices) self._MA_fasts = np.zeros_like(self._prices) self._MA_closes = np.zeros_like(self._prices) #np.random.seed(self.random_seed) for time in range(1,self.total_length): #step = np.random.randint(0, high=2) step = np.random.randint(-1, high=1) self._prices[time] = self._prices[time - 1] + step if time > self.largest_av_length: self._MA_slows[time] = np.average(self._prices[time-self.largest_av_length:time]) self._MA_fasts[time] = np.average(self._prices[time-self.largest_av_length:time]) self._MA_closes[time] = np.average(self._prices[time-self.largest_av_length:time]) self._prices = self._prices[self.largest_av_length + 1:] self._MA_slows = self._MA_slows[self.largest_av_length + 1:] self._MA_fasts = self._MA_fasts[self.largest_av_length + 1:] self._MA_closes = self._MA_closes[self.largest_av_length + 1:] self._entry_price = np.float64(0) def get_state(self): return { 'price': np.array(list(zip(self._prices, self._MA_slows, self._MA_fasts, self._MA_closes))[self._bar_number-self._num_prices:self._bar_number], dtype=np.float64), 'pos': np.array([self._short_pos, self._long_pos], dtype=np.int32), 'pos_price': np.array([self._entry_price], dtype=np.float64), 'time': np.array([self._bar_number], dtype=np.int32) } def action_spec(self): return self._action_spec def observation_spec(self): return self._observation_spec def _reset(self): self.init_prices() self._short_pos = np.int32(0) self._long_pos = np.int32(0) self._step_no = np.int32(0) self._bar_number = self._step_no + self._num_prices self._state = self.get_state() # print("TO-DO: First state needs to be taken from data feed") self._episode_ended = False return ts.restart(self._state) def _step(self, action): if self._episode_ended: # The last action ended the episode. Ignore the current action and start # a new episode. return self.reset() if self._step_no == 0: self._epi_counter += 1 # Make sure episodes don't go on forever. # Say stop loss or end of day - we need to exit? forced_exit = self._check_exit_condition() if forced_exit: if self._long_pos == 1: # Long action = 2 # Sell elif self._short_pos == 1: # Short action = 0 # Buy to sell previous_price = self._price self.set_current_bar_prices() reward = 0 action_string = "" flat = False # DEBUG # if action == 0: # reward = 100 # elif action == 1: # reward = 25 # elif action == 2: # reward = -100 if action == 0: # Short or exit short (buy to sell) if self._short_pos == 0 and self._long_pos == 0: # Enter Short as no pos self._short_pos = 1 # record the price entered short on self._entry_price = self._price action_string = "Enter short" elif self._long_pos == 1: # Long, leave alone - flat action_string = "Flat" flat = True elif self._short_pos == 1: # Exit short (buy to sell) reward = self._entry_price - self._price self._short_pos = 0 action_string = "Buy to sell" self._entry_price = 0 elif action == 1: # Flat action_string = "Flat" flat = True elif action == 2: # Long or exit long (sell) if self._short_pos == 0 and self._long_pos == 0: # Enter Long as no pos self._long_pos = 1 # record the price entered Long on action_string = "Enter long" self._entry_price = self._price elif self._short_pos == 1: # Short, leave alone - flat action_string = "Flat" flat = True elif self._long_pos == 1: # exit long (sell) reward = self._price - self._entry_price self._long_pos = 0 self._entry_price = 0 action_string = "Sell" else: raise ValueError('`action` should be in [0,1,2].') if flat and (self._short_pos == 1 or self._long_pos == 1): reward = self._price - previous_price if self._short_pos: reward *= -1 print(f"[Episode {self._epi_counter }][{self._step_no}] Action: {action} {action_string} ", end="\r") self._step_no += 1 self._bar_number += 1 if self._episode_ended or forced_exit: # if forced_exit: # reward = abs(reward) * -1 # reward = 0 self._state = self.get_state() self.print_state(reward=reward, final=True) return ts.termination(self._state, reward) else: # Get next values for MA etc self._get_next_indicators() self._state = self.get_state() self.print_state(reward=reward) return ts.transition(self._state, reward=reward, discount=1.0) def _check_exit_condition(self): if self._step_no == self.max_steps or self._bar_number >= self.data_length - 1: self._episode_ended = True return True return False def _get_next_indicators(self): # print("TO-DO: Get next values for MA etc") return def reset_ep_counter(self): self._epi_counter = 0 def print_state(self, reward = None, final=False): if self._short_pos == 1: pos_string = "Short" elif self._long_pos == 1: pos_string = "Long" else: pos_string = "Flat" state_string = "\n" state_string += f"[step num: {self._step_no}]," state_string += f"[entry pos: {self._entry_price}]," state_string += f"[pos type: {pos_string}]," state_string += f"[mid price: {self._price}]," state_string += f"[MA slow: {self._MA_slow}]," state_string += f"[MA fast: {self._MA_fast}]," state_string += f"[MA close: {self._MA_close}]" if reward is not None: if final: state_string += f",[Final reward: {reward}]" else: state_string += f",[Step reward: {reward}]" # state = self.get_state() # state_string += f"\n {state}]" print(state_string) reward = None class MyTFEnv(tf_py_environment.TFPyEnvironment): def __init__(self, verbose_env=False): self._pyenv = MyPyEnv(verbose_env=verbose_env) super().__init__(self._pyenv) def reset_ep_counter(self): self._pyenv.reset_ep_counter() __all__ = ["MyPyEnv", "MyTFEnv"]
{"/optuna_agent_driver.py": ["/dqn_agent_driver.py"], "/dqn_my_agent.py": ["/dqn_my_env.py"], "/test_agent_driver.py": ["/dqn_agent_driver.py"], "/dqn_agent_driver.py": ["/dqn_my_agent.py"]}
16,269,950
CeeEffEff/DQNExploration
refs/heads/main
/dqn_my_agent.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from tf_agents.agents.dqn import dqn_agent from tf_agents.utils import common tf.compat.v1.enable_v2_behavior() from dqn_my_env import MyTFEnv from tf_agents.networks import q_network class MyAgent(dqn_agent.DqnAgent): def __init__(self, learning_rate, fc_layer_units, fc_layer_depth, verbose_env=False, show_summary=False): tf.random.set_seed(123123) self._tf_env = MyTFEnv(verbose_env=verbose_env) action_spec = self._tf_env.action_spec() num_actions = action_spec.maximum - action_spec.minimum + 1 # As our action spec is defined on N observation_spec = self._tf_env.observation_spec() time_step_spec = self._tf_env.time_step_spec() preprocessing_layers = { 'price':tf.keras.layers.Flatten(), 'pos':tf.keras.layers.Dense(2), 'pos_price':tf.keras.layers.Dense(2), 'time':tf.keras.layers.Dense(1) } self._q_network = q_network.QNetwork( input_tensor_spec=observation_spec, action_spec= action_spec, preprocessing_layers=preprocessing_layers, preprocessing_combiner= tf.keras.layers.Concatenate(axis=-1), fc_layer_params = (fc_layer_units,) * fc_layer_depth ) super().__init__( time_step_spec, action_spec, q_network=self._q_network, optimizer = tf.keras.optimizers.Adam(learning_rate=learning_rate), td_errors_loss_fn= common.element_wise_squared_loss ) self._q_network.summary() self._q_network._encoder.summary() if show_summary: input() def reset_ep_counter(self): self._tf_env.reset_ep_counter()
{"/optuna_agent_driver.py": ["/dqn_agent_driver.py"], "/dqn_my_agent.py": ["/dqn_my_env.py"], "/test_agent_driver.py": ["/dqn_agent_driver.py"], "/dqn_agent_driver.py": ["/dqn_my_agent.py"]}