index
int64 | repo_name
string | branch_name
string | path
string | content
string | import_graph
string |
|---|---|---|---|---|---|
22,438
|
opendata-stuttgart/meinsack
|
refs/heads/master
|
/sack/main/management/commands/schaalundmueller_datafile_parsing.py
|
# coding=utf-8
from django.core.management import BaseCommand
from main.models import Street, Area, PickUpDate
from main.utils import parse_schaal_und_mueller_csv_data
class Command(BaseCommand):
help = "schaal+mueller datafile parsing"
def add_arguments(self, parser):
parser.add_argument('--filename', required=True)
parser.add_argument('--year', type=int, required=True)
def handle(self, *args, **options):
parse_schaal_und_mueller_csv_data(options['filename'], options['year'])
|
{"/sack/main/urls.py": ["/sack/main/views.py"], "/sack/main/serializers.py": ["/sack/main/models.py"], "/sack/main/views.py": ["/sack/main/models.py", "/sack/main/serializers.py"], "/sack/main/admin.py": ["/sack/main/models.py"]}
|
22,439
|
opendata-stuttgart/meinsack
|
refs/heads/master
|
/sack/main/urls.py
|
# coding=utf-8
from django.conf.urls import include, url
from rest_framework.routers import Route, SimpleRouter, DynamicDetailRoute
from .views import ZipCodeViewSet, StreetViewSet
class ZipCodeRouter(SimpleRouter):
routes = [
Route(
url=r'^$',
mapping={'get': 'list'},
name='{basename}-list',
initkwargs={'suffix': 'List'}
),
Route(
url=r'^{lookup}/$',
mapping={'get': 'retrieve'},
name='{basename}-detail',
initkwargs={'suffix': 'Detail'}
),
]
router = ZipCodeRouter()
router.register('zipcode', ZipCodeViewSet, base_name="zipcode")
class StreetRouter(SimpleRouter):
routes = [
Route(
url=r'^(?P<zipcode>\w+)/{lookup}/$',
mapping={'get': 'retrieve'},
name='{basename}-detail',
initkwargs={'suffix': 'Detail'}
),
DynamicDetailRoute(
url=r'^(?P<zipcode>\w+)/{lookup}/{methodnamehyphen}/$',
name='{basename}-{methodnamehyphen}',
initkwargs={}
)
]
street_router = StreetRouter()
street_router.register('street', StreetViewSet, base_name="street")
urlpatterns = [
url(r'^', include(router.urls)),
url(r'^', include(street_router.urls)),
]
|
{"/sack/main/urls.py": ["/sack/main/views.py"], "/sack/main/serializers.py": ["/sack/main/models.py"], "/sack/main/views.py": ["/sack/main/models.py", "/sack/main/serializers.py"], "/sack/main/admin.py": ["/sack/main/models.py"]}
|
22,440
|
opendata-stuttgart/meinsack
|
refs/heads/master
|
/sack/tests/conftest.py
|
import os
import pytest
@pytest.fixture
def stuttgart_districts():
return os.path.join(os.path.dirname(os.path.abspath(__file__)),
'fixtures/',
'stuttgart_districts.html')
@pytest.fixture
def mocked_district(stuttgart_districts):
import responses
from main.utils import get_districts_stuttgart
with responses.RequestsMock() as rsps:
rsps.add(responses.GET, 'http://onlinestreet.de/strassen/in-Stuttgart.html',
status=200, body=open(stuttgart_districts).read(), content_type='text/html')
return list(get_districts_stuttgart())
@pytest.fixture
def stuttgart_districts_process(mocked_district):
from main.utils import add_district_to_database, extract_district_from_tr
for index, tr in enumerate(mocked_district):
x = extract_district_from_tr(tr)
add_district_to_database(x)
|
{"/sack/main/urls.py": ["/sack/main/views.py"], "/sack/main/serializers.py": ["/sack/main/models.py"], "/sack/main/views.py": ["/sack/main/models.py", "/sack/main/serializers.py"], "/sack/main/admin.py": ["/sack/main/models.py"]}
|
22,441
|
opendata-stuttgart/meinsack
|
refs/heads/master
|
/sack/main/serializers.py
|
import datetime
from rest_framework import serializers, relations
from rest_framework.reverse import reverse
from .models import Street, ZipCode, Area
class StreetDetailSerializer(serializers.HyperlinkedModelSerializer):
dates = serializers.SerializerMethodField()
def get_dates(self, obj):
try:
area = Area.objects.get(district_id=obj.schaalundmueller_district_id)
except Area.DoesNotExist:
return []
return [dt.date for dt in area.dates.filter(date__gte=datetime.date.today())]
class Meta:
model = Street
fields = [
'name', 'dates'
]
read_only_fields = fields
class StreetNestedSerializer(serializers.Serializer):
name = serializers.SerializerMethodField()
url = serializers.SerializerMethodField()
def get_url(self, obj):
view_name = 'street-detail'
url_kwargs = {
'name': obj.name,
'zipcode': obj.zipcode.zipcode
}
url = reverse(view_name, kwargs=url_kwargs, request=self.context.get('request'))
if url is None:
return None
return relations.Hyperlink(url, obj.name)
def get_name(self, obj):
return obj.name
class ZipCodeDetailSerializer(serializers.HyperlinkedModelSerializer):
street = serializers.SerializerMethodField()
def get_street(self, obj):
qs = obj.street_set.all()
name_filter = self.context['request'].query_params.get('name', None)
if name_filter:
qs = qs.filter(name__icontains=name_filter)
for street in qs:
yield StreetNestedSerializer(street, context=self.context).data
class Meta:
model = ZipCode
fields = [
'zipcode', 'street'
]
read_only_fields = fields
class ZipCodeListSerializer(serializers.HyperlinkedModelSerializer):
url = serializers.HyperlinkedIdentityField(
view_name='zipcode-detail', read_only=True, lookup_field="zipcode"
)
class Meta:
model = ZipCode
fields = [
'zipcode', 'url'
]
read_only_fields = fields
|
{"/sack/main/urls.py": ["/sack/main/views.py"], "/sack/main/serializers.py": ["/sack/main/models.py"], "/sack/main/views.py": ["/sack/main/models.py", "/sack/main/serializers.py"], "/sack/main/admin.py": ["/sack/main/models.py"]}
|
22,442
|
opendata-stuttgart/meinsack
|
refs/heads/master
|
/sack/main/management/commands/get_streets.py
|
# coding=utf-8
from django.core.management import BaseCommand
class Command(BaseCommand):
help = "Import streets and districts"
def handle(self, *args, **options):
from main.utils import (
add_district_to_database,
add_street_to_database,
extract_district_from_tr,
extract_street_from_tr,
get_districts_stuttgart,
get_streets_from_district,
)
for tr in get_districts_stuttgart():
d = extract_district_from_tr(tr)
district = add_district_to_database(d)
for street in get_streets_from_district(district):
data = extract_street_from_tr(street)
street = add_street_to_database(data, district)
|
{"/sack/main/urls.py": ["/sack/main/views.py"], "/sack/main/serializers.py": ["/sack/main/models.py"], "/sack/main/views.py": ["/sack/main/models.py", "/sack/main/serializers.py"], "/sack/main/admin.py": ["/sack/main/models.py"]}
|
22,443
|
opendata-stuttgart/meinsack
|
refs/heads/master
|
/sack/tests/test_streetnames.py
|
import pytest
from main.utils import get_possible_street_variants
class TestStreetNameVariants:
@pytest.mark.parametrize(('street_name', 'results'), (
('Ulmer Straße', (
'Ulmer Straße', 'Ulmer Strasse', 'Ulmer Str.', 'Ulmerstraße',
'Ulmerstrasse', 'Ulmerstr.')),
('Daimlerstraße', (
'Daimlerstraße', 'Daimlerstrasse', 'Daimlerstr.', 'Daimler Straße',
'Daimler Strasse', 'Daimler Str.')),
('Neue Brücke', (
'Neue Brücke', 'Neue Bruecke')),
('Großglocknerstraße', (
'Großglocknerstraße', 'Grossglocknerstrasse', 'Großglocknerstr.',
'Grossglocknerstr.', 'Großglockner Straße', 'Grossglockner Strasse',
'Großglockner Str.', 'Grossglockner Str.')),
))
def test_variants(self, street_name, results):
assert get_possible_street_variants(street_name) == set(results)
|
{"/sack/main/urls.py": ["/sack/main/views.py"], "/sack/main/serializers.py": ["/sack/main/models.py"], "/sack/main/views.py": ["/sack/main/models.py", "/sack/main/serializers.py"], "/sack/main/admin.py": ["/sack/main/models.py"]}
|
22,444
|
opendata-stuttgart/meinsack
|
refs/heads/master
|
/sack/main/utils.py
|
import datetime
import re
from bs4 import BeautifulSoup
import requests
def get_districts_stuttgart():
url = 'http://onlinestreet.de/strassen/in-Stuttgart.html'
data = requests.get(url).content
soup = BeautifulSoup(data, 'html.parser')
for table in soup.findAll('table'):
if 'blz' in table.get("class"):
for index, tr in enumerate(table.findAll('tr')):
if index == 0:
continue
yield tr
break
def extract_district_from_tr(tr):
data = list(tr.children)
return {
'name': data[0].a.text,
'url_onlinestreet': data[0].a['href'],
'city': 'Stuttgart',
'number_of_streets': data[1].text
}
def add_district_to_database(data):
from main.models import District
district, created = District.objects.get_or_create(**data)
return district
def get_streets_from_district(district):
url = district.url_onlinestreet
data = requests.get(url).text
soup = BeautifulSoup(data, 'html.parser')
for table in soup.findAll('table'):
if 'strassen' in table.get('class'):
for index, tr in enumerate(table.findAll('tr')):
if index == 0:
continue
yield tr
def normalize_street(street):
if street.endswith('tr.'):
street = street[:-1] + "aße"
return street
def extract_street_from_tr(tr):
data = list(tr.children)
p = re.compile(r'(?P<street>.*)\s+(?P<zipcode>[0-9]{5})\s+(?P<city>.*)')
x = re.search(p, data[0].a.text)
if not x:
return None
return {
'url_onlinestreet': data[0].a['href'],
'name': normalize_street(x.groupdict().get('street')),
'city': x.groupdict().get('city'),
'zipcode': x.groupdict().get('zipcode'),
}
def add_street_to_database(data, district):
from main.models import Street, ZipCode
if not data:
return None
zipcode = data.pop("zipcode")
zipcode, created = ZipCode.objects.get_or_create(zipcode=zipcode)
data["zipcode"] = zipcode
street, created = Street.objects.get_or_create(district=district, **data)
return street
def replace_umlauts(string):
for i, j in (('ß', 'ss'), ('ä', 'ae'), ('ü', 'ue'), ('ö', 'oe')):
x = string.replace(i, j)
if x != string:
yield x
def get_possible_street_variants(street_name):
result = [street_name]
result += list(replace_umlauts(street_name))
other_spacing_variant = None
if normalize_street(street_name) != street_name:
other_spacing_variant = normalize_street(street_name)
if street_name.endswith('traße'):
other_spacing_variant = street_name[:-3] + "."
if other_spacing_variant:
result += [other_spacing_variant]
result += list(replace_umlauts(other_spacing_variant))
other_spacing_variant = None
p = re.compile(r'(.*)[^\w]S(tra[ss|ß]e)')
x = re.findall(p, street_name)
if x:
other_spacing_variant = "{}s{}".format(x[0][0], x[0][1])
p = re.compile(r'(.*[^\s])s(tra[ss|ß]e)')
x = re.findall(p, street_name)
if x:
other_spacing_variant = "{} S{}".format(x[0][0], x[0][1])
if other_spacing_variant:
if normalize_street(other_spacing_variant) != other_spacing_variant:
result += [normalize_street(street_name)]
if other_spacing_variant.endswith('traße'):
x = other_spacing_variant[:-3] + "."
result += list(replace_umlauts(x))
result += [x]
result += [other_spacing_variant]
result += list(replace_umlauts(other_spacing_variant))
return set(result)
def call_schaal_und_mueller_for_district_id(street, fixture=False):
if fixture:
import responses
# if street.schaalundmueller_district_id:
# return
street_list = get_possible_street_variants(street.name)
url = 'http://www.schaal-mueller.de/GelberSackinStuttgart.aspx'
if fixture:
with responses.RequestsMock() as rsps:
rsps.add(responses.POST, 'http://www.schaal-mueller.de/GelberSackinStuttgart.aspx',
status=200, body=open(fixture).read(),
content_type='text/html')
resp = requests.post(url)
else:
resp = requests.post(url)
soup = BeautifulSoup(resp.text.encode(resp.encoding).decode('utf-8'))
viewstate = soup.select("#__VIEWSTATE")[0]['value']
stategenerator = soup.select("#__VIEWSTATEGENERATOR")[0]['value']
stateencrypted = soup.select("#__VIEWSTATEENCRYPTED")[0]['value']
eventvalidation = soup.select("#__EVENTVALIDATION")[0]['value']
for street_name in street_list:
payload = {
'__VIEWSTATEGENERATOR': stategenerator,
'__VIEWSTATEENCRYPTED': stateencrypted,
'__VIEWSTATE': viewstate,
'__EVENTVALIDATION': eventvalidation,
'dnn$ctr491$View$txtZIP': street.zipcode.zipcode,
'dnn$ctr491$View$txtStreet': street_name,
'dnn$ctr491$View$btSearchStreets': 'suchen',
}
if fixture:
with responses.RequestsMock() as rsps:
rsps.add(responses.POST, 'http://www.schaal-mueller.de/GelberSackinStuttgart.aspx',
status=200, body=open(fixture).read(),
content_type='text/html')
resp = requests.post(url, data=payload)
else:
resp = requests.post(url, data=payload)
text = resp.text.encode(resp.encoding).decode('utf-8')
x = re.findall(r"javascript:__doPostBack\('ThatStreet', '(\d+)'\)", text)
if x:
street.schaalundmueller_district_id = int(x[0])
street.save()
return int(x[0])
def call_schaal_und_mueller_district(district_id, fixture=False):
if fixture:
import responses
url = 'http://www.schaal-mueller.de/GelberSackinStuttgart.aspx'
payload = {'__EVENTTARGET': 'ThatStreet'}
payload['__EVENTARGUMENT'] = str(district_id)
if fixture:
with responses.RequestsMock() as rsps:
rsps.add(responses.POST, 'http://www.schaal-mueller.de/GelberSackinStuttgart.aspx',
status=200, body=open(fixture).read(),
content_type='text/html')
resp = requests.post(url, data=payload)
else:
resp = requests.post(url, data=payload)
soup = BeautifulSoup(resp.text.encode(resp.encoding).decode('utf-8'))
div = soup.find('div', {'id': 'dnn_ctr491_View_panResults'})
if div:
area_name = None
if div.find('span'):
area_name = div.find('span', {'id': 'dnn_ctr491_View_lblResults'}).text
if div.find('table'):
dates = [span.text for span in div.find('table').findAll('span')]
return {
'area': area_name,
'dates': dates
}
def parse_schaal_und_mueller_csv_data(filename, year):
regex = r"(.*)\ ([0-9\.]*)\ (Mo.|Di.|Mi.|Do.|Fr.)\ ([0-9\.\ ]*)"
from main.models import Area, PickUpDate
with open(filename, 'r') as fp:
for line in fp.readlines():
if line.startswith('#'):
continue
# find weekday and split on it
area = re.findall(regex, line)[0][0]
a = Area.objects.filter(description=area).first()
if not a:
for in_db, in_csv in (
('Birkach, Botnang, Plieningen', 'Birkach, Plieningen, Botnang'),
('Frauenkopf, Hedelfingen (ohne Hafen), Sillenbuch, Riedenberg', 'Frauenkopf, Hedelfingen (ohne Hafen) Sillenbuch (mit Riedenberg)'),
('Stuttgart-West (ohne Kräherwald, Solitude, Wildpark)', 'Stuttgart-West (ohne Kräherwald, Solitude,Wildpark)'),
('Bad Cannstatt I (ohneSteinhaldenfeld), Mühlhausen', 'Bad Cannstatt I (ohneSteinhaldenfeld) Mühlhausen'),
('Büsnau, Degerloch, Dürrlewang, Kräherwald,Solitude, Wildpark', 'Büsnau, Degerloch, Dürrlewang,Kräherwald,Solitude, Wildpark'),
):
if area == in_csv:
a = Area.objects.filter(description=in_db).first()
if not a:
assert 'Area not found'
dates = re.findall(regex, line)[0][3].split()
# add years
dates_wyears = [i + str(year) for i in dates[:-1]]
dates_wyears.append(dates[-1] + str(year + 1))
for _ in dates_wyears:
dt = datetime.datetime.strptime(_, "%d.%m.%Y").date()
PickUpDate.objects.get_or_create(date=dt, area=a)
|
{"/sack/main/urls.py": ["/sack/main/views.py"], "/sack/main/serializers.py": ["/sack/main/models.py"], "/sack/main/views.py": ["/sack/main/models.py", "/sack/main/serializers.py"], "/sack/main/admin.py": ["/sack/main/models.py"]}
|
22,445
|
opendata-stuttgart/meinsack
|
refs/heads/master
|
/sack/main/views.py
|
import datetime
from rest_framework import viewsets, mixins, response
from rest_framework.response import Response
from rest_framework import renderers
from rest_framework import decorators
from rest_framework.exceptions import NotFound
from django.views.generic.edit import FormView
from django.shortcuts import render
from django.urls import reverse
from .models import Street, ZipCode, Area
from .serializers import ZipCodeDetailSerializer, ZipCodeListSerializer, StreetDetailSerializer
from django import forms
class GetIcalForm(forms.Form):
zipcode = forms.CharField(max_length=10)
street = forms.CharField(max_length=100)
class GetIcalView(FormView):
template_name = 'home.html'
form_class = GetIcalForm
success_url = '/'
def post(self, request):
context = self.get_context_data()
form = self.get_form(self.form_class)
if form.is_valid():
zipcode = form.cleaned_data['zipcode']
street = form.cleaned_data['street']
context['ical_url'] = reverse('street-ical', kwargs={'zipcode': zipcode,
'name': street})
return render(self.request, self.template_name, context)
class ZipCodeViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin,
viewsets.GenericViewSet):
lookup_field = 'zipcode'
authentication_classes = list()
permission_classes = list()
def get_serializer_class(self):
if 'zipcode' in self.kwargs:
return ZipCodeDetailSerializer
return ZipCodeListSerializer
def get_queryset(self):
qs = ZipCode.objects.distinct('zipcode').order_by('zipcode')
if not 'zipcode' in self.kwargs:
zipcode_filter = self.request.query_params.get('zipcode', None)
if zipcode_filter is not None:
return qs.filter(zipcode__icontains=zipcode_filter)
return qs
class PlainTextRenderer(renderers.BaseRenderer):
media_type = 'text/plain'
format = 'txt'
def render(self, data, media_type=None, renderer_context=None):
if isinstance(data, dict):
return renderers.JSONRenderer().render(data, media_type, renderer_context)
return data
class StreetViewSet(mixins.RetrieveModelMixin,
viewsets.GenericViewSet):
lookup_field = 'name'
authentication_classes = list()
permission_classes = list()
queryset = Street.objects.all()
def get_serializer_class(self):
return ZipCodeDetailSerializer
def get_object(self):
if 'zipcode' in self.kwargs:
return Street.objects.filter(zipcode=self.kwargs['zipcode']).first()
return None
def retrieve(self, request, name=None, zipcode=None):
try:
data = self.queryset.get(name=name, zipcode__zipcode=zipcode)
except Street.DoesNotExist:
raise NotFound()
serializer = StreetDetailSerializer(data)
return response.Response(serializer.data)
@decorators.detail_route(methods=['get'], renderer_classes=(PlainTextRenderer,))
def ical(self, request, name, zipcode):
from icalendar import Calendar, Event
try:
data = self.queryset.get(name=name, zipcode__zipcode=zipcode)
except Street.DoesNotExist:
raise NotFound()
except Street.MultipleObjectsReturned:
data = self.queryset.filter(name=name, zipcode__zipcode=zipcode).first()
district_id = data.schaalundmueller_district_id
try:
area = Area.objects.get(district_id=district_id)
except Area.DoesNotExist:
raise NotFound()
cal = Calendar()
cal.add('prodid', '-//Meinsack.click Generator - //NONSGML//DE')
cal.add('version', '0.01')
cal.add('x-wr-calname', 'meinsack Abholtermine')
cal.add('x-original-url', 'https://meinsack.click/')
cal.add('x-wr-caldesc', area.description)
for dt in area.dates.filter(date__gte=datetime.date.today()):
start = dt.date
event = Event()
event.add('summary', 'Meinsack Abholtermin')
event.add('dtstart', start)
event.add('dtend', start + datetime.timedelta(days=1))
cal.add_component(event)
return Response(cal.to_ical())
|
{"/sack/main/urls.py": ["/sack/main/views.py"], "/sack/main/serializers.py": ["/sack/main/models.py"], "/sack/main/views.py": ["/sack/main/models.py", "/sack/main/serializers.py"], "/sack/main/admin.py": ["/sack/main/models.py"]}
|
22,446
|
opendata-stuttgart/meinsack
|
refs/heads/master
|
/sack/main/management/commands/schaalundmueller_districts.py
|
# coding=utf-8
from django.core.management import BaseCommand
from main.models import Street, Area, PickUpDate
from main.utils import call_schaal_und_mueller_district
import datetime
class Command(BaseCommand):
help = "schaal+mueller districts"
def handle(self, *args, **options):
l = Street.objects.order_by('schaalundmueller_district_id').distinct('schaalundmueller_district_id').values_list('schaalundmueller_district_id', flat=True)
for num in l:
if num:
d = call_schaal_und_mueller_district(num)
area, created = Area.objects.get_or_create(description=d['area'],
bag_type="gelb",
collector="Schaal+Mueller",
district_id=num)
for _ in d['dates']:
dt = datetime.datetime.strptime(_, "%d.%m.%Y").date()
pickupdate, created = PickUpDate.objects.get_or_create(date=dt,
area=area)
print(pickupdate)
|
{"/sack/main/urls.py": ["/sack/main/views.py"], "/sack/main/serializers.py": ["/sack/main/models.py"], "/sack/main/views.py": ["/sack/main/models.py", "/sack/main/serializers.py"], "/sack/main/admin.py": ["/sack/main/models.py"]}
|
22,447
|
opendata-stuttgart/meinsack
|
refs/heads/master
|
/sack/main/migrations/0001_initial.py
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import django_extensions.db.fields
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='District',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created', django_extensions.db.fields.CreationDateTimeField(auto_now_add=True, verbose_name='created')),
('modified', django_extensions.db.fields.ModificationDateTimeField(auto_now=True, verbose_name='modified')),
('name', models.CharField(max_length=255)),
('city', models.CharField(max_length=255)),
('number_of_streets', models.IntegerField()),
('url_onlinestreet', models.URLField()),
],
options={
'ordering': ['name'],
},
),
migrations.CreateModel(
name='Street',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created', django_extensions.db.fields.CreationDateTimeField(auto_now_add=True, verbose_name='created')),
('modified', django_extensions.db.fields.ModificationDateTimeField(auto_now=True, verbose_name='modified')),
('name', models.CharField(max_length=255)),
('url_onlinestreet', models.URLField()),
('city', models.CharField(max_length=255)),
('district', models.ForeignKey(to='main.District', on_delete=models.CASCADE)),
],
options={
'ordering': ['name'],
},
),
migrations.CreateModel(
name='ZipCode',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created', django_extensions.db.fields.CreationDateTimeField(auto_now_add=True, verbose_name='created')),
('modified', django_extensions.db.fields.ModificationDateTimeField(auto_now=True, verbose_name='modified')),
('zipcode', models.CharField(max_length=255)),
],
options={
'ordering': ['zipcode'],
},
),
migrations.AddField(
model_name='street',
name='zipcode',
field=models.ForeignKey(to='main.ZipCode', on_delete=models.CASCADE),
),
]
|
{"/sack/main/urls.py": ["/sack/main/views.py"], "/sack/main/serializers.py": ["/sack/main/models.py"], "/sack/main/views.py": ["/sack/main/models.py", "/sack/main/serializers.py"], "/sack/main/admin.py": ["/sack/main/models.py"]}
|
22,448
|
opendata-stuttgart/meinsack
|
refs/heads/master
|
/sack/main/models.py
|
from django.db import models
from django_extensions.db.models import TimeStampedModel
class District(TimeStampedModel):
name = models.CharField(max_length=255)
city = models.CharField(max_length=255)
number_of_streets = models.IntegerField()
url_onlinestreet = models.URLField()
class Meta:
ordering = ['name']
def __str__(self):
return self.name
class ZipCode(TimeStampedModel):
zipcode = models.CharField(max_length=255)
class Meta:
ordering = ['zipcode']
def __str__(self):
return self.zipcode
class Street(TimeStampedModel):
name = models.CharField(max_length=255)
zipcode = models.ForeignKey('zipcode', on_delete=models.CASCADE)
district = models.ForeignKey('District', on_delete=models.CASCADE)
url_onlinestreet = models.URLField()
city = models.CharField(max_length=255)
schaalundmueller_district_id = models.IntegerField(null=True, blank=True)
class Meta:
ordering = ['name']
def __str__(self):
return self.name
class Area(TimeStampedModel):
description = models.CharField(max_length=1000)
bag_type = models.CharField(max_length=20, choices=(('gelb', 'gelb'),))
collector = models.CharField(max_length=1000)
district_id = models.IntegerField(null=True, blank=True)
def __str__(self):
return "{} [{}]".format(self.description, self.dates.count())
class PickUpDate(TimeStampedModel):
date = models.DateField()
area = models.ForeignKey(Area, related_name='dates', on_delete=models.CASCADE)
class Meta:
ordering = ['date']
def __str__(self):
return "{} {}".format(self.area, self.date)
|
{"/sack/main/urls.py": ["/sack/main/views.py"], "/sack/main/serializers.py": ["/sack/main/models.py"], "/sack/main/views.py": ["/sack/main/models.py", "/sack/main/serializers.py"], "/sack/main/admin.py": ["/sack/main/models.py"]}
|
22,449
|
opendata-stuttgart/meinsack
|
refs/heads/master
|
/sack/main/management/commands/schaalundmueller.py
|
# coding=utf-8
from django.core.management import BaseCommand
from main.models import Street
from main.utils import call_schaal_und_mueller_for_district_id
class Command(BaseCommand):
help = "schaal+mueller id crawling"
def handle(self, *args, **options):
for street in Street.objects\
.filter(city__contains="Stuttgart")\
.filter(schaalundmueller_district_id__isnull=True):
print(street.pk),
print(street.name)
call_schaal_und_mueller_for_district_id(street)
|
{"/sack/main/urls.py": ["/sack/main/views.py"], "/sack/main/serializers.py": ["/sack/main/models.py"], "/sack/main/views.py": ["/sack/main/models.py", "/sack/main/serializers.py"], "/sack/main/admin.py": ["/sack/main/models.py"]}
|
22,450
|
opendata-stuttgart/meinsack
|
refs/heads/master
|
/sack/main/admin.py
|
from django.contrib import admin
from .models import District, Street, ZipCode, Area, PickUpDate
@admin.register(District)
class DistrictAdmin(admin.ModelAdmin):
list_display = ['name', 'city']
@admin.register(Street)
class StreetAdmin(admin.ModelAdmin):
list_display = ['name', 'district', 'zipcode', 'city', 'schaalundmueller_district_id']
list_filter = ['district', 'zipcode', 'schaalundmueller_district_id']
search_fields = ['name', 'zipcode__zipcode', 'city']
@admin.register(ZipCode)
class ZipCodeAdmin(admin.ModelAdmin):
list_display = ['zipcode']
@admin.register(Area)
class AreaAdmin(admin.ModelAdmin):
pass
@admin.register(PickUpDate)
class PickUpDateAdmin(admin.ModelAdmin):
pass
|
{"/sack/main/urls.py": ["/sack/main/views.py"], "/sack/main/serializers.py": ["/sack/main/models.py"], "/sack/main/views.py": ["/sack/main/models.py", "/sack/main/serializers.py"], "/sack/main/admin.py": ["/sack/main/models.py"]}
|
22,451
|
opendata-stuttgart/meinsack
|
refs/heads/master
|
/sack/tests/test_schaalundmueller.py
|
import datetime
import os
import pytest
from main.utils import call_schaal_und_mueller_for_district_id, call_schaal_und_mueller_district
@pytest.fixture
def schaalundmueller_ulmerstrasse():
return os.path.join(os.path.dirname(os.path.abspath(__file__)),
'fixtures/',
'schaalundmueller_ulmerstrasse.html')
@pytest.fixture
def schaalundmueller_daimlerstrasse():
return os.path.join(os.path.dirname(os.path.abspath(__file__)),
'fixtures/',
'schaalundmueller_daimlerstrasse.html')
@pytest.fixture
def schaalundmueller_district_6():
return os.path.join(os.path.dirname(os.path.abspath(__file__)),
'fixtures/',
'schaalundmueller_district_6.html')
@pytest.fixture
def mocked_ulmerstrasse():
from main.models import District, Street, ZipCode
dis = District.objects.create(name="Wangen",
city='Stuttgart',
number_of_streets=1,
url_onlinestreet="http://google.de")
street = Street.objects.create(name="Ulmer Str.",
city='Stuttgart',
district=dis,
zipcode=ZipCode.objects.create(zipcode="70327"),
url_onlinestreet="http://google.de")
return street
@pytest.fixture
def mocked_daimlerstrasse():
from main.models import District, Street, ZipCode
dis = District.objects.create(name="Bad Canstatt",
city='Stuttgart',
number_of_streets=1,
url_onlinestreet="http://google.de")
street = Street.objects.create(name="Daimlerstr.",
city='Stuttgart',
district=dis,
zipcode=ZipCode.objects.create(zipcode="70372"),
url_onlinestreet="http://google.de")
return street
@pytest.mark.django_db
class TestSchaalundmuellerCrawler:
def test_ulmerstrasse(self, mocked_ulmerstrasse, schaalundmueller_ulmerstrasse):
assert call_schaal_und_mueller_for_district_id(
mocked_ulmerstrasse,
fixture=schaalundmueller_ulmerstrasse) == 6
assert mocked_ulmerstrasse.schaalundmueller_district_id == 6
@pytest.mark.skip
def test_ulmerstrasse_live(self, mocked_ulmerstrasse, schaalundmueller_ulmerstrasse):
assert call_schaal_und_mueller_for_district_id(mocked_ulmerstrasse) == 6
assert mocked_ulmerstrasse.schaalundmueller_district_id == 6
def test_daimlerstrasse(self, mocked_daimlerstrasse, schaalundmueller_daimlerstrasse):
assert call_schaal_und_mueller_for_district_id(
mocked_daimlerstrasse,
fixture=schaalundmueller_daimlerstrasse) == 12
assert mocked_daimlerstrasse.schaalundmueller_district_id == 12
@pytest.mark.skip
def test_daimlerstrasse_live(self, mocked_daimlerstrasse, schaalundmueller_daimlerstrasse):
assert call_schaal_und_mueller_for_district_id(mocked_daimlerstrasse) == 12
assert mocked_daimlerstrasse.schaalundmueller_district_id == 12
@pytest.mark.skip
def test_district_6_live(self):
d = call_schaal_und_mueller_district(6)
assert d['area'] == "Hafen, Unter- und Obertürkheim, Wangen"
assert '.201' in d['dates'][0]
def test_district_6(self, schaalundmueller_district_6):
d = call_schaal_und_mueller_district(6, schaalundmueller_district_6)
assert d['area'] == "Hafen, Unter- und Obertürkheim, Wangen"
assert '12.12.2016' in d['dates']
@pytest.mark.django_db
class TestSchaalundmuellerDataImporter:
@pytest.fixture
def schaal_und_mueller_areas(self):
from main.models import Area
for index, area in enumerate(('Frauenkopf, Hedelfingen (ohne Hafen), Sillenbuch, Riedenberg',
'Feuerbach, Killesberg, Weißenhof',
'Möhringen',
'Stuttgart-West (ohne Kräherwald, Solitude, Wildpark)',
'Stammheim, Weilimdorf',
'Hafen, Unter- und Obertürkheim, Wangen',
'Münster, Steinhaldenfeld, Zuffenhausen',
'Stuttgart-Süd',
'Stuttgart-Ost (ohne Frauenkopf)',
'Vaihingen (ohne Büsnau, Dürrlewang)',
'Bad Cannstatt I (ohneSteinhaldenfeld), Mühlhausen',
'Bad Cannstatt II (ohne Steinhaldenfeld)',
'Stuttgart-Mitte, Stuttgart-Nord (ohne Killesberg, Weißenhof)',
'Birkach, Botnang, Plieningen',
'Büsnau, Degerloch, Dürrlewang, Kräherwald,Solitude, Wildpark')):
Area.objects.create(description=area, district_id=index, bag_type='gelb', collector='Schaal+Mueller')
@pytest.mark.parametrize(('filename', 'year', 'testarea', 'first_date_in_year', 'dates_in_year'), (
('stuttgart_2017.txt', 2017, 'Birkach, Botnang, Plieningen', datetime.date(2018, 1, 5), 17),
('stuttgart_2017.txt', 2017, 'Stuttgart-Süd', datetime.date(2018, 1, 17), 18),
('stuttgart_2017.txt', 2017, 'Vaihingen (ohne Büsnau, Dürrlewang)', datetime.date(2018, 1, 19), 18),
))
def test_import(self, schaal_und_mueller_areas, filename, year, testarea, first_date_in_year, dates_in_year):
from main.models import District, Area
fn = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'main', 'data', filename)
from main.utils import parse_schaal_und_mueller_csv_data
parse_schaal_und_mueller_csv_data(fn, year)
area = Area.objects.get(description=testarea)
assert area.dates.count() == dates_in_year + 1
assert area.dates.filter(date__year=year).count() == dates_in_year
assert area.dates.filter(date__year=year + 1).first().date == first_date_in_year
|
{"/sack/main/urls.py": ["/sack/main/views.py"], "/sack/main/serializers.py": ["/sack/main/models.py"], "/sack/main/views.py": ["/sack/main/models.py", "/sack/main/serializers.py"], "/sack/main/admin.py": ["/sack/main/models.py"]}
|
22,452
|
opendata-stuttgart/meinsack
|
refs/heads/master
|
/sack/sack/urls.py
|
from django.conf.urls import include, url
from django.contrib import admin
from django.views.generic.base import RedirectView
from django.views.generic import TemplateView
from rest_framework.authtoken.views import obtain_auth_token
from main.views import GetIcalView
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', GetIcalView.as_view(), name='get_ical'),
url(r'^faq/$', TemplateView.as_view(template_name='faq.html'), name='faq'),
url(r'^legal/$', TemplateView.as_view(template_name='legal.html'), name='legal'),
url(r'^v1$', RedirectView.as_view(url='/v1/', permanent=False)),
url(r'^v1/', include('main.urls')),
url(r'^auth/', include('rest_framework.urls',
namespace='rest_framework')),
url(r'^get-auth-token/', obtain_auth_token),
]
|
{"/sack/main/urls.py": ["/sack/main/views.py"], "/sack/main/serializers.py": ["/sack/main/models.py"], "/sack/main/views.py": ["/sack/main/models.py", "/sack/main/serializers.py"], "/sack/main/admin.py": ["/sack/main/models.py"]}
|
22,453
|
opendata-stuttgart/meinsack
|
refs/heads/master
|
/sack/tests/test_district.py
|
import os.path
import pytest
import responses
from main.utils import (
add_street_to_database,
extract_district_from_tr,
extract_street_from_tr,
get_streets_from_district,
normalize_street,
)
@pytest.fixture
def stuttgart_streets_hausen():
return os.path.join(os.path.dirname(os.path.abspath(__file__)),
'fixtures/',
'stuttgart_streets_hausen.html')
@pytest.fixture
def stuttgart_streets_hausen_process(mocked_streets_hausen):
from main.models import District
for index, tr in enumerate(mocked_streets_hausen):
x = extract_street_from_tr(tr)
add_street_to_database(x, District.objects.first())
@pytest.fixture
def mocked_streets_hausen(stuttgart_districts_process, stuttgart_streets_hausen):
from main.models import District
dis = District.objects.get(name="Hausen")
with responses.RequestsMock() as rsps:
rsps.add(responses.GET, dis.url_onlinestreet,
status=200, body=open(stuttgart_streets_hausen).read(), content_type='text/html')
return list(get_streets_from_district(dis))
@pytest.mark.django_db
class TestDistrict():
def test_district_import(self, mocked_district):
assert len(mocked_district) == 56
def test_extract_district_from_tr(self, mocked_district):
for index, tr in enumerate(mocked_district):
x = extract_district_from_tr(tr)
assert isinstance(x, dict)
assert 'name' in x
break # one is enough
def test_add_district_to_database(self, stuttgart_districts_process):
from main.models import District
assert District.objects.count() == 56
assert District.objects.filter(name="Bad Cannstatt")
assert District.objects.filter(name="Büsnau")
@pytest.mark.django_db
class TestStreet():
def test_extract_street_from_tr(self, mocked_streets_hausen):
for index, tr in enumerate(mocked_streets_hausen):
x = extract_street_from_tr(tr)
assert x['name'] == 'Gerlinger Straße'
assert x['zipcode'] == '70499'
assert x['city'] == 'Stuttgart-Hausen'
break # one is enough
def test_add_district_to_database(self, stuttgart_streets_hausen_process):
from main.models import Street
assert Street.objects.count() == 7
assert Street.objects.filter(name="Gerlinger Straße")
class TestNormlizingStreet():
@pytest.mark.parametrize(('name', 'name_normalized'), (
('Gerlinger Str.', 'Gerlinger Straße'),
('Gerlingerstr.', 'Gerlingerstraße'),
))
def test_normalize_street(self, name, name_normalized):
assert normalize_street(name) == name_normalized
|
{"/sack/main/urls.py": ["/sack/main/views.py"], "/sack/main/serializers.py": ["/sack/main/models.py"], "/sack/main/views.py": ["/sack/main/models.py", "/sack/main/serializers.py"], "/sack/main/admin.py": ["/sack/main/models.py"]}
|
22,454
|
kevingasik/BasileRoboticsRPI
|
refs/heads/master
|
/deep_learning_object_detection.py
|
# import the necessary packages
import numpy as np
import argparse
import cv2
#construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i","--image", required=True,help="path to input image")
ap.add_argument("-p","--prototxt",required=True,help="path to Caffe 'deploy' prototxt file")
ap.add_argument("-m", "--model", required=True,help="path to Caffe pre-trained model")
ap.add_argument("-c", "--confidence", type=float, default=0.2, help="minimum probability to filter weak detections")
args = vars(ap.parse_args())
#init the list of class labels MobileNet SSD was trained to detect
# then generate a set of bounding box colors for each class
CLASSES = ["background","aeroplane","bicycle","bird","boat",
"bottle","bus","car","cat","chair","cow","diningtable","dog",
"horse","motorbike","person","pottedplant","sheep",
"sofa","train","tvmonitor"]
CLASSES = ["background","person"]
#load our serialized model from disk
print("[INFO] loading model...")
net = cv2.dnn.readNetFromCaffe(args["prototxt"], args["model"])
#load the input image and construct an input blob for the image
# by resizing to a fixed 300x300 pixels and then normalizing it
# (note: normalization is done via the authors of the MobileNet SSD
# implementation)
image = cv2.imread(args["image"])
(h,w) = image.shape[:2]
blob = cv2.dnn.blobFromImage(cv2.resize(image,( 300,300)), 0.007843, (300,300), 127.5)
#pass the blobs through the network and obtain the detections and predictions
print("[INFO] computing object detections...")
net.setInput(blob)
detections = net.forward()
# loop over the detections
for i in np.arange(0, detections.shape[2]):
# extract the confidence(i.e., probability) associated with the
# prediction
confidence = detections[0,0,i,2]
# filter out weak detections by ensuring the 'confidnce' is
# greater than the minimum confidence
if confidence > args["confidence"]:
#extract the index of the class label from the 'detections',
# then compute the (x,y)-coordinates of the bounding box for
# the object
idx = int(detections[0, 0, i, 1])
box = detections[0, 0, i, 3:7] * np.array([w,h,w,h])
(startX, startY, endX, endY) = box.astype("int")
# display the prediction
label = "{}: {:.2f}%".format(CLASSES[idx], confidence*100)
print("[INFO] {}".format(label))
cv2.rectangle(image, (startX, startY), (endX, endY), COLORS[idx],2)
y = startY - 15 if staryY-15 > 15 else startY + 15
cv2.putText(image, label, (startX,y), cv2.FONT_HERSHEY_SIMPLEX,0.5,COLORS[idx],2)
cv2.imshow("Output", image)
cv2.waitKey(0)
|
{"/usb_camera.py": ["/basicmotiondetector.py"]}
|
22,455
|
kevingasik/BasileRoboticsRPI
|
refs/heads/master
|
/MorningGlory/MGbuttons.py
|
import time
import os
import RPi.GPIO as GPIO
import cv2
class MGButtons():
GPIO.setmode(GPIO.BCM)
#BCM17,11 Motor_INB
#BCM22 15 Motor_EnB
#BCM5,29 Motor_CS
#Motor_EnA, BCM13 33
#BCM26,37 Motor_INA
#MotorPWM BCM18_PCM_C 12 but in verision one it was where?
def __init__(self):
self.button_dict = {}
# self.button_dict['red'] = {}
# self.button_dict['red']['read'] = 23
# self.button_dict['red']['light'] = 37
# self.button_dict['red']['status'] = 'off'
self.button_dict['red'] = {}
self.button_dict['red']['read'] = 24
self.button_dict['red']['light'] = 22 #13
self.button_dict['red']['status'] = 'off'
self.button_dict['red']['prevState'] = None
self.button_dict['red']['currState'] = None
self.button_dict['white'] = {}
self.button_dict['white']['read'] = 25
self.button_dict['white']['light'] = 26 #6
self.button_dict['white']['status'] = 'off'
self.button_dict['white']['prevState'] = None
self.button_dict['white']['currState'] = None
self.button_dict['green'] = {}
self.button_dict['green']['read'] = 12
self.button_dict['green']['light'] = 13 #22
self.button_dict['green']['status'] = 'off'
self.button_dict['green']['prevState'] = None
self.button_dict['green']['currState'] = None
self.button_dict['yellow'] = {}
self.button_dict['yellow']['read'] = 16
self.button_dict['yellow']['light'] = 6 #32
self.button_dict['yellow']['status'] = 'off'
self.button_dict['yellow']['prevState'] = None
self.button_dict['yellow']['currState'] = None
for key,value in self.button_dict.items():
#print(value['read'])
GPIO.setup(value['read'],GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(value['light'],GPIO.OUT)
GPIO.add_event_detect(self.button_dict['red']['read'], GPIO.RISING, callback=lambda x: self.change_status(self.button_dict['red']['read']), bouncetime=300)
GPIO.add_event_detect(self.button_dict['white']['read'], GPIO.RISING, callback=lambda x: self.change_status(self.button_dict['white']['read']), bouncetime=300)
GPIO.add_event_detect(self.button_dict['green']['read'], GPIO.RISING, callback=lambda x: self.change_status(self.button_dict['green']['read']), bouncetime=300)
GPIO.add_event_detect(self.button_dict['yellow']['read'], GPIO.RISING, callback=lambda x: self.change_status(self.button_dict['yellow']['read']), bouncetime=300)
def change_status(self,button):
a_button_pressed = False
for key,value in self.button_dict.items():
if(value['status'] == 'on'):
a_button_pressed = True
for key,value in self.button_dict.items():
if(value['read'] == button) and (value['status'] == 'off') and (a_button_pressed == False):
self.button_dict[str(key)]['status'] = 'on'
GPIO.output(self.button_dict[str(key)]['light'],1)
elif(value['read'] == button) and (value['status'] == 'on'):
self.button_dict[str(key)]['status'] = 'off'
GPIO.output(self.button_dict[str(key)]['light'],0)
def read_button(self,button):
return GPIO.input(button)
def read_buttons(self):
# this function returns an arr of the values being read
read_arr = []
for key,value in self.button_dict.items():
read_arr.append(GPIO.output(value['read']))
return read_arr
def print_buttons(self,read, light, status):
#this function prints the button read values
if(read == True):
for key,value in self.button_dict.items():
print(value['read'])
elif(light == True):
for key,value in self.button_dict.items():
print(value['light'])
elif(status == True):
for key,value in self.button_dict.items():
print(value['status'])
def light_buttons(self):
for key,value in self.button_dict.items():
if(value['status'] == 'on'):
GPIO.output(self.button_dict[str(key)]['light'],1)
elif(value['status'] == 'off'):
GPIO.output(value['light'],0)
# def read_light_buttons(self):
# for key,value in self.button_dict.items():
# print(GPIO.input(value['read']))
# GPIO.output(value['light'],1)
if __name__ == "__main__":
buttons = MGButtons()
while True:
#buttons.change_status_buttons()
#print(buttons.read_button(16))
#print('hello')
buttons.print_buttons(False,False,True)
#buttons.light_buttons()
time.sleep(0.25)
#for key,value in MGButtons.button_dict.items():
#print(value['read'])
#print(buttons.button_dict)
|
{"/usb_camera.py": ["/basicmotiondetector.py"]}
|
22,456
|
kevingasik/BasileRoboticsRPI
|
refs/heads/master
|
/unifyingcameras.py
|
from imutils.video import VideoStream
import datetime
import argparse
import imutils
import time
import cv2
ap = argparse.ArgumentParser()
ap.add_argument("-p","--picamera", type=int, default=-1,help="weather or not the pi cam should be used")
args = vars(ap.parse_args())
#init the video stream and allow the camera sensor to warmup
vs = VideoStream(usePiCamera = args["picamera"] > 0).start()
time.sleep(2.0)
while True:
frame = vs.read()
frame = imutils.resize(frame, width=400)
timestamp = datetime.datetime.now()
ts = timestamp.strftime("%A %d %B %Y %I:%M:%S%p")
cv2.putText(frame,ts,(10, frame.shape[0] - 10),cv2.FONT_HERSHEY_SIMPLEX,0.35,(0,0,255),1)
cv2.imshow("Frame",frame)
key = cv2.waitKey(1) & 0xFF
if key == ord("q"):
break
cv2.destroyAllWindows()
vs.stop()
|
{"/usb_camera.py": ["/basicmotiondetector.py"]}
|
22,457
|
kevingasik/BasileRoboticsRPI
|
refs/heads/master
|
/CV_test_scripting.py
|
import numpy as np
import cv2
faceCascade = cv2.CascadeClassifier('/usr/local/lib/python3.7/dist-packages/cv2/data/haarcascade_frontalface_default.xml')
#faceCascade = cv2.CascadeClassifier('lbp_cascade_frontalface.xml')
#eyeCascade= cv2.CascadeClassifier('/usr/local/lib/python3.7/dist-packages/cv2/data/haarcascade_eye.xml')
#faceCascade = cv2.CascadeClassifier('/usr/local/lib/python3.7/dist-packages/cv2/data/haarcascade_fullbody.xml')
cap = cv2.VideoCapture(0)
cap.set(3,1280) # set Width
cap.set(4,730) # set Height
#cv2.namedWindow("output",cv2.WINDOW_NORMAL)
while True:
ret, img = cap.read()
#img = cv2.flip(img, -1)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.2,
minNeighbors=4,
minSize=(40, 40)
)
#faces.append(faces2)
for (x,y,w,h) in faces:
cv2.rectangle(img,(x,y),(x+w,y+h),(255,255,0),2)
roi_gray = gray[y:y+h, x:x+w]
roi_color = img[y:y+h, x:x+w]
#for(ex,ey,ew,eh) in eyes:
# cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)
#image = cv2.imread('img')
#cv2.resizeWindow("output",(640,480))
cv2.imshow('video',img)
k = cv2.waitKey(30) & 0xff
if k == 27: # press 'ESC' to quit
break
cap.release()
cv2.destroyAllWindows()
|
{"/usb_camera.py": ["/basicmotiondetector.py"]}
|
22,458
|
kevingasik/BasileRoboticsRPI
|
refs/heads/master
|
/MorningGlory/rotary_switch.py
|
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
# switch pinout
switch1 = 18
switch2 = 17
switch3 = 27
switch4 = 22
switch5 = 23
switch6 = 24
switch7 = 25
switch8 = 8
GPIO.setup(switch1,GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(switch2,GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(switch3,GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(switch4,GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(switch5,GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(switch6,GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(switch7,GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(switch8,GPIO.IN, pull_up_down=GPIO.PUD_UP)
while (1):
if GPIO.input(switch1) == 0:
print("Switch 1 set")
time.sleep(0.2)
if GPIO.input(switch2) == False:
print("Switch 2 set")
time.sleep(0.2)
if GPIO.input(switch3) == False:
print("Switch 3 set")
time.sleep(0.2)
if GPIO.input(switch4) == False:
print("Switch 4 set")
time.sleep(0.2)
if GPIO.input(switch5) == False:
print("Switch 5 set")
time.sleep(0.2)
if GPIO.input(switch6) == False:
print("Switch 6 set")
time.sleep(0.2)
if GPIO.input(switch7) == False:
print("Switch 7 set")
time.sleep(0.2)
if GPIO.input(switch8) == False:
print("Switch 8 set")
time.sleep(0.2)
|
{"/usb_camera.py": ["/basicmotiondetector.py"]}
|
22,459
|
kevingasik/BasileRoboticsRPI
|
refs/heads/master
|
/MorningGlory/serialtesting.py
|
#!/usr/bin/env python
import serial
import time
import os
import termios
port='/dev/ttyAMA0'
with open(port) as f:
attrs = termios.tcgetattr(f)
attrs[2] = attrs[2] & ~termios.HUPCL
termios.tcsetattr(f, termios.TCSAFLUSH,attrs)
ser = serial.Serial(
port='/dev/ttyACM0',
baudrate = 115200,
parity = serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS,
timeout=1
)
ser.close()
ser.open()
ser.reset_input_buffer()
ser.reset_output_buffer()
ser.close()
ser.open()
count = 0
def animationOne():
for i in range(0,22):
data = "up {} 20".format(i)
ser.write(data)
read_ser = ser.readline()
time.sleep(0.2)
print read_ser
while True:
if(count == 0):
count = 1
ser.read(8)
data = raw_input("Enter something : ")
if(data == "animate"):
animationOne()
else:
ser.write(data)
read_serial = ser.readline()
print read_serial
|
{"/usb_camera.py": ["/basicmotiondetector.py"]}
|
22,460
|
kevingasik/BasileRoboticsRPI
|
refs/heads/master
|
/TendServos/realtimehelper.py
|
from imutils.video import VideoStream
import datetime
import argparse
import imutils
import time
import cv2
class RealTimeHelper():
def __init__(self):
self.hello = "hello World"
self.width = 0
self.height = 0
self.classes = ["background", "aeroplane", "bicycle", "bird", "boat",
"bottle", "bus", "car", "cat", "chair", "cow", "diningtable",
"dog", "horse", "motorbike", "person", "pottedplant", "sheep",
"sofa", "train", "tvmonitor"]
def setSize(self, width, height):
self.width = width
self.height = height
def create_line(self, frame):
cv2.line(frame, (self.width // 2, self.height ), (self.width // 2, 0), (0, 255, 0), 2)
cv2.line(frame, (self.width // 2 + 2, self.height ), (self.width // 2 + 2, 0), (0, 128, 0), 2)
cv2.line(frame, (self.width // 2 - 2, self.height ), (self.width // 2 - 2, 0), (0, 128, 0), 2)
def create_text(self,frame,info):
# loop over the info tuples and draw them on our frame
for (i, (k, v)) in enumerate(info):
text = "{}: {}".format(k, v)
cv2.putText(frame, text, (self.width // 4 + i*self.width//2 - 30, self.height - (20)),
cv2.FONT_HERSHEY_SIMPLEX, 1.5, (255, 0, 255), 2)
def create_blob(self,frame):
# grab the frame dimensions and convert it to a blob
blob = cv2.dnn.blobFromImage(cv2.resize(frame, (300, 300)),0.007843, (300, 300), 127.5)
return blob
def draw_predictions(frame,mytuple,COLORS,idx):
(startX,startY,endX,endY) = mytuple
label = "{}: {:.2f}%".format(CLASSES[idx],confidence * 100)
cv2.rectangle(frame, (startX, startY), (endX, endY),COLORS[idx], 2)
y = startY - 15 if startY - 15 > 15 else startY + 15
cv2.putText(frame, label, (startX, y),cv2.FONT_HERSHEY_SIMPLEX, 0.5, COLORS[idx], 2)
return label,y
#def create_text(self):
|
{"/usb_camera.py": ["/basicmotiondetector.py"]}
|
22,461
|
kevingasik/BasileRoboticsRPI
|
refs/heads/master
|
/MorningGlory/MG_serial.py
|
#!/usr/bin/env python
import serial
import time
import os
import termios
class Animation():
def __init__(self):
self.mystr = "hello"
self.row1 = []
self.row2 = []
def open_serial(self):
port='/dev/ttyAMA0'
#port='/dev/ttyACM0'
with open(port) as f:
attrs = termios.tcgetattr(f)
attrs[2] = attrs[2] & ~termios.HUPCL
termios.tcsetattr(f, termios.TCSAFLUSH,attrs)
self.ser = serial.Serial(
port='/dev/ttyACM0',
baudrate = 9600,
parity = serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS,
timeout=1
)
self.ser.close()
self.ser.open()
self.ser.reset_input_buffer()
self.ser.reset_output_buffer()
self.ser.close()
self.ser.open()
return
def generate_order(self,order):
#sides in
if(order == 0):
self.row1 = [0,1,2,3,4,5,6,7,8,9,10,11]
self.row2 = [23,22,21,20,19,18,17,16,15,14,13,12]
if(order == 1):
self.row1 = [17,16,15,14,13,12]
self.row2 = [23,22,21,20,19,18]
def dance_up(self,row):
delay = 0
#lets dance our windows
#What should it look like?
#goToE {addr} {%between 2 and 3} {speed} {time delay}
#row1,row2 = self.generate_order(0)
if(row == 1):
for item in self.row1:
delay = delay + 1000
position = 95
speed = 30
print(item)
data = "goToE {} {} {} {}\r\n".format(item,position,speed,delay)
self.ser.write(data.encode())
read_ser = self.ser.readline().decode()
time.sleep(0.1)
print (read_ser)
if(row == 2):
for item in self.row2:
delay = delay + 1000
position = 95
speed = 30
print(item)
data = "goToE {} {} {} {}\r\n".format(item,position,speed,delay)
self.ser.write(data.encode())
read_ser = self.ser.readline().decode()
time.sleep(0.1)
print (read_ser)
return
def dance_down(self,row):
delay = 0
#lets dance our windows
#What should it look like?
#goToE {addr} {%between 2 and 3} {speed} {time delay}
#row1,row2 = self.generate_order(0)
if(row == 1):
for item in self.row1:
delay = delay + 1000
position = 25
speed = 30
print(item)
data = "goToE {} {} {} {}\r\n".format(item,position,speed,delay)
self.ser.write(data.encode())
read_ser = self.ser.readline().decode()
time.sleep(0.1)
print (read_ser)
if(row == 2):
for item in self.row2:
delay = delay + 1000
position = 25
speed = 30
print(item)
data = "goToE {} {} {} {}\r\n".format(item,position,speed,delay)
self.ser.write(data.encode())
read_ser = self.ser.readline().decode()
time.sleep(0.1)
print (read_ser)
return
def dance_one(self):
#try this... if this doesnt work then put the dance down code into the dance up and create a big animation function
self.dance_up(2)
time.sleep(5.5)
self.dance_up(1)
time.sleep(8)
self.dance_down(2)
time.sleep(5.5)
self.dance_down(1)
time.sleep(7)
self.dance_up(2)
time.sleep(5.5)
self.dance_up(1)
time.sleep(8)
self.dance_down(2)
time.sleep(5.5)
self.dance_down(1)
if __name__ == "__main__":
myany = Animation()
myany.open_serial()
myany.generate_order(1)
#myany.dance_one()
|
{"/usb_camera.py": ["/basicmotiondetector.py"]}
|
22,462
|
kevingasik/BasileRoboticsRPI
|
refs/heads/master
|
/basicmotiondetector.py
|
#import the ncessary packages
import imutils
import cv2
class BasicMotionDetector:
def __init__(self, accumWeight=0.5,deltaThresh=5,minArea=5000):
#determine the openCv version, followed by storing the
# frame accumlation weight, the fixed threshold for te delta
# image, and finally the minimum area eqruied
#for "motion" to be reported
self.isv2 = imutils.is_cv2()
self.accumWeight = accumWeight
self.deltaThresh = deltaThresh
self.minArea = minArea
# initialie the average image for motion detection
self.avg = None
def update(self, image):
#init the locations
locs = []
# if the average image is None, init it
if self.avg is None:
self.avg = image.astype("float")
return locs
# otherwise, accmlate the weighted average between
# the current grame and the revious frames, then comuter
# the pixel-wse differences between the cureent frame
# and running avergae
cv2.accumulateWeighted(image, self.avg, self.accumWeight)
frameDelta = cv2.absdiff(image, cv2.convertScaleAbs(self.avg))
# threshold the dleta image and apply a series of dilations
# to help fill in holes
thresh = cv2.threshold(frameDelta, self.deltaThresh, 255, cv2.THRESH_BINARY)[1]
thresh = cv2.dilate(thresh, None, iterations=2)
#find contous in the thresholded image, taking care to
# use the appreopriate version of OpenCV
cnts = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)
#loop over the contours
for c in cnts:
# only add the contour to the locations list if it
# exceeds the minimu area
if cv2.contourArea(c) > self.minArea:
locs.append(c)
return locs
if __name__ == "__main__":
hello = BasicMotionDetector()
hello.update(0)
|
{"/usb_camera.py": ["/basicmotiondetector.py"]}
|
22,463
|
kevingasik/BasileRoboticsRPI
|
refs/heads/master
|
/webapp/leds.py
|
import board
import neopixel
pixels = neopixel.NeoPixel(board.D18, 5)
pixels[3] = (255, 0, 0)
#pixels.fill((0, 255, 0))
# import neopixel
# from board import *
# RED = 0x100000 # (0x10, 0, 0) also works
# pixels = neopixel.NeoPixel(NEOPIXEL, 10)
# for i in range(len(pixels)):
# pixels[i] = RED
|
{"/usb_camera.py": ["/basicmotiondetector.py"]}
|
22,464
|
kevingasik/BasileRoboticsRPI
|
refs/heads/master
|
/real_time_object_detection1.py
|
from imutils.video import VideoStream
from imutils.video import FPS
import numpy as np
import argparse
import imutils
import time
import cv2
#construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i","--image", required=True,help="path to input image")
ap.add_argument("-p","--prototxt",required=True,help="path to Caffe 'deploy' prototxt file")
ap.add_argument("-m", "--model", required=True,help="path to Caffe pre-trained model")
ap.add_argument("-c", "--confidence", type=float, default=0.2, help="minimum probability to filter weak detections")
args = vars(ap.parse_args())
#init the list of class labels MobileNet SSD was trained to detect
# then generate a set of bounding box colors for each class
CLASSES = ["background","aeroplane","bicycle","bird","boat",
"bottle","bus","car","cat","chair","cow","diningtable","dog",
"horse","motorbike","person","pottedplant","sheep",
"sofa","train","tvmonitor"]
COLORS = np.random.uniform(0,255, size=(len(CLASSES),3))
#load our serialized model from disk
print("[INFO] loading model...")
net = cv2.dnn.readNetFromCaffe(args["prototxt"], args["model"])
#init the video stream and allow the camera sensor to warmup,
# and initalisize the FPS counter
print("[INFO] starting video sream...")
vs = VideoStream(src=0).start()
time.sleep(2.0)
fps = FPS().start()
#loop over the grames from the video stream
while True:
#grab the frame from the threaded video stream and resize it
# to have a maximum width of 400 pixels
frame = vs.read()
frame = imutils.resize(frame, width=400)
#grab the frame dimensions and convert it to a blob
(h,w) = frame.shape[:2]
blob = cv2.dnn.blobFromImage(cv2.resize(frame, (300, 300)), 0.007843, (300,300), 127.5)
#pass the blob through the networks and obtains the detections and
# predictions
net.setInput(blob)
detections = net.forward()
for i in np.arange(0,detections.shape[2]):
#extract the confidence(i.e. probability) associated with
#the prediction
confidence = detections[0,0,i,2]
# filter out weak detections by ensuring the 'confidence' is
# greater than the minimum confidence
if confidence > args["confidence"]:
#extract the index of the class label from the 'detections',
# then compute the (x,y)-coordinates of the bounding box for
# the object
idx = int(detections[0, 0, i, 1])
box = detections[0, 0, i, 3:7] * np.array([w,h,w,h])
(startX, startY, endX, endY) = box.astype("int")
# display the prediction
label = "{}: {:.2f}%".format(CLASSES[idx], confidence*100)
print("[INFO] {}".format(label))
cv2.rectangle(image, (startX, startY), (endX, endY), COLORS[idx],2)
y = startY - 15 if staryY-15 > 15 else startY + 15
cv2.putText(image, label, (startX,y), cv2.FONT_HERSHEY_SIMPLEX,0.5,COLORS[idx],2)
cv2.imshow("Frame", frame)
key = cv2.waitKey(1) & 0xFF
if key == ord("q"):
break
fps.update()
|
{"/usb_camera.py": ["/basicmotiondetector.py"]}
|
22,465
|
kevingasik/BasileRoboticsRPI
|
refs/heads/master
|
/real_time_object_detection.py
|
# USAGE
# python3 real_time_object_detection.py --prototxt MobileNetSSD_deploy.prototxt.txt --model MobileNetSSD_deploy.caffemodel
# import the necessary packages
from imutils.video import VideoStream
from imutils.video import FPS
import numpy as np
import argparse
import imutils
import time
import cv2
# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-p", "--prototxt", required=True,
help="path to Caffe 'deploy' prototxt file")
ap.add_argument("-m", "--model", required=True,
help="path to Caffe pre-trained model")
ap.add_argument("-c", "--confidence", type=float, default=0.2,
help="minimum probability to filter weak detections")
args = vars(ap.parse_args())
# initialize the list of class labels MobileNet SSD was trained to
# detect, then generate a set of bounding box colors for each class
CLASSES = ["background", "aeroplane", "bicycle", "bird", "boat",
"bottle", "bus", "car", "cat", "chair", "cow", "diningtable",
"dog", "horse", "motorbike", "person", "pottedplant", "sheep",
"sofa", "train", "tvmonitor"]
#CLASSES = ["background","person","sofa", "train", "tvmonitor","aeroplane", "bicycle", "bird", "boat"]
COLORS = np.random.uniform(0, 255, size=(len(CLASSES), 3))
# load our serialized model from disk
print("[INFO] loading model...")
net = cv2.dnn.readNetFromCaffe(args["prototxt"], args["model"])
# initialize the video stream, allow the cammera sensor to warmup,
# and initialize the FPS counter
print("[INFO] starting video stream...")
vs = VideoStream(src=0).start()
time.sleep(2.0)
fps = FPS().start()
#import serial class and open serial port
#establish comms with an arduino
#move two servos that are being controlled by the OPENCM board...
#complete
# loop over the frames from the video stream
while True:
# grab the frame from the threaded video stream and resize it
# to have a maximum width of 400 pixels
frame = vs.read()
frame = imutils.resize(frame, width=1000)
# grab the frame dimensions and convert it to a blob
(h, w) = frame.shape[:2]
blob = cv2.dnn.blobFromImage(cv2.resize(frame, (300, 300)),
0.007843, (300, 300), 127.5)
# pass the blob through the network and obtain the detections and
# predictions
net.setInput(blob)
detections = net.forward()
cv2.line(frame, (w // 2, h ), (w // 2, 0), (0, 255, 0), 2)
cv2.line(frame, (w // 2 + 2, h ), (w // 2 + 2, 0), (0, 128, 0), 2)
cv2.line(frame, (w // 2 - 2, h ), (w // 2 - 2, 0), (0, 128, 0), 2)
totalUp = 0
totalDown = 0
# loop over the detections
for i in np.arange(0, detections.shape[2]):
# extract the confidence (i.e., probability) associated with
# the prediction
confidence = detections[0, 0, i, 2]
centroids = np.zeros((detections.shape[2], 2), dtype="int")
# filter out weak detections by ensuring the `confidence` is
# greater than the minimum confidence
if confidence > args["confidence"]:
# extract the index of the class label from the
# `detections`, then compute the (x, y)-coordinates of
# the bounding box for the object
idx = int(detections[0, 0, i, 1])
# if the class label is not a person, ignore it
if CLASSES[idx] != "person":
continue
box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
(startX, startY, endX, endY) = box.astype("int")
cX = int((startX + endX) / 2.0)
cY = int((startY + endY) / 2.0)
centroids[i] = (cX, cY)
# draw the prediction on the frame
label = "{}: {:.2f}%".format(CLASSES[idx],
confidence * 100)
cv2.rectangle(frame, (startX, startY), (endX, endY),
COLORS[idx], 2)
y = startY - 15 if startY - 15 > 15 else startY + 15
cv2.putText(frame, label, (startX, y),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, COLORS[idx], 2)
for centroid in centroids:
direction = centroid[0]
if centroid.any():
# if the direction is negative (indicating the object
# is moving up) AND the centroid is above the center
# line, count the object
if direction < w // 2: # and centroid[1] < H // 2:
totalUp += 1
# if the direction is positive (indicating the object
# is moving down) AND the centroid is below the
# center line, count the object
elif direction > w // 2 :# and centroid[1] > H // 2:
totalDown += 1
cv2.circle(frame, (centroid[0], centroid[1]), 4, (0, 255, 0), -1)
# construct a tuple of information we will be displaying on the
# frame
info = [
("left", totalUp),
("right", totalDown),
]
# loop over the info tuples and draw them on our frame
for (i, (k, v)) in enumerate(info):
text = "{}: {}".format(k, v)
cv2.putText(frame, text, (w // 4 + i*w//2 - 30, h - (20)),
cv2.FONT_HERSHEY_SIMPLEX, 1.5, (255, 0, 255), 2)
# show the output frame
cv2.imshow("Frame", frame)
key = cv2.waitKey(1) & 0xFF
# if the `q` key was pressed, break from the loop
if key == ord("q"):
break
# update the FPS counter
fps.update()
# stop the timer and display FPS information
fps.stop()
print("[INFO] elapsed time: {:.2f}".format(fps.elapsed()))
print("[INFO] approx. FPS: {:.2f}".format(fps.fps()))
# do a bit of cleanup
cv2.destroyAllWindows()
vs.stop()
|
{"/usb_camera.py": ["/basicmotiondetector.py"]}
|
22,466
|
kevingasik/BasileRoboticsRPI
|
refs/heads/master
|
/videostream.py
|
# import the ncessary packages
from webcamvideostream import WebcamVideoStream
class VideoStream:
def __init__(self, src=0,usePiCamera=False, resolution=(320,240),framerate=32):
#check to see if the picamera module should be used
if usePiCamera:
from pivideostream import PiVideoStream
self.stream = PiVideoStream(resolution=resolution, framerate=framerate)
else:
self.stream = WebcamVideoStream(src=src)
def start(self):
#start the threaded video stream
return self.stream.start()
def update(self):
#grab the next frame from the stream
self.stream.update()
def read(self):
#return the current frame
return self.stream.read()
def stop(self):
# stop the thread and release any resources
self.stream.stop()
if __name__ =="__main__":
videos = VideoStream()
|
{"/usb_camera.py": ["/basicmotiondetector.py"]}
|
22,467
|
kevingasik/BasileRoboticsRPI
|
refs/heads/master
|
/TendServos/tendserial.py
|
#!/usr/bin/env python
import serial
import time
import os
import termios
import cv2
import datetime
import threading
class TendSerial():
def __init__(self):
self.mystr = "hello"
self.row1 = []
self.row2 = []
self.openPort = False
self.freq = 3
self.right = 0
self.left = 0
def open_serial(self):
port='/dev/ttyAMA0'
#port='/dev/ttyACM0'
with open(port) as f:
attrs = termios.tcgetattr(f)
attrs[2] = attrs[2] & ~termios.HUPCL
termios.tcsetattr(f, termios.TCSAFLUSH,attrs)
self.ser = serial.Serial(
port='/dev/ttyACM0',
baudrate = 9600,
parity = serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS,
timeout=1
)
self.ser.close()
self.ser.open()
self.ser.reset_input_buffer()
self.ser.reset_output_buffer()
self.ser.close()
self.ser.open()
self.openPort = True
return
def hello(self,s):
print('hello {} ({:.4f})'.format(s,time.time()))
time.sleep(.3)
def do_every(self,period,f,*args):
def g_tick():
t = time.time()
count = 0
while True:
count += 1
yield max(t + count*period - time.time(),0)
g = g_tick()
while True:
time.sleep(next(g))
f(*args)
def send_serial(self):
# if time is greater than the sendTime send which ever right or left is greater
if(self.right > self.left):
send = 'r'
elif(self.left > self.right):
send = 'l'
else:
send = 'e'
print(send)
return
#self.ser.write(send.encode())
def send_thread(self):
timerThread = threading.Thread(target=lambda: self.do_every(self.freq,self.send_serial))
timerThread.daemon = True
timerThread.start()
if __name__ == "__main__":
count = 0
tserial = TendSerial()
#tserial.do_every(1,tserial.send_serial,0,1)
#threadmy = threading.Thread(target=lambda: do_every(5, hello,'foo')).start()
tserial.send_thread()
while True:
count = count + 1
if(count > 20000):
tserial.right = 2
print(count)
count = 0
key = cv2.waitKey(1) & 0xFF
# if the `q` key was pressed, break from the loop
if key == ord("q"):
break
|
{"/usb_camera.py": ["/basicmotiondetector.py"]}
|
22,468
|
kevingasik/BasileRoboticsRPI
|
refs/heads/master
|
/usb_camera.py
|
#import the necessary packages
from __future__ import print_function
from basicmotiondetector import BasicMotionDetector
from imutils.video import VideoStream
import numpy as np
import datetime
import datetime
import imutils
import time
import cv2
import argparse
#init the video streams and all them to warump
print("[INFO] starting camera...")
#webcam1 = VideoStream(src=0).start()
#ap = argparse.ArgumentParser()
#ap.add_argument("-p","--picamera", type=int, default=-1,help="weather or not the pi cam should be used")
#args = vars(ap.parse_args())
stream = VideoStream().start()
motion = BasicMotionDetector()
total = 0
time.sleep(2.0)
while True:
frames = []
#loop over the frames and their detectors
if stream and motion: #((webcam,camMotion))
#read the next frame and resize it to have a max width of 400 pixels
frame = stream.read()
frame = imutils.resize(frame, width=500)
# convert the frame to grayscale, blue it slightly, update the motion detector
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
gray = cv2.GaussianBlur(gray, (21,21),0)
locs = motion.update(gray)
# we should allow the motion detector to run for a bit
# and then accumlate a set of frame to form a nice avergage
#if total < 32:
# frames.append(frame)
# print("hello1")
# continue
#otherwise check to see if motion was detected
if len(locs) > 0:
#init the minimum and maximum xy coords
(minX, minY) = (np.inf, np.inf)
(maxX, maxY) = (-np.inf,-np.inf)
#loop over the ocations of motion and accumulate the minimum and maximum locations of the bounding boxes
for l in locs:
(x, y, w,h) = cv2.boundingRect(l)
(minX, maxX) = (min(minX, x), max(maxX, x + w))
(minY, maxY) = (min(minY, y), max(maxY, y +h))
cv2.rectangle(frame, (minX, minY), (maxX, maxY),(0,0,255), 3)
frames.append(frame)
total += 1
timestamp = datetime.datetime.now()
ts = timestamp.strftime("%A %d %B %Y %I:%M:%S%p")
#loop over the frames a second time
for(frame,name) in zip(frames, ("stream")):
# draw the timestamp on the frame and display it
cv2.putText(frame, ts, (10, frame.shape[0] - 10),cv2.FONT_HERSHEY_SIMPLEX, 0.35, (0,0,255),1)
cv2.imshow(name,frame)
#check to see if a key was pressed
key = cv2.waitKey(1) & 0xFF
#if the 'q' was pressed, break from the loop
if key==ord("q"):
break
# cleanup
print("[INFO] cleaning up...")
cv2.destroyAllWindows()
stream.stop()
|
{"/usb_camera.py": ["/basicmotiondetector.py"]}
|
22,469
|
kevingasik/BasileRoboticsRPI
|
refs/heads/master
|
/MorningGlory/main_MG_animation.py
|
#!/usr/bin/env python
import serial
import time
import os
import termios
import MG_serial
def main():
comms = MG_serial.Animation()
comms.open_serial()
print(comms.ser.readline())
count = 0
while True:
data = input("Enter something : ")
data = data +'\r\n'
if(data == "animate\r\n"):
comms.generate_order(1)
comms.dance_one()
comms.ser.write(data.encode())
read_serial = comms.ser.readline().decode()
print (read_serial)
if __name__ == "__main__":
main()
|
{"/usb_camera.py": ["/basicmotiondetector.py"]}
|
22,475
|
msokolik55/MessengerBots-python
|
refs/heads/main
|
/autobot.py
|
from fbchat import Client # , log
from fbchat.models import Message
from datetime import datetime
class AutoBot(Client):
def listen(self, markAlive=None):
if markAlive is not None:
self.setActiveStatus(markAlive)
self.startListening()
self.onListening()
recipient_id = self.uid
counter = 5
previous = None
while self.listening and self.doOneListen():
if counter <= 0:
break
now = datetime.now()
if previous is not None and now.second == previous.second:
continue
actual_time = f"{now.hour}:{now.minute:02}:{now.second:02}"
print(actual_time)
self.send(Message(actual_time), recipient_id)
previous = now
counter -= 1
self.stopListening()
|
{"/main.py": ["/echobot.py", "/config.py"], "/addresses.py": ["/config.py"]}
|
22,476
|
msokolik55/MessengerBots-python
|
refs/heads/main
|
/main.py
|
from echobot import EchoBot
from config import EMAIL, PASSWORD
client = EchoBot(EMAIL, PASSWORD)
client.listen()
|
{"/main.py": ["/echobot.py", "/config.py"], "/addresses.py": ["/config.py"]}
|
22,477
|
msokolik55/MessengerBots-python
|
refs/heads/main
|
/echobot.py
|
from fbchat import Client # , log
class Reply:
def __init__(self, keys, output):
self.keys = keys
self.output = output
class EchoBot(Client):
goodNight = Reply(["dobru noc"], "dobru noc ;*")
goodMorning = Reply(["dobre rano", "dobre ranko"], "dobre rano prajem :)")
goodAfternoon = Reply(["dobry den"], "dobry den prajem :D")
goodEvening = Reply(["dobry vecer"], "dobry vecer prajem ;)")
replies = [goodMorning, goodAfternoon, goodEvening, goodNight]
def generateOutput(self, message):
for reply in self.replies:
if message in reply.keys:
return reply.output
return ""
def onMessage(self, author_id, message_object, thread_id, thread_type,
**kwargs):
self.markAsDelivered(thread_id, message_object.uid)
self.markAsRead(thread_id)
# log.info(
# f"text: {message_object.text}\n" +
# f"from {thread_id}\n" +
# f"in {thread_type.name}")
msg_text = message_object.text.lower()
reply = self.generateOutput(msg_text)
# If you're not the author, echo
if (author_id != self.uid) and (len(reply) > 0):
message_object.text = reply
self.send(message_object, thread_id=thread_id,
thread_type=thread_type)
|
{"/main.py": ["/echobot.py", "/config.py"], "/addresses.py": ["/config.py"]}
|
22,478
|
msokolik55/MessengerBots-python
|
refs/heads/main
|
/config.py
|
from getpass import getpass
EMAIL = input("Email: ")
PASSWORD = getpass()
|
{"/main.py": ["/echobot.py", "/config.py"], "/addresses.py": ["/config.py"]}
|
22,479
|
msokolik55/MessengerBots-python
|
refs/heads/main
|
/addresses.py
|
from fbchat import Client
from unidecode import unidecode
from config import EMAIL, PASSWORD
client = Client(EMAIL, PASSWORD)
# Fetches a list of all users you're currently chatting with, as `User` objects
users = client.fetchAllUsers()
"""
for user in users:
name = unidecode(user.name).lower()
if "michal" in name:
print(f"{user.uid}: {user.name}")
"""
# client.logout()
|
{"/main.py": ["/echobot.py", "/config.py"], "/addresses.py": ["/config.py"]}
|
22,487
|
lukh/microparcel-python
|
refs/heads/master
|
/tests/test_up_message.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for `microparcel` package."""
import unittest
from microparcel import microparcel as up
class TestMicroparcelMessage(unittest.TestCase):
"""Tests for `microparcel` package."""
def setUp(self):
"""Set up test fixtures, if any."""
def tearDown(self):
"""Tear down test fixtures, if any."""
def test_get_8bits(self):
"""Test access to 8 bits messages."""
# full nibble, off 0
msg = up.Message(size=4)
msg.data[0] = 0xF
b = msg.get(0, 4)
self.assertTrue(b == 0xF)
b = msg.get(4, 4)
self.assertTrue(b == 0x0)
msg.data[0] = 0x0
# full nibble, off 8
msg.data[1] = 0xF
b = msg.get(8, 4)
self.assertTrue(b == 0xF)
b = msg.get(12, 4)
self.assertTrue(b == 0x0)
msg.data[1] = 0x0
# full nibble, off 6
msg.data[0] = 0b11000000
msg.data[1] = 0b00000011
b = msg.get(0, 6)
self.assertTrue(b == 0x0)
b = msg.get(10, 6)
self.assertTrue(b == 0x0)
b = msg.get(6, 4)
self.assertTrue(b == 0xF)
msg.data[1] = 0x0
msg.data[0] = 0x0
# full byte, off 0
msg.data[0] = 0xFF
b = msg.get(0, 8)
self.assertTrue(b == 0xFF)
b = msg.get(8, 8)
self.assertTrue(b == 0x0)
msg.data[0] = 0x0
# full byte, off 4
msg.data[0] = 0b11110000
msg.data[1] = 0b00001111
b = msg.get(0, 4)
self.assertTrue(b == 0x0)
b = msg.get(12, 4)
self.assertTrue(b == 0x0)
b = msg.get(4, 8)
self.assertTrue(b == 0xFF)
msg.data[1] = 0x0
msg.data[0] = 0x0
# 6bits, off 6
msg.data[0] = 0b11000000
msg.data[1] = 0b00001001
b = msg.get(0, 6)
self.assertTrue(b == 0x0)
b = msg.get(12, 4)
self.assertTrue(b == 0x0)
b = msg.get(6, 6)
self.assertTrue(b == 0b100111)
msg.data[1] = 0x0
msg.data[0] = 0x0
def test_set_8bits(self):
"""Test write to 8 bits messages."""
msg = up.Message(size=4)
msg.set(0, 4, 0xF)
self.assertTrue(msg.data[0] == 0xF)
msg.data[0] = 0x0
msg.set(0, 8, 0xFF)
self.assertTrue(msg.data[0] == 0xFF)
msg.data[0] = 0x0
msg.set(4, 4, 0xF)
self.assertTrue(msg.data[0] == (0xF<<4))
msg.data[0] = 0x0
msg.set(2, 4, 0xF)
self.assertTrue(msg.data[0] == (0xF<<2))
msg.data[0] = 0x0
msg.set(6, 4, 0xF)
self.assertTrue(msg.data[0] == (0x3<<6))
self.assertTrue(msg.data[1] == (0x3))
msg.data[0] = 0x0
msg.data[1] = 0x0
msg.set(6, 8, 0xFF)
self.assertTrue(msg.data[0] == (0x3<<6))
self.assertTrue(msg.data[1] == (0x3F))
msg.data[0] = 0x0
msg.data[1] = 0x0
|
{"/tests/test_up_message.py": ["/microparcel/__init__.py"], "/microparcel/__init__.py": ["/microparcel/microparcel.py"], "/tests/test_up_parser.py": ["/microparcel/__init__.py"]}
|
22,488
|
lukh/microparcel-python
|
refs/heads/master
|
/tests/__init__.py
|
# -*- coding: utf-8 -*-
"""Unit test package for microparcel."""
|
{"/tests/test_up_message.py": ["/microparcel/__init__.py"], "/microparcel/__init__.py": ["/microparcel/microparcel.py"], "/tests/test_up_parser.py": ["/microparcel/__init__.py"]}
|
22,489
|
lukh/microparcel-python
|
refs/heads/master
|
/microparcel/microparcel.py
|
# -*- coding: utf-8 -*-
from enum import Enum
class Message(object):
"""
Encapsulates data byte
Provide bit access to the data via get/set.
"""
def __init__(self, size=0, data=None):
assert (data is None or isinstance(data, list))
self.data = [0 for i in range(size)] if data is None else data
def get(self, offset, bitsize):
"""
return value stored in the data array,
at address "offset", in bit.
:param offset: the position in the array
:param bitsize: the size of the data to return (1 to 16)
"""
assert (bitsize <= 16)
assert (bitsize > 0)
assert ((offset+bitsize) <= 8*self.size)
assert((bitsize <= 8) or ((bitsize > 8) and (offset & 0x3) == 0))
if bitsize <= 8:
# on one byte
if((offset & 0x7) + bitsize <= 8):
mask = (1 << bitsize) - 1
byte_idx = offset >> 3
byte_shift = offset & 0x7
return (self.data[byte_idx] >> byte_shift) & mask
else:
mask = (1 << bitsize) - 1
byte_idx = offset >> 3
byte_shift = offset & 0x7
mask_lsb = mask & ((1 << (8 - byte_shift)) - 1)
mask_msb = mask >> (8 - byte_shift)
lsb_part = (self.data[byte_idx] >> byte_shift) & mask_lsb
msb_part = self.data[byte_idx+1] & mask_msb
return lsb_part | (msb_part << (8 - byte_shift))
else:
mask = (1 << bitsize) - 1
byte_idx = offset >> 3
part0 = self.data[byte_idx] & (mask & 0xFF)
part1 = (self.data[byte_idx + 1] & (mask >> 8)) << 8
return part0 | part1
def set(self, offset, bitsize, value):
"""
Set a specific value in the data array, at offset.
:param offset: position in the data array, in bit.
:param bitsize: size of the data to set, in bit (1 to 16)
:param value: the value to set
"""
assert (bitsize <= 16)
assert (bitsize > 0)
assert ((offset+bitsize) <= 8*self.size)
assert((bitsize <= 8) or ((bitsize > 8) and (offset & 0x3) == 0))
if bitsize <= 8:
# on one byte
if((offset & 0x7) + bitsize <= 8):
mask = (1 << bitsize) - 1
byte_idx = offset >> 3
byte_shift = offset & 0x7
self.data[byte_idx] &= ~(mask << byte_shift)
self.data[byte_idx] |= (value & mask) << byte_shift
return
else:
mask = (1 << bitsize) - 1
byte_idx = offset >> 3
lsb_byte_shift = offset & 0x7
msb_byte_shift = 8 - lsb_byte_shift
mask_lsb = mask & ((1 << msb_byte_shift) - 1)
mask_msb = mask >> msb_byte_shift
# lsb
self.data[byte_idx] &= ~(mask_lsb << lsb_byte_shift)
self.data[byte_idx] |= (value & mask_lsb) << lsb_byte_shift
# msb
self.data[byte_idx+1] &= ~mask_msb
self.data[byte_idx+1] |= (value >> msb_byte_shift) & mask_msb
return # lsb_part | (msb_part << (8 - byte_shift))
else:
mask = (1 << bitsize) - 1
byte_idx = offset >> 3
self.data[byte_idx] &= ~(mask & 0xFF)
self.data[byte_idx] |= (value & 0xFF)
self.data[byte_idx+1] &= ~(mask >> 8)
self.data[byte_idx+1] |= (value >> 8)
@property
def size(self):
return len(self.data)
class Frame(object):
"""
Encapsulate a Message in a Frame,
between a Start Of Frame and a Checksum (8bits).
"""
kSOF = 0xAA
def __init__(self):
self.SOF = 0
self.message = Message(0)
self.checksum = 0
@property
def size(self):
return self.message.size + 2
@property
def data(self):
return [self.SOF] + self.message.data + [self.checksum]
def make_parser_cls(message_size):
"""
A Factory to generate a Parser handling Message
of message_size.
"""
class Parser(object):
"""
Parses bytes to rebuild messages from byte stream.
And generates frames from messages.
Used for sending messages via network or serial line.
"""
MsgSize = message_size
FrameSize = message_size + 2
class Status(Enum):
Complete = 0
NotComplete = 1
Error = 2
class State(Enum):
Idle = 0
Busy = 1
def __init__(self):
self._state = self.State.Idle
self._status = self.Status.NotComplete
self._buffer = 0
def parse(self, in_byte, out_msg):
"""
takes a byte, parses it to rebuild a message.
:param in_byte: byte to parse.
:param out_message: reference of the message built.
:ret Status; Complete, NotComplete, Error.
"""
if self._state == self.State.Idle:
# when receiving a byte in idle, reset
self._buffer = []
# valid start of frame
if in_byte == Frame.kSOF:
self._status = self.Status.NotComplete
self._state = self.State.Busy
self._buffer.append(in_byte)
else:
self._status = self.Status.Error
else:
self._buffer.append(in_byte)
if len(self._buffer) == self.FrameSize:
if self._isCheckSumValid():
self._status = self.Status.Complete
out_msg.data = self._buffer[1:self.FrameSize-1]
else:
self._status = self.Status.Error
self._state = self.State.Idle
else:
self._status = self.Status.NotComplete
return self._status
def encode(self, in_msg):
"""
Encode a Message in a Frame, calculating the CheckSum
"""
assert(in_msg.size == self.MsgSize)
frame = Frame()
frame.SOF = Frame.kSOF
frame.message = in_msg
frame.checksum = (frame.SOF + sum(frame.message.data)) & 0xFF
return frame
def _isCheckSumValid(self):
if len(self._buffer) != self.FrameSize:
raise ValueError()
return (sum(self._buffer[0: -1]) & 0xFF) == self._buffer[-1]
return Parser
|
{"/tests/test_up_message.py": ["/microparcel/__init__.py"], "/microparcel/__init__.py": ["/microparcel/microparcel.py"], "/tests/test_up_parser.py": ["/microparcel/__init__.py"]}
|
22,490
|
lukh/microparcel-python
|
refs/heads/master
|
/microparcel/__init__.py
|
# -*- coding: utf-8 -*-
"""Top-level package for microparcel."""
__author__ = """Vivien Henry"""
__email__ = 'vivien.henry@outlook.fr'
__version__ = '0.1.1'
from .microparcel import Message, Frame, make_parser_cls
|
{"/tests/test_up_message.py": ["/microparcel/__init__.py"], "/microparcel/__init__.py": ["/microparcel/microparcel.py"], "/tests/test_up_parser.py": ["/microparcel/__init__.py"]}
|
22,491
|
lukh/microparcel-python
|
refs/heads/master
|
/tests/test_up_parser.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for `microparcel` package."""
import unittest
from microparcel import microparcel as up
class TestMicroparcelParser(unittest.TestCase):
"""Tests for `microparcel` package."""
def setUp(self):
"""Set up test fixtures, if any."""
def tearDown(self):
"""Tear down test fixtures, if any."""
def test_encode(self):
"""Test Parser Encoding."""
parser = up.make_parser_cls(4)()
msg = up.Message(4)
msg.data[0] = 0
msg.data[1] = 1
msg.data[2] = 2
msg.data[3] = 3
frame = parser.encode(msg)
self.assertEqual(frame.SOF, 0xAA)
self.assertEqual(frame.message.data[0], 0)
self.assertEqual(frame.message.data[1], 1)
self.assertEqual(frame.message.data[2], 2)
self.assertEqual(frame.message.data[3], 3)
self.assertEqual(frame.checksum, 0xAA + sum([0,1,2,3]))
def test_decode(self):
"""Test Parser Decoding."""
parser = up.make_parser_cls(4)()
msg = up.Message()
# valid message
self.assertEqual(parser.parse(0xAA, msg), parser.Status.NotComplete)
self.assertEqual(parser.parse(0x0, msg), parser.Status.NotComplete)
self.assertEqual(parser.parse(0x1, msg), parser.Status.NotComplete)
self.assertEqual(parser.parse(0x2, msg), parser.Status.NotComplete)
self.assertEqual(parser.parse(0x3, msg), parser.Status.NotComplete)
self.assertEqual(parser.parse(0xFF & (0xAA + 0 + 1 + 2 + 3), msg), parser.Status.Complete)
self.assertEqual(msg.data[0], 0)
self.assertEqual(msg.data[1], 1)
self.assertEqual(msg.data[2], 2)
self.assertEqual(msg.data[3], 3)
# invalid CS
self.assertEqual(parser.parse(0xAA, msg), parser.Status.NotComplete)
self.assertEqual(parser.parse(0x44, msg), parser.Status.NotComplete)
self.assertEqual(parser.parse(0x99, msg), parser.Status.NotComplete)
self.assertEqual(parser.parse(0xB, msg), parser.Status.NotComplete)
self.assertEqual(parser.parse(0x4, msg), parser.Status.NotComplete)
self.assertEqual(parser.parse(0xFF, msg), parser.Status.Error)
# Invalid SOF
self.assertEqual(parser.parse(0xDD, msg), parser.Status.Error)
self.assertEqual(parser.parse(0xEE, msg), parser.Status.Error)
self.assertEqual(parser.parse(0xBB, msg), parser.Status.Error)
self.assertEqual(parser.parse(0xAA, msg), parser.Status.NotComplete)
self.assertEqual(parser.parse(0x4, msg), parser.Status.NotComplete)
self.assertEqual(parser.parse(0x5, msg), parser.Status.NotComplete)
self.assertEqual(parser.parse(0x6, msg), parser.Status.NotComplete)
self.assertEqual(parser.parse(0x7, msg), parser.Status.NotComplete)
self.assertEqual(parser.parse(0xFF & (0xAA + 4+5+6+7), msg), parser.Status.Complete)
|
{"/tests/test_up_message.py": ["/microparcel/__init__.py"], "/microparcel/__init__.py": ["/microparcel/microparcel.py"], "/tests/test_up_parser.py": ["/microparcel/__init__.py"]}
|
22,497
|
nareynolds/pyRPDR
|
refs/heads/master
|
/examples.py
|
# examples.py
# import pyRPDR
import rpdr
# instantiate RPDR dataset
rpdrDir = "/path/to/directory/containing/RPDR/text/files"
ds = rpdr.Dataset( rpdrDir )
# instantiate a patient
empi = '1234567'
p = rpdr.Patient( ds, empi )
# print patient's timeline
p.timeline()
# print patient's timeline for limited tables
tableNames = "Rdt Rad"
p.timeline( tableNames )
# look at particular event in patient's timeline
tableName = "Rad"
eventId = 1
p.event( tableName, eventId )
# record a note about patient
author = "Your Name"
note = "something noteable about this patient"
p.writeNote( author, note )
# print patient notes
p.printNotes()
# delete patient notes
noteIds = [1,2,3,4,5]
p.deleteNotes( noteIds )
|
{"/examples.py": ["/rpdr.py"]}
|
22,498
|
nareynolds/pyRPDR
|
refs/heads/master
|
/rpdr.py
|
# rpdr.py
# add working directory to search path
import os
import sys
sys.path.insert(0, os.path.realpath(__file__))
# get RPDR Table info
import rpdrdefs
# get file management tools
import shutil
import fnmatch
import re
# get SQLite tools
import sqlite3
# get csv tools
import csv
# get time tools
import time
# for dealing with unicode
import unicodedata
class Dataset:
#--------------------------------------------------------------------------------------------
# instantiation
def __init__ ( self, dataDir, dbName='RPDR_DATASET' ):
# save directory
self.dir = dataDir
# compute path to SQLite database
self.dbPath = os.path.join( self.dir, '%s.sqlite' % dbName )
# search for RPDR text files
self.tables = self.findTables(self.dir)
if len(self.tables) < 1:
print "Warning! No RPDR files found in given directory: %s" % self.dir
# search for SQLite database
if not os.path.isfile(self.dbPath):
print "Warning! SQLite database found: %s" % self.dbPath
return
# create/connect to SQLite database and enable dictionary access of rows
if not os.path.isfile(self.dbPath):
print "Creating SQLite database: %s" % self.dbPath
self.dbCon = sqlite3.connect(self.dbPath)
self.dbCon.row_factory = sqlite3.Row
# loop through RPDR text files
for tableName in self.tables:
# create RPDR table in database
if self.dbCreateRpdrTable( tableName ):
# fill table
self.dbFillRpdrTable( tableName )
#--------------------------------------------------------------------------------------------
#
def findTables ( self, dataDir ):
# check that the given directory exists
if not os.path.isdir(dataDir):
print "Error! Given directory doesn't exist: %s" % dataDir
return
# list the import directory files
files = [ f for f in os.listdir(dataDir) if os.path.isfile( os.path.join(dataDir,f) ) ]
# get list of vaild RPDR file endings
rpdrFileEndings = [ '%s.%s' % (table.name, table.fileExt) for table in rpdrdefs.Tables]
# check if each file follows the RPDR naming convention
rpdrFiles = []
rpdrFilePrefixes = []
for f in files:
for fileEnding in rpdrFileEndings:
if f.endswith( fileEnding ):
rpdrFiles.append(f)
rpdrFilePrefixes.append( f.rstrip(fileEnding) )
break
# check if all RPDR files have the same prefix
if len(list(set( rpdrFilePrefixes ))) > 1:
print "Warning! Not all the RPDR files have the same prefix: %s" % str(rpdrFilePrefixes)
# loop through RPDR files
tables = {}
for rpdrFile in rpdrFiles:
filePath = os.path.join( dataDir, rpdrFile )
# determine type of RPDR table of the file
tableDefinition = None
for t in rpdrdefs.Tables:
if filePath.endswith( '%s.%s' % (t.name, t.fileExt) ):
tableDefinition = t
break
# check that file is a known RPDR table type
if tableDefinition == None:
print "Error! File is not a known RPDR file: %s" % filePath
return
# open file as csv file with approriate dialect
csvFile = open(filePath,"rU")
csvReader = csv.reader(
csvFile,
delimiter = tableDefinition.csvDialect.delimiter,
doublequote = tableDefinition.csvDialect.doublequote,
escapechar = tableDefinition.csvDialect.escapechar,
lineterminator = tableDefinition.csvDialect.lineterminator,
quotechar = tableDefinition.csvDialect.quotechar,
quoting = tableDefinition.csvDialect.quoting,
skipinitialspace = tableDefinition.csvDialect.skipinitialspace,
strict = tableDefinition.csvDialect.strict
)
# get CSV headers from file
headers = csvReader.next()
# close file
csvFile.close()
# check headers against table definitions in RpdrTables
columns = [ col.name for col in tableDefinition.columns ]
unexpectedCols = []
for header in headers:
if header.strip() not in columns:
unexpectedCols.append( header )
if len(unexpectedCols) > 0:
print "Error! Unexpected columns found in %s.txt: %s" % ( tableDefinition.name, str(unexpectedCols) )
return
if len(columns) > len(headers):
print "Error! Missing columns in file %s.txt: %s" % ( tableDefinition.name, list(set(columns) - set(headers)) )
return
tables[tableDefinition.name] = { 'file':filePath, 'definition':tableDefinition }
#
return tables
#--------------------------------------------------------------------------------------------
#
def dbCreateRpdrTable ( self, tableName ):
tableDefinition = self.tables[tableName]['definition']
# check if the RPDR table already exists
with self.dbCon:
dbCur = self.dbCon.cursor()
dbCur.execute( "SELECT name FROM sqlite_master WHERE type='table' AND name='%s'" % tableDefinition.name )
qResult = dbCur.fetchone()
if qResult is not None:
return
# create column declarations
colDecs = []
for col in tableDefinition.columns:
newDec = " `%s` %s " % (col.name, col.type)
if col.notNull:
newDec = " %s NOT NULL " % newDec
if col.primaryKey:
newDec = " %s PRIMARY KEY " % newDec
colDecs.append( newDec )
# shouldn't use unique with "INSERT OR IGNORE" below to avoid unexpected ignoring of data
# not including foreign keys, because not worth the work.
#if col.unique:
# newDec = " %s UNIQUE " % newDec
# create database table
qCreate = "CREATE TABLE `%s` ( %s )" % ( tableDefinition.name, ','.join(colDecs) )
with self.dbCon:
dbCur = self.dbCon.cursor()
dbCur.execute(qCreate)
# add column indices
for col in tableDefinition.columns:
if col.index:
with self.dbCon:
dbCur = self.dbCon.cursor()
qIndex = "CREATE INDEX `%s_%s_idx` ON `%s` (`%s`)" % (tableDefinition.name, col.name, tableDefinition.name, col.name)
dbCur.execute(qIndex)
#
return True
#--------------------------------------------------------------------------------------------
#
def dbFillRpdrTable ( self, tableName ):
tableDefinition = self.tables[tableName]['definition']
filePath = self.tables[tableName]['file']
# get list of column names in table
columnNames = [ col.name for col in tableDefinition.columns ]
# prepare insert query - will ignore duplicates for tables with primary keys and uniqueness
qInsert = "INSERT OR IGNORE INTO %s ( `%s` ) VALUES ( %s )" % (tableDefinition.name, '`, `'.join(columnNames), ', '.join([ '?' for col in columnNames]) )
# header table definitions from RpdrTables
columnNames = [ col.name for col in tableDefinition.columns ]
# open file as csv file with approriate dialect
csvFile = open(filePath,"rU")
csvReader = csv.reader(
csvFile,
delimiter = tableDefinition.csvDialect.delimiter,
doublequote = tableDefinition.csvDialect.doublequote,
escapechar = tableDefinition.csvDialect.escapechar,
lineterminator = tableDefinition.csvDialect.lineterminator,
quotechar = tableDefinition.csvDialect.quotechar,
quoting = tableDefinition.csvDialect.quoting,
skipinitialspace = tableDefinition.csvDialect.skipinitialspace,
strict = tableDefinition.csvDialect.strict
)
# get CSV headers from file
headers = csvReader.next()
# fill table
print "Filling database table: '%s'" % tableDefinition.name
with self.dbCon:
dbCur = self.dbCon.cursor()
numCols = len(columnNames)
lineIdx = -1
for rIdx, row in enumerate(csvReader):
lineIdx = lineIdx + 1
try:
# check for too few columns
if len(row) < numCols:
print "Error (row %d)! Less than %d columns found! %s" % (lineIdx, numCols, row)
return
# handle extra columns: combine end columns
if len(row) > numCols:
row = row[:numCols-1] + ['|'.join(row[numCols-1:])]
# reformatting
for cIdx, col in enumerate(tableDefinition.columns):
# enforce ascii text
if row[cIdx]:
row[cIdx] = self.enforce_ascii( row[cIdx] )
# date reformatting
if col.dateReformat and row[cIdx]:
row[cIdx] = time.strftime( col.dateReformat.reformat, time.strptime(row[cIdx], col.dateReformat.format) )
# handle free-text report in last column
if tableDefinition.freeTextReportInLastColumn:
reportRows = [ row[-1] ]
while 1:
nextRow = csvReader.next()
lineIdx = lineIdx + 1
if not nextRow:
reportRows.append('')
else:
if '[report_end]' not in nextRow[0]:
reportRows.append( '|'.join(nextRow) )
else:
break
row[-1] = '\n'.join(reportRows)
# insert row into database
dbCur.execute(qInsert, row)
except:
print "Error processing line %d:" % lineIdx
raise
# close file
csvFile.close()
#--------------------------------------------------------------------------------------------
def enforce_ascii(self, s):
# strip non-unicode characters
s = "".join(i for i in s if ord(i)<128)
# ascii encoding
s = s.encode('ascii','ignore')
return s
class Patient:
#--------------------------------------------------------------------------------------------
def __init__( self, dataset, empi=None ):
# validate args
if dataset is None:
print "Warning! Must provide RPDR dataset"
return
if empi is None:
print "Warning! Must provide patient EMPI"
return
# RPDR dataset
self.dataset = dataset
# database info
self.dbPath = self.dataset.dbPath
self.dbCon = self.dataset.dbCon
# patient Enterprise Master Patient Index (EMPI)
self.empi = empi
# names of RPDR tables
self.rpdrTableNames = [ t.name for t in rpdrdefs.Tables ]
# given RPDR dataset table names
self.datasetTableNames = None
# given RPDR dataset table definitions
self.datasetTableDefinitions = None
# given RPDR dataset table names used in self.timeline()
self.timelineTableNames = None
# given RPDR dataset table definitions used in self.timeline()
self.timelineTableDefinitions = None
# basic info about patient
self.demographics = None
# notes about the patient saved in database
self.patientNotes = None
# get list of tables in database
with self.dbCon:
dbCur = self.dbCon.cursor()
dbCur.execute( "SELECT name FROM sqlite_master WHERE type='table'" )
qResult = dbCur.fetchall()
if qResult is None:
print "Warning! No tables in database."
return
else:
dbTableNames = [str(row[0]) for row in qResult]
# get list of RPDR tables in given database
self.datasetTableNames = [ n for n in dbTableNames if n in self.rpdrTableNames ]
self.datasetTableDefinitions = [ t for t in rpdrdefs.Tables if t.name in self.datasetTableNames ]
# check that there are rpdr tables in given database
if len(self.datasetTableNames) < 1:
print "Warning! No RPDR tables found in database."
# get list of RPDR tables in database to use in self.timeline()
possibleTimelineTableNames = [ t.name for t in rpdrdefs.Tables if t.useInTimeline ]
self.timelineTableNames = [ n for n in dbTableNames if n in possibleTimelineTableNames ]
self.timelineTableDefinitions = [ t for t in rpdrdefs.Tables if t.name in self.timelineTableNames ]
# search for basic patient demographics
with self.dbCon:
dbCur = self.dbCon.cursor()
dbCur.execute( "SELECT * FROM Dem WHERE EMPI=? LIMIT 1", (empi,) )
qResult = dbCur.fetchone()
if qResult is None:
print "Warning: Couldn't find patient in Dem with EMPI = %s." % empi
return
self.demographics = qResult
# instantiate PatientNotes to use with this patient
self.patientNotes = PatientNotes(self.dataset)
#--------------------------------------------------------------------------------------------
def timeline( self, tables='' ):
# determine tables to search
if tables:
timelineTableDefinitions = [ t for t in self.timelineTableDefinitions if t.name in tables ]
if not timelineTableDefinitions:
print "Error: Provided timeline tables are invalid ( %s )" % tables
return
else:
timelineTableDefinitions = self.timelineTableDefinitions
# create SQL search query
tablesSearchQueries = []
for tableDefinition in timelineTableDefinitions:
dateColName = None
blurbColName = None
for col in tableDefinition.columns:
if col.timelineDate:
dateColName = col.name
if col.timelineBlurb:
blurbColName = col.name
q = "SELECT '%s' AS 'Table', rowid AS EventId, %s AS Date, round( ( ( julianday(%s) - julianday('%s') ) / 365 ), 2 ) AS Age, %s AS Blurb FROM %s WHERE EMPI = %s" \
% (tableDefinition.name, dateColName, dateColName, self.demographics['Date_of_Birth'], blurbColName, tableDefinition.name, self.empi )
tablesSearchQueries.append(q)
qSearch = "Select * From ( %s ) ORDER BY Date" % " UNION ".join(tablesSearchQueries)
# query database
events = None
with self.dbCon:
dbCur = self.dbCon.cursor()
dbCur.execute( qSearch )
qResult = dbCur.fetchall()
if qResult is None:
print "Warning! Database query returned nothing."
return
events = qResult
# print events
print " _______________________________________________________________________________________________\n |"
print " | Timeline: %s" % str(tables)
print " |----------------------------------------------------------------------------------------------"
print " |Table\t|Event \t|Date \t\t|Age \t|Blurb"
print " |----------------------------------------------------------------------------------------------"
print " |Dem \t|1 \t|%s \t|0.00 \t|Birth Date" % self.demographics['Date_of_Birth']
for event in events:
if len(event['Blurb']) > 50:
blurb = "%s..." % event['Blurb'][:50]
else:
blurb = event['Blurb']
print " |%s \t|%s \t|%s \t|%s \t|%s" % (event['Table'], str(event['EventId']), event['Date'], str(event['Age']), blurb )
if self.demographics['Date_of_Death']:
print " |Dem \t|1 \t|%s \t| \t|Birth Date" % self.demographics['Date_of_Birth']
print " |______________________________________________________________________________________________\n"
#--------------------------------------------------------------------------------------------
def event( self, tableName, eventId ):
# validate args
if tableName:
tableDefinition = [ t for t in self.datasetTableDefinitions if t.name in tableName ][0]
else:
print "Warning! '%s' is not a valid RPDR table." % tableName
return
if not eventId:
print "Warning! Must provide RPDR event ID."
return
# search for event
qResult = None
with self.dbCon:
dbCur = self.dbCon.cursor()
dbCur.execute( "SELECT * FROM %s WHERE EMPI = ? AND rowid = ? LIMIT 1" % tableDefinition.name, (self.empi,eventId) )
qResult = dbCur.fetchone()
if qResult is None:
print "Warning! Query for event returned nothing."
return
eventCols = [c for c in qResult]
# determine spacing after name
colLength = 0
for col in tableDefinition.columns:
if len(col.name) > colLength:
colLength = len(col.name)
print " _______________________________________________________________________________________________\n |"
# print table name
spacing = ''.join([ ' ' for i in xrange(colLength - len("Table")) ])
print " |Table:%s %s" % (spacing, tableDefinition.name)
# account for last column containing a free-text report
spacing = "|%s" % ''.join([ ' ' for i in xrange(colLength+1) ])
eventCols[len(eventCols)-1] = eventCols[len(eventCols)-1].replace('\n', '\n %s ' % spacing)
# print columns
for cIdx, col in enumerate(tableDefinition.columns):
spacing = ''.join([ ' ' for i in xrange(colLength - len(col.name)) ])
print " |%s:%s %s" % (col.name, spacing, eventCols[cIdx])
print " |______________________________________________________________________________________________\n"
#--------------------------------------------------------------------------------------------
def writeNote( self, author, note ):
self.patientNotes.write( author, self.empi, note )
#--------------------------------------------------------------------------------------------
def deleteNotes( self, noteIds ):
self.patientNotes.delete( noteIds )
#--------------------------------------------------------------------------------------------
def printNotes( self ):
self.patientNotes.printAll( self.empi )
class PatientNotes:
#--------------------------------------------------------------------------------------------
def __init__( self, dataset, tableName='PatientNotes' ):
# RPDR dataset
self.dataset = dataset
# database info
self.dbPath = self.dataset.dbPath
self.dbCon = self.dataset.dbCon
# name of database table containing patient notes
self.patientNotesTableName = 'PatientNotes'
# check if the patient notes database table exists
qResult = None
with self.dbCon:
dbCur = self.dbCon.cursor()
dbCur.execute( "SELECT name FROM sqlite_master WHERE type='table' AND name='%s'" % self.patientNotesTableName )
qResult = dbCur.fetchone()
if qResult is None:
# patient notes table doesn't exist - create table in database
qCreate = "CREATE TABLE " + self.patientNotesTableName + " ( id INTEGER PRIMARY KEY, Author TEXT NOT NULL, CreatedTimestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL, Empi TEXT NOT NULL, Note TEXT NOT NULL )"
with self.dbCon:
dbCur = self.dbCon.cursor()
dbCur.execute(qCreate)
print "Created database table '%s'." % self.patientNotesTableName
#--------------------------------------------------------------------------------------------
def write(self, author, empi, note):
# check that args are valid strings
if not author or not isinstance(author, str):
print "Error! Must provide an author string."
return
if not empi or not isinstance(empi, str):
print "Error! Must provide an empi string."
return
if not note or not isinstance(note, str):
print "Error! Must provide a note string."
return
with self.dbCon:
dbCur = self.dbCon.cursor()
# check that the patient exists
dbCur.execute( "SELECT count(*) FROM Mrn WHERE Enterprise_Master_Patient_Index = ?", (empi,) )
if dbCur.fetchone()[0] == 0:
print "Warning! The patient with EMPI %d was not found in the Mrn table." % empi
return
# record note
dbCur.execute( "INSERT INTO %s ( Author, Empi, Note ) VALUES ( ?, ?, ? )" % self.patientNotesTableName, ( author, empi, note ) )
#--------------------------------------------------------------------------------------------
def delete(self, noteIds):
# check that at least 1 note ID was provided as a list
if not isinstance( noteIds, list ):
print "Warning! Nothing deleted. Must provide a list of note IDs."
return
numIds = len( noteIds )
if numIds == 0:
print "Warning! Nothing deleted. Must provide a list of note IDs."
return
# loop through list of note ids
for noteId in noteIds:
with self.dbCon:
dbCur = self.dbCon.cursor()
# check note's existence
dbCur.execute( "SELECT count(*) FROM %s WHERE id = ?" % self.patientNotesTableName, (noteId,) )
if dbCur.fetchone()[0] == 0:
print "Warning! Nothing deleted. The patient note with id %d was not found!" % noteId
return
# delete note
dbCur.execute( "DELETE FROM %s WHERE id = ?" % self.patientNotesTableName, (noteId,) )
#--------------------------------------------------------------------------------------------
def printAll(self, empi):
with self.dbCon:
dbCur = self.dbCon.cursor()
# check that the patient exists
dbCur.execute( "SELECT count(*) FROM Mrn WHERE Enterprise_Master_Patient_Index = ?", (empi,) )
if dbCur.fetchone()[0] == 0:
print "Warning! The patient with EMPI %d was not found in the Mrn table." % empi
return
# get patient notes
dbCur.execute( "SELECT * FROM %s WHERE Empi = ?" % self.patientNotesTableName, (empi,) )
qResult = dbCur.fetchall()
if qResult is None:
print "This patient has no notes."
return
notes = qResult
# print notes
print " _______________________________________________________________________________________________\n |"
print " | Patient Notes ( EMPI = %s )" % empi
print " |----------------------------------------------------------------------------------------------"
print " |id \t|Timestamp \t\t|Author \t|Note"
print " |----------------------------------------------------------------------------------------------"
for note in notes:
if len(note['Note']) > 50:
blurb = "%s..." % note['Note'][:50]
else:
blurb = note['Note']
print " |%s \t|%s \t|%s \t|%s" % (note['id'], str(note['CreatedTimestamp']), note['Author'], blurb )
print " |______________________________________________________________________________________________\n"
|
{"/examples.py": ["/rpdr.py"]}
|
22,499
|
nareynolds/pyRPDR
|
refs/heads/master
|
/rpdrdefs.py
|
# rpdrtables.py
# get csv tools
from csv import QUOTE_NONE
# get namedtuple
from collections import namedtuple
#--------------------------------------------------------------------------------------------
# define RPDR table column foreign key reference
ForeignKeyRef = namedtuple('ForeignKeyRef','table column')
# define RPDR table column date/time reformat map
DateReformat = namedtuple('DateReformat','format reformat')
SQLITE_DATE_FORMAT = '%Y-%m-%d'
# define RPDR table column
TableColumn = namedtuple('TableColumn','name type primaryKey index unique notNull foreignKeyRef dateReformat timelineDate timelineBlurb')
# define RPDR csv dialect and some standards
CsvDialect = namedtuple('CsvDialect','delimiter doublequote escapechar lineterminator quotechar quoting skipinitialspace strict')
StandardCsvDialect = CsvDialect(
delimiter = '|',
doublequote = True,
escapechar = None,
lineterminator = '\r\n',
quotechar = '',
quoting = QUOTE_NONE,
skipinitialspace = True,
strict = False
)
# define RPDR table
Table = namedtuple('Table', 'name fileExt columns csvDialect freeTextReportInLastColumn useInTimeline')
#--------------------------------------------------------------------------------------------
# define Car RPDR table
Car = Table(
name = 'Car',
fileExt = 'txt',
csvDialect = StandardCsvDialect,
freeTextReportInLastColumn = True,
useInTimeline = True,
columns=[
TableColumn(
name = "EMPI",
type = "TEXT",
primaryKey = False,
index = True,
unique = False,
notNull = True,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "MRN_Type",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "MRN",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Report_Number",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "MID",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Report_Date_Time",
type = "DATETIME",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = True,
timelineBlurb = False,
dateReformat = DateReformat( format='%m/%d/%Y %I:%M:%S %p', reformat=SQLITE_DATE_FORMAT )
),
TableColumn(
name = "Report_Description",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = True,
dateReformat = None
),
TableColumn(
name = "Report_Status",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Report_Type",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Report_Text",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
)
]
)
#--------------------------------------------------------------------------------------------
# define Con RPDR table
Con = Table(
name = 'Con',
fileExt = 'txt',
csvDialect = StandardCsvDialect,
freeTextReportInLastColumn = False,
useInTimeline = False,
columns=[
TableColumn(
name = "EMPI",
type = "TEXT",
primaryKey = True,
index = False,
unique = True,
notNull = True,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "MRN_Type",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "MRN",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Last_Name",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "First_Name",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Middle_Name",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Address1",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Address2",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "City",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "State",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Zip",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Country",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Home_Phone",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Day_Phone",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "SSN",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "VIP",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Previous_Name",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Patient_ID_List",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Insurance_1",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Insurance_2",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Insurance_3",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Primary_Care_Physician",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Resident_Primary_Care_Physician",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
)
]
)
#--------------------------------------------------------------------------------------------
# define Dem RPDR table
Dem = Table(
name = 'Dem',
fileExt = 'txt',
csvDialect = StandardCsvDialect,
freeTextReportInLastColumn = False,
useInTimeline = False,
columns=[
TableColumn(
name = "EMPI",
type = "TEXT",
primaryKey = True,
index = False,
unique = True,
notNull = True,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "MRN_Type",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "MRN",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Gender",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Date_of_Birth",
type = "DATETIME",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = DateReformat( format='%m/%d/%Y', reformat=SQLITE_DATE_FORMAT )
),
TableColumn(
name = "Age",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Language",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Race",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Marital_status",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Religion",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Is_a_veteran",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Zip_code",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Country",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Vital_status",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Date_Of_Death",
type = "DATETIME",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = DateReformat( format='%m/%d/%Y', reformat=SQLITE_DATE_FORMAT )
)
]
)
#--------------------------------------------------------------------------------------------
# define Dia RPDR table
Dia = Table(
name = 'Dia',
fileExt = 'txt',
csvDialect = StandardCsvDialect,
freeTextReportInLastColumn = False,
useInTimeline = True,
columns=[
TableColumn(
name = "EMPI",
type = "TEXT",
primaryKey = False,
index = True,
unique = False,
notNull = True,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "MRN_Type",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "MRN",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Date",
type = "DATETIME",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = True,
timelineBlurb = False,
dateReformat = DateReformat( format='%m/%d/%Y', reformat=SQLITE_DATE_FORMAT )
),
TableColumn(
name = "Diagnosis_Name",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = True,
dateReformat = None
),
TableColumn(
name = "Code_Type",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Code",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Diagnosis_Flag",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Provider",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Clinic",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Hospital",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Inpatient_Outpatient",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Encounter_number",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
)
]
)
#--------------------------------------------------------------------------------------------
# define Dis RPDR table
Dis = Table(
name = 'Dis',
fileExt = 'txt',
csvDialect = StandardCsvDialect,
freeTextReportInLastColumn = True,
useInTimeline = True,
columns=[
TableColumn(
name = "EMPI",
type = "TEXT",
primaryKey = False,
index = True,
unique = False,
notNull = True,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "MRN_Type",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "MRN",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Report_Number",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "MID",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Report_Date_Time",
type = "DATETIME",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = True,
timelineBlurb = False,
dateReformat = DateReformat( format='%m/%d/%Y %I:%M:%S %p', reformat=SQLITE_DATE_FORMAT )
),
TableColumn(
name = "Report_Description",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = True,
dateReformat = None
),
TableColumn(
name = "Report_Status",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Report_Type",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Report_Text",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
)
]
)
#--------------------------------------------------------------------------------------------
# define Dpt RPDR table
Dpt = Table(
name = 'Dpt',
fileExt = 'txt',
csvDialect = StandardCsvDialect,
freeTextReportInLastColumn = True,
useInTimeline = True,
columns=[
TableColumn(
name = "EMPI",
type = "TEXT",
primaryKey = False,
index = True,
unique = False,
notNull = True,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "MRN_Type",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "MRN",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Report_Number",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "MID",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Report_Date_Time",
type = "DATETIME",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = True,
timelineBlurb = False,
dateReformat = DateReformat( format='%m/%d/%Y %I:%M:%S %p', reformat=SQLITE_DATE_FORMAT )
),
TableColumn(
name = "Report_Description",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = True,
dateReformat = None
),
TableColumn(
name = "Report_Status",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Report_Type",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Report_Text",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
)
]
)
#--------------------------------------------------------------------------------------------
# define Enc RPDR table
Enc = Table(
name = 'Enc',
fileExt = 'txt',
csvDialect = StandardCsvDialect,
freeTextReportInLastColumn = False,
useInTimeline = True,
columns=[
TableColumn(
name = "EMPI",
type = "TEXT",
primaryKey = False,
index = True,
unique = False,
notNull = True,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "MRN_Type",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "MRN",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Encounter_number",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Encounter_Status",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Hospital",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Inpatient_Outpatient",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Service_Line",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Attending_MD",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Admit_Date",
type = "DATETIME",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = True,
timelineBlurb = False,
dateReformat = DateReformat( format='%m/%d/%Y', reformat=SQLITE_DATE_FORMAT )
),
TableColumn(
name = "Discharge_Date",
type = "DATETIME",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = DateReformat( format='%m/%d/%Y', reformat=SQLITE_DATE_FORMAT )
),
TableColumn(
name = "Clinic_Name",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = True,
dateReformat = None
),
TableColumn(
name = "Admit_Source",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Discharge_Disposition",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Payor",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Admitting_Diagnosis",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Principle_Diagnosis",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Diagnosis_1",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Diagnosis_2",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Diagnosis_3",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Diagnosis_4",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Diagnosis_5",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Diagnosis_6",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Diagnosis_7",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Diagnosis_8",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Diagnosis_9",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Diagnosis_10",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "DRG",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Patient_Type",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Referrer_Discipline",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
)
]
)
#--------------------------------------------------------------------------------------------
# define End RPDR table
End = Table(
name = 'End',
fileExt = 'txt',
csvDialect = StandardCsvDialect,
freeTextReportInLastColumn = True,
useInTimeline = True,
columns=[
TableColumn(
name = "EMPI",
type = "TEXT",
primaryKey = False,
index = True,
unique = False,
notNull = True,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "MRN_Type",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "MRN",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Report_Number",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "MID",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Report_Date_Time",
type = "DATETIME",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = True,
timelineBlurb = False,
dateReformat = DateReformat( format='%m/%d/%Y %I:%M:%S %p', reformat=SQLITE_DATE_FORMAT )
),
TableColumn(
name = "Report_Description",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = True,
dateReformat = None
),
TableColumn(
name = "Report_Status",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Report_Type",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Report_Text",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
)
]
)
#--------------------------------------------------------------------------------------------
# define Lab RPDR table
Lab = Table(
name = 'Lab',
fileExt = 'txt',
csvDialect = StandardCsvDialect,
freeTextReportInLastColumn = False,
useInTimeline = True,
columns=[
TableColumn(
name = "EMPI",
type = "TEXT",
primaryKey = False,
index = True,
unique = False,
notNull = True,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "MRN_Type",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "MRN",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Seq_Date_Time",
type = "DATETIME",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = True,
timelineBlurb = False,
dateReformat = DateReformat( format='%m/%d/%Y %H:%M', reformat=SQLITE_DATE_FORMAT )
),
TableColumn(
name = "Group_Id",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Loinc_Code",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Test_Id",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Test_Description",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = True,
dateReformat = None
),
TableColumn(
name = "Result",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Result_Text",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Abnormal_Flag",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Reference_Units",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Reference_Range",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Toxic_Range",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Specimen_Type",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Specimen_Text",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Correction_Flag",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Test_Status",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Ordering_Doc_Name",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Accession",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Source",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
)
]
)
#--------------------------------------------------------------------------------------------
# define Lhm RPDR table
Lhm = Table(
name = 'Lhm',
fileExt = 'txt',
csvDialect = StandardCsvDialect,
freeTextReportInLastColumn = False,
useInTimeline = True,
columns=[
TableColumn(
name = "EMPI",
type = "TEXT",
primaryKey = False,
index = True,
unique = False,
notNull = True,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "MRN_Type",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "MRN",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "System",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "LMR_Health_Maintenance_Date_Time",
type = "DATETIME",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = True,
timelineBlurb = False,
dateReformat = DateReformat( format='%m/%d/%Y %H:%M', reformat=SQLITE_DATE_FORMAT )
),
TableColumn(
name = "LMR_Text_Name",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = True,
dateReformat = None
),
TableColumn(
name = "Code",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "LMR_Code_Name",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Result",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Result_Text",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Comments",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
)
]
)
#--------------------------------------------------------------------------------------------
# define Lme RPDR table
Lme = Table(
name = 'Lme',
fileExt = 'txt',
csvDialect = StandardCsvDialect,
freeTextReportInLastColumn = False,
useInTimeline = True,
columns=[
TableColumn(
name = "EMPI",
type = "TEXT",
primaryKey = False,
index = True,
unique = False,
notNull = True,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "MRN_Type",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "MRN",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "LMR_Medication_Date_Time",
type = "DATETIME",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = True,
timelineBlurb = False,
dateReformat = DateReformat( format='%m/%d/%Y %H:%M', reformat=SQLITE_DATE_FORMAT )
),
TableColumn(
name = "LMR_Text_Med_Name",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = True,
dateReformat = None
),
TableColumn(
name = "Generic_ID",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Rollup_ID",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "LMR_Code_Med_Name",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Med_ID",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Med_Freq",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Med_Route",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Dose",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Units",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Take_Dose",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Take_Units",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Dispense",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Dispense_Units",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Duration",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Duration_Units",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Refills",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "PRN",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Rx",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "No_Substitutions",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Directions",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Comments",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
)
]
)
#--------------------------------------------------------------------------------------------
# define Lno RPDR table
Lno = Table(
name = 'Lno',
fileExt = 'txt',
csvDialect = StandardCsvDialect,
freeTextReportInLastColumn = True,
useInTimeline = True,
columns=[
TableColumn(
name = "EMPI",
type = "TEXT",
primaryKey = False,
index = True,
unique = False,
notNull = True,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "MRN_Type",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "MRN",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "LMRNote_Date",
type = "DATETIME",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = True,
timelineBlurb = False,
dateReformat = DateReformat( format='%m/%d/%Y %H:%M', reformat=SQLITE_DATE_FORMAT )
),
TableColumn(
name = "Record_Id",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Status",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Author",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "COD",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Institution",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Author_MRN",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Subject",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = True,
dateReformat = None
),
TableColumn(
name = "Comments",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
)
]
)
#--------------------------------------------------------------------------------------------
# define Lpr RPDR table
Lpr = Table(
name = 'Lpr',
fileExt = 'txt',
csvDialect = StandardCsvDialect,
freeTextReportInLastColumn = False,
useInTimeline = True,
columns=[
TableColumn(
name = "EMPI",
type = "TEXT",
primaryKey = False,
index = True,
unique = False,
notNull = True,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "MRN_Type",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "MRN",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "LMR_Problem_Date",
type = "DATETIME",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = True,
timelineBlurb = False,
dateReformat = DateReformat( format='%m/%d/%Y', reformat=SQLITE_DATE_FORMAT )
),
TableColumn(
name = "LMR_Text_Description",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = True,
dateReformat = None
),
TableColumn(
name = "Concept_ID",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "LMR_Code_Description",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Comments",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Type",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Onset_Date",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Resolution_Date",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Procedure_Date",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Modifiers",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Acuity",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Severity",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Condition",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Sensitivity_Flag",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Location",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
)
]
)
#--------------------------------------------------------------------------------------------
# define Lvs RPDR table
Lvs = Table(
name = 'Lvs',
fileExt = 'txt',
csvDialect = StandardCsvDialect,
freeTextReportInLastColumn = False,
useInTimeline = True,
columns=[
TableColumn(
name = "EMPI",
type = "TEXT",
primaryKey = False,
index = True,
unique = False,
notNull = True,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "MRN_Type",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "MRN",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "LMR_Vital_Date_Time",
type = "DATETIME",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = True,
timelineBlurb = False,
dateReformat = DateReformat( format='%m/%d/%Y %H:%M', reformat=SQLITE_DATE_FORMAT )
),
TableColumn(
name = "LMR_Text_Type",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = True,
dateReformat = None
),
TableColumn(
name = "Code",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "LMR_Code_Type",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Result",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Units",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Site",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Position",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Rythm",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
)
]
)
#--------------------------------------------------------------------------------------------
# define Mcm RPDR table
Mcm = Table(
name = 'Mcm',
fileExt = 'txt',
csvDialect = StandardCsvDialect,
freeTextReportInLastColumn = False,
useInTimeline = False,
columns=[
TableColumn(
name = "Control_Patient_EMPI",
type = "TEXT",
primaryKey = False,
index = True,
unique = False,
notNull = True,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Case_Patient_EMPI",
type = "TEXT",
primaryKey = False,
index = True,
unique = False,
notNull = True,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Match_Strength",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = True,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
)
]
)
#--------------------------------------------------------------------------------------------
# define Med RPDR table
Med = Table(
name = 'Med',
fileExt = 'txt',
csvDialect = StandardCsvDialect,
freeTextReportInLastColumn = False,
useInTimeline = True,
columns=[
TableColumn(
name = "EMPI",
type = "TEXT",
primaryKey = False,
index = True,
unique = False,
notNull = True,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "MRN_Type",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "MRN",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Medication_Date",
type = "DATETIME",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = True,
timelineBlurb = False,
dateReformat = DateReformat( format='%m/%d/%Y', reformat=SQLITE_DATE_FORMAT )
),
TableColumn(
name = "Medication",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = True,
dateReformat = None
),
TableColumn(
name = "Code_Type",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Code",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Quantity",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Provider",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Clinic",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Hospital",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Inpatient_Outpatient",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Encounter_number",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
)
]
)
#--------------------------------------------------------------------------------------------
# define Mic RPDR table
Mic = Table(
name = 'Mic',
fileExt = 'txt',
csvDialect = StandardCsvDialect,
freeTextReportInLastColumn = True,
useInTimeline = True,
columns=[
TableColumn(
name = "EMPI",
type = "TEXT",
primaryKey = False,
index = True,
unique = False,
notNull = True,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "MRN_Type",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "MRN",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Microbiology_Number",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Microbiology_Date_Time",
type = "DATETIME",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = True,
timelineBlurb = False,
dateReformat = DateReformat( format='%m/%d/%Y %H:%M:%S', reformat=SQLITE_DATE_FORMAT )
),
TableColumn(
name = "Specimen_Type",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = True,
dateReformat = None
),
TableColumn(
name = "Specimen_Comments",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Test_Name",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Test_Code",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Test_Comments",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Test_Status",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Organism_Name",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Organism_Code",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Organism_Comment",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Organism_Text",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
)
]
)
#--------------------------------------------------------------------------------------------
# define Mrn RPDR table
Mrn = Table(
name = 'Mrn',
fileExt = 'txt',
csvDialect = StandardCsvDialect,
freeTextReportInLastColumn = False,
useInTimeline = False,
columns=[
TableColumn(
name = "IncomingId",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "IncomingSite",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Status",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Enterprise_Master_Patient_Index",
type = "TEXT",
primaryKey = True,
index = False,
unique = True,
notNull = True,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "MGH_MRN",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "BWH_MRN",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "FH_MRN",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "SRH_MRN",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "NWH_MRN",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "NSMC_MRN",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "MCL_MRN",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
)
]
)
#--------------------------------------------------------------------------------------------
# define Opn RPDR table
Opn = Table(
name = 'Opn',
fileExt = 'txt',
csvDialect = StandardCsvDialect,
freeTextReportInLastColumn = True,
useInTimeline = True,
columns=[
TableColumn(
name = "EMPI",
type = "TEXT",
primaryKey = False,
index = True,
unique = False,
notNull = True,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "MRN_Type",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "MRN",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Report_Number",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "MID",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Report_Date_Time",
type = "DATETIME",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = True,
timelineBlurb = False,
dateReformat = DateReformat( format='%m/%d/%Y %I:%M:%S %p', reformat=SQLITE_DATE_FORMAT )
),
TableColumn(
name = "Report_Description",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = True,
dateReformat = None
),
TableColumn(
name = "Report_Status",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Report_Type",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Report_Text",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
)
]
)
#--------------------------------------------------------------------------------------------
# define Pal RPDR table
Pal = Table(
name = 'Pal',
fileExt = 'txt',
csvDialect = StandardCsvDialect,
freeTextReportInLastColumn = False,
useInTimeline = True,
columns=[
TableColumn(
name = "EMPI",
type = "TEXT",
primaryKey = False,
index = True,
unique = False,
notNull = True,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "MRN",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "MRN_Type",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "System",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "PEARAllergy_Date_Time",
type = "DATETIME",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = True,
timelineBlurb = False,
dateReformat = DateReformat( format='%m/%d/%Y %H:%M:%S', reformat=SQLITE_DATE_FORMAT )
),
TableColumn(
name = "Allergen",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = True,
dateReformat = None
),
TableColumn(
name = "Allergen_Type",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Allergen_Code",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Reaction",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Comments",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Status",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
)
]
)
#--------------------------------------------------------------------------------------------
# define Pat RPDR table
Pat = Table(
name = 'Pat',
fileExt = 'txt',
csvDialect = StandardCsvDialect,
freeTextReportInLastColumn = True,
useInTimeline = True,
columns=[
TableColumn(
name = "EMPI",
type = "TEXT",
primaryKey = False,
index = True,
unique = False,
notNull = True,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "MRN_Type",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "MRN",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Report_Number",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "MID",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Report_Date_Time",
type = "DATETIME",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = True,
timelineBlurb = False,
dateReformat = DateReformat( format='%m/%d/%Y %I:%M:%S %p', reformat=SQLITE_DATE_FORMAT )
),
TableColumn(
name = "Report_Description",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = True,
dateReformat = None
),
TableColumn(
name = "Report_Status",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Report_Type",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Report_Text",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
)
]
)
#--------------------------------------------------------------------------------------------
# define Phy RPDR table
Phy = Table(
name = 'Phy',
fileExt = 'txt',
csvDialect = StandardCsvDialect,
freeTextReportInLastColumn = False,
useInTimeline = True,
columns=[
TableColumn(
name = "EMPI",
type = "TEXT",
primaryKey = False,
index = True,
unique = False,
notNull = True,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "MRN_Type",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "MRN",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Date",
type = "DATETIME",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = True,
timelineBlurb = False,
dateReformat = DateReformat( format='%m/%d/%Y', reformat=SQLITE_DATE_FORMAT )
),
TableColumn(
name = "Concept_Name",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = True,
dateReformat = None
),
TableColumn(
name = "Code_Type",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Code",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Result",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Units",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Provider",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Clinic",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Hospital",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Inpatient_Outpatient",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Encounter_number",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
)
]
)
#--------------------------------------------------------------------------------------------
# define Prc RPDR table
Prc = Table(
name = 'Prc',
fileExt = 'txt',
csvDialect = StandardCsvDialect,
freeTextReportInLastColumn = False,
useInTimeline = True,
columns=[
TableColumn(
name = "EMPI",
type = "TEXT",
primaryKey = False,
index = True,
unique = False,
notNull = True,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "MRN_Type",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "MRN",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Date",
type = "DATETIME",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = True,
timelineBlurb = False,
dateReformat = DateReformat( format='%m/%d/%Y', reformat=SQLITE_DATE_FORMAT )
),
TableColumn(
name = "Procedure_Name",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = True,
dateReformat = None
),
TableColumn(
name = "Code_Type",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Code",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Procedure_Flag",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Quantity",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Provider",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Clinic",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Hospital",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Inpatient_Outpatient",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Encounter_number",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
)
]
)
#--------------------------------------------------------------------------------------------
# define Prv RPDR table
Prv = Table(
name = 'Prv',
fileExt = 'txt',
csvDialect = StandardCsvDialect,
freeTextReportInLastColumn = False,
useInTimeline = True,
columns=[
TableColumn(
name = "EMPI",
type = "TEXT",
primaryKey = False,
index = True,
unique = False,
notNull = True,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "MRN_Type",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "MRN",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Provider_Rank",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Is_PCP",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Last_Seen_Date",
type = "DATETIME",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = True,
timelineBlurb = False,
dateReformat = DateReformat( format='%m/%d/%Y', reformat=SQLITE_DATE_FORMAT )
),
TableColumn(
name = "Provider_Name",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = True,
dateReformat = None
),
TableColumn(
name = "Provider_ID",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Address_1",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Address_2",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "City",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "State",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Zip",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Phone_Ext",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Fax",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "EMail",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Specialties",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Enterprise_service",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "CPM_Id",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
)
]
)
#--------------------------------------------------------------------------------------------
# define Pul RPDR table
Pul = Table(
name = 'Pul',
fileExt = 'txt',
csvDialect = StandardCsvDialect,
freeTextReportInLastColumn = True,
useInTimeline = True,
columns=[
TableColumn(
name = "EMPI",
type = "TEXT",
primaryKey = False,
index = True,
unique = False,
notNull = True,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "MRN_Type",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "MRN",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Report_Number",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "MID",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Report_Date_Time",
type = "DATETIME",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = True,
timelineBlurb = False,
dateReformat = DateReformat( format='%m/%d/%Y %I:%M:%S %p', reformat=SQLITE_DATE_FORMAT )
),
TableColumn(
name = "Report_Description",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = True,
dateReformat = None
),
TableColumn(
name = "Report_Status",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Report_Type",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Report_Text",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
)
]
)
#--------------------------------------------------------------------------------------------
# define Rad RPDR table
Rad = Table(
name = 'Rad',
fileExt = 'txt',
csvDialect = StandardCsvDialect,
freeTextReportInLastColumn = True,
useInTimeline = True,
columns=[
TableColumn(
name = "EMPI",
type = "TEXT",
primaryKey = False,
index = True,
unique = False,
notNull = True,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "MRN_Type",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = True,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "MRN",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = True,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Report_Number",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = True,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "MID",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = True,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Report_Date_Time",
type = "DATETIME",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = True,
timelineBlurb = False,
dateReformat = DateReformat( format='%m/%d/%Y %I:%M:%S %p', reformat=SQLITE_DATE_FORMAT )
),
TableColumn(
name = "Report_Description",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = True,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = True,
dateReformat = None
),
TableColumn(
name = "Report_Status",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = True,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Report_Type",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = True,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Report_Text",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = True,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
)
]
)
#--------------------------------------------------------------------------------------------
# define Rdt RPDR table
Rdt = Table(
name = 'Rdt',
fileExt = 'txt',
csvDialect = StandardCsvDialect,
freeTextReportInLastColumn = False,
useInTimeline = True,
columns=[
TableColumn(
name = "EMPI",
type = "TEXT",
primaryKey = False,
index = True,
unique = False,
notNull = True,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "MRN_Type",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "MRN",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Date",
type = "DATETIME",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = True,
timelineBlurb = False,
dateReformat = DateReformat( format='%m/%d/%Y', reformat=SQLITE_DATE_FORMAT )
),
TableColumn(
name = "Mode",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Group",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Test_Code",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Test_Description",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = True,
dateReformat = None
),
TableColumn(
name = "Accession_Number",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Provider",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Clinic",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Hospital",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Inpatient_Outpatient",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
)
]
)
#--------------------------------------------------------------------------------------------
# define Rnd RPDR table
Rnd = Table(
name = 'Rnd',
fileExt = 'txt',
csvDialect = StandardCsvDialect,
freeTextReportInLastColumn = False,
useInTimeline = False,
columns=[
TableColumn(
name = "EMPI",
type = "TEXT",
primaryKey = False,
index = True,
unique = False,
notNull = True,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "MRN_Type",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "MRN",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Accession",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Department",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Exam_Code",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "History1",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "History2",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "History3",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Long_Description",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Rad1",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Rad2",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Rad3",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Req",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Division",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Region",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Specialty",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "Body_Part",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
),
TableColumn(
name = "FileName",
type = "TEXT",
primaryKey = False,
index = False,
unique = False,
notNull = False,
foreignKeyRef = None,
timelineDate = False,
timelineBlurb = False,
dateReformat = None
)
]
)
#--------------------------------------------------------------------------------------------
# list of RPDR tables to consider
Tables = [
Car,
Con,
Dem,
Dia,
Dis,
Dpt,
Enc,
End,
Lab,
Lhm,
Lme,
Lno,
Lpr,
Lvs,
Med,
Mic,
Mrn,
Opn,
Pal,
Pal,
Pat,
Phy,
Prc,
Prv,
Pul,
Rad,
Rdt,
Rnd
]
|
{"/examples.py": ["/rpdr.py"]}
|
22,513
|
chuzarski/superpong
|
refs/heads/master
|
/entities.py
|
from controllers import *
from rotating_rectangle import RotatingRect
from colors import *
class Player():
def __init__(self, name, pos, surf_size):
self.__paddle = None
self.__name = name
self.__controller = Controller() # default controller. Does nothing when polled
self.__position = pos
self.__move_rate = 6
self.__rotate_rate = 1
self.__rotate_max = 10
self.__rotate_min = -10
self.__scoring_font = pygame.font.Font("PROMETHEUS.ttf", 64)
self.__score = 0
self.color = Color
self.surface_height = 0
self.surface_width = 0
self.paddle_grow_active = False
# set dimensions
self.set_surf_size(surf_size)
# init
self.set_initial_pos(self.__position)
def reset(self):
self.set_initial_pos(self.__position)
self.paddle_grow_active = False
def set_surf_size(self, surf_size):
if isinstance(surf_size, tuple):
self.surface_height = surf_size[1]
self.surface_width = surf_size[0]
else:
raise ValueError
def set_initial_pos(self, pos):
paddle_height = 80
paddle_width = 10
paddle_margin = 20
paddle_center = (self.surface_height / 2) - (paddle_height / 2)
if pos == 'l':
# position rectangle on left side
self.__paddle = RotatingRect(paddle_margin, paddle_center, paddle_width, paddle_height)
elif pos == 'r':
xpos = self.surface_width - paddle_margin
self.__paddle = RotatingRect(xpos, paddle_center, paddle_width, paddle_height)
else:
raise ValueError
def get_paddle(self):
return self.__paddle
def grow(self):
max = 140
if self.__paddle.get_height() < max:
self.__paddle.set_height(self.__paddle.get_height() + 2)
def shrink(self):
default = 80
if self.__paddle.get_height() > default:
self.__paddle.set_height(self.__paddle.get_height() - 2)
def get_rotation(self):
return self.__paddle.get_rotation()
def get_name(self):
return self.__name
def set_controller(self, con):
self.__controller = con
def get_score(self):
return self.__score
def draw_score(self, surface):
x_margin = 25
y_margin = 50
if self.__position == "l":
horiz_pos = self.__paddle.getX() + x_margin
elif self.__position == "r":
horiz_pos = self.surface_width - 64 - x_margin
else:
horiz_pos = self.surface_width / 2
scoreBlit = self.__scoring_font.render(str(self.__score), 1, (255, 255, 255))
surface.blit(scoreBlit, (horiz_pos, y_margin))
def score(self):
self.__score = self.__score + 1
def update_movement(self):
e = self.__controller.poll()
# eval up/down
if e[self.__controller.CONTROL_UP]:
self.__move('u')
elif e[self.__controller.CONTROL_DOWN]:
self.__move('d')
# eval rotation forward/backward
if e[self.__controller.CONTROL_ROT_FORWARD]:
self.__rotate('f')
elif e[self.__controller.CONTROL_ROT_BACKWARD]:
self.__rotate('b')
elif e[self.__controller.CONTROL_ROT_FORWARD] == False and e[self.__controller.CONTROL_ROT_BACKWARD] == False:
self.__rotate('n')
# paddle growth
if self.paddle_grow_active:
self.grow()
else:
self.shrink()
def __move(self, flag):
if flag == 'u':
top = self.get_paddle().getY() - (self.__paddle.get_height() / 2)
if top > 0:
self.__paddle.setY(self.__paddle.getY() - self.__move_rate) # UP
elif flag == 'd':
bottom = self.get_paddle().getY() + (self.__paddle.get_height() / 2)
if bottom < self.surface_height:
self.__paddle.setY(self.__paddle.getY() + self.__move_rate) # DOWN
def __rotate(self, flag):
if flag == 'f':
if self.__paddle.get_rotation() < self.__rotate_max:
self.__paddle.set_rotation(self.__paddle.get_rotation() + self.__rotate_rate)
elif flag == 'b':
if self.__paddle.get_rotation() > self.__rotate_min:
self.__paddle.set_rotation(self.__paddle.get_rotation() - self.__rotate_rate)
elif flag == 'n':
if self.__paddle.get_rotation() > 0:
self.__paddle.set_rotation(self.__paddle.get_rotation() - self.__rotate_rate)
elif self.__paddle.get_rotation() < 0:
self.__paddle.set_rotation(self.__paddle.get_rotation() + self.__rotate_rate)
def did_collide(self, ball):
# For now simple bounding box collision will work but will not look right
paddle_rect = self.__paddle.get_rect()
bX = ball.getX()
bY = ball.getY()
return paddle_rect.collidepoint(bX, bY)
def draw(self, surface):
self.__paddle.draw(surface)
self.draw_score(surface)
class Ball():
def __init__(self, surf_size):
self.__rect = None
self.set_surf_size(surf_size)
self.__set_initial_values()
def set_surf_size(self, surf_size):
if isinstance(surf_size, tuple):
self.surface_height = surf_size[1]
self.surface_width = surf_size[0]
else:
raise ValueError
def set_charge(self, charge):
charge = str(charge)
self.__ball_charge = charge
if charge is "FAST_BALL":
self.set_color(COLOR_RED)
elif charge is "COLOR_FLASH":
self.set_color(COLOR_YELLOW)
elif charge is "PAD_GROW":
self.set_color(COLOR_CYAN)
def get_charge(self):
return self.__ball_charge
def set_color(self, color):
self.__color = color
def has_charge(self):
if self.__ball_charge is not "":
return True
else:
return False
def clear_charge(self):
self.__ball_charge = ""
self.set_color(COLOR_WHITE)
def reset(self):
self.__set_initial_values()
def __set_initial_values(self):
self.__move_rate = 5
self.__x = self.surface_width / 2
self.__y = self.surface_height / 2
self.__radius = 7
self.__x_flip = -1
self.__y_flip = 1
self.__ball_charge = ""
self.__color = COLOR_WHITE
def set_effect(self, effect):
effect = str(effect)
self.__effect = effect
def get_rect(self):
return self.__rect
def set_speed(self, val):
val = int(val)
self.__move_rate = val
def get_speed(self):
return self.__move_rate
def update_movement(self):
self.__x = self.__x + (self.__move_rate * self.__x_flip)
self.__y = self.__y - (self.__move_rate * self.__y_flip)
def draw(self, surface):
self.__rect = pygame.draw.circle(surface, self.__color, (int(self.__x), int(self.__y)), self.__radius)
def getX(self):
return self.__x
def getY(self):
return self.__y
def getX_flip(self):
return self.__x_flip
def getY_flip(self):
return self.__y_flip
def flipX(self):
self.__x_flip = self.__x_flip * -1
def flipY(self):
self.__y_flip = self.__y_flip * -1
|
{"/game.py": ["/entities.py"]}
|
22,514
|
chuzarski/superpong
|
refs/heads/master
|
/game.py
|
# Program: Superpong !
# Date: 12-10-2015
# Edited by: Cody Huzarski
import pygame, sys, math, time, random
from colors import *
from pygame.locals import *
from entities import *
from controllers import *
from util import LifeCycle
class Game(LifeCycle):
def __init__(self, surface):
LifeCycle.__init__(self, surface)
self.player_1 = None
self.player_2 = None
self.ball = Ball(self.surface_size)
self.last_collision = time.time()
self.total_ball_hits = 0
self.ball_charges = ["FAST_BALL", "COLOR_FLASH", "PAD_GROW"]
self.active_charges = list()
self.bg_color = COLOR_BLACK
self.initial_setup()
def initial_setup(self):
self.player_1 = Player("Player 1", 'l', self.surface_size)
self.player_2 = Player("Player 2", 'r', self.surface_size)
self.player_1.set_controller(KeyboardController(K_w, K_s, K_a, K_d))
self.player_2.set_controller(KeyboardController(K_UP, K_DOWN, K_RIGHT, K_LEFT))
def handle_paddle_collision(self, p, ball):
if p.get_rotation() == 0:
ball.flipX()
elif p.get_rotation() < 0 and ball.getY_flip() == 1:
# Paddle is rotated FORWARD and ball is headed UP
ball.flipX()
ball.flipY()
elif p.get_rotation() > 0 and ball.getY_flip() == 1:
# Paddle is rotated BACKWARD and ball is headed
ball.flipX()
elif p.get_rotation() < 0 and ball.getY_flip() == -1:
# Paddle is rotated BACKWARD and ball is headed DOWN
ball.flipX()
ball.flipY()
elif p.get_rotation() > 0 and ball.getY_flip() == -1:
ball.flipX()
def reset_all(self):
self.ball.reset()
self.player_1.reset()
self.player_2.reset()
self.total_ball_hits = 0
self.bg_color = COLOR_BLACK
# clear active charge states
self.active_charges.clear()
def player_collision_event(self, player):
player = int(player)
if player is 1:
self.handle_paddle_collision(self.player_1, self.ball)
if self.ball.has_charge():
self.register_charge(1)
pass
elif player is 2:
self.handle_paddle_collision(self.player_2, self.ball)
if self.ball.has_charge():
self.register_charge(2)
pass
else:
return False
self.last_collision = time.time()
self.total_ball_hits = self.total_ball_hits + 1
if self.total_ball_hits > 2:
self.charge_ball()
def generate_charge(self):
randIdx = random.randint(0, len(self.ball_charges) - 1)
return self.ball_charges[randIdx]
def charge_ball(self):
# Heads or tails, charge the ball?
if bool(random.getrandbits(1)):
self.ball.set_charge(self.generate_charge())
else:
return False
def register_charge(self, consumer):
c = self.ball.get_charge()
self.ball.clear_charge()
if c is self.ball_charges[0]: # Fast Ball
self.active_charges.append(ChargeType(self.ball_charges[0], "NUM_HITS", self.total_ball_hits))
elif c is self.ball_charges[1]: # Color flash
self.active_charges.append(ChargeType(self.ball_charges[1], "TIME", time.time()))
elif c is self.ball_charges[2]: # paddle grow
self.active_charges.append(ChargeType(self.ball_charges[2], "NUM_HITS",
self.total_ball_hits, consumer))
def handle_active_charges(self):
if len(self.active_charges) > 0:
for c in self.active_charges:
if c == self.ball_charges[0]: # fast ball
self.handle_fast_ball(c)
elif c == self.ball_charges[1]: # color flash
self.handle_bg_flash(c)
elif c == self.ball_charges[2]: # Paddle grow
self.handle_paddle_grow(c)
def handle_fast_ball(self, charge):
# check expiration policy
if (self.total_ball_hits - charge.val) > 1:
# remove from active
self.active_charges.pop(self.active_charges.index(charge))
# reset ball
self.ball.set_speed(5)
return True
if self.ball.get_speed() < 9:
self.ball.set_speed(9)
def handle_bg_flash(self, charge):
# check expiration policy
if(time.time() - charge.val) > 3:
# remove from active
self.active_charges.pop(self.active_charges.index(charge))
# reset bg and ball
self.bg_color = COLOR_BLACK
self.ball.set_color(COLOR_WHITE)
return True
color_list = [COLOR_BLACK, COLOR_WHITE, COLOR_BLUE,
COLOR_PURPLE, COLOR_GREEN, COLOR_RED, COLOR_CYAN, COLOR_YELLOW]
rIdx = 0
bIdx = 0
bIdx = random.randint(1, len(color_list) - 2)
while True:
rIdx = random.randint(0, len(color_list) - 1)
if self.bg_color is not color_list[rIdx]:
break
self.bg_color = color_list[rIdx]
self.ball.set_color(color_list[bIdx])
def handle_paddle_grow(self, charge):
player = self.player_1
# determine player
if charge.consumer == 1:
player = self.player_1
elif charge.consumer == 2:
player = self.player_2
# check expiration policy
if (self.total_ball_hits - charge.val) > 3:
# remove charge from active
self.active_charges.pop(self.active_charges.index(charge))
# disable
player.paddle_grow_active = False
elif not player.paddle_grow_active:
player.paddle_grow_active = True
def cycle(self):
# apply active charges
self.handle_active_charges()
# take input, update movement
self.player_1.update_movement()
self.player_2.update_movement()
self.ball.update_movement()
# draw
self.surface.fill(self.bg_color)
self.player_1.draw(self.surface)
self.player_2.draw(self.surface)
self.ball.draw(self.surface)
if (time.time() - self.last_collision) > .5: # Fixes a glitch that causes the ball to collide with paddles infinitely
# Test collisions
if self.player_1.did_collide(self.ball):
self.player_collision_event(1)
if self.player_2.did_collide(self.ball):
self.player_collision_event(2)
# test wall collisions
if self.ball.getY() <= 0 or self.ball.getY() >= self.surface_size[1]:
self.ball.flipY()
if self.ball.getX() <= 0:
self.player_2.score()
self.reset_all()
if self.ball.getX() >= self.surface_size[0]:
self.player_1.score()
self.reset_all()
if self.player_1.get_score() == 10:
return 1
if self.player_2.get_score() == 10:
return 2
return "None"
class ChargeType():
def __init__(self, tag, expiration_policy, val, consumer=0):
self.tag = str(tag)
self.expiration_policy = str(expiration_policy)
self.val = val
self.consumer = int(consumer)
def __eq__(self, other):
# compare string to object
if isinstance(other, str):
if other == self.tag:
return True
else:
return False
# compare objet to object
if other.tag == self.tag:
return True
else:
return False
|
{"/game.py": ["/entities.py"]}
|
22,549
|
sarv19/ass4
|
refs/heads/master
|
/upload/src/main/mp/codegen/CodeGenerator.py
|
'''
* @author Nguyen Hua Phung
* @version 1.0
* 23/10/2015
* This file provides a simple version of code generator
*
'''
from Utils import *
from StaticCheck import *
from StaticError import *
from Emitter import Emitter
from Frame import Frame
from abc import ABC, abstractmethod
class CodeGenerator(Utils):
def __init__(self):
self.libName = "io"
def init(self):
return [Symbol("getInt", MType(list(), IntType()), CName(self.libName)),
Symbol("putInt", MType([IntType()], VoidType()), CName(self.libName)),
Symbol("putIntLn", MType([IntType()], VoidType()), CName(self.libName)),
Symbol("getFloat", MType(list(), FloatType()), CName(self.libName)),
Symbol("putFloat", MType([FloatType()], VoidType()), CName(self.libName)),
Symbol("putFloatLn", MType([FloatType()], VoidType()), CName(self.libName)),
Symbol("putBool", MType([BoolType()], VoidType()), CName(self.libName)),
Symbol("putBoolLn", MType([BoolType()], VoidType()), CName(self.libName)),
Symbol("putString", MType([StringType()], VoidType()), CName(self.libName)),
Symbol("putStringLn", MType([StringType()], VoidType()), CName(self.libName)),
Symbol("putLn", MType(list(), VoidType()), CName(self.libName))
]
def gen(self, ast, dir_):
#ast: AST
#dir_: String
gl = self.init()
gc = CodeGenVisitor(ast, gl, dir_)
gc.visit(ast, None)
# class StringType(Type):
# def __str__(self):
# return "StringType"
# def accept(self, v, param):
# return None
class ArrayPointerType(Type):
def __init__(self, ctype):
#cname: String
self.eleType = ctype
def __str__(self):
return "ArrayPointerType({0})".format(str(self.eleType))
def accept(self, v, param):
return None
class ClassType(Type):
def __init__(self,cname):
self.cname = cname
def __str__(self):
return "Class({0})".format(str(self.cname))
def accept(self, v, param):
return None
class SubBody(): #stmt
def __init__(self, frame, sym):
#frame: Frame
#sym: List[Symbol]
self.frame = frame
self.sym = sym
class Access(): #expr
def __init__(self, frame, sym, isLeft, isFirst):
#frame: Frame
#sym: List[Symbol]
#isLeft: Boolean
#isFirst: Boolean
self.frame = frame
self.sym = sym
self.isLeft = isLeft
self.isFirst = isFirst
class Val(ABC):
pass
class Index(Val):
def __init__(self, value):
#value: Int
self.value = value
class CName(Val):
def __init__(self, value):
#value: String
self.value = value
class CodeGenVisitor(BaseVisitor, Utils):
def __init__(self, astTree, env, dir_):
#astTree: AST
#env: List[Symbol]
#dir_: File
self.astTree = astTree
self.env = env
self.className = "MPClass"
self.path = dir_
self.emit = Emitter(self.path + "/" + self.className + ".j")
def visitProgram(self, ast, c):
#ast: Program
#c: Any
self.emit.printout(self.emit.emitPROLOG(self.className, "java.lang.Object"))
# for x in ast.decl:
# if type(x) is VarDecl:
# e = self.visit(x, e)
# for x in ast.decl:
# if type(x) is FuncDecl:
# e=self.visit(x,e)
# framee =Frame(ast.name.name, ast.returnType)
decl_all = list()
for x in ast.decl:
if type(x) is VarDecl:
decl_all.append(Symbol(x.variable.name, x.varType,CName(self.className)))
for x in ast.decl:
if type(x) is FuncDecl:
decl_all.append(Symbol(x.name.name,MType([i.varType for i in x.param],x.returnType), CName(self.className) ))
e = SubBody(None, self.env+decl_all)
for x in ast.decl:
if type(x) is VarDecl:
k = self.visit(x, e)
for x in ast.decl:
if type(x) is FuncDecl:
k=self.visit(x,e)
# generate default constructor
self.genMETHOD(FuncDecl(Id("<init>"), list(), list(), list(),None), c, Frame("<init>", VoidType))
self.emit.emitEPILOG()
return c
def genMETHOD(self, consdecl, o, frame):
#consdecl: FuncDecl
#o: Any
#frame: Frame
isInit = consdecl.returnType is None
isMain = consdecl.name.name.lower() == "main" and len(consdecl.param) == 0 and type(consdecl.returnType) is VoidType
returnType = VoidType() if isInit else consdecl.returnType
# methodName = "<init>" if isInit else consdecl.name.name ## need lower()????
if isInit:
methodName = "<init>"
elif consdecl.name.name.lower() == 'main':
methodName = consdecl.name.name.lower()
else:
methodName = consdecl.name.name
intype = [ArrayPointerType(StringType())] if isMain else list(map(lambda x: x.varType,consdecl.param))
mtype = MType(intype, returnType)
self.emit.printout(self.emit.emitMETHOD(methodName, mtype, not isInit, frame))
frame.enterScope(True)
glenv = o
# Generate code for parameter declarations
if isInit:
self.emit.printout(self.emit.emitVAR(frame.getNewIndex(), "this", ClassType(self.className), frame.getStartLabel(), frame.getEndLabel(), frame))
if isMain:
self.emit.printout(self.emit.emitVAR(frame.getNewIndex(), "args", ArrayPointerType(StringType()), frame.getStartLabel(), frame.getEndLabel(), frame))
decl = list()
for x in consdecl.param + consdecl.local:
a = frame.getNewIndex()
decl.append(Symbol(x.variable.name, x.varType, Index(a)))
self.emit.printout(self.emit.emitVAR(a, x.variable.name, x.varType, frame.getStartLabel(), frame.getEndLabel(), frame))
body = consdecl.body
self.emit.printout(self.emit.emitLABEL(frame.getStartLabel(), frame))
# Generate code for statements
if isInit:
self.emit.printout(self.emit.emitREADVAR("this", ClassType(self.className), 0, frame))
self.emit.printout(self.emit.emitINVOKESPECIAL(frame))
list(map(lambda x: self.visit(x, SubBody(frame, decl + glenv)), body))
self.emit.printout(self.emit.emitLABEL(frame.getEndLabel(), frame))
if type(returnType) is VoidType:
self.emit.printout(self.emit.emitRETURN(VoidType(), frame))
self.emit.printout(self.emit.emitENDMETHOD(frame))
frame.exitScope();
def visitVarDecl(self, ast, o):
subctxt = o
self.emit.printout(self.emit.emitATTRIBUTE(ast.variable.name, ast.varType, False, ""))
return SubBody(None, [Symbol(ast.variable.name, ast.varType, CName(self.className))]+subctxt.sym)
# return SubBody(None, subctxt.sym)
def visitFuncDecl(self, ast, o):
#ast: FuncDecl
#o: Any
# for x in o.sym:
# print(ast.name,x.name)
subctxt = o
frame = Frame(ast.name.name, ast.returnType)
self.genMETHOD(ast, o.sym, frame)
# print(ast.returnType)
return SubBody(None, o.sym)
def visitCallStmt(self, ast, o):
#ast: CallStmt
#o: Any
ctxt = o
frame = ctxt.frame
nenv = ctxt.sym
sym = self.lookup(ast.method.name.lower(), nenv, lambda x: x.name.lower())
cname = sym.value.value
ctype = sym.mtype
in_ = ("", list())
n=0
for x in ast.param:
str1, typ1 = self.visit(x, Access(frame, nenv, False, True))
if type(typ1) is IntType and type(sym.mtype.partype[n]) is FloatType:
# in_ = (in_[0] + str1, in_[1].append(typ1))
in_ = (in_[0] + str1 + self.emit.emitI2F(frame), in_[1] + [typ1])
else:
in_ = (in_[0] + str1, in_[1] + [typ1])
n+=1
self.emit.printout(in_[0])
self.emit.printout(self.emit.emitINVOKESTATIC(cname + "/" + sym.name, ctype, frame))
def visitCallExpr(self, ast, o):
#ast: CallExpr
#o: Any
ctxt = o
frame = ctxt.frame
nenv = ctxt.sym
sym = self.lookup(ast.method.name.lower(), nenv, lambda x: x.name.lower())
cname = sym.value.value
ctype = sym.mtype
in_ = ("", list())
n = 0
for x in ast.param:
str1, typ1 = self.visit(x, Access(frame, nenv, False, True))
if type(typ1) is IntType and type(sym.mtype.partype[n]) is FloatType:
# in_ = (in_[0] + str1, in_[1].append(typ1))
in_ = (in_[0] + str1 + self.emit.emitI2F(frame), in_[1] + [FloatType()])
else:
in_ = (in_[0] + str1, in_[1] + [typ1])
n+=1
# self.emit.printout(in_[0])
return in_[0] + self.emit.emitINVOKESTATIC(cname + "/" + sym.name, ctype, frame), ctype.rettype
#maybe need fix???!!!
def visitIntLiteral(self, ast, o):
#ast: IntLiteral
#o: Any
ctxt = o
frame = ctxt.frame
return self.emit.emitPUSHICONST(ast.value, frame), IntType()
def visitFloatLiteral(self, ast, o):
#ast: FloatLiteral
#o: Any
ctxt = o
frame = ctxt.frame
return self.emit.emitPUSHFCONST(str(ast.value), frame), FloatType()
def visitStringLiteral(self, ast, o):
#ast: StringLiteral
#o: Any
ctxt = o
frame = ctxt.frame
return self.emit.emitPUSHCONST('"'+str(ast.value)+'"', StringType(),frame), StringType()
def visitBooleanLiteral(self, ast, o):
#ast: BooleanLiteral
#o: Any
ctxt = o
frame = ctxt.frame
if str(ast.value).lower() == 'true':
in_ = 'true'
else:
in_ = 'false'
return self.emit.emitPUSHICONST(str(in_.lower()), frame), BoolType()
def visitBinaryOp(self, ast, o):
ctxt = o
frame = ctxt.frame
nenv = ctxt.sym
left, lefttype = self.visit(ast.left, Access(frame,nenv,False, True))
right, righttype = self.visit(ast.right, Access(frame,nenv,False, True))
# return left + right + self.emit.emitADDOP(str(ast.op), IntType(), frame), IntType()
if type(lefttype) is BoolType and type(righttype) is BoolType:
if ast.op.lower() == 'and':
return left + right + self.emit.emitANDOP(frame), BoolType()
elif ast.op.lower() == 'or':
return left + right + self.emit.emitOROP(frame), BoolType()
elif ast.op.lower() == 'andthen':
# return left + right + self.emit.emitREOP(str(ast.op), BoolType(), frame), BoolType()
result = list()
labelF = frame.getNewLabel()
labelO = frame.getNewLabel()
result.append(left)
result.append(self.emit.jvm.emitDUP())
result.append(self.emit.jvm.emitIFEQ(labelO))
result.append(self.emit.emitGOTO(labelF,frame))
result.append(self.emit.emitLABEL(labelF,frame))
result.append(right)
result.append(self.emit.emitANDOP(frame))
result.append(self.emit.emitLABEL(labelO,frame))
return ''.join(result), BoolType()
elif ast.op.lower() == 'orelse':
# return left + right + self.emit.emitREOP(str(ast.op), BoolType(), frame), BoolType()
result = list()
labelF = frame.getNewLabel()
labelO = frame.getNewLabel()
result.append(left)
result.append(self.emit.jvm.emitDUP())
result.append(self.emit.jvm.emitIFEQ(labelF))
result.append(self.emit.emitGOTO(labelO,frame))
result.append(self.emit.emitLABEL(labelF,frame))
result.append(right)
result.append(self.emit.emitOROP(frame))
result.append(self.emit.emitLABEL(labelO,frame))
return ''.join(result), BoolType()
elif ast.op in ['>','<','<>','=','<=','>=']:
if type(lefttype) is type(righttype):
return left + right + self.emit.emitREOP(str(ast.op), lefttype, frame), BoolType()
elif type(righttype) is FloatType:
return left + self.emit.emitI2F(frame) + right + self.emit.emitREOP(str(ast.op), FloatType(), frame), BoolType()
else:
return left + right + self.emit.emitI2F(frame) + self.emit.emitREOP(str(ast.op), FloatType(), frame), BoolType()
elif ast.op in ['-','+']:
# if (type(lefttype) is IntType) and (type(righttype) is IntType):
if type(lefttype) is type(righttype):
return left + right + self.emit.emitADDOP(str(ast.op), lefttype, frame), lefttype
elif type(righttype) is FloatType:
return left + self.emit.emitI2F(frame) + right + self.emit.emitADDOP(str(ast.op), FloatType(), frame), FloatType()
elif type(lefttype) is FloatType:
return left + right + self.emit.emitI2F(frame) + self.emit.emitADDOP(str(ast.op), FloatType(), frame), FloatType()
elif ast.op.lower() in ['mod','div']:
if ast.op.lower() == 'mod':
return left + right + self.emit.emitMOD(frame), IntType()
else:
return left + right + self.emit.emitDIV(frame), IntType()
elif ast.op in ['/','*']:
if ast.op is '*':
if type(lefttype) is type(righttype):
return left + right + self.emit.emitMULOP(str(ast.op), lefttype, frame), lefttype
elif type(righttype) is FloatType:
return left + self.emit.emitI2F(frame) + right + self.emit.emitMULOP(str(ast.op), FloatType(), frame), FloatType()
elif type(lefttype) is FloatType:
return left + right + self.emit.emitI2F(frame) + self.emit.emitMULOP(str(ast.op), FloatType(), frame), FloatType()
else:
if type(lefttype) is type(righttype):
if type(lefttype) is IntType:
return left + self.emit.emitI2F(frame) + right + self.emit.emitI2F(frame) + self.emit.emitMULOP(str(ast.op), FloatType(), frame), FloatType()
else:
return left + right + self.emit.emitMULOP(str(ast.op), lefttype, frame), FloatType()
elif type(righttype) is FloatType:
return left + self.emit.emitI2F(frame) + right + self.emit.emitMULOP(str(ast.op), FloatType(), frame), FloatType()
elif type(lefttype) is FloatType:
return left + right + self.emit.emitI2F(frame) + self.emit.emitMULOP(str(ast.op), FloatType(), frame), FloatType()
def visitUnaryOp(self, ast, o):
ctxt = o
frame = ctxt.frame
nenv = ctxt.sym
left, lefttype = self.visit(ast.body, Access(frame,nenv,False, True))
if ast.op == '-':
return left + self.emit.emitNEGOP(lefttype, frame), lefttype
elif ast.op.lower() == 'not':
return left + self.emit.emitNOT(BoolType(), frame), BoolType()
def visitAssign(self, ast, o):
rc, rt = self.visit(ast.exp, Access(o.frame, o.sym, False, True))
lc, lt = self.visit(ast.lhs, Access(o.frame, o.sym, True, True))
if type(rt) is IntType and type(lt) is FloatType:
self.emit.printout(rc + self.emit.emitI2F(o.frame) + lc)
# if type(rt) is type(lt):
else:
self.emit.printout(rc+lc)
def visitId(self, ast, o):
ctxt = o
frame = ctxt.frame
sym = self.lookup(ast.name.lower(), o.sym, lambda x: x.name.lower())
if o.isLeft:
if type(sym.value) is CName:
return self.emit.emitPUTSTATIC(sym.value.value + "/" + sym.name, sym.mtype, frame), sym.mtype
else:
return self.emit.emitWRITEVAR(sym.name, sym.mtype, sym.value.value, frame), sym.mtype
else:
if type(sym.value) is CName:
return self.emit.emitGETSTATIC(sym.value.value + "/" + sym.name, sym.mtype, frame), sym.mtype
else:
return self.emit.emitREADVAR(sym.name, sym.mtype,sym.value.value, frame), sym.mtype
def visitWhile(self, ast, o):
ctxt = o
frame = ctxt.frame
# result = list()
frame.enterLoop()
exp, expty = self.visit(ast.exp, o)
self.emit.printout(self.emit.emitLABEL(frame.getContinueLabel(), frame))
self.emit.printout(exp)
self.emit.printout(self.emit.emitIFFALSE(frame.getBreakLabel(), frame))
[self.visit(x, SubBody(frame, o.sym)) for x in ast.sl]
self.emit.printout(self.emit.emitGOTO(frame.getContinueLabel(), frame))
self.emit.printout(self.emit.emitLABEL(frame.getBreakLabel(), frame))
# self.emit.printout(''.join(result))
frame.exitLoop()
def visitIf(self, ast, o): ##need to left out GOTO when there is no else
ctxt = o
frame = ctxt.frame
# result = list()
exp, typee = self.visit(ast.expr, Access(o.frame, o.sym, False, True))
self.emit.printout(exp)
label1 = frame.getNewLabel()
label2 = frame.getNewLabel()
self.emit.printout(self.emit.emitIFFALSE(label1,frame))
[self.visit(x,SubBody(frame, o.sym)) for x in ast.thenStmt]
checkthen = self.checkReturn(ast.thenStmt)
if ast.elseStmt != []:
checkelse = self.checkReturn(ast.elseStmt)
else:
checkelse = False
if (checkthen and checkelse) is False:
self.emit.printout(self.emit.emitGOTO(label2,frame))
self.emit.printout(self.emit.emitLABEL(label1, frame))
[self.visit(x, SubBody(frame, o.sym)) for x in ast.elseStmt]
self.emit.printout(self.emit.emitLABEL(label2, frame))
def checkReturn(self, body): ##check enough return in [stmt]
for x in body:
if (self.checkReturnStatement(x) is True):
return True
return False
def checkReturnStatement(self, state): ##check if enough return in one stmt
if type(state) is If:
thenn = self.checkReturn(state.thenStmt)
if state.elseStmt is not None:
elsee = self.checkReturn(state.elseStmt)
else:
elsee = False
return thenn and elsee ##what if else is empty??
elif type(state) is With:
return self.checkReturn(state.stmt)
elif type(state) is Return:
return True
return False
def visitFor(self, ast, o):
ctxt = o
frame = ctxt.frame
frame.enterLoop()
exp1, exp1type = self.visit(ast.expr1,Access(o.frame, o.sym, False, True)) #1sr expr
condi,conditype = self.visit(ast.id, Access(o.frame, o.sym, True, True)) #getID
condi2,conditype2 = self.visit(ast.id, Access(o.frame, o.sym, False, True))
self.emit.printout(exp1)
self.emit.printout(condi)
condi_index = self.lookup(ast.id.name.lower(), o.sym, lambda x: x.name.lower())
# self.emit.printout(self.emit.emitWRITEVAR(ast.id.name, IntType(),condi_index.value.value,frame))
#if up -1, if downto +1
self.emit.printout(self.emit.emitREADVAR(ast.id.name, IntType(), condi_index.value.value, frame) + self.emit.emitPUSHICONST(1,frame))
if ast.up is True:
self.emit.printout(self.emit.emitADDOP('-',IntType(), frame) +self.emit.emitWRITEVAR(ast.id.name, IntType(), condi_index.value.value, frame))
else:
self.emit.printout(self.emit.emitADDOP('+',IntType(), frame) +self.emit.emitWRITEVAR(ast.id.name, IntType(), condi_index.value.value, frame))
self.emit.printout(self.emit.emitLABEL(frame.getContinueLabel(), frame)) # co
exp2, exp2type = self.visit(ast.expr2, Access(o.frame, o.sym, False, True))
if ast.up is True: ##increase loop
self.emit.printout(condi2 + self.emit.emitPUSHICONST(1,frame) + self.emit.emitADDOP('+', IntType(), frame))
self.emit.printout(condi)
else:
self.emit.printout(condi2 + self.emit.emitPUSHICONST(1,frame) + self.emit.emitADDOP('-', IntType(), frame))
self.emit.printout(condi)
if ast.up is True: #check condition
self.emit.printout(condi2 + exp2 + self.emit.emitREOP('<=', IntType(),frame))
else:
self.emit.printout(condi2 + exp2 + self.emit.emitREOP('>=', IntType(), frame))
self.emit.printout(self.emit.emitIFFALSE(frame.getBreakLabel(), frame))
[self.visit(x, SubBody(frame, o.sym)) for x in ast.loop]
self.emit.printout(self.emit.emitGOTO(frame.getContinueLabel(),frame))
self.emit.printout(self.emit.emitLABEL(frame.getBreakLabel(), frame))
frame.exitLoop()
def visitReturn(self, ast, o):
if ast.expr:
exp, typexp = self.visit(ast.expr, Access(o.frame, o.sym, False, True))
if type(typexp) == IntType and type(o.frame.returnType) == FloatType:
self.emit.printout(exp + self.emit.emitI2F(o.frame) + self.emit.emitRETURN(FloatType(), o.frame))
else:
self.emit.printout(exp + self.emit.emitRETURN(typexp, o.frame))
else:
self.emit.printout(self.emit.emitRETURN(VoidType(), o.frame))
def visitBreak(self, ast, o):
self.emit.printout(self.emit.emitGOTO(str(o.frame.getBreakLabel()),o.frame))
def visitContinue(self, ast, o):
self.emit.printout(self.emit.emitGOTO(str(o.frame.getContinueLabel()),o.frame))
def visitWith(self, ast, o):
ctxt = o
frame = ctxt.frame
label1 = frame.getNewLabel()
label2 = frame.getNewLabel()
varde = list()
self.emit.printout(self.emit.emitLABEL(label1, frame))
for x in ast.decl:
sym = Symbol(x.variable.name, x.varType, Index(frame.getNewIndex()))
varde.append(sym)
self.emit.printout(self.emit.emitVAR(sym.value.value, sym.name, sym.mtype, label1, label2, frame))
for x in ast.stmt:
stmt = self.visit(x, SubBody(frame, varde + ctxt.sym))
self.emit.printout(self.emit.emitLABEL(label2, frame))
|
{"/upload/src/main/mp/parser/MPVisitor.py": ["/upload/src/main/mp/parser/MPParser.py"]}
|
22,550
|
sarv19/ass4
|
refs/heads/master
|
/upload/src/main/mp/parser/MPParser.py
|
# Generated from main/mp/parser/MP.g4 by ANTLR 4.7.1
# encoding: utf-8
from antlr4 import *
from io import StringIO
from typing.io import TextIO
import sys
def serializedATN():
with StringIO() as buf:
buf.write("\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\3?")
buf.write("\u018d\4\2\t\2\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7\t\7")
buf.write("\4\b\t\b\4\t\t\t\4\n\t\n\4\13\t\13\4\f\t\f\4\r\t\r\4\16")
buf.write("\t\16\4\17\t\17\4\20\t\20\4\21\t\21\4\22\t\22\4\23\t\23")
buf.write("\4\24\t\24\4\25\t\25\4\26\t\26\4\27\t\27\4\30\t\30\4\31")
buf.write("\t\31\4\32\t\32\4\33\t\33\4\34\t\34\4\35\t\35\4\36\t\36")
buf.write("\4\37\t\37\4 \t \4!\t!\4\"\t\"\4#\t#\4$\t$\4%\t%\4&\t")
buf.write("&\3\2\6\2N\n\2\r\2\16\2O\3\2\3\2\3\3\3\3\3\3\5\3W\n\3")
buf.write("\3\4\3\4\6\4[\n\4\r\4\16\4\\\3\5\3\5\3\5\3\5\3\5\3\6\3")
buf.write("\6\3\6\7\6g\n\6\f\6\16\6j\13\6\3\7\3\7\5\7n\n\7\3\b\3")
buf.write("\b\3\t\3\t\3\t\3\t\3\t\3\t\3\t\3\t\3\t\3\n\5\n|\n\n\3")
buf.write("\n\3\n\3\13\3\13\3\13\3\13\5\13\u0084\n\13\3\13\3\13\3")
buf.write("\13\3\13\3\13\5\13\u008b\n\13\3\13\3\13\3\f\3\f\3\f\7")
buf.write("\f\u0092\n\f\f\f\16\f\u0095\13\f\3\r\3\r\3\r\3\r\3\16")
buf.write("\3\16\3\16\3\16\5\16\u009f\n\16\3\16\3\16\3\16\5\16\u00a4")
buf.write("\n\16\3\16\3\16\3\17\3\17\7\17\u00aa\n\17\f\17\16\17\u00ad")
buf.write("\13\17\3\17\3\17\3\20\3\20\3\20\3\20\3\20\3\20\3\20\3")
buf.write("\20\3\20\3\20\5\20\u00bb\n\20\3\21\3\21\3\22\3\22\3\22")
buf.write("\6\22\u00c2\n\22\r\22\16\22\u00c3\3\22\3\22\3\22\3\23")
buf.write("\3\23\5\23\u00cb\n\23\3\24\3\24\3\24\3\24\3\24\3\24\5")
buf.write("\24\u00d3\n\24\3\25\3\25\3\25\3\25\3\25\3\26\3\26\3\26")
buf.write("\3\26\3\26\3\26\3\26\3\26\3\26\3\27\3\27\3\27\3\30\3\30")
buf.write("\3\30\3\31\3\31\5\31\u00eb\n\31\3\31\3\31\3\32\3\32\6")
buf.write("\32\u00f1\n\32\r\32\16\32\u00f2\3\32\3\32\3\32\3\33\3")
buf.write("\33\3\33\3\33\3\33\7\33\u00fd\n\33\f\33\16\33\u0100\13")
buf.write("\33\5\33\u0102\n\33\3\33\3\33\3\33\3\34\3\34\3\34\3\34")
buf.write("\3\34\3\34\3\34\3\34\3\34\3\34\3\34\7\34\u0112\n\34\f")
buf.write("\34\16\34\u0115\13\34\3\35\3\35\3\35\3\35\3\35\3\35\3")
buf.write("\35\3\35\3\35\3\35\3\35\3\35\3\35\3\35\3\35\3\35\3\35")
buf.write("\3\35\3\35\3\35\3\35\3\35\3\35\3\35\3\35\5\35\u0130\n")
buf.write("\35\3\36\3\36\3\36\3\36\3\36\3\36\3\36\3\36\3\36\3\36")
buf.write("\3\36\3\36\7\36\u013e\n\36\f\36\16\36\u0141\13\36\3\37")
buf.write("\3\37\3\37\3\37\3\37\3\37\3\37\3\37\3\37\3\37\3\37\3\37")
buf.write("\3\37\3\37\3\37\3\37\3\37\3\37\7\37\u0155\n\37\f\37\16")
buf.write("\37\u0158\13\37\3 \3 \3 \3 \3 \5 \u015f\n \3!\3!\3!\3")
buf.write("!\3!\3!\5!\u0167\n!\3\"\3\"\3\"\3\"\3\"\5\"\u016e\n\"")
buf.write("\3#\3#\3#\3#\3#\3#\5#\u0176\n#\3$\3$\3$\3$\3$\7$\u017d")
buf.write("\n$\f$\16$\u0180\13$\5$\u0182\n$\3$\3$\3%\3%\3%\3%\3%")
buf.write("\3&\3&\3&\2\5\66:<\'\2\4\6\b\n\f\16\20\22\24\26\30\32")
buf.write("\34\36 \"$&(*,.\60\62\64\668:<>@BDFHJ\2\5\6\2\6\6\22\22")
buf.write("\30\30\32\32\4\2\13\13\34\34\4\2\16\16\35\35\2\u019f\2")
buf.write("M\3\2\2\2\4V\3\2\2\2\6X\3\2\2\2\b^\3\2\2\2\nc\3\2\2\2")
buf.write("\fm\3\2\2\2\16o\3\2\2\2\20q\3\2\2\2\22{\3\2\2\2\24\177")
buf.write("\3\2\2\2\26\u008e\3\2\2\2\30\u0096\3\2\2\2\32\u009a\3")
buf.write("\2\2\2\34\u00a7\3\2\2\2\36\u00ba\3\2\2\2 \u00bc\3\2\2")
buf.write("\2\"\u00c1\3\2\2\2$\u00ca\3\2\2\2&\u00cc\3\2\2\2(\u00d4")
buf.write("\3\2\2\2*\u00d9\3\2\2\2,\u00e2\3\2\2\2.\u00e5\3\2\2\2")
buf.write("\60\u00e8\3\2\2\2\62\u00ee\3\2\2\2\64\u00f7\3\2\2\2\66")
buf.write("\u0106\3\2\2\28\u012f\3\2\2\2:\u0131\3\2\2\2<\u0142\3")
buf.write("\2\2\2>\u015e\3\2\2\2@\u0166\3\2\2\2B\u016d\3\2\2\2D\u0175")
buf.write("\3\2\2\2F\u0177\3\2\2\2H\u0185\3\2\2\2J\u018a\3\2\2\2")
buf.write("LN\5\4\3\2ML\3\2\2\2NO\3\2\2\2OM\3\2\2\2OP\3\2\2\2PQ\3")
buf.write("\2\2\2QR\7\2\2\3R\3\3\2\2\2SW\5\6\4\2TW\5\24\13\2UW\5")
buf.write("\32\16\2VS\3\2\2\2VT\3\2\2\2VU\3\2\2\2W\5\3\2\2\2XZ\7")
buf.write("\36\2\2Y[\5\b\5\2ZY\3\2\2\2[\\\3\2\2\2\\Z\3\2\2\2\\]\3")
buf.write("\2\2\2]\7\3\2\2\2^_\5\n\6\2_`\7(\2\2`a\5\f\7\2ab\7\'\2")
buf.write("\2b\t\3\2\2\2ch\79\2\2de\7&\2\2eg\79\2\2fd\3\2\2\2gj\3")
buf.write("\2\2\2hf\3\2\2\2hi\3\2\2\2i\13\3\2\2\2jh\3\2\2\2kn\5\16")
buf.write("\b\2ln\5\20\t\2mk\3\2\2\2ml\3\2\2\2n\r\3\2\2\2op\t\2\2")
buf.write("\2p\17\3\2\2\2qr\7\4\2\2rs\7/\2\2st\5\22\n\2tu\7\65\2")
buf.write("\2uv\5\22\n\2vw\7\60\2\2wx\7\25\2\2xy\5\16\b\2y\21\3\2")
buf.write("\2\2z|\7\"\2\2{z\3\2\2\2{|\3\2\2\2|}\3\2\2\2}~\7:\2\2")
buf.write("~\23\3\2\2\2\177\u0080\7\20\2\2\u0080\u0081\79\2\2\u0081")
buf.write("\u0083\7\61\2\2\u0082\u0084\5\26\f\2\u0083\u0082\3\2\2")
buf.write("\2\u0083\u0084\3\2\2\2\u0084\u0085\3\2\2\2\u0085\u0086")
buf.write("\7\62\2\2\u0086\u0087\7(\2\2\u0087\u0088\5\f\7\2\u0088")
buf.write("\u008a\7\'\2\2\u0089\u008b\5\6\4\2\u008a\u0089\3\2\2\2")
buf.write("\u008a\u008b\3\2\2\2\u008b\u008c\3\2\2\2\u008c\u008d\5")
buf.write("\34\17\2\u008d\25\3\2\2\2\u008e\u0093\5\30\r\2\u008f\u0090")
buf.write("\7\'\2\2\u0090\u0092\5\30\r\2\u0091\u008f\3\2\2\2\u0092")
buf.write("\u0095\3\2\2\2\u0093\u0091\3\2\2\2\u0093\u0094\3\2\2\2")
buf.write("\u0094\27\3\2\2\2\u0095\u0093\3\2\2\2\u0096\u0097\5\n")
buf.write("\6\2\u0097\u0098\7(\2\2\u0098\u0099\5\f\7\2\u0099\31\3")
buf.write("\2\2\2\u009a\u009b\7\27\2\2\u009b\u009c\79\2\2\u009c\u009e")
buf.write("\7\61\2\2\u009d\u009f\5\26\f\2\u009e\u009d\3\2\2\2\u009e")
buf.write("\u009f\3\2\2\2\u009f\u00a0\3\2\2\2\u00a0\u00a1\7\62\2")
buf.write("\2\u00a1\u00a3\7\'\2\2\u00a2\u00a4\5\6\4\2\u00a3\u00a2")
buf.write("\3\2\2\2\u00a3\u00a4\3\2\2\2\u00a4\u00a5\3\2\2\2\u00a5")
buf.write("\u00a6\5\34\17\2\u00a6\33\3\2\2\2\u00a7\u00ab\7\5\2\2")
buf.write("\u00a8\u00aa\5\36\20\2\u00a9\u00a8\3\2\2\2\u00aa\u00ad")
buf.write("\3\2\2\2\u00ab\u00a9\3\2\2\2\u00ab\u00ac\3\2\2\2\u00ac")
buf.write("\u00ae\3\2\2\2\u00ad\u00ab\3\2\2\2\u00ae\u00af\7\r\2\2")
buf.write("\u00af\35\3\2\2\2\u00b0\u00bb\5\"\22\2\u00b1\u00bb\5&")
buf.write("\24\2\u00b2\u00bb\5(\25\2\u00b3\u00bb\5*\26\2\u00b4\u00bb")
buf.write("\5,\27\2\u00b5\u00bb\5.\30\2\u00b6\u00bb\5\60\31\2\u00b7")
buf.write("\u00bb\5\62\32\2\u00b8\u00bb\5\64\33\2\u00b9\u00bb\5 ")
buf.write("\21\2\u00ba\u00b0\3\2\2\2\u00ba\u00b1\3\2\2\2\u00ba\u00b2")
buf.write("\3\2\2\2\u00ba\u00b3\3\2\2\2\u00ba\u00b4\3\2\2\2\u00ba")
buf.write("\u00b5\3\2\2\2\u00ba\u00b6\3\2\2\2\u00ba\u00b7\3\2\2\2")
buf.write("\u00ba\u00b8\3\2\2\2\u00ba\u00b9\3\2\2\2\u00bb\37\3\2")
buf.write("\2\2\u00bc\u00bd\5\34\17\2\u00bd!\3\2\2\2\u00be\u00bf")
buf.write("\5$\23\2\u00bf\u00c0\7%\2\2\u00c0\u00c2\3\2\2\2\u00c1")
buf.write("\u00be\3\2\2\2\u00c2\u00c3\3\2\2\2\u00c3\u00c1\3\2\2\2")
buf.write("\u00c3\u00c4\3\2\2\2\u00c4\u00c5\3\2\2\2\u00c5\u00c6\5")
buf.write("\66\34\2\u00c6\u00c7\7\'\2\2\u00c7#\3\2\2\2\u00c8\u00cb")
buf.write("\79\2\2\u00c9\u00cb\5H%\2\u00ca\u00c8\3\2\2\2\u00ca\u00c9")
buf.write("\3\2\2\2\u00cb%\3\2\2\2\u00cc\u00cd\7\21\2\2\u00cd\u00ce")
buf.write("\5\66\34\2\u00ce\u00cf\7\33\2\2\u00cf\u00d2\5\36\20\2")
buf.write("\u00d0\u00d1\7\f\2\2\u00d1\u00d3\5\36\20\2\u00d2\u00d0")
buf.write("\3\2\2\2\u00d2\u00d3\3\2\2\2\u00d3\'\3\2\2\2\u00d4\u00d5")
buf.write("\7\37\2\2\u00d5\u00d6\5\66\34\2\u00d6\u00d7\7\n\2\2\u00d7")
buf.write("\u00d8\5\36\20\2\u00d8)\3\2\2\2\u00d9\u00da\7\17\2\2\u00da")
buf.write("\u00db\79\2\2\u00db\u00dc\7%\2\2\u00dc\u00dd\5\66\34\2")
buf.write("\u00dd\u00de\t\3\2\2\u00de\u00df\5\66\34\2\u00df\u00e0")
buf.write("\7\n\2\2\u00e0\u00e1\5\36\20\2\u00e1+\3\2\2\2\u00e2\u00e3")
buf.write("\7\7\2\2\u00e3\u00e4\7\'\2\2\u00e4-\3\2\2\2\u00e5\u00e6")
buf.write("\7\b\2\2\u00e6\u00e7\7\'\2\2\u00e7/\3\2\2\2\u00e8\u00ea")
buf.write("\7\31\2\2\u00e9\u00eb\5\66\34\2\u00ea\u00e9\3\2\2\2\u00ea")
buf.write("\u00eb\3\2\2\2\u00eb\u00ec\3\2\2\2\u00ec\u00ed\7\'\2\2")
buf.write("\u00ed\61\3\2\2\2\u00ee\u00f0\7 \2\2\u00ef\u00f1\5\b\5")
buf.write("\2\u00f0\u00ef\3\2\2\2\u00f1\u00f2\3\2\2\2\u00f2\u00f0")
buf.write("\3\2\2\2\u00f2\u00f3\3\2\2\2\u00f3\u00f4\3\2\2\2\u00f4")
buf.write("\u00f5\7\n\2\2\u00f5\u00f6\5\36\20\2\u00f6\63\3\2\2\2")
buf.write("\u00f7\u00f8\79\2\2\u00f8\u0101\7\61\2\2\u00f9\u00fe\5")
buf.write("\66\34\2\u00fa\u00fb\7&\2\2\u00fb\u00fd\5\66\34\2\u00fc")
buf.write("\u00fa\3\2\2\2\u00fd\u0100\3\2\2\2\u00fe\u00fc\3\2\2\2")
buf.write("\u00fe\u00ff\3\2\2\2\u00ff\u0102\3\2\2\2\u0100\u00fe\3")
buf.write("\2\2\2\u0101\u00f9\3\2\2\2\u0101\u0102\3\2\2\2\u0102\u0103")
buf.write("\3\2\2\2\u0103\u0104\7\62\2\2\u0104\u0105\7\'\2\2\u0105")
buf.write("\65\3\2\2\2\u0106\u0107\b\34\1\2\u0107\u0108\58\35\2\u0108")
buf.write("\u0113\3\2\2\2\u0109\u010a\f\5\2\2\u010a\u010b\7\3\2\2")
buf.write("\u010b\u010c\7\33\2\2\u010c\u0112\58\35\2\u010d\u010e")
buf.write("\f\4\2\2\u010e\u010f\7\26\2\2\u010f\u0110\7\f\2\2\u0110")
buf.write("\u0112\58\35\2\u0111\u0109\3\2\2\2\u0111\u010d\3\2\2\2")
buf.write("\u0112\u0115\3\2\2\2\u0113\u0111\3\2\2\2\u0113\u0114\3")
buf.write("\2\2\2\u0114\67\3\2\2\2\u0115\u0113\3\2\2\2\u0116\u0117")
buf.write("\5:\36\2\u0117\u0118\7)\2\2\u0118\u0119\5:\36\2\u0119")
buf.write("\u0130\3\2\2\2\u011a\u011b\5:\36\2\u011b\u011c\7*\2\2")
buf.write("\u011c\u011d\5:\36\2\u011d\u0130\3\2\2\2\u011e\u011f\5")
buf.write(":\36\2\u011f\u0120\7+\2\2\u0120\u0121\5:\36\2\u0121\u0130")
buf.write("\3\2\2\2\u0122\u0123\5:\36\2\u0123\u0124\7,\2\2\u0124")
buf.write("\u0125\5:\36\2\u0125\u0130\3\2\2\2\u0126\u0127\5:\36\2")
buf.write("\u0127\u0128\7-\2\2\u0128\u0129\5:\36\2\u0129\u0130\3")
buf.write("\2\2\2\u012a\u012b\5:\36\2\u012b\u012c\7.\2\2\u012c\u012d")
buf.write("\5:\36\2\u012d\u0130\3\2\2\2\u012e\u0130\5:\36\2\u012f")
buf.write("\u0116\3\2\2\2\u012f\u011a\3\2\2\2\u012f\u011e\3\2\2\2")
buf.write("\u012f\u0122\3\2\2\2\u012f\u0126\3\2\2\2\u012f\u012a\3")
buf.write("\2\2\2\u012f\u012e\3\2\2\2\u01309\3\2\2\2\u0131\u0132")
buf.write("\b\36\1\2\u0132\u0133\5<\37\2\u0133\u013f\3\2\2\2\u0134")
buf.write("\u0135\f\6\2\2\u0135\u0136\7!\2\2\u0136\u013e\5<\37\2")
buf.write("\u0137\u0138\f\5\2\2\u0138\u0139\7\"\2\2\u0139\u013e\5")
buf.write("<\37\2\u013a\u013b\f\4\2\2\u013b\u013c\7\26\2\2\u013c")
buf.write("\u013e\5<\37\2\u013d\u0134\3\2\2\2\u013d\u0137\3\2\2\2")
buf.write("\u013d\u013a\3\2\2\2\u013e\u0141\3\2\2\2\u013f\u013d\3")
buf.write("\2\2\2\u013f\u0140\3\2\2\2\u0140;\3\2\2\2\u0141\u013f")
buf.write("\3\2\2\2\u0142\u0143\b\37\1\2\u0143\u0144\5> \2\u0144")
buf.write("\u0156\3\2\2\2\u0145\u0146\f\b\2\2\u0146\u0147\7$\2\2")
buf.write("\u0147\u0155\5> \2\u0148\u0149\f\7\2\2\u0149\u014a\7#")
buf.write("\2\2\u014a\u0155\5> \2\u014b\u014c\f\6\2\2\u014c\u014d")
buf.write("\7\t\2\2\u014d\u0155\5> \2\u014e\u014f\f\5\2\2\u014f\u0150")
buf.write("\7\23\2\2\u0150\u0155\5> \2\u0151\u0152\f\4\2\2\u0152")
buf.write("\u0153\7\3\2\2\u0153\u0155\5> \2\u0154\u0145\3\2\2\2\u0154")
buf.write("\u0148\3\2\2\2\u0154\u014b\3\2\2\2\u0154\u014e\3\2\2\2")
buf.write("\u0154\u0151\3\2\2\2\u0155\u0158\3\2\2\2\u0156\u0154\3")
buf.write("\2\2\2\u0156\u0157\3\2\2\2\u0157=\3\2\2\2\u0158\u0156")
buf.write("\3\2\2\2\u0159\u015a\7\"\2\2\u015a\u015f\5> \2\u015b\u015c")
buf.write("\7\24\2\2\u015c\u015f\5> \2\u015d\u015f\5@!\2\u015e\u0159")
buf.write("\3\2\2\2\u015e\u015b\3\2\2\2\u015e\u015d\3\2\2\2\u015f")
buf.write("?\3\2\2\2\u0160\u0161\5B\"\2\u0161\u0162\7/\2\2\u0162")
buf.write("\u0163\5\66\34\2\u0163\u0164\7\60\2\2\u0164\u0167\3\2")
buf.write("\2\2\u0165\u0167\5B\"\2\u0166\u0160\3\2\2\2\u0166\u0165")
buf.write("\3\2\2\2\u0167A\3\2\2\2\u0168\u0169\7\61\2\2\u0169\u016a")
buf.write("\5\66\34\2\u016a\u016b\7\62\2\2\u016b\u016e\3\2\2\2\u016c")
buf.write("\u016e\5D#\2\u016d\u0168\3\2\2\2\u016d\u016c\3\2\2\2\u016e")
buf.write("C\3\2\2\2\u016f\u0176\79\2\2\u0170\u0176\7:\2\2\u0171")
buf.write("\u0176\7;\2\2\u0172\u0176\7<\2\2\u0173\u0176\5J&\2\u0174")
buf.write("\u0176\5F$\2\u0175\u016f\3\2\2\2\u0175\u0170\3\2\2\2\u0175")
buf.write("\u0171\3\2\2\2\u0175\u0172\3\2\2\2\u0175\u0173\3\2\2\2")
buf.write("\u0175\u0174\3\2\2\2\u0176E\3\2\2\2\u0177\u0178\79\2\2")
buf.write("\u0178\u0181\7\61\2\2\u0179\u017e\5\66\34\2\u017a\u017b")
buf.write("\7&\2\2\u017b\u017d\5\66\34\2\u017c\u017a\3\2\2\2\u017d")
buf.write("\u0180\3\2\2\2\u017e\u017c\3\2\2\2\u017e\u017f\3\2\2\2")
buf.write("\u017f\u0182\3\2\2\2\u0180\u017e\3\2\2\2\u0181\u0179\3")
buf.write("\2\2\2\u0181\u0182\3\2\2\2\u0182\u0183\3\2\2\2\u0183\u0184")
buf.write("\7\62\2\2\u0184G\3\2\2\2\u0185\u0186\5B\"\2\u0186\u0187")
buf.write("\7/\2\2\u0187\u0188\5\66\34\2\u0188\u0189\7\60\2\2\u0189")
buf.write("I\3\2\2\2\u018a\u018b\t\4\2\2\u018bK\3\2\2\2#OV\\hm{\u0083")
buf.write("\u008a\u0093\u009e\u00a3\u00ab\u00ba\u00c3\u00ca\u00d2")
buf.write("\u00ea\u00f2\u00fe\u0101\u0111\u0113\u012f\u013d\u013f")
buf.write("\u0154\u0156\u015e\u0166\u016d\u0175\u017e\u0181")
return buf.getvalue()
class MPParser ( Parser ):
grammarFileName = "MP.g4"
atn = ATNDeserializer().deserialize(serializedATN())
decisionsToDFA = [ DFA(ds, i) for i, ds in enumerate(atn.decisionToState) ]
sharedContextCache = PredictionContextCache()
literalNames = [ "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>",
"<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>",
"<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>",
"<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>",
"<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>",
"<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>",
"<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>",
"<INVALID>", "<INVALID>", "<INVALID>", "'+'", "'-'",
"'*'", "'/'", "':='", "','", "';'", "':'", "'='", "'<>'",
"'<'", "'<='", "'>'", "'>='", "'['", "']'", "'('",
"')'", "'{'", "'}'", "'..'" ]
symbolicNames = [ "<INVALID>", "AND", "ARRAY", "BEGIN", "BOOLEAN", "BREAK",
"CONTINUE", "DIV", "DO", "DOWNTO", "ELSE", "END",
"FALSE", "FOR", "FUNCTION", "IF", "INTEGER", "MOD",
"NOT", "OF", "OR", "PROCEDURE", "REAL", "RETURN",
"STRING", "THEN", "TO", "TRUE", "VAR", "WHILE", "WITH",
"ADD", "SUB", "MUL", "SLASH", "ASSIGN", "COMMA", "SEMI",
"COLON", "EQUAL", "NOTEQUAL", "LT", "LE", "GT", "GE",
"LB", "RB", "LP", "RP", "LC", "RC", "DOTDOT", "WHITESPACE",
"BLOCK_COMMENT", "LINE_COMMENT", "ID", "INTLIT", "FLOATLIT",
"STRINGLIT", "UNCLOSE_STRING", "ILLEGAL_ESCAPE", "ERROR_CHAR" ]
RULE_program = 0
RULE_decl = 1
RULE_vardecl = 2
RULE_vargroup = 3
RULE_idlist = 4
RULE_idtype = 5
RULE_primtype = 6
RULE_arraytype = 7
RULE_signedInt = 8
RULE_funcdecl = 9
RULE_plist = 10
RULE_pgroup = 11
RULE_procdecl = 12
RULE_body = 13
RULE_stmt = 14
RULE_cpstmt = 15
RULE_assign = 16
RULE_variable = 17
RULE_ifstmt = 18
RULE_whilestmt = 19
RULE_forstmt = 20
RULE_breakstmt = 21
RULE_continuestmt = 22
RULE_returnstmt = 23
RULE_withstmt = 24
RULE_callstmt = 25
RULE_expr = 26
RULE_exp1 = 27
RULE_exp2 = 28
RULE_exp3 = 29
RULE_exp4 = 30
RULE_exp5 = 31
RULE_exp6 = 32
RULE_op = 33
RULE_funcall = 34
RULE_arraycell = 35
RULE_boollit = 36
ruleNames = [ "program", "decl", "vardecl", "vargroup", "idlist", "idtype",
"primtype", "arraytype", "signedInt", "funcdecl", "plist",
"pgroup", "procdecl", "body", "stmt", "cpstmt", "assign",
"variable", "ifstmt", "whilestmt", "forstmt", "breakstmt",
"continuestmt", "returnstmt", "withstmt", "callstmt",
"expr", "exp1", "exp2", "exp3", "exp4", "exp5", "exp6",
"op", "funcall", "arraycell", "boollit" ]
EOF = Token.EOF
AND=1
ARRAY=2
BEGIN=3
BOOLEAN=4
BREAK=5
CONTINUE=6
DIV=7
DO=8
DOWNTO=9
ELSE=10
END=11
FALSE=12
FOR=13
FUNCTION=14
IF=15
INTEGER=16
MOD=17
NOT=18
OF=19
OR=20
PROCEDURE=21
REAL=22
RETURN=23
STRING=24
THEN=25
TO=26
TRUE=27
VAR=28
WHILE=29
WITH=30
ADD=31
SUB=32
MUL=33
SLASH=34
ASSIGN=35
COMMA=36
SEMI=37
COLON=38
EQUAL=39
NOTEQUAL=40
LT=41
LE=42
GT=43
GE=44
LB=45
RB=46
LP=47
RP=48
LC=49
RC=50
DOTDOT=51
WHITESPACE=52
BLOCK_COMMENT=53
LINE_COMMENT=54
ID=55
INTLIT=56
FLOATLIT=57
STRINGLIT=58
UNCLOSE_STRING=59
ILLEGAL_ESCAPE=60
ERROR_CHAR=61
def __init__(self, input:TokenStream, output:TextIO = sys.stdout):
super().__init__(input, output)
self.checkVersion("4.7.1")
self._interp = ParserATNSimulator(self, self.atn, self.decisionsToDFA, self.sharedContextCache)
self._predicates = None
class ProgramContext(ParserRuleContext):
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def EOF(self):
return self.getToken(MPParser.EOF, 0)
def decl(self, i:int=None):
if i is None:
return self.getTypedRuleContexts(MPParser.DeclContext)
else:
return self.getTypedRuleContext(MPParser.DeclContext,i)
def getRuleIndex(self):
return MPParser.RULE_program
def accept(self, visitor:ParseTreeVisitor):
if hasattr( visitor, "visitProgram" ):
return visitor.visitProgram(self)
else:
return visitor.visitChildren(self)
def program(self):
localctx = MPParser.ProgramContext(self, self._ctx, self.state)
self.enterRule(localctx, 0, self.RULE_program)
self._la = 0 # Token type
try:
self.enterOuterAlt(localctx, 1)
self.state = 75
self._errHandler.sync(self)
_la = self._input.LA(1)
while True:
self.state = 74
self.decl()
self.state = 77
self._errHandler.sync(self)
_la = self._input.LA(1)
if not ((((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << MPParser.FUNCTION) | (1 << MPParser.PROCEDURE) | (1 << MPParser.VAR))) != 0)):
break
self.state = 79
self.match(MPParser.EOF)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class DeclContext(ParserRuleContext):
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def vardecl(self):
return self.getTypedRuleContext(MPParser.VardeclContext,0)
def funcdecl(self):
return self.getTypedRuleContext(MPParser.FuncdeclContext,0)
def procdecl(self):
return self.getTypedRuleContext(MPParser.ProcdeclContext,0)
def getRuleIndex(self):
return MPParser.RULE_decl
def accept(self, visitor:ParseTreeVisitor):
if hasattr( visitor, "visitDecl" ):
return visitor.visitDecl(self)
else:
return visitor.visitChildren(self)
def decl(self):
localctx = MPParser.DeclContext(self, self._ctx, self.state)
self.enterRule(localctx, 2, self.RULE_decl)
try:
self.state = 84
self._errHandler.sync(self)
token = self._input.LA(1)
if token in [MPParser.VAR]:
self.enterOuterAlt(localctx, 1)
self.state = 81
self.vardecl()
pass
elif token in [MPParser.FUNCTION]:
self.enterOuterAlt(localctx, 2)
self.state = 82
self.funcdecl()
pass
elif token in [MPParser.PROCEDURE]:
self.enterOuterAlt(localctx, 3)
self.state = 83
self.procdecl()
pass
else:
raise NoViableAltException(self)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class VardeclContext(ParserRuleContext):
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def VAR(self):
return self.getToken(MPParser.VAR, 0)
def vargroup(self, i:int=None):
if i is None:
return self.getTypedRuleContexts(MPParser.VargroupContext)
else:
return self.getTypedRuleContext(MPParser.VargroupContext,i)
def getRuleIndex(self):
return MPParser.RULE_vardecl
def accept(self, visitor:ParseTreeVisitor):
if hasattr( visitor, "visitVardecl" ):
return visitor.visitVardecl(self)
else:
return visitor.visitChildren(self)
def vardecl(self):
localctx = MPParser.VardeclContext(self, self._ctx, self.state)
self.enterRule(localctx, 4, self.RULE_vardecl)
self._la = 0 # Token type
try:
self.enterOuterAlt(localctx, 1)
self.state = 86
self.match(MPParser.VAR)
self.state = 88
self._errHandler.sync(self)
_la = self._input.LA(1)
while True:
self.state = 87
self.vargroup()
self.state = 90
self._errHandler.sync(self)
_la = self._input.LA(1)
if not (_la==MPParser.ID):
break
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class VargroupContext(ParserRuleContext):
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def idlist(self):
return self.getTypedRuleContext(MPParser.IdlistContext,0)
def COLON(self):
return self.getToken(MPParser.COLON, 0)
def idtype(self):
return self.getTypedRuleContext(MPParser.IdtypeContext,0)
def SEMI(self):
return self.getToken(MPParser.SEMI, 0)
def getRuleIndex(self):
return MPParser.RULE_vargroup
def accept(self, visitor:ParseTreeVisitor):
if hasattr( visitor, "visitVargroup" ):
return visitor.visitVargroup(self)
else:
return visitor.visitChildren(self)
def vargroup(self):
localctx = MPParser.VargroupContext(self, self._ctx, self.state)
self.enterRule(localctx, 6, self.RULE_vargroup)
try:
self.enterOuterAlt(localctx, 1)
self.state = 92
self.idlist()
self.state = 93
self.match(MPParser.COLON)
self.state = 94
self.idtype()
self.state = 95
self.match(MPParser.SEMI)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class IdlistContext(ParserRuleContext):
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def ID(self, i:int=None):
if i is None:
return self.getTokens(MPParser.ID)
else:
return self.getToken(MPParser.ID, i)
def COMMA(self, i:int=None):
if i is None:
return self.getTokens(MPParser.COMMA)
else:
return self.getToken(MPParser.COMMA, i)
def getRuleIndex(self):
return MPParser.RULE_idlist
def accept(self, visitor:ParseTreeVisitor):
if hasattr( visitor, "visitIdlist" ):
return visitor.visitIdlist(self)
else:
return visitor.visitChildren(self)
def idlist(self):
localctx = MPParser.IdlistContext(self, self._ctx, self.state)
self.enterRule(localctx, 8, self.RULE_idlist)
self._la = 0 # Token type
try:
self.enterOuterAlt(localctx, 1)
self.state = 97
self.match(MPParser.ID)
self.state = 102
self._errHandler.sync(self)
_la = self._input.LA(1)
while _la==MPParser.COMMA:
self.state = 98
self.match(MPParser.COMMA)
self.state = 99
self.match(MPParser.ID)
self.state = 104
self._errHandler.sync(self)
_la = self._input.LA(1)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class IdtypeContext(ParserRuleContext):
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def primtype(self):
return self.getTypedRuleContext(MPParser.PrimtypeContext,0)
def arraytype(self):
return self.getTypedRuleContext(MPParser.ArraytypeContext,0)
def getRuleIndex(self):
return MPParser.RULE_idtype
def accept(self, visitor:ParseTreeVisitor):
if hasattr( visitor, "visitIdtype" ):
return visitor.visitIdtype(self)
else:
return visitor.visitChildren(self)
def idtype(self):
localctx = MPParser.IdtypeContext(self, self._ctx, self.state)
self.enterRule(localctx, 10, self.RULE_idtype)
try:
self.state = 107
self._errHandler.sync(self)
token = self._input.LA(1)
if token in [MPParser.BOOLEAN, MPParser.INTEGER, MPParser.REAL, MPParser.STRING]:
self.enterOuterAlt(localctx, 1)
self.state = 105
self.primtype()
pass
elif token in [MPParser.ARRAY]:
self.enterOuterAlt(localctx, 2)
self.state = 106
self.arraytype()
pass
else:
raise NoViableAltException(self)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class PrimtypeContext(ParserRuleContext):
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def BOOLEAN(self):
return self.getToken(MPParser.BOOLEAN, 0)
def INTEGER(self):
return self.getToken(MPParser.INTEGER, 0)
def REAL(self):
return self.getToken(MPParser.REAL, 0)
def STRING(self):
return self.getToken(MPParser.STRING, 0)
def getRuleIndex(self):
return MPParser.RULE_primtype
def accept(self, visitor:ParseTreeVisitor):
if hasattr( visitor, "visitPrimtype" ):
return visitor.visitPrimtype(self)
else:
return visitor.visitChildren(self)
def primtype(self):
localctx = MPParser.PrimtypeContext(self, self._ctx, self.state)
self.enterRule(localctx, 12, self.RULE_primtype)
self._la = 0 # Token type
try:
self.enterOuterAlt(localctx, 1)
self.state = 109
_la = self._input.LA(1)
if not((((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << MPParser.BOOLEAN) | (1 << MPParser.INTEGER) | (1 << MPParser.REAL) | (1 << MPParser.STRING))) != 0)):
self._errHandler.recoverInline(self)
else:
self._errHandler.reportMatch(self)
self.consume()
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class ArraytypeContext(ParserRuleContext):
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def ARRAY(self):
return self.getToken(MPParser.ARRAY, 0)
def LB(self):
return self.getToken(MPParser.LB, 0)
def signedInt(self, i:int=None):
if i is None:
return self.getTypedRuleContexts(MPParser.SignedIntContext)
else:
return self.getTypedRuleContext(MPParser.SignedIntContext,i)
def DOTDOT(self):
return self.getToken(MPParser.DOTDOT, 0)
def RB(self):
return self.getToken(MPParser.RB, 0)
def OF(self):
return self.getToken(MPParser.OF, 0)
def primtype(self):
return self.getTypedRuleContext(MPParser.PrimtypeContext,0)
def getRuleIndex(self):
return MPParser.RULE_arraytype
def accept(self, visitor:ParseTreeVisitor):
if hasattr( visitor, "visitArraytype" ):
return visitor.visitArraytype(self)
else:
return visitor.visitChildren(self)
def arraytype(self):
localctx = MPParser.ArraytypeContext(self, self._ctx, self.state)
self.enterRule(localctx, 14, self.RULE_arraytype)
try:
self.enterOuterAlt(localctx, 1)
self.state = 111
self.match(MPParser.ARRAY)
self.state = 112
self.match(MPParser.LB)
self.state = 113
self.signedInt()
self.state = 114
self.match(MPParser.DOTDOT)
self.state = 115
self.signedInt()
self.state = 116
self.match(MPParser.RB)
self.state = 117
self.match(MPParser.OF)
self.state = 118
self.primtype()
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class SignedIntContext(ParserRuleContext):
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def INTLIT(self):
return self.getToken(MPParser.INTLIT, 0)
def SUB(self):
return self.getToken(MPParser.SUB, 0)
def getRuleIndex(self):
return MPParser.RULE_signedInt
def accept(self, visitor:ParseTreeVisitor):
if hasattr( visitor, "visitSignedInt" ):
return visitor.visitSignedInt(self)
else:
return visitor.visitChildren(self)
def signedInt(self):
localctx = MPParser.SignedIntContext(self, self._ctx, self.state)
self.enterRule(localctx, 16, self.RULE_signedInt)
self._la = 0 # Token type
try:
self.enterOuterAlt(localctx, 1)
self.state = 121
self._errHandler.sync(self)
_la = self._input.LA(1)
if _la==MPParser.SUB:
self.state = 120
self.match(MPParser.SUB)
self.state = 123
self.match(MPParser.INTLIT)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class FuncdeclContext(ParserRuleContext):
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def FUNCTION(self):
return self.getToken(MPParser.FUNCTION, 0)
def ID(self):
return self.getToken(MPParser.ID, 0)
def LP(self):
return self.getToken(MPParser.LP, 0)
def RP(self):
return self.getToken(MPParser.RP, 0)
def COLON(self):
return self.getToken(MPParser.COLON, 0)
def idtype(self):
return self.getTypedRuleContext(MPParser.IdtypeContext,0)
def SEMI(self):
return self.getToken(MPParser.SEMI, 0)
def body(self):
return self.getTypedRuleContext(MPParser.BodyContext,0)
def plist(self):
return self.getTypedRuleContext(MPParser.PlistContext,0)
def vardecl(self):
return self.getTypedRuleContext(MPParser.VardeclContext,0)
def getRuleIndex(self):
return MPParser.RULE_funcdecl
def accept(self, visitor:ParseTreeVisitor):
if hasattr( visitor, "visitFuncdecl" ):
return visitor.visitFuncdecl(self)
else:
return visitor.visitChildren(self)
def funcdecl(self):
localctx = MPParser.FuncdeclContext(self, self._ctx, self.state)
self.enterRule(localctx, 18, self.RULE_funcdecl)
self._la = 0 # Token type
try:
self.enterOuterAlt(localctx, 1)
self.state = 125
self.match(MPParser.FUNCTION)
self.state = 126
self.match(MPParser.ID)
self.state = 127
self.match(MPParser.LP)
self.state = 129
self._errHandler.sync(self)
_la = self._input.LA(1)
if _la==MPParser.ID:
self.state = 128
self.plist()
self.state = 131
self.match(MPParser.RP)
self.state = 132
self.match(MPParser.COLON)
self.state = 133
self.idtype()
self.state = 134
self.match(MPParser.SEMI)
self.state = 136
self._errHandler.sync(self)
_la = self._input.LA(1)
if _la==MPParser.VAR:
self.state = 135
self.vardecl()
self.state = 138
self.body()
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class PlistContext(ParserRuleContext):
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def pgroup(self, i:int=None):
if i is None:
return self.getTypedRuleContexts(MPParser.PgroupContext)
else:
return self.getTypedRuleContext(MPParser.PgroupContext,i)
def SEMI(self, i:int=None):
if i is None:
return self.getTokens(MPParser.SEMI)
else:
return self.getToken(MPParser.SEMI, i)
def getRuleIndex(self):
return MPParser.RULE_plist
def accept(self, visitor:ParseTreeVisitor):
if hasattr( visitor, "visitPlist" ):
return visitor.visitPlist(self)
else:
return visitor.visitChildren(self)
def plist(self):
localctx = MPParser.PlistContext(self, self._ctx, self.state)
self.enterRule(localctx, 20, self.RULE_plist)
self._la = 0 # Token type
try:
self.enterOuterAlt(localctx, 1)
self.state = 140
self.pgroup()
self.state = 145
self._errHandler.sync(self)
_la = self._input.LA(1)
while _la==MPParser.SEMI:
self.state = 141
self.match(MPParser.SEMI)
self.state = 142
self.pgroup()
self.state = 147
self._errHandler.sync(self)
_la = self._input.LA(1)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class PgroupContext(ParserRuleContext):
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def idlist(self):
return self.getTypedRuleContext(MPParser.IdlistContext,0)
def COLON(self):
return self.getToken(MPParser.COLON, 0)
def idtype(self):
return self.getTypedRuleContext(MPParser.IdtypeContext,0)
def getRuleIndex(self):
return MPParser.RULE_pgroup
def accept(self, visitor:ParseTreeVisitor):
if hasattr( visitor, "visitPgroup" ):
return visitor.visitPgroup(self)
else:
return visitor.visitChildren(self)
def pgroup(self):
localctx = MPParser.PgroupContext(self, self._ctx, self.state)
self.enterRule(localctx, 22, self.RULE_pgroup)
try:
self.enterOuterAlt(localctx, 1)
self.state = 148
self.idlist()
self.state = 149
self.match(MPParser.COLON)
self.state = 150
self.idtype()
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class ProcdeclContext(ParserRuleContext):
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def PROCEDURE(self):
return self.getToken(MPParser.PROCEDURE, 0)
def ID(self):
return self.getToken(MPParser.ID, 0)
def LP(self):
return self.getToken(MPParser.LP, 0)
def RP(self):
return self.getToken(MPParser.RP, 0)
def SEMI(self):
return self.getToken(MPParser.SEMI, 0)
def body(self):
return self.getTypedRuleContext(MPParser.BodyContext,0)
def plist(self):
return self.getTypedRuleContext(MPParser.PlistContext,0)
def vardecl(self):
return self.getTypedRuleContext(MPParser.VardeclContext,0)
def getRuleIndex(self):
return MPParser.RULE_procdecl
def accept(self, visitor:ParseTreeVisitor):
if hasattr( visitor, "visitProcdecl" ):
return visitor.visitProcdecl(self)
else:
return visitor.visitChildren(self)
def procdecl(self):
localctx = MPParser.ProcdeclContext(self, self._ctx, self.state)
self.enterRule(localctx, 24, self.RULE_procdecl)
self._la = 0 # Token type
try:
self.enterOuterAlt(localctx, 1)
self.state = 152
self.match(MPParser.PROCEDURE)
self.state = 153
self.match(MPParser.ID)
self.state = 154
self.match(MPParser.LP)
self.state = 156
self._errHandler.sync(self)
_la = self._input.LA(1)
if _la==MPParser.ID:
self.state = 155
self.plist()
self.state = 158
self.match(MPParser.RP)
self.state = 159
self.match(MPParser.SEMI)
self.state = 161
self._errHandler.sync(self)
_la = self._input.LA(1)
if _la==MPParser.VAR:
self.state = 160
self.vardecl()
self.state = 163
self.body()
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class BodyContext(ParserRuleContext):
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def BEGIN(self):
return self.getToken(MPParser.BEGIN, 0)
def END(self):
return self.getToken(MPParser.END, 0)
def stmt(self, i:int=None):
if i is None:
return self.getTypedRuleContexts(MPParser.StmtContext)
else:
return self.getTypedRuleContext(MPParser.StmtContext,i)
def getRuleIndex(self):
return MPParser.RULE_body
def accept(self, visitor:ParseTreeVisitor):
if hasattr( visitor, "visitBody" ):
return visitor.visitBody(self)
else:
return visitor.visitChildren(self)
def body(self):
localctx = MPParser.BodyContext(self, self._ctx, self.state)
self.enterRule(localctx, 26, self.RULE_body)
self._la = 0 # Token type
try:
self.enterOuterAlt(localctx, 1)
self.state = 165
self.match(MPParser.BEGIN)
self.state = 169
self._errHandler.sync(self)
_la = self._input.LA(1)
while (((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << MPParser.BEGIN) | (1 << MPParser.BREAK) | (1 << MPParser.CONTINUE) | (1 << MPParser.FALSE) | (1 << MPParser.FOR) | (1 << MPParser.IF) | (1 << MPParser.RETURN) | (1 << MPParser.TRUE) | (1 << MPParser.WHILE) | (1 << MPParser.WITH) | (1 << MPParser.LP) | (1 << MPParser.ID) | (1 << MPParser.INTLIT) | (1 << MPParser.FLOATLIT) | (1 << MPParser.STRINGLIT))) != 0):
self.state = 166
self.stmt()
self.state = 171
self._errHandler.sync(self)
_la = self._input.LA(1)
self.state = 172
self.match(MPParser.END)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class StmtContext(ParserRuleContext):
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def assign(self):
return self.getTypedRuleContext(MPParser.AssignContext,0)
def ifstmt(self):
return self.getTypedRuleContext(MPParser.IfstmtContext,0)
def whilestmt(self):
return self.getTypedRuleContext(MPParser.WhilestmtContext,0)
def forstmt(self):
return self.getTypedRuleContext(MPParser.ForstmtContext,0)
def breakstmt(self):
return self.getTypedRuleContext(MPParser.BreakstmtContext,0)
def continuestmt(self):
return self.getTypedRuleContext(MPParser.ContinuestmtContext,0)
def returnstmt(self):
return self.getTypedRuleContext(MPParser.ReturnstmtContext,0)
def withstmt(self):
return self.getTypedRuleContext(MPParser.WithstmtContext,0)
def callstmt(self):
return self.getTypedRuleContext(MPParser.CallstmtContext,0)
def cpstmt(self):
return self.getTypedRuleContext(MPParser.CpstmtContext,0)
def getRuleIndex(self):
return MPParser.RULE_stmt
def accept(self, visitor:ParseTreeVisitor):
if hasattr( visitor, "visitStmt" ):
return visitor.visitStmt(self)
else:
return visitor.visitChildren(self)
def stmt(self):
localctx = MPParser.StmtContext(self, self._ctx, self.state)
self.enterRule(localctx, 28, self.RULE_stmt)
try:
self.state = 184
self._errHandler.sync(self)
la_ = self._interp.adaptivePredict(self._input,12,self._ctx)
if la_ == 1:
self.enterOuterAlt(localctx, 1)
self.state = 174
self.assign()
pass
elif la_ == 2:
self.enterOuterAlt(localctx, 2)
self.state = 175
self.ifstmt()
pass
elif la_ == 3:
self.enterOuterAlt(localctx, 3)
self.state = 176
self.whilestmt()
pass
elif la_ == 4:
self.enterOuterAlt(localctx, 4)
self.state = 177
self.forstmt()
pass
elif la_ == 5:
self.enterOuterAlt(localctx, 5)
self.state = 178
self.breakstmt()
pass
elif la_ == 6:
self.enterOuterAlt(localctx, 6)
self.state = 179
self.continuestmt()
pass
elif la_ == 7:
self.enterOuterAlt(localctx, 7)
self.state = 180
self.returnstmt()
pass
elif la_ == 8:
self.enterOuterAlt(localctx, 8)
self.state = 181
self.withstmt()
pass
elif la_ == 9:
self.enterOuterAlt(localctx, 9)
self.state = 182
self.callstmt()
pass
elif la_ == 10:
self.enterOuterAlt(localctx, 10)
self.state = 183
self.cpstmt()
pass
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class CpstmtContext(ParserRuleContext):
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def body(self):
return self.getTypedRuleContext(MPParser.BodyContext,0)
def getRuleIndex(self):
return MPParser.RULE_cpstmt
def accept(self, visitor:ParseTreeVisitor):
if hasattr( visitor, "visitCpstmt" ):
return visitor.visitCpstmt(self)
else:
return visitor.visitChildren(self)
def cpstmt(self):
localctx = MPParser.CpstmtContext(self, self._ctx, self.state)
self.enterRule(localctx, 30, self.RULE_cpstmt)
try:
self.enterOuterAlt(localctx, 1)
self.state = 186
self.body()
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class AssignContext(ParserRuleContext):
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def expr(self):
return self.getTypedRuleContext(MPParser.ExprContext,0)
def SEMI(self):
return self.getToken(MPParser.SEMI, 0)
def variable(self, i:int=None):
if i is None:
return self.getTypedRuleContexts(MPParser.VariableContext)
else:
return self.getTypedRuleContext(MPParser.VariableContext,i)
def ASSIGN(self, i:int=None):
if i is None:
return self.getTokens(MPParser.ASSIGN)
else:
return self.getToken(MPParser.ASSIGN, i)
def getRuleIndex(self):
return MPParser.RULE_assign
def accept(self, visitor:ParseTreeVisitor):
if hasattr( visitor, "visitAssign" ):
return visitor.visitAssign(self)
else:
return visitor.visitChildren(self)
def assign(self):
localctx = MPParser.AssignContext(self, self._ctx, self.state)
self.enterRule(localctx, 32, self.RULE_assign)
try:
self.enterOuterAlt(localctx, 1)
self.state = 191
self._errHandler.sync(self)
_alt = 1
while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:
if _alt == 1:
self.state = 188
self.variable()
self.state = 189
self.match(MPParser.ASSIGN)
else:
raise NoViableAltException(self)
self.state = 193
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input,13,self._ctx)
self.state = 195
self.expr(0)
self.state = 196
self.match(MPParser.SEMI)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class VariableContext(ParserRuleContext):
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def ID(self):
return self.getToken(MPParser.ID, 0)
def arraycell(self):
return self.getTypedRuleContext(MPParser.ArraycellContext,0)
def getRuleIndex(self):
return MPParser.RULE_variable
def accept(self, visitor:ParseTreeVisitor):
if hasattr( visitor, "visitVariable" ):
return visitor.visitVariable(self)
else:
return visitor.visitChildren(self)
def variable(self):
localctx = MPParser.VariableContext(self, self._ctx, self.state)
self.enterRule(localctx, 34, self.RULE_variable)
try:
self.state = 200
self._errHandler.sync(self)
la_ = self._interp.adaptivePredict(self._input,14,self._ctx)
if la_ == 1:
self.enterOuterAlt(localctx, 1)
self.state = 198
self.match(MPParser.ID)
pass
elif la_ == 2:
self.enterOuterAlt(localctx, 2)
self.state = 199
self.arraycell()
pass
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class IfstmtContext(ParserRuleContext):
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def IF(self):
return self.getToken(MPParser.IF, 0)
def expr(self):
return self.getTypedRuleContext(MPParser.ExprContext,0)
def THEN(self):
return self.getToken(MPParser.THEN, 0)
def stmt(self, i:int=None):
if i is None:
return self.getTypedRuleContexts(MPParser.StmtContext)
else:
return self.getTypedRuleContext(MPParser.StmtContext,i)
def ELSE(self):
return self.getToken(MPParser.ELSE, 0)
def getRuleIndex(self):
return MPParser.RULE_ifstmt
def accept(self, visitor:ParseTreeVisitor):
if hasattr( visitor, "visitIfstmt" ):
return visitor.visitIfstmt(self)
else:
return visitor.visitChildren(self)
def ifstmt(self):
localctx = MPParser.IfstmtContext(self, self._ctx, self.state)
self.enterRule(localctx, 36, self.RULE_ifstmt)
try:
self.enterOuterAlt(localctx, 1)
self.state = 202
self.match(MPParser.IF)
self.state = 203
self.expr(0)
self.state = 204
self.match(MPParser.THEN)
self.state = 205
self.stmt()
self.state = 208
self._errHandler.sync(self)
la_ = self._interp.adaptivePredict(self._input,15,self._ctx)
if la_ == 1:
self.state = 206
self.match(MPParser.ELSE)
self.state = 207
self.stmt()
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class WhilestmtContext(ParserRuleContext):
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def WHILE(self):
return self.getToken(MPParser.WHILE, 0)
def expr(self):
return self.getTypedRuleContext(MPParser.ExprContext,0)
def DO(self):
return self.getToken(MPParser.DO, 0)
def stmt(self):
return self.getTypedRuleContext(MPParser.StmtContext,0)
def getRuleIndex(self):
return MPParser.RULE_whilestmt
def accept(self, visitor:ParseTreeVisitor):
if hasattr( visitor, "visitWhilestmt" ):
return visitor.visitWhilestmt(self)
else:
return visitor.visitChildren(self)
def whilestmt(self):
localctx = MPParser.WhilestmtContext(self, self._ctx, self.state)
self.enterRule(localctx, 38, self.RULE_whilestmt)
try:
self.enterOuterAlt(localctx, 1)
self.state = 210
self.match(MPParser.WHILE)
self.state = 211
self.expr(0)
self.state = 212
self.match(MPParser.DO)
self.state = 213
self.stmt()
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class ForstmtContext(ParserRuleContext):
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def FOR(self):
return self.getToken(MPParser.FOR, 0)
def ID(self):
return self.getToken(MPParser.ID, 0)
def ASSIGN(self):
return self.getToken(MPParser.ASSIGN, 0)
def expr(self, i:int=None):
if i is None:
return self.getTypedRuleContexts(MPParser.ExprContext)
else:
return self.getTypedRuleContext(MPParser.ExprContext,i)
def DO(self):
return self.getToken(MPParser.DO, 0)
def stmt(self):
return self.getTypedRuleContext(MPParser.StmtContext,0)
def TO(self):
return self.getToken(MPParser.TO, 0)
def DOWNTO(self):
return self.getToken(MPParser.DOWNTO, 0)
def getRuleIndex(self):
return MPParser.RULE_forstmt
def accept(self, visitor:ParseTreeVisitor):
if hasattr( visitor, "visitForstmt" ):
return visitor.visitForstmt(self)
else:
return visitor.visitChildren(self)
def forstmt(self):
localctx = MPParser.ForstmtContext(self, self._ctx, self.state)
self.enterRule(localctx, 40, self.RULE_forstmt)
self._la = 0 # Token type
try:
self.enterOuterAlt(localctx, 1)
self.state = 215
self.match(MPParser.FOR)
self.state = 216
self.match(MPParser.ID)
self.state = 217
self.match(MPParser.ASSIGN)
self.state = 218
self.expr(0)
self.state = 219
_la = self._input.LA(1)
if not(_la==MPParser.DOWNTO or _la==MPParser.TO):
self._errHandler.recoverInline(self)
else:
self._errHandler.reportMatch(self)
self.consume()
self.state = 220
self.expr(0)
self.state = 221
self.match(MPParser.DO)
self.state = 222
self.stmt()
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class BreakstmtContext(ParserRuleContext):
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def BREAK(self):
return self.getToken(MPParser.BREAK, 0)
def SEMI(self):
return self.getToken(MPParser.SEMI, 0)
def getRuleIndex(self):
return MPParser.RULE_breakstmt
def accept(self, visitor:ParseTreeVisitor):
if hasattr( visitor, "visitBreakstmt" ):
return visitor.visitBreakstmt(self)
else:
return visitor.visitChildren(self)
def breakstmt(self):
localctx = MPParser.BreakstmtContext(self, self._ctx, self.state)
self.enterRule(localctx, 42, self.RULE_breakstmt)
try:
self.enterOuterAlt(localctx, 1)
self.state = 224
self.match(MPParser.BREAK)
self.state = 225
self.match(MPParser.SEMI)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class ContinuestmtContext(ParserRuleContext):
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def CONTINUE(self):
return self.getToken(MPParser.CONTINUE, 0)
def SEMI(self):
return self.getToken(MPParser.SEMI, 0)
def getRuleIndex(self):
return MPParser.RULE_continuestmt
def accept(self, visitor:ParseTreeVisitor):
if hasattr( visitor, "visitContinuestmt" ):
return visitor.visitContinuestmt(self)
else:
return visitor.visitChildren(self)
def continuestmt(self):
localctx = MPParser.ContinuestmtContext(self, self._ctx, self.state)
self.enterRule(localctx, 44, self.RULE_continuestmt)
try:
self.enterOuterAlt(localctx, 1)
self.state = 227
self.match(MPParser.CONTINUE)
self.state = 228
self.match(MPParser.SEMI)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class ReturnstmtContext(ParserRuleContext):
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def RETURN(self):
return self.getToken(MPParser.RETURN, 0)
def SEMI(self):
return self.getToken(MPParser.SEMI, 0)
def expr(self):
return self.getTypedRuleContext(MPParser.ExprContext,0)
def getRuleIndex(self):
return MPParser.RULE_returnstmt
def accept(self, visitor:ParseTreeVisitor):
if hasattr( visitor, "visitReturnstmt" ):
return visitor.visitReturnstmt(self)
else:
return visitor.visitChildren(self)
def returnstmt(self):
localctx = MPParser.ReturnstmtContext(self, self._ctx, self.state)
self.enterRule(localctx, 46, self.RULE_returnstmt)
self._la = 0 # Token type
try:
self.enterOuterAlt(localctx, 1)
self.state = 230
self.match(MPParser.RETURN)
self.state = 232
self._errHandler.sync(self)
_la = self._input.LA(1)
if (((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << MPParser.FALSE) | (1 << MPParser.NOT) | (1 << MPParser.TRUE) | (1 << MPParser.SUB) | (1 << MPParser.LP) | (1 << MPParser.ID) | (1 << MPParser.INTLIT) | (1 << MPParser.FLOATLIT) | (1 << MPParser.STRINGLIT))) != 0):
self.state = 231
self.expr(0)
self.state = 234
self.match(MPParser.SEMI)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class WithstmtContext(ParserRuleContext):
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def WITH(self):
return self.getToken(MPParser.WITH, 0)
def DO(self):
return self.getToken(MPParser.DO, 0)
def stmt(self):
return self.getTypedRuleContext(MPParser.StmtContext,0)
def vargroup(self, i:int=None):
if i is None:
return self.getTypedRuleContexts(MPParser.VargroupContext)
else:
return self.getTypedRuleContext(MPParser.VargroupContext,i)
def getRuleIndex(self):
return MPParser.RULE_withstmt
def accept(self, visitor:ParseTreeVisitor):
if hasattr( visitor, "visitWithstmt" ):
return visitor.visitWithstmt(self)
else:
return visitor.visitChildren(self)
def withstmt(self):
localctx = MPParser.WithstmtContext(self, self._ctx, self.state)
self.enterRule(localctx, 48, self.RULE_withstmt)
self._la = 0 # Token type
try:
self.enterOuterAlt(localctx, 1)
self.state = 236
self.match(MPParser.WITH)
self.state = 238
self._errHandler.sync(self)
_la = self._input.LA(1)
while True:
self.state = 237
self.vargroup()
self.state = 240
self._errHandler.sync(self)
_la = self._input.LA(1)
if not (_la==MPParser.ID):
break
self.state = 242
self.match(MPParser.DO)
self.state = 243
self.stmt()
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class CallstmtContext(ParserRuleContext):
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def ID(self):
return self.getToken(MPParser.ID, 0)
def LP(self):
return self.getToken(MPParser.LP, 0)
def RP(self):
return self.getToken(MPParser.RP, 0)
def SEMI(self):
return self.getToken(MPParser.SEMI, 0)
def expr(self, i:int=None):
if i is None:
return self.getTypedRuleContexts(MPParser.ExprContext)
else:
return self.getTypedRuleContext(MPParser.ExprContext,i)
def COMMA(self, i:int=None):
if i is None:
return self.getTokens(MPParser.COMMA)
else:
return self.getToken(MPParser.COMMA, i)
def getRuleIndex(self):
return MPParser.RULE_callstmt
def accept(self, visitor:ParseTreeVisitor):
if hasattr( visitor, "visitCallstmt" ):
return visitor.visitCallstmt(self)
else:
return visitor.visitChildren(self)
def callstmt(self):
localctx = MPParser.CallstmtContext(self, self._ctx, self.state)
self.enterRule(localctx, 50, self.RULE_callstmt)
self._la = 0 # Token type
try:
self.enterOuterAlt(localctx, 1)
self.state = 245
self.match(MPParser.ID)
self.state = 246
self.match(MPParser.LP)
self.state = 255
self._errHandler.sync(self)
_la = self._input.LA(1)
if (((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << MPParser.FALSE) | (1 << MPParser.NOT) | (1 << MPParser.TRUE) | (1 << MPParser.SUB) | (1 << MPParser.LP) | (1 << MPParser.ID) | (1 << MPParser.INTLIT) | (1 << MPParser.FLOATLIT) | (1 << MPParser.STRINGLIT))) != 0):
self.state = 247
self.expr(0)
self.state = 252
self._errHandler.sync(self)
_la = self._input.LA(1)
while _la==MPParser.COMMA:
self.state = 248
self.match(MPParser.COMMA)
self.state = 249
self.expr(0)
self.state = 254
self._errHandler.sync(self)
_la = self._input.LA(1)
self.state = 257
self.match(MPParser.RP)
self.state = 258
self.match(MPParser.SEMI)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class ExprContext(ParserRuleContext):
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def exp1(self):
return self.getTypedRuleContext(MPParser.Exp1Context,0)
def expr(self):
return self.getTypedRuleContext(MPParser.ExprContext,0)
def AND(self):
return self.getToken(MPParser.AND, 0)
def THEN(self):
return self.getToken(MPParser.THEN, 0)
def OR(self):
return self.getToken(MPParser.OR, 0)
def ELSE(self):
return self.getToken(MPParser.ELSE, 0)
def getRuleIndex(self):
return MPParser.RULE_expr
def accept(self, visitor:ParseTreeVisitor):
if hasattr( visitor, "visitExpr" ):
return visitor.visitExpr(self)
else:
return visitor.visitChildren(self)
def expr(self, _p:int=0):
_parentctx = self._ctx
_parentState = self.state
localctx = MPParser.ExprContext(self, self._ctx, _parentState)
_prevctx = localctx
_startState = 52
self.enterRecursionRule(localctx, 52, self.RULE_expr, _p)
try:
self.enterOuterAlt(localctx, 1)
self.state = 261
self.exp1()
self._ctx.stop = self._input.LT(-1)
self.state = 273
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input,21,self._ctx)
while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:
if _alt==1:
if self._parseListeners is not None:
self.triggerExitRuleEvent()
_prevctx = localctx
self.state = 271
self._errHandler.sync(self)
la_ = self._interp.adaptivePredict(self._input,20,self._ctx)
if la_ == 1:
localctx = MPParser.ExprContext(self, _parentctx, _parentState)
self.pushNewRecursionContext(localctx, _startState, self.RULE_expr)
self.state = 263
if not self.precpred(self._ctx, 3):
from antlr4.error.Errors import FailedPredicateException
raise FailedPredicateException(self, "self.precpred(self._ctx, 3)")
self.state = 264
self.match(MPParser.AND)
self.state = 265
self.match(MPParser.THEN)
self.state = 266
self.exp1()
pass
elif la_ == 2:
localctx = MPParser.ExprContext(self, _parentctx, _parentState)
self.pushNewRecursionContext(localctx, _startState, self.RULE_expr)
self.state = 267
if not self.precpred(self._ctx, 2):
from antlr4.error.Errors import FailedPredicateException
raise FailedPredicateException(self, "self.precpred(self._ctx, 2)")
self.state = 268
self.match(MPParser.OR)
self.state = 269
self.match(MPParser.ELSE)
self.state = 270
self.exp1()
pass
self.state = 275
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input,21,self._ctx)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.unrollRecursionContexts(_parentctx)
return localctx
class Exp1Context(ParserRuleContext):
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def exp2(self, i:int=None):
if i is None:
return self.getTypedRuleContexts(MPParser.Exp2Context)
else:
return self.getTypedRuleContext(MPParser.Exp2Context,i)
def EQUAL(self):
return self.getToken(MPParser.EQUAL, 0)
def NOTEQUAL(self):
return self.getToken(MPParser.NOTEQUAL, 0)
def LT(self):
return self.getToken(MPParser.LT, 0)
def LE(self):
return self.getToken(MPParser.LE, 0)
def GT(self):
return self.getToken(MPParser.GT, 0)
def GE(self):
return self.getToken(MPParser.GE, 0)
def getRuleIndex(self):
return MPParser.RULE_exp1
def accept(self, visitor:ParseTreeVisitor):
if hasattr( visitor, "visitExp1" ):
return visitor.visitExp1(self)
else:
return visitor.visitChildren(self)
def exp1(self):
localctx = MPParser.Exp1Context(self, self._ctx, self.state)
self.enterRule(localctx, 54, self.RULE_exp1)
try:
self.state = 301
self._errHandler.sync(self)
la_ = self._interp.adaptivePredict(self._input,22,self._ctx)
if la_ == 1:
self.enterOuterAlt(localctx, 1)
self.state = 276
self.exp2(0)
self.state = 277
self.match(MPParser.EQUAL)
self.state = 278
self.exp2(0)
pass
elif la_ == 2:
self.enterOuterAlt(localctx, 2)
self.state = 280
self.exp2(0)
self.state = 281
self.match(MPParser.NOTEQUAL)
self.state = 282
self.exp2(0)
pass
elif la_ == 3:
self.enterOuterAlt(localctx, 3)
self.state = 284
self.exp2(0)
self.state = 285
self.match(MPParser.LT)
self.state = 286
self.exp2(0)
pass
elif la_ == 4:
self.enterOuterAlt(localctx, 4)
self.state = 288
self.exp2(0)
self.state = 289
self.match(MPParser.LE)
self.state = 290
self.exp2(0)
pass
elif la_ == 5:
self.enterOuterAlt(localctx, 5)
self.state = 292
self.exp2(0)
self.state = 293
self.match(MPParser.GT)
self.state = 294
self.exp2(0)
pass
elif la_ == 6:
self.enterOuterAlt(localctx, 6)
self.state = 296
self.exp2(0)
self.state = 297
self.match(MPParser.GE)
self.state = 298
self.exp2(0)
pass
elif la_ == 7:
self.enterOuterAlt(localctx, 7)
self.state = 300
self.exp2(0)
pass
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class Exp2Context(ParserRuleContext):
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def exp3(self):
return self.getTypedRuleContext(MPParser.Exp3Context,0)
def exp2(self):
return self.getTypedRuleContext(MPParser.Exp2Context,0)
def ADD(self):
return self.getToken(MPParser.ADD, 0)
def SUB(self):
return self.getToken(MPParser.SUB, 0)
def OR(self):
return self.getToken(MPParser.OR, 0)
def getRuleIndex(self):
return MPParser.RULE_exp2
def accept(self, visitor:ParseTreeVisitor):
if hasattr( visitor, "visitExp2" ):
return visitor.visitExp2(self)
else:
return visitor.visitChildren(self)
def exp2(self, _p:int=0):
_parentctx = self._ctx
_parentState = self.state
localctx = MPParser.Exp2Context(self, self._ctx, _parentState)
_prevctx = localctx
_startState = 56
self.enterRecursionRule(localctx, 56, self.RULE_exp2, _p)
try:
self.enterOuterAlt(localctx, 1)
self.state = 304
self.exp3(0)
self._ctx.stop = self._input.LT(-1)
self.state = 317
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input,24,self._ctx)
while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:
if _alt==1:
if self._parseListeners is not None:
self.triggerExitRuleEvent()
_prevctx = localctx
self.state = 315
self._errHandler.sync(self)
la_ = self._interp.adaptivePredict(self._input,23,self._ctx)
if la_ == 1:
localctx = MPParser.Exp2Context(self, _parentctx, _parentState)
self.pushNewRecursionContext(localctx, _startState, self.RULE_exp2)
self.state = 306
if not self.precpred(self._ctx, 4):
from antlr4.error.Errors import FailedPredicateException
raise FailedPredicateException(self, "self.precpred(self._ctx, 4)")
self.state = 307
self.match(MPParser.ADD)
self.state = 308
self.exp3(0)
pass
elif la_ == 2:
localctx = MPParser.Exp2Context(self, _parentctx, _parentState)
self.pushNewRecursionContext(localctx, _startState, self.RULE_exp2)
self.state = 309
if not self.precpred(self._ctx, 3):
from antlr4.error.Errors import FailedPredicateException
raise FailedPredicateException(self, "self.precpred(self._ctx, 3)")
self.state = 310
self.match(MPParser.SUB)
self.state = 311
self.exp3(0)
pass
elif la_ == 3:
localctx = MPParser.Exp2Context(self, _parentctx, _parentState)
self.pushNewRecursionContext(localctx, _startState, self.RULE_exp2)
self.state = 312
if not self.precpred(self._ctx, 2):
from antlr4.error.Errors import FailedPredicateException
raise FailedPredicateException(self, "self.precpred(self._ctx, 2)")
self.state = 313
self.match(MPParser.OR)
self.state = 314
self.exp3(0)
pass
self.state = 319
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input,24,self._ctx)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.unrollRecursionContexts(_parentctx)
return localctx
class Exp3Context(ParserRuleContext):
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def exp4(self):
return self.getTypedRuleContext(MPParser.Exp4Context,0)
def exp3(self):
return self.getTypedRuleContext(MPParser.Exp3Context,0)
def SLASH(self):
return self.getToken(MPParser.SLASH, 0)
def MUL(self):
return self.getToken(MPParser.MUL, 0)
def DIV(self):
return self.getToken(MPParser.DIV, 0)
def MOD(self):
return self.getToken(MPParser.MOD, 0)
def AND(self):
return self.getToken(MPParser.AND, 0)
def getRuleIndex(self):
return MPParser.RULE_exp3
def accept(self, visitor:ParseTreeVisitor):
if hasattr( visitor, "visitExp3" ):
return visitor.visitExp3(self)
else:
return visitor.visitChildren(self)
def exp3(self, _p:int=0):
_parentctx = self._ctx
_parentState = self.state
localctx = MPParser.Exp3Context(self, self._ctx, _parentState)
_prevctx = localctx
_startState = 58
self.enterRecursionRule(localctx, 58, self.RULE_exp3, _p)
try:
self.enterOuterAlt(localctx, 1)
self.state = 321
self.exp4()
self._ctx.stop = self._input.LT(-1)
self.state = 340
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input,26,self._ctx)
while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:
if _alt==1:
if self._parseListeners is not None:
self.triggerExitRuleEvent()
_prevctx = localctx
self.state = 338
self._errHandler.sync(self)
la_ = self._interp.adaptivePredict(self._input,25,self._ctx)
if la_ == 1:
localctx = MPParser.Exp3Context(self, _parentctx, _parentState)
self.pushNewRecursionContext(localctx, _startState, self.RULE_exp3)
self.state = 323
if not self.precpred(self._ctx, 6):
from antlr4.error.Errors import FailedPredicateException
raise FailedPredicateException(self, "self.precpred(self._ctx, 6)")
self.state = 324
self.match(MPParser.SLASH)
self.state = 325
self.exp4()
pass
elif la_ == 2:
localctx = MPParser.Exp3Context(self, _parentctx, _parentState)
self.pushNewRecursionContext(localctx, _startState, self.RULE_exp3)
self.state = 326
if not self.precpred(self._ctx, 5):
from antlr4.error.Errors import FailedPredicateException
raise FailedPredicateException(self, "self.precpred(self._ctx, 5)")
self.state = 327
self.match(MPParser.MUL)
self.state = 328
self.exp4()
pass
elif la_ == 3:
localctx = MPParser.Exp3Context(self, _parentctx, _parentState)
self.pushNewRecursionContext(localctx, _startState, self.RULE_exp3)
self.state = 329
if not self.precpred(self._ctx, 4):
from antlr4.error.Errors import FailedPredicateException
raise FailedPredicateException(self, "self.precpred(self._ctx, 4)")
self.state = 330
self.match(MPParser.DIV)
self.state = 331
self.exp4()
pass
elif la_ == 4:
localctx = MPParser.Exp3Context(self, _parentctx, _parentState)
self.pushNewRecursionContext(localctx, _startState, self.RULE_exp3)
self.state = 332
if not self.precpred(self._ctx, 3):
from antlr4.error.Errors import FailedPredicateException
raise FailedPredicateException(self, "self.precpred(self._ctx, 3)")
self.state = 333
self.match(MPParser.MOD)
self.state = 334
self.exp4()
pass
elif la_ == 5:
localctx = MPParser.Exp3Context(self, _parentctx, _parentState)
self.pushNewRecursionContext(localctx, _startState, self.RULE_exp3)
self.state = 335
if not self.precpred(self._ctx, 2):
from antlr4.error.Errors import FailedPredicateException
raise FailedPredicateException(self, "self.precpred(self._ctx, 2)")
self.state = 336
self.match(MPParser.AND)
self.state = 337
self.exp4()
pass
self.state = 342
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input,26,self._ctx)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.unrollRecursionContexts(_parentctx)
return localctx
class Exp4Context(ParserRuleContext):
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def SUB(self):
return self.getToken(MPParser.SUB, 0)
def exp4(self):
return self.getTypedRuleContext(MPParser.Exp4Context,0)
def NOT(self):
return self.getToken(MPParser.NOT, 0)
def exp5(self):
return self.getTypedRuleContext(MPParser.Exp5Context,0)
def getRuleIndex(self):
return MPParser.RULE_exp4
def accept(self, visitor:ParseTreeVisitor):
if hasattr( visitor, "visitExp4" ):
return visitor.visitExp4(self)
else:
return visitor.visitChildren(self)
def exp4(self):
localctx = MPParser.Exp4Context(self, self._ctx, self.state)
self.enterRule(localctx, 60, self.RULE_exp4)
try:
self.state = 348
self._errHandler.sync(self)
token = self._input.LA(1)
if token in [MPParser.SUB]:
self.enterOuterAlt(localctx, 1)
self.state = 343
self.match(MPParser.SUB)
self.state = 344
self.exp4()
pass
elif token in [MPParser.NOT]:
self.enterOuterAlt(localctx, 2)
self.state = 345
self.match(MPParser.NOT)
self.state = 346
self.exp4()
pass
elif token in [MPParser.FALSE, MPParser.TRUE, MPParser.LP, MPParser.ID, MPParser.INTLIT, MPParser.FLOATLIT, MPParser.STRINGLIT]:
self.enterOuterAlt(localctx, 3)
self.state = 347
self.exp5()
pass
else:
raise NoViableAltException(self)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class Exp5Context(ParserRuleContext):
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def exp6(self):
return self.getTypedRuleContext(MPParser.Exp6Context,0)
def LB(self):
return self.getToken(MPParser.LB, 0)
def expr(self):
return self.getTypedRuleContext(MPParser.ExprContext,0)
def RB(self):
return self.getToken(MPParser.RB, 0)
def getRuleIndex(self):
return MPParser.RULE_exp5
def accept(self, visitor:ParseTreeVisitor):
if hasattr( visitor, "visitExp5" ):
return visitor.visitExp5(self)
else:
return visitor.visitChildren(self)
def exp5(self):
localctx = MPParser.Exp5Context(self, self._ctx, self.state)
self.enterRule(localctx, 62, self.RULE_exp5)
try:
self.state = 356
self._errHandler.sync(self)
la_ = self._interp.adaptivePredict(self._input,28,self._ctx)
if la_ == 1:
self.enterOuterAlt(localctx, 1)
self.state = 350
self.exp6()
self.state = 351
self.match(MPParser.LB)
self.state = 352
self.expr(0)
self.state = 353
self.match(MPParser.RB)
pass
elif la_ == 2:
self.enterOuterAlt(localctx, 2)
self.state = 355
self.exp6()
pass
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class Exp6Context(ParserRuleContext):
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def LP(self):
return self.getToken(MPParser.LP, 0)
def expr(self):
return self.getTypedRuleContext(MPParser.ExprContext,0)
def RP(self):
return self.getToken(MPParser.RP, 0)
def op(self):
return self.getTypedRuleContext(MPParser.OpContext,0)
def getRuleIndex(self):
return MPParser.RULE_exp6
def accept(self, visitor:ParseTreeVisitor):
if hasattr( visitor, "visitExp6" ):
return visitor.visitExp6(self)
else:
return visitor.visitChildren(self)
def exp6(self):
localctx = MPParser.Exp6Context(self, self._ctx, self.state)
self.enterRule(localctx, 64, self.RULE_exp6)
try:
self.state = 363
self._errHandler.sync(self)
token = self._input.LA(1)
if token in [MPParser.LP]:
self.enterOuterAlt(localctx, 1)
self.state = 358
self.match(MPParser.LP)
self.state = 359
self.expr(0)
self.state = 360
self.match(MPParser.RP)
pass
elif token in [MPParser.FALSE, MPParser.TRUE, MPParser.ID, MPParser.INTLIT, MPParser.FLOATLIT, MPParser.STRINGLIT]:
self.enterOuterAlt(localctx, 2)
self.state = 362
self.op()
pass
else:
raise NoViableAltException(self)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class OpContext(ParserRuleContext):
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def ID(self):
return self.getToken(MPParser.ID, 0)
def INTLIT(self):
return self.getToken(MPParser.INTLIT, 0)
def FLOATLIT(self):
return self.getToken(MPParser.FLOATLIT, 0)
def STRINGLIT(self):
return self.getToken(MPParser.STRINGLIT, 0)
def boollit(self):
return self.getTypedRuleContext(MPParser.BoollitContext,0)
def funcall(self):
return self.getTypedRuleContext(MPParser.FuncallContext,0)
def getRuleIndex(self):
return MPParser.RULE_op
def accept(self, visitor:ParseTreeVisitor):
if hasattr( visitor, "visitOp" ):
return visitor.visitOp(self)
else:
return visitor.visitChildren(self)
def op(self):
localctx = MPParser.OpContext(self, self._ctx, self.state)
self.enterRule(localctx, 66, self.RULE_op)
try:
self.state = 371
self._errHandler.sync(self)
la_ = self._interp.adaptivePredict(self._input,30,self._ctx)
if la_ == 1:
self.enterOuterAlt(localctx, 1)
self.state = 365
self.match(MPParser.ID)
pass
elif la_ == 2:
self.enterOuterAlt(localctx, 2)
self.state = 366
self.match(MPParser.INTLIT)
pass
elif la_ == 3:
self.enterOuterAlt(localctx, 3)
self.state = 367
self.match(MPParser.FLOATLIT)
pass
elif la_ == 4:
self.enterOuterAlt(localctx, 4)
self.state = 368
self.match(MPParser.STRINGLIT)
pass
elif la_ == 5:
self.enterOuterAlt(localctx, 5)
self.state = 369
self.boollit()
pass
elif la_ == 6:
self.enterOuterAlt(localctx, 6)
self.state = 370
self.funcall()
pass
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class FuncallContext(ParserRuleContext):
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def ID(self):
return self.getToken(MPParser.ID, 0)
def LP(self):
return self.getToken(MPParser.LP, 0)
def RP(self):
return self.getToken(MPParser.RP, 0)
def expr(self, i:int=None):
if i is None:
return self.getTypedRuleContexts(MPParser.ExprContext)
else:
return self.getTypedRuleContext(MPParser.ExprContext,i)
def COMMA(self, i:int=None):
if i is None:
return self.getTokens(MPParser.COMMA)
else:
return self.getToken(MPParser.COMMA, i)
def getRuleIndex(self):
return MPParser.RULE_funcall
def accept(self, visitor:ParseTreeVisitor):
if hasattr( visitor, "visitFuncall" ):
return visitor.visitFuncall(self)
else:
return visitor.visitChildren(self)
def funcall(self):
localctx = MPParser.FuncallContext(self, self._ctx, self.state)
self.enterRule(localctx, 68, self.RULE_funcall)
self._la = 0 # Token type
try:
self.enterOuterAlt(localctx, 1)
self.state = 373
self.match(MPParser.ID)
self.state = 374
self.match(MPParser.LP)
self.state = 383
self._errHandler.sync(self)
_la = self._input.LA(1)
if (((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << MPParser.FALSE) | (1 << MPParser.NOT) | (1 << MPParser.TRUE) | (1 << MPParser.SUB) | (1 << MPParser.LP) | (1 << MPParser.ID) | (1 << MPParser.INTLIT) | (1 << MPParser.FLOATLIT) | (1 << MPParser.STRINGLIT))) != 0):
self.state = 375
self.expr(0)
self.state = 380
self._errHandler.sync(self)
_la = self._input.LA(1)
while _la==MPParser.COMMA:
self.state = 376
self.match(MPParser.COMMA)
self.state = 377
self.expr(0)
self.state = 382
self._errHandler.sync(self)
_la = self._input.LA(1)
self.state = 385
self.match(MPParser.RP)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class ArraycellContext(ParserRuleContext):
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def exp6(self):
return self.getTypedRuleContext(MPParser.Exp6Context,0)
def LB(self):
return self.getToken(MPParser.LB, 0)
def expr(self):
return self.getTypedRuleContext(MPParser.ExprContext,0)
def RB(self):
return self.getToken(MPParser.RB, 0)
def getRuleIndex(self):
return MPParser.RULE_arraycell
def accept(self, visitor:ParseTreeVisitor):
if hasattr( visitor, "visitArraycell" ):
return visitor.visitArraycell(self)
else:
return visitor.visitChildren(self)
def arraycell(self):
localctx = MPParser.ArraycellContext(self, self._ctx, self.state)
self.enterRule(localctx, 70, self.RULE_arraycell)
try:
self.enterOuterAlt(localctx, 1)
self.state = 387
self.exp6()
self.state = 388
self.match(MPParser.LB)
self.state = 389
self.expr(0)
self.state = 390
self.match(MPParser.RB)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class BoollitContext(ParserRuleContext):
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def TRUE(self):
return self.getToken(MPParser.TRUE, 0)
def FALSE(self):
return self.getToken(MPParser.FALSE, 0)
def getRuleIndex(self):
return MPParser.RULE_boollit
def accept(self, visitor:ParseTreeVisitor):
if hasattr( visitor, "visitBoollit" ):
return visitor.visitBoollit(self)
else:
return visitor.visitChildren(self)
def boollit(self):
localctx = MPParser.BoollitContext(self, self._ctx, self.state)
self.enterRule(localctx, 72, self.RULE_boollit)
self._la = 0 # Token type
try:
self.enterOuterAlt(localctx, 1)
self.state = 392
_la = self._input.LA(1)
if not(_la==MPParser.FALSE or _la==MPParser.TRUE):
self._errHandler.recoverInline(self)
else:
self._errHandler.reportMatch(self)
self.consume()
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
def sempred(self, localctx:RuleContext, ruleIndex:int, predIndex:int):
if self._predicates == None:
self._predicates = dict()
self._predicates[26] = self.expr_sempred
self._predicates[28] = self.exp2_sempred
self._predicates[29] = self.exp3_sempred
pred = self._predicates.get(ruleIndex, None)
if pred is None:
raise Exception("No predicate with index:" + str(ruleIndex))
else:
return pred(localctx, predIndex)
def expr_sempred(self, localctx:ExprContext, predIndex:int):
if predIndex == 0:
return self.precpred(self._ctx, 3)
if predIndex == 1:
return self.precpred(self._ctx, 2)
def exp2_sempred(self, localctx:Exp2Context, predIndex:int):
if predIndex == 2:
return self.precpred(self._ctx, 4)
if predIndex == 3:
return self.precpred(self._ctx, 3)
if predIndex == 4:
return self.precpred(self._ctx, 2)
def exp3_sempred(self, localctx:Exp3Context, predIndex:int):
if predIndex == 5:
return self.precpred(self._ctx, 6)
if predIndex == 6:
return self.precpred(self._ctx, 5)
if predIndex == 7:
return self.precpred(self._ctx, 4)
if predIndex == 8:
return self.precpred(self._ctx, 3)
if predIndex == 9:
return self.precpred(self._ctx, 2)
|
{"/upload/src/main/mp/parser/MPVisitor.py": ["/upload/src/main/mp/parser/MPParser.py"]}
|
22,551
|
sarv19/ass4
|
refs/heads/master
|
/upload/src/main/mp/astgen/ASTGeneration.py
|
from MPVisitor import MPVisitor
from MPParser import MPParser
from AST import *
from functools import reduce
class ASTGeneration(MPVisitor):
def visitProgram(self, ctx: MPParser.ProgramContext):
return Program(reduce(lambda a, x: a + x, [self.visit(x) for x in ctx.decl()], []))
def visitDecl(self, ctx: MPParser.DeclContext):
if ctx.vardecl():
return self.visit(ctx.vardecl())
else:
return [self.visit(ctx.getChild(0))]
def visitFuncdecl(self, ctx: MPParser.FuncdeclContext):
rtype = self.visit(ctx.idtype())
cpstmt = self.visit(ctx.body())
return FuncDecl(Id(ctx.ID().getText()),
self.visit(ctx.plist()) if ctx.plist() else [],
self.visit(ctx.vardecl()) if ctx.vardecl() else [],
cpstmt,
rtype)
def visitProcdecl(self, ctx: MPParser.ProcdeclContext):
cpstmt = self.visit(ctx.body())
return FuncDecl(Id(ctx.ID().getText()),
self.visit(ctx.plist()) if ctx.plist() else [],
self.visit(ctx.vardecl()) if ctx.vardecl() else [],
cpstmt)
def visitVardecl(self, ctx: MPParser.VardeclContext):
lst = [self.visit(x) for x in ctx.vargroup()]
return reduce(lambda a, x: a + x, lst)
def visitVargroup(self, ctx: MPParser.VargroupContext):
idtype = self.visit(ctx.idtype())
return [VarDecl(id, idtype) for id in self.visit(ctx.idlist())]
def visitBody(self, ctx: MPParser.BodyContext):
return reduce(lambda a, x: a + x, [self.flatten(self.visit(x)) for x in ctx.stmt()], [])
def visitStmt(self, ctx: MPParser.StmtContext):
if ctx.breakstmt():
return Break()
elif ctx.continuestmt():
return Continue()
else:
return self.visit(ctx.getChild(0))
def visitAssign(self, ctx: MPParser.AssignContext):
lhs = len(ctx.variable())
assign_lst = []
if lhs > 1:
assign_lst = [Assign(self.visit(ctx.variable(x)),self.visit(ctx.variable(x+1))) for x in range(lhs-1)]
assign_lst += [Assign(self.visit(ctx.variable(lhs-1)), self.visit(ctx.expr()))]
return list(assign_lst.__reversed__())
def visitVariable(self, ctx: MPParser.VariableContext):
if ctx.ID():
return Id(ctx.ID().getText())
if ctx.arraycell():
return self.visit(ctx.arraycell())
def visitIfstmt(self, ctx: MPParser.IfstmtContext):
return If(self.visit(ctx.expr()),
self.flatten(self.visit(ctx.stmt(0))),
self.flatten(self.visit(ctx.stmt(1)) if ctx.stmt(1) else []))
def visitWhilestmt(self, ctx: MPParser.WhilestmtContext):
return While(self.visit(ctx.expr()),
self.flatten(self.visit(ctx.stmt())))
def visitReturnstmt(self, ctx: MPParser.ReturnstmtContext):
if not ctx.expr():
return Return()
else:
return Return(self.visit(ctx.expr()))
def visitForstmt(self, ctx: MPParser.ForstmtContext):
return For(Id(ctx.ID().getText()),
self.visit(ctx.expr(0)),
self.visit(ctx.expr(1)),
True if ctx.TO() else False,
self.flatten(self.visit(ctx.stmt())))
def visitWithstmt(self, ctx: MPParser.WithstmtContext):
return With(reduce(lambda a, x: a + x, [self.visit(x) for x in ctx.vargroup()], []),
self.flatten(self.visit(ctx.stmt())))
def visitCallstmt(self, ctx: MPParser.CallstmtContext):
return CallStmt(Id(ctx.ID().getText()),
[self.visit(x) for x in ctx.expr()])
def visitFuncall(self, ctx: MPParser.FuncallContext):
return CallExpr(Id(ctx.ID().getText()),
[self.visit(x) for x in ctx.expr()])
def visitExpr(self, ctx: MPParser.ExprContext):
if ctx.getChildCount() == 1:
return self.visit(ctx.exp1())
if ctx.AND():
return BinaryOp('andthen',
self.visit(ctx.expr()),
self.visit(ctx.exp1()))
if ctx.OR():
return BinaryOp('orelse',
self.visit(ctx.expr()),
self.visit(ctx.exp1()))
def visitExp1(self, ctx: MPParser.Exp1Context):
if ctx.getChildCount() == 1:
return self.visit(ctx.exp2(0))
else:
return BinaryOp(ctx.getChild(1).getText(),
self.visit(ctx.exp2(0)),
self.visit(ctx.exp2(1)))
def visitExp2(self, ctx: MPParser.Exp2Context):
if ctx.getChildCount() == 1:
return self.visit(ctx.exp3())
else:
return BinaryOp(ctx.getChild(1).getText(),
self.visit(ctx.exp2()),
self.visit(ctx.exp3()))
def visitExp3(self, ctx: MPParser.Exp3Context):
if ctx.getChildCount() == 1:
return self.visit(ctx.exp4())
else:
return BinaryOp(ctx.getChild(1).getText(),
self.visit(ctx.exp3()),
self.visit(ctx.exp4()))
def visitExp4(self, ctx: MPParser.Exp4Context):
if ctx.getChildCount() == 1:
return self.visit(ctx.exp5())
if ctx.SUB():
return UnaryOp(ctx.SUB().getText(), self.visit(ctx.exp4()))
if ctx.NOT():
return UnaryOp(ctx.NOT().getText(), self.visit(ctx.exp4()))
def visitExp5(self, ctx: MPParser.Exp5Context):
if ctx.getChildCount() == 1:
return self.visit(ctx.exp6())
else:
return ArrayCell(self.visit(ctx.exp6()), self.visit(ctx.expr()))
def visitExp6(self, ctx: MPParser.Exp5Context):
if ctx.op():
return self.visit(ctx.op())
else:
return self.visit(ctx.expr())
def visitOp(self, ctx: MPParser.OpContext):
if ctx.ID():
return Id(ctx.ID().getText())
if ctx.INTLIT():
return IntLiteral(int(ctx.INTLIT().getText()))
if ctx.FLOATLIT():
return FloatLiteral(float(ctx.FLOATLIT().getText()))
if ctx.STRINGLIT():
return StringLiteral(ctx.STRINGLIT().getText())
if ctx.boollit():
return BooleanLiteral(self.visit(ctx.boollit()))
if ctx.funcall():
return self.visit(ctx.funcall())
if ctx.arraycell():
return self.visit(ctx.arraycell())
def visitBoollit(self, ctx: MPParser.BoollitContext):
if ctx.TRUE():
return True
else:
return False
def visitArraycell(self, ctx: MPParser.ArraycellContext):
return ArrayCell(self.visit(ctx.exp6()), self.visit(ctx.expr()))
def visitPlist(self, ctx: MPParser.PlistContext):
grp = [self.visit(x) for x in ctx.pgroup()]
return reduce(lambda a, x: a + x, grp, [])
def visitPgroup(self, ctx: MPParser.PgroupContext):
idtype = self.visit(ctx.idtype())
return [VarDecl(id, idtype) for id in self.visit(ctx.idlist())]
def visitIdlist(self, ctx: MPParser.IdlistContext):
return [Id(x.getText()) for x in ctx.ID()]
def visitIdtype(self, ctx: MPParser.IdtypeContext):
return self.visit(ctx.getChild(0))
def visitPrimtype(self, ctx: MPParser.PrimtypeContext):
if ctx.BOOLEAN():
return BoolType()
if ctx.INTEGER():
return IntType()
if ctx.REAL():
return FloatType()
if ctx.STRING():
return StringType()
def visitArraytype(self, ctx: MPParser.ArraytypeContext):
return ArrayType(self.visit(ctx.signedInt()[0]),
self.visit(ctx.signedInt(1)),
self.visit(ctx.primtype()))
def visitSignedInt(self, ctx: MPParser.SignedIntContext):
return int(ctx.INTLIT().getText())*(-1 if ctx.SUB() else 1)
def flatten(self, target):
if isinstance(target, list):
return target
else:
return [target]
|
{"/upload/src/main/mp/parser/MPVisitor.py": ["/upload/src/main/mp/parser/MPParser.py"]}
|
22,552
|
sarv19/ass4
|
refs/heads/master
|
/upload/src/main/mp/parser/MPLexer.py
|
# Generated from main/mp/parser/MP.g4 by ANTLR 4.7.1
from antlr4 import *
from io import StringIO
from typing.io import TextIO
import sys
from lexererr import *
def serializedATN():
with StringIO() as buf:
buf.write("\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\2?")
buf.write("\u026e\b\1\4\2\t\2\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7")
buf.write("\t\7\4\b\t\b\4\t\t\t\4\n\t\n\4\13\t\13\4\f\t\f\4\r\t\r")
buf.write("\4\16\t\16\4\17\t\17\4\20\t\20\4\21\t\21\4\22\t\22\4\23")
buf.write("\t\23\4\24\t\24\4\25\t\25\4\26\t\26\4\27\t\27\4\30\t\30")
buf.write("\4\31\t\31\4\32\t\32\4\33\t\33\4\34\t\34\4\35\t\35\4\36")
buf.write("\t\36\4\37\t\37\4 \t \4!\t!\4\"\t\"\4#\t#\4$\t$\4%\t%")
buf.write("\4&\t&\4\'\t\'\4(\t(\4)\t)\4*\t*\4+\t+\4,\t,\4-\t-\4.")
buf.write("\t.\4/\t/\4\60\t\60\4\61\t\61\4\62\t\62\4\63\t\63\4\64")
buf.write("\t\64\4\65\t\65\4\66\t\66\4\67\t\67\48\t8\49\t9\4:\t:")
buf.write("\4;\t;\4<\t<\4=\t=\4>\t>\4?\t?\4@\t@\4A\tA\4B\tB\4C\t")
buf.write("C\4D\tD\4E\tE\4F\tF\4G\tG\4H\tH\4I\tI\4J\tJ\4K\tK\4L\t")
buf.write("L\4M\tM\4N\tN\4O\tO\4P\tP\4Q\tQ\4R\tR\4S\tS\4T\tT\4U\t")
buf.write("U\4V\tV\4W\tW\4X\tX\4Y\tY\4Z\tZ\4[\t[\4\\\t\\\4]\t]\4")
buf.write("^\t^\3\2\3\2\3\2\3\2\3\2\3\2\3\2\3\2\3\2\3\2\3\2\3\2\3")
buf.write("\2\3\2\3\2\3\2\3\2\3\2\3\2\3\2\3\2\3\2\3\2\3\2\3\2\3\2")
buf.write("\5\2\u00d8\n\2\3\3\3\3\3\4\3\4\3\5\3\5\3\6\3\6\3\7\3\7")
buf.write("\3\b\3\b\3\t\3\t\3\n\3\n\3\13\3\13\3\f\3\f\3\r\3\r\3\16")
buf.write("\3\16\3\17\3\17\3\20\3\20\3\21\3\21\3\22\3\22\3\23\3\23")
buf.write("\3\24\3\24\3\25\3\25\3\26\3\26\3\27\3\27\3\30\3\30\3\31")
buf.write("\3\31\3\32\3\32\3\33\3\33\3\34\3\34\3\35\3\35\3\35\3\35")
buf.write("\3\36\3\36\3\36\3\36\3\36\3\36\3\37\3\37\3\37\3\37\3\37")
buf.write("\3\37\3 \3 \3 \3 \3 \3 \3 \3 \3!\3!\3!\3!\3!\3!\3\"\3")
buf.write("\"\3\"\3\"\3\"\3\"\3\"\3\"\3\"\3#\3#\3#\3#\3$\3$\3$\3")
buf.write("%\3%\3%\3%\3%\3%\3%\3&\3&\3&\3&\3&\3\'\3\'\3\'\3\'\3(")
buf.write("\3(\3(\3(\3(\3(\3)\3)\3)\3)\3*\3*\3*\3*\3*\3*\3*\3*\3")
buf.write("*\3+\3+\3+\3,\3,\3,\3,\3,\3,\3,\3,\3-\3-\3-\3-\3.\3.\3")
buf.write(".\3.\3/\3/\3/\3\60\3\60\3\60\3\61\3\61\3\61\3\61\3\61")
buf.write("\3\61\3\61\3\61\3\61\3\61\3\62\3\62\3\62\3\62\3\62\3\63")
buf.write("\3\63\3\63\3\63\3\63\3\63\3\63\3\64\3\64\3\64\3\64\3\64")
buf.write("\3\64\3\64\3\65\3\65\3\65\3\65\3\65\3\66\3\66\3\66\3\67")
buf.write("\3\67\3\67\3\67\3\67\38\38\38\38\39\39\39\39\39\39\3:")
buf.write("\3:\3:\3:\3:\3;\3;\3<\3<\3=\3=\3>\3>\3?\3?\3?\3@\3@\3")
buf.write("A\3A\3B\3B\3C\3C\3D\3D\3D\3E\3E\3F\3F\3F\3G\3G\3H\3H\3")
buf.write("H\3I\3I\3J\3J\3K\3K\3L\3L\3M\3M\3N\3N\3O\3O\3O\3P\3P\3")
buf.write("P\3P\3Q\3Q\3Q\3Q\7Q\u01e8\nQ\fQ\16Q\u01eb\13Q\3Q\3Q\3")
buf.write("Q\3Q\7Q\u01f1\nQ\fQ\16Q\u01f4\13Q\3Q\5Q\u01f7\nQ\3Q\3")
buf.write("Q\3R\3R\3R\3R\7R\u01ff\nR\fR\16R\u0202\13R\3R\3R\3S\3")
buf.write("S\5S\u0208\nS\3S\3S\3S\7S\u020d\nS\fS\16S\u0210\13S\3")
buf.write("T\6T\u0213\nT\rT\16T\u0214\3U\6U\u0218\nU\rU\16U\u0219")
buf.write("\3U\3U\7U\u021e\nU\fU\16U\u0221\13U\3U\5U\u0224\nU\3U")
buf.write("\3U\6U\u0228\nU\rU\16U\u0229\3U\5U\u022d\nU\3U\6U\u0230")
buf.write("\nU\rU\16U\u0231\3U\3U\5U\u0236\nU\3V\3V\5V\u023a\nV\3")
buf.write("V\3V\3V\3W\3W\3X\3X\5X\u0243\nX\3X\6X\u0246\nX\rX\16X")
buf.write("\u0247\3Y\3Y\3Y\3Z\3Z\5Z\u024f\nZ\3[\6[\u0252\n[\r[\16")
buf.write("[\u0253\3\\\3\\\6\\\u0258\n\\\r\\\16\\\u0259\3\\\3\\\3")
buf.write("]\3]\7]\u0260\n]\f]\16]\u0263\13]\3]\3]\3]\5]\u0268\n")
buf.write("]\3]\3]\3^\3^\3^\4\u01e9\u01f2\2_\3\2\5\2\7\2\t\2\13\2")
buf.write("\r\2\17\2\21\2\23\2\25\2\27\2\31\2\33\2\35\2\37\2!\2#")
buf.write("\2%\2\'\2)\2+\2-\2/\2\61\2\63\2\65\2\67\29\3;\4=\5?\6")
buf.write("A\7C\bE\tG\nI\13K\fM\rO\16Q\17S\20U\21W\22Y\23[\24]\25")
buf.write("_\26a\27c\30e\31g\32i\33k\34m\35o\36q\37s u!w\"y#{$}%")
buf.write("\177&\u0081\'\u0083(\u0085)\u0087*\u0089+\u008b,\u008d")
buf.write("-\u008f.\u0091/\u0093\60\u0095\61\u0097\62\u0099\63\u009b")
buf.write("\64\u009d\65\u009f\66\u00a1\67\u00a38\u00a59\u00a7:\u00a9")
buf.write(";\u00ab<\u00ad\2\u00af\2\u00b1\2\u00b3\2\u00b5\2\u00b7")
buf.write("=\u00b9>\u00bb?\3\2\"\4\2CCcc\4\2DDdd\4\2EEee\4\2FFff")
buf.write("\4\2GGgg\4\2HHhh\4\2IIii\4\2JJjj\4\2KKkk\4\2LLll\4\2M")
buf.write("Mmm\4\2NNnn\4\2OOoo\4\2PPpp\4\2QQqq\4\2RRrr\4\2SSss\4")
buf.write("\2TTtt\4\2UUuu\4\2VVvv\4\2WWww\4\2XXxx\4\2YYyy\4\2ZZz")
buf.write("z\4\2[[{{\4\2\\\\||\5\2\13\f\16\17\"\"\4\2\f\f\17\17\3")
buf.write("\2\62;\3\2//\n\2$$))^^ddhhppttvv\7\2\n\f\16\17$$))^^\2")
buf.write("\u027f\29\3\2\2\2\2;\3\2\2\2\2=\3\2\2\2\2?\3\2\2\2\2A")
buf.write("\3\2\2\2\2C\3\2\2\2\2E\3\2\2\2\2G\3\2\2\2\2I\3\2\2\2\2")
buf.write("K\3\2\2\2\2M\3\2\2\2\2O\3\2\2\2\2Q\3\2\2\2\2S\3\2\2\2")
buf.write("\2U\3\2\2\2\2W\3\2\2\2\2Y\3\2\2\2\2[\3\2\2\2\2]\3\2\2")
buf.write("\2\2_\3\2\2\2\2a\3\2\2\2\2c\3\2\2\2\2e\3\2\2\2\2g\3\2")
buf.write("\2\2\2i\3\2\2\2\2k\3\2\2\2\2m\3\2\2\2\2o\3\2\2\2\2q\3")
buf.write("\2\2\2\2s\3\2\2\2\2u\3\2\2\2\2w\3\2\2\2\2y\3\2\2\2\2{")
buf.write("\3\2\2\2\2}\3\2\2\2\2\177\3\2\2\2\2\u0081\3\2\2\2\2\u0083")
buf.write("\3\2\2\2\2\u0085\3\2\2\2\2\u0087\3\2\2\2\2\u0089\3\2\2")
buf.write("\2\2\u008b\3\2\2\2\2\u008d\3\2\2\2\2\u008f\3\2\2\2\2\u0091")
buf.write("\3\2\2\2\2\u0093\3\2\2\2\2\u0095\3\2\2\2\2\u0097\3\2\2")
buf.write("\2\2\u0099\3\2\2\2\2\u009b\3\2\2\2\2\u009d\3\2\2\2\2\u009f")
buf.write("\3\2\2\2\2\u00a1\3\2\2\2\2\u00a3\3\2\2\2\2\u00a5\3\2\2")
buf.write("\2\2\u00a7\3\2\2\2\2\u00a9\3\2\2\2\2\u00ab\3\2\2\2\2\u00b7")
buf.write("\3\2\2\2\2\u00b9\3\2\2\2\2\u00bb\3\2\2\2\3\u00d7\3\2\2")
buf.write("\2\5\u00d9\3\2\2\2\7\u00db\3\2\2\2\t\u00dd\3\2\2\2\13")
buf.write("\u00df\3\2\2\2\r\u00e1\3\2\2\2\17\u00e3\3\2\2\2\21\u00e5")
buf.write("\3\2\2\2\23\u00e7\3\2\2\2\25\u00e9\3\2\2\2\27\u00eb\3")
buf.write("\2\2\2\31\u00ed\3\2\2\2\33\u00ef\3\2\2\2\35\u00f1\3\2")
buf.write("\2\2\37\u00f3\3\2\2\2!\u00f5\3\2\2\2#\u00f7\3\2\2\2%\u00f9")
buf.write("\3\2\2\2\'\u00fb\3\2\2\2)\u00fd\3\2\2\2+\u00ff\3\2\2\2")
buf.write("-\u0101\3\2\2\2/\u0103\3\2\2\2\61\u0105\3\2\2\2\63\u0107")
buf.write("\3\2\2\2\65\u0109\3\2\2\2\67\u010b\3\2\2\29\u010d\3\2")
buf.write("\2\2;\u0111\3\2\2\2=\u0117\3\2\2\2?\u011d\3\2\2\2A\u0125")
buf.write("\3\2\2\2C\u012b\3\2\2\2E\u0134\3\2\2\2G\u0138\3\2\2\2")
buf.write("I\u013b\3\2\2\2K\u0142\3\2\2\2M\u0147\3\2\2\2O\u014b\3")
buf.write("\2\2\2Q\u0151\3\2\2\2S\u0155\3\2\2\2U\u015e\3\2\2\2W\u0161")
buf.write("\3\2\2\2Y\u0169\3\2\2\2[\u016d\3\2\2\2]\u0171\3\2\2\2")
buf.write("_\u0174\3\2\2\2a\u0177\3\2\2\2c\u0181\3\2\2\2e\u0186\3")
buf.write("\2\2\2g\u018d\3\2\2\2i\u0194\3\2\2\2k\u0199\3\2\2\2m\u019c")
buf.write("\3\2\2\2o\u01a1\3\2\2\2q\u01a5\3\2\2\2s\u01ab\3\2\2\2")
buf.write("u\u01b0\3\2\2\2w\u01b2\3\2\2\2y\u01b4\3\2\2\2{\u01b6\3")
buf.write("\2\2\2}\u01b8\3\2\2\2\177\u01bb\3\2\2\2\u0081\u01bd\3")
buf.write("\2\2\2\u0083\u01bf\3\2\2\2\u0085\u01c1\3\2\2\2\u0087\u01c3")
buf.write("\3\2\2\2\u0089\u01c6\3\2\2\2\u008b\u01c8\3\2\2\2\u008d")
buf.write("\u01cb\3\2\2\2\u008f\u01cd\3\2\2\2\u0091\u01d0\3\2\2\2")
buf.write("\u0093\u01d2\3\2\2\2\u0095\u01d4\3\2\2\2\u0097\u01d6\3")
buf.write("\2\2\2\u0099\u01d8\3\2\2\2\u009b\u01da\3\2\2\2\u009d\u01dc")
buf.write("\3\2\2\2\u009f\u01df\3\2\2\2\u00a1\u01f6\3\2\2\2\u00a3")
buf.write("\u01fa\3\2\2\2\u00a5\u0207\3\2\2\2\u00a7\u0212\3\2\2\2")
buf.write("\u00a9\u0235\3\2\2\2\u00ab\u0237\3\2\2\2\u00ad\u023e\3")
buf.write("\2\2\2\u00af\u0240\3\2\2\2\u00b1\u0249\3\2\2\2\u00b3\u024e")
buf.write("\3\2\2\2\u00b5\u0251\3\2\2\2\u00b7\u0255\3\2\2\2\u00b9")
buf.write("\u025d\3\2\2\2\u00bb\u026b\3\2\2\2\u00bd\u00d8\5\5\3\2")
buf.write("\u00be\u00d8\5\7\4\2\u00bf\u00d8\5\t\5\2\u00c0\u00d8\5")
buf.write("\13\6\2\u00c1\u00d8\5\r\7\2\u00c2\u00d8\5\17\b\2\u00c3")
buf.write("\u00d8\5\21\t\2\u00c4\u00d8\5\23\n\2\u00c5\u00d8\5\25")
buf.write("\13\2\u00c6\u00d8\5\27\f\2\u00c7\u00d8\5\31\r\2\u00c8")
buf.write("\u00d8\5\33\16\2\u00c9\u00d8\5\35\17\2\u00ca\u00d8\5\37")
buf.write("\20\2\u00cb\u00d8\5!\21\2\u00cc\u00d8\5#\22\2\u00cd\u00d8")
buf.write("\5%\23\2\u00ce\u00d8\5\'\24\2\u00cf\u00d8\5)\25\2\u00d0")
buf.write("\u00d8\5+\26\2\u00d1\u00d8\5-\27\2\u00d2\u00d8\5/\30\2")
buf.write("\u00d3\u00d8\5\61\31\2\u00d4\u00d8\5\63\32\2\u00d5\u00d8")
buf.write("\5\65\33\2\u00d6\u00d8\5\67\34\2\u00d7\u00bd\3\2\2\2\u00d7")
buf.write("\u00be\3\2\2\2\u00d7\u00bf\3\2\2\2\u00d7\u00c0\3\2\2\2")
buf.write("\u00d7\u00c1\3\2\2\2\u00d7\u00c2\3\2\2\2\u00d7\u00c3\3")
buf.write("\2\2\2\u00d7\u00c4\3\2\2\2\u00d7\u00c5\3\2\2\2\u00d7\u00c6")
buf.write("\3\2\2\2\u00d7\u00c7\3\2\2\2\u00d7\u00c8\3\2\2\2\u00d7")
buf.write("\u00c9\3\2\2\2\u00d7\u00ca\3\2\2\2\u00d7\u00cb\3\2\2\2")
buf.write("\u00d7\u00cc\3\2\2\2\u00d7\u00cd\3\2\2\2\u00d7\u00ce\3")
buf.write("\2\2\2\u00d7\u00cf\3\2\2\2\u00d7\u00d0\3\2\2\2\u00d7\u00d1")
buf.write("\3\2\2\2\u00d7\u00d2\3\2\2\2\u00d7\u00d3\3\2\2\2\u00d7")
buf.write("\u00d4\3\2\2\2\u00d7\u00d5\3\2\2\2\u00d7\u00d6\3\2\2\2")
buf.write("\u00d8\4\3\2\2\2\u00d9\u00da\t\2\2\2\u00da\6\3\2\2\2\u00db")
buf.write("\u00dc\t\3\2\2\u00dc\b\3\2\2\2\u00dd\u00de\t\4\2\2\u00de")
buf.write("\n\3\2\2\2\u00df\u00e0\t\5\2\2\u00e0\f\3\2\2\2\u00e1\u00e2")
buf.write("\t\6\2\2\u00e2\16\3\2\2\2\u00e3\u00e4\t\7\2\2\u00e4\20")
buf.write("\3\2\2\2\u00e5\u00e6\t\b\2\2\u00e6\22\3\2\2\2\u00e7\u00e8")
buf.write("\t\t\2\2\u00e8\24\3\2\2\2\u00e9\u00ea\t\n\2\2\u00ea\26")
buf.write("\3\2\2\2\u00eb\u00ec\t\13\2\2\u00ec\30\3\2\2\2\u00ed\u00ee")
buf.write("\t\f\2\2\u00ee\32\3\2\2\2\u00ef\u00f0\t\r\2\2\u00f0\34")
buf.write("\3\2\2\2\u00f1\u00f2\t\16\2\2\u00f2\36\3\2\2\2\u00f3\u00f4")
buf.write("\t\17\2\2\u00f4 \3\2\2\2\u00f5\u00f6\t\20\2\2\u00f6\"")
buf.write("\3\2\2\2\u00f7\u00f8\t\21\2\2\u00f8$\3\2\2\2\u00f9\u00fa")
buf.write("\t\22\2\2\u00fa&\3\2\2\2\u00fb\u00fc\t\23\2\2\u00fc(\3")
buf.write("\2\2\2\u00fd\u00fe\t\24\2\2\u00fe*\3\2\2\2\u00ff\u0100")
buf.write("\t\25\2\2\u0100,\3\2\2\2\u0101\u0102\t\26\2\2\u0102.\3")
buf.write("\2\2\2\u0103\u0104\t\27\2\2\u0104\60\3\2\2\2\u0105\u0106")
buf.write("\t\30\2\2\u0106\62\3\2\2\2\u0107\u0108\t\31\2\2\u0108")
buf.write("\64\3\2\2\2\u0109\u010a\t\32\2\2\u010a\66\3\2\2\2\u010b")
buf.write("\u010c\t\33\2\2\u010c8\3\2\2\2\u010d\u010e\5\5\3\2\u010e")
buf.write("\u010f\5\37\20\2\u010f\u0110\5\13\6\2\u0110:\3\2\2\2\u0111")
buf.write("\u0112\5\5\3\2\u0112\u0113\5\'\24\2\u0113\u0114\5\'\24")
buf.write("\2\u0114\u0115\5\5\3\2\u0115\u0116\5\65\33\2\u0116<\3")
buf.write("\2\2\2\u0117\u0118\5\7\4\2\u0118\u0119\5\r\7\2\u0119\u011a")
buf.write("\5\21\t\2\u011a\u011b\5\25\13\2\u011b\u011c\5\37\20\2")
buf.write("\u011c>\3\2\2\2\u011d\u011e\5\7\4\2\u011e\u011f\5!\21")
buf.write("\2\u011f\u0120\5!\21\2\u0120\u0121\5\33\16\2\u0121\u0122")
buf.write("\5\r\7\2\u0122\u0123\5\5\3\2\u0123\u0124\5\37\20\2\u0124")
buf.write("@\3\2\2\2\u0125\u0126\5\7\4\2\u0126\u0127\5\'\24\2\u0127")
buf.write("\u0128\5\r\7\2\u0128\u0129\5\5\3\2\u0129\u012a\5\31\r")
buf.write("\2\u012aB\3\2\2\2\u012b\u012c\5\t\5\2\u012c\u012d\5!\21")
buf.write("\2\u012d\u012e\5\37\20\2\u012e\u012f\5+\26\2\u012f\u0130")
buf.write("\5\25\13\2\u0130\u0131\5\37\20\2\u0131\u0132\5-\27\2\u0132")
buf.write("\u0133\5\r\7\2\u0133D\3\2\2\2\u0134\u0135\5\13\6\2\u0135")
buf.write("\u0136\5\25\13\2\u0136\u0137\5/\30\2\u0137F\3\2\2\2\u0138")
buf.write("\u0139\5\13\6\2\u0139\u013a\5!\21\2\u013aH\3\2\2\2\u013b")
buf.write("\u013c\5\13\6\2\u013c\u013d\5!\21\2\u013d\u013e\5\61\31")
buf.write("\2\u013e\u013f\5\37\20\2\u013f\u0140\5+\26\2\u0140\u0141")
buf.write("\5!\21\2\u0141J\3\2\2\2\u0142\u0143\5\r\7\2\u0143\u0144")
buf.write("\5\33\16\2\u0144\u0145\5)\25\2\u0145\u0146\5\r\7\2\u0146")
buf.write("L\3\2\2\2\u0147\u0148\5\r\7\2\u0148\u0149\5\37\20\2\u0149")
buf.write("\u014a\5\13\6\2\u014aN\3\2\2\2\u014b\u014c\5\17\b\2\u014c")
buf.write("\u014d\5\5\3\2\u014d\u014e\5\33\16\2\u014e\u014f\5)\25")
buf.write("\2\u014f\u0150\5\r\7\2\u0150P\3\2\2\2\u0151\u0152\5\17")
buf.write("\b\2\u0152\u0153\5!\21\2\u0153\u0154\5\'\24\2\u0154R\3")
buf.write("\2\2\2\u0155\u0156\5\17\b\2\u0156\u0157\5-\27\2\u0157")
buf.write("\u0158\5\37\20\2\u0158\u0159\5\t\5\2\u0159\u015a\5+\26")
buf.write("\2\u015a\u015b\5\25\13\2\u015b\u015c\5!\21\2\u015c\u015d")
buf.write("\5\37\20\2\u015dT\3\2\2\2\u015e\u015f\5\25\13\2\u015f")
buf.write("\u0160\5\17\b\2\u0160V\3\2\2\2\u0161\u0162\5\25\13\2\u0162")
buf.write("\u0163\5\37\20\2\u0163\u0164\5+\26\2\u0164\u0165\5\r\7")
buf.write("\2\u0165\u0166\5\21\t\2\u0166\u0167\5\r\7\2\u0167\u0168")
buf.write("\5\'\24\2\u0168X\3\2\2\2\u0169\u016a\5\35\17\2\u016a\u016b")
buf.write("\5!\21\2\u016b\u016c\5\13\6\2\u016cZ\3\2\2\2\u016d\u016e")
buf.write("\5\37\20\2\u016e\u016f\5!\21\2\u016f\u0170\5+\26\2\u0170")
buf.write("\\\3\2\2\2\u0171\u0172\5!\21\2\u0172\u0173\5\17\b\2\u0173")
buf.write("^\3\2\2\2\u0174\u0175\5!\21\2\u0175\u0176\5\'\24\2\u0176")
buf.write("`\3\2\2\2\u0177\u0178\5#\22\2\u0178\u0179\5\'\24\2\u0179")
buf.write("\u017a\5!\21\2\u017a\u017b\5\t\5\2\u017b\u017c\5\r\7\2")
buf.write("\u017c\u017d\5\13\6\2\u017d\u017e\5-\27\2\u017e\u017f")
buf.write("\5\'\24\2\u017f\u0180\5\r\7\2\u0180b\3\2\2\2\u0181\u0182")
buf.write("\5\'\24\2\u0182\u0183\5\r\7\2\u0183\u0184\5\5\3\2\u0184")
buf.write("\u0185\5\33\16\2\u0185d\3\2\2\2\u0186\u0187\5\'\24\2\u0187")
buf.write("\u0188\5\r\7\2\u0188\u0189\5+\26\2\u0189\u018a\5-\27\2")
buf.write("\u018a\u018b\5\'\24\2\u018b\u018c\5\37\20\2\u018cf\3\2")
buf.write("\2\2\u018d\u018e\5)\25\2\u018e\u018f\5+\26\2\u018f\u0190")
buf.write("\5\'\24\2\u0190\u0191\5\25\13\2\u0191\u0192\5\37\20\2")
buf.write("\u0192\u0193\5\21\t\2\u0193h\3\2\2\2\u0194\u0195\5+\26")
buf.write("\2\u0195\u0196\5\23\n\2\u0196\u0197\5\r\7\2\u0197\u0198")
buf.write("\5\37\20\2\u0198j\3\2\2\2\u0199\u019a\5+\26\2\u019a\u019b")
buf.write("\5!\21\2\u019bl\3\2\2\2\u019c\u019d\5+\26\2\u019d\u019e")
buf.write("\5\'\24\2\u019e\u019f\5-\27\2\u019f\u01a0\5\r\7\2\u01a0")
buf.write("n\3\2\2\2\u01a1\u01a2\5/\30\2\u01a2\u01a3\5\5\3\2\u01a3")
buf.write("\u01a4\5\'\24\2\u01a4p\3\2\2\2\u01a5\u01a6\5\61\31\2\u01a6")
buf.write("\u01a7\5\23\n\2\u01a7\u01a8\5\25\13\2\u01a8\u01a9\5\33")
buf.write("\16\2\u01a9\u01aa\5\r\7\2\u01aar\3\2\2\2\u01ab\u01ac\5")
buf.write("\61\31\2\u01ac\u01ad\5\25\13\2\u01ad\u01ae\5+\26\2\u01ae")
buf.write("\u01af\5\23\n\2\u01aft\3\2\2\2\u01b0\u01b1\7-\2\2\u01b1")
buf.write("v\3\2\2\2\u01b2\u01b3\7/\2\2\u01b3x\3\2\2\2\u01b4\u01b5")
buf.write("\7,\2\2\u01b5z\3\2\2\2\u01b6\u01b7\7\61\2\2\u01b7|\3\2")
buf.write("\2\2\u01b8\u01b9\7<\2\2\u01b9\u01ba\7?\2\2\u01ba~\3\2")
buf.write("\2\2\u01bb\u01bc\7.\2\2\u01bc\u0080\3\2\2\2\u01bd\u01be")
buf.write("\7=\2\2\u01be\u0082\3\2\2\2\u01bf\u01c0\7<\2\2\u01c0\u0084")
buf.write("\3\2\2\2\u01c1\u01c2\7?\2\2\u01c2\u0086\3\2\2\2\u01c3")
buf.write("\u01c4\7>\2\2\u01c4\u01c5\7@\2\2\u01c5\u0088\3\2\2\2\u01c6")
buf.write("\u01c7\7>\2\2\u01c7\u008a\3\2\2\2\u01c8\u01c9\7>\2\2\u01c9")
buf.write("\u01ca\7?\2\2\u01ca\u008c\3\2\2\2\u01cb\u01cc\7@\2\2\u01cc")
buf.write("\u008e\3\2\2\2\u01cd\u01ce\7@\2\2\u01ce\u01cf\7?\2\2\u01cf")
buf.write("\u0090\3\2\2\2\u01d0\u01d1\7]\2\2\u01d1\u0092\3\2\2\2")
buf.write("\u01d2\u01d3\7_\2\2\u01d3\u0094\3\2\2\2\u01d4\u01d5\7")
buf.write("*\2\2\u01d5\u0096\3\2\2\2\u01d6\u01d7\7+\2\2\u01d7\u0098")
buf.write("\3\2\2\2\u01d8\u01d9\7}\2\2\u01d9\u009a\3\2\2\2\u01da")
buf.write("\u01db\7\177\2\2\u01db\u009c\3\2\2\2\u01dc\u01dd\7\60")
buf.write("\2\2\u01dd\u01de\7\60\2\2\u01de\u009e\3\2\2\2\u01df\u01e0")
buf.write("\t\34\2\2\u01e0\u01e1\3\2\2\2\u01e1\u01e2\bP\2\2\u01e2")
buf.write("\u00a0\3\2\2\2\u01e3\u01e4\7*\2\2\u01e4\u01e5\7,\2\2\u01e5")
buf.write("\u01e9\3\2\2\2\u01e6\u01e8\13\2\2\2\u01e7\u01e6\3\2\2")
buf.write("\2\u01e8\u01eb\3\2\2\2\u01e9\u01ea\3\2\2\2\u01e9\u01e7")
buf.write("\3\2\2\2\u01ea\u01ec\3\2\2\2\u01eb\u01e9\3\2\2\2\u01ec")
buf.write("\u01ed\7,\2\2\u01ed\u01f7\7+\2\2\u01ee\u01f2\7}\2\2\u01ef")
buf.write("\u01f1\13\2\2\2\u01f0\u01ef\3\2\2\2\u01f1\u01f4\3\2\2")
buf.write("\2\u01f2\u01f3\3\2\2\2\u01f2\u01f0\3\2\2\2\u01f3\u01f5")
buf.write("\3\2\2\2\u01f4\u01f2\3\2\2\2\u01f5\u01f7\7\177\2\2\u01f6")
buf.write("\u01e3\3\2\2\2\u01f6\u01ee\3\2\2\2\u01f7\u01f8\3\2\2\2")
buf.write("\u01f8\u01f9\bQ\2\2\u01f9\u00a2\3\2\2\2\u01fa\u01fb\7")
buf.write("\61\2\2\u01fb\u01fc\7\61\2\2\u01fc\u0200\3\2\2\2\u01fd")
buf.write("\u01ff\n\35\2\2\u01fe\u01fd\3\2\2\2\u01ff\u0202\3\2\2")
buf.write("\2\u0200\u01fe\3\2\2\2\u0200\u0201\3\2\2\2\u0201\u0203")
buf.write("\3\2\2\2\u0202\u0200\3\2\2\2\u0203\u0204\bR\2\2\u0204")
buf.write("\u00a4\3\2\2\2\u0205\u0208\5\3\2\2\u0206\u0208\7a\2\2")
buf.write("\u0207\u0205\3\2\2\2\u0207\u0206\3\2\2\2\u0208\u020e\3")
buf.write("\2\2\2\u0209\u020d\5\3\2\2\u020a\u020d\7a\2\2\u020b\u020d")
buf.write("\5\u00adW\2\u020c\u0209\3\2\2\2\u020c\u020a\3\2\2\2\u020c")
buf.write("\u020b\3\2\2\2\u020d\u0210\3\2\2\2\u020e\u020c\3\2\2\2")
buf.write("\u020e\u020f\3\2\2\2\u020f\u00a6\3\2\2\2\u0210\u020e\3")
buf.write("\2\2\2\u0211\u0213\5\u00adW\2\u0212\u0211\3\2\2\2\u0213")
buf.write("\u0214\3\2\2\2\u0214\u0212\3\2\2\2\u0214\u0215\3\2\2\2")
buf.write("\u0215\u00a8\3\2\2\2\u0216\u0218\5\u00adW\2\u0217\u0216")
buf.write("\3\2\2\2\u0218\u0219\3\2\2\2\u0219\u0217\3\2\2\2\u0219")
buf.write("\u021a\3\2\2\2\u021a\u021b\3\2\2\2\u021b\u021f\7\60\2")
buf.write("\2\u021c\u021e\5\u00adW\2\u021d\u021c\3\2\2\2\u021e\u0221")
buf.write("\3\2\2\2\u021f\u021d\3\2\2\2\u021f\u0220\3\2\2\2\u0220")
buf.write("\u0223\3\2\2\2\u0221\u021f\3\2\2\2\u0222\u0224\5\u00af")
buf.write("X\2\u0223\u0222\3\2\2\2\u0223\u0224\3\2\2\2\u0224\u0236")
buf.write("\3\2\2\2\u0225\u0227\7\60\2\2\u0226\u0228\5\u00adW\2\u0227")
buf.write("\u0226\3\2\2\2\u0228\u0229\3\2\2\2\u0229\u0227\3\2\2\2")
buf.write("\u0229\u022a\3\2\2\2\u022a\u022c\3\2\2\2\u022b\u022d\5")
buf.write("\u00afX\2\u022c\u022b\3\2\2\2\u022c\u022d\3\2\2\2\u022d")
buf.write("\u0236\3\2\2\2\u022e\u0230\5\u00adW\2\u022f\u022e\3\2")
buf.write("\2\2\u0230\u0231\3\2\2\2\u0231\u022f\3\2\2\2\u0231\u0232")
buf.write("\3\2\2\2\u0232\u0233\3\2\2\2\u0233\u0234\5\u00afX\2\u0234")
buf.write("\u0236\3\2\2\2\u0235\u0217\3\2\2\2\u0235\u0225\3\2\2\2")
buf.write("\u0235\u022f\3\2\2\2\u0236\u00aa\3\2\2\2\u0237\u0239\7")
buf.write("$\2\2\u0238\u023a\5\u00b5[\2\u0239\u0238\3\2\2\2\u0239")
buf.write("\u023a\3\2\2\2\u023a\u023b\3\2\2\2\u023b\u023c\7$\2\2")
buf.write("\u023c\u023d\bV\3\2\u023d\u00ac\3\2\2\2\u023e\u023f\t")
buf.write("\36\2\2\u023f\u00ae\3\2\2\2\u0240\u0242\t\6\2\2\u0241")
buf.write("\u0243\t\37\2\2\u0242\u0241\3\2\2\2\u0242\u0243\3\2\2")
buf.write("\2\u0243\u0245\3\2\2\2\u0244\u0246\t\36\2\2\u0245\u0244")
buf.write("\3\2\2\2\u0246\u0247\3\2\2\2\u0247\u0245\3\2\2\2\u0247")
buf.write("\u0248\3\2\2\2\u0248\u00b0\3\2\2\2\u0249\u024a\7^\2\2")
buf.write("\u024a\u024b\t \2\2\u024b\u00b2\3\2\2\2\u024c\u024f\n")
buf.write("!\2\2\u024d\u024f\5\u00b1Y\2\u024e\u024c\3\2\2\2\u024e")
buf.write("\u024d\3\2\2\2\u024f\u00b4\3\2\2\2\u0250\u0252\5\u00b3")
buf.write("Z\2\u0251\u0250\3\2\2\2\u0252\u0253\3\2\2\2\u0253\u0251")
buf.write("\3\2\2\2\u0253\u0254\3\2\2\2\u0254\u00b6\3\2\2\2\u0255")
buf.write("\u0257\7$\2\2\u0256\u0258\5\u00b3Z\2\u0257\u0256\3\2\2")
buf.write("\2\u0258\u0259\3\2\2\2\u0259\u0257\3\2\2\2\u0259\u025a")
buf.write("\3\2\2\2\u025a\u025b\3\2\2\2\u025b\u025c\b\\\4\2\u025c")
buf.write("\u00b8\3\2\2\2\u025d\u0261\7$\2\2\u025e\u0260\5\u00b3")
buf.write("Z\2\u025f\u025e\3\2\2\2\u0260\u0263\3\2\2\2\u0261\u025f")
buf.write("\3\2\2\2\u0261\u0262\3\2\2\2\u0262\u0267\3\2\2\2\u0263")
buf.write("\u0261\3\2\2\2\u0264\u0265\7^\2\2\u0265\u0268\n \2\2\u0266")
buf.write("\u0268\t!\2\2\u0267\u0264\3\2\2\2\u0267\u0266\3\2\2\2")
buf.write("\u0268\u0269\3\2\2\2\u0269\u026a\b]\5\2\u026a\u00ba\3")
buf.write("\2\2\2\u026b\u026c\13\2\2\2\u026c\u026d\b^\6\2\u026d\u00bc")
buf.write("\3\2\2\2\33\2\u00d7\u01e9\u01f2\u01f6\u0200\u0207\u020c")
buf.write("\u020e\u0214\u0219\u021f\u0223\u0229\u022c\u0231\u0235")
buf.write("\u0239\u0242\u0247\u024e\u0253\u0259\u0261\u0267\7\b\2")
buf.write("\2\3V\2\3\\\3\3]\4\3^\5")
return buf.getvalue()
class MPLexer(Lexer):
atn = ATNDeserializer().deserialize(serializedATN())
decisionsToDFA = [ DFA(ds, i) for i, ds in enumerate(atn.decisionToState) ]
AND = 1
ARRAY = 2
BEGIN = 3
BOOLEAN = 4
BREAK = 5
CONTINUE = 6
DIV = 7
DO = 8
DOWNTO = 9
ELSE = 10
END = 11
FALSE = 12
FOR = 13
FUNCTION = 14
IF = 15
INTEGER = 16
MOD = 17
NOT = 18
OF = 19
OR = 20
PROCEDURE = 21
REAL = 22
RETURN = 23
STRING = 24
THEN = 25
TO = 26
TRUE = 27
VAR = 28
WHILE = 29
WITH = 30
ADD = 31
SUB = 32
MUL = 33
SLASH = 34
ASSIGN = 35
COMMA = 36
SEMI = 37
COLON = 38
EQUAL = 39
NOTEQUAL = 40
LT = 41
LE = 42
GT = 43
GE = 44
LB = 45
RB = 46
LP = 47
RP = 48
LC = 49
RC = 50
DOTDOT = 51
WHITESPACE = 52
BLOCK_COMMENT = 53
LINE_COMMENT = 54
ID = 55
INTLIT = 56
FLOATLIT = 57
STRINGLIT = 58
UNCLOSE_STRING = 59
ILLEGAL_ESCAPE = 60
ERROR_CHAR = 61
channelNames = [ u"DEFAULT_TOKEN_CHANNEL", u"HIDDEN" ]
modeNames = [ "DEFAULT_MODE" ]
literalNames = [ "<INVALID>",
"'+'", "'-'", "'*'", "'/'", "':='", "','", "';'", "':'", "'='",
"'<>'", "'<'", "'<='", "'>'", "'>='", "'['", "']'", "'('", "')'",
"'{'", "'}'", "'..'" ]
symbolicNames = [ "<INVALID>",
"AND", "ARRAY", "BEGIN", "BOOLEAN", "BREAK", "CONTINUE", "DIV",
"DO", "DOWNTO", "ELSE", "END", "FALSE", "FOR", "FUNCTION", "IF",
"INTEGER", "MOD", "NOT", "OF", "OR", "PROCEDURE", "REAL", "RETURN",
"STRING", "THEN", "TO", "TRUE", "VAR", "WHILE", "WITH", "ADD",
"SUB", "MUL", "SLASH", "ASSIGN", "COMMA", "SEMI", "COLON", "EQUAL",
"NOTEQUAL", "LT", "LE", "GT", "GE", "LB", "RB", "LP", "RP",
"LC", "RC", "DOTDOT", "WHITESPACE", "BLOCK_COMMENT", "LINE_COMMENT",
"ID", "INTLIT", "FLOATLIT", "STRINGLIT", "UNCLOSE_STRING", "ILLEGAL_ESCAPE",
"ERROR_CHAR" ]
ruleNames = [ "LETTER", "A", "B", "C", "D", "E", "F", "G", "H", "I",
"J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T",
"U", "V", "W", "X", "Y", "Z", "AND", "ARRAY", "BEGIN",
"BOOLEAN", "BREAK", "CONTINUE", "DIV", "DO", "DOWNTO",
"ELSE", "END", "FALSE", "FOR", "FUNCTION", "IF", "INTEGER",
"MOD", "NOT", "OF", "OR", "PROCEDURE", "REAL", "RETURN",
"STRING", "THEN", "TO", "TRUE", "VAR", "WHILE", "WITH",
"ADD", "SUB", "MUL", "SLASH", "ASSIGN", "COMMA", "SEMI",
"COLON", "EQUAL", "NOTEQUAL", "LT", "LE", "GT", "GE",
"LB", "RB", "LP", "RP", "LC", "RC", "DOTDOT", "WHITESPACE",
"BLOCK_COMMENT", "LINE_COMMENT", "ID", "INTLIT", "FLOATLIT",
"STRINGLIT", "DIGIT", "EXPONENT", "ESCAPE_SQ", "STRING_CHAR",
"STRING_CHARS", "UNCLOSE_STRING", "ILLEGAL_ESCAPE", "ERROR_CHAR" ]
grammarFileName = "MP.g4"
def __init__(self, input=None, output:TextIO = sys.stdout):
super().__init__(input, output)
self.checkVersion("4.7.1")
self._interp = LexerATNSimulator(self, self.atn, self.decisionsToDFA, PredictionContextCache())
self._actions = None
self._predicates = None
def action(self, localctx:RuleContext, ruleIndex:int, actionIndex:int):
if self._actions is None:
actions = dict()
actions[84] = self.STRINGLIT_action
actions[90] = self.UNCLOSE_STRING_action
actions[91] = self.ILLEGAL_ESCAPE_action
actions[92] = self.ERROR_CHAR_action
self._actions = actions
action = self._actions.get(ruleIndex, None)
if action is not None:
action(localctx, actionIndex)
else:
raise Exception("No registered action for:" + str(ruleIndex))
def STRINGLIT_action(self, localctx:RuleContext , actionIndex:int):
if actionIndex == 0:
self.text = self.text[1:-1]
def UNCLOSE_STRING_action(self, localctx:RuleContext , actionIndex:int):
if actionIndex == 1:
raise UncloseString(self.text[1:])
def ILLEGAL_ESCAPE_action(self, localctx:RuleContext , actionIndex:int):
if actionIndex == 2:
raise IllegalEscape(self.text[1:])
def ERROR_CHAR_action(self, localctx:RuleContext , actionIndex:int):
if actionIndex == 3:
raise ErrorToken(self.text)
|
{"/upload/src/main/mp/parser/MPVisitor.py": ["/upload/src/main/mp/parser/MPParser.py"]}
|
22,553
|
sarv19/ass4
|
refs/heads/master
|
/upload/src/main/mp/parser/MPVisitor.py
|
# Generated from main/mp/parser/MP.g4 by ANTLR 4.7.1
from antlr4 import *
if __name__ is not None and "." in __name__:
from .MPParser import MPParser
else:
from MPParser import MPParser
# This class defines a complete generic visitor for a parse tree produced by MPParser.
class MPVisitor(ParseTreeVisitor):
# Visit a parse tree produced by MPParser#program.
def visitProgram(self, ctx:MPParser.ProgramContext):
return self.visitChildren(ctx)
# Visit a parse tree produced by MPParser#decl.
def visitDecl(self, ctx:MPParser.DeclContext):
return self.visitChildren(ctx)
# Visit a parse tree produced by MPParser#vardecl.
def visitVardecl(self, ctx:MPParser.VardeclContext):
return self.visitChildren(ctx)
# Visit a parse tree produced by MPParser#vargroup.
def visitVargroup(self, ctx:MPParser.VargroupContext):
return self.visitChildren(ctx)
# Visit a parse tree produced by MPParser#idlist.
def visitIdlist(self, ctx:MPParser.IdlistContext):
return self.visitChildren(ctx)
# Visit a parse tree produced by MPParser#idtype.
def visitIdtype(self, ctx:MPParser.IdtypeContext):
return self.visitChildren(ctx)
# Visit a parse tree produced by MPParser#primtype.
def visitPrimtype(self, ctx:MPParser.PrimtypeContext):
return self.visitChildren(ctx)
# Visit a parse tree produced by MPParser#arraytype.
def visitArraytype(self, ctx:MPParser.ArraytypeContext):
return self.visitChildren(ctx)
# Visit a parse tree produced by MPParser#signedInt.
def visitSignedInt(self, ctx:MPParser.SignedIntContext):
return self.visitChildren(ctx)
# Visit a parse tree produced by MPParser#funcdecl.
def visitFuncdecl(self, ctx:MPParser.FuncdeclContext):
return self.visitChildren(ctx)
# Visit a parse tree produced by MPParser#plist.
def visitPlist(self, ctx:MPParser.PlistContext):
return self.visitChildren(ctx)
# Visit a parse tree produced by MPParser#pgroup.
def visitPgroup(self, ctx:MPParser.PgroupContext):
return self.visitChildren(ctx)
# Visit a parse tree produced by MPParser#procdecl.
def visitProcdecl(self, ctx:MPParser.ProcdeclContext):
return self.visitChildren(ctx)
# Visit a parse tree produced by MPParser#body.
def visitBody(self, ctx:MPParser.BodyContext):
return self.visitChildren(ctx)
# Visit a parse tree produced by MPParser#stmt.
def visitStmt(self, ctx:MPParser.StmtContext):
return self.visitChildren(ctx)
# Visit a parse tree produced by MPParser#cpstmt.
def visitCpstmt(self, ctx:MPParser.CpstmtContext):
return self.visitChildren(ctx)
# Visit a parse tree produced by MPParser#assign.
def visitAssign(self, ctx:MPParser.AssignContext):
return self.visitChildren(ctx)
# Visit a parse tree produced by MPParser#variable.
def visitVariable(self, ctx:MPParser.VariableContext):
return self.visitChildren(ctx)
# Visit a parse tree produced by MPParser#ifstmt.
def visitIfstmt(self, ctx:MPParser.IfstmtContext):
return self.visitChildren(ctx)
# Visit a parse tree produced by MPParser#whilestmt.
def visitWhilestmt(self, ctx:MPParser.WhilestmtContext):
return self.visitChildren(ctx)
# Visit a parse tree produced by MPParser#forstmt.
def visitForstmt(self, ctx:MPParser.ForstmtContext):
return self.visitChildren(ctx)
# Visit a parse tree produced by MPParser#breakstmt.
def visitBreakstmt(self, ctx:MPParser.BreakstmtContext):
return self.visitChildren(ctx)
# Visit a parse tree produced by MPParser#continuestmt.
def visitContinuestmt(self, ctx:MPParser.ContinuestmtContext):
return self.visitChildren(ctx)
# Visit a parse tree produced by MPParser#returnstmt.
def visitReturnstmt(self, ctx:MPParser.ReturnstmtContext):
return self.visitChildren(ctx)
# Visit a parse tree produced by MPParser#withstmt.
def visitWithstmt(self, ctx:MPParser.WithstmtContext):
return self.visitChildren(ctx)
# Visit a parse tree produced by MPParser#callstmt.
def visitCallstmt(self, ctx:MPParser.CallstmtContext):
return self.visitChildren(ctx)
# Visit a parse tree produced by MPParser#expr.
def visitExpr(self, ctx:MPParser.ExprContext):
return self.visitChildren(ctx)
# Visit a parse tree produced by MPParser#exp1.
def visitExp1(self, ctx:MPParser.Exp1Context):
return self.visitChildren(ctx)
# Visit a parse tree produced by MPParser#exp2.
def visitExp2(self, ctx:MPParser.Exp2Context):
return self.visitChildren(ctx)
# Visit a parse tree produced by MPParser#exp3.
def visitExp3(self, ctx:MPParser.Exp3Context):
return self.visitChildren(ctx)
# Visit a parse tree produced by MPParser#exp4.
def visitExp4(self, ctx:MPParser.Exp4Context):
return self.visitChildren(ctx)
# Visit a parse tree produced by MPParser#exp5.
def visitExp5(self, ctx:MPParser.Exp5Context):
return self.visitChildren(ctx)
# Visit a parse tree produced by MPParser#exp6.
def visitExp6(self, ctx:MPParser.Exp6Context):
return self.visitChildren(ctx)
# Visit a parse tree produced by MPParser#op.
def visitOp(self, ctx:MPParser.OpContext):
return self.visitChildren(ctx)
# Visit a parse tree produced by MPParser#funcall.
def visitFuncall(self, ctx:MPParser.FuncallContext):
return self.visitChildren(ctx)
# Visit a parse tree produced by MPParser#arraycell.
def visitArraycell(self, ctx:MPParser.ArraycellContext):
return self.visitChildren(ctx)
# Visit a parse tree produced by MPParser#boollit.
def visitBoollit(self, ctx:MPParser.BoollitContext):
return self.visitChildren(ctx)
del MPParser
|
{"/upload/src/main/mp/parser/MPVisitor.py": ["/upload/src/main/mp/parser/MPParser.py"]}
|
22,554
|
sarv19/ass4
|
refs/heads/master
|
/upload/src/test/CodeGenSuite.py
|
import unittest
from TestUtils import TestCodeGen
from AST import *
class CheckCodeGenSuite(unittest.TestCase):
# def test_int(self):
# """Simple program: int main() {} """
# input = """procedure main(); begin putInt(100); end"""
# expect = "100"
# self.assertTrue(TestCodeGen.test(input,expect,500))
#
# def test_int_ast(self):
# input = Program([
# FuncDecl(Id("main"),[],[],[
# CallStmt(Id("putInt"),[IntLiteral(5)])])])
# expect = "5"
# self.assertTrue(TestCodeGen.test(input,expect,501))
#
# def test_float_ast(self):
# input = Program([
# FuncDecl(Id("main"),[],[],[
# CallStmt(Id("putFloat"),[FloatLiteral(5.5)])])])
# expect = "5.5"
# self.assertTrue(TestCodeGen.test(input,expect,502))
#
# def test_string_ast(self):
# input = Program([
# FuncDecl(Id("main"),[],[],[
# CallStmt(Id("putString"),[StringLiteral("oh wao")])])])
# expect = "oh wao"
# self.assertTrue(TestCodeGen.test(input,expect,503))
#
# def test_bool_ast(self):
# input = Program([
# FuncDecl(Id("main"),[],[],[
# CallStmt(Id("putBool"),[BooleanLiteral('True')])])])
# expect = "true"
# self.assertTrue(TestCodeGen.test(input,expect,504))
#
# def test_biop_int(self):
# input = Program([
# FuncDecl(Id("main"),[],[],[
# CallStmt(Id("putInt"),[BinaryOp('+',IntLiteral(1),IntLiteral(2))])])])
# expect = "3"
# self.assertTrue(TestCodeGen.test(input,expect,505))
#
# def test_biop_2(self):
# input = Program([
# FuncDecl(Id("main"),[],[],[
# CallStmt(Id("putFloat"),[BinaryOp('+',FloatLiteral(1.2),FloatLiteral(1.2))])])])
# expect = "2.4"
# self.assertTrue(TestCodeGen.test(input,expect,506))
#
# def test_biop_3(self):
# input = Program([
# FuncDecl(Id("main"),[],[],[
# CallStmt(Id("putInt"),[BinaryOp('-',IntLiteral(5),IntLiteral(2))])])])
# expect = "3"
# self.assertTrue(TestCodeGen.test(input,expect,507))
#
# def test_biop_4(self):
# input = Program([
# FuncDecl(Id("main"),[],[],[
# CallStmt(Id("putFloat"),[BinaryOp('-',FloatLiteral(1.2),FloatLiteral(0.2))])])])
# expect = "1.0"
# self.assertTrue(TestCodeGen.test(input,expect,508))
#
# def test_biop_5(self):
# input = Program([
# FuncDecl(Id("main"),[],[],[
# CallStmt(Id("putFloat"),[BinaryOp('+',IntLiteral(1),FloatLiteral(0.2))])])])
# expect = "1.2"
# self.assertTrue(TestCodeGen.test(input,expect,509))
#
# def test_biop_6(self):
# input = Program([
# FuncDecl(Id("main"),[],[],[
# CallStmt(Id("putFloat"),[BinaryOp('+',FloatLiteral(1.2),IntLiteral(1))])])])
# expect = "2.2"
# self.assertTrue(TestCodeGen.test(input,expect,510))
#
# def test_biop_7(self):
# input = Program([
# FuncDecl(Id("main"),[],[],[
# CallStmt(Id("putInt"),[BinaryOp('*',IntLiteral(2),IntLiteral(1))])])])
# expect = "2"
# self.assertTrue(TestCodeGen.test(input,expect,511))
#
# def test_biop_8(self):
# input = Program([
# FuncDecl(Id("main"),[],[],[
# CallStmt(Id("putFloat"),[BinaryOp('*',FloatLiteral(1.2),FloatLiteral(1.1))])])])
# expect = "1.32"
# self.assertTrue(TestCodeGen.test(input,expect,512))
#
# def test_biop_9(self):
# input = Program([
# FuncDecl(Id("main"),[],[],[
# CallStmt(Id("putFloat"),[BinaryOp('*',IntLiteral(1),FloatLiteral(1.1))])])])
# expect = "1.1"
# self.assertTrue(TestCodeGen.test(input,expect,513))
#
# def test_biop_10(self):
# input = Program([
# FuncDecl(Id("main"),[],[],[
# CallStmt(Id("putFloat"),[BinaryOp('+',FloatLiteral(1.1),IntLiteral(1))])])])
# expect = "2.1"
# self.assertTrue(TestCodeGen.test(input,expect,514))
#
# def test_biop_11(self):
# input = Program([
# FuncDecl(Id("main"),[],[],[
# CallStmt(Id("putFloat"),[BinaryOp('/',IntLiteral(5),IntLiteral(1))])])])
# expect = "5.0"
# self.assertTrue(TestCodeGen.test(input,expect,515))
#
# def test_biop_12(self):
# input = Program([
# FuncDecl(Id("main"),[],[],[
# CallStmt(Id("putFloat"),[BinaryOp('/',FloatLiteral(5.0),IntLiteral(1))])])])
# expect = "5.0"
# self.assertTrue(TestCodeGen.test(input,expect,516))
#
# def test_biop_13(self):
# input = Program([
# FuncDecl(Id("main"),[],[],[
# CallStmt(Id("putFloat"),[BinaryOp('/',FloatLiteral(5.0),FloatLiteral(1.0))])])])
# expect = "5.0"
# self.assertTrue(TestCodeGen.test(input,expect,517))
#
# def test_biop_14(self):
# input = Program([
# FuncDecl(Id("main"),[],[],[
# CallStmt(Id("putBool"),[BinaryOp('and',BooleanLiteral('true'), BooleanLiteral('true'))])])])
# expect = "true"
# self.assertTrue(TestCodeGen.test(input,expect,518))
#
# def test_biop_15(self):
# input = Program([
# FuncDecl(Id("main"),[],[],[
# CallStmt(Id("putBool"),[BinaryOp('or',BooleanLiteral('false'), BooleanLiteral('true'))])])])
# expect = "true"
# self.assertTrue(TestCodeGen.test(input,expect,520))
#
# def test_biop_16(self):
# input = Program([
# FuncDecl(Id("main"),[],[],[
# CallStmt(Id("putBool"),[BinaryOp('and',BooleanLiteral('false'), BooleanLiteral('true'))])])])
# expect = "false"
# self.assertTrue(TestCodeGen.test(input,expect,521))
#
# def test_biop_17(self):
# input = Program([
# FuncDecl(Id("main"),[],[],[
# CallStmt(Id("putInt"),[BinaryOp('mod',IntLiteral(5), IntLiteral(2))])])])
# expect = "1"
# self.assertTrue(TestCodeGen.test(input,expect,522))
#
# def test_biop_18(self):
# input = Program([
# FuncDecl(Id("main"),[],[],[
# CallStmt(Id("putInt"),[BinaryOp('div',IntLiteral(5), IntLiteral(2))])])])
# expect = "2"
# self.assertTrue(TestCodeGen.test(input,expect,523))
#
# def test_biop_19(self):
# input = Program([
# FuncDecl(Id("main"),[],[],[
# CallStmt(Id("putBool"),[BinaryOp('>',IntLiteral(5), IntLiteral(2))])])])
# expect = "true"
# self.assertTrue(TestCodeGen.test(input,expect,524))
#
# def test_biop_20(self):
# input = Program([
# FuncDecl(Id("main"),[],[],[
# CallStmt(Id("putBool"),[BinaryOp('<>',IntLiteral(5), IntLiteral(5))])])])
# expect = "false"
# self.assertTrue(TestCodeGen.test(input,expect,525))
#
# def test_biop_21(self):
# input = Program([
# FuncDecl(Id("main"),[],[],[
# CallStmt(Id("putBool"),[BinaryOp('>',FloatLiteral(5.5), IntLiteral(5))])])])
# expect = "true"
# self.assertTrue(TestCodeGen.test(input,expect,526))
#
# def test_biop_22(self):
# input = Program([
# FuncDecl(Id("main"),[],[],[
# CallStmt(Id("putBool"),[BinaryOp('<',FloatLiteral(6.5), FloatLiteral(5.5))])])])
# expect = "false"
# self.assertTrue(TestCodeGen.test(input,expect,527))
#
# def test_biop_23(self):
# input = Program([
# FuncDecl(Id("main"),[],[],[
# CallStmt(Id("putBool"),[BinaryOp('>=',FloatLiteral(4.5), FloatLiteral(5.5))])])])
# expect = "false"
# self.assertTrue(TestCodeGen.test(input,expect,528))
#
# def test_biop_24(self):
# input = Program([
# FuncDecl(Id("main"),[],[],[
# CallStmt(Id("putBool"),[BinaryOp('<=',FloatLiteral(6.5), FloatLiteral(5.5))])])])
# expect = "false"
# self.assertTrue(TestCodeGen.test(input,expect,529))
#
# def test_biop_25(self):
# input = Program([
# FuncDecl(Id("main"),[],[],[
# CallStmt(Id("putBool"),[BinaryOp('=',FloatLiteral(6.5), FloatLiteral(5.5))])])])
# expect = "false"
# self.assertTrue(TestCodeGen.test(input,expect,530))
#
# def test_unaryop_1(self):
# input = Program([
# FuncDecl(Id("main"),[],[],[
# CallStmt(Id("putBool"),[UnaryOp('not', BooleanLiteral('true'))])])])
# expect = "false"
# self.assertTrue(TestCodeGen.test(input,expect,551))
#
# def test_unaryop_2(self):
# input = Program([
# FuncDecl(Id("main"),[],[],[
# CallStmt(Id("putInt"),[UnaryOp('-', IntLiteral(6))])])])
# expect = "-6"
# self.assertTrue(TestCodeGen.test(input,expect,552))
#
# def test_unaryop_3(self):
# input = Program([
# FuncDecl(Id("main"),[],[],[
# CallStmt(Id("putFloat"),[UnaryOp('-', FloatLiteral(6.6))])])])
# expect = "-6.6"
# self.assertTrue(TestCodeGen.test(input,expect,553))
#
# def test_unaryop_4(self):
# input = Program([
# FuncDecl(Id("main"),[],[],[
# CallStmt(Id("putBool"),[UnaryOp('not', BooleanLiteral('false'))])])])
# expect = "true"
# self.assertTrue(TestCodeGen.test(input,expect,554))
#
# def test_assign1(self):
# input = Program([VarDecl(Id('a'), IntType()),
# VarDecl(Id('b'), FloatType()),
# VarDecl(Id('c'), StringType()),
# FuncDecl(Id("main"),[],[],[
# Assign(Id('a'),IntLiteral(5)),
# CallStmt(Id("putInt"),[Id('a')])])])
# expect = "5"
# self.assertTrue(TestCodeGen.test(input,expect,601))
#
# def test_assign3(self):
# input = Program([VarDecl(Id('a'), IntType()),
# VarDecl(Id('b'), FloatType()),
# VarDecl(Id('c'), StringType()),
# FuncDecl(Id("main"),[],[],[
# Assign(Id('b'),IntLiteral(5)),
# CallStmt(Id("putFloat"),[Id('b')])])])
# expect = "5.0"
# self.assertTrue(TestCodeGen.test(input,expect,603))
#
# def test_assign2(self):
# input = Program([VarDecl(Id('a'), IntType()),
# VarDecl(Id('b'), FloatType()),
# VarDecl(Id('c'), StringType()),
# VarDecl(Id('d'), BoolType()),
# FuncDecl(Id("main"),[],[],[
# Assign(Id('d'),BooleanLiteral('True')),
# CallStmt(Id("putBool"),[Id('d')])])])
# expect = "true"
# self.assertTrue(TestCodeGen.test(input,expect,602))
#
# def test_while1(self):
# input = Program([VarDecl(Id('a'), IntType()),
# VarDecl(Id('b'), FloatType()),
# VarDecl(Id('c'), StringType()),
# VarDecl(Id('d'), BoolType()),
# FuncDecl(Id("main"),[],[],[Assign(Id('a'),IntLiteral(4)),
# While(BinaryOp('>',Id('a'), IntLiteral(3)),[Assign(Id('a'), IntLiteral(1))])
# ])])
# expect = ""
# self.assertTrue(TestCodeGen.test(input,expect,701))
#
# def test_while2(self):
# input = Program([VarDecl(Id('a'), IntType()),
# VarDecl(Id('b'), IntType()),
# VarDecl(Id('c'), StringType()),
# VarDecl(Id('d'), BoolType()),
# FuncDecl(Id("main"),[],[],[Assign(Id('a'),IntLiteral(4)),
# Assign(Id('b'), IntLiteral(5)),
# While(BinaryOp('>',Id('a'), IntLiteral(3)),[Assign(Id('a'), IntLiteral(1)),
# While(BinaryOp('>',Id('b'),IntLiteral(2)),
# [Assign(Id('b'), IntLiteral(1))])])
# ])])
# expect = ""
# self.assertTrue(TestCodeGen.test(input,expect,702))
#
# def test_while2(self):
# input = Program([VarDecl(Id('a'), IntType()),
# VarDecl(Id('b'), IntType()),
# VarDecl(Id('c'), StringType()),
# VarDecl(Id('d'), BoolType()),
# FuncDecl(Id("main"),[],[],[Assign(Id('a'),IntLiteral(4)),
# Assign(Id('b'), IntLiteral(5)),
# While(BinaryOp('>',Id('a'), IntLiteral(3)),[Assign(Id('a'),BinaryOp('+',Id('a'),IntLiteral(1)))])
# ])])
# expect = ""
# self.assertTrue(TestCodeGen.test(input,expect,702))
#
# def test_if2(self):
# input = Program([VarDecl(Id('a'), IntType()),
# VarDecl(Id('b'), IntType()),
# VarDecl(Id('c'), StringType()),
# VarDecl(Id('d'), BoolType()),
# FuncDecl(Id("main"),[],[],[
# If(BinaryOp('>',IntLiteral(2),IntLiteral(1)),[CallStmt(Id("putInt"),[IntLiteral(5)]),
# CallStmt(Id("putInt"),[IntLiteral(6)])],[])
# ])])
# expect = "56"
# self.assertTrue(TestCodeGen.test(input,expect,802))
#
# def test_if2(self):
# input = """
# procedure main();
# var a: integer;
# begin
# a:=6;
# if a>=5 then
# a:=a+1;
# putInt(a);
# end
# """
# expect = "7"
# self.assertTrue(TestCodeGen.test(input,expect,802))
#
# def test_if3(self):
# input = """
# procedure main();
# var a: integer;
# begin
# a:=6;
# if (a>=5) and (a<10) then
# begin
# a:=a+1;
# putInt(a);
# end
# else
# putInt(a-1);
# end
# """
# expect = "7"
# self.assertTrue(TestCodeGen.test(input,expect,803))
#
# def test_if4(self):
# input = """
# procedure main();
# var a: integer;
# begin
# a:=6;
# if (a <> 0) or (a>=-1) then
# begin
# a:=a+1;
# putFloat(a);
# end
# else
# putInt(a-1);
# end
# """
# expect = "7.0"
# self.assertTrue(TestCodeGen.test(input,expect,804))
#
# def test_if5(self):
# input = """
# procedure checkEven(a:integer);
# begin
# if a mod 2 = 0 then
# putString("oh yeah");
# else
# putString("no no no");
# end
#
# procedure main();
# var a: integer;
# begin
# checkEven(5);
# putLn();
# checkEven(4);
# putLn();
# checkEven(100);
# end
# """
# expect = "no no no\noh yeah\noh yeah"
# self.assertTrue(TestCodeGen.test(input,expect,805))
#
# def test_if6(self):
# input = """
# var a: integer;
#
# function checkEven(i:integer): boolean;
# begin
# if i mod 2 = 0 then
# begin
# a:=a+2;
# return True;
# end
# else
# begin
# a:=a*2;
# return False;
# end
# end
#
# procedure main();
#
# begin
# a:=1;
# putBoolLn(checkEven(a));
# putIntLn(a);
# a:=2;
# putBoolLn(checkEven(a));
# putInt(a);
# end
# """
# expect = "false\n2\ntrue\n4"
# self.assertTrue(TestCodeGen.test(input,expect,806))
# #
# def test_for1(self):
# input = """
# procedure main();
#
# var a: integer;
# begin
# for a:= 1 to 5 do
# putFloatLn(7);
# end
# """
# expect = "7.0\n7.0\n7.0\n7.0\n7.0\n"
# self.assertTrue(TestCodeGen.test(input,expect,901))
#
# def test_call_expr1(self):
# input = """
# function foo(b:integer):integer;
# BEGIN
# return b+1;
# end
#
# procedure main();
# var a: integer;
# begin
# a:=1;
# putInt(foo(1));
# end
# """
# expect = "2"
# self.assertTrue(TestCodeGen.test(input,expect,1001))
# def test_call_expr2(self):
# input = """
# function increase1(b:integer):integer;
# BEGIN
# return b+1;
# end
#
# function double(b:integer):integer;
# BEGIN
# return b*2;
# end
#
# function half(b:integer):integer;
# BEGIN
# return b div 2;
# end
#
# procedure main();
# begin
# putInt(increase1(half(increase1(double(5)))));
# end
# """
# expect = "6"
# self.assertTrue(TestCodeGen.test(input,expect,1002))
#
# def test_return1(self):
# input = """
# function foo(n:integer):boolean;
# begin
# if (n = 1) or (n = 0 )then
# return false;
# return true;
# end
#
# procedure main();
# BEGIN
# putBool(foo(5));
# end
# """
# expect = "true"
# self.assertTrue(TestCodeGen.test(input,expect,1101))
#
# def test_mixstyle_1(self):
# input="""
# function power(x:integer;a:integer):integer;
# var i,b: integer;
# begin
#
# b:=1;
# for i:=1 to a do
# b:=b*x;
# return b;
# end
# procedure main();
# begin
# putInt(power(2,4));
# end
# """
# expect = "16"
# self.assertTrue(TestCodeGen.test(input,expect,2001))
#
# def test_mixstyle_2(self):
# input="""
# function log(a:integer;b:integer):integer;
# var i:integer;
# begin
#
# i:=0;
# while (a>1) do
# BEGIN
# if (a mod b <> 0 ) then
# break;
# a:=a+1;
# end
# return a;
# end
# procedure main();
# begin
# putInt(log(27,3));
# end
# """
# expect = "28"
# self.assertTrue(TestCodeGen.test(input,expect,2002))
#
#
# def test_mixstyle_3(self):
# input="""
# procedure square(a:integer);
# var x,y:integer;
# begin
#
# for x:=1 to a do
# begin
# for y:=1 to a do
# putString("*");
# putLn();
# end
# end
# procedure main();
# begin
# square(2);
# end
# """
# expect = "**\n**\n"
# self.assertTrue(TestCodeGen.test(input,expect,2003))
#
# def test_mixstyle_4(self):
# input="""
# procedure answer(a:integer);
# begin
# if (a=0) then
# putString("No");
# else
# putString("Yes");
# putLn();
# end
# procedure main();
# begin
# answer(0);
# answer(1);
# end
# """
# expect = "No\nYes\n"
# self.assertTrue(TestCodeGen.test(input,expect,2004))
#
# def test_mixstyle_5(self):
# input="""
# function dectohex(a:integer):string;
# begin
# if (a=0) then
# return "0";
# else if (a=1) then
# return "1";
# else if (a=2) then
# return "2";
# else if (a=3) then
# return "3";
# else if (a=4) then
# return "4";
# else if (a=5) then
# return "5";
# else if (a=6) then
# return "6";
# else if (a=7) then
# return "7";
# else if (a=8) then
# return "8";
# else if (a=9) then
# return "9";
# else if (a=10) then
# return "A";
# else if (a=11) then
# return "B";
# else if (a=12) then
# return "C";
# else if (a=13) then
# return "D";
# else if (a=14) then
# return "E";
# else return "F";
# end
# procedure main();
# begin
# putString(dectohex(10));
# end
# """
# expect = "A"
# self.assertTrue(TestCodeGen.test(input,expect,2005))
#
# def test_mixstyle_7(self):
# input="""
# function min(a:integer;b:integer): integer;
# begin
# if (a>b) then return b;
# else return a;
# end
#
# function mausochung(a:integer;b:integer):integer;
# var x,i: integer;
# begin
#
# x:=min(a,b);
# for i:=2 to x do
# begin
# if (a mod i =0) and (b mod i =0) then break;
# end
# return i;
# end
# procedure main();
# begin
# putInt(mausochung(121,66));
# end
# """
# expect = "11"
# self.assertTrue(TestCodeGen.test(input,expect,2007))
#
# def test_mixstyle_8(self):
# input="""
# function round(a:real): integer;
# var i: integer;
# BEGIN
#
# i:=0;
# while (i+1<a) do i:=i+1;
# return i;
# end
# procedure main();
# begin
# putInt(round(9.5));
# end
# """
# expect = "9"
# self.assertTrue(TestCodeGen.test(input,expect,2008))
#
# def test_mixstyle_9(self):
# input="""
# function divide(a:integer;b:integer): real;
# begin
# return a / b;
# end
# procedure main();
# begin
# putFloat(divide(5,2));
# end
# """
# expect = "2.5"
# self.assertTrue(TestCodeGen.test(input,expect,2009))
#
# def test_mixstyle_10(self):
# input="""
# function isPrime(n:integer):boolean;
# var flag:boolean;
# i:integer;
# begin
# if (n = 1) or (n = 0 )then
# return False;
# if (n = 2) or (n = 3) then
# return true;
# flag := true;
#
# for i:= 2 to (n div 2) do
# begin
# if n - (n div i) * i = 0 then
# begin
# flag := false;
# break;
# end
# end
# return flag;
# end
# procedure prime(a:integer);
# var i: integer;
# begin
#
# for i:=1 to a do
# if isPrime(i) then putIntLn(i);
# end
# procedure main();
# begin
# prime(20);
# end
# """
# expect = "2\n3\n5\n7\n11\n13\n17\n19\n"
# self.assertTrue(TestCodeGen.test(input,expect,2010))
#
# def test_mixstyle_11(self):
# input="""
# function gtokg(a:integer): real;
# var b:real;
# begin
#
# b:=a;
# return b/1000;
# end
# procedure main();
# begin
# putFloat(gtokg(5190));
# end
# """
# expect = "5.19"
# self.assertTrue(TestCodeGen.test(input,expect,2011))
#
# def test_mixstyle_12(self):
# input="""
# procedure loop(step:integer;a:integer;b:integer);
# BEGIN
# while (a<=b) do
# BEGIN
# putIntLn(a);
# a:=a+step;
# end
# end
#
# procedure main();
# begin
# loop(3,10,20);
# end
# """
# expect = "10\n13\n16\n19\n"
# self.assertTrue(TestCodeGen.test(input,expect,2012))
#
# def test_mixstyle_13(self):
# input="""
# function percent(a:integer;b:integer): real;
# var c,d:real;
# begin
# c:=a;
# d:=b;
# return c / d*100;
# end
#
# procedure main();
# begin
# putFloat(percent(3,8));
# end
# """
# expect = "37.5"
# self.assertTrue(TestCodeGen.test(input,expect,2013))
#
# def test_mixstyle_14(self):
# input="""
# function xor(a:boolean;b:boolean): boolean;
# begin
# return (a and (not b)) or ((not a) and b);
# end
#
# procedure main();
# begin
# putBoolLn(xor(true,false));
# putBoolLn(xor(false,false));
# end
# """
# expect = "true\nfalse\n"
# self.assertTrue(TestCodeGen.test(input,expect,2014))
#
# def test_mixstyle_15(self):
# input="""
# procedure letterL(a:integer);
# var i:integer;
# BEGIN
# if (a<2) then
# begin
# putString("fail");
# return;
# end
#
# for i:=1 to a do
# begin
# putString("*");
# putLn();
# end
# for i:=1 to a do
# putString("*");
# end
#
# procedure main();
# begin
# letterL(3);
# end
# """
# expect = "*\n*\n*\n***"
# self.assertTrue(TestCodeGen.test(input,expect,2015))
#
# def test_mixstyle_16(self):
# input="""
# function distance(xa:integer;ya:integer;x0:integer;y0:integer): real;
# begin
# return (xa-x0)*(xa-x0) + (ya-y0)*(ya-y0);
# end
# function isCircle(xa:integer;ya:integer;x0:integer;y0:integer;r:real): boolean;
# BEGIN
# return distance(xa,ya,x0,y0)<= r*r;
# end
#
# procedure main();
# begin
# putBool(isCircle(3,2,0,0,4.5));
# end
# """
# expect = "true"
# self.assertTrue(TestCodeGen.test(input,expect,2016))
#
# def test_mixstyle_17(self):
# input="""
# procedure letterC(a:integer);
# var i:integer;
# BEGIN
# if (a<3) then
# begin
# putString("fail");
# return;
# end
#
# for i:=1 to a do
# putString("*");
# putLn();
# for i:=1 to a do
# begin
# putString("*");
# putLn();
# end
# for i:=1 to a do
# putString("*");
# end
#
# procedure main();
# begin
# letterC(2);
# end
# """
# expect = "fail"
# self.assertTrue(TestCodeGen.test(input,expect,2017))
#
# def test_mixstyle_18(self):
# input="""
# procedure letterI(a:integer);
# var i:integer;
# BEGIN
#
# for i:=1 to a do
# begin
# putString("*");
# putLn();
# end
# end
#
# procedure main();
# begin
# letterI(2);
# end
# """
# expect = "*\n*\n"
# self.assertTrue(TestCodeGen.test(input,expect,2018))
#
# def test_mixstyle_19(self):
# input="""
# procedure square(a:integer);
# var i,n:integer;
# BEGIN
# if (a<2) then
# begin
# putString("fail");
# return;
# end
#
# for i:=1 to a do
# putString("*");
# putLn();
# for i:=1 to a-2 do
# begin
# putString("*");
# for n:=1 to a-2 do
# putString(" ");
# putString("*");
# putLn();
# end
# for i:=1 to a do
# putString("*");
# end
#
# procedure main();
# begin
# square(3);
# end
# """
# expect = "***\n* *\n***"
# self.assertTrue(TestCodeGen.test(input,expect,2019))
#
# def test_mixstyle_20(self):
# input="""
# procedure rec(a:integer;b:integer);
# var i,n:integer;
# BEGIN
# if (a<3) then
# begin
# putString("fail");
# return;
# end
#
# for i:=1 to a do
# begin
# for n:=1 to b do
# putString("*");
# putLn();
# end
# end
#
# procedure main();
# begin
# rec(2,3);
# end
# """
# expect = "fail"
# self.assertTrue(TestCodeGen.test(input,expect,2020))
#
# def test_mixstyle_21(self):
# input="""
# var pi:real;
# function circle_area(a:integer):real;
# BEGIN
# return pi*a*a;
# end
#
# procedure main();
# begin
# pi:=3.14;
# putFloat(circle_area(1));
# end
# """
# expect = "3.14"
# self.assertTrue(TestCodeGen.test(input,expect,2021))
#
# def test_mixstyle_22(self):
# input="""
# var pi:real;
# function sum(a:integer):integer;
# var i,sum: integer;
# BEGIN
#
# sum:=0;
# for i:=1 to a do
# sum:=sum+i;
# return sum;
# end
#
# procedure main();
# begin
# putInt(sum(100));
# end
# """
# expect = "5050"
# self.assertTrue(TestCodeGen.test(input,expect,2022))
#
# def test_mixstyle_23(self):
# input="""
# function sum(a:integer):integer;
# var sum,temp: integer;
# BEGIN
#
# sum:=0;
# with i: integer; do
# for i:=1 to a do
# begin
# with n: integer; do
# begin
# temp:=1;
# for n:=1 to i do
# temp:=temp*a;
# end
# sum:=sum+temp;
# end
# return sum;
# end
#
# procedure main();
# begin
# putInt(sum(2));
# end
# """
# expect = "6"
# self.assertTrue(TestCodeGen.test(input,expect,2023))
#
# def test_mixstyle_24(self):
# input="""
# procedure main();
# var a: boolean;
# i,n : boolean;
# begin
#
# a:=false;
#
# for i:=1 to 20 do
# BEGIN
# for n:=1 to 10 do
# a:= not a;
# a:= not a;
# end
# putBool(a);
# end
# """
# expect = "false"
# self.assertTrue(TestCodeGen.test(input,expect,2024))
#
# def test_mixstyle_25(self):
# input="""
# procedure main();
# var a:integer;
# begin
#
# a:=0;
# while (a>=0) do
# BEGIN
# a:=a+5;
# with b:real; do
# BEGIN
# b:=a/1.5;
# b:=b*3.3;
# a:=a-6;
# end
# with c:boolean; do
# c:= not false;
# end
# putInt(a);
# end
# """
# expect = "-1"
# self.assertTrue(TestCodeGen.test(input,expect,2025))
#
# def test_mixstyle_26(self):
# input="""
# procedure main();
# Var a:integer;
# begin
#
# for a:=1 to 1000 do
# BEGIN
# if a<10 then continue;
# if a<15 then putIntLn(a);
# else break;
# end
# end
# """
# expect = "10\n11\n12\n13\n14\n"
# self.assertTrue(TestCodeGen.test(input,expect,2026))
#
# def test_mixstyle_27(self):
# input="""
# function foo(a: integer): integer;
# begin
# if a>1 then
# return a+foo(a-1);
# else return 1;
# end
# procedure main();
# begin
# putInt(foo(5));
# end
# """
# expect = "15"
# self.assertTrue(TestCodeGen.test(input,expect,2027))
#
# def test_mixstyle_28(self):
# input="""
# function foo(a: integer): integer;
# begin
# if a>1 then
# return a*foo(a-1);
# else return 0;
# end
# procedure main();
#
# begin
# putInt(foo(101));
# end
# """
# expect = "0"
# self.assertTrue(TestCodeGen.test(input,expect,2028))
#
# def test_mixstyle_29(self):
# input="""
# function foo(a: integer): real;
# begin
# if a>1 then
# return a/foo(a-1);
# else return 0.5;
# end
# procedure main();
# begin
# putfloat(foo(3));
# end
# """
# expect = "0.75"
# self.assertTrue(TestCodeGen.test(input,expect,2029))
#
# def test_mixstyle_30(self):
# input="""
# function xor(a:boolean;b:boolean): boolean;
# begin
# return (a and (not b)) or ((not a) and b);
# end
# function foo(a: boolean; i: integer): boolean;
# begin
# if i>1 then
# return xor(a, foo(a,i-1));
# else return false;
# end
# procedure main();
# begin
# putbool(foo(True,3));
# end
# """
# expect = "false"
# self.assertTrue(TestCodeGen.test(input,expect,2030))
#
# def test_mixstyle_31(self):
# input="""
# procedure reverse(n: integer);
# begin
# if n <> 0 then
# begin
# putInt(n mod 10);
# reverse(n div 10);
# end
# end
#
# procedure main();
# begin
# reverse(15);
# end
# """
# expect = "51"
# self.assertTrue(TestCodeGen.test(input,expect,2031))
#
# def test_mixstyle_32(self):
# input="""
# function count(n: integer):integer;
# begin
# if n = 0 then
# return 0;
# return 1+count(n div 10);
# end
#
# procedure main();
# begin
# putInt(count(15112));
# end
# """
# expect = "5"
# self.assertTrue(TestCodeGen.test(input,expect,2032))
#
# def test_mixstyle_33(self):
# input="""
# function logarit(n: integer):integer;
# begin
# if n < 0 then
# return -1;
# if n>=2 then
# return 1+logarit(n div 2);
# else return 0;
# end
#
# procedure main();
# begin
# putInt(logarit(16));
# end
# """
# expect = "4"
# self.assertTrue(TestCodeGen.test(input,expect,2033))
#
# def test_mixstyle_34(self):
# input="""
# function algo(n:integer):integer;
# BEGIN
# if n=1 then return 1;
# return algo(n-1)*n;
# end
#
# function sum(n:integer):integer;
# begin
# if n=1 then return 1;
# return sum(n-1) + algo(n-1)*n;
# end
#
# procedure main();
# begin
# putInt(sum(5));
# end
# """
# expect = "153"
# self.assertTrue(TestCodeGen.test(input,expect,2034))
#
# def test_mixstyle_35(self):
# input="""
# function power(x,y:integer):real;
# BEGIN
# if y=0 then return 1;
# else
# BEGIN
# if y<0 then return power(x,y+1)*(1/x);
# else
# return x*power(x, y-1);
# end
# end
#
#
# procedure main();
# begin
# putFloat(power(5,2));
# end
# """
# expect = "25.0"
# self.assertTrue(TestCodeGen.test(input,expect,2035))
#
# def test_mixstyle_36(self):
# input="""
# function T(n:integer):real;
# BEGIN
# if n=0 then return 1;
# return T(n-1)*2*n;
# end
# function sum(n:integer):real;
# begin
# if n=0 then return 1;
# return T(n-1)+1/T(n);
# end
#
#
# procedure main();
# begin
# putFloat(sum(5));
# end
# """
# expect = "384.00027"
# self.assertTrue(TestCodeGen.test(input,expect,2036))
# def test_mixstyle_37(self):
# input="""
# function power(x,n:real):real;
# BEGIN
# if n=1 then return x;
# return power(x,n-1)*x;
# end
#
# function algo(n:real):real;
# begin
# if n=1 then return 1;
# return algo(n-1)*n;
# end
#
# function power_algo(x,n:real):real;
# begin
# if n=1 then return x;
# return power_algo(x, n-1)+((power(x,n-1)*x)/(algo(n-1)*n));
# end
#
#
# procedure main();
# begin
# putFloat(power_algo(3,10));
# end
# """
# expect = "19.079666"
# self.assertTrue(TestCodeGen.test(input,expect,2037))
# def test_mixstyle_38(self):
# input="""
# procedure main();
# var i,j:integer;
# begin
# i:=7;
# j:=7;
# for i:=1 to 7 do
# begin
# for j:=7-i downto 1 do
# putString("*");
# putLn();
# end
# end
# """
# expect = "******\n*****\n****\n***\n**\n*\n\n"
# self.assertTrue(TestCodeGen.test(input,expect,2038))
# def test_mixstyle_39(self):
# input="""
# procedure main();
# var i,j, k:integer;
# begin
# for i:=1 to 7 do
# begin
# for j:=1 to i do
# putInt(j);
# for k:=7-i downto 1 do
# putString("*");
# putLn();
# end
# end
# """
# expect = "1******\n12*****\n123****\n1234***\n12345**\n123456*\n1234567\n"
# self.assertTrue(TestCodeGen.test(input,expect,2039))
def test_mixstyle_40(self):
input="""
procedure main();
var i,j:integer;
begin
for i:=1 to 9 do
begin
i:=i+2;
for j:=1 to i do
begin
putString("*");
end
putLn();
end
for i:=9 downto 1 do
begin
for j:=i downto 1 do
begin
putString("*");
putLn();
end
end
end
"""
expect = "1******\n12*****\n123****\n1234***\n12345**\n123456*\n1234567\n"
self.assertTrue(TestCodeGen.test(input,expect,2040))
|
{"/upload/src/main/mp/parser/MPVisitor.py": ["/upload/src/main/mp/parser/MPParser.py"]}
|
22,570
|
Pestisy/WCS
|
refs/heads/master
|
/addons/source-python/plugins/wcs/core/helpers/esc/commands.py
|
# ../wcs/core/helpers/esc/commands.py
# ============================================================================
# >> IMPORTS
# ============================================================================
# Python Imports
# Random
from random import choice
# Shlex
from shlex import split
# String
from string import Template
# Time
from time import time
# Source.Python Imports
# Colors
from colors import Color
# CVars
from cvars import ConVar
# Engines
from engines.server import execute_server_command
# Entities
from entities.constants import MoveType
# Filters
from filters.weapons import WeaponClassIter
# Keyvalues
from _keyvalues import KeyValues
# NOTE: Have to prefix it with a _ otherwise it'd import KeyValues from ES Emulator if it's loaded
# Listeners
from listeners.tick import Delay
# Mathlib
from mathlib import Vector
# Messages
from messages import HudMsg
from messages import SayText2
# Players
from players.entity import Player
from players.helpers import index_from_userid
# Translations
from translations.strings import LangStrings
# Weapons
from weapons.restrictions import WeaponRestrictionHandler
# WCS Imports
# Constants
from ...constants import COLOR_DARKGREEN
from ...constants import COLOR_DEFAULT
from ...constants import COLOR_GREEN
from ...constants import COLOR_LIGHTGREEN
from ...constants.paths import CFG_PATH
from ...constants.paths import TRANSLATION_PATH
# Helpers
from .converts import valid_userid
from .converts import valid_userid_and_team
from .converts import convert_userid_to_player
from .converts import convert_userid_to_wcsplayer
from .converts import convert_identifier_to_players
from .converts import convert_userid_identifier_to_players
from .converts import real_value
from .converts import valid_operators
from .converts import split_str
from .converts import deprecated
from .effects import TypedServerCommand
# Players
from ...players import team_data
from ...players.entity import Player as WCSPlayer
# ============================================================================
# >> GLOBAL VARIABLES
# ============================================================================
_aliases = {}
if (TRANSLATION_PATH / 'strings.ini').isfile():
_strings = LangStrings(TRANSLATION_PATH / 'strings')
for key in _strings:
for language, message in _strings[key].items():
_strings[key][language] = message.replace('#default', COLOR_DEFAULT).replace('#green', COLOR_GREEN).replace('#lightgreen', COLOR_LIGHTGREEN).replace('#darkgreen', COLOR_DARKGREEN)
else:
_strings = None
_restrictions = WeaponRestrictionHandler()
_all_weapons = set([x.basename for x in WeaponClassIter('all', ['melee', 'objective'])])
if (CFG_PATH / 'es_WCSlanguage_db.txt').isfile():
_languages = KeyValues.load_from_file(CFG_PATH / 'es_WCSlanguage_db.txt').as_dict()
else:
_languages = {}
# ============================================================================
# >> HELPER FUNCTIONS
# ============================================================================
def validate_userid_after_delay(callback, userid, *args, validator=convert_userid_to_player):
callback(None, validator(userid), *args)
def _format_message(userid, name, args):
if _strings is None:
return tuple(), None
text = _strings.get(name)
if text is None:
return tuple(), None
if userid.isdigit():
try:
players = (Player.from_userid(int(userid)), )
except ValueError:
return tuple(), None
else:
players = convert_identifier_to_players(userid)
if args:
tokens = {}
for i in range(0, len(args), 2):
tokens[args[i]] = args[i + 1]
for language, message in text.items():
text[language] = Template(message).substitute(tokens)
return players, text
# ============================================================================
# >> COMMANDS
# ============================================================================
@TypedServerCommand(['wcs_setfx', 'freeze'])
def wcs_setfx_freeze_command(command_info, player:convert_userid_to_player, operator:valid_operators('='), value:int, time:float=0):
if player is None:
return
if value:
player.move_type = MoveType.NONE
else:
player.move_type = MoveType.WALK
if time > 0:
Delay(time, validate_userid_after_delay, (wcs_setfx_freeze_command, player.userid, '=', not value))
@TypedServerCommand(['wcs_setfx', 'jetpack'])
def wcs_setfx_jetpack_command(command_info, player:convert_userid_to_player, operator:valid_operators('='), value:int, time:float=0):
if player is None:
return
if value:
player.move_type = MoveType.FLY
else:
player.move_type = MoveType.WALK
if time > 0:
Delay(time, validate_userid_after_delay, (wcs_setfx_jetpack_command, player.userid, '=', not value))
@TypedServerCommand(['wcs_setfx', 'god'])
def wcs_setfx_god_command(command_info, player:convert_userid_to_player, operator:valid_operators('='), value:int, time:float=0):
if player is None:
return
player.godmode = value
if time > 0:
Delay(time, validate_userid_after_delay, (wcs_setfx_god_command, player.userid, '=', not value))
@TypedServerCommand(['wcs_setfx', 'noblock'])
def wcs_setfx_noblock_command(command_info, player:convert_userid_to_player, operator:valid_operators('='), value:int, time:float=0):
if player is None:
return
player.noblock = value
if time > 0:
Delay(time, validate_userid_after_delay, (wcs_setfx_noblock_command, player.userid, '=', not value))
@TypedServerCommand(['wcs_setfx', 'burn'])
def wcs_setfx_burn_command(command_info, player:convert_userid_to_player, operator:valid_operators('='), value:int, time:float=0):
if player is None:
return
player.ignite_lifetime((time if time else 999) if value else 0)
@TypedServerCommand(['wcs_setfx', 'speed'])
def wcs_setfx_speed_command(command_info, player:convert_userid_to_player, operator:valid_operators(), value:float, time:float=0):
if player is None:
return
if operator == '=':
old_value = player.speed
player.speed = value
value = old_value - value
elif operator == '+':
player.speed += value
value *= -1
else:
player.speed -= value
if time > 0:
Delay(time, validate_userid_after_delay, (wcs_setfx_speed_command, player.userid, '+', value))
@TypedServerCommand(['wcs_setfx', 'invis'])
def wcs_setfx_invis_command(command_info, player:convert_userid_to_player, operator:valid_operators(), value:int, time:float=0):
if player is None:
return
color = player.color
if operator == '=':
old_value = color.a
player.color = color.with_alpha(value)
value = old_value - value
elif operator == '+':
player.color = color.with_alpha(min(color.a + value, 255))
value *= -1
else:
player.color = color.with_alpha(max(color.a - value, 0))
if time > 0:
Delay(time, validate_userid_after_delay, (wcs_setfx_invis_command, player.userid, '+', value))
@TypedServerCommand(['wcs_setfx', 'invisp'])
def wcs_setfx_invisp_command(command_info, player:convert_userid_to_player, operator:valid_operators(), value:float, time:float=0):
pass # TODO
@TypedServerCommand(['wcs_setfx', 'health'])
def wcs_setfx_health_command(command_info, player:convert_userid_to_player, operator:valid_operators(), value:int, time:float=0):
if player is None:
return
if operator == '=':
old_value = player.health
player.health = value
value = old_value - value
elif operator == '+':
player.health += value
value *= -1
else:
# TODO: Minimum 1 health?
player.health -= value
if time > 0:
Delay(time, validate_userid_after_delay, (wcs_setfx_health_command, player.userid, '+', value))
@TypedServerCommand(['wcs_setfx', 'armor'])
def wcs_setfx_armor_command(command_info, player:convert_userid_to_player, operator:valid_operators(), value:int, time:float=0):
if player is None:
return
if operator == '=':
old_value = player.armor
player.armor = value
value = old_value - value
elif operator == '+':
player.armor += value
value *= -1
else:
player.armor = max(player.armor - value, 0)
if time > 0:
Delay(time, validate_userid_after_delay, (wcs_setfx_armor_command, player.userid, '+', value))
@TypedServerCommand(['wcs_setfx', 'cash'])
def wcs_setfx_cash_command(command_info, player:convert_userid_to_player, operator:valid_operators(), value:int, time:float=0):
if player is None:
return
if operator == '=':
old_value = player.cash
player.cash = value
value = old_value - value
elif operator == '+':
player.cash += value
value *= -1
else:
player.cash = max(player.cash - value, 0)
if time > 0:
Delay(time, validate_userid_after_delay, (wcs_setfx_cash_command, player.userid, '+', value))
@TypedServerCommand(['wcs_setfx', 'gravity'])
def wcs_setfx_gravity_command(command_info, player:convert_userid_to_player, operator:valid_operators(), value:float, time:float=0):
if player is None:
return
if operator == '=':
old_value = player.gravity
player.gravity = value
value = old_value - value
elif operator == '+':
player.gravity += value
value *= -1
else:
player.gravity = max(player.gravity - value, 0)
if time > 0:
Delay(time, validate_userid_after_delay, (wcs_setfx_gravity_command, player.userid, '+', value))
@TypedServerCommand(['wcs_setfx', 'ulti_immunity'])
def wcs_setfx_ulti_immunity_command(command_info, wcsplayer:convert_userid_to_wcsplayer, operator:valid_operators(), value:int, time:float=0):
if wcsplayer is None:
return
if operator == '=':
old_value = wcsplayer.data.get('ulti_immunity', 0)
wcsplayer.data['ulti_immunity'] = value
value = old_value - value
elif operator == '+':
wcsplayer.data['ulti_immunity'] = wcsplayer.data.get('ulti_immunity', 0)
value *= -1
else:
old_value = wcsplayer.data.get('ulti_immunity', 0)
# This is here to prevent them from gaining if there was a time set
if not old_value:
return
wcsplayer.data['ulti_immunity'] = max(old_value - value, 0)
if time > 0:
Delay(time, validate_userid_after_delay, (wcs_setfx_ulti_immunity_command, wcsplayer.userid, '+', value), {'validator':convert_userid_to_wcsplayer})
@TypedServerCommand(['wcs_setfx', 'disguise'])
def wcs_setfx_disguise_command(command_info, wcsplayer:convert_userid_to_player, operator:valid_operators(), value:int, time:float=0):
pass # TODO
@TypedServerCommand(['wcs_setfx', 'longjump'])
def wcs_setfx_longjump_command(command_info, wcsplayer:convert_userid_to_wcsplayer, operator:valid_operators(), value:float, time:float=0):
if wcsplayer is None:
return
if operator == '=':
old_value = wcsplayer.data.get('longjump', 0)
wcsplayer.data['longjump'] = value
value = old_value - value
elif operator == '+':
wcsplayer.data['longjump'] = wcsplayer.data.get('longjump', 0)
value *= -1
else:
old_value = wcsplayer.data.get('longjump', 0)
# This is here to prevent them from gaining if there was a time set
if not old_value:
return
wcsplayer.data['longjump'] = max(old_value - value, 0)
if time > 0:
Delay(time, validate_userid_after_delay, (wcs_setfx_longjump_command, wcsplayer.userid, '+', value), {'validator':convert_userid_to_wcsplayer})
@TypedServerCommand('wcs_removefx')
def wcs_removefx_freeze_command(command_info, *args):
raise NotImplementedError(args)
@TypedServerCommand(['wcsgroup', 'get'])
def wcsgroup_get_command(command_info, key:str, var:ConVar, userid:valid_userid_and_team):
if userid is None:
var.set_int(0)
return
if isinstance(userid, str):
value = team_data[{'T':2, 'CT':3}[userid]].get(key, '0')
else:
wcsplayer = WCSPlayer.from_userid(userid)
value = wcsplayer.data.get(key, '0')
var.set_string(str(value))
@TypedServerCommand(['wcsgroup', 'set'])
def wcsgroup_set_command(command_info, key:str, userid:valid_userid_and_team, value:real_value):
if userid is None:
return
if isinstance(userid, str):
team_data[{'T':2, 'CT':3}[userid]][key] = value
else:
wcsplayer = WCSPlayer.from_userid(userid)
wcsplayer.data[key] = value
@TypedServerCommand('wcs_get_skill_level')
def wcs_get_skill_level_command(command_info, wcsplayer:convert_userid_to_wcsplayer, var:ConVar, index:int):
if wcsplayer is None:
var.set_int(0)
return
active_race = wcsplayer.active_race
skills = [*active_race.settings.config['skills']]
if index >= len(skills):
var.set_int(0)
return
var.set_int(active_race.skills[skills[index]].level)
@TypedServerCommand(['wcs_foreach', 'player'])
def wcs_foreach_command(command_info, var:str, players:convert_userid_identifier_to_players, command:str):
for player in players:
for cmd in [f'es_xset {var} {player.userid}'] + command.split(';'):
execute_server_command(*split(cmd))
@TypedServerCommand('wcs_nearcoord')
def wcs_nearcoord_command(command_info, var:str, players:convert_identifier_to_players, x:float, y:float, z:float, distance:float, command:str):
vector = Vector(x, y, z)
for player in players:
if vector.get_distance(player.origin) <= distance:
for cmd in [f'es_xset {var} {player.userid}'] + command.split(';'):
execute_server_command(*split(cmd))
@TypedServerCommand('wcs_color')
def wcs_color_command(command_info, player:convert_userid_to_player, red:int, green:int, blue:int, alpha:int=255, weapons:int=0):
if player is None:
return
color = Color(red, green, blue, alpha)
player.color = color
if weapons:
for weapon in player.weapons():
weapon.color = color
@TypedServerCommand('wcs_changerace')
def wcs_changerace_command(command_info, wcsplayer:convert_userid_to_wcsplayer, name:str):
if wcsplayer is None:
return
wcsplayer.current_race = name
@TypedServerCommand('wcs_givexp')
def wcs_givexp_command(command_info, wcsplayer:convert_userid_to_wcsplayer, value:int, reason:deprecated=None, forced:deprecated=None):
if wcsplayer is None:
return
wcsplayer.xp += value
@TypedServerCommand('wcs_givelevel')
def wcs_givelevel_command(command_info, wcsplayer:convert_userid_to_wcsplayer, value:int, reason:deprecated=None, forced:deprecated=None):
if wcsplayer is None:
return
wcsplayer.level += value
@TypedServerCommand('wcs_xalias')
def wcs_xalias_command(command_info, alias:str, command:str=None):
if command is None:
for cmd in _aliases[alias].split(';'):
execute_server_command(*split(cmd))
else:
_aliases[alias] = command
@TypedServerCommand('wcs_dalias')
def wcs_dalias_command(command_info, alias:str, *args:str):
for i, value in enumerate(args, 1):
ConVar(f'wcs_tmp{i}').set_string(value)
for cmd in _aliases[alias].split(';'):
execute_server_command(*split(cmd))
@TypedServerCommand('wcs_decimal')
def wcs_decimal_command(command_info, var:ConVar, value:float):
var.set_int(int(round(value)))
@TypedServerCommand('wcs_xtell')
def wcs_xtell_command(command_info, userid:str, name:str, *args:str):
players, message = _format_message(userid, name, args)
for player in players:
SayText2(message[message.get(player.language, 'en')]).send(player.index)
@TypedServerCommand('wcs_xcentertell')
def wcs_xcentertell_command(command_info, userid:str, name:str, *args:str):
players, message = _format_message(userid, name, args)
for player in players:
HudMsg(message[message.get(player.language, 'en')], y=0.2).send(player.index)
@TypedServerCommand('wcs_centermsg')
def wcs_centermsg_command(command_info, *message:str):
HudMsg(' '.join(message), y=0.2).send()
@TypedServerCommand('wcs_centertell')
def wcs_centertell_command(command_info, player:convert_userid_to_player, *message:str):
if player is None:
return
HudMsg(' '.join(message), y=0.2).send(player.index)
@TypedServerCommand('wcs_dealdamage')
def wcs_dealdamage_command(command_info, wcstarget:convert_userid_to_wcsplayer, attacker:valid_userid, damage:int, weapon:str=None):
if wcstarget is None:
return
if attacker is None:
attacker = 0
else:
attacker = index_from_userid(attacker)
wcstarget.take_damage(damage, attacker=attacker, weapon=weapon)
@TypedServerCommand('wcs_getcolors')
def wcs_getcolors_command(command_info, player:convert_userid_to_player, red:ConVar, green:ConVar, blue:ConVar, alpha:ConVar):
if player is None:
return
color = player.color
red.set_int(color.r)
green.set_int(color.g)
blue.set_int(color.b)
alpha.set_int(color.a)
@TypedServerCommand('wcs_getinfo')
def wcs_getinfo_command(command_info, wcsplayer:convert_userid_to_wcsplayer, var:ConVar, attribute:str, key:str):
if wcsplayer is None:
var.set_int(0)
return
if key == 'race':
if attribute == 'realname':
var.set_string(wcsplayer.active_race.name)
elif attribute == 'name':
var.set_string(wcsplayer.active_race.settings.strings['name'])
elif key == 'player':
if attribute == 'realcurrace':
var.set_string(wcsplayer.active_race.name)
elif attribute == 'currace':
var.set_string(wcsplayer.active_race.settings.strings['name'])
@TypedServerCommand('wcs_restrict')
def wcs_restrict_command(command_info, player:convert_userid_to_player, weapons:split_str(), reverse:int=0):
if player is None:
return
if weapons[0] == 'all':
_restrictions.add_player_restrictions(player, *_all_weapons)
return
if 'only' in weapons:
weapons.remove('only')
weapons = _all_weapons.difference(weapons)
_restrictions.player_restrictions[player.userid].clear()
_restrictions.add_player_restrictions(player, *weapons)
@TypedServerCommand('wcs_unrestrict')
def wcs_unrestrict_command(command_info, player:convert_userid_to_player, weapons:split_str()):
if player is None:
return
_restrictions.remove_player_restrictions(player, *weapons)
@TypedServerCommand('wcs_getlanguage')
def wcs_getlanguage_command(command_info, var:ConVar, id_:str, language:str='en'):
var.set_string(_languages.get(language, {}).get(id_, 'n/a'))
@TypedServerCommand('wcs_randplayer')
def wcs_randplayer_command(command_info, var:ConVar, players:convert_identifier_to_players):
players = list(players)
if players:
var.set_int(choice(list(players)).userid)
else:
var.set_int(0)
@TypedServerCommand('wcs_get_cooldown')
def wcs_get_cooldown_command(command_info, wcsplayer:convert_userid_to_wcsplayer, var:ConVar):
active_race = wcsplayer.active_race
for skill in active_race.skills.values():
if 'player_ultimate' in skill.config['event']:
var.set_float(max(skill.cooldown - time(), 0))
break
else:
var.set_int(-1)
@TypedServerCommand('wcs_getcooldown')
def wcs_getcooldown_command(command_info, wcsplayer:convert_userid_to_wcsplayer, var:ConVar):
wcs_get_cooldown_command(command_info, wcsplayer, var)
@TypedServerCommand('wcs_set_cooldown')
def wcs_set_cooldown_command(command_info, wcsplayer:convert_userid_to_wcsplayer, value:float):
active_race = wcsplayer.active_race
for skill in active_race.skills.values():
if 'player_ultimate' in skill.config['event']:
skill.reset_cooldown(value)
break
@TypedServerCommand('wcs_setcooldown')
def wcs_setcooldown_command(command_info, wcsplayer:convert_userid_to_wcsplayer, value:float):
wcs_set_cooldown_command(command_info, wcsplayer, value)
|
{"/addons/source-python/plugins/wcs/core/helpers/esc/commands.py": ["/addons/source-python/plugins/wcs/core/players/__init__.py"]}
|
22,571
|
Pestisy/WCS
|
refs/heads/master
|
/addons/source-python/plugins/wcs/core/players/__init__.py
|
# ../wcs/core/players/__init__.py
# ============================================================================
# >> IMPORTS
# ============================================================================
# Source.Python Imports
# Entities
from entities.entity import Entity
# Listeners
from listeners import OnEntityDeleted
# ============================================================================
# >> ALL DECLARATION
# ============================================================================
__all__ = (
'set_weapon_name',
'team_data',
)
# ============================================================================
# >> GLOBAL VARIABLES
# ============================================================================
team_data = {2:{}, 3:{}}
_global_weapon_entity = None
# ============================================================================
# >> FUNCTIONS
# ============================================================================
def set_weapon_name(name, prefix='wcs'):
global _global_weapon_entity
if _global_weapon_entity is None:
_global_weapon_entity = Entity.create('info_target')
_global_weapon_entity.set_key_value_string('classname', ('' if prefix is None else prefix + '_') + name)
return _global_weapon_entity.index
# ============================================================================
# >> LISTENERS
# ============================================================================
@OnEntityDeleted
def on_entity_deleted(base_entity):
if not base_entity.is_networked():
return
global _global_weapon_entity
if _global_weapon_entity is not None:
if base_entity.index == _global_weapon_entity.index:
_global_weapon_entity = None
|
{"/addons/source-python/plugins/wcs/core/helpers/esc/commands.py": ["/addons/source-python/plugins/wcs/core/players/__init__.py"]}
|
22,572
|
Pestisy/WCS
|
refs/heads/master
|
/addons/source-python/plugins/wcs/core/menus/close.py
|
# ../wcs/core/menus/close.py
# ============================================================================
# >> IMPORTS
# ============================================================================
# WCS Imports
# Menus
from . import raceinfo_detail_menu
from . import raceinfo_skills_menu
from . import raceinfo_skills_detail_menu
from . import raceinfo_race_detail_menu
from . import shopinfo_detail_menu
# Players
from ..players.entity import Player
# ============================================================================
# >> ALL DECLARATION
# ============================================================================
__all__ = ()
# ============================================================================
# >> CLOSE CALLBACKS
# ============================================================================
@raceinfo_detail_menu.register_close_callback
@raceinfo_skills_menu.register_close_callback
@raceinfo_skills_detail_menu.register_close_callback
@raceinfo_race_detail_menu.register_close_callback
def raceinfo_menu_close(menu, client):
Player.from_index(client).data.pop('_internal_raceinfo_category', None)
@shopinfo_detail_menu.register_close_callback
def shopinfo_menu_close(menu, client):
Player.from_index(client).data.pop('_internal_shopinfo_category', None)
|
{"/addons/source-python/plugins/wcs/core/helpers/esc/commands.py": ["/addons/source-python/plugins/wcs/core/players/__init__.py"]}
|
22,573
|
Pestisy/WCS
|
refs/heads/master
|
/addons/source-python/plugins/wcs/core/helpers/esc/vars.py
|
# ../wcs/core/helpers/esc/vars.py
# ============================================================================
# >> IMPORTS
# ============================================================================
# Source.Python Imports
# Core
from core import GAME_NAME
# CVars
from cvars import ConVar
# WCS Imports
# Constants
from ...constants.paths import CFG_PATH
# ============================================================================
# >> ALL DECLARATION
# ============================================================================
__all__ = (
'cvar_wcs_dices',
'cvar_wcs_userid',
'cvars',
)
# ============================================================================
# >> GLOBAL VARIABLES
# ============================================================================
cvar_wcs_dices = [ConVar(f'wcs_dice{i}', '0') for i in [''] + list(range(1, 10))]
cvar_wcs_userid = ConVar('wcs_userid', '0')
cvars = {}
# TODO: What am I even...
for variable in ('ex', 'vector1', 'vector2', 'wcs_x', 'wcs_y', 'wcs_z', 'wcs_x1', 'wcs_y1', 'wcs_z1', 'wcs_x2', 'wcs_y2', 'wcs_z2', 'wcs_x3', 'wcs_y3', 'wcs_z3',
'wcs_ultinotexec', 'wcs_health', 'wcs_divider', 'wcs_speed', 'wcs_gravity', 'wcs_chance', 'wcs_damage', 'wcs_dmg', 'wcs_tmp', 'wcs_tmp1', 'wcs_tmp2', 'wcs_tmp3',
'wcs_tmp4', 'wcs_tmp5', 'wcs_tmp6', 'wcs_tmp7', 'wcs_tmp8', 'wcs_tmp9', 'wcs_tmp10', 'wcs_tmp11', 'wcs_tmp12', 'wcs_tmp13', 'wcs_tmp14', 'wcs_tmp15','wcs_team',
'wcs_team2', 'wcs_gamecheck', 'wcs_phoenix', 'wcs_invis', 'wcs_addhealth', 'wcs_range', 'wcs_fadetimer', 'wcs_multiplier', 'wcs_maxtargets', 'wcs_radius',
'wcs_alive', 'wcs_freezetime', 'wcs_time', 'wcs_money', 'wcs_hpmana', 'wcs_shaketime', 'wcs_bonushp', 'wcs_jetpack', 'wcs_armor', 'wcs_player', 'wcs_dead',
'wcs_uid', 'wcs_lng', 'wcs_rand', 'wcs_wardencounter', 'wcs_trapcounter', 'wcs_healcounter', 'wcs_target', 'wcs_targetid', 'wcs_amount', 'wcs_maxhp', 'wcs_round',
'wcs_maxheal', 'wcs_roundcounter', 'wcs_type', 'wcs_removeid', 'wcs_fxtype', 'wcs_op', 'wcs_params', 'wcs_sucxp', 'wcs_skulls', 'wcs_skulls_amount', 'wcs_res_ui',
'wcs_res_type', 'wcs_res_wep', 'wcs_res_give', 'wcs_res_knife', 'wcs_res_wep_wep', 'wcs_choice', 'wcs_todo', 'wcs_name', 'wcs_mole', 'wcs_exists', 'wcs_smokestack_counter',
'wcs_duration', 'wcs_speed_var', 'wcs_magnitude', 'wcs_healthadd', 'wcs_ammo', 'wcs_game', 'wcs_gamestarted', 'wcs_game_css', 'wcs_game_csgo', 'wcs_game_dods'):
cvars[variable] = ConVar(variable, '0')
if (CFG_PATH / 'var.txt').isfile():
with open(CFG_PATH / 'var.txt') as inputfile:
for variable in [x.strip() for x in inputfile.readlines() if not x.startswith('//') and x.strip()]:
if variable not in cvars:
cvars[variable] = ConVar(variable, '0')
else:
with open(CFG_PATH / 'var.txt', 'w') as outputfile:
outputfile.write('// Place all the server variables you want to set under here.\n')
outputfile.write('// This is only necessary for ESS races and items.\n')
outputfile.write('//\n')
outputfile.write('// Lines with // in front of it will not be read.\n')
cvars['wcs_game'].set_string(GAME_NAME)
cvars['wcs_game_css'].set_string('cstrike')
cvars['wcs_game_csgo'].set_string('csgo')
cvars['wcs_game_dods'].set_string('dod')
|
{"/addons/source-python/plugins/wcs/core/helpers/esc/commands.py": ["/addons/source-python/plugins/wcs/core/players/__init__.py"]}
|
22,596
|
aguajardo/CENSE_Demonstrator
|
refs/heads/master
|
/Drahterfassung_OpenCV/beta modules/Mask_Cleanup.py
|
"""
===========================
@Author : aguajardo<aguajardo.me>
@Version: 1.0 24/03/2017
This is a color detection method that allows to focus onto the
color being detected with color variance.
===========================
"""
import cv2
import numpy as np
import matplotlib.pyplot as plt
import Color_Detection as colors
class Agents:
agents = []
agents_temp = []
def sync_agents():
Agents.agents = np.array(Agents.agents_temp)
def neighbours(x, y, image):
img = image
x_1, y_1, x1, y1 = x - 1, y - 1, x + 1, y + 1
return [img[x_1][y], img[x_1][y1], img[x][y1], img[x1][y1], # u,ur,r,dr
img[x1][y], img[x1][y_1], img[x][y_1], img[x_1][y_1]] # d,dl,l,ul
def alive(agent, mask):
Agents.agents_temp.append(agent)
mask[agent[0]][agent[1]] = 1
def dead(agent, mask):
mask[agent[0]][agent[1]] = 0
Agents.agents_temp.remove([agent[0], agent[1]])
def move(agent, directions, mask):
position = list(agent)
for i in range(len(directions)):
if directions[i] == 0:
if i == 0:
dead(agent, mask)
position[1] += 1
alive(position, mask)
return
if i == 1:
dead(agent, mask)
position[0] += 1
position[1] += 1
alive(position, mask)
return
if i == 2:
dead(agent, mask)
position[0] += 1
alive(position, mask)
return
if i == 3:
dead(agent, mask)
position[0] += 1
position[1] -= 1
alive(position, mask)
return
if i == 4:
dead(agent, mask)
position[1] -= 1
alive(position, mask)
return
if i == 5:
dead(agent, mask)
position[0] -= 1
position[1] -= 1
alive(position, mask)
return
if i == 6:
dead(agent, mask)
position[0] -= 1
alive(position, mask)
return
if i == 7:
dead(agent, mask)
position[0] -= 1
position[1] += 1
alive(position, mask)
return
def reproduce(agent, directions, mask):
position = list(agent)
for i in range(len(directions)):
if directions[i] == 0:
if i == 0:
position[1] += 1
alive(position, mask)
return
if i == 1:
position[0] += 1
position[1] += 1
alive(position, mask)
return
if i == 2:
position[0] += 1
alive(position, mask)
return
if i == 3:
position[0] += 1
position[1] -= 1
alive(position, mask)
return
if i == 4:
position[1] -= 1
alive(position, mask)
return
if i == 5:
position[0] -= 1
position[1] -= 1
alive(position, mask)
return
if i == 6:
position[0] -= 1
alive(position, mask)
return
if i == 7:
position[0] -= 1
position[1] += 1
alive(position, mask)
return
name = 'Bilder\Test6.png'
scale = 1
bands = 8
thresh = 3
color = 25
focus = [25, 35, 255, 35, 255]
images = colors.color_vision(color, focus, bands, thresh, scale, name)
mask = np.array(images[len(images)-1])
roi = mask[190:215, 0:25]
rows, cols = roi.shape
for x in range(cols):
for y in range(rows):
if roi[y][x] == 1:
p_1 = [y+190, x]
break
if roi[y][x] == 1:
p_1 = [y+190, x]
break
rows, cols = mask.shape
print([rows, cols])
new_mask = np.zeros((rows, cols), np.uint8)
ret, mask = cv2.threshold(mask, 0, 1, cv2.THRESH_BINARY_INV)
population = 0
max_population = 4000
pop_change = True
alive(p_1, new_mask)
sync_agents()
cv2.imshow('original', mask*255)
while True:
pop_change = False
for agent in Agents.agents:
temp = cv2.bitwise_or(mask, new_mask)
if population != max_population:
u, ur, r, dr, d, dl, l, ul = neighbours(agent[0], agent[1], temp)
connections = u+ur+r+dr+d+dl+l+ul
directions = [r, dr, d, dl, l, ul, u, ur]
if connections < 8:
reproduce(agent, directions, new_mask)
population += 1
pop_change = True
else:
u, ur, r, dr, d, dl, l, ul = neighbours(agent[0], agent[1], temp)
connections = u + ur + r + dr + d + dl + l + ul
directions = [r, dr, d, dl, l, ul, u, ur]
if connections < 8:
move(agent, directions, new_mask)
pop_change = True
sync_agents()
print(len(Agents.agents))
cv2.imshow('New', * 255)
k = cv2.waitKey(5) & 0xFF
if k == 27:
break
sum = 0
for i in range(rows):
for j in range(cols):
if new_mask[i][j]==1:
sum+=1
print(sum)
cv2.destroyAllWindows()
|
{"/Drahterfassung_OpenCV/Main_Vision.py": ["/Drahterfassung_OpenCV/Color_Detection.py", "/Drahterfassung_OpenCV/Kamera.py"], "/Drahterfassung_OpenCV/Kalibrierung.py": ["/Drahterfassung_OpenCV/Color_Detection.py"], "/Drahterfassung_OpenCV/Kamera.py": ["/Drahterfassung_OpenCV/Kalibrierung.py"]}
|
22,597
|
aguajardo/CENSE_Demonstrator
|
refs/heads/master
|
/Drahterfassung_OpenCV/other/Drahterfassung_PIL.py
|
from PIL import Image
from PIL import ImageChops
import numpy as np
from matplotlib import pyplot as plt
image1=Image.open('Bilder\im1.jpg')
image2=Image.open('Bilder\im2.jpg')
image=ImageChops.subtract(image2, image1)
mask1=Image.eval(image, lambda a: 0 if a<=10 else 255)
mask2=mask1.convert('1')
blank=Image.eval(image, lambda a:0 )
new=Image.composite(image2, blank, mask2)
img=np.array(new)
plt.imshow(img)
plt.show()
|
{"/Drahterfassung_OpenCV/Main_Vision.py": ["/Drahterfassung_OpenCV/Color_Detection.py", "/Drahterfassung_OpenCV/Kamera.py"], "/Drahterfassung_OpenCV/Kalibrierung.py": ["/Drahterfassung_OpenCV/Color_Detection.py"], "/Drahterfassung_OpenCV/Kamera.py": ["/Drahterfassung_OpenCV/Kalibrierung.py"]}
|
22,598
|
aguajardo/CENSE_Demonstrator
|
refs/heads/master
|
/RTDE_Interface/TestB.py
|
import RTDE_Controller_CENSE as rtde
print(rtde.current_position())
rtde.go_start_via_path()
rtde.go_camera()
#rtde.go_start_via_path()
rtde.disconnect_rtde()
|
{"/Drahterfassung_OpenCV/Main_Vision.py": ["/Drahterfassung_OpenCV/Color_Detection.py", "/Drahterfassung_OpenCV/Kamera.py"], "/Drahterfassung_OpenCV/Kalibrierung.py": ["/Drahterfassung_OpenCV/Color_Detection.py"], "/Drahterfassung_OpenCV/Kamera.py": ["/Drahterfassung_OpenCV/Kalibrierung.py"]}
|
22,599
|
aguajardo/CENSE_Demonstrator
|
refs/heads/master
|
/Drahterfassung_OpenCV/other/Drahterfassung_Thresholding.py
|
import cv2
import numpy as np
from matplotlib import pyplot as plt
img = cv2.imread('Bilder\Buddah3.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
img = cv2.resize(img, None, fx=0.125, fy=0.125)
gray = cv2.resize(gray, None, fx=0.125, fy=0.125)
retval, thresh = cv2.threshold(gray, 80, 255, cv2.THRESH_BINARY)
retval2, otsu = cv2.threshold(gray, 80, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)
gaus = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 115, 1)
cv2.imshow('Gray', gray)
cv2.imshow('Image', img)
cv2.imshow('Threshold', thresh)
cv2.imshow('Gaus', gaus)
cv2.imshow('OTSU', otsu)
cv2.waitKey(0)
cv2.destroyAllWindows()
|
{"/Drahterfassung_OpenCV/Main_Vision.py": ["/Drahterfassung_OpenCV/Color_Detection.py", "/Drahterfassung_OpenCV/Kamera.py"], "/Drahterfassung_OpenCV/Kalibrierung.py": ["/Drahterfassung_OpenCV/Color_Detection.py"], "/Drahterfassung_OpenCV/Kamera.py": ["/Drahterfassung_OpenCV/Kalibrierung.py"]}
|
22,600
|
aguajardo/CENSE_Demonstrator
|
refs/heads/master
|
/Drahterfassung_OpenCV/beta modules/Edge_Detection.py
|
"""
===========================
@Author : aguajardo<aguajardo.me>
@Version: 1.0 28/03/2017
This is a color detection method that allows to focus onto the
color being detected with color variance.
===========================
"""
import cv2
import numpy as np
import matplotlib.pyplot as plt
def edge_vision(name, minval, maxval, apsize, scale):
img = cv2.imread(name,0)
img = cv2.resize(img, None, fx=scale, fy=scale)
edges = cv2.Canny(img, minval, maxval, apertureSize=apsize, L2gradient=True)
ret, edges_binary = cv2.threshold(edges, 1, 1, cv2.THRESH_BINARY_INV)
return edges_binary
cv2.imshow('edges', edge_vision('Bilder\Test6.png', 100, 200, 3, 1)*255)
cv2.waitKey(0)
|
{"/Drahterfassung_OpenCV/Main_Vision.py": ["/Drahterfassung_OpenCV/Color_Detection.py", "/Drahterfassung_OpenCV/Kamera.py"], "/Drahterfassung_OpenCV/Kalibrierung.py": ["/Drahterfassung_OpenCV/Color_Detection.py"], "/Drahterfassung_OpenCV/Kamera.py": ["/Drahterfassung_OpenCV/Kalibrierung.py"]}
|
22,601
|
aguajardo/CENSE_Demonstrator
|
refs/heads/master
|
/Drahterfassung_OpenCV/Color_Detection.py
|
"""
===========================
@Author : aguajardo<aguajardo.me>
@Version: 1.0 24/03/2017
This is a color detection method that allows to focus onto the
color being detected with color variance.
===========================
"""
import cv2
import numpy as np
# an image or saved image will be color processed and the masks will be returned in an array
def color_vision(color, focus, bands, thresh, scale, name=None, image=None):
# the bands will be saved into an array of masks
masks = colorDetect(bands, color, focus, scale, name=name, image=image)
rows, cols = masks[2].shape
# an empty numpy array will be generated with the shape of the masks
sum_mask = np.zeros((rows, cols), np.uint8)
# all masks will be added together in a numpy array
for i in range(len(masks)-3):
sum_mask += masks[3+i]
# any value above 'thresh' will be set to 1 and all the other values will be set to 0 creating a binary mask
for i in range(rows):
for j in range(cols):
if sum_mask[i, j] >= thresh:
sum_mask[i, j] = 1
else:
sum_mask[i, j] = 0
# morphological transformations will be applied to the resulting mask to be able to remove noise
kernel = np.ones((1,1), np.uint8)
# sum_mask = cv2.morphologyEx(sum_mask, cv2.MORPH_OPEN, kernel)
# sum_mask = cv2.morphologyEx(sum_mask, cv2.MORPH_CLOSE, kernel)
sum_mask = cv2.dilate(sum_mask, None, iterations=6)
# sum_mask = cv2.morphologyEx(sum_mask, cv2.MORPH_OPEN, kernel)
# sum_mask = cv2.morphologyEx(sum_mask, cv2.MORPH_OPEN, kernel)
# sum_mask = cv2.morphologyEx(sum_mask, cv2.MORPH_CLOSE, kernel)
# sum_mask = cv2.morphologyEx(sum_mask, cv2.MORPH_OPEN, kernel)
sum_mask = cv2.erode(sum_mask, None, iterations=5)
# resulting mask will be applied to the original image to see what the camera sees from the mask and saved to masks
res = cv2.bitwise_and(masks[0], masks[0], mask=sum_mask)
masks.append(res)
masks.append(sum_mask)
return masks
def colorDetect(bands, color, focus, scale, name=None, image=None):
# when no file path was specified but an image was given then process the image if not then return None
if name is None:
if image is None:
return None
else:
img = image
else:
img = cv2.imread(name)
# image is resized
img = cv2.resize(img, None, fx=scale, fy=scale)
# image color format is changed from bgr to rgb
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# the min hue and max hue are specified
minp = color-focus[0]
maxp = color
# an Hue, Saturation, Value color formatted version of the image is saved on 'hsv' and saved to 'list' with original
hsv = cv2.cvtColor(img, cv2.COLOR_RGB2HSV)
list = [img, hsv]
# the min range values for the color detection of OpenCV are initialized
min_a = np.array([minp, focus[1], focus[3]])
max_a = np.array([maxp, focus[2], focus[4]])
# first band is calculated and saved in mask
mask = cv2.inRange(hsv, min_a, max_a)
# the process is repeated for the amount of bands needed
for i in range(bands):
minp += (focus[0])/bands
maxp += (focus[0])/bands
min_a = np.array([minp, focus[1], focus[3]])
max_a = np.array([maxp, focus[2], focus[4]])
mask = cv2.inRange(hsv, min_a, max_a)
ret, mask_binary = cv2.threshold(mask, 1, 1, cv2.THRESH_BINARY)
list.append(mask_binary)
# masks and images are returned in an array of images
return list
# no idea but it was recommended to write this here for the camera preview video stream
def nothing(x):
pass
# a 'real-time' video stream of images processed by the color detection and sliders for the parameters will be shown
def preview_colors(color, focus, bands, thresh, scale):
# object for image capture initialized for camera in port 1
cap = cv2.VideoCapture(0)
# the window is initialized with the name 'Settings'
cv2.namedWindow('Settings')
# trackbars are created and min values are set
cv2.createTrackbar('color', 'Settings', color, 180, nothing)
cv2.createTrackbar('bands', 'Settings', bands, 20, nothing)
cv2.createTrackbar('thresh', 'Settings', thresh, 20, nothing)
cv2.createTrackbar('bandwidth', 'Settings', focus[0], 180, nothing)
cv2.createTrackbar('min S', 'Settings', focus[1], 255, nothing)
cv2.createTrackbar('max S', 'Settings', focus[2], 255, nothing)
cv2.createTrackbar('min H', 'Settings', focus[3], 255, nothing)
cv2.createTrackbar('max H', 'Settings', focus[4], 255, nothing)
cv2.setTrackbarMin('bands', 'Settings', 1)
cv2.setTrackbarMin('thresh', 'Settings', 1)
# video stream is displayed
while True:
# a frame is taken from the camera feed and saved in 'frame'
__, frame = cap.read()
# trackbar positions are read and saved onto the appropriate paramters
color = cv2.getTrackbarPos('color', 'Settings')
bands = cv2.getTrackbarPos('bands', 'Settings')
thresh = cv2.getTrackbarPos('thresh', 'Settings')
focus[0] = cv2.getTrackbarPos('bandwidth', 'Settings')
focus[1] = cv2.getTrackbarPos('min S', 'Settings')
focus[2] = cv2.getTrackbarPos('max S', 'Settings')
focus[3] = cv2.getTrackbarPos('min H', 'Settings')
focus[4] = cv2.getTrackbarPos('max H', 'Settings')
# frame is filtered and displayed
filtered = color_vision(color, focus, bands, thresh, scale, image=frame)
gray = filtered[len(filtered)-1]*255
gray = cv2.resize(gray, None, fx=1/scale, fy=1/scale)
cv2.imshow('Preview', gray)
# waits for the escape key to stop the video stream and save the trackbar values onto the appropriate parameters
k = cv2.waitKey(5) & 0xFF
if k == 27:
break
cv2.destroyAllWindows()
# returns the filter parameters
return bands, thresh, color, focus
|
{"/Drahterfassung_OpenCV/Main_Vision.py": ["/Drahterfassung_OpenCV/Color_Detection.py", "/Drahterfassung_OpenCV/Kamera.py"], "/Drahterfassung_OpenCV/Kalibrierung.py": ["/Drahterfassung_OpenCV/Color_Detection.py"], "/Drahterfassung_OpenCV/Kamera.py": ["/Drahterfassung_OpenCV/Kalibrierung.py"]}
|
22,602
|
aguajardo/CENSE_Demonstrator
|
refs/heads/master
|
/Drahterfassung_OpenCV/other/Drahterfassung_MultiFilterComparison.py
|
import numpy as np
import cv2
import Thinning as skelet
import matplotlib.pyplot as plt
SCALE = 0.1
img = cv2.imread('Bilder\Draht1.jpg')
img = cv2.resize(img, None, fx=SCALE, fy=SCALE)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
hsv = cv2.cvtColor(img, cv2.COLOR_RGB2HSV)
LOWER_GREEN = np.array([15,45,50])
UPPER_GREEN = np.array([35,100,255])
mask = cv2.inRange(hsv, LOWER_GREEN, UPPER_GREEN)
mask = cv2.dilate(mask, None, iterations=6)
mask = cv2.erode(mask, None, iterations=5)
res = cv2.bitwise_and(img, img, mask=mask)
ret, mask_binary = cv2.threshold(mask, 1, 1, cv2.THRESH_BINARY)
skeleton = skelet.zhangSuen(mask_binary)
rows, cols, __ = img.shape
img_skelet = np.zeros((rows, cols, 3), np.uint8)
for i in range(cols):
for j in range(rows):
if skeleton[j, i] == 1:
img_skelet[j, i] = [0, 255, 0]
else:
img_skelet[j, i] = img[j, i]
titles = ['Original Image', 'Result', 'Binary Mask', 'Skeleton']
images = [img, img_skelet, mask_binary, skeleton]
for i in xrange(4):
plt.subplot(2,2,i+1),plt.imshow(images[i])
plt.title(titles[i])
plt.xticks([]),plt.yticks([])
plt.show()
|
{"/Drahterfassung_OpenCV/Main_Vision.py": ["/Drahterfassung_OpenCV/Color_Detection.py", "/Drahterfassung_OpenCV/Kamera.py"], "/Drahterfassung_OpenCV/Kalibrierung.py": ["/Drahterfassung_OpenCV/Color_Detection.py"], "/Drahterfassung_OpenCV/Kamera.py": ["/Drahterfassung_OpenCV/Kalibrierung.py"]}
|
22,603
|
aguajardo/CENSE_Demonstrator
|
refs/heads/master
|
/Drahterfassung_OpenCV/other/Drahterfassung_Farbenerkennung.py
|
import numpy as np
import cv2
import Thinning as skelet
import matplotlib.pyplot as plt
SCALE = 0.25
img = cv2.imread('Bilder\Draht1.jpg')
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
LOWER_GREEN = np.array([10,30,50])
UPPER_GREEN = np.array([40,100,255])
mask = cv2.inRange(hsv, LOWER_GREEN, UPPER_GREEN)
mask = cv2.dilate(mask, None, iterations=5)
mask = cv2.erode(mask, None, iterations=5)
res = cv2.bitwise_and(img, img, mask=mask)
img = cv2.resize(img, None, fx=SCALE, fy=SCALE)
res = cv2.resize(res, None, fx=SCALE, fy=SCALE)
hsv = cv2.resize(hsv, None, fx=SCALE, fy=SCALE)
mask = cv2.resize(mask, None, fx=SCALE, fy=SCALE)
ret,mask_binary = cv2.threshold(mask,1,1,cv2.THRESH_BINARY)
skeleton = skelet.zhangSuen(mask_binary)
titles = ['Original Image','Binary Mask','Result','Skeleton']
images = [img, mask_binary, res, skeleton]
for i in xrange(4):
plt.subplot(2,2,i+1),plt.imshow(images[i],'gray')
plt.title(titles[i])
plt.xticks([]),plt.yticks([])
plt.show()
|
{"/Drahterfassung_OpenCV/Main_Vision.py": ["/Drahterfassung_OpenCV/Color_Detection.py", "/Drahterfassung_OpenCV/Kamera.py"], "/Drahterfassung_OpenCV/Kalibrierung.py": ["/Drahterfassung_OpenCV/Color_Detection.py"], "/Drahterfassung_OpenCV/Kamera.py": ["/Drahterfassung_OpenCV/Kalibrierung.py"]}
|
22,604
|
aguajardo/CENSE_Demonstrator
|
refs/heads/master
|
/Drahterfassung_OpenCV/Main_Vision.py
|
"""
===========================
@Author : aguajardo<aguajardo.me>
@Version: 1.0 24/03/2017
This is a module for detecting a cable
with use of color detection and then
skeletonizing it with the Zhan-Suen
thinning algorithm.
===========================
"""
import cv2
import numpy as np
import matplotlib.pyplot as plt
import Drahterfassung_OpenCV.Color_Detection as colors
import Drahterfassung_OpenCV.Thinning as skelet
import Drahterfassung_OpenCV.Kamera as cam
from operator import itemgetter
# takes a picture and saves it in the file path 'name', processes it and saves the processed image as 'world_img.png'
def take_picture():
# file path
name = "Bilder\camera_picture.png"
# scale at which the image will be processed
scale = 1
# the color focus area will be segmented into color bands this states how many bands will be analyzed
bands = 8
# minimum amount of bands in which a pixel has to be to make it to the resulting mask
thresh = 4
# color hue to be looked for
color = 25
# variation range for hue, saturation, and value e.g.: color+focus = max_hue, color-focus = min_hue
focus = [30, 35, 255, 35, 255]
# a 'real-time' video feed with the color detection filter will be shown
bands, thresh, color, focus = colors.preview_colors(color, focus, bands, thresh, scale)
# an image will be captured and saved in the file path 'name'
cam.capture_image(name)
# a series of masks will be generated and saved onto 'images'
images = colors.color_vision(color, focus, bands, thresh, scale, name=name)
# the resulting mask saved in images will be turned into a binary mask
ret, mask_binary = cv2.threshold(images[len(images)-1], 0, 1, cv2.THRESH_BINARY)
# the dimensions of the image will be saved in rows and cols to calculate the scaling_constant and superimpose image
rows, cols = images[len(images)-1].shape
# the mask is then run through a thinning algorithm to generate a 1 pixel wide line
skeleton = skelet.zhangSuen(mask_binary)
# superimposes the skeleton image on the original image
img_skelet = np.zeros((rows, cols, 3), np.uint8)
for i in range(cols):
for j in range(rows):
if skeleton[j, i] == 1:
img_skelet[j, i] = [255, 0, 0]
else:
img_skelet[j, i] = images[0][j, i]
gray_skeleton = np.zeros((rows, cols, 3), np.uint8)
rows, cols = skeleton.shape
for i in range(rows):
for j in range(cols):
if skeleton[i, j] == 1:
gray_skeleton[i, j] = [255, 255, 255]
else:
gray_skeleton[i, j] = [0, 0, 0]
gray_skeleton = np.delete(gray_skeleton,0,1)
gray_skeleton = np.delete(gray_skeleton,cols-2,1)
images.append(img_skelet)
images.append(skeleton)
cv2.imwrite('Bilder\world_img.png', gray_skeleton)
# returns the images in an array
return images
# plots the HSV, superimposed image, binary mask, and the skeleton
def plot_images(images):
titles = ['Original Image', 'Result', 'Binary Mask', 'Skeleton']
plot = [images[1], images[len(images)-2], images[len(images)-3], images[len(images)-1]]
for i in range(len(plot)):
plt.subplot(2,2,i+1),plt.imshow(plot[i])
plt.title(titles[i])
plt.xticks([]),plt.yticks([])
plt.show()
#plot_images(take_picture())
images = take_picture()
plot_images(images)
|
{"/Drahterfassung_OpenCV/Main_Vision.py": ["/Drahterfassung_OpenCV/Color_Detection.py", "/Drahterfassung_OpenCV/Kamera.py"], "/Drahterfassung_OpenCV/Kalibrierung.py": ["/Drahterfassung_OpenCV/Color_Detection.py"], "/Drahterfassung_OpenCV/Kamera.py": ["/Drahterfassung_OpenCV/Kalibrierung.py"]}
|
22,605
|
aguajardo/CENSE_Demonstrator
|
refs/heads/master
|
/realWorld.py
|
#from World.world import World
from RTDE_Interface import RTDE_Controller_CENSE as rtde
import math
from multiprocessing import Process
import numpy as np
class RealWorld():
pi = math.pi
scaling_constant = .03
turn_constant = 45
def move_left(self):
current_pos = rtde.current_position()
current_pos[0] -= RealWorld.scaling_constant
rtde.move_to_position(current_pos)
pass
def move_right(self):
current_pos = rtde.current_position()
current_pos[0] += RealWorld.scaling_constant
rtde.move_to_position(current_pos)
pass
def move_up(self):
current_pos = rtde.current_position()
current_pos[2] -= RealWorld.scaling_constant
rtde.move_to_position(current_pos)
pass
def move_down(self):
current_pos = rtde.current_position()
current_pos[2] += RealWorld.scaling_constant
rtde.move_to_position(current_pos)
pass
def turn_counter_clockwise(self):
current_pos = rtde.current_position()
current_pos[4] += RealWorld.pi*RealWorld.turn_constant/180
rtde.move_to_position(current_pos)
pass
def turn_clockwise(self):
current_pos = rtde.current_position()
current_pos[4] -= RealWorld.pi*RealWorld.turn_constant/180
rtde.move_to_position(current_pos)
pass
def get_state(self):
# Ich weiss nicht was ich hier machen soll oder welche koordinaten sind in coordinates gespeichert.
pass
def go_to_coordinates(self, coordinates):
new_pos = rtde.current_position()
new_pos[0] = coordinates[0]
new_pos[2] = coordinates[1]
rtde.move_to_position_no_append(new_pos)
pass
def reset(self):
rtde.go_start_via_path()
pass
def take_picture(self):
rtde.disengage()
rtde.go_camera()
rtde.take_picture()
rtde.resume()
rtde.go_start_disengaged()
rtde.engage()
pass
# def test():
# print('CH1')
# RealWorld.reset()
#
# while True:
# print('CH2')
# RealWorld.move_up()
# print('CH3')
# RealWorld.move_down()
# print('CH4')
# RealWorld.move_left()
# print('CH5')
# RealWorld.move_right()
# print('CH6')
# RealWorld.turn_clockwise()
# print('CH7')
# RealWorld.turn_counter_clockwise()
# print('CH8')
# RealWorld.take_picture()
RealWorld = RealWorld()
print('CH1')
RealWorld.reset()
while True:
print('CH2')
RealWorld.move_up()
print('CH3')
RealWorld.move_down()
print('CH4')
RealWorld.move_left()
print('CH5')
RealWorld.move_right()
print('CH6')
RealWorld.turn_clockwise()
print('CH7')
RealWorld.turn_counter_clockwise()
print('CH8')
RealWorld.take_picture()
|
{"/Drahterfassung_OpenCV/Main_Vision.py": ["/Drahterfassung_OpenCV/Color_Detection.py", "/Drahterfassung_OpenCV/Kamera.py"], "/Drahterfassung_OpenCV/Kalibrierung.py": ["/Drahterfassung_OpenCV/Color_Detection.py"], "/Drahterfassung_OpenCV/Kamera.py": ["/Drahterfassung_OpenCV/Kalibrierung.py"]}
|
22,606
|
aguajardo/CENSE_Demonstrator
|
refs/heads/master
|
/Drahterfassung_OpenCV/beta modules/Testing_Colors.py
|
"""
===========================
@Author : aguajardo<aguajardo.me>
@Version: 1.0 24/03/2017
This is a module for taking images from a
webcam and saving them as a png.
===========================
"""
import cv2
import numpy as np
import matplotlib.pyplot as plt
import Color_Detection as colors
def preview_colors(color, focus, bands, thresh, scale):
cap = cv2.VideoCapture(0)
while True:
__, frame = cap.read()
filtered = colors.color_vision(color, focus, bands, thresh, scale, image=frame)
gray = filtered[len(filtered)-1]*255
gray = cv2.resize(gray, None, fx=1/scale, fy=1/scale)
cv2.imshow('filtered', gray)
k = cv2.waitKey(5) & 0xFF
if k == 27:
break
cv2.destroyAllWindows()
return
scale = 0.7
bands = 8
thresh = 3
color = 25
focus = [25, 35, 255, 35, 255]
preview_colors(color, focus, bands, thresh, scale)
|
{"/Drahterfassung_OpenCV/Main_Vision.py": ["/Drahterfassung_OpenCV/Color_Detection.py", "/Drahterfassung_OpenCV/Kamera.py"], "/Drahterfassung_OpenCV/Kalibrierung.py": ["/Drahterfassung_OpenCV/Color_Detection.py"], "/Drahterfassung_OpenCV/Kamera.py": ["/Drahterfassung_OpenCV/Kalibrierung.py"]}
|
22,607
|
aguajardo/CENSE_Demonstrator
|
refs/heads/master
|
/Drahterfassung_OpenCV/Kalibrierung.py
|
"""
===========================
@Author : aguajardo<aguajardo.me>
@Version: 1.0 24/03/2017
This is a camera calibration method.
===========================
"""
import cv2
import numpy as np
import matplotlib.pyplot as plt
from Drahterfassung_OpenCV import Kamera as cam
import time
from Drahterfassung_OpenCV.calibration_vars import objpv
from Drahterfassung_OpenCV.calibration_vars import imgpv
import Drahterfassung_OpenCV.Color_Detection as colors
from operator import itemgetter
class Points:
# Arrays to store object points and image points from all the images.
objpoints = objpv
imgpoints = imgpv
def save_file():
# Save points to python file
with open('calibration_vars.py', 'w') as f:
f.write('from numpy import *')
f.write('\n\nobjpv = %s' % str(Points.objpoints))
f.write('\n\nimgpv = %s' % str(Points.imgpoints))
def calibrate():
# termination criteria
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)
# prepare object points
objp = np.zeros((6*8,3), np.float32)
objp[:,:2] = np.mgrid[0:8,0:6].T.reshape(-1,2)
# empty list to hold the pictures
images = []
# counter for amount of images with chessboard found
count = 0
for j in range(10):
print('Pictures will be taken in 5 seconds.')
time.sleep(5)
# stores 15 pictures into images
for i in range(15):
print ('Taking picture %i out of 15' % int(i+1))
images.append(cam.get_image())
# checks all images for chessboard corners
print ('Scanning for chessboard.')
for img in images:
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Find the chess board corners
ret, corners = cv2.findChessboardCorners(gray, (8,6), None)
# If found, add object points, image points (after refining them) and break the loop to take new images
if ret:
count += 1
Points.objpoints.append(objp)
corners2 = cv2.cornerSubPix(gray,corners,(11,11),(-1,-1),criteria)
Points.imgpoints.append(corners2)
print ('%i chessboards found out of 10' % int(count))
break
cam.release_cam()
save_file()
def undistort_img(img):
# checks to see if camera has been calibrated
if Points.objpoints == [] or Points.imgpoints == []:
print('Camera must be calibrated. Press enter to continue into calibration mode.')
calibrate()
# Image is turn into gray scale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# gets the calibration matrix and optimizes it
ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(Points.objpoints, Points.imgpoints, gray.shape[::-1], None, None)
h, w = img.shape[:2]
newcameramtx, roi = cv2.getOptimalNewCameraMatrix(mtx, dist, (w, h), 1, (w, h))
# undistorts the image
dst = cv2.undistort(img, mtx, dist, None, newcameramtx)
# crop the image
x, y, w, h = roi
# returns the image
dst = dst[y:y + h, x:x + w]
return dst
def perspective_undistort(image):
# scale at which the image will be processed
scale = 1
# the color focus area will be segmented into color bands this states how many bands will be analyzed
bands = 8
# minimum amount of bands in which a pixel has to be to make it to the resulting mask
thresh = 4
# color hue to be looked for
color = 70
# variation range for hue, saturation, and value e.g.: color+focus = max_hue, color-focus = min_hue
focus = [20, 51, 255, 80, 255]
# image is color analyzed to find the location of the corner points
images = colors.color_vision(color, focus, bands, thresh, scale, image=image)
# contours of the corner points are calculated
im2, contours, hierarchy = cv2.findContours(images[len(images)-1], cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# array with the coordinates of the center points of the corner points are saved on an array
center_points = []
for cnt in contours:
(x, y), radius = cv2.minEnclosingCircle(cnt)
center_points.append([int(y), int(x), int(x+y)])
center_points = sort_points(center_points)
# center point coordinates and end coordinates for the corner center points are prepped for the transformation
rows, cols = images[len(images)-1].shape
pts1 = np.float32(np.delete(center_points,2,1))
print(rows, cols)
print(pts1)
pts2 = np.float32([[-10, -10], [rows-10, -10], [-10, cols], [rows-10, cols]])
M = cv2.getPerspectiveTransform(pts1, pts2)
undistorted = cv2.warpPerspective(image, M, (cols, rows))
print(undistorted.shape)
return undistorted
def sort_points(center_points):
new_pts = tuple(sorted(center_points, key=itemgetter(2,0)))
return new_pts
|
{"/Drahterfassung_OpenCV/Main_Vision.py": ["/Drahterfassung_OpenCV/Color_Detection.py", "/Drahterfassung_OpenCV/Kamera.py"], "/Drahterfassung_OpenCV/Kalibrierung.py": ["/Drahterfassung_OpenCV/Color_Detection.py"], "/Drahterfassung_OpenCV/Kamera.py": ["/Drahterfassung_OpenCV/Kalibrierung.py"]}
|
22,608
|
aguajardo/CENSE_Demonstrator
|
refs/heads/master
|
/Drahterfassung_OpenCV/other/Drahterfassung_Hough.py
|
import numpy as np
import cv2
from PIL import Image
img = cv2.imread('Bilder\Draht1.jpg')
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray,50,150,apertureSize = 3)
minLineLength = 1
maxLineGap = 20
lines = cv2.HoughLinesP(edges,1,np.pi/180,100,minLineLength,maxLineGap)
print('Lines found: {}'.format(len(lines)))
for i in range(0,len(lines)):
for x1,y1,x2,y2 in lines[i]:
cv2.line(img,(x1,y1),(x2,y2),(0,255,0),10)
img = cv2.resize(img, None, fx=0.25, fy=0.25)
cv2.imshow('houghlines5.jpg',img)
cv2.waitKey()
|
{"/Drahterfassung_OpenCV/Main_Vision.py": ["/Drahterfassung_OpenCV/Color_Detection.py", "/Drahterfassung_OpenCV/Kamera.py"], "/Drahterfassung_OpenCV/Kalibrierung.py": ["/Drahterfassung_OpenCV/Color_Detection.py"], "/Drahterfassung_OpenCV/Kamera.py": ["/Drahterfassung_OpenCV/Kalibrierung.py"]}
|
22,609
|
aguajardo/CENSE_Demonstrator
|
refs/heads/master
|
/Drahterfassung_OpenCV/Kamera.py
|
"""
===========================
@Author : aguajardo<aguajardo.me>
@Version: 1.0 24/03/2017
This is a module for taking images from a
webcam and saving them as a png.
===========================
"""
import cv2
import numpy as np
import matplotlib.pyplot as plt
import Drahterfassung_OpenCV.Kalibrierung as cal
# camera port and amount of frames to be discarded while focusing
port = 0
frames = 25
# class with variables needed to know if camera is in use or not
class Kamera:
cam = None
released = True
# camera is released for further use
def release_cam():
Kamera.cam = None
Kamera.released = True
# image is taken and returned
def get_image():
if Kamera.released:
Kamera.cam = cv2.VideoCapture(port)
Kamera.released = False
im = get_image_internal()
return im
# image is taken and returned without initializing the camera
def get_image_internal():
retval = False
while not retval:
retval, im = Kamera.cam.read()
return im
# image is taken, undistorted and saved to the file path in 'name'
def capture_image(name):
if Kamera.released:
Kamera.cam = cv2.VideoCapture(port)
Kamera.released = False
for i in range(frames):
temp = get_image_internal()
camera_capture = get_image_internal()
release_cam()
# image is transformed into undistorted version using the module Kalibrierung.py
#camera_capture = cal.undistort_img(camera_capture)
# image perspective is undistorted using the module Kalibrierung.py
camera_capture = cal.perspective_undistort(camera_capture)
cv2.imwrite(name, camera_capture)
|
{"/Drahterfassung_OpenCV/Main_Vision.py": ["/Drahterfassung_OpenCV/Color_Detection.py", "/Drahterfassung_OpenCV/Kamera.py"], "/Drahterfassung_OpenCV/Kalibrierung.py": ["/Drahterfassung_OpenCV/Color_Detection.py"], "/Drahterfassung_OpenCV/Kamera.py": ["/Drahterfassung_OpenCV/Kalibrierung.py"]}
|
22,610
|
aguajardo/CENSE_Demonstrator
|
refs/heads/master
|
/Drahterfassung_OpenCV/other/Drahterfassung_BackgroundSubstractorMOG.py
|
import numpy as np
import cv2
import sys
bgSub=cv2.createBackgroundSubtractorMOG2()
for i in range(1,15):
bgImageFile = "bg{0}.jpg".format(i)
bg = cv2.imread(bgImageFile)
bg=cv2.resize(bg,None,fx=0.125,fy=0.125)
bgSub.apply(bg, learningRate=0.5)
stillFrame=cv2.imread('Still1.jpg')
stillFrame=cv2.resize(stillFrame,None,fx=0.125,fy=0.125)
fgmask=bgSub.apply(stillFrame, learningRate=0)
cv2.imshow('Original', stillFrame)
cv2.imshow('Masked', fgmask)
cv2.waitKey(0)
cv2.destroyAllWindows()
|
{"/Drahterfassung_OpenCV/Main_Vision.py": ["/Drahterfassung_OpenCV/Color_Detection.py", "/Drahterfassung_OpenCV/Kamera.py"], "/Drahterfassung_OpenCV/Kalibrierung.py": ["/Drahterfassung_OpenCV/Color_Detection.py"], "/Drahterfassung_OpenCV/Kamera.py": ["/Drahterfassung_OpenCV/Kalibrierung.py"]}
|
22,611
|
aguajardo/CENSE_Demonstrator
|
refs/heads/master
|
/RTDE_Interface/RTDE_Controller_CENSE_2.py
|
"""
===========================
@Author : aguajardo<aguajardo.me>
@Version: 1.0 24/03/2017
This is a module for RTDE Control
of a UR5 from Universal Robots.
===========================
"""
import sys
import logging
import RTDE_Interface.rtde_client.rtde.rtde as rtde
import RTDE_Interface.rtde_client.rtde.rtde_config as rtde_config
from operator import sub,abs
# begin variable and object setup
ROBOT_HOST = '169.254.203.187'
ROBOT_PORT = 30004
config_filename = 'ur5_configuration_CENSE_test.xml'
START_POSITION = [0.336,- 0.378, 0.730, 0, 0, 0]
CENTER_POSITION = [-0.12028426334880883, 0.22592083702208404, 0.6888784830906385, -1.1776661923930953, -1.1603887788030312, -1.2277226782518533]
CAMERA_POSITION = [-1.5806005636798304, -2.0574949423419397, 2.765082836151123, -3.0610531012164515, -1.6087492148028772, -1.5503385702716272]
RTDE_PROTOCOL_VERSION = 1
keep_running = True
MAX_ERROR = 0.001
logging.getLogger().setLevel(logging.INFO)
conf = rtde_config.ConfigFile(config_filename)
state_names, state_types = conf.get_recipe('state')
setp_names, setp_types = conf.get_recipe('setp')
watchdog_names, watchdog_types = conf.get_recipe('watchdog')
joint_names, joint_types = conf.get_recipe('joint')
con = rtde.RTDE(ROBOT_HOST, ROBOT_PORT)
# end variable and object setup
# Initiate connection
con.connect()
# get_controller_version is used to know if minimum requirements are met
con.get_controller_version()
# Compares protocol version of the robot with that of the program. Mismatch leads to system exit
if not con.negotiate_protocol_version(RTDE_PROTOCOL_VERSION):
sys.exit()
# Send configuration for output and input recipes
con.send_output_setup(state_names, state_types)
#print('check point 1')
setp = con.send_input_setup(setp_names, setp_types)
#print('check point 2')
# Send configuration for the watchdog timer (1 Hz) input recipe
watchdog = con.send_input_setup(watchdog_names, watchdog_types)
# Joint trigger: when 0 the points given are interpreted as pose, when 1 as joint angles
joint = con.send_input_setup(joint_names, joint_types)
# Set input registers (double) to 0
setp.input_double_register_0 = 0
setp.input_double_register_1 = 0
setp.input_double_register_2 = 0
setp.input_double_register_3 = 0
setp.input_double_register_4 = 0
setp.input_double_register_5 = 0
# Set input register for watchdog timer to 0 so that it can be reset
watchdog.input_int_register_0 = 0
# Set input register for joint to 0
joint.input_int_register_1 = 0
# Starts data sync
def start_sync():
# start data exchange. If the exchange fails it returns 'Failed'
if not con.send_start():
return 'Failed'
# Pauses the data sync
def pause_sync():
con.send_pause()
# Disconnects the RTDE
def disconnect_rtde():
con.disconnect()
# current_position gives the current position of the TCP relative to the defined Cartesian plane in list format
def current_position():
# Checks for the state of the connection
state = con.receive()
# If output config not initialized, RTDE synchronization is inactive, or RTDE is disconnected it returns 'Failed'
if state is None:
return 'Failed'
# if the joint values are needed then return joint values
if state.output_int_register_1 == 1:
# If successful it returns the list with the current joint position
return state.actual_q
# If successful it returns the list with the current TCP position
return state.actual_TCP_pose
# This class hold the list of all positions
class Positions:
start_sync()
all_positions = [START_POSITION]
# setp_to_list converts a serialized data object to a list
def setp_to_list(setp):
list = []
for i in range(0,6):
list.append(setp.__dict__["input_double_register_%i" % i])
return list
# list_to_setp converts a list int0 serialized data object
def list_to_setp(setp, list):
for i in range (0,6):
setp.__dict__["input_double_register_%i" % i] = list[i]
return setp
# move_to_position changes the position and orientation of the TCP of the robot relative to the defined Cartesian plane
def move_to_position(new_pos):
# Checks for the state of the connection
state = con.receive()
# If output config not initialized, RTDE synchronization is inactive, or RTDE is disconnected it returns 'Failed'
if state is None:
return 'Failed'
# Set joint to 0
joint.input_int_register_1 = 0
con.send(joint)
# Will try to move to position till current_position() is within a max error range from new_pos
while max(map(abs, map(sub, current_position(), new_pos))) >= MAX_ERROR:
# Checks for the state of the connection
state = con.receive()
# If output config not initialized, RTDE synchronization is inactive, or RTDE is disconnected it returns 'Failed'
if state is None:
return 'Failed'
# The output_int_register_0 defines if the robot is in motion.
if state.output_int_register_0 != 0:
# Changes the value from setp to the new position
list_to_setp(setp, new_pos)
# Send new position
con.send(setp)
con.send(watchdog)
# If successful the RTDE sync is paused, new position is added to all_positions, and it returns 'SUCCESS'
Positions.all_positions.append(new_pos)
return 'SUCCESS'
# move_to_position changes the position and orientation of the TCP of the robot relative to the defined Cartesian plane
def move_to_position_no_append(new_pos):
# Will try to move to position till current_position() is within a max error range from new_pos
while max(map(abs, map(sub, current_position(), new_pos))) >= MAX_ERROR:
# Checks for the state of the connection
state = con.receive()
# If output config not initialized, RTDE synchronization is inactive, or RTDE is disconnected it returns 'Failed'
if state is None:
return 'Failed'
# The output_int_register_0 defines if the robot is in motion.
if state.output_int_register_0 != 0:
# Changes the value from setp to the new position
list_to_setp(setp, new_pos)
# Send new position
con.send(setp)
con.send(watchdog)
# If successful the RTDE sync is paused, new position is added to all_positions, and it returns 'SUCCESS'
return 'SUCCESS'
# go_start_via_path moves the robot back to the defined starting position through all recorded positions
def go_start_via_path():
# Set joint to 0
print(setp.__dict__)
joint.input_int_register_1 = 0
con.send(joint)
# Makes a new list which is the reverses of all_positions to be able to go from end position to start position
rev_all_positions = list(Positions.all_positions)
rev_all_positions.reverse()
move_to_position_no_append(rev_all_positions[0])
# For all the positions in all_positions it implements the function move_to_position
while len(rev_all_positions) != 1:
move_response = 'Failed'
# It will try the movement till 'SUCCESS' is returned
while move_response == 'Failed':
move_response = move_to_position_no_append(rev_all_positions[0])
# It removes the position from all_positions
rev_all_positions.remove(rev_all_positions[0])
# Moves to start position
move_to_position_no_append(rev_all_positions[0])
# If successful all_positions will be cleared and redefined with initial position
Positions.all_positions = list(rev_all_positions)
return 'SUCCESS'
# go_camera moves the robot to the position defined as camera position
def go_camera():
# Checks for the state of the connection
state = con.receive()
# If output config not initialized, RTDE synchronization is inactive, or RTDE is disconnected it returns 'Failed'
if state is None:
return 'Failed'
# Set joint to 0
joint.input_int_register_1 = 0
con.send(joint)
move_to_position_no_append(CENTER_POSITION)
# Tell the server the following points are to be interpreted as joint values
joint.input_int_register_1 = 1
con.send(joint)
move_to_position_no_append(CAMERA_POSITION)
# Set joint to 0
joint.input_int_register_1 = 0
con.send(joint)
# Set pose to 0 so the robot will not continue moving
# Set input registers (double) to 0
setp.input_double_register_0 = 0
setp.input_double_register_1 = 0
setp.input_double_register_2 = 0
setp.input_double_register_3 = 0
setp.input_double_register_4 = 0
setp.input_double_register_5 = 0
con.send(setp)
return 'SUCCESS'
|
{"/Drahterfassung_OpenCV/Main_Vision.py": ["/Drahterfassung_OpenCV/Color_Detection.py", "/Drahterfassung_OpenCV/Kamera.py"], "/Drahterfassung_OpenCV/Kalibrierung.py": ["/Drahterfassung_OpenCV/Color_Detection.py"], "/Drahterfassung_OpenCV/Kamera.py": ["/Drahterfassung_OpenCV/Kalibrierung.py"]}
|
22,612
|
aguajardo/CENSE_Demonstrator
|
refs/heads/master
|
/Drahterfassung_OpenCV/other/Drahterfassung_GrabCut.py
|
import numpy as np
import cv2
from matplotlib import pyplot as plt
from PIL import Image
# Import image with PIL
img = Image.open('Bilder\Draht1.jpg')
# Rotate image 180 degrees
img_r = img.rotate(180, expand=True)
# Transform image into Numpy Array
img_r = np.array(img_r)
# RGB to BGR
# img_r = img_r[:, :, ::-1].copy()
# Resize image
img_rs = cv2.resize(img_r, None, fx=0.125, fy=0.125, interpolation=cv2.INTER_CUBIC)
# Create a mask for the image
mask = np.zeros(img_rs.shape[:2], np.uint8)
# Create models for both the background and foreground
bgdModel = np.zeros((1, 65), np.float64)
fgdModel = np.zeros((1, 65), np.float64)
rect = (50, 110, 440, 275)
cv2.grabCut(img_rs,mask,rect,bgdModel,fgdModel,5,cv2.GC_INIT_WITH_RECT)
mask2 = np.where((mask == 2) | (mask == 0), 0, 1).astype('uint8')
img_m = img_rs*mask2[:, :, np.newaxis]
# Show image
plt.imshow(img_m)
plt.show()
|
{"/Drahterfassung_OpenCV/Main_Vision.py": ["/Drahterfassung_OpenCV/Color_Detection.py", "/Drahterfassung_OpenCV/Kamera.py"], "/Drahterfassung_OpenCV/Kalibrierung.py": ["/Drahterfassung_OpenCV/Color_Detection.py"], "/Drahterfassung_OpenCV/Kamera.py": ["/Drahterfassung_OpenCV/Kalibrierung.py"]}
|
22,613
|
aguajardo/CENSE_Demonstrator
|
refs/heads/master
|
/RTDE_Interface/TestA.py
|
import RTDE_Controller_CENSE as rtde
while True:
print(rtde.Positions.all_positions)
rtde.go_start_via_path()
print ('Start Position')
rtde.move_to_position([-0.10782, 0.3822, 0.5866, 0.0, -0.136, 1.593])
print ('Position 1')
rtde.move_to_position([-0.10782, 0.4822, 0.5866, 0.0, -0.136, 1.593])
print ('Position 2')
rtde.move_to_position([-0.10782, 0.4822, 0.4866, 0.0, -0.136, 1.593])
print ('Position 3')
rtde.move_to_position([-0.10782, 0.3822, 0.4866, 0.0, -0.136, 1.593])
print ('Position 4')
rtde.go_start_via_path()
print ('Start Position')
print(rtde.Positions.all_positions)
rtde.disconnect_rtde()
|
{"/Drahterfassung_OpenCV/Main_Vision.py": ["/Drahterfassung_OpenCV/Color_Detection.py", "/Drahterfassung_OpenCV/Kamera.py"], "/Drahterfassung_OpenCV/Kalibrierung.py": ["/Drahterfassung_OpenCV/Color_Detection.py"], "/Drahterfassung_OpenCV/Kamera.py": ["/Drahterfassung_OpenCV/Kalibrierung.py"]}
|
22,614
|
aguajardo/CENSE_Demonstrator
|
refs/heads/master
|
/Drahterfassung_OpenCV/beta modules/Mask_Cleanup_2.py
|
"""
===========================
@Author : aguajardo<aguajardo.me>
@Version: 1.0 24/03/2017
This is a color detection method that allows to focus onto the
color being detected with color variance.
===========================
"""
import cv2
import numpy as np
import matplotlib.pyplot as plt
import Color_Detection as colors
from random import randint
class Agents:
agents = []
agents_temp = []
def sync_agents():
Agents.agents = np.array(Agents.agents_temp)
def neighbours(x, y, image):
img = image
x_1, y_1, x1, y1 = x - 1, y - 1, x + 1, y + 1
return [img[x_1][y], img[x][y1], # u,ur,r,dr
img[x1][y], img[x][y_1]] # d,dl,l,ul
def alive(agent, mask):
Agents.agents_temp.append(agent)
mask[agent[0]][agent[1]] = 1
def dead(agent, mask):
mask[agent[0]][agent[1]] = 0
Agents.agents_temp.remove([agent[0], agent[1]])
def reproduce(agent, directions, mask):
position = list(agent)
random = randint(0, 3)
if directions[random] == 0:
if random == 0:
position[1] += 1
alive(position, mask)
return
if random == 1:
position[0] += 1
alive(position, mask)
return
if random == 2:
position[1] -= 1
alive(position, mask)
return
if random == 3:
position[0] -= 1
alive(position, mask)
return
name = 'Bilder\Test6.png'
scale = 1
bands = 8
thresh = 3
color = 25
focus = [25, 35, 255, 35, 255]
images = colors.color_vision(color, focus, bands, thresh, scale, name)
mask = np.array(images[len(images)-1])
roi = mask[190:215, 0:25]
rows, cols = roi.shape
for x in range(cols):
for y in range(rows):
if roi[y][x] == 1:
p_1 = [y+190+1, x+1]
break
if roi[y][x] == 1:
p_1 = [y+190+1, x+1]
break
cv2.imshow('roi', roi*255)
rows, cols = mask.shape
print([rows, cols])
new_mask = np.zeros((rows, cols), np.uint8)
ret, mask = cv2.threshold(mask, 0, 1, cv2.THRESH_BINARY_INV)
alive(p_1, new_mask)
sync_agents()
cv2.imshow('original', mask*255)
while True:
temp = cv2.bitwise_or(mask, new_mask)
u, r, d, l = neighbours(Agents.agents[len(Agents.agents)-1][0], Agents.agents[len(Agents.agents)-1][1], temp)
connections = u+r+d+l
directions = [r, d, l, u]
if connections <= 2:
reproduce(Agents.agents[len(Agents.agents)-1], directions, new_mask)
sync_agents()
else:
length = len(Agents.agents)
while len(Agents.agents)!= 1 and len(Agents.agents) > length-4:
dead(Agents.agents[len(Agents.agents)-1], new_mask)
sync_agents()
print(len(Agents.agents))
cv2.imshow('New', temp * 255)
k = cv2.waitKey(5) & 0xFF
if k == 27:
break
sum = 0
for i in range(rows):
for j in range(cols):
if new_mask[i][j]==1:
sum+=1
print(sum)
cv2.destroyAllWindows()
|
{"/Drahterfassung_OpenCV/Main_Vision.py": ["/Drahterfassung_OpenCV/Color_Detection.py", "/Drahterfassung_OpenCV/Kamera.py"], "/Drahterfassung_OpenCV/Kalibrierung.py": ["/Drahterfassung_OpenCV/Color_Detection.py"], "/Drahterfassung_OpenCV/Kamera.py": ["/Drahterfassung_OpenCV/Kalibrierung.py"]}
|
22,620
|
jung-bak/Arqui2_Proyecto_1
|
refs/heads/main
|
/BloqueCache.py
|
class BloqueCache:
def __init__(self, identifier):
self.identifier = identifier
self.estado = 'I'
self.direccion = '0'
self.dato = '0'
#Setter and Getters for Estado
def b_estadoSet(self,nuevoEstado):
self.estado = nuevoEstado
return
def b_estadoGet(self):
return self.estado
#Setter and Getters for Direccion
def b_direccionSet(self,nuevaDireccion):
self.direccion = nuevaDireccion
return
def b_direccionGet(self):
return self.direccion
#Setter and Getters for Dato
def b_datoSet(self,nuevoDato):
self.dato = nuevoDato
return
def b_datoGet(self):
return self.dato
|
{"/Processor.py": ["/Cache.py"], "/GUI.py": ["/Processor.py", "/Memory.py", "/Snoop.py"], "/Cache.py": ["/SetCache.py"], "/SetCache.py": ["/BloqueCache.py"]}
|
22,621
|
jung-bak/Arqui2_Proyecto_1
|
refs/heads/main
|
/Processor.py
|
import time
from numpy import array2string
from Cache import Cache
class Processor:
def __init__(self, identifier, memory, timer):
self.identifier = identifier
self.timer = timer
self.memory = memory
self.Cache = Cache(self.memory)
self.Publisher = None
self.lastInstruction = ""
self.previousInstruction = ""
self.instructionPrint = ""
self.lastMessage = ""
def instruction(self, inst, direccionMemoria, valor):
self.previousInstruction = self.lastInstruction
self.lastInstruction = ""
if (inst == 0):
self.lastInstruction = self.instructionSelector(inst)+" "+direccionMemoria
self.readCache(direccionMemoria)
elif (inst == 2):
self.lastInstruction = self.instructionSelector(inst)+" "+direccionMemoria+" "+valor
self.writeCache(direccionMemoria,valor)
else:
self.lastInstruction = self.instructionSelector(inst)
self.lastMessage = ""
pass
self.instructionPrint = self.previousInstruction + " || " + self.lastInstruction
return
def instructionSelector(self, instruccion):
if (instruccion == 0):
return "READ"
elif (instruccion == 1):
return "CALC"
else:
return "WRITE"
#-------Cache Related Operations-----------------
def writeCache(self, direccionMemoria, valor):
if (self.estadoCacheGet(direccionMemoria) == "I"):
self.Cache.write(direccionMemoria,valor)
self.lastMessage = "write miss"
self.Publisher.broadcast(self.identifier, "write miss", direccionMemoria)
self.estadoCacheSet(direccionMemoria,"M")
return
elif(self.estadoCacheGet(direccionMemoria) == "S"):
self.Cache.write(direccionMemoria,valor)
self.Publisher.broadcast(self.identifier, "write hit", direccionMemoria)
self.lastMessage = "write hit"
self.estadoCacheSet(direccionMemoria,"M")
return
elif(self.estadoCacheGet(direccionMemoria) == "E"):
self.Cache.write(direccionMemoria,valor)
self.Publisher.broadcast(self.identifier, "write hit", direccionMemoria)
self.lastMessage = "write hit"
self.estadoCacheSet(direccionMemoria,"M")
return
elif(self.estadoCacheGet(direccionMemoria) == "O"):
self.Cache.write(direccionMemoria,valor)
self.Publisher.broadcast(self.identifier, "write hit", direccionMemoria)
self.lastMessage = "write hit"
self.estadoCacheSet(direccionMemoria,"M")
return
elif(self.estadoCacheGet(direccionMemoria) == "M"):
self.Cache.write(direccionMemoria,valor)
self.Publisher.broadcast(self.identifier, "write hit", direccionMemoria)
self.lastMessage = "write hit"
return
return
def readCache(self, direccionMemoria):
#I (Read Miss, Exclusive) E
if (self.estadoCacheGet(direccionMemoria) == "I"):
self.Publisher.broadcast(self.identifier, "read miss", direccionMemoria)
self.lastMessage = "read miss"
if (self.estadoCacheGet(direccionMemoria) == "I"):
self.writeCache(direccionMemoria, self.memory.memGet(int(direccionMemoria,2)))
self.lastMessage = "read miss"
self.estadoCacheSet(direccionMemoria,"E")
return
return
#S (Read Hit) S
elif (self.estadoCacheGet(direccionMemoria) == "S"):
self.Publisher.broadcast(self.identifier, "read hit", direccionMemoria)
self.lastMessage = "read hit"
return self.Cache.read(direccionMemoria)
#O (Read Hit) O
elif (self.estadoCacheGet(direccionMemoria) == "O"):
self.Publisher.broadcast(self.identifier, "read hit", direccionMemoria)
self.lastMessage = "read hit"
return self.Cache.read(direccionMemoria)
else:
return self.Cache.read(direccionMemoria)
return
def estadoCacheGet(self,direccionMemoria):
return self.Cache.estadoGet(direccionMemoria)
def estadoCacheSet(self,direccionMemoria,nuevoEstado):
return self.Cache.estadoSet(direccionMemoria,nuevoEstado)
#-------------------------------------------------
def sleep(self):
time.sleep(self.timer)
return
|
{"/Processor.py": ["/Cache.py"], "/GUI.py": ["/Processor.py", "/Memory.py", "/Snoop.py"], "/Cache.py": ["/SetCache.py"], "/SetCache.py": ["/BloqueCache.py"]}
|
22,622
|
jung-bak/Arqui2_Proyecto_1
|
refs/heads/main
|
/Snoop.py
|
class Subscriber:
def __init__(self, processor):
self.processor = processor
self.processorList = []
self.memory = processor.memory
self.identifier = processor.identifier
def update(self,senderId,message, direccionMemoria):
self.moesi(self.processorList[senderId], self.processor, self.memory, message, direccionMemoria)
return
def moesi(self, senderProcessor, processor, memory, message, direccionMemoria):
if (message == "read miss"):
if(processor.estadoCacheGet(direccionMemoria) == "E"):
senderProcessor.Cache.writeX(direccionMemoria, processor.readCache(direccionMemoria))
senderProcessor.estadoCacheSet(direccionMemoria,"S")
processor.estadoCacheSet(direccionMemoria,"S")
return
elif(processor.estadoCacheGet(direccionMemoria) == "S"):
senderProcessor.Cache.writeX(direccionMemoria, processor.readCache(direccionMemoria))
senderProcessor.estadoCacheSet(direccionMemoria,"S")
return
elif (message == "read hit"):
if(processor.estadoCacheGet(direccionMemoria) == "M"):
processor.estadoCacheSet(direccionMemoria,"O")
return
elif (processor.estadoCacheGet(direccionMemoria) == "O"):
return
elif (processor.estadoCacheGet(direccionMemoria) == "E"):
processor.estadoCacheSet(direccionMemoria,"S")
return
elif (processor.estadoCacheGet(direccionMemoria) == "S"):
return
elif (processor.estadoCacheGet(direccionMemoria) == "M"):
return
elif (message == "write hit"):
if(processor.estadoCacheGet(direccionMemoria) == "M"):
processor.estadoCacheSet(direccionMemoria,"I")
return
elif(processor.estadoCacheGet(direccionMemoria) == "O"):
processor.estadoCacheSet(direccionMemoria,"I")
return
elif(processor.estadoCacheGet(direccionMemoria) == "E"):
processor.estadoCacheSet(direccionMemoria,"I")
return
elif(processor.estadoCacheGet(direccionMemoria) == "S"):
processor.estadoCacheSet(direccionMemoria,"I")
return
elif (message == "write miss"):
if(processor.estadoCacheGet(direccionMemoria) == "M"):
processor.estadoCacheSet(direccionMemoria,"I")
return
elif(processor.estadoCacheGet(direccionMemoria) == "O"):
processor.estadoCacheSet(direccionMemoria,"I")
return
elif(processor.estadoCacheGet(direccionMemoria) == "E"):
processor.estadoCacheSet(direccionMemoria,"I")
return
elif(processor.estadoCacheGet(direccionMemoria) == "S"):
processor.estadoCacheSet(direccionMemoria,"I")
return
return
class Publisher:
def __init__(self,identifier):
self.identifier = identifier
self.subscriber = []
def register(self,subscriberName):
self.subscriber.append(subscriberName)
def broadcast(self, senderId, message, direccionMemoria):
for subscriber in self.subscriber:
subscriber.update(senderId,message,direccionMemoria)
|
{"/Processor.py": ["/Cache.py"], "/GUI.py": ["/Processor.py", "/Memory.py", "/Snoop.py"], "/Cache.py": ["/SetCache.py"], "/SetCache.py": ["/BloqueCache.py"]}
|
22,623
|
jung-bak/Arqui2_Proyecto_1
|
refs/heads/main
|
/GUI.py
|
from tkinter import Tk, Label, Button, Entry, OptionMenu, StringVar
from Processor import Processor
from Memory import Memory
from Snoop import Subscriber, Publisher
from numpy import random
from threading import Thread
import time
class GUI:
def __init__(self,master):
self.master = master
master.title("Proyecto Individual 1")
master.geometry("800x500")
self.processorSpeed = 0.1
self.memorySpeed = 0.2
self.loop = True
self.processor = []
self.subscriber = []
self.publisher = []
self.memory = Memory(self.memorySpeed)
for i in range(4):
self.processor.append(Processor(i,self.memory,self.processorSpeed))
self.subscriber.append(Subscriber(self.processor[i]))
self.publisher.append(Publisher(i))
#Add Subscribers to Publishers
self.subscribeToPublisher(self.publisher,self.subscriber)
#Add processors to the Subscriber
self.processorToSubscriber(self.processor,self.subscriber)
#Add publishers to processors
self.publisherToProcessor(self.processor,self.publisher)
self.width = 18
self.height = 1
#opcion ejecucion continua
self.ecLabel = Label(master, borderwidth = 2,relief="ridge",text="Ejecucion Continua", width=self.width, height=self.height)
self.ecStart = Button(master, text="Start", width=self.width , height=self.height, command= lambda: self.instructionFunction(3))
self.ecStop = Button(master, text="Stop", width=self.width, height=self.height, command = lambda: self.killLoop())
self.ecLabel.grid(row=0, column=0)
self.ecStart.grid(row=0, column=1)
self.ecStop.grid(row=0, column=2)
#opcion ejecucion loop
self.elLabel = Label(master, borderwidth = 2,relief="ridge",text="Ejecucion Loop", width=self.width, height=self.height)
self.elLoop = Entry(master, width=self.width)
self.elStart = Button(master, text="Start", width=self.width , height=self.height, command= lambda: self.instructionFunction(2))
self.elLabel.grid(row=1, column=0)
self.elLoop.grid(row=1, column=1)
self.elStart.grid(row=1, column=2)
#opcion ejecucion unitaria
self.esLabel = Label(master, borderwidth = 2,relief="ridge",text="Ejecucion Unitaria", width=self.width, height=self.height)
self.esStart = Button(master, text="Start", width=self.width , height=self.height, command = lambda: self.instructionFunction(1))
self.esLabel.grid(row=2, column=0)
self.esStart.grid(row=2, column=1)
#opcion ingresar instruccion
self.iiLabel = Label(master,borderwidth = 2,relief="ridge", text="Ingresar Instruccion", width=self.width, height=self.height)
self.processorOption = ["Processor 0", "Processor 1", "Processor 2", "Processor 3"]
self.processorVar = StringVar(master)
self.processorVar.set(self.processorOption[0])
self.pOption = OptionMenu(master,self.processorVar,*self.processorOption)
self.instructionOption = ["READ", "CALC", "WRITE"]
self.instructionVar = StringVar(master)
self.instructionVar.set(self.instructionOption[0])
self.iOption = OptionMenu(master,self.instructionVar,*self.instructionOption)
self.iiDireccion = Entry(master, width=self.width)
self.iiValor = Entry(master, width=self.width)
self.iiStart = Button(master, text="Start", width=self.width , height=self.height, command= lambda: self.buildInstruction())
self.iiLabel.grid(row=3, column=0)
self.pOption.grid(row=3, column=1)
self.iOption.grid(row=3, column=2)
self.iiDireccion.grid(row=3, column=3)
self.iiValor.grid(row=3, column=4)
self.iiStart.grid(row=3, column=5)
#Blank
self.blankLabel1 = Label(master,text="",width=self.width, height=self.height)
self.blankLabel1.grid(row=4,column=0)
#Processor 0
self.p0Label = Label(master,borderwidth = 2,relief="ridge", text="Procesador 0", width=self.width, height=self.height)
self.p0c0 = Label(master,borderwidth = 2,relief="ridge", text="", width=self.width, height=self.height)
self.p0c1 = Label(master,borderwidth = 2,relief="ridge", text="", width=self.width, height=self.height)
self.p0c2 = Label(master,borderwidth = 2,relief="ridge", text="", width=self.width, height=self.height)
self.p0c3 = Label(master,borderwidth = 2,relief="ridge", text="", width=self.width, height=self.height)
self.p0i = Label(master,borderwidth = 2,relief="raised", text="", width=self.width, height=self.height)
self.p0Label.grid(row=5, column=0)
self.p0c0.grid(row=6,column=0)
self.p0c1.grid(row=7,column=0)
self.p0c2.grid(row=8,column=0)
self.p0c3.grid(row=9,column=0)
self.p0i.grid(row=10,column=0)
#Processor 1
self.p1Label = Label(master,borderwidth = 2,relief="ridge", text="Procesador 1", width=self.width, height=self.height)
self.p1c0 = Label(master,borderwidth = 2,relief="ridge", text="", width=self.width, height=self.height)
self.p1c1 = Label(master,borderwidth = 2,relief="ridge", text="", width=self.width, height=self.height)
self.p1c2 = Label(master,borderwidth = 2,relief="ridge", text="", width=self.width, height=self.height)
self.p1c3 = Label(master,borderwidth = 2,relief="ridge", text="", width=self.width, height=self.height)
self.p1i = Label(master,borderwidth = 2,relief="raised", text="", width=self.width, height=self.height)
self.p1Label.grid(row=5, column=1)
self.p1c0.grid(row=6,column=1)
self.p1c1.grid(row=7,column=1)
self.p1c2.grid(row=8,column=1)
self.p1c3.grid(row=9,column=1)
self.p1i.grid(row=10,column=1)
#Processor 2
self.p2Label = Label(master, borderwidth = 2,relief="ridge",text="Procesador 2", width=self.width, height=self.height)
self.p2c0 = Label(master,borderwidth = 2,relief="ridge", text="", width=self.width, height=self.height)
self.p2c1 = Label(master,borderwidth = 2,relief="ridge", text="", width=self.width, height=self.height)
self.p2c2 = Label(master,borderwidth = 2,relief="ridge", text="", width=self.width, height=self.height)
self.p2c3 = Label(master,borderwidth = 2,relief="ridge", text="", width=self.width, height=self.height)
self.p2i = Label(master,borderwidth = 2,relief="raised", text="", width=self.width, height=self.height)
self.p2Label.grid(row=5, column=2)
self.p2c0.grid(row=6,column=2)
self.p2c1.grid(row=7,column=2)
self.p2c2.grid(row=8,column=2)
self.p2c3.grid(row=9,column=2)
self.p2i.grid(row=10,column=2)
#Processor 3
self.p3Label = Label(master, borderwidth = 2,relief="ridge",text="Procesador 3", width=self.width, height=self.height)
self.p3c0 = Label(master,borderwidth = 2,relief="ridge", text="", width=self.width, height=self.height)
self.p3c1 = Label(master,borderwidth = 2,relief="ridge", text="", width=self.width, height=self.height)
self.p3c2 = Label(master,borderwidth = 2,relief="ridge", text="", width=self.width, height=self.height)
self.p3c3 = Label(master,borderwidth = 2,relief="ridge", text="", width=self.width, height=self.height)
self.p3i = Label(master,borderwidth = 2,relief="raised", text="", width=self.width, height=self.height)
self.p3Label.grid(row=5, column=3)
self.p3c0.grid(row=6,column=3)
self.p3c1.grid(row=7,column=3)
self.p3c2.grid(row=8,column=3)
self.p3c3.grid(row=9,column=3)
self.p3i.grid(row=10,column=3)
#Instruction Matrix
self.p0iLabel = Label(master, borderwidth = 2,relief="ridge",text="Procesador 0", width=self.width, height=self.height)
self.p1iLabel = Label(master, borderwidth = 2,relief="ridge",text="Procesador 1", width=self.width, height=self.height)
self.p2iLabel = Label(master, borderwidth = 2,relief="ridge",text="Procesador 2", width=self.width, height=self.height)
self.p3iLabel = Label(master, borderwidth = 2,relief="ridge",text="Procesador 3", width=self.width, height=self.height)
self.p0iLabel.grid(row=13,column=0)
self.p1iLabel.grid(row=14,column=0)
self.p2iLabel.grid(row=15,column=0)
self.p3iLabel.grid(row=16,column=0)
self.iLabel = Label(master, borderwidth = 2,relief="ridge",text="Instruccion Ejecutada", width=3*self.width, height=self.height)
self.p0inst = Label(master, borderwidth = 2,relief="ridge",text="", width=3*self.width, height=self.height)
self.p1inst = Label(master, borderwidth = 2,relief="ridge",text="", width=3*self.width, height=self.height)
self.p2inst = Label(master, borderwidth = 2,relief="ridge",text="", width=3*self.width, height=self.height)
self.p3inst = Label(master, borderwidth = 2,relief="ridge",text="", width=3*self.width, height=self.height)
self.iLabel.grid(row=12,column=1, columnspan = 3)
self.p0inst.grid(row=13,column=1, columnspan = 3)
self.p1inst.grid(row=14,column=1, columnspan = 3)
self.p2inst.grid(row=15,column=1, columnspan = 3)
self.p3inst.grid(row=16,column=1, columnspan = 3)
#Memory
self.mLabel = Label(master, borderwidth = 2,relief="ridge",text="Memoria", width=self.width, height=self.height)
self.m0 = Label(master,borderwidth = 2,relief="ridge", text="", width=self.width, height=self.height)
self.m1 = Label(master,borderwidth = 2,relief="ridge", text="", width=self.width, height=self.height)
self.m2 = Label(master,borderwidth = 2,relief="ridge", text="", width=self.width, height=self.height)
self.m3 = Label(master,borderwidth = 2,relief="ridge", text="", width=self.width, height=self.height)
self.m4 = Label(master,borderwidth = 2,relief="ridge", text="", width=self.width, height=self.height)
self.m5 = Label(master,borderwidth = 2,relief="ridge", text="", width=self.width, height=self.height)
self.m6 = Label(master,borderwidth = 2,relief="ridge", text="", width=self.width, height=self.height)
self.m7 = Label(master,borderwidth = 2,relief="ridge", text="", width=self.width, height=self.height)
self.m8 = Label(master,borderwidth = 2,relief="ridge", text="", width=self.width, height=self.height)
self.m9 = Label(master,borderwidth = 2,relief="ridge", text="", width=self.width, height=self.height)
self.m10 = Label(master,borderwidth = 2,relief="ridge", text="", width=self.width, height=self.height)
self.m11 = Label(master,borderwidth = 2,relief="ridge", text="", width=self.width, height=self.height)
self.m12 = Label(master,borderwidth = 2,relief="ridge", text="", width=self.width, height=self.height)
self.m13 = Label(master,borderwidth = 2,relief="ridge", text="", width=self.width, height=self.height)
self.m14 = Label(master,borderwidth = 2,relief="ridge", text="", width=self.width, height=self.height)
self.m15 = Label(master,borderwidth = 2,relief="ridge", text="", width=self.width, height=self.height)
self.mLabel.grid(row=5, column=5)
self.m0.grid(row=6,column=5)
self.m1.grid(row=7,column=5)
self.m2.grid(row=8,column=5)
self.m3.grid(row=9,column=5)
self.m4.grid(row=10,column=5)
self.m5.grid(row=11,column=5)
self.m6.grid(row=12,column=5)
self.m7.grid(row=13,column=5)
self.m8.grid(row=14,column=5)
self.m9.grid(row=15,column=5)
self.m10.grid(row=16,column=5)
self.m11.grid(row=17,column=5)
self.m12.grid(row=18,column=5)
self.m13.grid(row=19,column=5)
self.m14.grid(row=20,column=5)
self.m15.grid(row=21,column=5)
self.m0pos = Label(master,borderwidth = 2,relief="ridge", text="0000", width=self.width//3, height=self.height)
self.m1pos = Label(master,borderwidth = 2,relief="ridge", text="0001", width=self.width//3, height=self.height)
self.m2pos = Label(master,borderwidth = 2,relief="ridge", text="0010", width=self.width//3, height=self.height)
self.m3pos = Label(master,borderwidth = 2,relief="ridge", text="0011", width=self.width//3, height=self.height)
self.m4pos = Label(master,borderwidth = 2,relief="ridge", text="0100", width=self.width//3, height=self.height)
self.m5pos = Label(master,borderwidth = 2,relief="ridge", text="0101", width=self.width//3, height=self.height)
self.m6pos = Label(master,borderwidth = 2,relief="ridge", text="0110", width=self.width//3, height=self.height)
self.m7pos = Label(master,borderwidth = 2,relief="ridge", text="0111", width=self.width//3, height=self.height)
self.m8pos = Label(master,borderwidth = 2,relief="ridge", text="1000", width=self.width//3, height=self.height)
self.m9pos = Label(master,borderwidth = 2,relief="ridge", text="1001", width=self.width//3, height=self.height)
self.m10pos = Label(master,borderwidth = 2,relief="ridge", text="1010", width=self.width//3, height=self.height)
self.m11pos = Label(master,borderwidth = 2,relief="ridge", text="1011", width=self.width//3, height=self.height)
self.m12pos = Label(master,borderwidth = 2,relief="ridge", text="1100", width=self.width//3, height=self.height)
self.m13pos = Label(master,borderwidth = 2,relief="ridge", text="1101", width=self.width//3, height=self.height)
self.m14pos = Label(master,borderwidth = 2,relief="ridge", text="1110", width=self.width//3, height=self.height)
self.m15pos = Label(master,borderwidth = 2,relief="ridge", text="1111", width=self.width//3, height=self.height)
self.m0pos.grid(row=6,column=4,sticky="E")
self.m1pos.grid(row=7,column=4,sticky="E")
self.m2pos.grid(row=8,column=4,sticky="E")
self.m3pos.grid(row=9,column=4,sticky="E")
self.m4pos.grid(row=10,column=4,sticky="E")
self.m5pos.grid(row=11,column=4,sticky="E")
self.m6pos.grid(row=12,column=4,sticky="E")
self.m7pos.grid(row=13,column=4,sticky="E")
self.m8pos.grid(row=14,column=4,sticky="E")
self.m9pos.grid(row=15,column=4,sticky="E")
self.m10pos.grid(row=16,column=4,sticky="E")
self.m11pos.grid(row=17,column=4,sticky="E")
self.m12pos.grid(row=18,column=4,sticky="E")
self.m13pos.grid(row=19,column=4,sticky="E")
self.m14pos.grid(row=20,column=4,sticky="E")
self.m15pos.grid(row=21,column=4,sticky="E")
self.printMemoryAndCache(self.processorSelector,self.memory)
def subscribeToPublisher(self, publisher, subscribers):
publisher[0].register(subscribers[1])
publisher[0].register(subscribers[2])
publisher[0].register(subscribers[3])
publisher[1].register(subscribers[0])
publisher[1].register(subscribers[2])
publisher[1].register(subscribers[3])
publisher[2].register(subscribers[0])
publisher[2].register(subscribers[1])
publisher[2].register(subscribers[3])
publisher[3].register(subscribers[0])
publisher[3].register(subscribers[1])
publisher[3].register(subscribers[2])
return
def processorToSubscriber(self, processor, subscribers):
for i in range(4):
self.subscriber[i].processorList = processor
return
def publisherToProcessor(self, processor, publisher):
for i in range(4):
processor[i].Publisher = publisher[i]
return
#--------------------------------------EXECUTION LOOPS# ---------------------------------
def generatorSingle(self, instruccion, direccionMemoria,valor):
self.printMemoryAndCache(self.processor,self.memory)
p0 = Thread(target=self.mtInstruction, args=(self.processor[0],))
p1 = Thread(target=self.mtInstruction, args=(self.processor[1],))
p2 = Thread(target=self.mtInstruction, args=(self.processor[2],))
p3 = Thread(target=self.mtInstruction, args=(self.processor[3],))
p0.start()
p1.start()
p2.start()
p3.start()
return
def generatorIteraciones(self, instruccion, direccionMemoria, valor):
for i in range(int(self.elLoop.get())):
self.printMemoryAndCache(self.processor,self.memory)
p0 = Thread(target=self.mtInstruction, args=(self.processor[0],))
p1 = Thread(target=self.mtInstruction, args=(self.processor[1],))
p2 = Thread(target=self.mtInstruction, args=(self.processor[2],))
p3 = Thread(target=self.mtInstruction, args=(self.processor[3],))
p0.start()
p1.start()
p2.start()
p3.start()
return
def generatorContinous(self, instruccion, direccionMemoria,valor):
self.loop = True
while(self.loop):
self.printMemoryAndCache(self.processor,self.memory)
p0 = Thread(target=self.mtInstruction, args=(self.processor[0],))
p1 = Thread(target=self.mtInstruction, args=(self.processor[1],))
p2 = Thread(target=self.mtInstruction, args=(self.processor[2],))
p3 = Thread(target=self.mtInstruction, args=(self.processor[3],))
p0.start()
p1.start()
p2.start()
p3.start()
return
def killLoop(self):
self.loop=False
return
# --------------------------------------------------------------------------------------------
def mtInstruction(self, processor):
[instruccion, direccionMemoria, valor] = self.generatorInstruction()
processor.instruction(instruccion, direccionMemoria, valor)
def instructionFunction(self, mode):
[instruccion, direccionMemoria, valor] = self.generatorInstruction()
if (mode == 1):
self.generatorSingle(instruccion, direccionMemoria,valor)
elif (mode == 2):
self.generatorIteraciones(instruccion, direccionMemoria, valor)
else:
self.generatorContinous(instruccion, direccionMemoria,valor)
def generatorInstruction(self):
instruccion = random.binomial(n=2,p=0.5,size=1)[0]
direccionMemoria = bin(random.randint(0,15)).replace('0b','')
valor = hex(random.randint(0,65535)).replace('0x','')
return [instruccion,direccionMemoria,valor]
#-----------------------------------DISPLAY PRINTS--------------------------------------------
def printMemoryAndCache(self,processor,memory):
self.p0c0["text"] = self.cacheTextBuilder(self.processor[0].Cache.set0.bloque0)
self.p0c1["text"] = self.cacheTextBuilder(self.processor[0].Cache.set0.bloque1)
self.p0c2["text"] = self.cacheTextBuilder(self.processor[0].Cache.set1.bloque0)
self.p0c3["text"] = self.cacheTextBuilder(self.processor[0].Cache.set1.bloque1)
self.p0i["text"] = self.processor[0].lastMessage
self.p1c0["text"] = self.cacheTextBuilder(self.processor[1].Cache.set0.bloque0)
self.p1c1["text"] = self.cacheTextBuilder(self.processor[1].Cache.set0.bloque1)
self.p1c2["text"] = self.cacheTextBuilder(self.processor[1].Cache.set1.bloque0)
self.p1c3["text"] = self.cacheTextBuilder(self.processor[1].Cache.set1.bloque1)
self.p1i["text"] = self.processor[1].lastMessage
self.p2c0["text"] = self.cacheTextBuilder(self.processor[2].Cache.set0.bloque0)
self.p2c1["text"] = self.cacheTextBuilder(self.processor[2].Cache.set0.bloque1)
self.p2c2["text"] = self.cacheTextBuilder(self.processor[2].Cache.set1.bloque0)
self.p2c3["text"] = self.cacheTextBuilder(self.processor[2].Cache.set1.bloque1)
self.p2i["text"] = self.processor[2].lastMessage
self.p3c0["text"] = self.cacheTextBuilder(self.processor[3].Cache.set0.bloque0)
self.p3c1["text"] = self.cacheTextBuilder(self.processor[3].Cache.set0.bloque1)
self.p3c2["text"] = self.cacheTextBuilder(self.processor[3].Cache.set1.bloque0)
self.p3c3["text"] = self.cacheTextBuilder(self.processor[3].Cache.set1.bloque1)
self.p3i["text"] = self.processor[3].lastMessage
self.m0["text"] = self.memory.memGet(0)
self.m1["text"] = self.memory.memGet(1)
self.m2["text"] = self.memory.memGet(2)
self.m3["text"] = self.memory.memGet(3)
self.m4["text"] = self.memory.memGet(4)
self.m5["text"] = self.memory.memGet(5)
self.m6["text"] = self.memory.memGet(6)
self.m7["text"] = self.memory.memGet(7)
self.m8["text"] = self.memory.memGet(8)
self.m9["text"] = self.memory.memGet(9)
self.m10["text"] = self.memory.memGet(10)
self.m11["text"] = self.memory.memGet(11)
self.m12["text"] = self.memory.memGet(12)
self.m13["text"] = self.memory.memGet(13)
self.m14["text"] = self.memory.memGet(14)
self.m15["text"] = self.memory.memGet(15)
self.p0inst["text"] = self.processor[0].instructionPrint
self.p1inst["text"] = self.processor[1].instructionPrint
self.p2inst["text"] = self.processor[2].instructionPrint
self.p3inst["text"] = self.processor[3].instructionPrint
return
def cacheTextBuilder(self,bloqueCache):
estado = bloqueCache.b_estadoGet()
direccion = bloqueCache.b_direccionGet()
dato = bloqueCache.b_datoGet()
escribir = estado + " - " + direccion + " - " + dato
return escribir
# --------------------------------------------------------------------------------------------
# -----------------------------------SPECIFIC INSTRUCTION BUILDER-----------------------------
def buildInstruction(self):
processorNumber = self.processorSelector(self.processorVar.get())
instructionNumber = self.instructionSelector(self.instructionVar.get())
direccionMemoria = bin(int(self.iiDireccion.get(),2)).replace("0b","")
valor = self.iiValor.get()
self.processor[processorNumber].instruction(instructionNumber,direccionMemoria,valor)
self.printMemoryAndCache(self.processor,self.memory)
if (self.instructionVar.get() == "READ"):
self.processor[processorNumber].lastInstruction = self.instructionVar.get() + " " + direccionMemoria
elif (self.instructionVar.get() == "WRITE"):
self.processor[processorNumber].lastInstruction = self.instructionVar.get() + " " + direccionMemoria + " " + valor
else:
self.processor[processorNumber].lastInstruction = self.instructionVar.get()
return
def processorSelector(self, processorText):
if (processorText == "Processor 0"):
return 0
elif (processorText == "Processor 1"):
return 1
elif (processorText == "Processor 2"):
return 2
else:
return 3
def instructionSelector(self, instructionText):
if (instructionText == "READ"):
return 0
elif (instructionText == "CALC"):
return 1
else:
return 2
# --------------------------------------------------------------------------------------------
|
{"/Processor.py": ["/Cache.py"], "/GUI.py": ["/Processor.py", "/Memory.py", "/Snoop.py"], "/Cache.py": ["/SetCache.py"], "/SetCache.py": ["/BloqueCache.py"]}
|
22,624
|
jung-bak/Arqui2_Proyecto_1
|
refs/heads/main
|
/Memory.py
|
import time
from threading import Lock
class Memory:
def __init__(self, timer):
self.mem = ['0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0']
self.timer = timer
self.mutex = Lock()
def memGet(self,position):
self.mutex.acquire()
self.sleep()
self.mutex.release()
return self.mem[position]
def memSet(self,position,value):
self.mutex.acquire()
self.sleep()
self.mem[position] = value
self.mutex.release()
return
#Descanso
def sleep(self):
time.sleep(self.timer)
return
def printMemory(self):
return self.mem
|
{"/Processor.py": ["/Cache.py"], "/GUI.py": ["/Processor.py", "/Memory.py", "/Snoop.py"], "/Cache.py": ["/SetCache.py"], "/SetCache.py": ["/BloqueCache.py"]}
|
22,625
|
jung-bak/Arqui2_Proyecto_1
|
refs/heads/main
|
/Cache.py
|
from SetCache import SetCache
class Cache:
def __init__(self, memory):
self.memory = memory
self.set0 = SetCache(self.memory)
self.set1 = SetCache(self.memory)
def write(self, direccionMemoria, valor):
if (direccionMemoria[-1] == '0'):
return self.set0.s_write(direccionMemoria,valor)
else:
return self.set1.s_write(direccionMemoria,valor)
def writeX(self, direccionMemoria, valor):
if (direccionMemoria[-1] == '0'):
return self.set0.s_writeX(direccionMemoria,valor)
else:
return self.set1.s_writeX(direccionMemoria,valor)
def read(self, direccionMemoria):
if (direccionMemoria[-1] == '0'):
return self.set0.s_read(direccionMemoria)
else:
return self.set1.s_read(direccionMemoria)
def estadoGet(self, direccionMemoria):
if (direccionMemoria[-1] == '0'):
return self.set0.s_estadoGet(direccionMemoria)
else:
return self.set1.s_estadoGet(direccionMemoria)
def estadoSet(self, direccionMemoria, nuevoEstado):
if (direccionMemoria[-1] == '0'):
return self.set0.s_estadoSet(direccionMemoria,nuevoEstado)
else:
return self.set1.s_estadoSet(direccionMemoria,nuevoEstado)
|
{"/Processor.py": ["/Cache.py"], "/GUI.py": ["/Processor.py", "/Memory.py", "/Snoop.py"], "/Cache.py": ["/SetCache.py"], "/SetCache.py": ["/BloqueCache.py"]}
|
22,626
|
jung-bak/Arqui2_Proyecto_1
|
refs/heads/main
|
/SetCache.py
|
from BloqueCache import BloqueCache
class SetCache:
def __init__(self, memory):
self.lastUsed = 0
self.memory = memory
self.bloque0 = BloqueCache(0)
self.bloque1 = BloqueCache(1)
def s_write(self,direccionMemoria, valor):
if (self.lastUsed == 0):
if (self.bloque0.b_direccionGet() == direccionMemoria):
self.bloque0.b_datoSet(valor)
self.bloque0.b_estadoSet("M")
self.lastUsed = 1
return
else:
if (self.bloque0.b_estadoGet() == "M"):
self.memory.memSet(int(self.bloque0.b_direccionGet(),2),self.bloque0.b_datoGet())
self.bloque0.b_direccionSet(direccionMemoria)
self.bloque0.b_datoSet(valor)
elif (self.bloque0.b_estadoGet() == "O"):
self.memory.memSet(int(self.bloque0.b_direccionGet(),2),self.bloque0.b_datoGet())
self.bloque0.b_direccionSet(direccionMemoria)
self.bloque0.b_datoSet(valor)
self.bloque0.b_estadoSet("M")
elif (self.bloque0.b_estadoGet() == "E"):
self.memory.memSet(int(self.bloque0.b_direccionGet(),2),self.bloque0.b_datoGet())
self.bloque0.b_direccionSet(direccionMemoria)
self.bloque0.b_datoSet(valor)
self.bloque0.b_estadoSet("M")
else:
self.bloque0.b_direccionSet(direccionMemoria)
self.bloque0.b_datoSet(valor)
self.bloque0.b_estadoSet("M")
self.lastUsed = 1
return
else:
if (self.bloque1.b_direccionGet() == direccionMemoria):
self.bloque1.b_datoSet(valor)
self.bloque1.b_estadoSet("M")
self.lastUsed = 0
return
else:
if (self.bloque1.b_estadoGet() == "M"):
self.memory.memSet(int(self.bloque1.b_direccionGet(),2),self.bloque1.b_datoGet())
self.bloque1.b_direccionSet(direccionMemoria)
self.bloque1.b_datoSet(valor)
elif (self.bloque1.b_estadoGet() == "O"):
self.memory.memSet(int(self.bloque1.b_direccionGet(),2),self.bloque1.b_datoGet())
self.bloque1.b_direccionSet(direccionMemoria)
self.bloque1.b_datoSet(valor)
self.bloque1.b_estadoSet("M")
elif (self.bloque1.b_estadoGet() == "E"):
self.memory.memSet(int(self.bloque1.b_direccionGet(),2),self.bloque1.b_datoGet())
self.bloque1.b_direccionSet(direccionMemoria)
self.bloque1.b_datoSet(valor)
self.bloque1.b_estadoSet("M")
else:
self.bloque1.b_direccionSet(direccionMemoria)
self.bloque1.b_datoSet(valor)
self.bloque1.b_estadoSet("M")
self.lastUsed = 0
return
def s_writeX(self,direccionMemoria, valor):
if (self.lastUsed == 0):
if (self.bloque0.b_direccionGet() == direccionMemoria):
self.bloque0.b_datoSet(valor)
self.bloque0.b_estadoSet("M")
return
else:
if (self.bloque0.b_estadoGet() == "M"):
self.memory.memSet(int(self.bloque0.b_direccionGet(),2),self.bloque0.b_datoGet())
self.bloque0.b_direccionSet(direccionMemoria)
self.bloque0.b_datoSet(valor)
elif (self.bloque0.b_estadoGet() == "O"):
self.memory.memSet(int(self.bloque0.b_direccionGet(),2),self.bloque0.b_datoGet())
self.bloque0.b_direccionSet(direccionMemoria)
self.bloque0.b_datoSet(valor)
self.bloque0.b_estadoSet("M")
elif (self.bloque0.b_estadoGet() == "E"):
self.memory.memSet(int(self.bloque0.b_direccionGet(),2),self.bloque0.b_datoGet())
self.bloque0.b_direccionSet(direccionMemoria)
self.bloque0.b_datoSet(valor)
self.bloque0.b_estadoSet("M")
else:
self.bloque0.b_direccionSet(direccionMemoria)
self.bloque0.b_datoSet(valor)
self.bloque0.b_estadoSet("M")
return
else:
if (self.bloque1.b_direccionGet() == direccionMemoria):
self.bloque1.b_datoSet(valor)
self.bloque1.b_estadoSet("M")
return
else:
if (self.bloque1.b_estadoGet() == "M"):
self.memory.memSet(int(self.bloque1.b_direccionGet(),2),self.bloque1.b_datoGet())
self.bloque1.b_direccionSet(direccionMemoria)
self.bloque1.b_datoSet(valor)
elif (self.bloque1.b_estadoGet() == "O"):
self.memory.memSet(int(self.bloque1.b_direccionGet(),2),self.bloque1.b_datoGet())
self.bloque1.b_direccionSet(direccionMemoria)
self.bloque1.b_datoSet(valor)
self.bloque1.b_estadoSet("M")
elif (self.bloque1.b_estadoGet() == "E"):
self.memory.memSet(int(self.bloque1.b_direccionGet(),2),self.bloque1.b_datoGet())
self.bloque1.b_direccionSet(direccionMemoria)
self.bloque1.b_datoSet(valor)
self.bloque1.b_estadoSet("M")
else:
self.bloque1.b_direccionSet(direccionMemoria)
self.bloque1.b_datoSet(valor)
self.bloque1.b_estadoSet("M")
return
def s_read(self, direccionMemoria):
if (direccionMemoria == self.bloque0.b_direccionGet()):
return self.bloque0.b_datoGet()
elif (direccionMemoria == self.bloque1.b_direccionGet()):
return self.bloque1.b_datoGet()
else:
return
def s_estadoGet(self,direccionMemoria):
if (direccionMemoria == self.bloque0.b_direccionGet()):
return self.bloque0.b_estadoGet()
elif (direccionMemoria == self.bloque1.b_direccionGet()):
return self.bloque1.b_estadoGet()
else:
return "I"
def s_estadoSet(self,direccionMemoria, nuevoEstado):
if (direccionMemoria == self.bloque0.b_direccionGet()):
self.bloque0.b_estadoSet(nuevoEstado)
return
elif (direccionMemoria == self.bloque1.b_direccionGet()):
self.bloque1.b_estadoSet(nuevoEstado)
return
def s_writeToMem(self, memory, direccionMemoria, valor):
self.memory.memSet(int(direccionMemoria,2),valor)
return
|
{"/Processor.py": ["/Cache.py"], "/GUI.py": ["/Processor.py", "/Memory.py", "/Snoop.py"], "/Cache.py": ["/SetCache.py"], "/SetCache.py": ["/BloqueCache.py"]}
|
22,629
|
MillQK/Nsu_Schedule_Telegram_Bot
|
refs/heads/master
|
/schedule_crawler.py
|
import requests
import json
import bs4
import time
from bs4 import BeautifulSoup
def get_gk_links():
url = 'http://www.nsu.ru/education/schedule/Html_GK/schedule.htm'
source_code = requests.get(url)
text = source_code.text
soup = BeautifulSoup(text, "html.parser")
links = []
for link in soup.find_all('li'):
print('http://www.nsu.ru/education/schedule/Html_GK/' + link.a.get('href'))
links.append('http://www.nsu.ru/education/schedule/Html_GK/' + link.a.get('href'))
return links
# for link in soup.find_all('a'):
# print(link.string)
# print('http://www.nsu.ru/education/schedule/Html_GK/' + link.get('href'))
def get_lk_links():
url = 'http://www.nsu.ru/education/schedule/Html_LK/schedule.htm'
source_code = requests.get(url)
text = source_code.text
soup = BeautifulSoup(text, "html.parser")
links = []
for link in soup.find_all('li'):
print('http://www.nsu.ru/education/schedule/Html_LK/' + link.a.get('href'))
links.append('http://www.nsu.ru/education/schedule/Html_LK/' + link.a.get('href'))
return links
def get_schedule(links):
nsu_schedule = dict()
for link in links:
source_code = requests.get(link)
text = source_code.text
soup = BeautifulSoup(text, "html.parser")
for group_link in soup.find_all('a'):
if has_digit(group_link.string):
group_number = group_link.string
last_slash = link.rindex('/')
url = link[:last_slash+1] + group_link.get('href')
# url = 'http://www.nsu.ru/education/schedule/Html_GK/Groups/16351_1.htm'
print(url)
group_source_code = requests.get(url)
group_text = group_source_code.text
group_soup = BeautifulSoup(group_text, "html.parser")
group_sch = []
for trs in group_soup.find_all('tr'):
if trs.td.string is not None:
if has_digit(trs.td.string) and (':' in trs.td.string or '.' in trs.td.string):
subj = []
for shit1 in trs.find_all('td', recursive=False):
# print(shit1.a)
# print(shit1.string)
# print(shit1.text)
if 'ауд' in shit1.text:
strs = parse_content(shit1)
# if len(shit1.contents) == 5:
# strs = shit1.contents[0].text + '\n' + shit1.contents[1] + '\n' + shit1.contents[4].text
#
# elif len(shit1.contents) == 6:
# strs = shit1.contents[0] + '\n' + shit1.contents[2] + '\n' + shit1.contents[5].text
#
# elif len(shit1.contents) == 4:
# strs = shit1.contents[0].text
#
# else:
# pair = shit1.find_all('td')
# if pair[0].text.strip() != '' and pair[1].text.strip() != '':
#
# elif pair[0].text.strip() == '':
# content = pair[1].hr
# if content is None:
# content = pair[1].contents
# else:
# content = content.contents
# if isinstance(content[0], bs4.element.Tag):
# strs = '//////////\n----------\n' + content[0].text + '\n' + content[1] + '\n' + content[4].text
# else:
# strs = '//////////\n----------\n' + content[0] + '\n' + content[2] + '\n' + content[5].text
# else:
# content = pair[0].hr
# if content is None:
# content = pair[0].contents
# else:
# content = content.contents
# if isinstance(content[0], bs4.element.Tag):
# strs = content[0].text + '\n' + content[1] + '\n' + content[4].text + '\n----------\n//////////'
# else:
# strs = content[0] + '\n' + content[2] + '\n' + content[5].text + '\n----------\n//////////'
subj.append(strs)
print(strs)
elif shit1.text.rstrip() == '':
subj.append(['']) # empty subject
else:
subj.append(shit1.text) # subject time
group_sch.append(subj)
print(group_sch)
group_dict = dict() # all days with subjects
for i in range(1, 7):
daydict = dict() # 1 day dict
for j in range(0, 7):
strg = [group_sch[j][0]] + group_sch[j][i] # subject in day with time
daydict[j] = strg
group_dict[i] = daydict
nsu_schedule[group_number] = group_dict
time.sleep(1)
with open('sch.txt', 'w') as output:
json.dump(nsu_schedule, output)
def parse_content(tagContent):
subjs = list()
if len(tagContent.contents) == 5:
if isinstance(tagContent.contents[0], bs4.element.NavigableString) and isinstance(tagContent.contents[2], bs4.element.NavigableString):
strs = tagContent.contents[0] + '\n' + tagContent.contents[2]
else:
strs = tagContent.contents[0].text + '\n' + tagContent.contents[1] + '\n' + tagContent.contents[4].text
subjs.append(strs)
elif len(tagContent.contents) == 6:
strs = tagContent.contents[0] + '\n' + tagContent.contents[2] + '\n' + tagContent.contents[5].text
subjs.append(strs)
elif len(tagContent.contents) == 4:
strs = tagContent.contents[0].text
if isinstance(tagContent.contents[1], bs4.element.NavigableString):
strs += '\n' + tagContent.contents[1]
subjs.append(strs)
elif len(tagContent.contents) == 1:
subjs = parse_content(tagContent.contents[0])
else:
pair = tagContent.find_all('td')
if pair[0].text.strip() != '' and pair[1].text.strip() != '':
#strs = parse_content(pair[0]) + '\n----------\n' + parse_content(pair[1])
subjs += parse_content(pair[0])
subjs += parse_content(pair[1])
elif pair[0].text.strip() == '':
content = pair[1]
#strs = '//////////\n----------\n' + parse_content(content)
subjs.append('empty_pair')
subjs += parse_content(content)
# content = pair[1].hr
# if content is None:
# content = pair[1].contents
# else:
# content = content.contents
# if isinstance(content[0], bs4.element.Tag):
# strs = '//////////\n----------\n' + content[0].text + '\n' + content[1] + '\n' + content[4].text
# else:
# strs = '//////////\n----------\n' + content[0] + '\n' + content[2] + '\n' + content[5].text
else:
content = pair[0]
# strs = parse_content(content) + '\n----------\n//////////'
subjs += parse_content(content)
subjs.append('empty_pair')
# content = pair[0].hr
# if content is None:
# content = pair[0].contents
# else:
# content = content.contents
# if isinstance(content[0], bs4.element.Tag):
# strs = content[0].text + '\n' + content[1] + '\n' + content[4].text + '\n----------\n//////////'
# else:
# strs = content[0] + '\n' + content[2] + '\n' + content[5].text + '\n----------\n//////////'
return subjs
def has_digit(string):
return any(char.isdigit() for char in string)
links = get_gk_links() + get_lk_links()
print(links)
get_schedule(links)
|
{"/flask_pythonanywhere.py": ["/nsubot.py"]}
|
22,630
|
MillQK/Nsu_Schedule_Telegram_Bot
|
refs/heads/master
|
/flask_pythonanywhere.py
|
# -*- coding: utf-8 -*-
import config
import telebot
from flask import Flask, request, abort
import logging
import nsubot
bot = nsubot.bot
logger = telebot.logger.setLevel(logging.WARN)
WEBHOOK_URL = "https://MilQ.pythonanywhere.com/{}".format(config.webhook_guid)
app = Flask(__name__)
@app.route('/{}'.format(config.webhook_guid), methods=['POST'])
def index():
update = request.json
if update:
bot.process_new_updates([telebot.types.Update.de_json(update)])
return '', 200
else:
abort(403)
bot.remove_webhook()
# Ставим заново вебхук
bot.set_webhook(url=WEBHOOK_URL)
|
{"/flask_pythonanywhere.py": ["/nsubot.py"]}
|
22,631
|
MillQK/Nsu_Schedule_Telegram_Bot
|
refs/heads/master
|
/nsubot.py
|
# -*- coding: utf-8 -*-
import config
import telebot
from telebot import types
from random import randint
import json
import pickledb
import datetime
bot = telebot.TeleBot(config.token, threaded=config.bot_threaded)
groups_storage = pickledb.load('groups_storage.db', False)
with open('sch.txt', 'r') as inp:
sch = json.load(inp)
def is_command(text):
return text[0] == '/'
@bot.message_handler(commands=['fcoin'])
def flip_coin(message):
coin = randint(0, 1)
if coin:
bot.send_message(message.chat.id, 'Орел')
else:
bot.send_message(message.chat.id, 'Решка')
days_dict = {'понедельник': '1',
'вторник': '2',
'среда': '3',
'четверг': '4',
'пятница': '5',
'суббота': '6',
'пн': '1',
'вт': '2',
'ср': '3',
'чт': '4',
'пт': '5',
'сб': '6',
'1': '1',
'2': '2',
'3': '3',
'4': '4',
'5': '5',
'6': '6'}
subjs_dict = {'первая': '0',
'вторая': '1',
'третья': '2',
'четвертая': '3',
'пятая': '4',
'шестая': '5',
'седьмая': '6',
'1': '0',
'2': '1',
'3': '2',
'4': '3',
'5': '4',
'6': '5',
'7': '6',
'первая (9:00)': '0',
'вторая (10:50)': '1',
'третья (12:40)': '2',
'четвертая (14:30)': '3',
'пятая (16:20)': '4',
'шестая (18:10)': '5',
'седьмая (20:00)': '6'}
subjects_list = ['0', '1', '2', '3', '4', '5', '6']
weekdays_list = ['Понедельник', 'Вторник', 'Среда', 'Четверг', 'Пятница', 'Суббота']
EMPTY_SUBJ = 'empty_pair'
GROUP_NAME = 'group_name'
EMPTY_DAY_MESSAGE = 'В этот день пар нет.'
EMPTY_SUBJ_MESSAGE = 'Пустая пара.'
@bot.message_handler(func=lambda msg: len(msg.text.split()) > 1, commands=['sch'])
def get_schedule(message):
information = message.text.split()
if not check_and_correct_request(information):
send_sch_error_message(message.chat.id)
return
answer = ''
if len(information) == 2:
dialog_group(message.chat.id, information[1])
elif len(information) == 3:
day = sch[information[1]][information[2]]
for i in range(0, 7):
answer += make_subject_message(day[str(i)]) + '\n\n'
elif len(information) == 4:
answer = make_subject_message(sch[information[1]][information[2]][information[3]])
else:
send_sch_error_message(message.chat.id)
return
# print(answer)
bot.send_message(message.chat.id, answer)
chat_history = dict()
@bot.message_handler(commands=['sch'])
def schedule_custom_keyboard(message):
sent = bot.send_message(message.chat.id, 'Введите номер группы.', reply_markup=types.ReplyKeyboardHide())
bot.register_next_step_handler(sent, dialog_group_check)
def dialog_group_check(message):
group_num = message.text
if is_command(message.text):
return
if group_num not in sch:
bot.send_message(message.chat.id, 'Нет такой группы. Попробуйте еще раз.',
reply_markup=types.ReplyKeyboardHide())
return
dialog_group(message.chat.id, group_num)
def dialog_group(mchat_id, group):
chat_history[mchat_id] = sch[group]
markup = types.ReplyKeyboardMarkup()
markup.row('Сегодня', 'Завтра')
markup.row('Понедельник', 'Вторник')
markup.row('Среда', 'Четверг')
markup.row('Пятница', 'Суббота')
markup.row('Вся неделя')
sent = bot.send_message(mchat_id, 'Выберете день недели', reply_markup=markup)
bot.register_next_step_handler(sent, dialog_weekday)
def dialog_weekday(message):
if is_command(message.text):
return
weekday = message.text.lower()
if weekday == 'вся неделя':
send_week_schedule(message.chat.id, chat_history[message.chat.id])
return
if weekday == 'сегодня' or weekday == 'завтра':
if weekday == 'сегодня':
weekday = today_weekday()
elif weekday == 'завтра':
weekday = tomorrow_weekday()
if weekday == 0:
bot.send_message(message.chat.id, 'В воскресенье нет занятий.',
reply_markup=types.ReplyKeyboardHide())
return
weekday = str(weekday)
if weekday not in days_dict:
bot.send_message(message.chat.id, 'Нет такого дня недели. Попробуйте еще раз.',
reply_markup=types.ReplyKeyboardHide())
return
chat_history[message.chat.id] = chat_history[message.chat.id][days_dict[weekday]]
if is_day_empty(chat_history[message.chat.id]):
bot.send_message(message.chat.id, EMPTY_DAY_MESSAGE,
reply_markup=types.ReplyKeyboardHide())
return
markup = types.ReplyKeyboardMarkup()
markup.row('Первая (9:00)', 'Вторая (10:50)')
markup.row('Третья (12:40)', 'Четвертая (14:30)')
markup.row('Пятая (16:20)', 'Шестая (18:10)')
markup.row('Седьмая (20:00)', 'Все пары')
sent = bot.send_message(message.chat.id, 'Выберете пару', reply_markup=markup)
bot.register_next_step_handler(sent, dialog_answer)
def dialog_answer(message):
if is_command(message.text):
return
subj = message.text.lower()
if subj not in subjs_dict and subj != 'все пары':
bot.send_message(message.chat.id, 'Нет такой пары. Попробуйте еще раз.', reply_markup=types.ReplyKeyboardHide())
return
day = chat_history[message.chat.id]
if subj == 'все пары':
answer = make_day_subjects_message(day)
elif day[subjs_dict[subj]][1] == '': # Пустая пара
answer = '*{0}*: {1}'.format(day[subjs_dict[subj]][0], EMPTY_SUBJ_MESSAGE)
else:
answer = make_subject_message(day[subjs_dict[subj]])
bot.send_message(message.chat.id, answer, reply_markup=types.ReplyKeyboardHide(), parse_mode='Markdown')
def send_sch_error_message(mid):
error_massage = 'Использование: /sch <номер группы> <день недели (например: пн или понедельник или 1)' \
'(опционально)> <номер пары (цифрой, только если есть день недели)(опционально)>' \
'\nНапример: /sch 16202 пт 3\n\n' \
'Либо можете просто написать /sch и дальше взаимодействовать с ботом.'
bot.send_message(mid, error_massage, reply_markup=types.ReplyKeyboardHide())
def check_and_correct_request(split_request):
if len(split_request) == 1 or split_request[1] not in sch:
return False
if len(split_request) > 2:
split_request[2] = split_request[2].lower()
if not split_request[2] in days_dict:
return False
else:
split_request[2] = days_dict[split_request[2]]
if len(split_request) > 3:
split_request[3] = split_request[3].lower()
if not split_request[3] in subjs_dict:
return False
else:
split_request[3] = subjs_dict[split_request[3]]
return True
def make_subject_message(subj):
if len(subj) == 2 and subj[1] != '':
return '*{0}*:\n{1}'.format(subj[0], subj[1])
elif len(subj) == 3:
return '*{0}*:\n*Нечетная неделя*:\n{1}\n*Четная неделя*:\n{2}'.format(subj[0],
'Пустая пара' if subj[1] == EMPTY_SUBJ else subj[1],
'Пустая пара' if subj[2] == EMPTY_SUBJ else subj[2])
else:
return ''
def make_day_subjects_message(day):
if is_day_empty(day):
return EMPTY_DAY_MESSAGE
message = ''
for num_subj in subjects_list:
ans = make_subject_message(day[num_subj])
message += '{0}\n\n'.format(ans) if ans != '' else ''
return message
def send_week_schedule(mchat_id, group_sch):
for weekday in weekdays_list:
day_subjects = group_sch[days_dict[weekday.lower()]]
msg = '*{0}*\n\n{1}'.format(weekday, make_day_subjects_message(day_subjects))
bot.send_message(mchat_id, msg, reply_markup=types.ReplyKeyboardHide(),
parse_mode='Markdown')
def is_day_empty(day):
for num_subj in subjects_list:
cur_subj = day[num_subj]
if len(cur_subj) == 2 and cur_subj[1] != '':
return False
elif len(cur_subj) == 3:
return False
return True
def today_weekday():
utc = datetime.datetime.utcnow()
delta_nsk_tz = datetime.timedelta(hours=7)
nsk_time = utc + delta_nsk_tz
# In python monday is 0, tuesday is 1 and etc. In bot monday is 1 and sunday is 0.
return (nsk_time.weekday() + 1) % 7
def tomorrow_weekday():
return (today_weekday() + 1) % 7
@bot.message_handler(func=lambda msg: len(msg.text.split()) > 1, commands=['setgroup'])
def set_group_in_msg(message):
text = message.text.split()
if len(text) > 2:
setgroup_help_message(message.chat.id)
return
if text[1] not in sch:
bot.send_message(message.chat.id, 'Нет такой группы.')
return
if save_data_in_storage(str(message.chat.id), GROUP_NAME, text[1]):
bot.send_message(message.chat.id, 'Группа сохранена.')
else:
bot.send_message(message.chat.id, 'Возникла ошибка при сохранении. Попробуйте еще раз.')
@bot.message_handler(commands=['setgroup'])
def set_group_in_msg(message):
text = message.text.split()
if len(text) > 1:
setgroup_help_message(message.chat.id)
return
if message.text == '/setgroup':
send = bot.send_message(message.chat.id, 'Введите номер вашей группы.')
bot.register_next_step_handler(send, set_group_in_msg)
elif is_command(message.text):
return
else:
group = message.text
if group not in sch:
bot.send_message(message.chat.id, 'Нет такой группы.')
return
if save_data_in_storage(str(message.chat.id), GROUP_NAME, group):
bot.send_message(message.chat.id, 'Группа сохранена.')
else:
bot.send_message(message.chat.id, 'Возникла ошибка при сохранении. Попробуйте еще раз.')
def setgroup_help_message(mid):
text = 'Использование: /setgroup <номер группы> или /setgroup'
bot.send_message(mid, text)
def save_data_in_storage(storage_key, data_key, data_value):
if storage_key not in groups_storage.getall():
return groups_storage.set(storage_key, {data_key: data_value}) and groups_storage.dump()
else:
data = groups_storage.get(storage_key)
data[data_key] = data_value
return groups_storage.set(storage_key, data) and groups_storage.dump()
@bot.message_handler(commands=["mysch"])
def dialog_mysch(message):
chat_id_str = str(message.chat.id)
if chat_id_str not in groups_storage.getall():
bot.send_message(message.chat.id, 'У вас неустановленна группа. Воспользуйтесь коммандой /setgroup.')
return
dialog_group(message.chat.id, groups_storage.get(chat_id_str)[GROUP_NAME])
@bot.message_handler(commands=["start"])
def repeat_all_messages(message):
send_sch_error_message(message.chat.id)
# if __name__ == '__main__':
# bot.polling(none_stop=True)
|
{"/flask_pythonanywhere.py": ["/nsubot.py"]}
|
22,637
|
JNPRAutomate/junos-babel2
|
refs/heads/master
|
/babel2/device.py
|
import logging
import pprint
logger = logging.getLogger( 'babel2' )
pp = pprint.PrettyPrinter(indent=4)
class Device:
## o unknown, 1 agg, 2 access \
def __init__( self, name ):
self.__name = name
self.__links = {}
self.__peer = ''
self.__personnality = 0
self.__links['to_peer'] = []
self.__links['to_access'] = {}
self.__links['to_aggregation'] = []
self.__links['to_server'] = {}
self.__group_name = ''
self.__fpc_id = 0
def get_name(self):
return self.__name
def get_peer_name(self):
return self.__peer.get_name()
def get_fpc_id(self):
return self.__fpc_id
def set_fpc_id(self, fpc_id):
self.__fpc_id = fpc_id
def set_as_aggregation(self):
self.__personnality = 1
def set_as_access(self, group_name):
self.__personnality = 2
self.__group_name = group_name
def is_aggregation (self):
if self.__personnality == 1:
return 1
else:
return 0
def is_access (self):
if self.__personnality == 2:
return 1
else:
return 0
def get_access_grp (self):
return self.__group_name
def set_peer (self, peer):
self.__peer = peer
def get_peer (self):
return self.__peer
def add_link_to_peer (self, link):
self.__links['to_peer'].append(link)
logger.debug('{0} - add_link_to_peer: link {1} added '.format(self.__name, link))
def add_link_to_aggregation (self, link):
self.__links['to_aggregation'].append(link)
logger.debug('{0} - add_link_to_aggregation: link {1} added '.format(self.__name, link))
def add_link_to_access (self, grp_name, device, link):
if not self.__links['to_access'].has_key(grp_name):
self.__links['to_access'][grp_name] = []
self.__links['to_access'][grp_name].append({'dev': device, 'int': link})
logger.debug( '{0} - add_link_to_access: device {1} link {2} added to {3}'.format(self.__name, device, link, grp_name) )
def add_link_to_server (self, grp_name, device, link ):
if not self.__links['to_server'].has_key(grp_name):
self.__links['to_server'][grp_name] = []
self.__links['to_server'][grp_name].append({'dev': device, 'int': link})
logger.debug( '{0} - add_link_to_server: link {1} added to {2}'.format(self.__name, link, grp_name))
def get_peer_links (self):
return self.__links['to_peer']
def get_aggregation_links (self):
return self.__links['to_aggregation']
def get_servers_links (self, name):
if not self.__links['to_server'].has_key(name):
return []
tmp_list = []
for link in self.__links['to_server'][name]:
tmp_list.append( link['int'] )
return tmp_list
def get_servers_links_with_dev (self, grp_name):
if not self.__links['to_server'].has_key(grp_name):
return []
return self.__links['to_server'][grp_name]
def get_access_links (self, grp_name):
if not self.__links['to_access'].has_key(grp_name):
return []
tmp_list = []
for link in self.__links['to_access'][grp_name]:
tmp_list.append(link['int'])
return tmp_list
def get_access_links_with_dev (self, grp_name):
if not self.__links['to_access'].has_key(grp_name):
return []
return self.__links['to_access'][grp_name]
|
{"/babel2.py": ["/babel2/lib.py"]}
|
22,638
|
JNPRAutomate/junos-babel2
|
refs/heads/master
|
/babel2.py
|
#! /usr/bin/env python
import ansible.inventory
import ansible.inventory.ini
import argparse
from jinja2 import Template
from babel2 import device
from babel2 import parsingerror
import babel2.lib
import pprint
import yaml
import logging
from subprocess import call
from os import path
import os
'''
Usage:
python babel2.py --push <conf_type> --log LEVEL
TODO: Complete description
'''
parser = argparse.ArgumentParser(description='Process user input')
parser.add_argument("--push", dest="push_conf", metavar="CONF_TYPE",
choices=['mclag', 'jfd'],
help="Indicate if you want to push the configuration to all devices")
parser.add_argument("--log", dest="log", metavar="LEVEL", default='info',
choices=['info', 'warn', 'debug', 'error'],
help="Specify the log level ")
args = parser.parse_args()
here = path.abspath(path.dirname(__file__))
parsingError = parsingerror.ParsingError()
pp = pprint.PrettyPrinter(indent=4)
############################################
### Variables initialization
#############################################
devices = {}
group_vars = {}
host_vars = {}
groups_name = []
nbr_access_grp = 0
fpc_id = 100
HOSTS_FILE = 'input/hosts'
CONFIG_FILE = 'input/configuration.yaml'
TOPO_FILE = 'input/topology.yaml'
PB_MCLAG_GEN = 'mclag.all.p.yaml'
PB_MCLAG_PUSH = 'mclag.all.commit.p.yaml'
PB_JFD_GEN = 'jfd.all.p.yaml'
PB_JFD_PUSH = 'jfd.all.commit.p.yaml'
############################################
### Log level configuration
#############################################
logger = logging.getLogger( 'babel2' )
if args.log == 'debug':
logger.setLevel(logging.DEBUG)
elif args.log == 'warn':
logger.setLevel(logging.WARN)
elif args.log == 'error':
logger.setLevel(logging.ERROR)
else:
logger.setLevel(logging.INFO)
logging.basicConfig(format=' %(name)s - %(levelname)s - %(message)s')
############################################
### Open main input files
#############################################
## Access the hosts file from Ansible and check its conformity
inventory = ansible.inventory.ini.InventoryParser(HOSTS_FILE)
hosts = inventory.hosts
groups = inventory.groups
logger.info('Checking Inventory file')
babel2.lib.check_hosts_file(hosts, groups, parsingError)
parsingError.exit_on_error()
## Find devices and classify them
aggregations = groups['aggregation'].get_hosts()
groups_name.append('aggregation')
## Create both Aggregation devices
agg1 = aggregations[0].name
agg2 = aggregations[1].name
agg1dev = device.Device(agg1)
agg2dev = device.Device(agg2)
agg1dev.set_as_aggregation()
agg2dev.set_as_aggregation()
agg2dev.set_peer(agg1dev)
agg1dev.set_peer(agg2dev)
## Add devices to the dict for storage
devices[agg1] = agg1dev
devices[agg2] = agg2dev
## Create access devices
access_groups = groups['access'].child_groups
for access_group in access_groups:
nbr_access_grp += 1
groups_name.append(access_group.name)
access_devices = access_group.get_hosts()
acc1 = access_devices[0].name
acc2 = access_devices[1].name
acc1dev = device.Device(acc1)
acc2dev = device.Device(acc2)
acc1dev.set_as_access(access_group.name)
acc2dev.set_as_access(access_group.name)
acc1dev.set_fpc_id(fpc_id)
acc2dev.set_fpc_id(fpc_id + 1)
acc2dev.set_peer(acc1dev)
acc1dev.set_peer(acc2dev)
devices[acc1] = acc1dev
devices[acc2] = acc2dev
fpc_id += 2
## Access the topology file
## Parse it and chech that all devices are present in the inventory
topology_file = open(TOPO_FILE)
# Render the file as a jinja2 template
topo_tpl = Template(topology_file.read())
topo_tpl_rdr = topo_tpl.render()
topology = yaml.load(topo_tpl_rdr)
logger.info('Checking Topology file')
babel2.lib.check_topology_file(topology, hosts, parsingError)
babel2.lib.assign_interfaces_to_devices(topology, devices)
## Access the configuration definition file
conf_file = open(CONFIG_FILE)
# Render the file as a jinja2 template
config_tpl = Template(conf_file.read())
config_tpl_rdr = config_tpl.render()
config = yaml.load(config_tpl_rdr)
logger.info('Checking Configuration file')
babel2.lib.check_config_file(config, topology, parsingError)
## If some error, exit and print
parsingError.exit_on_error()
#########################################
## Clean Up existing file in group_vars and host_vars
########################################
logger.info('Cleaning Up Old generated file')
for name, device in devices.iteritems():
mydir = path.join(here, 'host_vars', name)
myfile = path.join(mydir, config['global']['gen_file_name'])
if not path.exists(mydir):
os.mkdir(mydir)
elif not path.isdir(mydir):
raise RuntimeError("{0} is not a directory, please fix")
if path.exists(myfile):
logger.debug('File {0} found and deleted'.format(myfile))
os.remove(myfile)
for group in groups_name:
mydir = path.join(here, 'group_vars', group)
myfile = path.join(mydir, config['global']['gen_file_name'])
if not path.exists(mydir):
os.mkdir(mydir)
elif not path.isdir(mydir):
raise RuntimeError("{0} is not a directory, please fix".format(mydir))
if path.exists(myfile):
logger.debug('File {0} found and deleted'.format(myfile))
os.remove(myfile)
##########################################
## Expand Vlans
##########################################
# Go over vlans
# assign Ip addresses for gateway and for all aggs devices
babel2.lib.expland_vlans(config)
##########################################
## Generate variables file for MC-LAG
##########################################
## Create this array with values for both peers, will be use later to generate config for a pair of devices
mclag_cluster_param = []
mclag_cluster_param.append({'chassis_id': 0, 'status_control': 'active', 'local_ip': '1.1.1.1', 'peer_ip': '1.1.1.2'})
mclag_cluster_param.append({'chassis_id': 1, 'status_control': 'standby', 'local_ip': '1.1.1.2', 'peer_ip': '1.1.1.1'})
# Need to generate mac address for all groups
mymac = babel2.lib.generate_mac_address(nbr_access_grp + 1, '00:11:22:33:33')
### Generate variable for aggregation devices
# - first group_vars
# - then host
group_vars['aggregation'] = {}
group_vars['aggregation']['mclag_shared'] = {}
group_vars['aggregation']['mclag_shared']['iccp'] = {}
group_vars['aggregation']['mclag_shared']['mac'] = mymac.pop(0)
group_vars['aggregation']['mclag_shared']['mode'] = config['global']['mc_lag_mode']
group_vars['aggregation']['mclag_shared']['iccp']['vlan_name'] = config['global']['iccp_vlan_name']
group_vars['aggregation']['mclag_shared']['iccp']['vlan_id'] = config['global']['iccp_vlan_id']
## Generate Variables for Aggregation devices ##
for i in range(0, 2):
dev_name = aggregations[i].name
host_vars[dev_name] = {}
host_vars[dev_name]['vlans'] = []
host_vars[dev_name]['mclag'] = {}
host_vars[dev_name]['mclag']['links'] = {}
host_vars[dev_name]['mclag']['links']['to_access'] = []
host_vars[dev_name]['mclag']['iccp'] = {}
host_vars[dev_name]['mclag']['chassis_id'] = mclag_cluster_param[i]['chassis_id']
host_vars[dev_name]['mclag']['status_control'] = mclag_cluster_param[i]['status_control']
host_vars[dev_name]['mclag']['iccp']['local_ip'] = mclag_cluster_param[i]['local_ip']
host_vars[dev_name]['mclag']['iccp']['peer_ip'] = mclag_cluster_param[i]['peer_ip']
host_vars[dev_name]['mclag']['icl_interface'] = config['global']['icl_interface']
## Create vlans for aggre and assigne VIP and addr
for name, vlan in config['vlans'].iteritems():
tmp_vlan = {}
tmp_vlan['name'] = name
tmp_vlan['id'] = vlan['id']
tmp_vlan['ip'] = vlan['router_ips'][i]
tmp_vlan['mask'] = vlan['mask']
tmp_vlan['vip'] = vlan['vip']
# Get peer links info
host_vars[dev_name]['vlans'].append(tmp_vlan)
host_vars[dev_name]['mclag']['links']['to_peer'] = devices[dev_name].get_peer_links()
### Generate Variables for Access devices ##
# - first group_vars
# - then host
grp_id = 1
for access_group in access_groups:
name = access_group.name
access_devices = access_group.get_hosts()
group_vars[name] = {}
group_vars[name]['mclag_shared'] = {}
group_vars[name]['mclag_shared']['iccp'] = {}
group_vars[name]['mclag_shared']['mac'] = mymac.pop(0)
group_vars[name]['mclag_shared']['mode'] = config['global']['mc_lag_mode']
group_vars[name]['mclag_shared']['iccp']['vlan_name'] = config['global']['iccp_vlan_name']
group_vars[name]['mclag_shared']['iccp']['vlan_id'] = config['global']['iccp_vlan_id']
## Populate to_access info for aggregation devices
for i in range(0, 2):
agg_name = aggregations[i].name
links = devices[agg_name].get_access_links(name)
tmp = {'key': grp_id, 'links': links, 'description': "to_{0}".format(name) }
logger.debug('Agg device {0} will add link for access'.format(agg_name))
host_vars[agg_name]['mclag']['links']['to_access'].append(tmp)
## For both devices in the group
for i in range(0, 2):
dev_name = access_devices[i].name
host_vars[dev_name] = {}
host_vars[dev_name]['vlans'] = []
host_vars[dev_name]['mclag'] = {}
host_vars[dev_name]['mclag']['links'] = {}
host_vars[dev_name]['mclag']['iccp'] = {}
host_vars[dev_name]['mclag']['chassis_id'] = mclag_cluster_param[i]['chassis_id']
host_vars[dev_name]['mclag']['status_control'] = mclag_cluster_param[i]['status_control']
host_vars[dev_name]['mclag']['iccp']['local_ip'] = mclag_cluster_param[i]['local_ip']
host_vars[dev_name]['mclag']['iccp']['peer_ip'] = mclag_cluster_param[i]['peer_ip']
host_vars[dev_name]['mclag']['icl_interface'] = config['global']['icl_interface']
for name, vlan in config['vlans'].iteritems():
tmp_vlan = {}
tmp_vlan['name'] = name
tmp_vlan['id'] = vlan['id']
host_vars[dev_name]['vlans'].append(tmp_vlan)
# Get peer & Aggregation links info
host_vars[dev_name]['mclag']['links']['to_servers'] = []
host_vars[dev_name]['mclag']['links']['to_peer'] = devices[dev_name].get_peer_links()
host_vars[dev_name]['mclag']['links']['to_aggregation'] = devices[dev_name].get_aggregation_links()
seg_key = 2
for seg, srv_links in topology['external_links'].iteritems():
do_have = 0
for i in range(0, 2):
dev_name = access_devices[i].name
links = devices[dev_name].get_servers_links(seg)
if not len(links) == 0:
do_have = 1
tmp = {'key': seg_key, 'links': links, 'description': seg, 'vlans':[]}
for vlan_name, vlan in config['vlans'].iteritems():
for link in vlan['links']:
for key, value in link.iteritems():
if key == seg:
tmp['vlans'].append(vlan['id'])
host_vars[dev_name]['mclag']['links']['to_servers'].append(tmp)
if do_have == 1:
seg_key += 1
grp_id += 1
## Count the number of AE per Access device
for i in range(0, 2):
dev_name = access_devices[i].name
nbr_ae = len(host_vars[dev_name]['mclag']['links']['to_servers']) + 2
host_vars[dev_name]['mclag']['nbr_ae'] = nbr_ae
## Count the number of AE per aggregation device
for i in range(0, 2):
agg_name = aggregations[i].name
nbr_ae = len(host_vars[agg_name]['mclag']['links']['to_access']) + 2
host_vars[agg_name]['mclag']['nbr_ae'] = nbr_ae
##########################################
## Generate variables file for JFD ####
##########################################
jfd_cluster_param = []
jfd_cluster_param.append({'chassis_id': 1, 'peer_chassis_id': 2, 'peer_ip': '1.1.1.2', 'peer_name': aggregations[1].name})
jfd_cluster_param.append({'chassis_id': 2, 'peer_chassis_id': 1, 'peer_ip': '1.1.1.1', 'peer_name': aggregations[0].name})
## Generate Variables for Aggregation devices ##
for i in range(0, 2):
agg_name = aggregations[i].name
logger.debug('JFD - Starting {0}'.format(agg_name))
if not host_vars[dev_name]:
host_vars[agg_name] = {}
host_vars[agg_name]['vlans'] = []
## Init host_vars dict
host_vars[agg_name]['jfd'] = {}
host_vars[agg_name]['jfd']['links'] = {}
host_vars[agg_name]['jfd']['links']['to_peer'] = []
host_vars[agg_name]['jfd']['links']['to_servers'] = []
host_vars[agg_name]['jfd']['links']['to_satellite'] = []
## Populate general info
host_vars[agg_name]['jfd']['chassis_id'] = jfd_cluster_param[i]['chassis_id']
host_vars[agg_name]['jfd']['peer_chassis_id'] = jfd_cluster_param[i]['peer_chassis_id']
host_vars[agg_name]['jfd']['peer_ip'] = jfd_cluster_param[i]['peer_ip']
host_vars[agg_name]['jfd']['peer_name'] = jfd_cluster_param[i]['peer_name']
host_vars[agg_name]['jfd']['icl_interface'] = config['global']['icl_interface']
host_vars[agg_name]['jfd']['links']['to_peer'] = devices[dev_name].get_peer_links()
## To Generate Satellite and Server ports info, we go over list of access groups
## and device per device inside each group
for access_group in access_groups:
name = access_group.name
access_devices = access_group.get_hosts()
links_to_sd = devices[agg_name].get_access_links_with_dev(name)
## For Each device in access group, get list of interface
for i in range(0, 2):
sd_name = access_devices[i].name
tmp = {}
tmp['id'] = devices[sd_name].get_fpc_id()
tmp['name'] = sd_name
tmp['links'] = []
for link in links_to_sd:
if link['dev'] == sd_name:
tmp['links'].append(link['int'])
host_vars[agg_name]['jfd']['links']['to_satellite'].append(tmp)
## Generate Server port information
seg_key = 1
for seg, srv_links in topology['external_links'].iteritems():
do_have = 0
tmp = {}
tmp['description'] = "to {0}".format(seg)
tmp['links'] = []
tmp['vlans'] = []
tmp['key'] = ''
for i in range(0, 2):
sd_name = access_devices[i].name
links = devices[sd_name].get_servers_links(seg)
fpc_id = devices[sd_name].get_fpc_id()
## Get list of links
if not len(links) == 0:
do_have = 1
tmp['key'] = seg_key
for link in links:
ep_port = link.replace('-0/', "-{0}/".format(fpc_id) )
tmp['links'].append(ep_port)
## Get list of vlans
for vlan_name, vlan in config['vlans'].iteritems():
for link in vlan['links']:
for key, value in link.iteritems():
if key == seg:
tmp['vlans'].append(vlan['id'])
if do_have == 1:
seg_key += 1
host_vars[agg_name]['jfd']['links']['to_servers'].append(tmp)
##############################################
## Generate Variable Files
##############################################
logger.info('Generate new variable files ... ')
for name, device in devices.iteritems():
myfile = path.join(here, 'host_vars', name, config['global']['gen_file_name'])
with open(myfile, 'w') as f:
yaml.dump(host_vars[name], f, indent=4, default_flow_style=False)
for group in groups_name:
myfile = path.join(here, 'group_vars', group, config['global']['gen_file_name'])
with open(myfile, 'w') as f:
yaml.dump(group_vars[group], f, indent=4, default_flow_style=False)
# ##############################################
# ## Generate Configuration Files
# ##############################################
#
# logger.info('Generate Configuration files for MCLAG ... ')
# call("ansible-playbook -i {0} {1}".format(HOSTS_FILE, PB_MCLAG_GEN), shell=True)
#
# logger.info('Generate Configuration files for JFD ... ')
# call("ansible-playbook -i {0} {1}".format(HOSTS_FILE, PB_JFD_GEN), shell=True)
|
{"/babel2.py": ["/babel2/lib.py"]}
|
22,639
|
JNPRAutomate/junos-babel2
|
refs/heads/master
|
/babel2/lib.py
|
import logging
import sys
import yaml
from os import path
import defconf
here = path.abspath(path.dirname(__file__))
logger = logging.getLogger( 'babel2' )
# Check if topology file is correct
# All entry have 2 sides with "device interface" for each
def check_topology_file( topology, hosts, parsingError ):
logger.debug('Checking internal Links')
definition = yaml.load( open(path.join(here, 'topology.def.yml')) )
defconf.validate_config( topology, definition, 'topology.def.yml' )
for link in topology['internal_links']:
# Check if link size is 2
if not len(link) == 2:
parsingError.add("Internal Link: A link has not 2 sides as expected" + str(len(link)) + " instead")
next
side1 = link[0].split()
side2 = link[1].split()
if not hosts.has_key( side1[0] ):
parsingError.add("Internal Link: Device " + side1[0] + " is not part of the inventory file")
if not hosts.has_key( side2[0] ):
parsingError.add("Internal Link: Device " + side2[0] + " is not part of the inventory file")
logger.debug('Checking External Links')
for name, links in topology['external_links'].iteritems():
for link in links:
dev_int = link.split()#
if not hosts.has_key( dev_int[0] ):
parsingError.add("External Link: Device " + dev_int[0] + " is not part of the inventory file")
def check_hosts_file( hosts, groups, parsingError ):
## Check if groups access and aggregation exists
if not groups.has_key('aggregation'):
parsingError.add("Group aggregation have not been found in file 'hosts'")
return 0
if not groups.has_key('access'):
parsingError.add("Group access have not been found in file 'hosts'")
return 0
## Check if aggregations has 2 hosts, no more no less
aggregations = groups['aggregation'].get_hosts()
if len(aggregations) < 2:
parsingError.add("Less than 2 aggregation device have been found, only 2 allow")
elif len(aggregations) > 2:
parsingError.add("More than 2 aggregation device have been found, only 2 allow")
## Check if all child access group have 2 hosts, no more, no less
access_groups = groups['access'].child_groups
for access_group in access_groups:
access_devices = access_group.get_hosts()
if len(access_devices) < 2:
parsingError.add("Less than 2 access devices have been found in group " + access_group.name + ", only 2 allow")
elif len(access_devices) > 2:
parsingError.add("More than 2 access devices have been found in group " + access_group.name + ", only 2 allow")
def check_config_file( config, topology, parsingError ):
definition = yaml.load( open(path.join(here, 'configuration.def.yml')) )
defconf.validate_config( config, definition, 'configuration.def.yml' )
## Check if all links names provided exist and replace name with proper info
for name, vlan in config['vlans'].iteritems():
for i in range(len(vlan['links'])):
link = vlan['links'][i]
if not topology['external_links'].has_key(link):
parsingError.add("Vlan {0}: Link '{1}' not found in topology file".format(name, link))
else:
vlan['links'][i] = { link: topology['external_links'][link] }
def assign_interfaces_to_devices( topology, devices ):
for link in topology['internal_links']:
side1 = link[0].split()
side2 = link[1].split()
dev1 = side1[0]
dev2 = side2[0]
## if Devices are Peer
if devices[dev1].get_peer_name() == dev2:
logger.debug('Device {0} and {1} are peer'.format(dev1, dev2))
devices[dev1].add_link_to_peer(side1[1])
devices[dev2].add_link_to_peer(side2[1])
## if Dev1 is aggregation, then dev2 is access
elif devices[dev1].is_aggregation() and devices[dev2].is_access():
access_grp = devices[dev2].get_access_grp()
logger.debug('Device {0} is Aggregation and {1} is Access ({2})'.format(dev1, dev2, access_grp))
devices[dev1].add_link_to_access( access_grp, dev2, side1[1] )
devices[dev2].add_link_to_aggregation(side2[1])
elif devices[dev1].is_access() and devices[dev2].is_aggregation():
access_grp = devices[dev1].get_access_grp()
logger.debug('Device {0} is Access ({1}) and {2} is Aggregation'.format(dev1, access_grp, dev2))
devices[dev1].add_link_to_aggregation(side1[1])
devices[dev2].add_link_to_access( access_grp, dev1, side2[1] )
for name, links in topology['external_links'].iteritems():
for link in links:
dev_int = link.split()
devices[dev_int[0]].add_link_to_server(name, dev_int[0], dev_int[1])
def expland_vlans( config ):
for name, value in config['vlans'].iteritems():
# add name at the same level
value['name'] = name
# Parse network info and generate IP for VIP and all routers
network_info = value['network'].split('/')
net = network_info[0].split('.')
value['network'] = network_info[0]
value['mask'] = network_info[1]
value['vip'] = "{0}.{1}.{2}.{3}".format( net[0], net[1], net[2], config['global']['default_gw_ip'] )
value['router_ips'] = []
for i in config['global']['router_ips']:
value['router_ips'].append( "{0}.{1}.{2}.{3}".format( net[0], net[1], net[2], i ) )
def generate_mac_address( qty, base_mac ):
mac_addresses = []
for i in range(qty):
mac = "{0}:{1:02}".format( base_mac, i )
mac_addresses.append(mac)
return mac_addresses
|
{"/babel2.py": ["/babel2/lib.py"]}
|
22,640
|
JNPRAutomate/junos-babel2
|
refs/heads/master
|
/babel2/parsingerror.py
|
import logging
class ParsingError:
__nbr_error = 0
def __init__( self ):
self.errors = []
def add( self, msg ):
self.errors.append(msg)
self.__nbr_error += 1
def has_error( self ):
if self.__nbr_error == 0 :
return 0
else:
return 1
def display( self ):
for msg in self.errors:
logging.warning( msg )
def exit_on_error( self ):
if self.has_error():
self.display()
exit()
|
{"/babel2.py": ["/babel2/lib.py"]}
|
22,642
|
Freebien/ropgenerator
|
refs/heads/master
|
/ropgenerator/exploit/Utils.py
|
# -*- coding:utf-8 -*-
# Utils module: useful functions to build exploits
from ropgenerator.semantic.Engine import search, LMAX
from ropgenerator.Constraints import Constraint, RegsNotModified, Assertion, Chainable, StackPointerIncrement
from ropgenerator.semantic.ROPChains import ROPChain
from ropgenerator.Database import QueryType
from ropgenerator.exploit.Scanner import getFunctionAddress, findBytes
from ropgenerator.IO import verbose, string_bold, string_special, string_ropg
import itertools
import ropgenerator.Architecture as Arch
#### Pop values into registers
POP_MULTIPLE_LMAX = 6000
def popMultiple(args, constraint=None, assertion=None, clmax=None, optimizeLen=False):
"""
args is a list of pairs (reg, value)
OR a list of triples (reg, value, comment)
reg is a reg UID
value is an int
Creates a chain that pops values into regs
"""
if( clmax is None ):
clmax = POP_MULTIPLE_LMAX
elif( clmax <= 0 ):
return None
if( constraint is None ):
constr = Constraint()
else:
constr = constraint
if( assertion is None ):
a = Assertion()
else:
a = assertion
perms = itertools.permutations(args)
for perm in perms:
clmax_tmp = clmax
res = ROPChain()
constr_tmp = constr
for arg in perm:
if( len(arg) == 3 ):
comment = arg[2]
else:
comment = None
if( optimizeLen ):
pop = search(QueryType.CSTtoREG, arg[0], arg[1], constr_tmp, a, n=1, clmax=clmax_tmp, CSTtoREG_comment=comment, optimizeLen=True)
else:
pop = search(QueryType.CSTtoREG, arg[0], arg[1], constr_tmp, a, n=1, clmax=clmax_tmp, CSTtoREG_comment=comment)
if( not pop ):
break
else:
clmax_tmp -= len(pop[0])
# If Reached max length, exit
if( clmax_tmp < 0 ):
pop = None
break
else:
res.addChain(pop[0])
constr_tmp = constr_tmp.add(RegsNotModified([arg[0]]))
if( pop ):
return res
return None
|
{"/ropgenerator/exploit/HighLevelUtils.py": ["/ropgenerator/exploit/Call.py"], "/ropgenerator/exploit/syscalls/Linux32.py": ["/ropgenerator/exploit/syscalls/SyscallDef.py", "/ropgenerator/exploit/Utils.py"], "/ropgenerator/exploit/Syscall.py": ["/ropgenerator/exploit/syscalls/Linux32.py", "/ropgenerator/exploit/syscalls/Linux64.py"], "/ropgenerator/exploit/Call.py": ["/ropgenerator/exploit/Utils.py"], "/ropgenerator/exploit/syscalls/Linux64.py": ["/ropgenerator/exploit/syscalls/SyscallDef.py", "/ropgenerator/exploit/Utils.py", "/ropgenerator/exploit/Call.py"]}
|
22,643
|
Freebien/ropgenerator
|
refs/heads/master
|
/ropgenerator/exploit/HighLevelUtils.py
|
# -*- coding:utf-8 -*-
# Utils module: useful functions to build exploits (more advanced features
# than Utils.py)
from ropgenerator.semantic.Engine import search, LMAX
from ropgenerator.Constraints import Constraint, RegsNotModified, Assertion, Chainable, StackPointerIncrement
from ropgenerator.semantic.ROPChains import ROPChain
from ropgenerator.Database import QueryType
from ropgenerator.exploit.Scanner import getFunctionAddress, findBytes
from ropgenerator.IO import verbose, string_bold, string_special, string_ropg
from ropgenerator.exploit.Call import build_call
import itertools
import ropgenerator.Architecture as Arch
#### Put strings in memory
STR_TO_MEM_LMAX = 6000
def STRtoMEM(string, address, constraint, assertion, limit=None, lmax=STR_TO_MEM_LMAX\
,addr_str=None, hex_info=False, optimizeLen=False):
"""
Put a string into memory
limit : if (int) then the max address where to write in memory
if None then string should be written ONLY at 'addr' (no adjust possible)
return value:
if limit is not None then a pair (address, ROPChain) or (None, None)
if limit is None then a ROPChain or None
"""
(addr,chain) = STRtoMEM_memcpy(string, address, constraint, assertion, limit, lmax, addr_str, hex_info)
res = (addr,chain)
if( (not chain) or optimizeLen ):
(addr2,chain2) = STRtoMEM_strcpy(string, address, constraint, assertion, limit, lmax, addr_str, hex_info)
if( not res[1] ):
res = (addr2,chain2)
elif (chain2 and ( len(chain2) < len(res[1]))):
res = (addr2,chain2)
# If possible adjust, return address and chain
if( limit is None ):
return res[1]
# Otherwise return only chain
else:
return res
def STRtoMEM_strcpy(string, addr, constraint, assertion, limit=None, lmax=STR_TO_MEM_LMAX , addr_str=None, hex_info=False):
"""
STRCPY STRATEGY
Copy the string using strcpy function
"""
if( not addr_str ):
addr_str = hex(addr)
# Getting strcpy function
(func_name, func_addr ) = getFunctionAddress('strcpy')
if( not func_addr ):
verbose('Could not find strcpy function')
return (None,None)
elif( not constraint.badBytes.verifyAddress(func_addr)):
verbose("strcpy address ({}) contains bad bytes".format(hex(func_addr)))
return (None,None)
# We decompose the string in substrings to be copied
substrings_addr = findBytes(string, badBytes = constraint.getBadBytes(), add_null=True)
if( not substrings_addr ):
return (None,None)
# Find delivery address
substr_lengthes = [len(substr[1])-1 for substr in substrings_addr]# -1 becasue strcpy
substr_lengthes[-1] += 1
if( not limit is None ):
custom_stack = find_closest_base_fake_stack_address(addr, limit, substr_lengthes, constraint)
if( custom_stack is None ):
verbose("Couldn't write string in memory because of bad bytes")
return (None,None)
else:
custom_stack = find_closest_base_fake_stack_address(addr, addr+sum(substr_lengthes), substr_lengthes, constraint)
if( custom_stack is None ):
verbose("Couldn't write string in memory because of bad bytes")
return (None,None)
if( custom_stack != addr ):
addr_str = hex(custom_stack)
# Build chain
res = ROPChain()
offset = 0
saved_custom_stack = custom_stack
for (substring_addr,substring_str) in substrings_addr:
if( hex_info ):
substring_info = '\\x'+'\\x'.join(["%02x"%ord(c) for c in substring_str])
else:
substring_info = substring_str
commentStack="Arg2: " + string_ropg("{} + {}".format(addr_str, offset))
commentSubStr="Arg1: " + string_ropg(substring_info)
func_call = build_call(func_name, [substring_addr, custom_stack], constraint, assertion, [commentSubStr, commentStack], optimizeLen=True)
if( isinstance(func_call, str)):
verbose("strcpy: " + func_call)
return (None,None)
else:
res.addChain(func_call)
if( len(res) > lmax ):
return (None,None)
# Adjust
# -1 Because strcpy has a null byte :/
# Except when we INTEND to write a null byte
if( substring_str == '\x00' ):
dec = 0
else:
dec = 1
custom_stack = custom_stack + len(substring_str) -dec
offset = offset + len(substring_str) - dec
return (saved_custom_stack, res)
def STRtoMEM_memcpy(string, addr, constraint, assertion, limit=None, lmax=STR_TO_MEM_LMAX , addr_str=None, hex_info=False):
"""
MEMCPY STRATEGY
Copy the string using memcpy function
"""
if( not addr_str ):
addr_str = hex(addr)
# Getting strcpy function
(func_name, func_addr ) = getFunctionAddress('memcpy')
if( not func_addr ):
verbose('Could not find memcpy function')
return (None,None)
elif( not constraint.badBytes.verifyAddress(func_addr)):
verbose("memcpy address ({}) contains bad bytes".format(hex(func_addr)))
return (None,None)
# We decompose the string in substrings to be copied
substrings_addr = findBytes(string, badBytes = constraint.getBadBytes())
if( not substrings_addr ):
return (None,None)
# Find delivery address
substr_lengthes = [len(substr[1]) for substr in substrings_addr]
if( not limit is None ):
custom_stack = find_closest_base_fake_stack_address(addr, limit, substr_lengthes, constraint)
if( custom_stack is None ):
verbose("Couldn't write string in memory because of bad bytes")
return (None,None)
else:
custom_stack = find_closest_base_fake_stack_address(addr, addr+sum(substr_lengthes), substr_lengthes, constraint)
if( custom_stack is None ):
verbose("Couldn't write string in memory because of bad bytes")
return (None,None)
if( custom_stack != addr ):
addr_str = hex(custom_stack)
# Build chain
res = ROPChain()
offset = 0
saved_custom_stack = custom_stack
for (substring_addr,substring_str) in substrings_addr:
if( hex_info ):
substring_info = "'"+'\\x'+'\\x'.join(["%02x"%ord(c) for c in substring_str])+"'"
else:
substring_info = "'"+substring_str+"'"
comment3 ="Arg3: " + string_ropg(str(len(substring_str)))
comment2 ="Arg2: " + string_ropg(substring_info)
comment1 ="Arg1: " + string_ropg("{} + {}".format(addr_str, offset))
func_call = build_call(func_name, [custom_stack, substring_addr, len(substring_str)],\
constraint, assertion, [comment1, comment2, comment3], optimizeLen=True)
if( isinstance(func_call, str) ):
verbose("memcpy: " + func_call)
return (None,None)
res.addChain(func_call)
if( len(res) > lmax ):
return (None,None)
# Adjust
custom_stack = custom_stack + len(substring_str)
offset = offset + len(substring_str)
return (saved_custom_stack,res)
# Util function
def find_closest_base_fake_stack_address(base, limit, substr_lengthes, constraint):
"""
When writing substrings, a bad address might occur for some of them
BASE <- SUB1
BASE + LEN(SUB1) <- SUB2
BASE + LEN(SUB1) + LEN(SUB2) -- BAD BYTE IN IT !! :O
So find another base address that works in the range [lower_addr..upper_addr]
"""
# Compute the list of addresses that will be used with base and the substring lengthes
def get_addr_list(base, substr_lengthes):
inc = 0
res = [base]
for l in substr_lengthes[:-1]: # Don't take the last one because we don't write after
inc += l
res.append(base + inc)
return res
address = base
total_length = sum(substr_lengthes)
while(address + total_length <= limit):
addr_list = get_addr_list(address, substr_lengthes)
for addr in addr_list:
index = constraint.badBytes.findIndex(addr)
if( index >= 0 ):
# Bad byte found
# If we tried everything for this byte return
if( (address & (0xff << index*8)) == (0xff << index*8) ):
return None
# Other wise add 1 and retry
address += (0x1 << index*8)
break
# No bad bytes found in addresses, return result :)
# Else we keep looping
if( index == -1 ):
return address
# We reached upper limit to write without finding a good address
return None
|
{"/ropgenerator/exploit/HighLevelUtils.py": ["/ropgenerator/exploit/Call.py"], "/ropgenerator/exploit/syscalls/Linux32.py": ["/ropgenerator/exploit/syscalls/SyscallDef.py", "/ropgenerator/exploit/Utils.py"], "/ropgenerator/exploit/Syscall.py": ["/ropgenerator/exploit/syscalls/Linux32.py", "/ropgenerator/exploit/syscalls/Linux64.py"], "/ropgenerator/exploit/Call.py": ["/ropgenerator/exploit/Utils.py"], "/ropgenerator/exploit/syscalls/Linux64.py": ["/ropgenerator/exploit/syscalls/SyscallDef.py", "/ropgenerator/exploit/Utils.py", "/ropgenerator/exploit/Call.py"]}
|
22,644
|
Freebien/ropgenerator
|
refs/heads/master
|
/ropgenerator/Semantics.py
|
# -*- coding: utf-8 -*-
# Semantics module: structure to store gadget semantics
from ropgenerator.Conditions import Cond, CT, CTrue, CFalse
from ropgenerator.Expressions import SSAReg
from ropgenerator.Architecture import r2n
class SPair:
"""
SPair = Semantics pair = (Expression, Condition)
"""
def __init__(self, expr, cond):
self.expr = expr
self.cond = cond
def __str__(self):
return '\t> Value: {}\n\t> Condition: {}\n'.format(self.expr, self.cond)
class Semantics:
"""
Represents semantics of a gadget
self.registers[<SSAReg>] = list of SPair for this register
self.memory[<Expr>] = list of SPair for this mem location
self.final[<reg number>] = bigger index for the register
"""
def __init__(self):
self.registers = dict()
self.memory = dict()
self.final = dict()
self.simplified = False
# Keep track of simplified semantics
self.simplifiedRegs = dict()
def __str__(self):
res = 'Semantics\n'
res += '---------\n'
for reg in self.registers:
res += '\n\t{} {} semantics:\n'.format(reg, r2n(reg.num))
res += '\t--------------\n'
for p in self.registers[reg]:
res += str(p)+'\n'
for addr in self.memory:
res += '\n\tmem[{}] semantics:\n'.format(addr)
res += '\t-----------------\n'
for p in self.memory[addr]:
res += str(p)+'\n'
return res
def get(self, value):
if( isinstance(value, SSAReg)):
return self.registers.get(value, [])
else:
return self.memory.get(value, [])
def set(self, value, spair_list):
if( isinstance(value, SSAReg)):
self.registers[value] = spair_list
else:
self.memory[value] = spair_list
def simplifyValues(self):
"""
Simplifies basic operations, conditions, etc, in order to have
only basic values left ('basic' is the initial state variables,
so Expr with SSA forms of R?_0)
"""
def simplifyReg(semantics, ssaReg):
"""
Compute the basic value for the register
"""
res = []
tmpRes = []
if( ssaReg.ind == 0 ):
semantics.simplifiedRegs[ssaReg] = True
return
# For each possible value
for pair in semantics.registers[ssaReg]:
newPairs = [pair]
# (1) For each sub register in expressions
for subReg in pair.expr.getRegisters():
# Simplify values for sub register
if( not subReg in semantics.simplifiedRegs ):
simplifyReg(self, subReg)
# And replace by its possible values
tmp = []
for p in newPairs:
if( not subReg in p.expr.getRegisters()):
continue
for subPair in semantics.registers[subReg]:
tmp.append(SPair(p.expr.replaceReg(subReg, subPair.expr),\
Cond(CT.AND, subPair.cond, p.cond)))
newPairs = tmp
tmpRes += newPairs
# (2) For each sub register in conditions
for subReg in pair.cond.getRegisters():
# Simplify values for sub register
if( not subReg in semantics.simplifiedRegs ):
simplifyReg(semantics, subReg)
# And replace by its possible values
tmp = []
for subPair in semantics.registers[subReg]:
for p in tmpRes:
tmp.append(SPair(p.expr, Cond(CT.AND, \
p.cond.replaceReg(subReg, subPair.expr), subPair.cond)))
tmpRes = tmp
res = tmpRes
# Dont forget to save and mark it as simplified ;)
semantics.registers[ssaReg] = res
semantics.simplifiedRegs[ssaReg] = True
# Initialize replaceTable
for reg in self.registers.keys():
if( len(self.registers[reg]) == 1):
self.simplifiedRegs[reg] = True
# Replace interatively registers until
for reg in self.registers:
simplifyReg(self, reg)
# Replace registers in memory accesses
newMemory = dict()
for addr in self.memory:
# (1) First we simplify what we write
memoryValues = []
for pair in self.memory[addr]:
# First we replace registers in expression fields
newPairs = [pair]
for subReg in pair.expr.getRegisters():
tmp = []
for subPair in self.registers[subReg]:
for p in newPairs:
tmp.append(SPair(p.expr.replaceReg(subReg, subPair.expr),\
Cond(CT.AND, p.cond, subPair.cond)))
newPairs = tmp
# Then we replace registers in the condition fields
for subReg in pair.cond.getRegisters():
tmp = []
for subPair in self.registers[subReg]:
for p in newPairs:
tmp.append( SPair(p.expr,Cond(CT.AND, subPair.cond,\
p.cond.replaceReg(subReg, subPair.expr))))
newPairs = tmp
memoryValues += newPairs
# (2) Then simplify where we write
addrValues = [SPair(addr, CTrue())]
for subReg in addr.getRegisters():
for subPair in self.registers[subReg]:
addrValues = [SPair(p.expr.replaceReg(subReg, subPair.expr), \
Cond(CT.AND, subPair.cond, p.cond)) for p in addrValues]
# Combine memoryValues and addressValues
for addrPair in addrValues:
tmp = [SPair(p.expr,Cond(CT.AND, p.cond, addrPair.cond)) for p in memoryValues]
newAddr = addrPair.expr.simplify()
newMemory[newAddr] = tmp
# Update memory semantics with the new ones
self.memory = newMemory
def customSemanticAdjust(self):
"""
Make some adjustments in semantics so that it is easier to process by the search engine
"""
## Adjust Cat(0, Extract( x, 0, E))
## --> E if E < 2^(x-1) €z
pass # TODO
def simplifyConditions(self):
"""
Simplifies the dependencies according to the conditions evaluated
to True/False (removes impossible dependencies)
"""
if( self.simplified ):
return
for reg in self.registers.keys():
newPairs = []
for p in self.registers[reg]:
if( p.cond.isTrue()):
pass
if( not p.cond.isFalse()):
p.expr = p.expr.simplify()
newPairs.append( p )
self.registers[reg] = newPairs
for addr in self.memory.keys():
newPairs = []
for p in self.memory[addr]:
if( p.cond.isTrue()):
pass
if( not p.cond.isFalse()):
p.expr = p.expr.simplify()
newPairs.append( p )
self.memory[addr] = newPairs
self.simplified = True
def flattenITE( self ):
"""
Flattens the If-Then-Else statements in dependencies
"""
for reg in self.registers.keys():
self.registers[reg] = [SPair(p.expr, p.cond.flattenITE()) for p in self.registers[reg]]
for addr in self.memory.keys():
self.memory[addr] = [SPair(p.expr, p.cond.flattenITE()) for p in self.memory[addr]]
|
{"/ropgenerator/exploit/HighLevelUtils.py": ["/ropgenerator/exploit/Call.py"], "/ropgenerator/exploit/syscalls/Linux32.py": ["/ropgenerator/exploit/syscalls/SyscallDef.py", "/ropgenerator/exploit/Utils.py"], "/ropgenerator/exploit/Syscall.py": ["/ropgenerator/exploit/syscalls/Linux32.py", "/ropgenerator/exploit/syscalls/Linux64.py"], "/ropgenerator/exploit/Call.py": ["/ropgenerator/exploit/Utils.py"], "/ropgenerator/exploit/syscalls/Linux64.py": ["/ropgenerator/exploit/syscalls/SyscallDef.py", "/ropgenerator/exploit/Utils.py", "/ropgenerator/exploit/Call.py"]}
|
22,645
|
Freebien/ropgenerator
|
refs/heads/master
|
/ropgenerator/exploit/syscalls/Linux32.py
|
# -*- coding:utf-8 -*-
# Linux32 module: build syscalls for linux 32 bits
from ropgenerator.exploit.syscalls.SyscallDef import Syscall
from ropgenerator.exploit.Utils import popMultiple
from ropgenerator.IO import verbose, string_bold, string_ropg, string_payload, error
from ropgenerator.semantic.Engine import search
from ropgenerator.Database import QueryType
from ropgenerator.Constraints import Constraint, Assertion
import ropgenerator.Architecture as Arch
SYSCALL_LMAX = 500
# mprotect
def build_mprotect32(addr, size, prot=7, constraint=None, assertion = None, clmax=SYSCALL_LMAX, optimizeLen=False):
"""
Call mprotect from X86 arch
Args must be on the stack:
int mprotect(void *addr, size_t len, int prot)
args must be in registers (ebx, ecx, edx)
eax must be 0x7d = 125
"""
# Check args
if not isinstance(addr, int):
error("Argument error. Expected integer, got " + str(type(addr)))
return None
elif not isinstance(size, int):
error("Argument error. Expected integer, got " + str(type(size)))
return None
elif not isinstance(prot, int):
error("Argument error. Expected integer, got " + str(type(prot)))
return None
if( constraint is None ):
constraint = Constraint()
if( assertion is None ):
assertion = Assertion()
# Check if we have the function !
verbose("Trying to call mprotect() function directly")
func_call = build_call('mprotect', [addr, size, prot], constraint, assertion, clmax=clmax, optimizeLen=optimizeLen)
if( not isinstance(func_call, str) ):
verbose("Success")
return func_call
else:
if( not constraint.chainable.ret ):
verbose("Coudn't call mprotect(), try direct syscall")
else:
verbose("Couldn't call mprotect() and return to ROPChain")
return None
# Otherwise do syscall directly
# Set the registers
args = [[Arch.n2r('eax'),0x7d],[Arch.n2r('ebx'), addr],[Arch.n2r('ecx'),size], [Arch.n2r('edx'),prot]]
chain = popMultiple(args, constraint, assertion, clmax-1, optimizeLen)
if( not chain ):
verbose("Failed to set registers for the mprotect syscall")
return None
# Int 0x80
int80_gadgets = search(QueryType.INT80, None, None, constraint, assertion)
if( not int80_gadgets ):
verbose("Failed to find an 'int 80' gadget")
return None
else:
chain.addChain(int80_gadgets[0])
verbose("Success")
return chain
mprotect = Syscall('int', 'mprotect', \
[('void*', 'addr'),('size_t','len'),('int','prot')], build_mprotect32)
## All available syscalls
available = dict()
available[mprotect.name+"32"] = mprotect
####################
# Useful functions #
####################
def print_available():
global available
print(string_bold("\n\n\tSupported Linux 32-bits syscalls"))
for name,syscall in available.iteritems():
print("\n\t"+string_payload(name)+": "+str(syscall))
|
{"/ropgenerator/exploit/HighLevelUtils.py": ["/ropgenerator/exploit/Call.py"], "/ropgenerator/exploit/syscalls/Linux32.py": ["/ropgenerator/exploit/syscalls/SyscallDef.py", "/ropgenerator/exploit/Utils.py"], "/ropgenerator/exploit/Syscall.py": ["/ropgenerator/exploit/syscalls/Linux32.py", "/ropgenerator/exploit/syscalls/Linux64.py"], "/ropgenerator/exploit/Call.py": ["/ropgenerator/exploit/Utils.py"], "/ropgenerator/exploit/syscalls/Linux64.py": ["/ropgenerator/exploit/syscalls/SyscallDef.py", "/ropgenerator/exploit/Utils.py", "/ropgenerator/exploit/Call.py"]}
|
22,646
|
Freebien/ropgenerator
|
refs/heads/master
|
/ropgenerator/exploit/Syscall.py
|
# -*- coding:utf-8 -*-
# Syscall module: building ropchains performing syscalls
from ropgenerator.IO import string_special, banner, string_bold, error
from enum import Enum
import ropgenerator.exploit.syscalls.Linux32 as Linux32
import ropgenerator.exploit.syscalls.Linux64 as Linux64
import ropgenerator.Architecture as Arch
from ropgenerator.Constraints import Constraint, Assertion, BadBytes, RegsNotModified
from ropgenerator.Load import loadedBinary
#####################
# Available systems #
#####################
sysLinux32 = "LINUX32"
sysLinux64 = "LINUX64"
availableSystems = [sysLinux32, sysLinux64]
###################
# SYSCALL COMMAND #
###################
OPTION_OUTPUT = '--output-format'
OPTION_OUTPUT_SHORT = '-f'
# Options for output
OUTPUT_CONSOLE = 'console'
OUTPUT_PYTHON = 'python'
OUTPUT_RAW = 'raw'
OUTPUT = None # The one choosen
OPTION_BAD_BYTES = '--bad-bytes'
OPTION_BAD_BYTES_SHORT = '-b'
OPTION_KEEP_REGS = '--keep-regs'
OPTION_KEEP_REGS_SHORT = '-k'
OPTION_LIST = "--list"
OPTION_LIST_SHORT = "-l"
OPTION_FUNCTION = "--call"
OPTION_FUNCTION_SHORT = "-c"
OPTION_HELP = "--help"
OPTION_HELP_SHORT = "-h"
CMD_SYSCALL_HELP = banner([string_bold("'syscall' command"),\
string_special("(Call system functions with ROPChains)")])
CMD_SYSCALL_HELP += "\n\n\t"+string_bold("Usage:")+\
"\n\t\tsyscall [OPTIONS]"
CMD_SYSCALL_HELP += "\n\n\t"+string_bold("Options")+":"
CMD_SYSCALL_HELP += "\n\t\t"+string_special(OPTION_FUNCTION_SHORT)+","+\
string_special(OPTION_FUNCTION)+" <function>\t Call a system function"
CMD_SYSCALL_HELP += "\n\n\t\t"+string_special(OPTION_BAD_BYTES_SHORT)+","+string_special(OPTION_BAD_BYTES)+" <bytes>\t Bad bytes for payload.\n\t\t\t\t\t Expected format is a list of bytes \n\t\t\t\t\t separated by comas (e.g '-b 0A,0B,2F')"
CMD_SYSCALL_HELP += "\n\n\t\t"+string_special(OPTION_KEEP_REGS_SHORT)+","+string_special(OPTION_KEEP_REGS)+" <regs>\t Registers that shouldn't be modified.\n\t\t\t\t\t Expected format is a list of registers \n\t\t\t\t\t separated by comas (e.g '-k edi,eax')"
CMD_SYSCALL_HELP += "\n\n\t\t"+string_special(OPTION_LIST_SHORT)+","+\
string_special(OPTION_LIST)+" [<system>]\t List supported functions"
CMD_SYSCALL_HELP += "\n\n\t\t"+string_special(OPTION_OUTPUT_SHORT)+","+\
string_special(OPTION_OUTPUT)+\
" <fmt> Output format for ropchains.\n\t\t\t\t\t Expected format is one of the\n\t\t\t\t\t following: "+\
string_special(OUTPUT_CONSOLE)+','+string_special(OUTPUT_PYTHON)
CMD_SYSCALL_HELP += "\n\n\t\t"+string_special(OPTION_HELP_SHORT)+","+string_special(OPTION_HELP)+"\t\t Show this help"
CMD_SYSCALL_HELP += "\n\n\t"+string_bold("Supported systems")+": "+', '.join([string_special(s) for s in availableSystems])
CMD_SYSCALL_HELP += "\n\n\t"+string_bold("Function format")+": "+\
string_special("function")+"( "+string_special("arg1")+","+string_special(" ...")+\
"," + string_special(" argN")+")"
CMD_SYSCALL_HELP += "\n\n\t"+string_bold("Examples")+": "+\
"\n\t\tsyscall -f python -c mprotect32(0x123456, 200, 7)\n\t\tsyscall -l LINUX64"
def print_help():
print(CMD_SYSCALL_HELP)
def syscall(args):
global OUTPUT, OUTPUT_CONSOLE, OUTPUT_PYTHON
# Parsing arguments
if( not args):
print_help()
return
OUTPUT = OUTPUT_CONSOLE
funcName = None
i = 0
seenOutput = False
seenFunction = False
seenBadBytes = False
seenKeepRegs = False
constraint = Constraint()
assertion = Assertion()
while i < len(args):
if( args[i] in [OPTION_LIST, OPTION_LIST_SHORT]):
listSyscalls(args[1:])
return
if( args[i] in [OPTION_BAD_BYTES, OPTION_BAD_BYTES_SHORT]):
if( seenBadBytes ):
error("Error. '" + args[i] + "' option should be used only once")
return
if( i+1 >= len(args)):
error("Error. Missing bad bytes after option '"+args[i]+"'")
return
seenBadBytes = True
(success, res) = parse_bad_bytes(args[i+1])
if( not success ):
error(res)
return
i = i+2
constraint = constraint.add(BadBytes(res))
elif( args[i] in [OPTION_KEEP_REGS, OPTION_KEEP_REGS_SHORT]):
if( seenKeepRegs ):
error("Error. '" + args[i] + "' option should be used only once")
return
if( i+1 >= len(args)):
error("Error. Missing register after option '"+args[i]+"'")
return
seenKeepRegs = True
(success, res) = parse_keep_regs(args[i+1])
if( not success ):
error(res)
return
i = i+2
constraint = constraint.add(RegsNotModified(res))
elif( args[i] in [OPTION_FUNCTION, OPTION_FUNCTION_SHORT] ):
if( not loadedBinary() ):
error("Error. You should load a binary before building ROPChains")
return
elif( seenFunction ):
error("Option '{}' should be used only once".format(args[i]))
return
userInput = ''
i +=1
while( i < len(args) and args[i][0] != "-"):
userInput += args[i]
i += 1
(funcName, funcArgs ) = parseFunction(userInput)
if( not funcName):
return
seenFunction = True
elif( args[i] in [OPTION_OUTPUT, OPTION_OUTPUT_SHORT]):
if( seenOutput ):
error("Option '{}' should be used only once".format(args[i]))
return
if( i+1 >= len(args)):
error("Error. Missing output format after option '"+args[i]+"'")
return
if( args[i+1] in [OUTPUT_CONSOLE, OUTPUT_PYTHON]):
OUTPUT = args[i+1]
seenOutput = True
i += 2
else:
error("Error. Unknown output format: {}".format(args[i+1]))
return
elif( args[i] in [OPTION_HELP, OPTION_HELP_SHORT]):
print_help()
return
else:
error("Error. Unknown option '{}'".format(args[i]))
return
if( not funcName ):
error("Missing function to call")
else:
call(funcName, funcArgs, constraint, assertion)
def call(funcName, parsedArgs, constraint, assertion):
# Get target system
if( Arch.currentBinType == Arch.BinaryType.X86_ELF ):
syscall = Linux32.available.get(funcName)
system = sysLinux32
elif( Arch.currentBinType == Arch.BinaryType.X64_ELF ):
syscall = Linux64.available.get(funcName)
system = sysLinux64
else:
error("Binary type '{}' not supported yet".format(Arch.currentBinType))
return
if( not syscall ):
error("Syscall '{}' not supported for system '{}'".format(\
funcName, system))
return
if( len(parsedArgs) != len(syscall.args)):
error("Error. Wrong number of arguments")
return
# Build syscall
res = _build_syscall(syscall.buildFunc, parsedArgs, constraint, assertion, optimizeLen = True)
# Print result
if( not res ):
print(string_bold("\n\tNo matching ROPChain found"))
else:
print(string_bold("\n\tFound matching ROPChain\n"))
badBytes = constraint.getBadBytes()
if( OUTPUT == OUTPUT_CONSOLE ):
print(res.strConsole(Arch.bits(), badBytes))
elif( OUTPUT == OUTPUT_PYTHON ):
print(res.strPython(Arch.bits(), badBytes))
def _build_syscall(funcPointer, args , constraint, assertion, optimizeLen=False):
if( len(args) == 0 ):
return funcPointer(constraint, assertion, optimizeLen=optimizeLen)
elif( len(args) == 1 ):
return funcPointer(args[0], constraint, assertion,optimizeLen=optimizeLen)
elif( len(args) == 2 ):
return funcPointer(args[0], args[1], constraint, assertion, optimizeLen=optimizeLen)
elif( len(args) == 3 ):
return funcPointer(args[0], args[1], args[2], constraint, assertion, optimizeLen=optimizeLen)
elif( len(args) == 4 ):
return funcPointer(args[0], args[1], args[2], args[3], constraint, assertion, optimizeLen=optimizeLen)
elif( len(args) == 5 ):
return funcPointer(args[0], args[1], args[2], args[3], args[4], constraint, assertion, optimizeLen=optimizeLen)
else:
error("{}-arguments calls not supported".format(len(args)))
return []
def listSyscalls(args):
if( not args ):
systems = availableSystems
else:
systems = []
for arg in args:
if( arg in availableSystems ):
systems.append(arg)
else:
error("Unknown system: '{}'".format(arg))
return
for system in list(set(systems)):
if( system == sysLinux32 ):
Linux32.print_available()
elif( system == sysLinux64 ):
Linux64.print_available()
def parseFunction(string):
def seek(char, string):
for i in range(0, len(string)):
if string[i] == char:
return (string[:i], i)
return ([],-1)
if( not string ):
error("Missing fuction to call")
return (None, None)
# COmpress the string
string = "".join(string.split())
# Get the function name
(funcName, index) = seek("(", string)
if( not funcName ):
error("Invalid function call")
return (None, None)
rest = string[index+1:]
args = []
arg = ''
i = 0
end = False
while(i < len(rest)):
c = rest[i]
# No args
if( c == ")" and not args):
end = True
i += 1
# String
elif( c == '"' or c == "'" ):
(s, index)= seek(c, rest[i+1:])
if( not s ):
error("Missing closing {} for string".format(c))
return (None, None)
args.append(s)
i += index +2
if( i >= len(rest)):
error("Error. Missing ')'")
return (None, None)
elif( rest[i] == ')' ):
end = True
i += 1
elif( rest[i] == "," ):
i += 1
# Constant
else:
# Get the constant
arg = ''
ok = False
for j in range(i, len(rest)):
if( rest[j] == ")" ):
end = True
ok = True
break
elif( rest[j] == ','):
ok = True
break
else:
arg += rest[j]
if( not ok ):
error("Missing ')' after argument")
return (None, None)
if( (not arg) and args):
error("Missing argument")
return (None, None)
# Convert to int
try:
value = int(arg)
except:
try:
value = int(arg, 16)
except:
try:
value = int(arg, 2)
except:
error("Invalid operand: " + arg )
return (None, None)
args.append(value)
i = j+1
if( end):
break
if( not end ):
error("Error. Missing ')'")
return (None, None)
if( i < len(rest)):
error("Error. Extra argument: {}".format(rest[i:]))
return (None, None)
return (funcName, args)
## ------------
## Parsing from ropgenerator.semantic.Find
def parse_bad_bytes(string):
"""
Parses a bad bytes string into a list of bad bytes
Input: a string of format like "00,0A,FF,32,C7"
Ouput if valid string : (True, list) where list =
['00', '0a', 'ff', '32', 'c7'] (separate them in individual strings
and force lower case)
Output if invalid string (False, error_message)
"""
hex_chars = '0123456789abcdefABCDEF'
i = 0
bad_bytes = []
user_bad_bytes = [b.lower() for b in string.split(',')]
for user_bad_byte in user_bad_bytes:
if( not user_bad_byte ):
return (False, "Error. Missing bad byte after ','")
elif( len(user_bad_byte) != 2 ):
return (False, "Error. '{}' is not a valid byte".format(user_bad_byte))
elif( not ((user_bad_byte[i] in hex_chars) and (user_bad_byte[i+1] in hex_chars))):
return (False, "Error. '{}' is not a valid byte".format(user_bad_byte))
else:
bad_bytes.append(user_bad_byte)
return (True, bad_bytes)
def parse_keep_regs(string):
"""
Parses a 'keep registers' string into a list of register uids
Input: a string of format like "rax,rcx,rdi"
Output if valid string (True, list) where list =
[1, 3, 4] (R1 is rax, R3 is RCX, ... )
Output if invalid string (False, error_message)
"""
user_keep_regs = string.split(',')
keep_regs = set()
for reg in user_keep_regs:
if( reg in Arch.regNameToNum ):
keep_regs.add(Arch.n2r(reg))
else:
return (False, "Error. '{}' is not a valid register".format(reg))
return (True, list(keep_regs))
|
{"/ropgenerator/exploit/HighLevelUtils.py": ["/ropgenerator/exploit/Call.py"], "/ropgenerator/exploit/syscalls/Linux32.py": ["/ropgenerator/exploit/syscalls/SyscallDef.py", "/ropgenerator/exploit/Utils.py"], "/ropgenerator/exploit/Syscall.py": ["/ropgenerator/exploit/syscalls/Linux32.py", "/ropgenerator/exploit/syscalls/Linux64.py"], "/ropgenerator/exploit/Call.py": ["/ropgenerator/exploit/Utils.py"], "/ropgenerator/exploit/syscalls/Linux64.py": ["/ropgenerator/exploit/syscalls/SyscallDef.py", "/ropgenerator/exploit/Utils.py", "/ropgenerator/exploit/Call.py"]}
|
22,647
|
Freebien/ropgenerator
|
refs/heads/master
|
/ropgenerator/exploit/Call.py
|
# -*- coding:utf-8 -*-
# Call module: call functions with ropchains
from ropgenerator.IO import string_special, string_bold, banner, error, string_ropg
from ropgenerator.Constraints import Constraint, Assertion, BadBytes, RegsNotModified
from ropgenerator.Load import loadedBinary
from ropgenerator.exploit.Scanner import getFunctionAddress, getAllFunctions
from ropgenerator.semantic.ROPChains import ROPChain, validAddrStr
from ropgenerator.semantic.Engine import search
from ropgenerator.Database import QueryType
from ropgenerator.exploit.Utils import popMultiple
import ropgenerator.Architecture as Arch
###################
# CALL COMMAND #
###################
OPTION_OUTPUT = '--output-format'
OPTION_OUTPUT_SHORT = '-f'
# Options for output
OUTPUT_CONSOLE = 'console'
OUTPUT_PYTHON = 'python'
OUTPUT_RAW = 'raw'
OUTPUT = None # The one choosen
OPTION_BAD_BYTES = '--bad-bytes'
OPTION_BAD_BYTES_SHORT = '-b'
OPTION_CALL = "--call"
OPTION_CALL_SHORT = "-c"
OPTION_KEEP_REGS = '--keep-regs'
OPTION_KEEP_REGS_SHORT = '-k'
OPTION_LIST = "--list"
OPTION_LIST_SHORT = "-l"
OPTION_HELP = "--help"
OPTION_HELP_SHORT = "-h"
OPTION_SHORTEST = '--shortest'
OPTION_SHORTEST_SHORT = '-s'
OPTION_LMAX = '--max-length'
OPTION_LMAX_SHORT = '-m'
CMD_CALL_HELP = banner([string_bold("'call' command"),\
string_special("(Call functions with ROPChains)")])
CMD_CALL_HELP += "\n\n\t"+string_bold("Usage:")+\
"\n\t\tcall [OPTIONS]"
CMD_CALL_HELP += "\n\n\t"+string_bold("Options")+":"
CMD_CALL_HELP += "\n\t\t"+string_special(OPTION_CALL_SHORT)+","+\
string_special(OPTION_CALL)+" <function>\t Call a function"
CMD_CALL_HELP += "\n\n\t\t"+string_special(OPTION_BAD_BYTES_SHORT)+","+string_special(OPTION_BAD_BYTES)+" <bytes>\t Bad bytes for payload.\n\t\t\t\t\t Expected format is a list of bytes \n\t\t\t\t\t separated by comas (e.g '-b 0A,0B,2F')"
CMD_CALL_HELP += "\n\n\t\t"+string_special(OPTION_KEEP_REGS_SHORT)+","+string_special(OPTION_KEEP_REGS)+" <regs>\t Registers that shouldn't be modified.\n\t\t\t\t\t Expected format is a list of registers \n\t\t\t\t\t separated by comas (e.g '-k edi,eax')"
CMD_CALL_HELP += "\n\n\t\t"+string_special(OPTION_LMAX_SHORT)+","+string_special(OPTION_LMAX)+" <int>\t Max length of the ROPChain in bytes"
CMD_CALL_HELP += "\n\n\t\t"+string_special(OPTION_SHORTEST_SHORT)+","+string_special(OPTION_SHORTEST)+"\t\t Find the shortest matching ROP-Chains"
CMD_CALL_HELP += "\n\n\t\t"+string_special(OPTION_LIST_SHORT)+","+\
string_special(OPTION_LIST)+"\t\t List available functions"
CMD_CALL_HELP += "\n\n\t\t"+string_special(OPTION_OUTPUT_SHORT)+","+\
string_special(OPTION_OUTPUT)+\
" <fmt> Output format for ropchains.\n\t\t\t\t\t Expected format is one of the\n\t\t\t\t\t following: "+\
string_special(OUTPUT_CONSOLE)+','+string_special(OUTPUT_PYTHON)
CMD_CALL_HELP += "\n\n\t\t"+string_special(OPTION_HELP_SHORT)+","+string_special(OPTION_HELP)+"\t\t Show this help"
CMD_CALL_HELP += "\n\n\t"+string_bold("Function format")+": "+\
string_special("function")+"( "+string_special("arg1")+","+string_special(" ...")+\
"," + string_special(" argN")+")"
CMD_CALL_HELP += "\n\n\t"+string_bold("Examples")+": "+\
"\n\t\tcall strcpy(0x123456, 0x987654)"
def print_help():
print(CMD_CALL_HELP)
def call(args):
global OUTPUT, OUTPUT_CONSOLE, OUTPUT_PYTHON
# Parsing arguments
if( not args):
print_help()
return
OUTPUT = OUTPUT_CONSOLE
funcName = None
i = 0
seenOutput = False
seenFunction = False
seenBadBytes = False
seenKeepRegs = False
seenShortest = False
seenLmax = False
clmax = None
constraint = Constraint()
assertion = Assertion()
while i < len(args):
if( args[i] in [OPTION_LIST, OPTION_LIST_SHORT]):
func_list = getAllFunctions()
print_functions(func_list)
return
if( args[i] in [OPTION_BAD_BYTES, OPTION_BAD_BYTES_SHORT]):
if( seenBadBytes ):
error("Error. '" + args[i] + "' option should be used only once")
return
if( i+1 >= len(args)):
error("Error. Missing bad bytes after option '"+args[i]+"'")
return
seenBadBytes = True
(success, res) = parse_bad_bytes(args[i+1])
if( not success ):
error(res)
return
i = i+2
constraint = constraint.add(BadBytes(res))
elif( args[i] in [OPTION_KEEP_REGS, OPTION_KEEP_REGS_SHORT]):
if( seenKeepRegs ):
error("Error. '" + args[i] + "' option should be used only once")
return
if( i+1 >= len(args)):
error("Error. Missing register after option '"+args[i]+"'")
return
seenKeepRegs = True
(success, res) = parse_keep_regs(args[i+1])
if( not success ):
error(res)
return
i = i+2
constraint = constraint.add(RegsNotModified(res))
elif( args[i] in [OPTION_CALL, OPTION_CALL_SHORT] ):
if( not loadedBinary() ):
error("Error. You should load a binary before building ROPChains")
return
elif( seenFunction ):
error("Option '{}' should be used only once".format(args[i]))
return
userInput = ''
i +=1
while( i < len(args) and args[i][0] != "-"):
userInput += args[i]
i += 1
(funcName, funcArgs ) = parseFunction(userInput)
if( not funcName):
return
seenFunction = True
elif( args[i] in [OPTION_OUTPUT, OPTION_OUTPUT_SHORT]):
if( seenOutput ):
error("Option '{}' should be used only once".format(args[i]))
return
if( i+1 >= len(args)):
error("Error. Missing output format after option '"+args[i]+"'")
return
if( args[i+1] in [OUTPUT_CONSOLE, OUTPUT_PYTHON]):
OUTPUT = args[i+1]
seenOutput = True
i += 2
else:
error("Error. Unknown output format: {}".format(args[i+1]))
return
elif( args[i] in [OPTION_SHORTEST, OPTION_SHORTEST_SHORT]):
if( seenShortest ):
error("Option '{}' should be used only once".format(args[i]))
return
seenShortest = True
i += 1
elif( args[i] == OPTION_LMAX or args[i] == OPTION_LMAX_SHORT ):
if( seenLmax ):
error("Option '{}' should be used only once".format(args[i]))
return
if( i+1 >= len(args)):
error("Error. Missing length after option '"+args[i]+"'")
return
try:
clmax = int(args[i+1])
if( clmax < Arch.octets() ):
raise Exception()
# Convert number of bytes into number of ropchain elements
clmax /= Arch.octets()
except:
error("Error. '" + args[i+1] +"' bytes is not valid")
return
i += 2
seenLmax = True
elif( args[i] in [OPTION_HELP, OPTION_HELP_SHORT]):
print_help()
return
else:
error("Error. Unknown option '{}'".format(args[i]))
return
if( not funcName ):
error("Missing function to call")
else:
res = build_call(funcName, funcArgs, constraint, assertion, clmax=clmax, optimizeLen=seenShortest)
if( isinstance(res, str) ):
error(res)
else:
print_chains([res], "Built matching ROPChain", constraint.getBadBytes())
def build_call(funcName, funcArgs, constraint, assertion, argsDescription=None, clmax=None, optimizeLen=False):
"""
funcArgs : list of pairs (arg_value, arg_description)
"""
# Merge description and args
if( argsDescription ):
funcArgs = zip(funcArgs, argsDescription)
else:
funcArgs = [(arg,) for arg in funcArgs]
if( Arch.currentBinType == Arch.BinaryType.X86_ELF ):
return build_call_linux86(funcName, funcArgs, constraint, assertion, clmax, optimizeLen)
elif( Arch.currentBinType == Arch.BinaryType.X64_ELF ):
return build_call_linux64(funcName, funcArgs, constraint, assertion, clmax, optimizeLen)
return []
def build_call_linux64(funcName, funcArgs, constraint, assertion, clmax=None, optimizeLen=False):
# Arguments registers
# (Args should go in these registers for x64)
argsRegsNames = ['rdi','rsi','rdx','rcx', 'r8', 'r9']
argsRegs = [Arch.n2r(name) for name in argsRegsNames]
# Find the address of the fonction
(funcName2, funcAddr) = getFunctionAddress(funcName)
if( funcName2 is None ):
return "Couldn't find function '{}' in the binary".format(funcName)
# Check if bad bytes in function address
if( not constraint.badBytes.verifyAddress(funcAddr) ):
return "'{}' address ({}) contains bad bytes".format(funcName2, string_special('0x'+format(funcAddr, '0'+str(Arch.octets()*2)+'x')))
# Check how many arguments
if( len(funcArgs) > 6 ):
return "Doesn't support function call with more than 6 arguments with Linux X64 calling convention :("
# Find a gadget for the fake return address
if( funcArgs ):
# Build the ropchain with the arguments
args_chain = popMultiple(map(lambda x,y:(x,)+y, argsRegs[:len(funcArgs)], funcArgs), constraint, assertion, clmax=clmax, optimizeLen=optimizeLen)
if( not args_chain):
return "Couldn't load arguments in registers"
else:
# No arguments
args_chain = ROPChain()
# Build call chain (function address + fake return address)
return args_chain.addPadding(funcAddr, comment=string_ropg(funcName2))
def build_call_linux86(funcName, funcArgs, constraint, assertion, clmax=None, optimizeLen=False):
# Find the address of the fonction
(funcName2, funcAddr) = getFunctionAddress(funcName)
if( funcName2 is None ):
return "Couldn't find function '{}' in the binary".format(funcName)
# Check if bad bytes in function address
if( not constraint.badBytes.verifyAddress(funcAddr) ):
return "'{}' address ({}) contains bad bytes".format(funcName2, string_special('0x'+format(funcAddr, '0'+str(Arch.octets()*2)+'x')))
# Check if lmax too small
if( (1 + len(funcArgs) + (lambda x: 1 if len(x)>0 else 0)(funcArgs)) > clmax ):
return "Not enough bytes to call function '{}'".format(funcName)
# Find a gadget for the fake return address
if( funcArgs ):
offset = (len(funcArgs)-1)*Arch.octets() # Because we do +octets() at the beginning of the loop
skip_args_chains = []
i = 4 # Try 4 more maximum
while( i > 0 and (not skip_args_chains)):
offset += Arch.octets()
skip_args_chains = search(QueryType.MEMtoREG, Arch.ipNum(), \
(Arch.spNum(),offset), constraint, assertion, n=1, optimizeLen=optimizeLen)
i -= 1
if( not skip_args_chains ):
return "Couldn't build ROP-Chain"
skip_args_chain = skip_args_chains[0]
else:
# No arguments
skip_args_chain = None
# Build the ropchain with the arguments
args_chain = ROPChain()
arg_n = len(funcArgs)
for arg in reversed(funcArgs):
if( isinstance(arg, int) ):
args_chain.addPadding(arg, comment="Arg{}: {}".format(arg_n, string_ropg(hex(arg))))
arg_n -= 1
else:
return "Type of argument '{}' not supported yet :'(".format(arg)
# Build call chain (function address + fake return address)
call_chain = ROPChain()
call_chain.addPadding(funcAddr, comment=string_ropg(funcName2))
if( funcArgs ):
skip_args_addr = int( validAddrStr(skip_args_chain.chain[0], constraint.getBadBytes(), Arch.bits()) ,16)
call_chain.addPadding(skip_args_addr, comment="Address of: "+string_bold(str(skip_args_chain.chain[0])))
return call_chain.addChain(args_chain)
def parseFunction(string):
def seek(char, string):
for i in range(0, len(string)):
if string[i] == char:
return (string[:i], i)
return ([],-1)
if( not string ):
error("Missing fuction to call")
return (None, None)
# COmpress the string
string = "".join(string.split())
# Get the function name
(funcName, index) = seek("(", string)
if( not funcName ):
error("Invalid function call")
return (None, None)
rest = string[index+1:]
args = []
arg = ''
i = 0
end = False
while(i < len(rest)):
c = rest[i]
# No args
if( c == ")" and not args):
end = True
i += 1
# String
elif( c == '"' or c == "'" ):
(s, index)= seek(c, rest[i+1:])
if( not s ):
error("Missing closing {} for string".format(c))
return (None, None)
args.append(s)
i += index +2
if( i >= len(rest)):
error("Error. Missing ')'")
return (None, None)
elif( rest[i] == ')' ):
end = True
i += 1
elif( rest[i] == "," ):
i += 1
# Constant
else:
# Get the constant
arg = ''
ok = False
for j in range(i, len(rest)):
if( rest[j] == ")" ):
end = True
ok = True
break
elif( rest[j] == ','):
ok = True
break
else:
arg += rest[j]
if( not ok ):
error("Missing ')' after argument")
return (None, None)
if( (not arg) and args):
error("Missing argument")
return (None, None)
# Convert to int
try:
value = int(arg)
except:
try:
value = int(arg, 16)
except:
try:
value = int(arg, 2)
except:
error("Invalid operand: " + arg )
return (None, None)
args.append(value)
i = j+1
if( end):
break
if( not end ):
error("Error. Missing ')'")
return (None, None)
if( i < len(rest)):
error("Error. Extra argument: {}".format(rest[i:]))
return (None, None)
return (funcName, args)
## ------------
## Parsing from ropgenerator.semantic.Find
def parse_bad_bytes(string):
"""
Parses a bad bytes string into a list of bad bytes
Input: a string of format like "00,0A,FF,32,C7"
Ouput if valid string : (True, list) where list =
['00', '0a', 'ff', '32', 'c7'] (separate them in individual strings
and force lower case)
Output if invalid string (False, error_message)
"""
hex_chars = '0123456789abcdefABCDEF'
i = 0
bad_bytes = []
user_bad_bytes = [b.lower() for b in string.split(',')]
for user_bad_byte in user_bad_bytes:
if( not user_bad_byte ):
return (False, "Error. Missing bad byte after ','")
elif( len(user_bad_byte) != 2 ):
return (False, "Error. '{}' is not a valid byte".format(user_bad_byte))
elif( not ((user_bad_byte[i] in hex_chars) and (user_bad_byte[i+1] in hex_chars))):
return (False, "Error. '{}' is not a valid byte".format(user_bad_byte))
else:
bad_bytes.append(user_bad_byte)
return (True, bad_bytes)
def parse_keep_regs(string):
"""
Parses a 'keep registers' string into a list of register uids
Input: a string of format like "rax,rcx,rdi"
Output if valid string (True, list) where list =
[1, 3, 4] (R1 is rax, R3 is RCX, ... )
Output if invalid string (False, error_message)
"""
user_keep_regs = string.split(',')
keep_regs = set()
for reg in user_keep_regs:
if( reg in Arch.regNameToNum ):
keep_regs.add(Arch.n2r(reg))
else:
return (False, "Error. '{}' is not a valid register".format(reg))
return (True, list(keep_regs))
##########################
# Pretty print functions #
##########################
def print_chains(chainList, msg, badBytes=[]):
global OUTPUT
sep = "------------------"
if( chainList):
print(string_bold('\n\t'+msg))
if( OUTPUT == OUTPUT_CONSOLE ):
print("\n"+chainList[0].strConsole(Arch.currentArch.bits, badBytes))
elif( OUTPUT == OUTPUT_PYTHON ):
print('\n' + chainList[0].strPython(Arch.currentArch.bits, badBytes))
for chain in chainList[1:]:
if( OUTPUT == OUTPUT_CONSOLE ):
print('\t'+sep + "\n"+ chain.strConsole(Arch.currentArch.bits, badBytes))
elif( OUTPUT == OUTPUT_PYTHON ):
print('\t'+sep + '\n' + chain.strPython(Arch.currentArch.bits, badBytes))
else:
print(string_bold("\n\tNo matching ROPChain found"))
def print_functions(func_list):
"""
func_list - list of pairs (str, int) = (funcName, funcAddress)
"""
space = 28
print(banner([string_bold("Available functions")]))
print("\tFunction" + " "*(space-8) + "Address")
print("\t------------------------------------")
for (funcName, funcAddr) in sorted(func_list, key=lambda x:x[0] ):
space2 = space - len(funcName)
if( space2 < 0 ):
space2 = 2
print("\t"+string_special(funcName)+ " "*space2 + hex(funcAddr))
print("")
|
{"/ropgenerator/exploit/HighLevelUtils.py": ["/ropgenerator/exploit/Call.py"], "/ropgenerator/exploit/syscalls/Linux32.py": ["/ropgenerator/exploit/syscalls/SyscallDef.py", "/ropgenerator/exploit/Utils.py"], "/ropgenerator/exploit/Syscall.py": ["/ropgenerator/exploit/syscalls/Linux32.py", "/ropgenerator/exploit/syscalls/Linux64.py"], "/ropgenerator/exploit/Call.py": ["/ropgenerator/exploit/Utils.py"], "/ropgenerator/exploit/syscalls/Linux64.py": ["/ropgenerator/exploit/syscalls/SyscallDef.py", "/ropgenerator/exploit/Utils.py", "/ropgenerator/exploit/Call.py"]}
|
22,648
|
Freebien/ropgenerator
|
refs/heads/master
|
/ropgenerator/exploit/syscalls/SyscallDef.py
|
# -*- coding:utf-8 -*-
# SyscallDef module: small data structure for syscalls
from ropgenerator.IO import string_special, string_bold
class Syscall:
def __init__(self, retType, name, args, buildFunc):
self.ret = retType
self.name = name
self.args = args
self.buildFunc = buildFunc
def __str__(self):
res = self.ret + " " + string_bold(self.name)
res += "("
res += ', '.join([a[0] + " " + string_special(a[1]) for a in self.args])
res += ")"
return res
|
{"/ropgenerator/exploit/HighLevelUtils.py": ["/ropgenerator/exploit/Call.py"], "/ropgenerator/exploit/syscalls/Linux32.py": ["/ropgenerator/exploit/syscalls/SyscallDef.py", "/ropgenerator/exploit/Utils.py"], "/ropgenerator/exploit/Syscall.py": ["/ropgenerator/exploit/syscalls/Linux32.py", "/ropgenerator/exploit/syscalls/Linux64.py"], "/ropgenerator/exploit/Call.py": ["/ropgenerator/exploit/Utils.py"], "/ropgenerator/exploit/syscalls/Linux64.py": ["/ropgenerator/exploit/syscalls/SyscallDef.py", "/ropgenerator/exploit/Utils.py", "/ropgenerator/exploit/Call.py"]}
|
22,649
|
Freebien/ropgenerator
|
refs/heads/master
|
/ropgenerator/exploit/syscalls/Linux64.py
|
# -*- coding:utf-8 -*-
# Linux32 module: build syscalls for linux 32 bits
from ropgenerator.exploit.syscalls.SyscallDef import Syscall
from ropgenerator.exploit.Utils import popMultiple
from ropgenerator.exploit.Call import build_call
from ropgenerator.IO import verbose, string_bold, string_ropg, string_payload, error
from ropgenerator.semantic.Engine import search
from ropgenerator.Database import QueryType
from ropgenerator.Constraints import Constraint, Assertion
import ropgenerator.Architecture as Arch
SYSCALL_LMAX = 500
# mprotect
def build_mprotect64(addr, size, prot=7, constraint=None, assertion=None, clmax=SYSCALL_LMAX, optimizeLen=False):
"""
Call mprotect from X86-64 arch
Args must be on registers (rdi, rsi, rdx):
Sizes are (unsigned long, size_t, unsigned long)
rax must be 10
"""
# Check args
if not isinstance(addr, int):
error("Argument error. Expected integer, got " + str(type(addr)))
return None
elif not isinstance(size, int):
error("Argument error. Expected integer, got " + str(type(size)))
return None
elif not isinstance(prot, int):
error("Argument error. Expected integer, got " + str(type(prot)))
return None
if( constraint is None ):
constraint = Constraint()
if( assertion is None ):
assertion = Assertion()
# Check if we have the function !
verbose("Trying to call mprotect() function directly")
func_call = build_call('mprotect', [addr, size, prot], constraint, assertion, clmax=clmax, optimizeLen=optimizeLen)
if( not isinstance(func_call, str) ):
verbose("Success")
return func_call
else:
if( not constraint.chainable.ret ):
verbose("Coudn't call mprotect(), try direct syscall")
else:
verbose("Couldn't call mprotect() and return to ROPChain")
return None
# Otherwise do the syscall by 'hand'
# Set the registers
args = [[Arch.n2r('rdi'),addr],[Arch.n2r('rsi'), size],[Arch.n2r('rdx'),prot], [Arch.n2r('rax'),10]]
chain = popMultiple(args, constraint, assertion, clmax-1, optimizeLen)
if( not chain ):
verbose("Failed to set registers for the mprotect syscall")
return None
# Syscall
syscalls = search(QueryType.SYSCALL, None, None, constraint, assertion)
if( not syscalls ):
verbose("Failed to find a syscall gadget")
return None
else:
chain.addChain(syscalls[0])
verbose("Success")
return chain
mprotect = Syscall('int', 'mprotect', \
[('void*', 'addr'),('size_t','len'),('int','prot')], build_mprotect64)
## All available syscalls
available = dict()
available[mprotect.name+"64"] = mprotect
####################
# Useful functions #
####################
def print_available():
global available
print(string_bold("\n\n\tSupported Linux 64-bits syscalls"))
for name,syscall in available.iteritems():
print("\n\t"+string_payload(name)+": "+str(syscall))
|
{"/ropgenerator/exploit/HighLevelUtils.py": ["/ropgenerator/exploit/Call.py"], "/ropgenerator/exploit/syscalls/Linux32.py": ["/ropgenerator/exploit/syscalls/SyscallDef.py", "/ropgenerator/exploit/Utils.py"], "/ropgenerator/exploit/Syscall.py": ["/ropgenerator/exploit/syscalls/Linux32.py", "/ropgenerator/exploit/syscalls/Linux64.py"], "/ropgenerator/exploit/Call.py": ["/ropgenerator/exploit/Utils.py"], "/ropgenerator/exploit/syscalls/Linux64.py": ["/ropgenerator/exploit/syscalls/SyscallDef.py", "/ropgenerator/exploit/Utils.py", "/ropgenerator/exploit/Call.py"]}
|
22,672
|
HadrienRenaud/simple-calculator-kata
|
refs/heads/master
|
/test_calculator.py
|
from unittest import TestCase
from unittest.mock import patch, MagicMock
from calculator import Calculator
class TestCalculator(TestCase):
def test_add_null(self):
self.assertEqual(Calculator.add(""), 0)
def test_add_one(self):
self.assertEqual(Calculator.add("1"), 1)
self.assertEqual(Calculator.add("12.56"), 12.56)
def test_add_two(self):
self.assertEqual(Calculator.add("1,0"), 1)
self.assertEqual(Calculator.add("1,2"), 3)
self.assertEqual(Calculator.add("12,34"), 46)
def test_add_unkwown(self):
self.assertEqual(
Calculator.add(','.join(map(str, range(100)))),
100 * 99 / 2
)
self.assertEqual(
Calculator.add(','.join(map(str, range(100, 201)))),
200 * 201 / 2 - 100 * 99 / 2
)
def test_add_lines(self):
self.assertEqual(
Calculator.add('\n'.join(map(str, range(100)))),
100 * 99 / 2
)
self.assertEqual(
Calculator.add('\n'.join(map(str, range(0, 101, 2)))),
50 * 51
)
def test_add_custom_separator(self):
self.assertEqual(Calculator.add("//#\n1#2#3"), 6)
self.assertEqual(Calculator.add("//##\n1##2##3"), 6)
def test_add_negative(self):
self.assertRaises(Exception, Calculator.add, ["-2"])
self.assertRaises(Exception, Calculator.add, ["1,-2"])
self.assertRaises(Exception, Calculator.add, ["-\n-1,-2"])
def test_add_superior_1000(self):
self.assertEqual(Calculator.add("2,1001"), 2)
self.assertEqual(Calculator.add("2,1000,3"), 1005)
self.assertEqual(
Calculator.add(",".join(map(str, range(1200)))),
1000 * 1001 / 2
)
def test_add_multiple_custom_separator(self):
self.assertEqual(Calculator.add("//[#][%]\n1#2%3"), 6)
self.assertEqual(Calculator.add("//[##][%%]\n1##2%%3"), 6)
@patch('calculator.ILogger.write')
def test_add_simple_log(self, mock_write):
Calculator.add("1")
mock_write.assert_called_once()
@patch('calculator.ILogger.write')
def test_add_null_check_log(self, mock_write):
Calculator.add("")
mock_write.assert_called_once_with(0)
@patch('calculator.ILogger.write')
def test_add_one_check_log(self, mock_write):
Calculator.add("1")
mock_write.assert_called_once_with(1)
mock_write.reset_mock()
Calculator.add("12.56")
mock_write.assert_called_once_with(12.56)
mock_write.reset_mock()
@patch('calculator.ILogger.write')
def test_add_two_check_log(self, mock_write):
Calculator.add("1,0")
mock_write.assert_called_once_with(1)
mock_write.reset_mock()
Calculator.add("1,2")
mock_write.assert_called_once_with(3)
mock_write.reset_mock()
Calculator.add("12,34")
mock_write.assert_called_once_with(46)
mock_write.reset_mock()
@patch('calculator.ILogger.write')
def test_add_unkwown_check_log(self, mock_write):
Calculator.add(','.join(map(str, range(100))))
mock_write.assert_called_once_with(100 * 99 / 2)
mock_write.reset_mock()
Calculator.add(','.join(map(str, range(100, 201))))
mock_write.assert_called_once_with(200 * 201 / 2 - 100 * 99 / 2)
mock_write.reset_mock()
@patch('calculator.ILogger.write')
def test_add_lines_check_log(self, mock_write):
Calculator.add('\n'.join(map(str, range(100))))
mock_write.assert_called_once_with(100 * 99 / 2)
mock_write.reset_mock()
Calculator.add('\n'.join(map(str, range(0, 101, 2))))
mock_write.assert_called_once_with(50 * 51)
mock_write.reset_mock()
@patch('calculator.ILogger.write')
def test_add_custom_separator_check_log \
(self, mock_write):
Calculator.add("//#\n1#2#3")
mock_write.assert_called_once_with(6)
mock_write.reset_mock()
Calculator.add("//##\n1##2##3")
mock_write.assert_called_once_with(6)
mock_write.reset_mock()
@patch('calculator.ILogger.write')
def test_add_superior_1000_check_log(self, mock_write):
Calculator.add("2,1001")
mock_write.assert_called_once_with(2)
mock_write.reset_mock()
Calculator.add("2,1000,3")
mock_write.assert_called_once_with(1005)
mock_write.reset_mock()
Calculator.add(",".join(map(str, range(1200))))
mock_write.assert_called_once_with(1000 * 1001 / 2)
@patch('calculator.ILogger.write')
def test_add_multiple_custom_separator_check_log(self, mock_write):
Calculator.add("//[#][%]\n1#2%3")
mock_write.assert_called_once_with(6)
mock_write.reset_mock()
Calculator.add("//[##][%%]\n1##2%%3")
mock_write.assert_called_once_with(6)
@patch('calculator.ILogger.write')
def test_catching_errors_on_logger(self, mock_write):
mock_write.side_effect = Exception("Fake Failed")
try:
Calculator.add("1")
except Exception:
self.fail()
@patch('calculator.ILogger.write')
@patch('calculator.IWebserver.notify')
def test_catching_errors_on_logger(self, mock_notify, mock_write):
mock_write.side_effect = Exception("Fake Failed")
try:
Calculator.add("1")
except: pass
mock_notify.assert_called_once()
|
{"/test_calculator.py": ["/calculator.py"], "/calculator.py": ["/logger.py"]}
|
22,673
|
HadrienRenaud/simple-calculator-kata
|
refs/heads/master
|
/logger.py
|
class ILogger:
@staticmethod
def write(*args, **kwargs):
print("ILogger:", *args, **kwargs)
class IWebserver:
@staticmethod
def notify(*args, **kwargs):
print("IWebserver:", *args, **kwargs)
|
{"/test_calculator.py": ["/calculator.py"], "/calculator.py": ["/logger.py"]}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.