index
int64
repo_name
string
branch_name
string
path
string
content
string
import_graph
string
23,759,128
fullyalive/project_wecode
refs/heads/test
/wecode/banners/apps.py
from django.apps import AppConfig class BannersAppConfig(AppConfig): name = 'wecode.banners'
{"/wecode/views.py": ["/wecode/users/serializers.py"], "/wecode/lectures/admin.py": ["/wecode/lectures/models.py"], "/wecode/users/serializers.py": ["/wecode/posts/models.py"], "/wecode/banners/admin.py": ["/wecode/banners/models.py"]}
23,759,129
fullyalive/project_wecode
refs/heads/test
/wecode/banners/models.py
from django.db import models from django.utils.encoding import python_2_unicode_compatible from wecode.users import models as user_models from django.contrib.humanize.templatetags.humanize import naturaltime, intcomma import datetime # for deadline default from django.contrib.contenttypes.fields import GenericRelation @python_2_unicode_compatible class TimeStampedModel(models.Model): created_at = models.DateTimeField(auto_now_add=True) # first created updated_at = models.DateTimeField(auto_now=True) # last-modified class Meta: abstract = True @python_2_unicode_compatible class Banner(TimeStampedModel): """ Banner Model """ bannerImage = models.ImageField(null=True) title = models.CharField(max_length=200) creator = models.ForeignKey( user_models.User, null=True, related_name='banners', on_delete=models.CASCADE ) location = models.CharField(null=True, max_length=200) short_description = models.TextField(null=True) description = models.TextField(null=True) attendants = models.PositiveIntegerField(default=0) price = models.PositiveIntegerField(default=0) url = models.CharField(max_length=200, null=True,blank=True) @property def comma_price(self): return intcomma(self.price) @python_2_unicode_compatible class Images(models.Model): banner = models.ForeignKey(Banner, default=None, on_delete=models.CASCADE) image = models.ImageField(upload_to='photo/%Y/%m') upload_date = models.DateTimeField('Upload Date', auto_now_add=True)
{"/wecode/views.py": ["/wecode/users/serializers.py"], "/wecode/lectures/admin.py": ["/wecode/lectures/models.py"], "/wecode/users/serializers.py": ["/wecode/posts/models.py"], "/wecode/banners/admin.py": ["/wecode/banners/models.py"]}
23,759,130
fullyalive/project_wecode
refs/heads/test
/wecode/studygroups/migrations/0002_auto_20181026_1847.py
# Generated by Django 2.0.6 on 2018-10-26 09:47 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('studygroups', '0001_initial'), ] operations = [ migrations.AddField( model_name='studylike', name='creator', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL), ), migrations.AddField( model_name='studylike', name='study', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='study_likes', to='studygroups.StudyGroup'), ), migrations.AddField( model_name='studyimages', name='studygroup', field=models.ForeignKey(default=None, on_delete=django.db.models.deletion.CASCADE, to='studygroups.StudyGroup'), ), migrations.AddField( model_name='studygroup', name='attend_users', field=models.ManyToManyField(blank=True, related_name='attend_studygroups', to=settings.AUTH_USER_MODEL), ), migrations.AddField( model_name='studygroup', name='creator', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='studygroups', to=settings.AUTH_USER_MODEL), ), migrations.AddField( model_name='studygroup', name='wish_users', field=models.ManyToManyField(blank=True, related_name='wish_studygroups', to=settings.AUTH_USER_MODEL), ), migrations.AddField( model_name='studycomment', name='creator', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL), ), migrations.AddField( model_name='studycomment', name='study', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='study_comments', to='studygroups.StudyGroup'), ), ]
{"/wecode/views.py": ["/wecode/users/serializers.py"], "/wecode/lectures/admin.py": ["/wecode/lectures/models.py"], "/wecode/users/serializers.py": ["/wecode/posts/models.py"], "/wecode/banners/admin.py": ["/wecode/banners/models.py"]}
23,759,131
fullyalive/project_wecode
refs/heads/test
/wecode/lectures/urls.py
from django.urls import path from . import views app_name = "lectures" urlpatterns = [ path("", view=views.lecture_list_view.as_view(), name="list"), path("search/", view=views.Search.as_view(), name="search"), path('test/', view=views.TestView.as_view(), name='test'), path("<lecture_id>/", view=views.lecture_detail.as_view(), name="detail"), path("<lecture_id>/wish/", view=views.lecture_detail.as_view(), name="wish_lecture"), path("<lecture_id>/attend/", view=views.lecture_detail.as_view(), name="attend_lecture"), path("<lecture_id>/likes/", view=views.Likes.as_view(), name="like_lecture"), path("<lecture_id>/unlikes/", view=views.Unlikes.as_view(), name="unlike_lecture"), path("<lecture_id>/comments/", view=views.Comments.as_view(), name="comments"), path("<lecture_id>/comments/<comment_id>/", view=views.CommentDetail.as_view(), name="comment_detail"), path("<lecture_id>/comments/<comment_id>/recomments/", view=views.Recomments.as_view(), name="recomments"), path("<lecture_id>/comments/<comment_id>/recomments/<recomment_id>/", view=views.ReCommentDetail.as_view(), name="recomment_detail"), ]
{"/wecode/views.py": ["/wecode/users/serializers.py"], "/wecode/lectures/admin.py": ["/wecode/lectures/models.py"], "/wecode/users/serializers.py": ["/wecode/posts/models.py"], "/wecode/banners/admin.py": ["/wecode/banners/models.py"]}
23,759,132
fullyalive/project_wecode
refs/heads/test
/wecode/lectures/models.py
from django.db import models from django.utils.encoding import python_2_unicode_compatible from wecode.users import models as user_models from django.contrib.humanize.templatetags.humanize import naturaltime, intcomma import datetime # for deadline default from django.contrib.contenttypes.fields import GenericRelation from time import strftime # from django.template.defaultfilters import date @python_2_unicode_compatible class TimeStampedModel(models.Model): created_at = models.DateTimeField(auto_now_add=True) # first created updated_at = models.DateTimeField(auto_now=True) # last-modified class Meta: abstract = True @python_2_unicode_compatible class Lecture(TimeStampedModel): """ Lecture Model """ lectureImage = models.ImageField(null=True) title = models.CharField(max_length=200) creator = models.ForeignKey( user_models.User, null=True, related_name='lectures', on_delete=models.CASCADE ) location = models.CharField(blank=True, max_length=200) short_description = models.TextField(blank=True) description = models.TextField(blank=True) price = models.IntegerField(null=True) deadline = models.DateField(null=True) startDate = models.DateField(null=True) endDate = models.DateField(null=True) startTime = models.TimeField(null=True) endTime = models.TimeField(null=True) day1 = models.CharField(null=True, blank=True, max_length=200) day2 = models.CharField(null=True, blank=True, max_length=200) attend_users = models.ManyToManyField(user_models.User, blank=True, related_name="attend_lectures") wish_users = models.ManyToManyField(user_models.User, blank=True, related_name="wish_lectures") career1 = models.TextField(blank=True) career2 = models.TextField(blank=True) contents = models.TextField(blank=True) curriculum1 = models.TextField(blank=True) curriculum2 = models.TextField(blank=True) attendants = models.PositiveIntegerField(default=0, null=True, blank=True) url = models.CharField(max_length=200, null=True, blank=True) @property def natural_time(self): return naturaltime(self.created_at) @property def comma_price(self): return intcomma(self.price) @property def deadline_date(self): return self.deadline.strftime("%m/%d") @property def start_date(self): # return date(self.startDate, "m/d ") 이것도 작동된다. return self.startDate.strftime("%m/%d") @property def end_date(self): return self.endDate.strftime("%m/%d") @property def start_time(self): return self.startTime.strftime("%H:%M") @property def end_time(self): return self.endTime.strftime("%H:%M") @property def like_count(self): return self.lecture_likes.all().count() @property def comment_count(self): return self.lecutre_comments.all().count() def __str__(self): return '{} - {}'.format(self.title, self.creator) class Meta: ordering = ['-created_at'] @python_2_unicode_compatible class LectureComment(TimeStampedModel): """ Comment Model """ message = models.TextField() creator = models.ForeignKey(user_models.User, null=True, on_delete=models.CASCADE) lecture = models.ForeignKey(Lecture, null=True, on_delete=models.CASCADE, related_name='lecture_comments') parent = models.IntegerField(default=0, null=True) groupNumber = models.IntegerField(default=0, null=True) groupOrder = models.IntegerField(default=0, null=True) @property def recomment_count(self): queryset = self.lecture.lecture_comments.all() count = 0 for data in queryset: if data.parent == self.id: count+=1 return count class Meta: ordering = ['groupNumber', 'groupOrder'] def __str__(self): return self.message @property def created_time_mdhm(self): return self.created_at.strftime("%m/%d %H:%M") @python_2_unicode_compatible class LectureLike(TimeStampedModel): """ Like Model """ creator = models.ForeignKey(user_models.User, null=True, on_delete=models.CASCADE) lecture = models.ForeignKey(Lecture, null=True, on_delete=models.CASCADE, related_name='lecture_likes') def __str__(self): return 'User: {} - Lecture Caption: {}'.format(self.creator.username, self.lecture.title) @python_2_unicode_compatible class LectureImages(models.Model): lecture = models.ForeignKey(Lecture, default=None, on_delete=models.CASCADE) image = models.ImageField(upload_to='photo/%Y/%m') upload_date = models.DateTimeField('Upload Date', auto_now_add=True)
{"/wecode/views.py": ["/wecode/users/serializers.py"], "/wecode/lectures/admin.py": ["/wecode/lectures/models.py"], "/wecode/users/serializers.py": ["/wecode/posts/models.py"], "/wecode/banners/admin.py": ["/wecode/banners/models.py"]}
23,759,133
fullyalive/project_wecode
refs/heads/test
/wecode/banners/urls.py
from django.urls import path from . import views app_name = "banners" urlpatterns = [ path("", view=views.banner_list_view.as_view(), name="list"), path("<banner_id>/", view=views.banner_detail.as_view(), name="detail"), ]
{"/wecode/views.py": ["/wecode/users/serializers.py"], "/wecode/lectures/admin.py": ["/wecode/lectures/models.py"], "/wecode/users/serializers.py": ["/wecode/posts/models.py"], "/wecode/banners/admin.py": ["/wecode/banners/models.py"]}
23,759,134
fullyalive/project_wecode
refs/heads/test
/wecode/posts/migrations/0001_initial.py
# Generated by Django 2.0.6 on 2018-10-26 09:47 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Post', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created_at', models.DateTimeField(auto_now_add=True)), ('updated_at', models.DateTimeField(auto_now=True)), ('title', models.CharField(max_length=200)), ('post_type', models.CharField(choices=[('qna', 'Q&A'), ('free', '자유게시판'), ('ask', '문의사항')], max_length=80, null=True)), ('description', models.TextField(null=True)), ('view_count', models.IntegerField(default=0)), ('isImportant', models.NullBooleanField(default=False)), ], options={ 'ordering': ['-isImportant', '-created_at'], }, ), migrations.CreateModel( name='PostComment', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created_at', models.DateTimeField(auto_now_add=True)), ('updated_at', models.DateTimeField(auto_now=True)), ('message', models.TextField()), ('parent', models.IntegerField(default=0, null=True)), ('groupNumber', models.IntegerField(default=0, null=True)), ('groupOrder', models.IntegerField(default=0, null=True)), ], options={ 'ordering': ['groupNumber', 'groupOrder'], }, ), migrations.CreateModel( name='PostLike', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created_at', models.DateTimeField(auto_now_add=True)), ('updated_at', models.DateTimeField(auto_now=True)), ], options={ 'abstract': False, }, ), ]
{"/wecode/views.py": ["/wecode/users/serializers.py"], "/wecode/lectures/admin.py": ["/wecode/lectures/models.py"], "/wecode/users/serializers.py": ["/wecode/posts/models.py"], "/wecode/banners/admin.py": ["/wecode/banners/models.py"]}
23,759,135
fullyalive/project_wecode
refs/heads/test
/wecode/users/urls.py
from django.urls import path from . import views app_name = "users" urlpatterns = [ path("create/", view=views.CreateUserView.as_view(), name="create"), path("updatephoto/", view=views.UpdateUserView.as_view(), name="update_photo"), path("<username>/password/", view=views.ChangePassword.as_view(), name="changePassword"), path("login/facebook/", view=views.FacebookLogin.as_view(), name='fb_login'), path("profile/", view=views.ProfileView.as_view(), name='profile'), ]
{"/wecode/views.py": ["/wecode/users/serializers.py"], "/wecode/lectures/admin.py": ["/wecode/lectures/models.py"], "/wecode/users/serializers.py": ["/wecode/posts/models.py"], "/wecode/banners/admin.py": ["/wecode/banners/models.py"]}
23,759,136
fullyalive/project_wecode
refs/heads/test
/wecode/banners/migrations/0001_initial.py
# Generated by Django 2.0.6 on 2018-08-10 13:27 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Banner', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created_at', models.DateTimeField(auto_now_add=True)), ('updated_at', models.DateTimeField(auto_now=True)), ('bannerImage', models.ImageField(null=True, upload_to='')), ('title', models.CharField(max_length=200)), ('location', models.CharField(max_length=200, null=True)), ('short_description', models.TextField(null=True)), ('description', models.TextField(null=True)), ('attendants', models.PositiveIntegerField(default=0)), ], options={ 'abstract': False, }, ), migrations.CreateModel( name='Images', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('image', models.ImageField(upload_to='photo/%Y/%m')), ('upload_date', models.DateTimeField(auto_now_add=True, verbose_name='Upload Date')), ('banner', models.ForeignKey(default=None, on_delete=django.db.models.deletion.CASCADE, to='banners.Banner')), ], ), ]
{"/wecode/views.py": ["/wecode/users/serializers.py"], "/wecode/lectures/admin.py": ["/wecode/lectures/models.py"], "/wecode/users/serializers.py": ["/wecode/posts/models.py"], "/wecode/banners/admin.py": ["/wecode/banners/models.py"]}
23,812,988
Barsheshett/Exercise
refs/heads/master
/Person.py
class Person: def __init__(self, name="Ivgenia", id="123456789", age=30): self.name = name self.id = id self.age = age def __str__(self): return "name: %s\nid: %s\nage: %d" % (self.name, self.id, self.age)
{"/main.py": ["/Student.py", "/Person.py"], "/Student.py": ["/Person.py"]}
23,812,989
Barsheshett/Exercise
refs/heads/master
/Student.py
from Person import Person class Student (Person): def __init__(self, name="Ivgenia", id="123456789", age=30, average=100, institute="Queen"): Person.__init__(self, name, id, age) self.average = average self.institute = institute def __str__(self): print(Person.__str__(self)) return "average: %d\ninstitute:%s" % (self.average, self.institute)
{"/main.py": ["/Student.py", "/Person.py"], "/Student.py": ["/Person.py"]}
23,854,013
Shpagat/RoMA
refs/heads/main
/rpw.py
# подключение библиотеки для работы с контактами ввода/вывода import RPi.GPIO as IO import time # подключение библиотеки для работы с задержками IO.setwarnings(False) # отключаем показ любых предупреждений # мы будем программировать контакты GPIO по их функциональным номерам (BCM), то есть мы будем обращаться к PIN35 как ‘GPIO19’ IO.setmode(IO.BCM) import RPi.GPIO as GPIO import time GPIO_PWM_0 = 19 FREQUENCY = 100 DELAY_TIME = 0.02 GPIO.setmode(GPIO.BCM) GPIO.setup(GPIO_PWM_0, GPIO.OUT) pwmOutput_0 = GPIO.PWM(GPIO_PWM_0, FREQUENCY) pwmOutput_0.start(0) try: while True: for dutyCycle in range(0, 101, 1): pwmOutput_0.ChangeDutyCycle(dutyCycle) time.sleep(DELAY_TIME) except KeyboardInterrupt: pwmOutput_0.stop() GPIO.cleanup() print('exiting')
{"/main.py": ["/functions.py"]}
23,854,014
Shpagat/RoMA
refs/heads/main
/main.py
import functions #запуск сканирования qr-кода function.qr_detector() #ожидание датчика #открытие ячейки #закрытие ячеек
{"/main.py": ["/functions.py"]}
23,854,015
Shpagat/RoMA
refs/heads/main
/bluetooth.py
from bluedot import BlueDot from signal import pause from gpiozero import Robot robot = Robot(left=(4, 14), right=(17, 18)) bd = BlueDot(cols=3, rows=3) bd.color = "red" bd.square = True bd[0, 0].visible = False bd[2, 0].visible = False bd[0, 2].visible = False bd[2, 2].visible = False bd[1, 1].visible = False bd[1, 0].when_pressed = robot.forward bd[1, 2].when_pressed = robot.backward bd[0, 1].when_pressed = robot.left bd[2, 1].when_pressed = robot.right bd[1, 0].when_released = robot.stop bd[1, 2].when_released = robot.stop bd[0, 1].when_released = robot.stop bd[2, 1].when_released = robot.stop pause()
{"/main.py": ["/functions.py"]}
23,858,181
Pranshu-Bahadur/g2net
refs/heads/master
/utils.py
import pandas as pd from multiprocessing import Pool from os import walk, listdir from functools import reduce import os import time from tqdm import tqdm from torch.utils.data import Dataset, DataLoader from torch import from_numpy, tensor from numpy import load def multi_pathfinder(root_dir : str, num_cpus : int) -> pd.DataFrame: start = time.time() dirs = [f"{root_dir}/{d}" for d in listdir(root_dir) if os.path.isdir(f"{root_dir}/{d}")] with Pool(num_cpus) as threads: dfs = threads.map(_walker, dirs) df = pd.concat(dfs) stop = time.time() print(f"\n\n========\nTotal Time taken :\n {stop - start}\n========") return df def _walker(directory : str) -> pd.DataFrame: functions = [(filter,lambda x: len(x[2]) > 0), (map, lambda x: (x[0], x[2]))] paths_and_files = list(reduce(lambda x,f: f[0](f[1], x), functions, walk(directory))) list_dfs = list(map(lambda x: pd.DataFrame.from_dict(list(map(lambda y: {"unique values": y.split(".")[0], "path": f"{x[0]}/{y}"}, x[1])), orient='columns'), tqdm(paths_and_files))) df = pd.concat(list_dfs) if len(list_dfs) > 0 else pd.DataFrame() return df class NumpyImagesCSVDataset(Dataset): def __init__(self, root_dir : str, path_to_csv : str, is_train : bool): self.df = pd.read_csv(path_to_csv).join(multi_pathfinder(root_dir, os.cpu_count()), on="unique values") self.is_train = is_train def __getitem__(self, index : int): data = self.df.iloc[index].to_dict() x = from_numpy(load(data['path'])).view(3, 64, 64) y = tensor(data['target']) if self.is_train else tensor(0) return x, y def __len__(self): return len(self.df) """ given - list_abs_path : List[str] return most_suitable : str """ def df_from_abs_paths(abs_paths) -> str : df = pd.DataFrame(abs_paths) df = df['0'].str.split('/', expand=True) return df.groupby(list(df.columns), axis=1).apply(lambda x: x.count()).max().index.to_list()[0]
{"/agent.py": ["/modules.py", "/utils.py"]}
23,858,182
Pranshu-Bahadur/g2net
refs/heads/master
/agent.py
from timm import create_model import torch from tdqm import tdqm from utils import NumpyImagesCSVDataset def _splitter(dataset, partition : int): train_split = int(partition * len(dataset)) eval_split = int(len(dataset) - train_split) splits = [train_split, eval_split] return torch.utils.data.dataset.random_split(dataset, splits) def train(**kwargs): model = torch.nn.DataParallel(create_model(kwargs['model'], num_classes=2, pretrained=True)).cuda() train_split, val_split = _splitter(NumpyImagesCSVDataset(kwargs['root'], kwargs['csv'], True), 0.7) config = { "optim" : torch.optim.SGD(model.parameters(), lr=0.1, momentum=0.9, weight_decay=1e-5, nesterov=True), "loss" : torch.nn.BCELoss().cuda(), "train" : Loader(train_split, 256, shuffle=True, num_workers=4), "val" : Loader(val_split, 256, shuffle=True, num_workers=4)} config["scheduler"] = torch.optim.lr_scheduler.StepLR(config['optim'], 2.4, 0.97) for i in range(kwargs['epochs']): config['model'].train() print(f'{i+1}train:\n') print(update('train', **config)) with torch.no_grad(): config['model'].eval() print(f'{i+1}val:\n') print(update('val', **config)) _save("chekpoints", config['model']) def _save(directory, model): torch.save(model.state_dict(), "{}/./{}.pth".format(directory, "effnet_v2s")) def update(mode : str, **kwargs): correct, running_loss, total, iterations = 0, 0, 0, 0 for x, y in tdqm(kwargs[mode]): h = torch.nn.functional.softmax(kwargs['model'](x.cuda()), dim=1) loss = kwargs['loss'](h, y.cuda()) if mode == 'train': kwargs['optim'].zero_grad() loss.backward() kwargs['optim'].step() kwargs['scheduler'].step() running_loss += loss.cpu().item() total = y.size(0) iterations += 1 correct += (torch.argmax(h, dim=1).cpu()==y.cpu()).sum().item() print(correct/total, running_loss/iterations) return float(correct/total), float(running_loss/iterations)
{"/agent.py": ["/modules.py", "/utils.py"]}
24,014,418
ismael-martinez/NetworkStructureDSLs
refs/heads/master
/CodeGen/Python/QueuingNetwork.py
from CodeGen.Python.networkStructureAttributesAndInstances import * from CodeGen.Python.networkUtil import * import numpy as np import random from scipy.stats import expon # Simulation of events in queue network # class Simulation: def __init__(self, Events_O, Events_H, Queues): # Initial queue self.queue_init = Queue(0) # Add initial queue to every event self.Events_H = Events_O self.Events_H = Events_H self.Queues = Queues for e in Events_O: e.queues.insert(0, self.queue_init) first_arrival = e.arrival_times[0] e.departure_times.insert(0, first_arrival) self.update_hidden_events(self.Events_H) def queuing_sample(self): Events = merge_events(self.Events_O, self.Events_H) # Ordered by first arrival time for e in self.Events_H: e.queues.insert(0, self.queue_init) first_arrival = e.arrival_times[0] e.departure_times.insert(0, first_arrival) # events_first_arrival.append((e.id, e.arrival_times[0])) # First arrival of each event # Get all departure times, in order self.departure_times = [] for e in Events: self.departure_times = merge_id(self.departure_times, e.departure_times, e.id, e.queues) # Dictionaries self.dict_events = {} for e in Events: self.dict_events[e.id] = e self.dict_queue = {} for q in self.Queues: self.dict_queue[q.id] = q self.service_times = [] self.wait_times = [] self.execute() def update_hidden_events(self, Events_H): self.Events_H = Events_H self.queuing_sample() def execute(self): for dep_time in self.departure_times: e_id = dep_time[1] q_prev = dep_time[2] event = self.dict_events[e_id] q_next = event.move_queue() e_curr = event.current_queue queue_next = self.dict_queue[q_next] queue_next.arrival(e_id, dep_time[0], event.departure_times[e_curr]) queue_prev = self.dict_queue[q_prev] (s,w,e) = queue_prev.service_next() self.service_times.append((s,e)) # (service_time, e) self.wait_times.append((w,e)) # (wait_times, e) return [self.service_times, self.wait_times] # Log of joint density for set of departures, queues, transitions, and service parameters # Input: ## events (N array) - array of event ids ## departures (N array) - array of departure times ## queues (N array) - array of queues per event ## Transitions (Q x Q matrix) - Transition probabilities between queues ## theta (Q array) - distribution parameters for each queue # Return: joint_density_log (float) def joint_density_log(self, events, departures, queues, Transitions, theta): joint_density_log_d_q = 0 E = len(departures) if len(queues) != E: raise Exception("d and q must be equal sizes") event_queues = {} for i in range(E): transition = 1 ev_id = events[i] ev_queue = queues[i] if ev_id in event_queues.keys(): queues_pi = event_queues[ev_id] transition = Transitions[ev_queue, queues_pi] event_queues[ev_id] = ev_queue service_probability = expon.pdf(departures[i], scale=theta[ev_queue]) joint_density_log_d_q += np.log(transition) + np.log(service_probability) return joint_density_log_d_q class Event: def __init__(self, id, arrival_times, queues, departure_times, hidden=False): self.id = id self.arrival_times = arrival_times self.queues = queues self.departure_times = departure_times self.tasks = len(queues) self.current_queue = 0 self.hidden = hidden # Given an ordered list of queues to visit, leave current queue and move to queue of next def move_queue(self): self.current_queue += 1 if self.current_queue >= self.tasks: return [] else: queue_id = self.queues[self.current_queue] return queue_id class Queue: def __init__(self, id): self.id = id #self.service_rate = service_rate self.queue_events = [] self.queue_times_arrival = [] self.queue_times_departures = [] self.prev_dep = 0.0 self.waiting = 0 # Add an event to FIFO queue, end of line def arrival(self, event, time, departure_time): self.queue_events.append(event) self.queue_times_arrival.append(time) self.queue_times_departures.append(departure_time) self.waiting += 1 # Given arrival and departure time, calculate service and wait time of current event def service_next(self): event = self.queue_events.pop(0) arrival_time = self.queue_times_arrival.pop(0) departure_time = self.queue_times_departures.pop(0) self.waiting -= 1 earliest_service = np.max([arrival_time, self.prev_dep]) service_time = departure_time - earliest_service wait_time = departure_time - service_time - arrival_time self.prev_departure = departure_time return (service_time, wait_time, event) # # def service_next(self): # event = self.queue_events.pop(0) # time = self.queue_times.pop(0) # self.waiting -= 1 # service_time = np.random.exponential(1./(self.service_rate)) # return time + service_time events = 50 random.seed(events) ns = network_structure.graph.nodes service_rates = {} for node in ns: service_rates[node] = 5*np.random.random() arrival_rate = 3 arrivals = np.zeros(events) arrivals[0] = 0.0 departures = np.zeros(events) for e in range(events-1): arrivals[e+1] = arrivals[e] + np.random.exponential(1/arrival_rate) print(arrivals) queues = {} P = len(network_structure.graph.paths) paths = network_structure.graph.paths for e in range(events): rand_p = random.randint(0, P-1) path = paths[rand_p] queues[e] = path # TODO - Bass # Init simulation S = Simulation(...) runs = 10 for i in range(runs): # Build sample d [departure_times] # build new Events_H Events_H = [Event()] # TODO [service_times, wait_times] = S.update_hidden_events(Events_H) # Gibbs sampling from metrics # Use S.joint_density_log()
{"/CodeGen/Python/QueuingNetwork.py": ["/CodeGen/Python/networkStructureAttributesAndInstances.py", "/CodeGen/Python/networkUtil.py"], "/CodeGen/Python/codeGen.py": ["/CodeGen/Python/networkStructure.py"], "/CodeGen/Python/networkStructureAttributesAndInstances.py": ["/CodeGen/Python/networkStructure.py"], "/CodeGen/Python/networkStructureAnalysis.py": ["/CodeGen/Python/networkStructureAttributesAndInstances.py", "/CodeGen/Python/networkUtil.py"]}
24,014,419
ismael-martinez/NetworkStructureDSLs
refs/heads/master
/CodeGen/Python/networkUtil.py
from math import sin, cos, sqrt, atan2, radians import numpy as np # Compare two timestamps by first converting to seconds # Input: ## timestamp1 (string) ## timestamp2 (string) # Result: timestamp1_greater (int). 1 if true, -1 if timestamp1 < timestamp2, 0 if equal. def compare_time(timestamp1, timestamp2): hour1 = timestamp1.hour min1 = timestamp1.minutes sec1 = timestamp1.seconds ms1 = timestamp1.milliseconds hour2 = timestamp2.hour min2 = timestamp2.minutes sec2 = timestamp2.seconds ms2 = timestamp2.milliseconds if hour1 > hour2: time1_greater = 1 elif hour1 < hour2: time1_greater = -1 else: if min1 > min2: time1_greater = 1 elif min1 < min2: time1_greater = -1 else: if sec1 > sec2: time1_greater = 1 elif sec1 < sec2: time1_greater = -1 else: if ms1 > ms2: time1_greater = 1 elif ms1 < ms2: time1_greater = -1 else: time1_greater = 0 return time1_greater # Computer the geographical distance between two points in meters # Inputs: ## location1 (float) - class with latitude, longitude attributes ## location2 (float) - class with latitude, longitude attributes ## Result: distance (float) - Distance in meters def distance_location(location1, location2): R = 6373.0 # Radius of earth lat1 = location1.latitude lat2 = location2.latitude lon1 = location1.longitude lon2 = location2.longitude dlat = lat2 - lat1 dlon = lon2 - lon1 a = sin(dlat / 2) ** 2 + cos(lat1) * cos(lat2) * sin(dlon / 2) ** 2 c = 2 * atan2(sqrt(a), sqrt(1 - a)) d_coord = R*c height1 = location1.height height2 = location2.height dheight = height2 - height1 dist = sqrt(d_coord**2 + (dheight)**2) return dist # Merge two arrays of pairs together # Input: ## list_a (N array of pairs) - Original list ## list_b (M array of timestamps) ## q_ids (M array of indices) # Return: merged list of pairs def merge_id(list_a, list_b, e_id, q_ids): list_c = [] i = 0 j = 0 while i < len(list_a) and j < len(list_b): if compare_time(list_a[i][0],list_b[j]) > 0: list_c.append((list_b[j], e_id, q_ids[j])) j += 1 else: list_c.append(list_a[i]) i += 1 while i < len(list_a): list_c.append(list_a[i]) i += 1 while j < len(list_b): list_c.append((list_b[j], e_id, q_ids[j])) j += 1 return list_c # Merge two arrays of events together # Input: ## list_a (N array of events) ## list_b (N array of events) ## Pair (timestamp, id) # Return: merged list of pairs def merge_events(list_a, list_b): list_c = [] i = 0 j = 0 while i < len(list_a) and j < len(list_b): if compare_time(list_a[i].arrival_times[0], list_b[j].arrival_times[0]) > 0: list_c.append(list_b[j]) j += 1 else: list_c.append(list_a[i]) i += 1 while i < len(list_a): list_c.append(list_a[i]) i += 1 while j < len(list_b): list_c.append(list_b[j]) j += 1 return list_c
{"/CodeGen/Python/QueuingNetwork.py": ["/CodeGen/Python/networkStructureAttributesAndInstances.py", "/CodeGen/Python/networkUtil.py"], "/CodeGen/Python/codeGen.py": ["/CodeGen/Python/networkStructure.py"], "/CodeGen/Python/networkStructureAttributesAndInstances.py": ["/CodeGen/Python/networkStructure.py"], "/CodeGen/Python/networkStructureAnalysis.py": ["/CodeGen/Python/networkStructureAttributesAndInstances.py", "/CodeGen/Python/networkUtil.py"]}
24,014,420
ismael-martinez/NetworkStructureDSLs
refs/heads/master
/CodeGen/Python/networkStructure.py
from abc import ABC, abstractmethod import math def depthFirstSearch(nodes): all_paths = [] node_visited_map = {} for node in nodes: node_visited_map[node] = False node_visited = [node_visited_map[key] for key in node_visited_map] for node in nodes: if all(node_visited): break [node_visited_map, _, all_paths] = depthFirstSearch_rec(nodes, node, node_visited_map, all_paths) node_visited = [node_visited_map[key] for key in node_visited_map] return all_paths def depthFirstSearch_rec(nodes, root, node_visited_map, all_paths): root_paths = [] if node_visited_map[root]: return [node_visited_map, []] node_visited_map[root] = True node = root root_paths.append([root]) for nb in nodes[node].neighbours: [node_visited_map, paths, all_paths] = depthFirstSearch_rec(nodes, nb[1], node_visited_map, all_paths) for p in paths: root_paths.append([root] + p) for p in root_paths: all_paths.append(p) return [node_visited_map, root_paths, all_paths] class timestamp: def __init__(self, time_seconds): time_remaining = time_seconds self.hour = math.floor(time_remaining/ 3600) time_remaining -= 3600 * self.hour self.minutes = math.floor(time_remaining / 60) time_remaining -= 60 * self.minutes self.seconds = math.floor(time_remaining) self.milliseconds = int((time_remaining % 1)*1000) def __str__(self): hour_str = str(self.hour) if len(hour_str) < 2: hour_str = '0' + hour_str min_str = str(self.minutes) if len(min_str) < 2: min_str = '0' + min_str sec_str = str(self.seconds) if len(sec_str) < 2: sec_str = '0' + sec_str if self.milliseconds > 0: ms_str = str(self.milliseconds) if len(ms_str) < 2: ms_str = '00' + ms_str if len(ms_str) < 3: ms_str = '0' + ms_str sec_str += '.' + ms_str time = hour_str + ':' + min_str + ':' + sec_str return time @staticmethod def time_format(time): components = time.split(':') hour = int(components[0]) min = int(components[1]) if len(components[0]) != 2 or (hour < 0 or hour > 23): raise Exception("Not a valid Hour.") if len(components[1]) != 2 or (min < 0 or min > 59): raise Exception("Not a valid Minute.") if len(components) > 2: sec = float(components[3]) if len(components[3].split('.')[0]) != 2 or (sec < 0 or sec >= 60): raise Exception('Not a valid Second.') return True @staticmethod def convertTime(seconds): hour = math.floor(seconds / 3600) hour_str = str(hour) if len(hour_str) < 2: hour_str = '0' + hour_str seconds -= 3600 * hour min = math.floor(seconds / 60) min_str = str(min) seconds -= 60 * min if len(min_str) < 2: min_str = '0' + min_str sec_str = str(seconds) if len(sec_str.split('.')[0]) < 2: sec_str = '0' + sec_str if len(sec_str) > 6: sec_str = sec_str[0:6] time = hour_str + ':' + min_str + ':' + sec_str return time @staticmethod def convert_to_seconds(timestamp_str): seconds = 0 componenets = timestamp_str.split(':') seconds += int(componenets[0])*3600 if len(componenets) > 1: seconds += int(componenets[1])*60 if len(componenets) > 2: seconds += float(componenets[2]) return seconds class NetworkStructure: def __init__(self, graph, things): self.graph = graph self.things = things def listNodeAttributes(self): for node in self.graph.nodes: attr = self.graph.nodes[node].attributes.listAttributes() break return attr def listLinkAttributes(self): for link in self.graph.links: attr = self.graph.links[link].attributes.listAttributes() break return attr def listThingAttributes(self): for thing in self.things: attr = self.things[thing].attributes.listAttributes() break return attr class NodeAbstract(ABC): def __init__(self, id, locations, attributes): self.id = id self.locations = locations self.attributes = attributes self.neighbours = [] class LinkAbstract(ABC): def __init__(self, id, attributes, node_pair): self.id = id self.attributes = attributes self.node_pair = node_pair class GraphAbstract(ABC): def __init__(self, id, nodes, links): self.id = id self.nodes = nodes self.links = links self.paths = depthFirstSearch(self.nodes) class ThingAbstract(ABC): def __init__(self, id, schedule, locations, attributes): self.id = id self.schedule = schedule self.locations = locations self.attributes = attributes class Locations: def __init__(self, latitude, longitude, height=1): self.latitude = latitude self.longitude = longitude self.height = height
{"/CodeGen/Python/QueuingNetwork.py": ["/CodeGen/Python/networkStructureAttributesAndInstances.py", "/CodeGen/Python/networkUtil.py"], "/CodeGen/Python/codeGen.py": ["/CodeGen/Python/networkStructure.py"], "/CodeGen/Python/networkStructureAttributesAndInstances.py": ["/CodeGen/Python/networkStructure.py"], "/CodeGen/Python/networkStructureAnalysis.py": ["/CodeGen/Python/networkStructureAttributesAndInstances.py", "/CodeGen/Python/networkUtil.py"]}
24,014,421
ismael-martinez/NetworkStructureDSLs
refs/heads/master
/CodeGen/Python/codeGen.py
# Generate Node_, NodeAttributes, Thing_, and ThingAttributes classes ## Read parameters from .trs file import json import math from scipy.stats import expon from numpy.random import normal from CodeGen.Python.networkStructure import * from textx import metamodel_from_file from textx.export import metamodel_export import os # TODO When we find a keyword, we need to find the opening and closing brackets {} # Schedules def consistentSchedule(consistentMap): start = consistentMap['start'] end = consistentMap['end'] gap = consistentMap['gap'] start_components = start.split(':') start_sec = int(start_components[0])*60*60 + int(start_components[1])*60 if len(start_components) > 2: start_sec += int(start_components[3]) end_components = end.split(':') end_sec = int(end_components[0]) * 60 * 60 + int(end_components[1]) * 60 if len(end_components) > 2: end_sec += int(end_components[3]) gap_components = gap.split(':') gap_sec = int(gap_components[0]) * 60 * 60 + int(gap_components[1]) * 60 if len(gap_components) > 2: gap_sec += int(gap_components[3]) schedule_sec = list(range(start_sec, end_sec, gap_sec)) schedule_str = [str(timestamp(s)) for s in schedule_sec] return [schedule_sec, schedule_str] def probabilisticSchedule(probMap): start = probMap['start'] end = probMap['end'] start_components = start.split(':') start_sec = int(start_components[0])*60*60 + int(start_components[1])*60 if len(start_components) > 2: start_sec += int(start_components[3]) end_components = end.split(':') end_sec = int(end_components[0]) * 60 * 60 + int(end_components[1]) * 60 if len(end_components) > 2: end_sec += int(end_components[3]) distribution = probMap['interarrivalDistribution'] if 'Exponential' in distribution: exp_lambda_str = '' for i in range(len(distribution)): if distribution[i] == '=': i += 1 while distribution[i] != ')': exp_lambda_str += distribution[i] i+=1 break exp_lambda = float(exp_lambda_str) schedule_sec = [] curr_sec = start_sec while curr_sec < end_sec: schedule_sec.append(curr_sec) curr_sec += expon.rvs(scale=(1./exp_lambda)) schedule_str = [str(timestamp(s)) for s in schedule_sec] return [schedule_sec, schedule_str] elif 'Gaussian' in distribution: mu_str = '' var_str = '' for i in range(len(distribution)): if distribution[i] == '(': i += 1 begin_idx = i while distribution[i] != ')': i += 1 end_idx = i else: continue params = distribution[begin_idx:end_idx].split(',') for p in params: kv = p.split('=') if 'mu' in kv[0]: mu_str = kv[1] if 'var' in kv[0]: var_str = kv[1] break mu = float(mu_str) var = float(var_str) schedule_sec = [] curr_sec = start_sec while curr_sec < end_sec: schedule_sec.append(curr_sec) curr_sec += normal(mu, var) schedule_str = [str(timestamp(s)) for s in schedule_sec] return [schedule_sec, schedule_str] # TRS Parser def trs_parser(trs_model, location_json): thing_type = trs_model.name # Partition things instance_code_gen_thing = '## Thing instances ## \n\nthings = {}\n\n' for thing in trs_model.things: # Get thing ID thing_name = thing.name # Parse requestSchedule requestSchedule = thing.requestSchedule schedule_type =requestSchedule._tx_fqn if 'ConsistentRequestSchedule' in schedule_type: consistentMap = {} consistentMap['start'] = requestSchedule.start consistentMap['end'] = requestSchedule.end consistentMap['gap'] = requestSchedule.gap [schedule_sec, schedule_str] = consistentSchedule(consistentMap) elif 'ExplicitRequestSchedule' in schedule_type: explicitMap = {} explicitMap['schedule'] = requestSchedule.schedule schedule_str = requestSchedule.schedule[1:-1].split(',') scheule_sec = [timestamp.convert_to_seconds(s) for s in schedule_str] elif 'ProbabilisticRequestSchedule' in schedule_type: probMap = {} probMap['start'] = requestSchedule.start probMap['end'] = requestSchedule.end probMap['interarrivalDistribution'] = requestSchedule._tx_fqn if 'Exponential' in requestSchedule._tx_fqn: probMap['lambda'] = requestSchedule.lambda_mean elif 'Gaussian' in requestSchedule._tx_fqn: probMap['mu'] = requestSchedule.mu probMap['var'] = requestSchedule.var else: continue # Build Thing attributes thing_attributes = {} for i in range(len(thing.attributes)): attr = thing.attributes[i] attr_val = thing.val[i] thing_attributes[attr.name] = attr_val # Build locations thing_location = {} loc_refs = thing.location.loc_ref for loc_ref in loc_refs: ref_str = str(loc_ref) location_data = location_json[ref_str] thing_location[loc_ref] = location_data instance_code_gen_thing += 'locations = []\n' for id in thing_location: instance_code_gen_thing += 'locations.append(Locations({}, {}, {}))\n'.format(thing_location[id]['latitude'], thing_location[id]['longitude'], thing_location[id]['height']) configurations_values = [] for id in thing_attributes: configurations_values.append(str(thing_attributes[id])) instance_code_gen_thing += 'attributes = ThingAttributes_{}({})\n'.format(thing_type, ','.join(configurations_values)) # Comment timestamp meaning instance_code_gen_thing += '# schedule_str = {}\n'.format(schedule_str) instance_code_gen_thing += 'schedule = [' for t in range(len(schedule_sec)-1): instance_code_gen_thing += 'timestamp({}),'.format(schedule_sec[t]) instance_code_gen_thing += 'timestamp({})]\n'.format(schedule_sec[-1]) instance_code_gen_thing += 'things["{}"] = Thing_{}("{}", schedule, locations, attributes)\n\n'.format(thing_name, thing_type, thing_name) return instance_code_gen_thing #thing_elem = Thing(thing_idx, schedule, locations, configurations) #things_elems.append(thing_elem) ## Read parameters from .NSM file def pns_parser(pns_model, location_json, graph_name): instance_code_gen_graph = 'nodes = {}\nlinks={}\n' ## Node instances instance_code_gen_graph += '## Node Instances \n\n' node_set = pns_model.nodeSet.nodes for node in node_set: node_name = node.name # Build Node attributes node_attributes = {} for i in range(len(node.attributes)): attr = node.attributes[i] attr_val = node.val[i] node_attributes[attr.name] = attr_val # Build locations node_locations = {} loc_refs = node.location.loc_ref for loc_ref in loc_refs: ref_str = str(loc_ref) location_data = location_json[ref_str] node_locations[loc_ref] = location_data instance_code_gen_graph += 'locations = []\n' for id in node_locations: instance_code_gen_graph += 'locations.append(Locations({}, {}, {}))\n'.format(node_locations[id]['latitude'], node_locations[id]['longitude'], node_locations[id]['height']) attributes_values = [] for id in node_attributes: attributes_values.append(str(node_attributes[id])) instance_code_gen_graph += 'attributes = NodeAttributes_{}({})\n'.format(graph_name,','.join(attributes_values)) instance_code_gen_graph += 'nodes["{}"] = Node_{}("{}", locations, attributes)\n\n'.format(node_name, graph_name, node_name) ## LINK instances instance_code_gen_graph += '## Link Instances\n\n' link_set = pns_model.linkSet.links for link in link_set: link_name = link.name # Build Link attributes link_attributes = {} for i in range(len(link.attributes)): attr = link.attributes[i] attr_val = link.val[i] link_attributes[attr.name] = attr_val # NodePair node_pair = [link.nodePair.nodeSource.name, link.nodePair.nodeTarget.name] attributes_values = [] for id in link_attributes: attributes_values.append(str(link_attributes[id])) instance_code_gen_graph += 'node_pair = {}\n'.format(node_pair) instance_code_gen_graph += 'nodes["{}"].neighbours.append(("{}", "{}"))\n'.format(node_pair[0], link_name, node_pair[1]) instance_code_gen_graph += 'attributes = LinkAttributes_{}({})\n'.format(graph_name,','.join(attributes_values)) instance_code_gen_graph += 'links["{}"] = Link_{}("{}", node_pair, attributes)\n\n'.format(link_name, graph_name, link_name) instance_code_gen_graph += 'graph = Graph_{}("{}", nodes, links)\n'.format(graph_name, graph_name) instance_code_gen_graph += 'network_structure = NetworkStructure(graph, things)' return instance_code_gen_graph ## Generate Things def generateThingClass(name, attributes): class_gen = 'class Thing_{}(ThingAbstract):\n\tdef __init__(self,id, schedule, locations'.format(name) if len(attributes) > 0: class_gen += ',attributes):\n' else: class_gen += '):\n' class_gen += '\t\tself.id = id\n' class_gen += '\t\tself.schedule = schedule\n' class_gen += '\t\tself.locations = locations\n' class_gen += '\t\tself.attributes = attributes\n' return class_gen def generateThingAttributes(name, attributes): param_list = ', '.join(attributes) thing_attributes_class = 'class ThingAttributes_{}:\n\tdef __init__(self'.format(name) if len(param_list) > 0: thing_attributes_class += ', ' + param_list + '):\n' else: thing_attributes_class += '):\n' for attr in attributes: thing_attributes_class += '\t\tself.{} = {}\n'.format(attr, attr) attribute_list = ['"' + attr + '"' for attr in attributes] thing_attributes_class += '\tdef listAttributes(self):\n\t\treturn [{}]\n'.format(','.join(attribute_list)) return thing_attributes_class def generateThingClasses(trs_model): thing_name = trs_model.name attributes = [] for attr in trs_model.attributes: attributes.append(attr.name) thing_class_gen = generateThingClass(thing_name, attributes) thing_attributes_class = generateThingAttributes(thing_name, attributes) thing_classes = thing_attributes_class + '\n' + thing_class_gen return thing_classes ## Generate Graph def generateGraphClass(name): graph_class = 'class Graph_{}(GraphAbstract):\n'.format(name) graph_class += '\tdef __init__(self, id, nodes, links):\n' graph_class += '\t\tself.id= id\n' graph_class += '\t\tself.nodes = nodes\n\t\tself.links=links\n' graph_class += '\t\tself.paths = depthFirstSearch(self.nodes)\n' return graph_class def generateNodeClass(name): node_class = 'class Node_{}(NodeAbstract):\n'.format(name) node_class += '\tdef __init__(self, id, locations, attributes):\n' node_class += '\t\tself.id = id\n' node_class += '\t\tself.locations=locations\n' node_class += '\t\tself.attributes = attributes\n' node_class += '\t\tself.neighbours = []\n' return node_class def generateLinkClass(name): link_class = 'class Link_{}(LinkAbstract):\n'.format(name) link_class += '\tdef __init__(self, id, node_pair, attributes):\n' link_class += '\t\tself.id = id\n' link_class += '\t\tself.node_pair=node_pair\n' link_class += '\t\tself.attributes=attributes\n' return link_class def generateNodeAttributes(name, node_set): attributes = [] for attr in node_set.attributes: attributes.append(attr.name) param_list = ', '.join(attributes) nodeAttributesClass = 'class NodeAttributes_{}:\n\tdef __init__(self'.format(name) if len(param_list) > 0: nodeAttributesClass += ', ' + param_list + '):\n' else: nodeAttributesClass += '):\n' for attr in attributes: nodeAttributesClass += '\t\tself.{} = {}\n'.format(attr, attr) attribute_list = ['"' + attr + '"' for attr in attributes] nodeAttributesClass += '\tdef listAttributes(self):\n\t\treturn [{}]\n'.format(','.join(attribute_list)) return nodeAttributesClass def generateLinkAttributes(name, link_set): attributes = [] for attr in link_set.attributes: attributes.append(attr.name) param_list = ', '.join(attributes) linkAttributesClass = 'class LinkAttributes_{}:\n\tdef __init__(self'.format(name) if len(param_list) > 0: linkAttributesClass += ', ' + param_list + '):\n' else: linkAttributesClass += '):\n' for attr in attributes: linkAttributesClass += '\t\tself.{} = {}\n'.format(attr, attr) attribute_list = ['"' + attr + '"' for attr in attributes] linkAttributesClass += '\tdef listAttributes(self):\n\t\treturn [{}]\n'.format(','.join(attribute_list)) return linkAttributesClass def generateGraphClasses(pns_model): graph_name = pns_model.name node_set = pns_model.nodeSet link_set = pns_model.linkSet graph_class_gen = [] graph_class_gen.append(generateGraphClass(graph_name)) graph_class_gen.append(generateNodeClass(graph_name)) graph_class_gen.append(generateLinkClass(graph_name)) graph_class_gen.append(generateNodeAttributes(graph_name, node_set)) graph_class_gen.append(generateLinkAttributes(graph_name, link_set)) return ['\n'.join(graph_class_gen), graph_name] def code_gen(trs_model, pns_model, trs_location, nsm_location): attribute_class_gen = [] attribute_class_gen.append('from CodeGen.Python.networkStructure import *\n') attribute_class_gen.append(generateThingClasses(trs_model=trs_model)) [graph_code_gen, graph_name] = generateGraphClasses(pns_model) attribute_class_gen.append(graph_code_gen) # Instances attribute_class_gen.append(trs_parser(trs_model, trs_location)) attribute_class_gen.append(pns_parser(pns_model, nsm_location, graph_name)) a = open('networkStructureAttributesAndInstances.py', 'w') a.write('\n'.join(attribute_class_gen)) trs_file = 'TRS/iotRequestSchedule.trs' trs_grammar = 'TRS/trs.tx' trs_location_file = 'TRS/location.json' ## Verify TRS file mm_trs = metamodel_from_file(trs_grammar) metamodel_export(mm_trs, 'TRS/trs.dot') os.system('dot -Tpng -O TRS/trs.dot') #os.system('dot -Tpng -O TRS/trs_grammar.dot') # Creates PNG of metamodel from Grammar try: trs_model = mm_trs.model_from_file(trs_file) # All attributes are unique unique_set = list(set(trs_model.attributes)) if len(trs_model.attributes) != len(unique_set): raise Exception("Things attributes must be unique: ThingSet {}.".format(trs_model.name)) # The attributes of each thing is unique for thing in trs_model.things: thing_unqiue_attr = list(set(thing.attributes)) if len(thing_unqiue_attr) != len(thing.attributes): raise Exception("Thing attribubte must be unqiue: Thing {}".format(thing.name)) except Exception as e: print('Verification Failed: Error in file {}'.format(trs_file)) print(e) exit() print('Verification of file {} succeeded.'.format(trs_file)) with open(trs_location_file) as loc: loc_data_trs = json.load(loc) trs_parser(trs_model, loc_data_trs['location']) # pns_file = 'PNS/edgeNetwork.pns' pns_location_file = 'PNS/location.json' pns_grammar = 'PNS/pns.tx' ## Verify PNM file mm_pns = metamodel_from_file(pns_grammar) metamodel_export(mm_pns, 'PNS/pns.dot') os.system('dot -Tpng -O PNS/pns.dot') #os.system('dot -Tpng -O TRS/trs_grammar.dot') # Creates PNG of metamodel from Grammar try: pns_model = mm_pns.model_from_file(pns_file) # All attributes are unique ## Nodes nodeSet = pns_model.nodeSet unique_set_node = list(set(nodeSet.attributes)) if len(nodeSet.attributes) != len(unique_set_node): raise Exception("NodeSet attributes must be unique: Graph {}.".format(pns_model.name)) # The attributes of each thing is unique for node in nodeSet.nodes: node_unqiue_attr = list(set(nodeSet.attributes)) if len(node_unqiue_attr) != len(nodeSet.attributes): raise Exception("Node attribubte must be unqiue: Node {}".format(node.name)) ## Links linkSet = pns_model.linkSet unique_set_link = list(set(linkSet.attributes)) if len(linkSet.attributes) != len(unique_set_link): raise Exception("LinkSet attributes must be unique: Graph {}.".format(pns_model.name)) # The attributes of each thing is unique for link in linkSet.links: link_unqiue_attr = list(set(linkSet.attributes)) if len(link_unqiue_attr) != len(linkSet.attributes): raise Exception("Link attribubte must be unqiue: Link {}".format(link.name)) except Exception as e: print('Verification Failed: Error in file {}'.format(pns_file)) print(e) exit() print('Verification of file {} succeeded.'.format(pns_file)) with open(pns_location_file) as loc: loc_data_nsm = json.load(loc) code_gen(trs_model, pns_model, loc_data_trs['location'], loc_data_nsm['location'])
{"/CodeGen/Python/QueuingNetwork.py": ["/CodeGen/Python/networkStructureAttributesAndInstances.py", "/CodeGen/Python/networkUtil.py"], "/CodeGen/Python/codeGen.py": ["/CodeGen/Python/networkStructure.py"], "/CodeGen/Python/networkStructureAttributesAndInstances.py": ["/CodeGen/Python/networkStructure.py"], "/CodeGen/Python/networkStructureAnalysis.py": ["/CodeGen/Python/networkStructureAttributesAndInstances.py", "/CodeGen/Python/networkUtil.py"]}
24,014,422
ismael-martinez/NetworkStructureDSLs
refs/heads/master
/CodeGen/Python/networkStructureAttributesAndInstances.py
from CodeGen.Python.networkStructure import * class ThingAttributes_IoT: def __init__(self, fileSize_mb, localCPU_ghz, localProcessing_ms, memoryReq_mb, storageReq_mb): self.fileSize_mb = fileSize_mb self.localCPU_ghz = localCPU_ghz self.localProcessing_ms = localProcessing_ms self.memoryReq_mb = memoryReq_mb self.storageReq_mb = storageReq_mb def listAttributes(self): return ["fileSize_mb","localCPU_ghz","localProcessing_ms","memoryReq_mb","storageReq_mb"] class Thing_IoT(ThingAbstract): def __init__(self,id, schedule, locations,attributes): self.id = id self.schedule = schedule self.locations = locations self.attributes = attributes class Graph_Edge(GraphAbstract): def __init__(self, id, nodes, links): self.id= id self.nodes = nodes self.links=links self.paths = depthFirstSearch(self.nodes) class Node_Edge(NodeAbstract): def __init__(self, id, locations, attributes): self.id = id self.locations=locations self.attributes = attributes self.neighbours = [] class Link_Edge(LinkAbstract): def __init__(self, id, node_pair, attributes): self.id = id self.node_pair=node_pair self.attributes=attributes class NodeAttributes_Edge: def __init__(self, storage_mb, cpu_ghz, memory_mb): self.storage_mb = storage_mb self.cpu_ghz = cpu_ghz self.memory_mb = memory_mb def listAttributes(self): return ["storage_mb","cpu_ghz","memory_mb"] class LinkAttributes_Edge: def __init__(self, bandwidth): self.bandwidth = bandwidth def listAttributes(self): return ["bandwidth"] ## Thing instances ## things = {} locations = [] locations.append(Locations(45.465660936499575, -73.74569047347666, 1)) attributes = ThingAttributes_IoT(16,3.2,5,6,0) # schedule_str = ['12:12:00', '12:27:00', '12:42:00', '12:57:00', '13:12:00', '13:27:00', '13:42:00'] schedule = [timestamp(43920),timestamp(44820),timestamp(45720),timestamp(46620),timestamp(47520),timestamp(48420),timestamp(49320)] things["t1"] = Thing_IoT("t1", schedule, locations, attributes) locations = [] locations.append(Locations(45.465678336962135, -73.74567773298384, 1)) locations.append(Locations(45.46566399333796, -73.74567337439419, 1)) attributes = ThingAttributes_IoT(64,3.8,10,32,0) # schedule_str = ['12:00', '12:03', '14:29'] schedule = [timestamp(43920),timestamp(44820),timestamp(45720),timestamp(46620),timestamp(47520),timestamp(48420),timestamp(49320)] things["t2"] = Thing_IoT("t2", schedule, locations, attributes) locations = [] locations.append(Locations(45.465660701358146, -73.74562408880354, 1)) attributes = ThingAttributes_IoT(85,4.6,32,24,0) # schedule_str = ['12:00', '12:03', '14:29'] schedule = [timestamp(43920),timestamp(44820),timestamp(45720),timestamp(46620),timestamp(47520),timestamp(48420),timestamp(49320)] things["t3"] = Thing_IoT("t3", schedule, locations, attributes) locations = [] locations.append(Locations(45.465690799452325, -73.745617383281, 1)) locations.append(Locations(45.465673398993594, -73.74559458450437, 1)) attributes = ThingAttributes_IoT(64,1.3,52,73,0) # schedule_str = ['12:00', '12:03', '14:29'] schedule = [timestamp(43920),timestamp(44820),timestamp(45720),timestamp(46620),timestamp(47520),timestamp(48420),timestamp(49320)] things["t4"] = Thing_IoT("t4", schedule, locations, attributes) locations = [] locations.append(Locations(45.46570138080979, -73.74552954093576, 1)) attributes = ThingAttributes_IoT(543,4.7,542,13,0) # schedule_str = ['12:00', '12:03', '14:29'] schedule = [timestamp(43920),timestamp(44820),timestamp(45720),timestamp(46620),timestamp(47520),timestamp(48420),timestamp(49320)] things["t5"] = Thing_IoT("t5", schedule, locations, attributes) locations = [] locations.append(Locations(45.465699734820994, -73.7455637391007, 1)) attributes = ThingAttributes_IoT(5,5.2,5,6,0) # schedule_str = ['12:00', '12:03', '14:29'] schedule = [timestamp(43920),timestamp(44820),timestamp(45720),timestamp(46620),timestamp(47520),timestamp(48420),timestamp(49320)] things["t6"] = Thing_IoT("t6", schedule, locations, attributes) locations = [] locations.append(Locations(45.46563554122027, -73.74553524062992, 1)) locations.append(Locations(45.4656552931052, -73.74553758756281, 1)) attributes = ThingAttributes_IoT(79,3.2,13,798,0) # schedule_str = ['12:00:00'] schedule = [timestamp(43200)] things["t7"] = Thing_IoT("t7", schedule, locations, attributes) nodes = {} links={} ## Node Instances locations = [] locations.append(Locations(45.465664933903625, -73.7456826990701, 1)) attributes = NodeAttributes_Edge(3.2,1024,512) nodes["n1"] = Node_Edge("n1", locations, attributes) locations = [] locations.append(Locations(45.46566563932783, -73.74562006549, 1)) attributes = NodeAttributes_Edge(2.8,32,128) nodes["n2"] = Node_Edge("n2", locations, attributes) locations = [] locations.append(Locations(45.46569244544138, -73.74554328725696, 1)) attributes = NodeAttributes_Edge(1.6,64,32) nodes["n3"] = Node_Edge("n3", locations, attributes) locations = [] locations.append(Locations(45.46563906834305, -73.74555032805563, 1)) attributes = NodeAttributes_Edge(2.9,2048,4096) nodes["n4"] = Node_Edge("n4", locations, attributes) ## Link Instances node_pair = ['n1', 'n2'] nodes["n1"].neighbours.append(("l1", "n2")) attributes = LinkAttributes_Edge(3.5) links["l1"] = Link_Edge("l1", node_pair, attributes) node_pair = ['n2', 'n3'] nodes["n2"].neighbours.append(("l2", "n3")) attributes = LinkAttributes_Edge(8.1) links["l2"] = Link_Edge("l2", node_pair, attributes) node_pair = ['n2', 'n4'] nodes["n2"].neighbours.append(("l3", "n4")) attributes = LinkAttributes_Edge(7.3) links["l3"] = Link_Edge("l3", node_pair, attributes) graph = Graph_Edge("Edge", nodes, links) network_structure = NetworkStructure(graph, things)
{"/CodeGen/Python/QueuingNetwork.py": ["/CodeGen/Python/networkStructureAttributesAndInstances.py", "/CodeGen/Python/networkUtil.py"], "/CodeGen/Python/codeGen.py": ["/CodeGen/Python/networkStructure.py"], "/CodeGen/Python/networkStructureAttributesAndInstances.py": ["/CodeGen/Python/networkStructure.py"], "/CodeGen/Python/networkStructureAnalysis.py": ["/CodeGen/Python/networkStructureAttributesAndInstances.py", "/CodeGen/Python/networkUtil.py"]}
24,014,423
ismael-martinez/NetworkStructureDSLs
refs/heads/master
/CodeGen/Python/networkStructureAnalysis.py
from CodeGen.Python.networkStructureAttributesAndInstances import * from CodeGen.Python.networkUtil import * import numpy as np import matplotlib.pyplot as plt import nxviz as nv import networkx as nx import os print('*** ATTRIBUTES ***') print('Node Attributes: ' + str(network_structure.listNodeAttributes())) print('Thing Attributes: ' + str(network_structure.listThingAttributes())) print('Link Attributes: ' + str(network_structure.listLinkAttributes()) + '\n') # Show Network Structure G = nx.DiGraph() ns_graph = network_structure.graph for node_id in ns_graph.nodes: G.add_node(node_id) for link_id in ns_graph.links: [n_source, n_target] = ns_graph.links[link_id].node_pair G.add_edge(n_source, n_target) A = nx.nx_pydot.write_dot(G, 'graph.dot') os.system('dot -Tpng -O graph.dot') # Handshake -- create a distance matrix between every 'thing' and 'node' T = len(network_structure.things) N = len(network_structure.graph.nodes) distance_matrix = np.zeros((T, N)) nearest_node = [0]*T thing_key_index = [] for thing in network_structure.things: thing_key_index.append(thing) node_key_index = [] for node in network_structure.graph.nodes: node_key_index.append(node) t = 0 for thing in network_structure.things: n = 0 for node in network_structure.graph.nodes: thing_location = network_structure.things[thing].locations[0] node_location = network_structure.graph.nodes[node].locations[0] distance_matrix[t][n] = distance_location(thing_location, node_location) if distance_matrix[t][n] < distance_matrix[t][nearest_node[t]]: nearest_node[t] = n n += 1 t += 1 node_arrival_schedules = {} for t in range(T): node_id = node_key_index[nearest_node[t]] node_name = network_structure.graph.nodes[node_id].id if node_name not in node_arrival_schedules.keys(): node_arrival_schedules[node_name] = [] thing_id = thing_key_index[t] sched = network_structure.things[thing_id].schedule # Merge i, j = 0, 0 new_sched = [] old_sched = node_arrival_schedules[node_name] while i < len(old_sched) and j < len(sched): if compare_time(old_sched[i], sched[j]) < 0: new_sched.append(old_sched[i]) i += 1 else: new_sched.append(sched[j]) j += 1 while i < len(old_sched): new_sched.append(old_sched[i]) i += 1 while j < len(sched): new_sched.append(sched[j]) j += 1 node_arrival_schedules[node_name] = new_sched # Arrivals per hour min_hour = 0 first_hour_all = 24 last_hour_all = 0 for node in node_arrival_schedules: first_hour = node_arrival_schedules[node][0].hour last_hour = node_arrival_schedules[node][-1].hour if first_hour < first_hour_all: first_hour_all = first_hour if last_hour > last_hour_all: last_hour_all = last_hour hours = list(range(first_hour_all, last_hour_all+1)) arrivals_node = {} max_y = 0 for node in node_arrival_schedules: arrivals = [0]*(last_hour_all - first_hour + 1) for timestamp in node_arrival_schedules[node]: hour = timestamp.hour idx = hour - first_hour_all arrivals[idx] += 1 arrivals_node[node] = arrivals for a in arrivals: if a > max_y: max_y = a for node in node_arrival_schedules: # Plot hourly arrival arrivals = arrivals_node[node] fig, ax = plt.subplots() ax.bar(hours, arrivals) hour_str = [str(h) + 'h00' for h in hours] ax.set_xticks(hours) ax.set_xticklabels(hour_str) ax.set_ylim(0, max_y) ax.set_yticks(list(range(0, max_y+1))) ax.set_xlabel('Hours') ax.set_ylabel('Arrivals') ax.set_title('Arrivals per hour - Node {}'.format(node)) plt.show() # Arrivals per quarter hour (15) quarters = [] for h in hours: for i in range(4): quarter_time = h + i*0.25 quarters.append(quarter_time) arrivals_node = {} max_y = 0 for node in node_arrival_schedules: arrivals = [0]*(last_hour_all - first_hour + 1)*4 for timestamp in node_arrival_schedules[node]: hour = timestamp.hour minutes = timestamp.minutes idx = 4*(hour - first_hour_all) if minutes >= 15 and minutes < 30: idx += 1 elif minutes >= 30 and minutes < 45: idx += 2 elif minutes >= 45: idx += 3 arrivals[idx] += 1 arrivals_node[node] = arrivals for a in arrivals: if a > max_y: max_y = a for node in node_arrival_schedules: # Plot quarterly arrival arrivals = arrivals_node[node] fig, ax = plt.subplots() ax.bar(quarters, arrivals, 0.2, color='g') quarter_str = [] for q in quarters: h = math.floor(q) m = q % 1 if m < 0.25: quarter_str.append(str(h) + 'h00') elif m < 0.5: quarter_str.append(str(h) + 'h15') elif m < 0.75: quarter_str.append(str(h) + 'h30') else: quarter_str.append(str(h) + 'h45') ax.set_xticks(quarters) ax.set_xticklabels(quarter_str) ax.set_ylim(0, max_y) ax.set_yticks(list(range(0, max_y+1))) ax.set_xlabel('Quarter Hours') ax.set_ylabel('Arrivals') ax.set_title('Arrivals per 15 minutes - Node {}'.format(node)) plt.show()
{"/CodeGen/Python/QueuingNetwork.py": ["/CodeGen/Python/networkStructureAttributesAndInstances.py", "/CodeGen/Python/networkUtil.py"], "/CodeGen/Python/codeGen.py": ["/CodeGen/Python/networkStructure.py"], "/CodeGen/Python/networkStructureAttributesAndInstances.py": ["/CodeGen/Python/networkStructure.py"], "/CodeGen/Python/networkStructureAnalysis.py": ["/CodeGen/Python/networkStructureAttributesAndInstances.py", "/CodeGen/Python/networkUtil.py"]}
24,018,963
nvia62/coin2021
refs/heads/main
/hello.py
import random rand = '맞아죽었다', '살았다','퉁퉁이가 기겁하면서 도망쳤다' print("도라에몽이 길을 가다 퉁퉁이를 만났다 어떻게할것인가?") print("1. 맞서싸운다") print("2. 도망간다") print("3. 아무것도 안한다") print("4. 미친척한다") a = int(input("선택: ")) print("%d번을 입력하셧습니다" % a) if (a==1): print("맞아죽었다") elif (a==2): print("무사히 도망쳣다") elif (a==3): print("맞아죽었다") elif (a==4): print(random.choice(rand)) else: print("잘못된 선택지 입니다")
{"/app.py": ["/func.py", "/db.py"]}
24,018,964
nvia62/coin2021
refs/heads/main
/test.py
#import random #menu = '쫄면', '육계장', '비빔밥','돈까스' #print(menu) #print(random.choice(menu)) # a = '쫆면' # b = '육계장' # c = '비빔밥' # d = '돈까스' # print(menulist[0:4]) # print(len(menulist)) menulist = ['쫄면', '육계장', '비빔밥', '돈까스'] for i in menulist: print(i) for i in range(len(menulist)): print(menulist[i])
{"/app.py": ["/func.py", "/db.py"]}
24,018,965
nvia62/coin2021
refs/heads/main
/food.py
for i in range(1, 4): print("밥묵으러 가자") print("치킨 피자 햄버거") a = str(input(str(i) + " 선택:")) print("%s를 선택하셨습니다" % a) if(a=='치킨') : print("맛잇다") elif(a=='피자') : print("맛있다!!") elif(a=='햄버거') : print("맛앗다") else : print("잘못 선택하셧습니다")
{"/app.py": ["/func.py", "/db.py"]}
24,018,966
nvia62/coin2021
refs/heads/main
/db.py
import pymysql def insert_user(userid, pw, name, phone): try: db = pymysql.connect(host='127.0.0.1', user='root', password='1234', db='maindb', charset='utf8') c = db.cursor() setdata = (userid, pw, name, phone) c.execute("INSERT INTO user_tbl (id, pw, name, phone) VALUES (%s, %s, %s, %s)", setdata) db.commit() except Exception as e: print('db error:', e) finally: db.close() def get_idpw(userid, pw): ret = () try: db = pymysql.connect(host='127.0.0.1', user='root', password='1234', db='maindb', charset='utf8') c = db.cursor() setdata = (userid, pw) c.execute("SELECT * FROM user_tbl WHERE id = %s AND pw = %s", setdata) ret = c.fetchone except Exception as e: print('db error:', e) finally: db.close() return(ret)
{"/app.py": ["/func.py", "/db.py"]}
24,018,967
nvia62/coin2021
refs/heads/main
/food2.py
### 아래 전체를 반복 ### import random for i in range(1, 4): print("밥무러 가자") print("메뉴는? ") menu1 = '학식', '분식', '중식' print("1.학식 2.분식 3.중식. 4랜덤") menu = input(str(i) + ".입력: ") #만약에 사용자가 입력값이 1 과 같으면 if menu == '1': print("학식 먹어라\n") if menu == '2': print("분식 먹어라\n") if menu == '3': print("중식 먹어라\n") if menu == '4': print("내맘대로") print(random.choice(menu1)) print("") ### 여기까지 반복 ###
{"/app.py": ["/func.py", "/db.py"]}
24,018,968
nvia62/coin2021
refs/heads/main
/app.py
from flask import Flask, request, render_template, redirect, url_for, session from func import ck_idpw import db app = Flask(__name__) app.secret_key = b'aaa!111/' @app.route('/') def index(): return render_template('main.html') @app.route('/coin') def coin(): if 'user' in session: return '코인 거래소' else: return redirect('login') @app.route('/join') def join(): return render_template('join.html') @app.route('/join_action', methods=['GET','POST']) def join_action(): if request.method == 'GET': return "액션페이지" else: id = request.form["id"] pw = request.form["pw"] name = request.form["name"] phone = request.form["phone"] print(id, pw, name, phone) db.insert_user(id, pw, name, phone) #데이터넣기 return ck_idpw(id, pw) @app.route('/login', methods=['GET','POST']) def login(): if request.method == 'GET': return render_template('login.html') else: userid = request.form["userid"] pwd = request.form["pwd"] print(userid, pwd) ret = db.get_idpw(userid, pwd) if ret !=None: session['user'] = ret[3] #로그인처리 return ck_idpw(ret) @app.route('/action_page', methods=['GET','POST']) def action_page(): if request.method == 'GET': return '나는 액션페이지야' else: search = request.form["search"] return "당신은 '{}'로 검색을 했습니다".format(search) @app.route('/image') def image(): return render_template('image.html') @app.route('/logout') def logout(): session.pop('user', None) return redirect(url_for('form')) @app.route('/urltest') def url_test(): return redirect(url_for('naver')) @app.route('/move/<site>') def move_site(site): if site == 'naver': return redirect(url_for('naver')) elif site == 'daum': return redirect(url_for('daum')) else: return '없는 페이지 입니다' @app.errorhandler(404) def page_not_found(error): return "페이지가 없습니다 url를 확인하세요", 404 @app.route('/daum') def daum(): return redirect("http://www.daum.net/") if __name__ == '__main__': with app.test_request_context(): print(url_for('daum')) app.run(debug=True)
{"/app.py": ["/func.py", "/db.py"]}
24,018,969
nvia62/coin2021
refs/heads/main
/func.py
def ck_idpw(ret): if ret !=None: return "성공" else: return "가입되지않은 아이디"
{"/app.py": ["/func.py", "/db.py"]}
24,105,664
eciaF/RL_t
refs/heads/main
/TD3.py
import numpy as np import gym import torch import torch.nn.functional as F from collections import deque from tensorboardX import SummaryWriter import json import datetime from models import Actor, DoubleQNetworks from replaybuffer import ReplayBuffer class Agent(): def __init__(self, action_size, state_size, config, seed): self.action_size = action_size self.state_size = state_size self.tau = config["TD3_tau"] self.gamma = config["TD3_gamma"] self.batch_size = config["TD3_batch_size"] self.noise_clip = config["TD3_noise_clip"] self.sigma_exploration = config["TD3_sigma_exploration"] self.sigma_tilde = config["TD3_sigma_tilde"] self.update_freq = config["TD3_update_freq"] self.max_action = config["max_action"] self.min_action = config["min_action"] self.seed = seed self.env = gym.make(config["env_cont"]) # set seeds for comparison torch.manual_seed(seed) np.random.seed(seed) self.env.seed(seed) self.env.action_space.seed(seed) # check whether cuda available if chosen as device if config["device"] == "cuda": if not torch.cuda.is_available(): config["device"] == "cpu" self.device = config["device"] # replay self.memory = ReplayBuffer((state_size, ), (action_size, ), config["buffer_size"], self.device, config["seed"]) # everything necessary for SummaryWriter time_for_path = datetime.datetime.now().strftime("%Y.%m.%d-%H:%M:%S") pathname = f" {time_for_path}" tensorboard_name = str(config["locexp"]) + "/" + str(pathname) self.writer = SummaryWriter(tensorboard_name) self.steps = 0 # actor, optimizer of actor, target for actor, critic, optimizer of critic, target for critic self.actor = Actor(state_size, action_size, config["fc1_units"], config["fc2_units"], config["seed"]).to(self.device) self.optimizer_a = torch.optim.Adam(self.actor.parameters(), config["TD3_lr_actor"]) self.target_actor = Actor(state_size, action_size, config["fc1_units"], config["fc2_units"], config["seed"]).to(self.device) self.target_actor.load_state_dict(self.actor.state_dict()) self.critic = DoubleQNetworks(state_size, action_size, config["fc1_units"], config["fc2_units"], config["seed"]).to(self.device) self.optimizer_q = torch.optim.Adam(self.critic.parameters(), config["TD3_lr_critic"]) self.target_critic = DoubleQNetworks(state_size, action_size, config["fc1_units"], config["fc2_units"], config["seed"]).to(self.device) self.target_critic.load_state_dict(self.critic.state_dict()) def act(self, state, greedy=False): state = torch.as_tensor(state, dtype=torch.float32, device=self.device) state = state.unsqueeze(0) with torch.no_grad(): action = self.actor(state).numpy()[0] # ^ torch.argmax(q_nns) in continuous case return action def train(self, episodes, timesteps): mean_r = 0 mean_episode = 0 dq = deque(maxlen=100) for i in range(episodes): state = self.env.reset() for t in range(1, timesteps+1): noise = np.zeros(shape=(self.action_size,)) for idx in range(len(noise)): noise[idx] = np.random.normal(0, self.sigma_exploration * self.max_action) action = np.clip((self.act(state) + noise), self.min_action, self.max_action) next_state, reward, done, _ = self.env.step(action) self.memory.add(state, action, next_state, reward, done) state = next_state mean_r += reward # fill replay buffer with 10 samples before updating the policy if i > 10: self.update(t) if done: print(f"timesteps until break: {t}") break # print and write data to tensorboard for pre_evaluation dq.append(mean_r) mean_episode = np.mean(dq) self.writer.add_scalar("average_reward", mean_episode, self.steps) print(f"Episode: {i}, mean_r: {mean_r}, mean_episode: {mean_episode}") mean_r = 0 def update(self, t): self.steps += 1 # sample minibatch and calculate target value and q_nns state, action, next_state, reward, done = self.memory.sample(self.batch_size) noise = np.clip((torch.randn_like(action, dtype=torch.float32) * self.sigma_tilde), -self.noise_clip, self.noise_clip) #noise = (torch.randn_like(action, dtype=torch.float32) * self.sigma_tilde).clamp(-self.noise_clip, self.noise_clip) with torch.no_grad(): next_action = (self.target_actor(next_state) + noise).clamp(self.min_action, self.max_action) q_target = self.target_critic(next_state, next_action) y_target = reward + (self.gamma * torch.min(q_target[0], q_target[1]) * (1-done)) # update critic q_samples_target = self.critic(state, action) loss_0 = F.mse_loss(y_target, q_samples_target[0]) loss_1 = F.mse_loss(y_target, q_samples_target[1]) critics_loss = loss_0 + loss_1 self.writer.add_scalar("critics_loss", critics_loss, self.steps) # set gradients to zero and optimize q self.optimizer_q.zero_grad() critics_loss.backward() self.optimizer_q.step() if t % self.update_freq == 0: # update actor c_action = self.actor(state) q_sum_samples = self.critic(state, c_action)[0] actor_loss = -q_sum_samples.mean() self.writer.add_scalar("actor_loss", actor_loss, self.steps) # set gradients to zero and optimize a self.optimizer_a.zero_grad() actor_loss.backward() self.optimizer_a.step() # update target networks self.update_target(self.actor, self.target_actor) self.update_target(self.critic, self.target_critic) def update_target(self, online, target): for parameter, target in zip(online.parameters(), target.parameters()): target.data.copy_(self.tau * parameter.data + (1 - self.tau) * target.data) def main(): with open('param.json') as f: config = json.load(f) env = gym.make(config["env_cont"]) action_space = env.action_space.shape[0] state_size = env.observation_space.shape[0] config["max_action"] = env.action_space.high[0] config["min_action"] = env.action_space.low[0] agent = Agent(action_size=action_space, state_size=state_size, config=config, seed=config["seed"]) agent.train(episodes=1000, timesteps=1000) if __name__ == "__main__": main()
{"/TD3.py": ["/models.py", "/replaybuffer.py"], "/DDPG.py": ["/models.py", "/replaybuffer.py"]}
24,105,665
eciaF/RL_t
refs/heads/main
/DDPG.py
import time import numpy as np import gym import torch import torch.nn.functional as F from collections import deque from tensorboardX import SummaryWriter import json from helper import OrnsteinUhlenbeckProcess from models import Actor, QNetwork from replaybuffer import ReplayBuffer class Agent(): def __init__(self, action_size, state_size, config): self.action_size = action_size self.state_size = state_size self.tau = config["tau"] self.gamma = config["gamma"] self.batch_size = config["batch_size"] # check whether cuda available if chosen as device if config["device"] == "cuda": if not torch.cuda.is_available(): config["device"] == "cpu" self.device = config["device"] # initialize noise self.noise = OrnsteinUhlenbeckProcess(sigma=0.2, theta=0.15, dimension=action_size) self.noise.reset() # replay self.memory = ReplayBuffer((state_size, ), (action_size, ), config["buffer_size"], self.device) # everything necessary for SummaryWriter pathname = f"tau={self.tau}, gamma: {self.gamma}, \ batchsize: {self.batch_size}, {time.ctime()}" tensorboard_name = str(config["locexp"]) + '/runs' + str(pathname) self.writer = SummaryWriter(tensorboard_name) self.steps = 0 # actor, optimizer of actor, target for actor, critic, optimizer of # critic, target for critic self.actor = Actor(state_size, action_size, config["fc1_units"], config["fc2_units"]).to(self.device) self.optimizer_a = torch.optim.Adam(self.actor.parameters(), config["lr_actor"]) self.target_actor = Actor(state_size, action_size, config["fc1_units"], config["fc2_units"]).to(self.device) self.target_actor.load_state_dict(self.actor.state_dict()) self.critic = QNetwork(state_size, action_size, config["fc1_units"], config["fc2_units"]).to(self.device) self.optimizer_q = torch.optim.Adam(self.critic.parameters(), config["lr_critic"]) self.target_critic = QNetwork(state_size, action_size, config["fc1_units"], config["fc2_units"]).to(self.device) self.target_critic.load_state_dict(self.critic.state_dict()) def act(self, state, greedy=False): state = torch.as_tensor(state, dtype=torch.float32, device=self.device) state = state.unsqueeze(0) with torch.no_grad(): action = self.actor(state).numpy()[0] # ^ torch.argmax(q_nns) in continuous case noise = self.noise.step() action = action if greedy else np.clip(action + noise, -1, 1) return action def train(self, episodes, timesteps): env = gym.make("LunarLanderContinuous-v2") mean_r = 0 mean_episode = 0 dq = deque(maxlen=100) for i in range(episodes): state = env.reset() if i % 10 == 0: self.noise.reset() for j in range(timesteps): action = self.act(state) next_state, reward, done, _ = env.step(action) self.memory.add(state, action, next_state, reward, done) state = next_state mean_r += reward # fill replay buffer with 10 samples before updating the policy if i > 10: self.update() if done: print(f"timesteps until break: {j}") break # print and write data to tensorboard for pre_evaluation dq.append(mean_r) mean_episode = np.mean(dq) self.writer.add_scalar("a_rew", mean_episode, i) print(f"Episode: {i}, mean_r: {mean_r}, \ mean_episode: {mean_episode}") mean_r = 0 def update(self): self.steps += 1 # sample minibatch and calculate target value and q_nns state, action, next_state, reward, done = self.memory.sample(self.batch_size) with torch.no_grad(): next_action = self.target_actor(next_state) q_target = self.target_critic(next_state, next_action).detach() y_target = reward + (self.gamma * q_target * (1-done)) # update critic q_samples_target = self.critic(state, action) loss_critic = F.mse_loss(y_target, q_samples_target) self.writer.add_scalar("loss_critic", loss_critic, self.steps) # set gradients to zero and optimize q self.optimizer_q.zero_grad() loss_critic.backward() self.optimizer_q.step() # update actor c_action = self.actor(state) q_sum_samples = self.critic(state, c_action) loss_actor = -q_sum_samples.mean() self.writer.add_scalar("loss_actor", loss_actor, self.steps) # set gradients to zero and optimize a self.optimizer_a.zero_grad() loss_actor.backward() self.optimizer_a.step() # update target networks self.update_target(self.actor, self.target_actor) self.update_target(self.critic, self.target_critic) def update_target(self, online, target): for parameter, target in zip(online.parameters(), target.parameters()): target.data.copy_(self.tau * parameter.data + (1 - self.tau) * target.data) def main(): with open('param.json') as f: config = json.load(f) env = gym.make("LunarLanderContinuous-v2") torch.manual_seed(config["seed"]) np.random.seed(config["seed"]) env.seed(config["seed"]) env.action_space.seed(config["seed"]) env.reset() action_space = env.action_space.shape[0] state_size = env.observation_space.shape[0] agent = Agent(action_size=action_space, state_size=state_size, config=config) agent.train(episodes=1000, timesteps=1000) if __name__ == "__main__": main()
{"/TD3.py": ["/models.py", "/replaybuffer.py"], "/DDPG.py": ["/models.py", "/replaybuffer.py"]}
24,105,666
eciaF/RL_t
refs/heads/main
/models.py
import torch import torch.nn as nn import torch.nn.functional as F class Actor(nn.Module): def __init__(self, state_size, action_size, fc1, fc2, seed): super(Actor, self).__init__() self.seed = torch.manual_seed(seed) self.layer1 = nn.Linear(state_size, fc1) self.layer2 = nn.Linear(fc1, fc2) self.layer3 = nn.Linear(fc2, action_size) self.leak = 0.01 self.reset_parameteres() def forward(self, states): out_l1 = F.relu(self.layer1(states)) out_l2 = F.relu(self.layer2(out_l1)) out = F.tanh(self.layer3(out_l2)) return out def reset_parameteres(self): nn.init.kaiming_normal_(self.layer1.weight.data, a=self.leak, mode='fan_in') nn.init.kaiming_normal_(self.layer2.weight.data, a=self.leak, mode='fan_in') nn.init.uniform_(self.layer3.weight.data, -3e-3, 3e-3) class QNetwork(nn.Module): def __init__(self, state_size, action_size, fc1, fc2, seed): super(QNetwork, self).__init__() self.seed = torch.manual_seed(seed) self.layer1 = nn.Linear(state_size + action_size, fc1) self.layer2 = nn.Linear(fc1, fc2) self.layer3 = nn.Linear(fc2, 1) self.leak = 0.01 self.reset_parameteres() def forward(self, states, actions): batch = torch.cat([states, actions], 1) x1 = F.relu(self.layer1(batch)) x2 = F.relu(self.layer2(x1)) x3 = self.layer3(x2) return x3 def reset_parameteres(self): nn.init.kaiming_normal_(self.layer1.weight.data, a=self.leak, mode='fan_in') nn.init.kaiming_normal_(self.layer2.weight.data, a=self.leak, mode='fan_in') nn.init.uniform_(self.layer3.weight.data, -3e-3, 3e-3) class DoubleQNetworks(nn.Module): def __init__(self, state_size, action_size, fc1, fc2, seed): super(DoubleQNetworks, self).__init__() self.seed = torch.manual_seed(seed) self.layer1_1 = nn.Linear(state_size + action_size, fc1) self.layer2_1 = nn.Linear(fc1, fc2) self.layer3_1 = nn.Linear(fc2, 1) self.layer1_2 = nn.Linear(state_size + action_size, fc1) self.layer2_2 = nn.Linear(fc1, fc2) self.layer3_2 = nn.Linear(fc2, 1) self.leak = 0.01 self.reset_parameteres() def forward(self, states, actions): batch = torch.cat([states, actions], 1) q1_out1 = F.relu(self.layer1_1(batch)) q1_out2 = F.relu(self.layer2_1(q1_out1)) q1_out3 = self.layer3_1(q1_out2) q2_out1 = F.relu(self.layer1_2(batch)) q2_out2 = F.relu(self.layer2_2(q2_out1)) q2_out3 = self.layer3_2(q2_out2) return q1_out3, q2_out3 def reset_parameteres(self): torch.nn.init.kaiming_normal_(self.layer1_1.weight.data, a=self.leak, mode='fan_in') torch.nn.init.kaiming_normal_(self.layer2_1.weight.data, a=self.leak, mode='fan_in') torch.nn.init.uniform_(self.layer3_1.weight.data, -3e-3, 3e-3) torch.nn.init.kaiming_normal_(self.layer1_2.weight.data, a=self.leak, mode='fan_in') torch.nn.init.kaiming_normal_(self.layer2_2.weight.data, a=self.leak, mode='fan_in') torch.nn.init.uniform_(self.layer3_2.weight.data, -3e-3, 3e-3)
{"/TD3.py": ["/models.py", "/replaybuffer.py"], "/DDPG.py": ["/models.py", "/replaybuffer.py"]}
24,105,667
eciaF/RL_t
refs/heads/main
/replaybuffer.py
import numpy as np import torch class ReplayBuffer: def __init__(self, state_size, action_size, capacity, device, seed): self.seed = torch.manual_seed(seed) np.random.seed(seed) self.state_size = state_size self.action_size = action_size self.capacity = capacity self.device = device self.index = 0 self.full = False self.state = np.empty(shape=(capacity, *state_size), dtype=np.float32) self.action = np.empty(shape=(capacity, *action_size), dtype=np.float32) self.next_state = np.empty(shape=(capacity, *state_size), dtype=np.float32) self.reward = np.empty(shape=(capacity, 1), dtype=np.float32) self.done = np.empty(shape=(capacity, 1), dtype=np.int8) def add(self, state, action, next_state, reward, done): np.copyto(self.state[self.index], state) np.copyto(self.action[self.index], action) np.copyto(self.next_state[self.index], next_state) np.copyto(self.reward[self.index], reward) np.copyto(self.done[self.index], done) self.index = (self.index + 1) % self.capacity if self.index == 0: self.full = True def sample(self, batchsize): limit = self.index if not self.full else self.capacity batch = np.random.randint(0, limit, size=batchsize) state = torch.as_tensor(self.state[batch], device=self.device) action = torch.as_tensor(self.action[batch], device=self.device) next_state = torch.as_tensor(self.next_state[batch], device=self.device) reward = torch.as_tensor(self.reward[batch], device=self.device) done = torch.as_tensor(self.done[batch], device=self.device) return state, action, next_state, reward, done def save_memory(self): pass def load_memory(self): pass
{"/TD3.py": ["/models.py", "/replaybuffer.py"], "/DDPG.py": ["/models.py", "/replaybuffer.py"]}
24,115,770
DyaniDillard/StagHuntResearch
refs/heads/main
/spacy_agent.py
import sys sys.path.append('~/Desktop/Research/companionsKQML-master/companionsKQML/pythonian') from pythonian import Pythonian from spacy_parser import SpacyParser import logging logger = logging.getLogger('SpacyAgent') class SpacyAgent(Pythonian): """ Agent serving as API to Spacy NLP. """ name = "SpacyAgent" # This is the name of the agent to register with def __init__(self, **kwargs): super(SpacyAgent, self).__init__(**kwargs) self.spacy = SpacyParser() self.add_achieve('pos_tags', self.pos_tags) self.add_achieve('dependency_parse', self.dependency_parse) def pos_tags(self, content): # create return message. logger.debug("parsing sentence" + str(content)) pos_tags = self.spacy.pos_tags(content) logger.debug("finished\n\n") return pos_tags def dependency_parse(self, content): # create return message. logger.debug("parsing sentence" + str(content)) dependency_parse = self.spacy.dependency_parse(content) logger.debug("finished\n\n") return dependency_parse if __name__ == "__main__": logger.setLevel(logging.DEBUG) a = SpacyAgent(host='localhost', port=9000, localPort=8950, debug=True)
{"/spacy_agent.py": ["/spacy_parser.py"]}
24,115,771
DyaniDillard/StagHuntResearch
refs/heads/main
/my_staghunt.py
from companionsKQML.pythonian import Pythonian import socialSim.run_sim as sim import logging logger = logging.getLogger('StagHuntAgent') class StagHuntAgent(Pythonian): name = "StagHuntAgent" def __init__(self, **kwargs): super(StagHuntAgent, self).__init__(**kwargs) self.add_achieve(sim.my_make_game, 'my_make_game') self.add_achieve(sim.my_run_one, 'my_run_one') if __name__ == "__main__": logger.setLevel(logging.DEBUG) AGENT = StagHuntAgent.parse_command_line_args() # kqml AssertionError: Connection formed but output (None) not set. # (achieve :receiver StagHuntAgent :content (task :action (run_sim (2, 1, 3))))
{"/spacy_agent.py": ["/spacy_parser.py"]}
24,115,772
DyaniDillard/StagHuntResearch
refs/heads/main
/spacy_parser.py
import spacy class SpacyParser(): """ EA new POS tags: (Verb Quantifier-SP Punctuation-SP Pronoun Preposition Noun Interjection Determiner SubordinatingConjunction Conjunction OrdinalAdjective Number-SP AuxVerb Adverb Adjective) USED: Verb, Punctuation-SP, Pronoun, Preposition, Noun, Interjection, Determiner, Conjunction, Adverb, Adjective, Number-SP, AuxVerb, SubordinatingConjunction NOT USED: Quantifier-SP, OrdinalAdjective """ SPACY_POS_TO_EA_LEXTAG = { "NOUN": "Noun", "PRON": "Pronoun", "VERB": "Verb", "ADV": "Adverb", "PUNCT": "Punctuation-SP", "DET": "Determiner", "ADJ": "Adjective", "SYM": "unknown", "X": "unknown", "CONJ": "Conjunction", "NUM": "Number-SP", # (ordinal numbers "ordinal" not present in Spacy) "ADP": "Preposition", "PROPN": "pname", "PART": "advpart", "SPACE": "unknown", "INTJ": "Interjection", "AUX": "AuxVerb", "SCONJ": "SubordinatingConjunction", # TODO: this doesn't work (might have to change that in lisp code) # Missing: # quant (quantifiers), name, scope (scope markers), unit, word (grammatical function words), # misc, title (Title occurring before a proper name, e.g., Mr., Ms., etc) } def __init__(self): # load Spacy English model. self.nlp = spacy.load('en') def pos_tags(self, text): # Convert to a normal string and remove the " " text = str(text)[1:-1] doc = self.nlp(text) pos = [(token.text, self.SPACY_POS_TO_EA_LEXTAG[token.pos_]) for token in doc] return pos_list def dependency_parse(self, text): # Convert to a normal string and remove the " " text = str(text)[1:-1] dep = ["(%s %s %s)" % (token.dep_, str(token.head.i), str(token.i)) for token in doc] return dep
{"/spacy_agent.py": ["/spacy_parser.py"]}
24,115,773
DyaniDillard/StagHuntResearch
refs/heads/main
/staghunt_htn.py
import pyhop from a_start import a_star_search import sys INFINITY = sys.maxsize # general start state with all the necessary fields, and some necessary values def get_start_state(): state = pyhop.State('init') state.agents = [('r1', 'rabbit'), ('r2', 'rabbit'), ('s1', 'stag'), ('s2', 'stag'), ('s3', 'stag'), ('h1', 'hunter'), ('h2', 'hunter'), ('h3', 'hunter')] state.loc = {} state.map = None state.target = {} state.goal = {} state.assumes = {} state.captured = [] state.score = {('h1', 'hunter'):0, ('h2', 'hunter'):0, ('h3', 'hunter'):0} state.ready = [] return state # general rules def hunts(agent1, agent2): return agent1[1] == 'hunter' and (agent2[1] == 'stag' or agent2[1] == 'rabbit') def nearby(state, agent1, agent2): if agent1 in state.loc and agent2 in state.loc: return (abs(state.loc[agent1][0] - state.loc[agent2][0]) + abs(state.loc[agent1][1] - state.loc[agent2][1])) < 2 else: return False def distance(state, agent1, agent2): if agent1 in state.loc and agent2 in state.loc: return abs(state.loc[agent1][0] - state.loc[agent2][0]) + abs(state.loc[agent1][1] - state.loc[agent2][1]) else: return INFINITY def has_no_hunter(state, prey, loc): for other_agent in state.agents: # for each hunter if hunts(other_agent, prey) and \ loc[0] == state.loc[other_agent][0] and \ loc[1] == state.loc[other_agent][1] : # hunter is immediately to the right return False return True ########################################### # methods ########################################### def simulate_step_forall(state): tasks = [] for agent in state.agents: tasks.append(('simulate_agent', agent)) tasks.append(('simulate_game',)) return tasks def hunt(state, hunter): if hunter[1] == 'hunter': return [('pick_target', hunter), ('move_towards_target', hunter)] else: return False def plan(state, hunter, goal): print('plan', hunter, state.loc[hunter], goal) if state.loc[hunter] == goal: print('-at goal') return [('wait_one', hunter)] p = a_star_search(state, hunter, goal, [step_up, step_down, step_left, step_right]) if p: print('-plan to', p[0].__name__) return [(p[0].__name__, hunter)] print("no plan", hunter, goal) return False def mt_target(state, hunter): return [('move_towards', hunter, state.loc[state.target[hunter]])] def survive(state, prey): # if prey if prey[1] == 'stag': for agent in state.agents: if agent[1] == 'hunter' and nearby(state, prey, agent): return [('move_away_from', prey, agent)] return [('wait', prey)] else: return False # cooperate or not def cooperate(state, agent): # TODO need better logic here if agent in state.goal and 'cooperateWith' in state.goal[agent]: g = state.goal[agent]['cooperateWith'] if g[0] == agent: return [('pick_coop_target', agent, g[1])] else: return False else: return False def betray(state, agent): print('betray', agent) return [('pick_closest_target', agent)] # move towards def move_towards_up(state, agent, goal): # if goal is a valid goal of agent if state.loc[goal][1] < state.loc[agent][1]: print('move towards up', agent, goal) return [('step_up', agent)] else: return False def move_towards_down(state, agent, goal): if state.loc[goal][1] > state.loc[agent][1]: print('move towards up', agent, goal) return [('step_down', agent)] else: return False def move_towards_left(state, agent, goal): if state.loc[goal][0] < state.loc[agent][0]: print('move towards up', agent, goal) return [('step_left', agent)] else: return False def move_towards_right(state, agent, goal): if state.loc[goal][0] > state.loc[agent][0]: print('move towards up', agent, goal) return [('step_right', agent)] else: return False # move away def move_away_up(state, agent, enemy): # if enemy is threat to agent if state.loc[enemy][1] > state.loc[agent][1]: if has_no_hunter(state, agent, (state.loc[agent][0],state.loc[agent][1]-1)): return [('step_up', agent)] return False def move_away_down(state, agent, enemy): # if enemy is threat to agent if state.loc[enemy][1] < state.loc[agent][1]: if has_no_hunter(state, agent, (state.loc[agent][0],state.loc[agent][1]+1)): return [('step_down', agent)] return False def move_away_left(state, agent, enemy): # if enemy is threat to agent if state.loc[enemy][0] > state.loc[agent][0]: if has_no_hunter(state, agent, (state.loc[agent][0]-1,state.loc[agent][1])): return [('step_left', agent)] return False def move_away_right(state, agent, enemy): # agent is right of enemy if state.loc[enemy][0] < state.loc[agent][0]: if has_no_hunter(state, agent, (state.loc[agent][0]+1,state.loc[agent][1])): return [('step_right', agent)] return False # evade def evade_up(state, agent, enemy): # if enemy is threat to agent if state.loc[agent][0] != state.loc[enemy][0] and state.loc[agent][1] == state.loc[enemy][1]: if has_no_hunter(state, agent, (state.loc[agent][0],state.loc[agent][1]-1)): return [('step_up', agent)] return False def evade_down(state, agent, enemy): # if enemy is threat to agent if state.loc[agent][0] != state.loc[enemy][0] and state.loc[agent][1] == state.loc[enemy][1]: if has_no_hunter(state, agent, (state.loc[agent][0],state.loc[agent][1]+1)): return [('step_down', agent)] return False def evade_left(state, agent, enemy): # if enemy is threat to agent if state.loc[agent][0] == state.loc[enemy][0] and state.loc[agent][1] != state.loc[enemy][1]: if has_no_hunter(state, agent, (state.loc[agent][0]-1,state.loc[agent][1])): return [('step_left', agent)] return False def evade_right(state, agent, enemy): # if enemy is threat to agent if state.loc[agent][0] == state.loc[enemy][0] and state.loc[agent][1] != state.loc[enemy][1]: if has_no_hunter(state, agent, (state.loc[agent][0]+1,state.loc[agent][1])): return [('step_right', agent)] return False def capture_prey(state): print('*capture prey*') tasks = [] for agent in state.agents: for target in state.agents: if hunts(agent, target) and target in state.loc and state.loc[agent] == state.loc[target]: tasks.append(('attempt_capture_target', agent)) return tasks def attempt_stag_capture(state, hunter): for target in state.agents: if target[1] == 'stag' and target in state.loc and state.loc[hunter] == state.loc[target]: return [('capture_stag', hunter, target)] return False def attempt_rabbit_capture(state, hunter): for target in state.agents: if target[1] == 'rabbit' and target in state.loc and state.loc[hunter] == state.loc[target]: return [('capture_rabbit', hunter, target)] return False def attempt_no_capture(state, hunter): return [] def wait(state, agent): return [('wait_one', agent)] def load_methods(pyhop): pyhop.declare_methods('sim_all', simulate_step_forall) pyhop.declare_methods('move_away_from', move_away_up, move_away_down, move_away_left, move_away_right, evade_up, evade_down, evade_left, evade_right) pyhop.declare_methods('move_towards', plan) pyhop.declare_methods('simulate_agent', hunt, survive, wait) pyhop.declare_methods('simulate_game', capture_prey) pyhop.declare_methods('move_towards_target', mt_target) pyhop.declare_methods('pick_target', cooperate, betray) pyhop.declare_methods('attempt_capture_target', attempt_stag_capture, attempt_rabbit_capture, attempt_no_capture) ########################################### # operators ########################################### def wait_one(state, agent): return state def pick_closest_target(state, agent): best = ('', INFINITY) for ptarget in state.agents: if hunts(agent, ptarget) and ptarget[1] == 'rabbit' and ptarget not in state.captured and distance(state, agent, ptarget) < best[1]: best = (ptarget, distance(state, agent, ptarget)) if best[1] < 20: # arbitrary distance print('closest target', agent, best) state.target[agent] = best[0] if agent not in state.goal: state.goal[agent] = {} # else: # state.goal[agent]= {'hunt':(agent, best[0])} state.goal[agent]['hunt'] = (agent, best[0]) # picked a target, hunter is now locked and loaded if agent not in state.ready: state.ready.append(agent) if best[1] == 0: print('****', agent, best[0], '****') print(state.loc) #sys.exit(1) return state else: return False def pick_coop_target(state, agent, other): print('PICK COOP', agent, other) best = ('', INFINITY) for ptarget in state.agents: if hunts(agent, ptarget) and ptarget[1] == 'stag' and ptarget not in state.captured: d = distance(state, agent, ptarget) + distance(state, other, ptarget) if d < best[1]: best = (ptarget, d) print(best) if best[1] < 100: # arbitrary distance state.target[agent] = best[0] print('target is', best) state.goal[agent]['huntWith'] = (agent, best[0], other) # picked a target, hunter is now locked and loaded if agent not in state.ready: state.ready.append(agent) return state else: print('**** failed to pick coop target ****') return False def step_right(state, agent): # print('try: step right', agent) if state.map[state.loc[agent][0]+1][state.loc[agent][1]] > 0: state.loc[agent] = (state.loc[agent][0]+1, state.loc[agent][1]) return state else: # print('-fail') return False def step_left(state, agent): # print('try: step left', agent) if state.map[state.loc[agent][0]-1][state.loc[agent][1]] > 0: state.loc[agent] = (state.loc[agent][0]-1, state.loc[agent][1]) return state else: # print('-fail') return False def step_up(state, agent): #print('try: step up', agent) if state.map[state.loc[agent][0]][state.loc[agent][1]-1] > 0: state.loc[agent] = (state.loc[agent][0], state.loc[agent][1]-1) return state else: #print('-fail') return False def step_down(state, agent): # print('try: step down', agent) if state.map[state.loc[agent][0]][state.loc[agent][1]+1] > 0: state.loc[agent] = (state.loc[agent][0], state.loc[agent][1]+1) return state else: # print('-fail') return False #if stag need cooperator ### REALLY neeed to break this into separate actions def capture_stag(state, hunter, target): print('capturing stag', hunter, target) print('ready', state.ready) if target[1] == 'stag' and \ state.loc[hunter] == state.loc[target] and \ hunter in state.ready and \ target not in state.captured: hunters = [hunter] for agent in state.agents: if agent != hunter and hunts(agent, target) and \ state.loc[agent] == state.loc[target] and agent in state.ready: hunters.append(agent) print('hunters', hunters) if len(hunters) > 1: print(hunters, 'caught', target, state.loc[target]) state.captured.append(target) del state.loc[target] score = int(6 / len(hunters)) for h in hunters: state.score[h] += score state.ready.remove(h) return state else: return False else: return False def capture_rabbit(state, hunter, target): if target[1] == 'rabbit' and \ state.loc[hunter] == state.loc[target] and \ hunter in state.ready and \ target not in state.captured: print(hunter, state.loc[hunter], 'caught', target, state.loc[target]) state.captured.append(target) del state.loc[target] state.score[hunter] += 1 state.ready.remove(hunter) return state else: return False def capture_none(state, hunter, target): return state def load_operators(pyhop): pyhop.declare_operators(wait_one, step_right, step_left, step_up, step_down, pick_coop_target, pick_closest_target, capture_stag, capture_rabbit, capture_none)
{"/spacy_agent.py": ["/spacy_parser.py"]}
24,115,774
DyaniDillard/StagHuntResearch
refs/heads/main
/run_sim.py
from socialSim import pyhop from copy import deepcopy import random import pickle import socialSim.models.staghunt_htn import socialSim.print_trace as pt import itertools import logging MENTAL_SIM_LEN = 5 # maps = [0,1,2,3,4,5,6,7,8,9,10] # # maps[0] = [[0, 0, 0, 0, 0, 0, 0], # [0, 1, 1, 1, 1, 1, 0], # [0, 1, 0, 0, 0, 1, 0], # [0, 1, 0, 1, 0, 1, 0], # [0, 1, 0, 1, 0, 1, 0], # [0, 1, 1, 1, 1, 1, 0], # [0, 0, 0, 0, 0, 0, 0]] # # # scenario from yoshida? paper # maps[1] = [[0, 0, 0, 0, 0, 0, 0], # [0, 0, 0, 1, 0, 0, 0], # [0, 1, 1, 1, 1, 1, 0], # [0, 1, 0, 1, 0, 1, 0], # [0, 1, 1, 1, 1, 1, 0], # [0, 1, 0, 1, 0, 1, 0], # [0, 1, 1, 1, 1, 1, 0], # [0, 0, 0, 1, 0, 0, 0], # [0, 0, 0, 0, 0, 0, 0]] # # # scenario a from paper # maps[2] = [[0, 0, 0, 0, 0, 0, 0], # [0, 0, 0, 1, 0, 0, 0], # [0, 1, 1, 1, 1, 1, 0], # [0, 1, 0, 1, 0, 1, 0], # [0, 1, 1, 1, 0, 1, 0], # [0, 1, 0, 0, 0, 0, 0], # [0, 1, 1, 1, 1, 1, 0], # [0, 0, 0, 1, 0, 0, 0], # [0, 0, 0, 0, 0, 0, 0]] # # # secnario g from paper # maps[3] = [[0, 0, 0, 0, 0, 0, 0], # [0, 0, 0, 1, 0, 0, 0], # [0, 1, 1, 1, 1, 1, 0], # [0, 1, 0, 1, 1, 1, 0], # [0, 1, 0, 1, 1, 1, 0], # [0, 1, 0, 1, 1, 1, 0], # [0, 1, 1, 1, 1, 1, 0], # [0, 0, 0, 1, 0, 0, 0], # [0, 0, 0, 0, 0, 0, 0]] # # # secnario f from paper # maps[4] = [[0, 0, 0, 0, 0, 0, 0], # [0, 0, 0, 1, 0, 1, 0], # [0, 1, 1, 1, 0, 1, 0], # [0, 1, 0, 1, 0, 1, 0], # [0, 1, 1, 1, 1, 1, 0], # [0, 1, 0, 0, 0, 1, 0], # [0, 1, 1, 1, 1, 1, 0], # [0, 0, 0, 1, 0, 0, 0], # [0, 0, 0, 0, 0, 0, 0]] # # maps[5] = [[0, 0, 0, 0, 0, 0, 0, 0, 0], # [0, 0, 0, 0, 1, 0, 0, 0, 0], # [0, 0, 1, 1, 1, 1, 1, 0, 0], # [0, 0, 1, 0, 0, 0, 1, 0, 0], # [0, 1, 1, 0, 1, 0, 1, 1, 0], # [0, 0, 1, 0, 1, 0, 1, 0, 0], # [0, 0, 1, 1, 1, 1, 1, 0, 0], # [0, 0, 0, 0, 1, 0, 0, 0, 0], # [0, 0, 0, 0, 0, 0, 0, 0, 0]] # # # 27 walls # maps[6] = [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], # [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], # [0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0], # [0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0], # [0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0], # [0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 0], # [0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0], # [0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0], # [0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0], # [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], # [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]] # # # # 0 walls # maps[8] = [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], # [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], # [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], # [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], # [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], # [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], # [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], # [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], # [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], # [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], # [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]] # # # # 33 walls # maps[9] = [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], # [0, 1, 1, 1, 0, 1, 1, 0, 0, 1, 0], # [0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0], # [0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0], # [0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0], # [0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0], # [0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0], # [0, 1, 0, 0, 1, 0, 1, 1, 1, 0, 0], # [0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0], # [0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0], # [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]] ### # 3 walls map5x5x1 = [[0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 1, 0], [0, 1, 0, 1, 1, 1, 0], [0, 1, 1, 1, 0, 1, 0], [0, 1, 0, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0]] # 8 walls map5x5x3 = [[0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 1, 0], [0, 1, 0, 0, 0, 1, 0], [0, 1, 0, 0, 1, 1, 0], [0, 1, 1, 1, 1, 0, 0], [0, 0, 0, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0]] # 13 walls map5x5x5 = [[0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 1, 1, 0, 0], [0, 0, 1, 0, 1, 0, 0], [0, 1, 1, 1, 1, 0, 0], [0, 0, 0, 0, 1, 1, 0], [0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0]] # 5 walls map7x7x1 = [[0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 0, 1, 0, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 0, 1, 0, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 0, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]] # 15 walls map7x7x3 = [[0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 1, 0, 1, 0], [0, 1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 0, 0, 0, 0, 1, 0], [0, 1, 0, 0, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 0, 0], [0, 1, 0, 1, 1, 1, 1, 1, 0], [0, 1, 0, 1, 0, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]] # 25 walls map7x7x5 = [[0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 1, 0], [0, 1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 0, 0, 0, 0, 0, 1, 0], [0, 1, 0, 0, 0, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 0, 0, 0], [0, 0, 0, 1, 0, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]] # 8 walls map9x9x1 = [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]] # 24 walls map9x9x3 = [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0], [0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0], [0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0], [0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0], [0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0], [0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]] # 40 walls map9x9x5 = [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0], [0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0], [0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0], [0, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]] maps = [[map5x5x1, map5x5x3, map5x5x5], [map7x7x1, map7x7x3, map7x7x5], [map9x9x1, map9x9x3, map9x9x5]] # conditions # map size # map density # stag quantity # def get_start_state_rand(condition): # state = models.staghunt_htn.get_start_state() # pickMap(state, condition) # setupAgents(state, condition) # pickRandomGoals(state) # return state # def pickRandomGoals(state): # c = random.randint(0, 4) # assignGoals(state, c) # def assignGoals(state, c): # state.goal = {} # if c == 0: # return # elif c == 1: # state.goal[('h1', 'hunter')] = {'cooperateWith': (('h1', 'hunter'), ('h2', 'hunter'))} # state.goal[('h2', 'hunter')] = {'cooperateWith': (('h2', 'hunter'), ('h1', 'hunter'))} # elif c == 2: # state.goal[('h1', 'hunter')] = {'cooperateWith': (('h1', 'hunter'), ('h3', 'hunter'))} # state.goal[('h3', 'hunter')] = {'cooperateWith': (('h3', 'hunter'), ('h1', 'hunter'))} # elif c == 3: # state.goal[('h3', 'hunter')] = {'cooperateWith': (('h3', 'hunter'), ('h2', 'hunter'))} # state.goal[('h2', 'hunter')] = {'cooperateWith': (('h2', 'hunter'), ('h3', 'hunter'))} # else: # # 1 working with 2 who is working with 3 # # iow, they are all working together # state.goal[('h1', 'hunter')] = {'cooperateWith': (('h1', 'hunter'), ('h2', 'hunter'))} # state.goal[('h2', 'hunter')] = {'cooperateWith': (('h2', 'hunter'), ('h3', 'hunter'))} # state.goal[('h3', 'hunter')] = {'cooperateWith': (('h3', 'hunter'), ('h1', 'hunter'))} def my_assignRandomGoals(state, c=None): hunters = [] for agent in state.agents: if agent[1] == 'hunter': hunters.append(agent) poss_goals = [] # find all possible combinations of hunters of all possible lengths >= 2 for length in range(2, len(hunters) + 1): for combo in itertools.combinations(hunters, length): goal = {} # if mult hunters coop, each hunter coop with the next, the last hunter cooperates with the first for i in range(len(combo)): if i == len(combo) - 1: goal[combo[i]] = {'cooperateWith': (combo[i], combo[0])} else: goal[combo[i]] = {'cooperateWith': (combo[i], combo[i + 1])} poss_goals.append(goal) if not c: c = random.randint(0, len(poss_goals)) if c == len(poss_goals): # no cooperation return len(poss_goals) for hunter in poss_goals[c]: state.goal[hunter] = poss_goals[c][hunter] return len(poss_goals) # assigns coop goal with specific hunter def my_assignGoals(state, agent, hunter): logger = logging.getLogger('StagHuntAgent') if agent not in state.agents or hunter not in state.agents: raise ValueError logger.debug("cooperation between " + agent[0] + ' ' + hunter[0]) state.goal[agent] = {'cooperateWith': (agent, hunter)} # assumes only coop with one at a time for now logger.debug("finished\n\n") # def pickMap(state, condition): # # c = random.randint(0, 4) # # state.map = maps[c] # state.map = maps[condition[0]][condition[1]] # returns a random map def my_rand_pickMap(state): i = random.randint(0, 2) j = random.randint(0, 2) state.map = maps[i][j] # def setupAgents(state, condition): # state.agents = [('r1', 'rabbit'), ('r2', 'rabbit')] # for i in range(0, condition[2] + 1): # state.agents.append((f's{i + 1}', 'stag')) # state.agents.extend([('h1', 'hunter'), ('h2', 'hunter'), ('h3', 'hunter')]) # # state.loc = {} # for agent in state.agents: # print(agent) # done = False # while not done: # x = random.randint(0, len(state.map) - 1) # y = random.randint(0, len(state.map[0]) - 1) # print(x, y) # if state.map[x][y] > 0: # done = True # for other in state.loc: # if state.loc[other] == (x, y): # done = False # break # if done: # state.loc[agent] = (x, y) # assigns number of each agent to state according to amounts in agents def my_setupAgents(state, agents): if agents[0] < 1 or agents[1] < 1 or agents[2] < 1: raise ValueError state.agents.clear() for i in range(0, agents[0]): state.agents.append((f'r{i + 1}', 'rabbit')) for i in range(0, agents[1]): state.agents.append((f's{i + 1}', 'stag')) for i in range(0, agents[2]): state.agents.append((f'h{i + 1}', 'hunter')) # place all agents in random locations state.loc = {} for agent in state.agents: print(agent) done = False while not done: x = random.randint(0, len(state.map) - 1) y = random.randint(0, len(state.map[0]) - 1) print(x, y) if state.map[x][y] > 0: done = True for other in state.loc: if state.loc[other] == (x, y): done = False break if done: state.loc[agent] = (x, y) # runs all possible maps (3x3 dis sizes and densities) in 30 different conditions # def run_all(): # all_sims = [[[None for i in range(3)] for j in range(3)] for k in range(3)] # for i in range(0, 3): # map size # for j in range(0, 3): # map density # for k in range(0, 3): # runs_for_cond = [] # for c in range(0, 30): # states_plans = run_one((i, j, k)) # runs_for_cond.append(states_plans) # all_sims[i][j][k] = runs_for_cond # pickle.dump(all_sims, open('all.pickle', 'wb')) # agents = (num rabbits, num stags, num hunters) # runs n number of simulations on random maps, loc, goals, and constant num agents def my_run_sim(agents, n): logger = logging.getLogger('StagHuntAgent') for i in range(n): print("\n****** NEW GAME ******\n") state = socialSim.models.staghunt_htn.get_start_state() my_rand_pickMap(state) my_setupAgents(state, agents) num_poss_goals = my_assignRandomGoals(state) logger.debug("simulating state") simulate_state(state, 3, my_decide, num_poss_goals) logger.debug("finished\n\n") def my_make_game(agents): print("\n****** NEW GAME ******\n") state = socialSim.models.staghunt_htn.get_start_state() my_rand_pickMap(state) my_setupAgents(state, agents) return state def my_run_one(state): logger = logging.getLogger('StagHuntAgent') logger.debug("simulating state") my_assignRandomGoals(state) # in future, states, plans = simulate_state(state, 1) return states[1] # next state # def decide(state): # # sim each set of goals # sims = [] # for c in range(5): # print('goal set', c) # sims.append(deepcopy(state)) # # reset scores for each mental sim # for agent in sims[c].score: # sims[c].score[agent] = 0 # assignGoals(sims[c], c) # print('**** goals ****', sims[c].goal) # states, _ = simulate_state(sims[c], MENTAL_SIM_LEN) # sims[c] = states # print('**** scores ****', sims[c][-1].score) # # reset goals # state.goal = {} # # for each agent, pick best result # for agent in state.agents: # if agent[1] == 'hunter': # s = argmax(range(4), lambda x: sims[x][-1].score[agent]) # print('argmax', s, agent) # print('-sims score', sims[s][-1].score) # print('-sims goal', sims[s][0].goal) # if agent in sims[s][0].goal: # print('--assigning goal', sims[s][0].goal[agent]) # state.goal[agent] = sims[s][0].goal[agent] # state.assumes[agent] = sims[s][0].goal def my_decide(state, num_poss_goals): # sim each set of goals sims = [] for c in range(num_poss_goals): print('goal set', c) sims.append(deepcopy(state)) # reset scores for each mental sim for agent in sims[c].score: sims[c].score[agent] = 0 my_assignRandomGoals(sims[c], c) print('**** goals ****', sims[c].goal) states, _ = simulate_state(sims[c], MENTAL_SIM_LEN) # simulate each goal with 5 steps each? sims[c] = states print('**** scores ****', sims[c][-1].score) # reset goals state.goal = {} # for each agent, pick best result for agent in state.agents: if agent[1] == 'hunter': # what is 4? s = argmax(range(4), lambda x: sims[x][-1].score[agent]) # score of this agent at this state? print('argmax', s, agent) print('-sims score', sims[s][-1].score) print('-sims goal', sims[s][0].goal) if agent in sims[s][0].goal: print('--assigning goal', sims[s][0].goal[agent]) state.goal[agent] = sims[s][0].goal[agent] state.assumes[agent] = sims[s][0].goal def argmax(args, fn): max_val = -1000000 max_arg = None for arg in args: val = fn(arg) if val > max_val: max_val = val max_arg = arg return max_arg # def run_one(condition): # state = get_start_state_rand(condition) # return simulate_state(state, 3, decide) def simulate_state(state, sim_steps, goal_manager=None, num_poss_goals=None): planner = pyhop.Pyhop('hippity-hop') socialSim.models.staghunt_htn.load_operators(planner) socialSim.models.staghunt_htn.load_methods(planner) states = [state] plans = [] pt.print_map(state.map, state.loc) for i in range(0, sim_steps): # decisions, decisions. to decide or not to decide if goal_manager: goal_manager(state, num_poss_goals) # side-effects goals print('* goals *', state.goal) plan = planner.pyhop(state, [('sim_all',)], verbose=0) plans.append(plan) pt.print_plan(plan) state = deepcopy(state) for action in plan: fn = planner.operators[action[0][0]] fn(state, *action[0][1:]) pt.print_map(state.map, state.loc) states.append(state) return states, plans if __name__ == '__main__': # run_all() # agents = (2, 1, 3) # rabbits, stags, hunters # n = 3 # my_run_sim(agents, n) agents = (2, 2, 3) state = my_make_game(agents) state2 = my_run_one(state) my_run_one(state2)
{"/spacy_agent.py": ["/spacy_parser.py"]}
24,173,836
schafezp/karmabot
refs/heads/master
/karmabot/commands_strings.py
"""Holds string literals for commands """ START_COMMAND = "start" CLEAR_CHAT_COMMAND = "clearchatwithbot" SHOW_KARMA_COMMAND = 'showkarma'
{"/karmabot/handlers.py": ["/karmabot/annotations.py", "/karmabot/telegramservice.py", "/karmabot/formatters.py", "/karmabot/models.py", "/karmabot/responses.py", "/karmabot/commands_strings.py"], "/karmabot/postgres_funcs.py": ["/karmabot/models.py"], "/karmabot/setup_db_rows.py": ["/karmabot/customutils.py"], "/karmabot/telegramservice.py": ["/karmabot/models.py"], "/karmabot/formatters.py": ["/karmabot/responses.py"], "/test/integration_tests.py": ["/karmabot/responses.py", "/karmabot/commands_strings.py"], "/karmabot/bot.py": ["/karmabot/customutils.py", "/karmabot/commands_strings.py", "/karmabot/handlers.py", "/karmabot/telegramservice.py"]}
24,173,837
schafezp/karmabot
refs/heads/master
/karmabot/bot.py
"""Main entry point for telegram bot.""" import logging import os import sys import re from typing import Tuple, List from functools import wraps from telegram.ext import Filters, CommandHandler, MessageHandler, Updater, CallbackQueryHandler import telegram as tg import matplotlib.pyplot as plt from matplotlib.ticker import MaxNLocator from models import User, Telegram_Chat, Telegram_Message, user_from_tg_user import postgres_funcs as pf from customutils import attempt_connect, check_env_vars_all_loaded from responses import START_BOT_RESPONSE, SUCCESSFUL_CLEAR_CHAT, FAILED_CLEAR_CHAT_DUE_TO_GROUPCHAT, SHOW_KARMA_NO_HISTORY_RESPONSE from commands_strings import START_COMMAND, CLEAR_CHAT_COMMAND, SHOW_KARMA_COMMAND LOG_LEVEL_ENV_VAR = os.environ.get('LOG_LEVEL') LOG_LEVEL = None if LOG_LEVEL_ENV_VAR == "debug": LOG_LEVEL = logging.DEBUG elif LOG_LEVEL_ENV_VAR == "info": LOG_LEVEL = logging.INFO else: LOG_LEVEL = logging.INFO logging.basicConfig( format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=LOG_LEVEL) LOGGER = logging.getLogger(__name__) VERSION = '1.04' # TODO: make this automatic CHANGELOG_URL = 'https://schafezp.com/schafezp/txkarmabot/blob/master/CHANGELOG.md' LIST_OF_ADMINS = [65278791] def restricted(func): """Function wrap to deny access to a user based on user_id""" @wraps(func) def wrapped(bot, update, *args, **kwargs): """function to wrap""" user_id = update.effective_user.id if user_id not in LIST_OF_ADMINS: print("Unauthorized access denied for {}.".format(user_id)) return func(bot, update, *args, **kwargs) return wrapped def types(func): """Used by bot handlers that respond with text. ChatAction.Typing is called which makes the bot look like it's typing""" @wraps(func) def wrapped(bot, update, *args, **kwargs): """function to wrap""" bot.send_chat_action( chat_id=update.message.chat_id, action=tg.ChatAction.TYPING) return func(bot, update, *args, **kwargs) return wrapped #TODO: move this down into the main function #this stops us from importing directly from this function: bad practice #blocks here conn = attempt_connect() def reply(bot: tg.Bot, update: tg.Update): """Handler that's run when one user replies to another userself. This handler checks if an upvote or downvote are given""" reply_user = user_from_tg_user(update.message.reply_to_message.from_user) replying_user = user_from_tg_user(update.message.from_user) chat_id = str(update.message.chat_id) chat = Telegram_Chat(chat_id, update.message.chat.title) original_message = Telegram_Message( update.message.reply_to_message.message_id, chat.chat_id, reply_user.id, update.message.reply_to_message.text) reply_message = Telegram_Message( update.message.message_id, chat.chat_id, replying_user.id, update.message.text) reply_text = reply_message.message_text if re.match("^([\+pP][1-9][0-9]*|[Pp]{2}).*", reply_text): # if user tried to +1 self themselves # chat id is user_id when the user is talking 1 on 1 with the bot if(replying_user.id == update.message.reply_to_message.from_user.id and chat_id != str(reply_user.id)): default_respose = "USER_FIRST_NAME you cannot +1 yourself" response = pf.get_random_witty_response(conn) if response is None: response = default_respose message = response.replace("USER_FIRST_NAME", replying_user.first_name) bot.send_message(chat_id=chat_id, text=message) else: # user +1 someone else pf.user_reply_to_message( replying_user, reply_user, chat, original_message, reply_message, 1, conn) logging.debug("user replying other user") logging.debug(replying_user) logging.debug(reply_user) # user -1 someone else elif re.match("^([\-mM][1-9][0-9]*|[Dd]{2}).*", reply_text): pf.user_reply_to_message(replying_user, reply_user, chat, original_message, reply_message, -1, conn) logging.debug("user replying other user") logging.debug(replying_user) logging.debug(reply_user) def start(bot, update): """Message sent by bot upon first 1 on 1 interaction with the bot""" bot.send_message( chat_id=update.message.chat_id, text=START_BOT_RESPONSE) @types def show_version(bot, update, args): """Handler to show the current version""" message = f"Version: {VERSION}\nBot powered by Python." # harder to hack the bot if source code is obfuscated :p #message = message + "\nChangelog found at: " + changelog_url bot.send_message(chat_id=update.message.chat_id, text=message) @types def show_user_stats(bot, update, args): """Handler to return statistics on user""" # TODO: remove this boiler plate code somehow # without this if this is the first command run alone with the bot it will # fail due to psycopg2.IntegrityError: insert or update on table # "command_used" violates foreign key constraint # "command_used_chat_id_fkey" chat = Telegram_Chat(str(update.message.chat_id), update.message.chat.title) pf.save_or_create_chat(chat, conn) chat_id = str(update.message.chat_id) if len(args) != 1: bot.send_message( chat_id=update.message.chat_id, text="use command like: /userinfo username") return username = args[0] if username[0] == "@": username = username[1:] use_command( 'userinfo', user_from_tg_user( update.message.from_user), str( update.message.chat_id), arguments=username) message = None try: result = pf.get_user_stats(username, chat_id, conn) message = """<b>Username:</b> {:s} Karma: {:d} Karma given out stats: Upvotes, Downvotes, Total Votes, Net Karma {:d}, {:d}, {:d}, {:d}""" message = message.format( result['username'], result['karma'], result['upvotes_given'], result['downvotes_given'], result['total_votes_given'], result['net_karma_given']) except pf.UserNotFound as _: message = f"No user with username: {username}" bot.send_message(chat_id=update.message.chat_id, text=message, parse_mode=tg.ParseMode.HTML) def show_history_graph(bot: tg.Bot, update: tg.Update): """Handler to show a graph of upvotes/downvotes per day""" chat_id = str(update.message.chat_id) chat_name = pf.get_chatname(chat_id, conn) if chat_name is None: chat_name = "Chat With Bot" result = pf.get_responses_per_day(chat_id, conn) if result is None: bot.send_message(chat_id=update.message.chat_id, text="No responses for this chat") return bot.send_chat_action( chat_id=update.message.chat_id, action=tg.ChatAction.UPLOAD_PHOTO) days, responses = zip(*result) figure_name = f'/output/graph_{chat_id}.png' fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.plot(days, responses) ax.set_ylabel('Upvotes and Downvotes') ax.set_xlabel('Day') ax.yaxis.set_major_locator(MaxNLocator(integer=True)) ax.set_title(f'{chat_name}: User votes per day') fig.autofmt_xdate() fig.savefig(figure_name) bot.send_photo(chat_id=update.message.chat_id, photo=open(figure_name, 'rb')) # TODO: replace this with an annotation maybe? def use_command(command: str, user: User, chat_id: str, arguments=""): """Handler to log when commands are used and with which arguments""" pf.create_chat_if_not_exists(chat_id, conn) pf.save_or_create_user(user, conn) insertcmd = """INSERT INTO command_used (command,arguments,user_id,chat_id) VALUES (%s,%s,%s,%s)""" with conn: with conn.cursor() as crs: crs.execute(insertcmd, [command, arguments, user.id, chat_id]) def format_show_karma_for_users_in_chat(chat_id): """Returns a formatted html message showing the karma for users in a chat""" rows: List[Tuple[str, str, int]] = pf.get_karma_for_users_in_chat( chat_id, conn) if rows == []: return SHOW_KARMA_NO_HISTORY_RESPONSE rows.sort(key=lambda user: user[2], reverse=True) # use firstname if username not set def cleanrow(user): """selects desired user attributes to show""" if user[0] is None: return (user[1], user[2]) else: return (user[0], user[2]) message_rows = [] idx = 0 for user in map(cleanrow, rows): row = f"{user[0]}: {user[1]}" if idx == 0: row = '🥇' + row elif idx == 1: row = '🥈' + row elif idx == 2: row = '🥉' + row idx = idx + 1 message_rows.append(row) message = "\n".join(message_rows) message = "<b>Username: Karma</b>\n" + message return message @types def show_karma(bot, update, args): """Handler show the karma in the chat""" use_command( 'showkarma', user_from_tg_user( update.message.from_user), str( update.message.chat_id)) logging.debug(f"Chat id: {str(update.message.chat_id)}") # returns username, first_name, karma chat_id = str(update.message.chat_id) message = format_show_karma_for_users_in_chat(chat_id) bot.send_message(chat_id=update.message.chat_id, text=message, parse_mode=tg.ParseMode.HTML) @types def show_chat_info(bot, update, args): """Handler to show information about current chat """ use_command( 'chatinfo', user_from_tg_user( update.message.from_user), str( update.message.chat_id)) chat_id = str(update.message.chat_id) title = update.message.chat.title if title is None: title = "No Title" result = pf.get_chat_info(chat_id, conn) message = "<b>Chat Name:</b> {:s}\n Number of Users with Karma: {:d}\n Total Reply Count: {:d}".format( title, result['user_with_karma_count'], result['reply_count']) bot.send_message(chat_id=update.message.chat_id, text=message, parse_mode=tg.ParseMode.HTML) @restricted def am_i_admin(bot, update, args): """Handler to check if user is an admin""" message = "yes you are an admin" bot.send_message(chat_id=update.message.chat_id, text=message) @types def show_karma_personally(bot, update: tg.Update): """Conversation handler to allow users to check karma values through custom keyboard""" user_id = update.effective_user.id user: User = user_from_tg_user(update.effective_user) chat_id: str = str(update.message.chat_id) result = pf.get_chats_user_is_in(user_id, conn) use_command('checkchatkarmas', user, chat_id) keyboard = [] if result is not None: for (chat_id, chat_name) in result: if chat_name is not None: logging.info(f"Chat name:{chat_name}") keyboard.append([tg.InlineKeyboardButton(chat_name, callback_data=chat_id)]) reply_markup = tg.InlineKeyboardMarkup(keyboard) update.message.reply_text('Please choose a chat:', reply_markup=reply_markup) else: update.message.reply_text("""No chats available. You can only see chats you have given or received karma in.""") #TODO: rename def show_karma_personally_button_pressed(bot, update): """Runs /showkarma on chat the user_selected""" query = update.callback_query chat_id: str = str(query.data) message = format_show_karma_for_users_in_chat(chat_id) chat_name = pf.get_chatname(chat_id, conn) if chat_name is not None: message = f"<b>Chat name: {chat_name}</b>\n{message}" bot.edit_message_text(text=message, chat_id=query.message.chat_id, message_id=query.message.message_id, parse_mode=tg.ParseMode.HTML) def clear_chat_with_bot(bot, update): """Clears chat with bot""" chat_id = update.message.chat_id user_id = update.message.from_user.id if user_id != chat_id: bot.send_message(chat_id=update.message.chat_id, text=FAILED_CLEAR_CHAT_DUE_TO_GROUPCHAT) return bot.send_message(chat_id=update.message.chat_id, text=SUCCESSFUL_CLEAR_CHAT) pf.clear_chat_with_bot(chat_id, user_id, conn) def error(bot, update, _error): """Log Errors caused by Updates.""" logging.warning('Update "%s" caused error "%s"', update, _error) def main(): """Start the bot """ required_env_vars = ['BOT_TOKEN', 'LOG_LEVEL', 'POSTGRES_USER', 'POSTGRES_PASS', 'POSTGRES_DB',] (is_loaded, var) = check_env_vars_all_loaded(required_env_vars) if not is_loaded: logging.info(f"Env vars not set that are required: {str(var)}") sys.exit(1) # Setup bot token from environment variables bot_token = os.environ.get('BOT_TOKEN') updater = Updater(token=bot_token) dispatcher = updater.dispatcher start_handler = CommandHandler(START_COMMAND, start) dispatcher.add_handler(start_handler) reply_handler = MessageHandler(Filters.reply, reply) dispatcher.add_handler(reply_handler) showkarma_handler = CommandHandler(SHOW_KARMA_COMMAND, show_karma, pass_args=True) dispatcher.add_handler(showkarma_handler) show_user_handler = CommandHandler( 'userinfo', show_user_stats, pass_args=True) dispatcher.add_handler(show_user_handler) chat_info_handler = CommandHandler( 'chatinfo', show_chat_info, pass_args=True) dispatcher.add_handler(chat_info_handler) am_i_admin_handler = CommandHandler('amiadmin', am_i_admin, pass_args=True) dispatcher.add_handler(am_i_admin_handler) showversion_handler = CommandHandler( 'version', show_version, pass_args=True) dispatcher.add_handler(showversion_handler) show_karma_personally_handler = CommandHandler( 'checkchatkarmas', show_karma_personally) dispatcher.add_handler(show_karma_personally_handler) dispatcher.add_handler(CallbackQueryHandler(show_karma_personally_button_pressed)) show_history_graph_handler = CommandHandler( 'historygraph', show_history_graph) dispatcher.add_handler(show_history_graph_handler) #used for integration testing #should only work to clear a chat with a bot #chat_id == user_id clear_chat_with_bot_handler = CommandHandler( CLEAR_CHAT_COMMAND, clear_chat_with_bot) dispatcher.add_handler(clear_chat_with_bot_handler) dispatcher.add_error_handler(error) updater.start_polling() cursor = conn.cursor() cursor.execute("SELECT * FROM pg_catalog.pg_tables;") many = cursor.fetchall() public_tables = list( map(lambda x: x[1], filter(lambda x: x[0] == 'public', many))) logging.info(f"public_tables: {str(public_tables)}") updater.idle() cursor.close() conn.close() if __name__ == '__main__': main()
{"/karmabot/handlers.py": ["/karmabot/annotations.py", "/karmabot/telegramservice.py", "/karmabot/formatters.py", "/karmabot/models.py", "/karmabot/responses.py", "/karmabot/commands_strings.py"], "/karmabot/postgres_funcs.py": ["/karmabot/models.py"], "/karmabot/setup_db_rows.py": ["/karmabot/customutils.py"], "/karmabot/telegramservice.py": ["/karmabot/models.py"], "/karmabot/formatters.py": ["/karmabot/responses.py"], "/test/integration_tests.py": ["/karmabot/responses.py", "/karmabot/commands_strings.py"], "/karmabot/bot.py": ["/karmabot/customutils.py", "/karmabot/commands_strings.py", "/karmabot/handlers.py", "/karmabot/telegramservice.py"]}
24,173,838
schafezp/karmabot
refs/heads/master
/karmabot/responses.py
"""Central place for bot response text strings Used to simplify process of changing text responses, and to make tests better """ START_BOT_RESPONSE = "I'm a bot, please talk to me!" SUCCESSFUL_CLEAR_CHAT = "Clearing chat history" FAILED_CLEAR_CHAT_DUE_TO_GROUPCHAT = "This is a group chat. Don't delete me!" SHOW_KARMA_NO_HISTORY_RESPONSE = "No karma for users in this chat"
{"/karmabot/handlers.py": ["/karmabot/annotations.py", "/karmabot/telegramservice.py", "/karmabot/formatters.py", "/karmabot/models.py", "/karmabot/responses.py", "/karmabot/commands_strings.py"], "/karmabot/postgres_funcs.py": ["/karmabot/models.py"], "/karmabot/setup_db_rows.py": ["/karmabot/customutils.py"], "/karmabot/telegramservice.py": ["/karmabot/models.py"], "/karmabot/formatters.py": ["/karmabot/responses.py"], "/test/integration_tests.py": ["/karmabot/responses.py", "/karmabot/commands_strings.py"], "/karmabot/bot.py": ["/karmabot/customutils.py", "/karmabot/commands_strings.py", "/karmabot/handlers.py", "/karmabot/telegramservice.py"]}
24,264,240
ridhoq/soundslike
refs/heads/master
/manage.py
#!/usr/bin/env python import os import sys from app import create_app, db from flask.ext.script import Manager, Command, Option from flask.ext.migrate import Migrate, MigrateCommand class GunicornCommand(Command): """Run the app within Gunicorn""" def get_options(self): from gunicorn.config import make_settings settings = make_settings() options = ( Option(*klass.cli, action=klass.action) for setting, klass in settings.items() if klass.cli ) return options def run(self, *args, **kwargs): run_args = sys.argv[2:] run_args.append('manage:app') os.execvp('gunicorn', [''] + run_args) app = create_app(os.getenv('FLASK_CONFIG') or 'default') manager = Manager(app) migrate = Migrate(app, db) manager.add_command('db', MigrateCommand) manager.add_command('gunicorn', GunicornCommand) if __name__ == '__main__': manager.run()
{"/conftest.py": ["/server/__init__.py"], "/server/api/users.py": ["/server/models.py", "/server/__init__.py", "/server/api/errors.py"], "/test/server/test_songs.py": ["/server/models.py"], "/test/server/test_song_relations.py": ["/server/models.py"], "/manage.py": ["/server/__init__.py"], "/server/api/songs.py": ["/server/__init__.py", "/server/models.py", "/server/api/errors.py"], "/server/models.py": ["/server/__init__.py"], "/test/server/test_authentication.py": ["/server/models.py"], "/server/api/song_relations.py": ["/server/models.py", "/server/__init__.py", "/server/api/errors.py"]}
24,299,833
sultanmirzapydev/ecommerce
refs/heads/main
/products/views.py
from django.views.generic import ListView, DetailView from django.shortcuts import render, get_object_or_404 from django.http import Http404 from .models import Product class ProductListView(ListView): queryset = Product.objects.all() template_name = 'products/list.html' #def get_context_data(self, *args, **kwargs): # context = super(ProductListView, self).get_context_data(*args, **kwargs) # print(context) # return context def Product_list_view(request): queryset = Product.objects.all() context = { 'object_list': queryset } return render(request, 'products/list.html', context) class ProductDetailView(DetailView): queryset = Product.objects.all() template_name = 'products/detail.html' def get_context_data(self, *args, **kwargs): context = super(ProductDetailView, self).get_context_data(*args, **kwargs) print(context) #context['abc'] = 123 return context def get_object(self, *args, **kwargs): request = self.request pk = self.kwargs.get('pk') instance = Product.objects.get_by_id(pk) if instance is None: raise Http404('product does not exist') return instance def Product_detail_view(request, pk): #instance = Product.objects.get(pk=pk) #instance = get_object_or_404(Product, pk=pk) instance = Product.objects.get_by_id(pk) if instance is None: raise Http404('product does not exist') #qs = Product.objects.filter(id=pk) #print(qs) #if qs.exists() and qs.count() == 1: # instance = qs.first() #else: # raise Http404('Product does not exist') context = { 'object': instance } return render(request, 'products/detail.html', context)
{"/products/views.py": ["/products/models.py"]}
24,299,834
sultanmirzapydev/ecommerce
refs/heads/main
/products/models.py
from django.db import models import os import random def get_filename_ext(filepath): #print(filepath) name, ext = os.path.splitext(filepath) return name, ext def upload_image_path(instance, filename): #print(instance) #print(filename) new_filename = random.randint(1,4000000000) name, ext = get_filename_ext(filename) final_filename = '{new_filename}{ext}'.format(new_filename=new_filename, ext=ext) return "products/{new_filename}/{final_filename}".format(new_filename=new_filename, final_filename=final_filename) class ProductManager(models.Manager): def get_by_id(self,id): qs = self.get_queryset().filter(id=id) if qs.count() == 1: return qs.first() return None class Product(models.Model): title = models.CharField(max_length=120) description = models.TextField() price = models.DecimalField(decimal_places=2, max_digits=10, default=39.99) image = models.ImageField(upload_to=upload_image_path, null=True, blank=True) objects = ProductManager() def __str__(self): return self.title
{"/products/views.py": ["/products/models.py"]}
24,302,872
mtlmacedo/HMS_IFBA
refs/heads/master
/HotelIFBA/admin.py
from django.contrib import admin from HotelIFBA.models import Empresa, Cliente, Colaborador, Reserva, Estadia class Empresas(admin.ModelAdmin): list_display = ('nomeEmpresa', 'cnpj') list_display_links = ('cnpj', 'nomeEmpresa') search_fields = ('nomeEmpresa',) class Clientes(admin.ModelAdmin): list_display = ('id', 'nomeCliente', 'dtNascimento') list_display_links = ('id', 'nomeCliente') class Colaboradores(admin.ModelAdmin): list_display = ('id', 'nomeCompleto', 'rg') list_display_links = ('id', 'nomeCompleto') class Reservas(admin.ModelAdmin): list_display = ('id', 'dataEntrada', 'dataSaida', 'tipoQuarto', 'qtdPessoas') list_display_links = ('id', 'dataEntrada') class Estadias(admin.ModelAdmin): list_display = ('id', 'cliente', 'quarto', 'dataEntrada', 'dataSaida', 'dadosPagamento') list_display_links = ('id', 'cliente') admin.site.register(Empresa, Empresas) admin.site.register(Cliente, Clientes) admin.site.register(Colaborador, Colaboradores) admin.site.register(Reserva, Reservas) admin.site.register(Estadia, Estadias)
{"/hmsifba/serializer.py": ["/hmsifba/models.py"], "/config/urls.py": ["/hmsifba/views.py", "/HotelIFBA/views.py"], "/hmsifba/admin.py": ["/hmsifba/models.py"], "/hmsifba/views.py": ["/hmsifba/models.py", "/hmsifba/serializer.py"], "/HotelIFBA/admin.py": ["/HotelIFBA/models.py"], "/HotelIFBA/estadia_functions/disponibilidade.py": ["/HotelIFBA/models.py"], "/HotelIFBA/views.py": ["/HotelIFBA/models.py", "/HotelIFBA/serializer.py"], "/HotelIFBA/serializer.py": ["/HotelIFBA/models.py"]}
24,302,873
mtlmacedo/HMS_IFBA
refs/heads/master
/HotelIFBA/models.py
from django.db import models from django.conf import settings class Endereco(models.Model): rua = models.CharField(max_length=200, null=False, blank=False) numero = models.IntegerField(null=False, blank=False) complemento = models.CharField(max_length=200, null=False, blank=False) bairro = models.CharField(max_length=50, null=False, blank=False) cidade = models.CharField(max_length=100, null=False, blank=False) pais = models.CharField(max_length=50, null=False, blank=False) def __str__(self): return self.rua class Cliente(models.Model): id = models.AutoField(primary_key=True) nomeCliente = models.CharField(max_length=100) nacionalidade = models.CharField(max_length=100) dtNascimento = models.DateField() endereco = models.ForeignKey(Endereco, blank=True, null=True, default=None, on_delete=models.DO_NOTHING) telefone = models.CharField(max_length=100) idNumero = models.CharField(max_length=100) idData = models.DateField() email = models.EmailField(null=True) senha = models.CharField(max_length=25, null=True) def __str__(self): return self.id class Colaborador(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) nomeCompleto = models.CharField(max_length=100) cpf = models.CharField(max_length=11) rg = models.CharField(max_length=9) ctps = models.CharField(max_length=10) cargo = models.CharField(max_length=100) admissao = models.DateTimeField() jornadaDiaria = models.IntegerField() endereco = models.ForeignKey(Endereco, blank=True, null=True, default=None, on_delete=models.CASCADE) def __str__(self): return self.id class Empresa(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) nomeEmpresa = models.CharField(max_length=100) proprietario = models.CharField(max_length=50) cnpj = models.CharField(max_length=14) endereco = models.ForeignKey(Endereco, blank=True, null=True, default=None, on_delete=models.DO_NOTHING) telefone = models.CharField(max_length=11, null="True") categoria = models.CharField(max_length=100, null="True") email = models.EmailField(null=True) def __str__(self): return self.nomeEmpresa class Reserva(models.Model): id = models.AutoField(primary_key=True) dataEntrada = models.DateTimeField() dataSaida = models.DateTimeField() tipoQuarto = models.CharField(max_length=50) # Suíte Presidencial, Comum qtdPessoas = models.IntegerField(null=True) def __str__(self): return self.id class Estadia(models.Model): id = models.AutoField(primary_key=True) cliente = models.ForeignKey("Cliente", on_delete=models.CASCADE, related_name='cliente', null=True) quarto = models.ForeignKey("Quarto", on_delete=models.CASCADE, related_name='quarto', null=True) dataEntrada = models.DateTimeField() dataSaida = models.DateTimeField() dadosPagamento = models.ForeignKey("DadosPagamento", on_delete=models.CASCADE, related_name='dadosPagamento') def __str__(self): return self.id class DadosPagamento(models.Model): id = models.AutoField(primary_key=True) titular = models.CharField(max_length=50) numeroCartao = models.CharField(max_length=15) agencia = models.CharField(max_length=6) conta = models.CharField(max_length=6) digito = models.IntegerField() chavepix = models.CharField(max_length=50) def __str__ (self): return self.id class Quarto(models.Model): id = models.AutoField(primary_key=True) numeroQuarto = models.IntegerField() andar = models.IntegerField() categoria = models.CharField(max_length=50) interfoneNumero = models.IntegerField() capacidade = models.IntegerField(null=True) def __str__ (self): return self.id
{"/hmsifba/serializer.py": ["/hmsifba/models.py"], "/config/urls.py": ["/hmsifba/views.py", "/HotelIFBA/views.py"], "/hmsifba/admin.py": ["/hmsifba/models.py"], "/hmsifba/views.py": ["/hmsifba/models.py", "/hmsifba/serializer.py"], "/HotelIFBA/admin.py": ["/HotelIFBA/models.py"], "/HotelIFBA/estadia_functions/disponibilidade.py": ["/HotelIFBA/models.py"], "/HotelIFBA/views.py": ["/HotelIFBA/models.py", "/HotelIFBA/serializer.py"], "/HotelIFBA/serializer.py": ["/HotelIFBA/models.py"]}
24,302,874
mtlmacedo/HMS_IFBA
refs/heads/master
/HotelIFBA/migrations/0001_initial.py
# Generated by Django 3.2.4 on 2021-06-18 16:57 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Colaborador', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('nomeCompleto', models.CharField(max_length=100)), ('cpf', models.CharField(max_length=11)), ('rg', models.CharField(max_length=9)), ('ctps', models.CharField(max_length=10)), ('cargo', models.CharField(max_length=100)), ('admissao', models.DateTimeField()), ('jornadaDiaria', models.IntegerField()), ('endereco', models.CharField(max_length=200)), ], ), migrations.CreateModel( name='Empresa', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('nomeEmpresa', models.CharField(max_length=100)), ('proprietario', models.CharField(max_length=50)), ('cnpj', models.CharField(max_length=14)), ], ), migrations.CreateModel( name='Reserva', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('dataEntrada', models.DateTimeField()), ('dataSaida', models.DateTimeField()), ('tipoQuarto', models.CharField(max_length=50)), ], ), ]
{"/hmsifba/serializer.py": ["/hmsifba/models.py"], "/config/urls.py": ["/hmsifba/views.py", "/HotelIFBA/views.py"], "/hmsifba/admin.py": ["/hmsifba/models.py"], "/hmsifba/views.py": ["/hmsifba/models.py", "/hmsifba/serializer.py"], "/HotelIFBA/admin.py": ["/HotelIFBA/models.py"], "/HotelIFBA/estadia_functions/disponibilidade.py": ["/HotelIFBA/models.py"], "/HotelIFBA/views.py": ["/HotelIFBA/models.py", "/HotelIFBA/serializer.py"], "/HotelIFBA/serializer.py": ["/HotelIFBA/models.py"]}
24,302,875
mtlmacedo/HMS_IFBA
refs/heads/master
/config/urls.py
from django.contrib import admin from django.urls import path, include from HotelIFBA.views import EmpresasViewSet, ClienteViewSet, ColaboradorViewSet, ReservaViewSet, EstadiaViewSet from rest_framework import routers router = routers.DefaultRouter() router.register('empresas', EmpresasViewSet) router.register('clientes', ClienteViewSet) router.register('colaboradores', ColaboradorViewSet) router.register('reservas', ReservaViewSet) router.register('estadias', EstadiaViewSet) urlpatterns = [ path('admin/', admin.site.urls), path('', include(router.urls)), ]
{"/hmsifba/serializer.py": ["/hmsifba/models.py"], "/config/urls.py": ["/hmsifba/views.py", "/HotelIFBA/views.py"], "/hmsifba/admin.py": ["/hmsifba/models.py"], "/hmsifba/views.py": ["/hmsifba/models.py", "/hmsifba/serializer.py"], "/HotelIFBA/admin.py": ["/HotelIFBA/models.py"], "/HotelIFBA/estadia_functions/disponibilidade.py": ["/HotelIFBA/models.py"], "/HotelIFBA/views.py": ["/HotelIFBA/models.py", "/HotelIFBA/serializer.py"], "/HotelIFBA/serializer.py": ["/HotelIFBA/models.py"]}
24,302,876
mtlmacedo/HMS_IFBA
refs/heads/master
/HotelIFBA/migrations/0002_auto_20210620_2134.py
# Generated by Django 3.2.4 on 2021-06-21 00:34 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('HotelIFBA', '0001_initial'), ] operations = [ migrations.CreateModel( name='Cliente', fields=[ ('id', models.AutoField(primary_key=True, serialize=False)), ('nomeCliente', models.CharField(max_length=100)), ('nacionalidade', models.CharField(max_length=100)), ('dtNascimento', models.DateField()), ('telefone', models.CharField(max_length=100)), ('idNumero', models.CharField(max_length=100)), ('idData', models.DateField()), ('email', models.EmailField(max_length=254, null=True)), ('senha', models.CharField(max_length=25, null=True)), ], ), migrations.CreateModel( name='DadosPagamento', fields=[ ('id', models.AutoField(primary_key=True, serialize=False)), ('titular', models.CharField(max_length=50)), ('numeroCartao', models.CharField(max_length=15)), ('agencia', models.CharField(max_length=6)), ('conta', models.CharField(max_length=6)), ('digito', models.IntegerField()), ('chavepix', models.CharField(max_length=50)), ], ), migrations.CreateModel( name='Endereco', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('rua', models.CharField(max_length=200)), ('numero', models.IntegerField()), ('complemento', models.CharField(max_length=200)), ('bairro', models.CharField(max_length=50)), ('cidade', models.CharField(max_length=100)), ('pais', models.CharField(max_length=50)), ], ), migrations.CreateModel( name='Quarto', fields=[ ('id', models.AutoField(primary_key=True, serialize=False)), ('numeroQuarto', models.IntegerField()), ('andar', models.IntegerField()), ('categoria', models.CharField(max_length=50)), ('interfoneNumero', models.IntegerField()), ('capacidade', models.IntegerField(null=True)), ], ), migrations.AddField( model_name='colaborador', name='user', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL), ), migrations.AddField( model_name='empresa', name='categoria', field=models.CharField(max_length=100, null='True'), preserve_default='True', ), migrations.AddField( model_name='empresa', name='email', field=models.EmailField(max_length=254, null=True), ), migrations.AddField( model_name='empresa', name='telefone', field=models.CharField(max_length=11, null='True'), preserve_default='True', ), migrations.AddField( model_name='empresa', name='user', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL), ), migrations.AddField( model_name='reserva', name='qtdPessoas', field=models.IntegerField(null=True), ), migrations.AlterField( model_name='colaborador', name='id', field=models.AutoField(primary_key=True, serialize=False), ), migrations.AlterField( model_name='empresa', name='id', field=models.AutoField(primary_key=True, serialize=False), ), migrations.AlterField( model_name='reserva', name='id', field=models.AutoField(primary_key=True, serialize=False), ), migrations.CreateModel( name='Estadia', fields=[ ('id', models.AutoField(primary_key=True, serialize=False)), ('dataEntrada', models.DateTimeField()), ('dataSaida', models.DateTimeField()), ('cliente', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='cliente', to='HotelIFBA.cliente')), ('dadosPagamento', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='dadosPagamento', to='HotelIFBA.dadospagamento')), ('quarto', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='quarto', to='HotelIFBA.quarto')), ], ), migrations.AddField( model_name='cliente', name='endereco', field=models.OneToOneField(null=True, on_delete=django.db.models.deletion.SET_NULL, to='HotelIFBA.endereco'), ), migrations.AddField( model_name='empresa', name='endereco', field=models.OneToOneField(null=True, on_delete=django.db.models.deletion.SET_NULL, to='HotelIFBA.endereco'), ), ]
{"/hmsifba/serializer.py": ["/hmsifba/models.py"], "/config/urls.py": ["/hmsifba/views.py", "/HotelIFBA/views.py"], "/hmsifba/admin.py": ["/hmsifba/models.py"], "/hmsifba/views.py": ["/hmsifba/models.py", "/hmsifba/serializer.py"], "/HotelIFBA/admin.py": ["/HotelIFBA/models.py"], "/HotelIFBA/estadia_functions/disponibilidade.py": ["/HotelIFBA/models.py"], "/HotelIFBA/views.py": ["/HotelIFBA/models.py", "/HotelIFBA/serializer.py"], "/HotelIFBA/serializer.py": ["/HotelIFBA/models.py"]}
24,302,877
mtlmacedo/HMS_IFBA
refs/heads/master
/HotelIFBA/estadia_functions/disponibilidade.py
import datetime from HotelIFBA.models import Quarto, Estadia def checar_disponibilidade(quarto, dataEntrada, dataSaida): quartos_list=[] estadia_list = Estadia.objects.filter(quarto=quarto) for estadia in estadia_list: if estadia.dataEntrada > dataSaida or estadia.dataSaida < dataEntrada: quartos_list.append(True) else: quartos_list.append(False) return all(quartos_list)
{"/hmsifba/serializer.py": ["/hmsifba/models.py"], "/config/urls.py": ["/hmsifba/views.py", "/HotelIFBA/views.py"], "/hmsifba/admin.py": ["/hmsifba/models.py"], "/hmsifba/views.py": ["/hmsifba/models.py", "/hmsifba/serializer.py"], "/HotelIFBA/admin.py": ["/HotelIFBA/models.py"], "/HotelIFBA/estadia_functions/disponibilidade.py": ["/HotelIFBA/models.py"], "/HotelIFBA/views.py": ["/HotelIFBA/models.py", "/HotelIFBA/serializer.py"], "/HotelIFBA/serializer.py": ["/HotelIFBA/models.py"]}
24,302,878
mtlmacedo/HMS_IFBA
refs/heads/master
/HotelIFBA/views.py
from rest_framework import viewsets from HotelIFBA.models import Cliente, Empresa, Colaborador, Reserva, Estadia from HotelIFBA.serializer import EmpresaSerializer, ClienteSerializer, ColaboradorSerializer, ReservaSerializer, EstadiaSerializer class EmpresasViewSet(viewsets.ModelViewSet): queryset = Empresa.objects.all() serializer_class = EmpresaSerializer class ClienteViewSet(viewsets.ModelViewSet): queryset = Cliente.objects.all() serializer_class = ClienteSerializer class ColaboradorViewSet(viewsets.ModelViewSet): queryset = Colaborador.objects.all() serializer_class = ColaboradorSerializer class ReservaViewSet(viewsets.ModelViewSet): queryset = Reserva.objects.all() serializer_class = ReservaSerializer class EstadiaViewSet(viewsets.ModelViewSet): queryset = Estadia.objects.all() serializer_class = EstadiaSerializer
{"/hmsifba/serializer.py": ["/hmsifba/models.py"], "/config/urls.py": ["/hmsifba/views.py", "/HotelIFBA/views.py"], "/hmsifba/admin.py": ["/hmsifba/models.py"], "/hmsifba/views.py": ["/hmsifba/models.py", "/hmsifba/serializer.py"], "/HotelIFBA/admin.py": ["/HotelIFBA/models.py"], "/HotelIFBA/estadia_functions/disponibilidade.py": ["/HotelIFBA/models.py"], "/HotelIFBA/views.py": ["/HotelIFBA/models.py", "/HotelIFBA/serializer.py"], "/HotelIFBA/serializer.py": ["/HotelIFBA/models.py"]}
24,302,879
mtlmacedo/HMS_IFBA
refs/heads/master
/HotelIFBA/serializer.py
from django.db.models import fields from rest_framework import serializers from HotelIFBA.models import Cliente, Empresa, Colaborador, Reserva, Estadia class EmpresaSerializer(serializers.ModelSerializer): class Meta: model = Empresa fields = ['nomeEmpresa', 'cnpj', 'proprietario', 'endereco', 'telefone', 'categoria', 'email'] class ClienteSerializer(serializers.ModelSerializer): class Meta: model = Cliente fields = ['nomeCliente', 'nacionalidade', 'dtNascimento', 'endereco', 'telefone', 'idNumero', 'idData', 'email', 'senha'] class ColaboradorSerializer(serializers.ModelSerializer): class Meta: model = Colaborador fields = ['id', 'nomeCompleto', 'cpf', 'rg', 'ctps', 'cargo', 'admissao', 'jornadaDiaria', 'endereco'] class ReservaSerializer(serializers.ModelSerializer): class Meta: model = Reserva fields = ['id', 'dataEntrada', 'dataSaida', 'tipoQuarto', 'qtdPessoas'] class EstadiaSerializer(serializers.ModelSerializer): class Meta: model = Estadia fields = ['id', 'cliente', 'quarto', 'dataEntrada', 'dataSaida', 'dadosPagamento']
{"/hmsifba/serializer.py": ["/hmsifba/models.py"], "/config/urls.py": ["/hmsifba/views.py", "/HotelIFBA/views.py"], "/hmsifba/admin.py": ["/hmsifba/models.py"], "/hmsifba/views.py": ["/hmsifba/models.py", "/hmsifba/serializer.py"], "/HotelIFBA/admin.py": ["/HotelIFBA/models.py"], "/HotelIFBA/estadia_functions/disponibilidade.py": ["/HotelIFBA/models.py"], "/HotelIFBA/views.py": ["/HotelIFBA/models.py", "/HotelIFBA/serializer.py"], "/HotelIFBA/serializer.py": ["/HotelIFBA/models.py"]}
24,394,046
kingslayer2274/django-library
refs/heads/main
/sign/forms.py
from django import forms from django.db import models from django.forms import fields from sign.models import Users class UsersModelForm(forms.ModelForm): class Meta: model= Users fields=["name","email","password","role"] class UserLoginForm(forms.ModelForm): class Meta: model= Users fields= { "email":model.email, 'password': forms.PasswordInput(), }
{"/books/views.py": ["/books/forms.py"], "/sign/forms.py": ["/sign/models.py"], "/sign/views.py": ["/sign/forms.py", "/sign/models.py"], "/sign/urls.py": ["/sign/views.py"], "/sign/admin.py": ["/sign/models.py"], "/admindash/urls.py": ["/admindash/views.py"], "/student/urls.py": ["/admindash/views.py", "/student/views.py"]}
24,394,047
kingslayer2274/django-library
refs/heads/main
/sign/views.py
from typing import ContextManager from sign.forms import UserLoginForm, UsersModelForm from sign.models import Users from django.http.response import HttpResponse from django.shortcuts import render from django.contrib.auth.models import User # Create your views here. def login(request): # user = User.objects.create_user('john1', 'lennon@thebeatles.com', 'johnpassword') # print(type(user)) login_form = UserLoginForm() context={"form":login_form} return render(request,"sign/login.html",context) def register(request): register_user=UsersModelForm() context={"form":register_user} return render(request,"sign/register.html",context)
{"/books/views.py": ["/books/forms.py"], "/sign/forms.py": ["/sign/models.py"], "/sign/views.py": ["/sign/forms.py", "/sign/models.py"], "/sign/urls.py": ["/sign/views.py"], "/sign/admin.py": ["/sign/models.py"], "/admindash/urls.py": ["/admindash/views.py"], "/student/urls.py": ["/admindash/views.py", "/student/views.py"]}
24,394,048
kingslayer2274/django-library
refs/heads/main
/sign/urls.py
from os import name from sign.views import login, register from django.urls import path urlpatterns = [ path('login', login,name="login"), path('register',register,name="register") ]
{"/books/views.py": ["/books/forms.py"], "/sign/forms.py": ["/sign/models.py"], "/sign/views.py": ["/sign/forms.py", "/sign/models.py"], "/sign/urls.py": ["/sign/views.py"], "/sign/admin.py": ["/sign/models.py"], "/admindash/urls.py": ["/admindash/views.py"], "/student/urls.py": ["/admindash/views.py", "/student/views.py"]}
24,394,049
kingslayer2274/django-library
refs/heads/main
/admindash/views.py
# Create your views here. from typing import ContextManager from django.shortcuts import redirect, render # Create your views here. def adminHome(request): return render(request,"admindash/admin.html") # def viewstudents(request): # return render(request,"student/allstudents.html") # def studentprofile(request,std_id): # context={"std":std_id} # return render(request,"student/studentprofile.html",context) def books(request): return render(request,"admindash/books.html") def editbook(request,book_id): context={"book_id":book_id} return render(request,'admindash/editbook.html',context) def addbook(request): return render(request,'admindash/addbook.html') def changepass(request): return render(request,'admindash/changepass.html') def borrowedbooks(request): return render(request,'admindash/borrowedbooks.html') def deletebook(request,book_id): return redirect("books")
{"/books/views.py": ["/books/forms.py"], "/sign/forms.py": ["/sign/models.py"], "/sign/views.py": ["/sign/forms.py", "/sign/models.py"], "/sign/urls.py": ["/sign/views.py"], "/sign/admin.py": ["/sign/models.py"], "/admindash/urls.py": ["/admindash/views.py"], "/student/urls.py": ["/admindash/views.py", "/student/views.py"]}
24,394,050
kingslayer2274/django-library
refs/heads/main
/sign/admin.py
from sign.models import Users from django.contrib import admin # Register your models here. admin.site.register(Users)
{"/books/views.py": ["/books/forms.py"], "/sign/forms.py": ["/sign/models.py"], "/sign/views.py": ["/sign/forms.py", "/sign/models.py"], "/sign/urls.py": ["/sign/views.py"], "/sign/admin.py": ["/sign/models.py"], "/admindash/urls.py": ["/admindash/views.py"], "/student/urls.py": ["/admindash/views.py", "/student/views.py"]}
24,394,051
kingslayer2274/django-library
refs/heads/main
/admindash/urls.py
from admindash.views import addbook, adminHome, books, borrowedbooks, changepass, deletebook, editbook from django.urls import path urlpatterns = [ path('home',adminHome,name='adminhome'), # path('student',studnetHome,name='studenthome'), # path("allstudents",viewstudents,name='allstudents'), # path('allstudents/<int:std_id>',studentprofile,name='studentprofile'), path('books',books,name="books"), path('books/<int:book_id>',editbook,name='editbook'), path('addbook',addbook,name='addbook'), path('changepassword',changepass,name='changepassword'), path('borrowedbooks',borrowedbooks,name='borrowedbooks'), path('delete/<int:book_id>',deletebook,name='deletebook') ]
{"/books/views.py": ["/books/forms.py"], "/sign/forms.py": ["/sign/models.py"], "/sign/views.py": ["/sign/forms.py", "/sign/models.py"], "/sign/urls.py": ["/sign/views.py"], "/sign/admin.py": ["/sign/models.py"], "/admindash/urls.py": ["/admindash/views.py"], "/student/urls.py": ["/admindash/views.py", "/student/views.py"]}
24,394,052
kingslayer2274/django-library
refs/heads/main
/admindash/apps.py
from django.apps import AppConfig class AdmindashConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'admindash'
{"/books/views.py": ["/books/forms.py"], "/sign/forms.py": ["/sign/models.py"], "/sign/views.py": ["/sign/forms.py", "/sign/models.py"], "/sign/urls.py": ["/sign/views.py"], "/sign/admin.py": ["/sign/models.py"], "/admindash/urls.py": ["/admindash/views.py"], "/student/urls.py": ["/admindash/views.py", "/student/views.py"]}
24,394,053
kingslayer2274/django-library
refs/heads/main
/student/views.py
from django.shortcuts import redirect, render # Create your views here. def studenthome(request,std_id): return render(request, 'student/studenthome.html') def studentprofile(request,std_id): return render(request,'student/studentprofile.html') def viewstudents(request): return render(request , 'student/allstudents.html') def viewbooks(request): return render(request,'student/stdbooks.html') def stdborrowedbooks(request): return render(request,"student/stdborrowedbooks.html") def editprofile(request): return render(request,'student/editprofile.html')
{"/books/views.py": ["/books/forms.py"], "/sign/forms.py": ["/sign/models.py"], "/sign/views.py": ["/sign/forms.py", "/sign/models.py"], "/sign/urls.py": ["/sign/views.py"], "/sign/admin.py": ["/sign/models.py"], "/admindash/urls.py": ["/admindash/views.py"], "/student/urls.py": ["/admindash/views.py", "/student/views.py"]}
24,394,054
kingslayer2274/django-library
refs/heads/main
/student/urls.py
from admindash.views import books from student.views import editprofile, stdborrowedbooks, studenthome, studentprofile, viewbooks, viewstudents from django.urls import path urlpatterns = [ path('home/<int:std_id>',studenthome,name='studenthome'), path("allstudents",viewstudents,name='allstudents'), path('allstudents/<int:std_id>',studentprofile,name='studentprofile'), path('books',viewbooks,name="stdbooks"), path('borrowedbooks',stdborrowedbooks,name='stdborrowedbooks'), path('editprofile',editprofile,name='editprofile') ]
{"/books/views.py": ["/books/forms.py"], "/sign/forms.py": ["/sign/models.py"], "/sign/views.py": ["/sign/forms.py", "/sign/models.py"], "/sign/urls.py": ["/sign/views.py"], "/sign/admin.py": ["/sign/models.py"], "/admindash/urls.py": ["/admindash/views.py"], "/student/urls.py": ["/admindash/views.py", "/student/views.py"]}
24,394,055
kingslayer2274/django-library
refs/heads/main
/sign/models.py
from django.db import models # Create your models here. class Users(models.Model): name= models.CharField(max_length=100) email=models.EmailField(null=True) password=models.CharField(max_length=100) role= models.CharField(max_length=2,choices=[("a","admin"),("s","student")]) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name
{"/books/views.py": ["/books/forms.py"], "/sign/forms.py": ["/sign/models.py"], "/sign/views.py": ["/sign/forms.py", "/sign/models.py"], "/sign/urls.py": ["/sign/views.py"], "/sign/admin.py": ["/sign/models.py"], "/admindash/urls.py": ["/admindash/views.py"], "/student/urls.py": ["/admindash/views.py", "/student/views.py"]}
24,499,379
jowc/Django-React-Blog
refs/heads/main
/backend/blogs/migrations/0013_remove_article_message.py
# Generated by Django 3.1 on 2021-02-17 22:36 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('blogs', '0012_article_message'), ] operations = [ migrations.RemoveField( model_name='article', name='message', ), ]
{"/backend/blogs/views.py": ["/backend/blogs/models.py", "/backend/blogs/forms.py"], "/backend/blogs/forms.py": ["/backend/blogs/models.py"], "/backend/blogs/urls.py": ["/backend/blogs/views.py"], "/backend/blogs/slugify.py": ["/backend/blogs/models.py"], "/backend/test_project/urls.py": ["/backend/test_project/views.py"]}
24,499,380
jowc/Django-React-Blog
refs/heads/main
/backend/blogs/migrations/0015_auto_20210218_0024.py
# Generated by Django 3.1 on 2021-02-17 23:24 from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('blogs', '0014_auto_20210217_2311'), ] operations = [ migrations.AlterField( model_name='article', name='last_update', field=models.DateTimeField(auto_now=True, default=django.utils.timezone.now), preserve_default=False, ), migrations.AlterField( model_name='article', name='timestamp', field=models.DateTimeField(auto_now_add=True, default=django.utils.timezone.now), preserve_default=False, ), ]
{"/backend/blogs/views.py": ["/backend/blogs/models.py", "/backend/blogs/forms.py"], "/backend/blogs/forms.py": ["/backend/blogs/models.py"], "/backend/blogs/urls.py": ["/backend/blogs/views.py"], "/backend/blogs/slugify.py": ["/backend/blogs/models.py"], "/backend/test_project/urls.py": ["/backend/test_project/views.py"]}
24,499,381
jowc/Django-React-Blog
refs/heads/main
/backend/blogs/migrations/0024_auto_20210224_2210.py
# Generated by Django 3.1 on 2021-02-24 21:10 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('blogs', '0023_auto_20210224_2010'), ] operations = [ migrations.AlterField( model_name='article', name='publish_date', field=models.DateField(), ), ]
{"/backend/blogs/views.py": ["/backend/blogs/models.py", "/backend/blogs/forms.py"], "/backend/blogs/forms.py": ["/backend/blogs/models.py"], "/backend/blogs/urls.py": ["/backend/blogs/views.py"], "/backend/blogs/slugify.py": ["/backend/blogs/models.py"], "/backend/test_project/urls.py": ["/backend/test_project/views.py"]}
24,499,382
jowc/Django-React-Blog
refs/heads/main
/backend/blogs/views.py
from django.shortcuts import render, get_object_or_404, redirect from django.contrib.auth.decorators import login_required from .models import article from .forms import * # Create your views here. # Django RestAPI views from django.contrib.auth.models import User, Group from rest_framework import viewsets from rest_framework import permissions from .serializers import (UserSerializer, BlogSerializer) from rest_framework.decorators import api_view from rest_framework.response import Response def blog(request): # post = get_object_or_404(blog, post_id) template_name = "blog/index.html" qs = article.objects.all() return render(request, template_name, {"post": qs, 'title': 'Articles'}) @login_required def create_blog(request): # post = get_object_or_404(blog, post_id) if request.POST: form = Blogmodelform(request.POST) if form.is_valid(): form.save() return redirect('blog') else: form = Blogmodelform() print('upload error') template_name = 'blog/create.html' context = {"post": form, 'title': "New Article"} return render(request, template_name, context) def blog_detail(request, slug): template_name = 'blog/detail.html' post = get_object_or_404(article, slug=slug) comment = post.comment.filter(active=True) new_comment = None comment_form = Commentmodelform() context = { 'title': post.title, 'post': post, 'comment': comment, 'new_comment': new_comment, 'comment_form': comment_form } # Delete Article # if request.method == "POST" and request.POST['deletePost']: # post.delete() # return redirect("/blog") # Add comment if request.method == 'POST': comment_form = Commentmodelform(request.POST) if comment_form.is_valid(): # Create Comment object but don't save to database yet new_comment = comment_form.save(commit=False) # Assign the current post to the comment new_comment.post = post print(new_comment) # Save the comment to the database new_comment.save() else: print('not valid') else: comment_form = Commentmodelform() return render(request, template_name, context) @login_required def update_blog(request, slug): template_name = 'blog/update.html' post = get_object_or_404(article, slug=slug) form = Blogmodelform(request.POST or None, request.FILES or None, instance=post) if form.is_valid(): form.user = request.user form.save() print('Post Updated') return render(request, template_name, {"form": form, 'title': post.title}) # Delete view function not in use but used in the detail view. def delete_blog(request, slug): # post = get_object_or_404(article, slug) # if request.POST and request.POST['deletePost']: # post.delete() return print('deleted post') # return redirect("/blog") # template_name = 'delete_blog.html' # return render(request, template_name, {"post": post, 'title': post.title}) # Blog Api @api_view(['GET']) def blogURLS(request): message = { 'api/blog/list': 'Blogs list', 'api/blog/<str:slug>': 'Blog detail', 'api/blog-create/': 'Create blog post', 'api/blog/update/<str:slug>': 'Update blog post', 'api/blog/delete/<str:slug>': 'Delete blog post', } return Response(message) @api_view(['GET']) def blogList(request): payload = article.objects.all() serializer = BlogSerializer(payload, many=True) return Response(serializer.data) @api_view(['GET']) def blogDetail(request, slug): payload = article.objects.get(slug=slug) serializer = BlogSerializer(payload, many=False) return Response(serializer.data) @api_view(['POST']) def blogCreate(request): serializer = BlogSerializer(data=request.data) if serializer.is_valid(): print('content valid') serializer.save() else: print('Not Valid') return Response(serializer.data) @api_view(['POST']) def blogUpdate(request, slug): # post = get_object_or_404(article, slug=slug) post = article.objects.get(slug=slug) serializer = BlogSerializer(instance=post, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) @api_view(['DELETE']) def blogDelete(request, slug): # post = get_object_or_404(article, slug = slug) post = article.objects.get(slug=slug) post.delete() message = f"Post: {post.title} successfully deleted" return Response(message) class UserViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed or edited. """ queryset = User.objects.all().order_by('-date_joined') serializer_class = UserSerializer permission_classes = [permissions.IsAuthenticated] ''' # User Groups class GroupViewSet(viewsets.ModelViewSet): """ API endpoint that allows groups to be viewed or edited. """ queryset = Group.objects.all() serializer_class = GroupSerializer permission_classes = [permissions.IsAuthenticated] ''' # @api_view(['GET']) def user_api(request): queryset = User.objects.all().order_by('-date_joined') serializer = UserSerializer(queryset, many=True) return Response(serializer)
{"/backend/blogs/views.py": ["/backend/blogs/models.py", "/backend/blogs/forms.py"], "/backend/blogs/forms.py": ["/backend/blogs/models.py"], "/backend/blogs/urls.py": ["/backend/blogs/views.py"], "/backend/blogs/slugify.py": ["/backend/blogs/models.py"], "/backend/test_project/urls.py": ["/backend/test_project/views.py"]}
24,499,383
jowc/Django-React-Blog
refs/heads/main
/backend/blogs/migrations/0027_auto_20210422_1258.py
# Generated by Django 3.1 on 2021-04-22 11:58 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('blogs', '0026_auto_20210302_1825'), ] operations = [ migrations.RenameField( model_name='article', old_name='User', new_name='author', ), migrations.AlterField( model_name='article', name='description', field=models.TextField(max_length=5000), ), migrations.CreateModel( name='comment', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('comment', models.TextField(max_length=1000)), ('timestamp', models.DateTimeField(auto_now_add=True)), ('post', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='blogs.article')), ], ), ]
{"/backend/blogs/views.py": ["/backend/blogs/models.py", "/backend/blogs/forms.py"], "/backend/blogs/forms.py": ["/backend/blogs/models.py"], "/backend/blogs/urls.py": ["/backend/blogs/views.py"], "/backend/blogs/slugify.py": ["/backend/blogs/models.py"], "/backend/test_project/urls.py": ["/backend/test_project/views.py"]}
24,499,384
jowc/Django-React-Blog
refs/heads/main
/backend/blogs/migrations/0016_auto_20210218_0032.py
# Generated by Django 3.1 on 2021-02-17 23:32 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('blogs', '0015_auto_20210218_0024'), ] operations = [ migrations.AlterModelOptions( name='article', options={'ordering': ['-publish_date', '-timestamp', '-last_update']}, ), ]
{"/backend/blogs/views.py": ["/backend/blogs/models.py", "/backend/blogs/forms.py"], "/backend/blogs/forms.py": ["/backend/blogs/models.py"], "/backend/blogs/urls.py": ["/backend/blogs/views.py"], "/backend/blogs/slugify.py": ["/backend/blogs/models.py"], "/backend/test_project/urls.py": ["/backend/test_project/views.py"]}
24,499,385
jowc/Django-React-Blog
refs/heads/main
/backend/blogs/migrations/0030_auto_20210423_1307.py
# Generated by Django 3.1 on 2021-04-23 12:07 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('blogs', '0029_auto_20210422_1341'), ] operations = [ migrations.AlterField( model_name='comment', name='post', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='comment', to='blogs.article'), ), ]
{"/backend/blogs/views.py": ["/backend/blogs/models.py", "/backend/blogs/forms.py"], "/backend/blogs/forms.py": ["/backend/blogs/models.py"], "/backend/blogs/urls.py": ["/backend/blogs/views.py"], "/backend/blogs/slugify.py": ["/backend/blogs/models.py"], "/backend/test_project/urls.py": ["/backend/test_project/views.py"]}
24,499,386
jowc/Django-React-Blog
refs/heads/main
/backend/blogs/models.py
import string import random from django.db import models from django.utils.text import slugify from django.conf import settings from django.utils import timezone # Create your models here. User = settings.AUTH_USER_MODEL def rand_slug(): return ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(6)) class article(models.Model): author = models.ForeignKey( User, default=1, null=True, on_delete=models.SET_NULL) slug = models.SlugField(unique=True, null=False, blank=True) image = models.ImageField(upload_to='images', null=True, blank=True) title = models.CharField(max_length=225) content = models.TextField(max_length=5000) categories = ( ("Tech", "Tech",), ("Business", "Business"), ("UI/UX", "UI/UX") ) category = models.TextField( choices=categories, null=True) publish_date = models.DateTimeField(default=timezone.now) timestamp = models.DateTimeField(auto_now_add=True) last_update = models.DateTimeField(auto_now=True) class Meta: ordering = ['-pk', '-publish_date', '-last_update', '-timestamp'] def __str__(self): return self.title def get_edit_url(self): return f"{self.slug}/update" def summaryTXT(self): return self.content[:60] + "..." def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title + "-" + rand_slug()) super(article, self).save(*args, **kwargs) class comment(models.Model): # reference a post model post = models.ForeignKey( article, null=True, on_delete=models.CASCADE, related_name='comment') # author = models.ForeignKey(User, default=1, null=True, on_delete=models.SET_NULL) comment = models.TextField(max_length=1000) created_on = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=False) class Meta: ordering = ['created_on'] def __str__(self): comment = self.comment[:80] return f"{self.post.author} said {comment}..."
{"/backend/blogs/views.py": ["/backend/blogs/models.py", "/backend/blogs/forms.py"], "/backend/blogs/forms.py": ["/backend/blogs/models.py"], "/backend/blogs/urls.py": ["/backend/blogs/views.py"], "/backend/blogs/slugify.py": ["/backend/blogs/models.py"], "/backend/test_project/urls.py": ["/backend/test_project/views.py"]}
24,499,387
jowc/Django-React-Blog
refs/heads/main
/backend/blogs/forms.py
from django.forms import ModelForm # from django.forms import ModelForm from .models import (article, comment) # Django Forms """ class blogform(forms.Form): title = forms.CharField(label="title") slug = forms.SlugField(label="Unique URL") category = forms.ChoiceField(label='Category', choices=[ ("Tech", "Tech"), ("Business", "Business"), ("UI/UX", "UI/UX") ]) description = forms.CharField(widget=forms.Textarea) """ class Blogmodelform(ModelForm): class Meta: model = article fields = ['slug', 'title', 'image', 'content', 'category', 'publish_date'] class Commentmodelform(ModelForm): class Meta: model = comment fields = ['comment']
{"/backend/blogs/views.py": ["/backend/blogs/models.py", "/backend/blogs/forms.py"], "/backend/blogs/forms.py": ["/backend/blogs/models.py"], "/backend/blogs/urls.py": ["/backend/blogs/views.py"], "/backend/blogs/slugify.py": ["/backend/blogs/models.py"], "/backend/test_project/urls.py": ["/backend/test_project/views.py"]}
24,499,388
jowc/Django-React-Blog
refs/heads/main
/backend/blogs/migrations/0014_auto_20210217_2311.py
# Generated by Django 3.1 on 2021-02-17 23:11 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('blogs', '0013_remove_article_message'), ] operations = [ migrations.AddField( model_name='article', name='last_update', field=models.DateTimeField(auto_now_add=True, null=True), ), migrations.AddField( model_name='article', name='publish_date', field=models.DateTimeField(null=True), ), migrations.AddField( model_name='article', name='timestamp', field=models.DateTimeField(auto_now_add=True, null=True), ), ]
{"/backend/blogs/views.py": ["/backend/blogs/models.py", "/backend/blogs/forms.py"], "/backend/blogs/forms.py": ["/backend/blogs/models.py"], "/backend/blogs/urls.py": ["/backend/blogs/views.py"], "/backend/blogs/slugify.py": ["/backend/blogs/models.py"], "/backend/test_project/urls.py": ["/backend/test_project/views.py"]}
24,499,389
jowc/Django-React-Blog
refs/heads/main
/backend/blogs/urls.py
from django.urls import path from .views import * urlpatterns = [ path('', blog, name='blog'), path('<str:slug>', blog_detail), path('blog-new/', create_blog, name="new_article"), path('<str:slug>/update/', update_blog, name="update_article"), path('<str:slug>/blog-delete/', delete_blog, name='delete_blog'), ]
{"/backend/blogs/views.py": ["/backend/blogs/models.py", "/backend/blogs/forms.py"], "/backend/blogs/forms.py": ["/backend/blogs/models.py"], "/backend/blogs/urls.py": ["/backend/blogs/views.py"], "/backend/blogs/slugify.py": ["/backend/blogs/models.py"], "/backend/test_project/urls.py": ["/backend/test_project/views.py"]}
24,499,390
jowc/Django-React-Blog
refs/heads/main
/backend/blogs/slugify.py
import itertools from django.utils.text import slugify from .models import article def generate_slug(get_title): # check if the slug is already in the database slug_exist = article.objects.filter(slug=get_title).exists() # continue looping until False while slug_exist: num = None # Append a new number from 0 to infinity for i in range(1, 100, 1): num = i # merge the title and iterating num slug_title = slugify(get_title + "-" + str(num + 1)) new_slug = slug_title return new_slug # print(generate_slug(get_title)) # for n in range(1, 1000): # return str(n) # start from 1 to infinity
{"/backend/blogs/views.py": ["/backend/blogs/models.py", "/backend/blogs/forms.py"], "/backend/blogs/forms.py": ["/backend/blogs/models.py"], "/backend/blogs/urls.py": ["/backend/blogs/views.py"], "/backend/blogs/slugify.py": ["/backend/blogs/models.py"], "/backend/test_project/urls.py": ["/backend/test_project/views.py"]}
24,499,391
jowc/Django-React-Blog
refs/heads/main
/backend/test_project/urls.py
from django.contrib import admin from django.urls import path, include from .views import (homeview, aboutview, contactview) from django.conf import settings from django.conf.urls.static import static from blogs.views import * # Django RestAPI Urls from rest_framework import routers # from test_project.blogs import views # Rest settings router = routers.DefaultRouter() # router.register(r'users', views.UserViewSet) # router.register(r'groups', views.GroupViewSet) urlpatterns = [ path('admin/', admin.site.urls), path('', homeview, name="home"), path('about/', aboutview, name="about"), path('contact/', contactview, name="contact"), path('blog/', include('blogs.urls')), path('api/', include(router.urls)), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')), path('api/blog/list/', blogList, name = "Blog-list" ), path('api/blog/<str:slug>/', blogDetail, name = "blog-detail" ), path('api/blog-create/', blogCreate, name = "blog-create"), path('api/blog/update/<str:slug>/', blogUpdate, name = "blog-update"), path('api/blog/delete/<str:slug>/', blogDelete, name = "blog-delete"), path('api/urls/', blogURLS), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
{"/backend/blogs/views.py": ["/backend/blogs/models.py", "/backend/blogs/forms.py"], "/backend/blogs/forms.py": ["/backend/blogs/models.py"], "/backend/blogs/urls.py": ["/backend/blogs/views.py"], "/backend/blogs/slugify.py": ["/backend/blogs/models.py"], "/backend/test_project/urls.py": ["/backend/test_project/views.py"]}
24,499,392
jowc/Django-React-Blog
refs/heads/main
/backend/test_project/views.py
from django.shortcuts import render def homeview(request): return render(request, 'home.html', {'title': 'Home'}) def aboutview(request): return render(request, 'about.html', {'title': 'about'}) def contactview(request): return render(request, 'contact.html', {'title': 'contact'})
{"/backend/blogs/views.py": ["/backend/blogs/models.py", "/backend/blogs/forms.py"], "/backend/blogs/forms.py": ["/backend/blogs/models.py"], "/backend/blogs/urls.py": ["/backend/blogs/views.py"], "/backend/blogs/slugify.py": ["/backend/blogs/models.py"], "/backend/test_project/urls.py": ["/backend/test_project/views.py"]}
24,499,393
jowc/Django-React-Blog
refs/heads/main
/backend/blogs/migrations/0009_auto_20201223_1353.py
# Generated by Django 3.1 on 2020-12-23 13:53 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('blogs', '0008_article_slug'), ] operations = [ migrations.AddField( model_name='article', name='category', field=models.TextField(choices=[('Tech', 'Tech'), ('Business', 'Business'), ('UI/UX', 'UI/UX')], null=True), ), migrations.AlterField( model_name='article', name='description', field=models.CharField(max_length=1000), ), migrations.AlterField( model_name='article', name='title', field=models.CharField(max_length=225), ), ]
{"/backend/blogs/views.py": ["/backend/blogs/models.py", "/backend/blogs/forms.py"], "/backend/blogs/forms.py": ["/backend/blogs/models.py"], "/backend/blogs/urls.py": ["/backend/blogs/views.py"], "/backend/blogs/slugify.py": ["/backend/blogs/models.py"], "/backend/test_project/urls.py": ["/backend/test_project/views.py"]}
24,668,344
olinpin/onlinebakalarigit
refs/heads/main
/calendartest.py
from __future__ import print_function from apiclient.discovery import build from httplib2 import Http from oauth2client import file, client, tools import datetime import requests from bs4 import BeautifulSoup import json import sys import webbrowser classes = [ "Český jazyk", "Český jazyk a literatura", "Anglický jazyk", "Německý jazyk", "Francouzský jazyk", "Ruský jazyk", "Občanská nauka", "Základy společenských věd", "Dějepis", "Matematika", "Fyzika", "Fyzikální praktika", "Biologie", "Biologická praktika", "Chemie", "Chemická praktika", "Zeměpis", "Zeměpisná praktika", "Přírodovědná praktika", "Informatika a výpočetní technika", "Hudební výchova", "Výtvarná výchova", "Tělesná výchova", "Globální výchova", "Vlastivědný seminář", "Matematika s podporou ICT", "Školní časopis", "Literární praktikum", "Psaní na PC", "Geometrické praktikum", "Matematický seminář", "Chemický seminář", "Biologický seminář", "Fyzikální seminář", "Deskriptivní geometrie", "Zeměpisný seminář", "Dějepisný seminář", "Společenskovědní seminář", "Sociologie a psychologie", "Politologie a mezinárodní vztahy", "Ekonomika podnikání", "Konverzace z angličtiny", "Konverzace z francouzštiny", "Konverzace z němčiny", "Aplikace Windows a programování", "Literální seminář", "Chemicko-biologická praktika", "Biologie člověka a výchova ke zdraví", "Konverzace z ruštiny", "Fyzika pro lékařské fakulty", ] #$oauth_callback = 'https://accounts.google.com/o/oauth2/auth?client_id=669046485288-hk0o6915jn4givcqe1bfiso29i7fle67.apps.googleusercontent.com&redirect_uri=https:%2f%2fbakalaricz.herokuapp.com%2Frozvrh%2F&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcalendar&access_type=offline&response_type=code' def authorization(): try: import argparse #flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args() flags = tools.argparser.parse_args([]) except ImportError: flags = None SCOPES = 'https://www.googleapis.com/auth/calendar' store = file.Storage('storage.json') creds = store.get() #webbrowser.open(oauth_callback) print('opened') if not creds or creds.invalid: flow = client.flow_from_clientsecrets('client_secret.json', SCOPES) creds = tools.run_flow(flow, store, flags) \ if flags else tools.run(flow, store) def addCalendar(predmet, start, end, room, about): authorization() store = file.Storage('storage.json') creds = store.get() CAL = build('calendar', 'v3', http=creds.authorize(Http())) GMT_OFF = "-01:00" EVENT = { 'summary': f"{predmet}", 'start': {f'dateTime': f'{start}', "timeZone": "UTC+2"}, 'end': {'dateTime': f'{end}', "timeZone": "UTC+2"}, 'location': f'{room}', 'description': f'{about}', } e = CAL.events().insert(calendarId='primary', body=EVENT).execute() def getTimeTable(Name, Sem): print(Name) r = requests.get(f"https://gym-nymburk.bakalari.cz/bakaweb/Timetable/public/Actual/Class/{ Name }") soup = BeautifulSoup(r.text, "html.parser") finder = soup.find_all('div', attrs={"class":'day-item-hover'}) delete() for x in finder: data_detail = x['data-detail'].replace('null', '"Nothing"') data_detail = eval(data_detail) subjecttext = data_detail['subjecttext'] try: teacher = data_detail['teacher'] room = data_detail['room'] if room == "mim" or room == "A" or room == 'T' or room == 'DisV': room = str(room) else: room = int(room) except: continue try: jaz = data_detail["group"] except: jaz = '' if jaz not in Sem: continue splited = subjecttext.split(' |') predmet = splited[0] date = splited[1] try: time = splited[2] except: predmet = "ODPADLÁ HODINA" time = splited[1] date = splited[0] date = date.replace('po', '') date = date.replace('út', '') date = date.replace('st', '') date = date.replace('čt', '') date = date.replace('pá', '') date = date.replace(' ', '') t = 0 while t < 10: time = time.replace(")", "") time = time.replace(" ", '') time = time.replace(f'{t}(', '') t = t+1 start = time.split('-')[0]+":00" end = time.split('-')[1]+":00" date = date.split('.') date = str(datetime.datetime.today().year) + '-'+date[1]+'-'+date[0] start = date + "T" + start end = date + "T" + end start = start.split("T") if start[1].startswith("1") == False: start = start[0] + "T" + '0' + start[1] else: start = start[0] + "T" + start[1] end = end.split("T") if end[1].startswith("1") == False: end = end[0] + "T" + '0' + end[1] else: end = end[0] + "T" + end[1] if type(room) == int: room = "Učebna " + str(room) now = datetime.datetime.now().isoformat() now = now.split('.')[0] now = now.split("T") datenow = now[0] timenow = now[1] if timenow.startswith('0') == True: timenow = timenow[0:] now = datenow+'T'+timenow if now > start: print(predmet, "SKIPPED") continue addCalendar(predmet, start, end, room, teacher) print(predmet, room, teacher, start) # start, end, open('storage.json', 'r+').truncate() def delete(): authorization() store = file.Storage('storage.json') creds = store.get() CAL = build('calendar', 'v3', http=creds.authorize(Http())) now = datetime.datetime.now().isoformat() now = now.split('.')[0] + 'Z' e = CAL.events().list(calendarId='primary', timeMin='2020-10-14T11:35:00Z').execute() items = e['items'] for z in items: if z['status'] == 'confirmed': if z['summary'] in classes: print('deleted' + ' '+ z['summary']) eventid = z['id'] event = CAL.events().delete(calendarId='primary', eventId=eventid).execute() else: continue else: continue #if __name__ == "__main__": #getTimeTable("ZK", ['aj5', 'nej2', 'fys1', 'mas2', 'eps3', ''])#the ' ' has to be there, in order for it to work, jaz = ' '
{"/rozvrh/views.py": ["/rozvrh/Calendartest/calendartest.py"]}
24,751,525
gauravndabhade/MyCart
refs/heads/main
/MyCart/utils.py
import click import peewee from models import Cart, Category, Product, User, db from tabulate import tabulate from user.session import UserSession from MyCart.controller import CartController from product.controller import ProductController from category.controller import CategoryController cart = CartController() user_session = UserSession() product_controller = ProductController() def get_discount(amount): if amount >= 10000: return 500.0, True else: return 0.0, False def sum_price(matrix, index): return sum(row[index] for row in matrix) def add_admin(is_admin): if is_admin: return click.style(' [ADMIN]', fg='green') else: return click.style(' [CUSTOMER]', fg='green') def show_bills(): username, _ = user_session.read_current_user() if username: click.echo(click.style('Bill : ', fg='cyan') + click.style('\t\t\tPURCHASE ORDER OF MINIMUM 10000/-, AND GET DISCOUNT!!!', fg='green')) cart_data = cart.get_cart_products(username) if cart_data: total_amount = sum_price(cart_data, 1) # 1 -> price coloumn index discount_amount, _ = get_discount(total_amount) click.echo(click.style(' \tTotal : \t', fg='cyan') + str(total_amount)) click.echo(click.style(' \tDiscount :', fg='cyan') + '\t' + str(discount_amount)) click.echo( "\t\t\t--------") click.echo('\t\t\t' + str(total_amount - discount_amount)) else: show_login_require() def show_welcome(): try: username, is_admin = user_session.read_current_user() if username: show_nav(username, is_admin) show_categories() show_products() show_cart_status(username) click.echo( "--------------------------------------------------------------------------------") else: click.echo('MyCart') click.echo( "--------------------------------------------------------------------------------") show_login_require() except peewee.OperationalError: click.echo('MyCart') click.echo( "--------------------------------------------------------------------------------") show_init_database() def show_login_require(): click.echo(click.style( 'User login or Create new account to MyCart', fg='yellow')) def show_init_database(): click.echo(click.style( 'Not database found. Initalize database with command : ', fg='yellow') +click.style('$ mycart initdb', fg='red')) def show_nav(username, is_admin): click.echo() click.echo() click.echo('MyCart \t\t\t\t\t\t\t Login as: ' + click.style(username, fg='cyan') + add_admin(is_admin)) click.echo( "--------------------------------------------------------------------------------") def show_categories(): click.echo(click.style('Categories', fg='cyan')) categories = [[cat] for cat in CategoryController().all()] if categories: click.echo(tabulate(categories, headers=[ 'Name'], tablefmt='pretty')) else: click.echo('Categories not found') def show_products(): click.echo(click.style('Products', fg='cyan')) products = product_controller.get_all_product() if products: click.echo(tabulate(products, headers=[ 'Name', 'Price'], tablefmt='pretty')) else: click.echo('Products not found') def show_cart_status(username): click.echo(click.style('Cart', fg='cyan')) cart_products = cart.get_cart_products(username) if cart_products: click.echo(tabulate(cart_products, headers=[ 'Name', 'Price'], tablefmt='pretty')) else: click.echo('Cart is empty. Add Products in Cart')
{"/category/category_controller.py": ["/models/__init__.py"], "/MyCart/__main__.py": ["/category/category_cli.py", "/models/__init__.py", "/MyCart/cli.py", "/category/cli.py", "/product/cli.py", "/user/cli.py"], "/user/user_session.py": ["/models/__init__.py"], "/product/product_controller.py": ["/models/__init__.py"], "/MyCart/cart_controller.py": ["/models/__init__.py"], "/MyCart/utils.py": ["/models/__init__.py", "/user/session.py", "/MyCart/controller.py", "/product/controller.py", "/category/controller.py"], "/tests/setup.py": ["/config/__init__.py", "/models/__init__.py"], "/MyCart/cli.py": ["/MyCart/controller.py", "/category/controller.py", "/product/controller.py", "/user/session.py", "/config/__init__.py", "/models/__init__.py", "/MyCart/utils.py"], "/user/controller.py": ["/models/__init__.py", "/user/session.py", "/MyCart/utils.py"], "/tests/test_controller_product.py": ["/tests/setup.py", "/product/controller.py"], "/category/controller.py": ["/models/__init__.py", "/user/session.py"], "/user/session.py": ["/models/__init__.py"], "/tests/test_controller_user.py": ["/tests/setup.py", "/user/controller.py"], "/product/controller.py": ["/models/__init__.py", "/user/session.py", "/category/controller.py"], "/product/cli.py": ["/product/controller.py", "/category/controller.py"], "/category/cli.py": ["/category/controller.py"], "/user/cli.py": ["/user/controller.py"], "/models/__init__.py": ["/config/__init__.py"], "/MyCart/controller.py": ["/models/__init__.py", "/user/session.py", "/category/controller.py"], "/tests/test_controller_category.py": ["/tests/setup.py", "/category/controller.py"], "/tests/test_controller_cart.py": ["/tests/setup.py", "/MyCart/controller.py"]}
24,751,526
gauravndabhade/MyCart
refs/heads/main
/tests/setup.py
# Third party imports import pytest import config from peewee import SqliteDatabase from models import Product, User, Category, Cart MODELS = (User, Category, Cart, Product) db = SqliteDatabase(config.TEST_DATABASE) @pytest.fixture(scope='module', autouse=True) def setup_database(): # print('Initialized test database') db.connect() db.create_tables(MODELS) # Default test data user = User(username='Foo', password='12345678', is_admin=True) user.save() category = Category.create(name='Car', user=user) category.save() product = Product.create(name='Nano', user=user, price=10000.0, category=category) product.save() product = Product.create(name='Alto', user=user, price=10000.0, category=category) product.save() product = Product.create(name='Swift', user=user, price=10000.0, category=category) product.save() category = Category.create(name='Mobile', user=user) category.save() product = Product.create(name='Realme', user=user, price=10000.0, category=category) product.save() product = Product.create(name='OnePlus', user=user, price=10000.0, category=category) product.save() product = Product.create(name='Mi', user=user, price=10000.0, category=category) product.save() category = Category.create(name='Books', user=user) category.save() product = Product.create(name='The Alchemist', user=user, price=10000.0, category=category) product.save() product = Product.create(name='The Secret', user=user, price=10000.0, category=category) product.save() category = Category.create(name='Watch', user=user) category.save() product = Product.create(name='Titan', user=user, price=10000.0, category=category) product.save() product = Product.create(name='Casio', user=user, price=10000.0, category=category) product.save() yield db db.drop_tables(MODELS) db.close() # print('\nDropped test database')
{"/category/category_controller.py": ["/models/__init__.py"], "/MyCart/__main__.py": ["/category/category_cli.py", "/models/__init__.py", "/MyCart/cli.py", "/category/cli.py", "/product/cli.py", "/user/cli.py"], "/user/user_session.py": ["/models/__init__.py"], "/product/product_controller.py": ["/models/__init__.py"], "/MyCart/cart_controller.py": ["/models/__init__.py"], "/MyCart/utils.py": ["/models/__init__.py", "/user/session.py", "/MyCart/controller.py", "/product/controller.py", "/category/controller.py"], "/tests/setup.py": ["/config/__init__.py", "/models/__init__.py"], "/MyCart/cli.py": ["/MyCart/controller.py", "/category/controller.py", "/product/controller.py", "/user/session.py", "/config/__init__.py", "/models/__init__.py", "/MyCart/utils.py"], "/user/controller.py": ["/models/__init__.py", "/user/session.py", "/MyCart/utils.py"], "/tests/test_controller_product.py": ["/tests/setup.py", "/product/controller.py"], "/category/controller.py": ["/models/__init__.py", "/user/session.py"], "/user/session.py": ["/models/__init__.py"], "/tests/test_controller_user.py": ["/tests/setup.py", "/user/controller.py"], "/product/controller.py": ["/models/__init__.py", "/user/session.py", "/category/controller.py"], "/product/cli.py": ["/product/controller.py", "/category/controller.py"], "/category/cli.py": ["/category/controller.py"], "/user/cli.py": ["/user/controller.py"], "/models/__init__.py": ["/config/__init__.py"], "/MyCart/controller.py": ["/models/__init__.py", "/user/session.py", "/category/controller.py"], "/tests/test_controller_category.py": ["/tests/setup.py", "/category/controller.py"], "/tests/test_controller_cart.py": ["/tests/setup.py", "/MyCart/controller.py"]}
24,751,527
gauravndabhade/MyCart
refs/heads/main
/MyCart/cli.py
import os import click from tabulate import tabulate from MyCart.controller import CartController from category.controller import CategoryController from product.controller import ProductController from user.session import UserSession import config from models import db, Product, User, Category, Cart from MyCart.utils import show_welcome, show_bills MODELS = (User, Category, Cart, Product) cart = CartController() user_session = UserSession() product_controller = ProductController() @click.group() @click.version_option("1.0.0") def main(): """MyCart, An E-commerce cli application""" show_welcome() @main.command() def add_item(): """Add new product into cart""" click.echo("Creating new product") name = click.prompt('Please enter product name') click.echo(cart.add(name)) @main.command() def remove_item(): """Remove product from cart""" click.echo("Remove product") name = click.prompt('Please enter product name') click.echo(cart.remove(name)) @main.command() def bill(): """Create bill for your cart items""" show_bills() @main.command() def initdb(): """Initialize database""" db.connect() db.create_tables(MODELS) click.echo('Initialized the database') @main.command() def dropdb(): """Clear/Delete database""" db.drop_tables(MODELS) db.close() click.echo('Dropped the database') if os.path.isfile(config.USER_SECRET_FILE): os.remove(config.USER_SECRET_FILE)
{"/category/category_controller.py": ["/models/__init__.py"], "/MyCart/__main__.py": ["/category/category_cli.py", "/models/__init__.py", "/MyCart/cli.py", "/category/cli.py", "/product/cli.py", "/user/cli.py"], "/user/user_session.py": ["/models/__init__.py"], "/product/product_controller.py": ["/models/__init__.py"], "/MyCart/cart_controller.py": ["/models/__init__.py"], "/MyCart/utils.py": ["/models/__init__.py", "/user/session.py", "/MyCart/controller.py", "/product/controller.py", "/category/controller.py"], "/tests/setup.py": ["/config/__init__.py", "/models/__init__.py"], "/MyCart/cli.py": ["/MyCart/controller.py", "/category/controller.py", "/product/controller.py", "/user/session.py", "/config/__init__.py", "/models/__init__.py", "/MyCart/utils.py"], "/user/controller.py": ["/models/__init__.py", "/user/session.py", "/MyCart/utils.py"], "/tests/test_controller_product.py": ["/tests/setup.py", "/product/controller.py"], "/category/controller.py": ["/models/__init__.py", "/user/session.py"], "/user/session.py": ["/models/__init__.py"], "/tests/test_controller_user.py": ["/tests/setup.py", "/user/controller.py"], "/product/controller.py": ["/models/__init__.py", "/user/session.py", "/category/controller.py"], "/product/cli.py": ["/product/controller.py", "/category/controller.py"], "/category/cli.py": ["/category/controller.py"], "/user/cli.py": ["/user/controller.py"], "/models/__init__.py": ["/config/__init__.py"], "/MyCart/controller.py": ["/models/__init__.py", "/user/session.py", "/category/controller.py"], "/tests/test_controller_category.py": ["/tests/setup.py", "/category/controller.py"], "/tests/test_controller_cart.py": ["/tests/setup.py", "/MyCart/controller.py"]}
24,751,528
gauravndabhade/MyCart
refs/heads/main
/user/controller.py
import peewee from models import User from user.session import UserSession from base.controller import BaseController from MyCart.utils import show_init_database user_session = UserSession() class UserController(BaseController): def create(self, username, password, is_admin): try: user = User(username=username, password=password, is_admin=is_admin) user.save() # Update to offline user session user_session.write_current_user(username, is_admin) return f'User {username} created successful' except peewee.IntegrityError: return f'User {username} already exist!' except peewee.OperationalError: show_init_database() def login(self, username, password): try: user = User.select().where(User.username == username).get() if user and user.username == username: if password == user.password: # Update to offline user session user_session.write_current_user(user.username, user.is_admin) return f'Login successfully for {username}!' else: return f'Incorrect password' else: return f'User not found for {username}' except peewee.DoesNotExist: return f'{username} doesn\'t exists' except peewee.OperationalError: show_init_database() def logout(self): user_session.write_current_user(username=None, is_admin=None) return f'Logout successfully!'
{"/category/category_controller.py": ["/models/__init__.py"], "/MyCart/__main__.py": ["/category/category_cli.py", "/models/__init__.py", "/MyCart/cli.py", "/category/cli.py", "/product/cli.py", "/user/cli.py"], "/user/user_session.py": ["/models/__init__.py"], "/product/product_controller.py": ["/models/__init__.py"], "/MyCart/cart_controller.py": ["/models/__init__.py"], "/MyCart/utils.py": ["/models/__init__.py", "/user/session.py", "/MyCart/controller.py", "/product/controller.py", "/category/controller.py"], "/tests/setup.py": ["/config/__init__.py", "/models/__init__.py"], "/MyCart/cli.py": ["/MyCart/controller.py", "/category/controller.py", "/product/controller.py", "/user/session.py", "/config/__init__.py", "/models/__init__.py", "/MyCart/utils.py"], "/user/controller.py": ["/models/__init__.py", "/user/session.py", "/MyCart/utils.py"], "/tests/test_controller_product.py": ["/tests/setup.py", "/product/controller.py"], "/category/controller.py": ["/models/__init__.py", "/user/session.py"], "/user/session.py": ["/models/__init__.py"], "/tests/test_controller_user.py": ["/tests/setup.py", "/user/controller.py"], "/product/controller.py": ["/models/__init__.py", "/user/session.py", "/category/controller.py"], "/product/cli.py": ["/product/controller.py", "/category/controller.py"], "/category/cli.py": ["/category/controller.py"], "/user/cli.py": ["/user/controller.py"], "/models/__init__.py": ["/config/__init__.py"], "/MyCart/controller.py": ["/models/__init__.py", "/user/session.py", "/category/controller.py"], "/tests/test_controller_category.py": ["/tests/setup.py", "/category/controller.py"], "/tests/test_controller_cart.py": ["/tests/setup.py", "/MyCart/controller.py"]}
24,751,529
gauravndabhade/MyCart
refs/heads/main
/tests/test_controller_product.py
from tests.setup import setup_database from product.controller import ProductController mock_product = { 'name': 'i10', 'price': 10000.0, 'category': 'Car' } def test_create(setup_database): product_controller = ProductController() message = product_controller.create( mock_product['name'], mock_product['category'], mock_product['price']) assert message == 'Product {0} created!'.format(mock_product['name']) def test_remove(setup_database): product_controller = ProductController() message = product_controller.remove( mock_product['name']) assert message == 'Product {0} removed!'.format(mock_product['name']) def test_get_all_product(setup_database): product_controller = ProductController() data = product_controller.get_all_product() assert len(data) == 10
{"/category/category_controller.py": ["/models/__init__.py"], "/MyCart/__main__.py": ["/category/category_cli.py", "/models/__init__.py", "/MyCart/cli.py", "/category/cli.py", "/product/cli.py", "/user/cli.py"], "/user/user_session.py": ["/models/__init__.py"], "/product/product_controller.py": ["/models/__init__.py"], "/MyCart/cart_controller.py": ["/models/__init__.py"], "/MyCart/utils.py": ["/models/__init__.py", "/user/session.py", "/MyCart/controller.py", "/product/controller.py", "/category/controller.py"], "/tests/setup.py": ["/config/__init__.py", "/models/__init__.py"], "/MyCart/cli.py": ["/MyCart/controller.py", "/category/controller.py", "/product/controller.py", "/user/session.py", "/config/__init__.py", "/models/__init__.py", "/MyCart/utils.py"], "/user/controller.py": ["/models/__init__.py", "/user/session.py", "/MyCart/utils.py"], "/tests/test_controller_product.py": ["/tests/setup.py", "/product/controller.py"], "/category/controller.py": ["/models/__init__.py", "/user/session.py"], "/user/session.py": ["/models/__init__.py"], "/tests/test_controller_user.py": ["/tests/setup.py", "/user/controller.py"], "/product/controller.py": ["/models/__init__.py", "/user/session.py", "/category/controller.py"], "/product/cli.py": ["/product/controller.py", "/category/controller.py"], "/category/cli.py": ["/category/controller.py"], "/user/cli.py": ["/user/controller.py"], "/models/__init__.py": ["/config/__init__.py"], "/MyCart/controller.py": ["/models/__init__.py", "/user/session.py", "/category/controller.py"], "/tests/test_controller_category.py": ["/tests/setup.py", "/category/controller.py"], "/tests/test_controller_cart.py": ["/tests/setup.py", "/MyCart/controller.py"]}
24,751,530
gauravndabhade/MyCart
refs/heads/main
/category/controller.py
import peewee from models import Category from user.session import UserSession from base.controller import BaseController user_session = UserSession() class CategoryController(BaseController): def create(self, name): try: user = user_session.current_user() category = Category.create(name=name, user=user) category.save() return f'Category {category.name} created!' except peewee.IntegrityError: return f'Category {name} already exist!' def remove(self, name): try: category = Category.get(Category.name == name) category.delete_instance() return f'Category {category.name} removed!' except peewee.DoesNotExist: return f'{name} doesn\'t exists' def get(self, name): try: category = Category.select().where(Category.name == name).get() return category except peewee.DoesNotExist: return f'{name} doesn\'t exists' def all(self): try: return [cat.name for cat in Category.select()] except peewee.DoesNotExist: return None
{"/category/category_controller.py": ["/models/__init__.py"], "/MyCart/__main__.py": ["/category/category_cli.py", "/models/__init__.py", "/MyCart/cli.py", "/category/cli.py", "/product/cli.py", "/user/cli.py"], "/user/user_session.py": ["/models/__init__.py"], "/product/product_controller.py": ["/models/__init__.py"], "/MyCart/cart_controller.py": ["/models/__init__.py"], "/MyCart/utils.py": ["/models/__init__.py", "/user/session.py", "/MyCart/controller.py", "/product/controller.py", "/category/controller.py"], "/tests/setup.py": ["/config/__init__.py", "/models/__init__.py"], "/MyCart/cli.py": ["/MyCart/controller.py", "/category/controller.py", "/product/controller.py", "/user/session.py", "/config/__init__.py", "/models/__init__.py", "/MyCart/utils.py"], "/user/controller.py": ["/models/__init__.py", "/user/session.py", "/MyCart/utils.py"], "/tests/test_controller_product.py": ["/tests/setup.py", "/product/controller.py"], "/category/controller.py": ["/models/__init__.py", "/user/session.py"], "/user/session.py": ["/models/__init__.py"], "/tests/test_controller_user.py": ["/tests/setup.py", "/user/controller.py"], "/product/controller.py": ["/models/__init__.py", "/user/session.py", "/category/controller.py"], "/product/cli.py": ["/product/controller.py", "/category/controller.py"], "/category/cli.py": ["/category/controller.py"], "/user/cli.py": ["/user/controller.py"], "/models/__init__.py": ["/config/__init__.py"], "/MyCart/controller.py": ["/models/__init__.py", "/user/session.py", "/category/controller.py"], "/tests/test_controller_category.py": ["/tests/setup.py", "/category/controller.py"], "/tests/test_controller_cart.py": ["/tests/setup.py", "/MyCart/controller.py"]}
24,751,531
gauravndabhade/MyCart
refs/heads/main
/user/session.py
import peewee from models import User class UserSession(object): def read_current_user(self): """ Read user data from file (offline session for terminal) Return [username, is_admin] """ try: with open(".current_user.dat", "r") as f: data = f.readline().split(',') if len(data) == 2: return data else: return None, None except FileNotFoundError: return None, None def write_current_user(self, username, is_admin): if username: with open(".current_user.dat", 'w', encoding='utf-8') as f: f.write(username + ',') f.write(str(is_admin)) def current_user(self): try: username, _ = self.read_current_user() user = User.select().where(User.username == username).get() return user except peewee.DoesNotExist: return None
{"/category/category_controller.py": ["/models/__init__.py"], "/MyCart/__main__.py": ["/category/category_cli.py", "/models/__init__.py", "/MyCart/cli.py", "/category/cli.py", "/product/cli.py", "/user/cli.py"], "/user/user_session.py": ["/models/__init__.py"], "/product/product_controller.py": ["/models/__init__.py"], "/MyCart/cart_controller.py": ["/models/__init__.py"], "/MyCart/utils.py": ["/models/__init__.py", "/user/session.py", "/MyCart/controller.py", "/product/controller.py", "/category/controller.py"], "/tests/setup.py": ["/config/__init__.py", "/models/__init__.py"], "/MyCart/cli.py": ["/MyCart/controller.py", "/category/controller.py", "/product/controller.py", "/user/session.py", "/config/__init__.py", "/models/__init__.py", "/MyCart/utils.py"], "/user/controller.py": ["/models/__init__.py", "/user/session.py", "/MyCart/utils.py"], "/tests/test_controller_product.py": ["/tests/setup.py", "/product/controller.py"], "/category/controller.py": ["/models/__init__.py", "/user/session.py"], "/user/session.py": ["/models/__init__.py"], "/tests/test_controller_user.py": ["/tests/setup.py", "/user/controller.py"], "/product/controller.py": ["/models/__init__.py", "/user/session.py", "/category/controller.py"], "/product/cli.py": ["/product/controller.py", "/category/controller.py"], "/category/cli.py": ["/category/controller.py"], "/user/cli.py": ["/user/controller.py"], "/models/__init__.py": ["/config/__init__.py"], "/MyCart/controller.py": ["/models/__init__.py", "/user/session.py", "/category/controller.py"], "/tests/test_controller_category.py": ["/tests/setup.py", "/category/controller.py"], "/tests/test_controller_cart.py": ["/tests/setup.py", "/MyCart/controller.py"]}
24,751,532
gauravndabhade/MyCart
refs/heads/main
/MyCart/__main__.py
import sys from MyCart.cli import main from category.cli import category from product.cli import product from user.cli import user main.add_command(user) main.add_command(category) main.add_command(product) if __name__ == '__main__': args = sys.argv if "--help" in args or len(args) == 1: print("cart") main()
{"/category/category_controller.py": ["/models/__init__.py"], "/MyCart/__main__.py": ["/category/category_cli.py", "/models/__init__.py", "/MyCart/cli.py", "/category/cli.py", "/product/cli.py", "/user/cli.py"], "/user/user_session.py": ["/models/__init__.py"], "/product/product_controller.py": ["/models/__init__.py"], "/MyCart/cart_controller.py": ["/models/__init__.py"], "/MyCart/utils.py": ["/models/__init__.py", "/user/session.py", "/MyCart/controller.py", "/product/controller.py", "/category/controller.py"], "/tests/setup.py": ["/config/__init__.py", "/models/__init__.py"], "/MyCart/cli.py": ["/MyCart/controller.py", "/category/controller.py", "/product/controller.py", "/user/session.py", "/config/__init__.py", "/models/__init__.py", "/MyCart/utils.py"], "/user/controller.py": ["/models/__init__.py", "/user/session.py", "/MyCart/utils.py"], "/tests/test_controller_product.py": ["/tests/setup.py", "/product/controller.py"], "/category/controller.py": ["/models/__init__.py", "/user/session.py"], "/user/session.py": ["/models/__init__.py"], "/tests/test_controller_user.py": ["/tests/setup.py", "/user/controller.py"], "/product/controller.py": ["/models/__init__.py", "/user/session.py", "/category/controller.py"], "/product/cli.py": ["/product/controller.py", "/category/controller.py"], "/category/cli.py": ["/category/controller.py"], "/user/cli.py": ["/user/controller.py"], "/models/__init__.py": ["/config/__init__.py"], "/MyCart/controller.py": ["/models/__init__.py", "/user/session.py", "/category/controller.py"], "/tests/test_controller_category.py": ["/tests/setup.py", "/category/controller.py"], "/tests/test_controller_cart.py": ["/tests/setup.py", "/MyCart/controller.py"]}
24,751,533
gauravndabhade/MyCart
refs/heads/main
/tests/test_controller_user.py
from tests.setup import setup_database from user.controller import UserController mock_user = { 'username' : 'Foo', 'password' : '12345678', 'is_admin' : True } def test_create(setup_database): user_controller = UserController() message = user_controller.create( username=mock_user['username'], password=mock_user['password'], is_admin=mock_user['is_admin']) assert message == 'User {0} already exist!'.format(mock_user['username']) def test_login(setup_database): user_controller = UserController() message = user_controller.login( username=mock_user['username'], password=mock_user['password']) assert message == 'Login successfully for {0}!'.format(mock_user['username']) def test_fail_login(setup_database): user_controller = UserController() message = user_controller.login( username='ABC', # User ABC not available password=mock_user['password']) assert message != '{0} doesn\'t exists'.format(mock_user['username']) def test_fail_login_2(setup_database): user_controller = UserController() message = user_controller.login( username=mock_user['username'], password='password') assert message == 'Incorrect password' def test_logout(setup_database): user_controller = UserController() message = user_controller.logout() assert message == f'Logout successfully!'
{"/category/category_controller.py": ["/models/__init__.py"], "/MyCart/__main__.py": ["/category/category_cli.py", "/models/__init__.py", "/MyCart/cli.py", "/category/cli.py", "/product/cli.py", "/user/cli.py"], "/user/user_session.py": ["/models/__init__.py"], "/product/product_controller.py": ["/models/__init__.py"], "/MyCart/cart_controller.py": ["/models/__init__.py"], "/MyCart/utils.py": ["/models/__init__.py", "/user/session.py", "/MyCart/controller.py", "/product/controller.py", "/category/controller.py"], "/tests/setup.py": ["/config/__init__.py", "/models/__init__.py"], "/MyCart/cli.py": ["/MyCart/controller.py", "/category/controller.py", "/product/controller.py", "/user/session.py", "/config/__init__.py", "/models/__init__.py", "/MyCart/utils.py"], "/user/controller.py": ["/models/__init__.py", "/user/session.py", "/MyCart/utils.py"], "/tests/test_controller_product.py": ["/tests/setup.py", "/product/controller.py"], "/category/controller.py": ["/models/__init__.py", "/user/session.py"], "/user/session.py": ["/models/__init__.py"], "/tests/test_controller_user.py": ["/tests/setup.py", "/user/controller.py"], "/product/controller.py": ["/models/__init__.py", "/user/session.py", "/category/controller.py"], "/product/cli.py": ["/product/controller.py", "/category/controller.py"], "/category/cli.py": ["/category/controller.py"], "/user/cli.py": ["/user/controller.py"], "/models/__init__.py": ["/config/__init__.py"], "/MyCart/controller.py": ["/models/__init__.py", "/user/session.py", "/category/controller.py"], "/tests/test_controller_category.py": ["/tests/setup.py", "/category/controller.py"], "/tests/test_controller_cart.py": ["/tests/setup.py", "/MyCart/controller.py"]}
24,751,534
gauravndabhade/MyCart
refs/heads/main
/setup.py
import pathlib from io import open from os import path from setuptools import find_packages, setup HERE = pathlib.Path(__file__).parent README = (HERE / "README.md").read_text() with open(path.join(HERE, 'requirements.txt'), encoding='utf-8') as f: all_reqs = f.read().split('\n') install_requires = [x.strip() for x in all_reqs if ('git+' not in x) and ( not x.startswith('#')) and (not x.startswith('-'))] dependency_links = [x.strip().replace('git+', '') for x in all_reqs if 'git+' not in x] setup( name='MyCart', description='A simple commandline app for products in cart', version='1.0.0', packages=find_packages(), install_requires=install_requires, python_requires='>=3', entry_points=''' [console_scripts] mycart=MyCart.__main__:main ''', author="Gaurav Dabhade", keyword="products, mycart, e-commers", long_description=README, long_description_content_type="text/markdown", license='MIT', url='https://github.com/gauravndabhade/MyCart', download_url='https://github.com/gauravndabhade/MyCart', dependency_links=dependency_links, author_email='gauravndabhade@gmail.com', classifiers=[ "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.7", ] )
{"/category/category_controller.py": ["/models/__init__.py"], "/MyCart/__main__.py": ["/category/category_cli.py", "/models/__init__.py", "/MyCart/cli.py", "/category/cli.py", "/product/cli.py", "/user/cli.py"], "/user/user_session.py": ["/models/__init__.py"], "/product/product_controller.py": ["/models/__init__.py"], "/MyCart/cart_controller.py": ["/models/__init__.py"], "/MyCart/utils.py": ["/models/__init__.py", "/user/session.py", "/MyCart/controller.py", "/product/controller.py", "/category/controller.py"], "/tests/setup.py": ["/config/__init__.py", "/models/__init__.py"], "/MyCart/cli.py": ["/MyCart/controller.py", "/category/controller.py", "/product/controller.py", "/user/session.py", "/config/__init__.py", "/models/__init__.py", "/MyCart/utils.py"], "/user/controller.py": ["/models/__init__.py", "/user/session.py", "/MyCart/utils.py"], "/tests/test_controller_product.py": ["/tests/setup.py", "/product/controller.py"], "/category/controller.py": ["/models/__init__.py", "/user/session.py"], "/user/session.py": ["/models/__init__.py"], "/tests/test_controller_user.py": ["/tests/setup.py", "/user/controller.py"], "/product/controller.py": ["/models/__init__.py", "/user/session.py", "/category/controller.py"], "/product/cli.py": ["/product/controller.py", "/category/controller.py"], "/category/cli.py": ["/category/controller.py"], "/user/cli.py": ["/user/controller.py"], "/models/__init__.py": ["/config/__init__.py"], "/MyCart/controller.py": ["/models/__init__.py", "/user/session.py", "/category/controller.py"], "/tests/test_controller_category.py": ["/tests/setup.py", "/category/controller.py"], "/tests/test_controller_cart.py": ["/tests/setup.py", "/MyCart/controller.py"]}
24,751,535
gauravndabhade/MyCart
refs/heads/main
/product/controller.py
import peewee from models import Product from user.session import UserSession from category.controller import CategoryController from base.controller import BaseController user_session = UserSession() class ProductController(BaseController): def get_all_product(self): data = [[p.name, p.price] for p in Product.select()] return data def create(self, name, category, price): user = user_session.current_user() category = CategoryController().get(category) try: product = Product.create(name=name, user=user, price=price, category=category) product.save() return f'Product {product.name} created!' except peewee.IntegrityError: return f'Product {name} already exist!' def remove(self, name): product = Product.get(Product.name == name) product.delete_instance() return f'Product {product.name} removed!'
{"/category/category_controller.py": ["/models/__init__.py"], "/MyCart/__main__.py": ["/category/category_cli.py", "/models/__init__.py", "/MyCart/cli.py", "/category/cli.py", "/product/cli.py", "/user/cli.py"], "/user/user_session.py": ["/models/__init__.py"], "/product/product_controller.py": ["/models/__init__.py"], "/MyCart/cart_controller.py": ["/models/__init__.py"], "/MyCart/utils.py": ["/models/__init__.py", "/user/session.py", "/MyCart/controller.py", "/product/controller.py", "/category/controller.py"], "/tests/setup.py": ["/config/__init__.py", "/models/__init__.py"], "/MyCart/cli.py": ["/MyCart/controller.py", "/category/controller.py", "/product/controller.py", "/user/session.py", "/config/__init__.py", "/models/__init__.py", "/MyCart/utils.py"], "/user/controller.py": ["/models/__init__.py", "/user/session.py", "/MyCart/utils.py"], "/tests/test_controller_product.py": ["/tests/setup.py", "/product/controller.py"], "/category/controller.py": ["/models/__init__.py", "/user/session.py"], "/user/session.py": ["/models/__init__.py"], "/tests/test_controller_user.py": ["/tests/setup.py", "/user/controller.py"], "/product/controller.py": ["/models/__init__.py", "/user/session.py", "/category/controller.py"], "/product/cli.py": ["/product/controller.py", "/category/controller.py"], "/category/cli.py": ["/category/controller.py"], "/user/cli.py": ["/user/controller.py"], "/models/__init__.py": ["/config/__init__.py"], "/MyCart/controller.py": ["/models/__init__.py", "/user/session.py", "/category/controller.py"], "/tests/test_controller_category.py": ["/tests/setup.py", "/category/controller.py"], "/tests/test_controller_cart.py": ["/tests/setup.py", "/MyCart/controller.py"]}
24,751,536
gauravndabhade/MyCart
refs/heads/main
/product/cli.py
import click from product.controller import ProductController from category.controller import CategoryController product_controller = ProductController() category_controller = CategoryController() @click.group() def product(): """Manage products""" pass @ product.command() def create(): """Create new product""" categories = category_controller.all() if categories: click.echo("Creating new product") name = click.prompt('Enter product name') price = click.prompt('Enter price') category = click.prompt('Choose a category from list:', type=click.Choice(categories)) click.echo(product_controller.create(name, category, price)) else: click.echo('Category list is empty. Add new categories...') @ product.command() def remove(): """Remove product""" name = click.prompt('Enter product name') click.echo(product_controller.remove(name))
{"/category/category_controller.py": ["/models/__init__.py"], "/MyCart/__main__.py": ["/category/category_cli.py", "/models/__init__.py", "/MyCart/cli.py", "/category/cli.py", "/product/cli.py", "/user/cli.py"], "/user/user_session.py": ["/models/__init__.py"], "/product/product_controller.py": ["/models/__init__.py"], "/MyCart/cart_controller.py": ["/models/__init__.py"], "/MyCart/utils.py": ["/models/__init__.py", "/user/session.py", "/MyCart/controller.py", "/product/controller.py", "/category/controller.py"], "/tests/setup.py": ["/config/__init__.py", "/models/__init__.py"], "/MyCart/cli.py": ["/MyCart/controller.py", "/category/controller.py", "/product/controller.py", "/user/session.py", "/config/__init__.py", "/models/__init__.py", "/MyCart/utils.py"], "/user/controller.py": ["/models/__init__.py", "/user/session.py", "/MyCart/utils.py"], "/tests/test_controller_product.py": ["/tests/setup.py", "/product/controller.py"], "/category/controller.py": ["/models/__init__.py", "/user/session.py"], "/user/session.py": ["/models/__init__.py"], "/tests/test_controller_user.py": ["/tests/setup.py", "/user/controller.py"], "/product/controller.py": ["/models/__init__.py", "/user/session.py", "/category/controller.py"], "/product/cli.py": ["/product/controller.py", "/category/controller.py"], "/category/cli.py": ["/category/controller.py"], "/user/cli.py": ["/user/controller.py"], "/models/__init__.py": ["/config/__init__.py"], "/MyCart/controller.py": ["/models/__init__.py", "/user/session.py", "/category/controller.py"], "/tests/test_controller_category.py": ["/tests/setup.py", "/category/controller.py"], "/tests/test_controller_cart.py": ["/tests/setup.py", "/MyCart/controller.py"]}
24,751,537
gauravndabhade/MyCart
refs/heads/main
/config/__init__.py
USER_SECRET_FILE = '.current_user.dat' TESTING = True DATABASE = 'sqlite3.db' TEST_DATABASE = 'test.db'
{"/category/category_controller.py": ["/models/__init__.py"], "/MyCart/__main__.py": ["/category/category_cli.py", "/models/__init__.py", "/MyCart/cli.py", "/category/cli.py", "/product/cli.py", "/user/cli.py"], "/user/user_session.py": ["/models/__init__.py"], "/product/product_controller.py": ["/models/__init__.py"], "/MyCart/cart_controller.py": ["/models/__init__.py"], "/MyCart/utils.py": ["/models/__init__.py", "/user/session.py", "/MyCart/controller.py", "/product/controller.py", "/category/controller.py"], "/tests/setup.py": ["/config/__init__.py", "/models/__init__.py"], "/MyCart/cli.py": ["/MyCart/controller.py", "/category/controller.py", "/product/controller.py", "/user/session.py", "/config/__init__.py", "/models/__init__.py", "/MyCart/utils.py"], "/user/controller.py": ["/models/__init__.py", "/user/session.py", "/MyCart/utils.py"], "/tests/test_controller_product.py": ["/tests/setup.py", "/product/controller.py"], "/category/controller.py": ["/models/__init__.py", "/user/session.py"], "/user/session.py": ["/models/__init__.py"], "/tests/test_controller_user.py": ["/tests/setup.py", "/user/controller.py"], "/product/controller.py": ["/models/__init__.py", "/user/session.py", "/category/controller.py"], "/product/cli.py": ["/product/controller.py", "/category/controller.py"], "/category/cli.py": ["/category/controller.py"], "/user/cli.py": ["/user/controller.py"], "/models/__init__.py": ["/config/__init__.py"], "/MyCart/controller.py": ["/models/__init__.py", "/user/session.py", "/category/controller.py"], "/tests/test_controller_category.py": ["/tests/setup.py", "/category/controller.py"], "/tests/test_controller_cart.py": ["/tests/setup.py", "/MyCart/controller.py"]}
24,751,538
gauravndabhade/MyCart
refs/heads/main
/category/cli.py
import click from category.controller import CategoryController @click.group() def category(): """Manage category""" pass @category.command() def create(): """Create new category""" name = click.prompt('Enter category name') click.echo(CategoryController().create(name)) @category.command() def remove(): """Remove category""" name = click.prompt('Enter category name') click.echo(CategoryController().remove(name))
{"/category/category_controller.py": ["/models/__init__.py"], "/MyCart/__main__.py": ["/category/category_cli.py", "/models/__init__.py", "/MyCart/cli.py", "/category/cli.py", "/product/cli.py", "/user/cli.py"], "/user/user_session.py": ["/models/__init__.py"], "/product/product_controller.py": ["/models/__init__.py"], "/MyCart/cart_controller.py": ["/models/__init__.py"], "/MyCart/utils.py": ["/models/__init__.py", "/user/session.py", "/MyCart/controller.py", "/product/controller.py", "/category/controller.py"], "/tests/setup.py": ["/config/__init__.py", "/models/__init__.py"], "/MyCart/cli.py": ["/MyCart/controller.py", "/category/controller.py", "/product/controller.py", "/user/session.py", "/config/__init__.py", "/models/__init__.py", "/MyCart/utils.py"], "/user/controller.py": ["/models/__init__.py", "/user/session.py", "/MyCart/utils.py"], "/tests/test_controller_product.py": ["/tests/setup.py", "/product/controller.py"], "/category/controller.py": ["/models/__init__.py", "/user/session.py"], "/user/session.py": ["/models/__init__.py"], "/tests/test_controller_user.py": ["/tests/setup.py", "/user/controller.py"], "/product/controller.py": ["/models/__init__.py", "/user/session.py", "/category/controller.py"], "/product/cli.py": ["/product/controller.py", "/category/controller.py"], "/category/cli.py": ["/category/controller.py"], "/user/cli.py": ["/user/controller.py"], "/models/__init__.py": ["/config/__init__.py"], "/MyCart/controller.py": ["/models/__init__.py", "/user/session.py", "/category/controller.py"], "/tests/test_controller_category.py": ["/tests/setup.py", "/category/controller.py"], "/tests/test_controller_cart.py": ["/tests/setup.py", "/MyCart/controller.py"]}
24,751,539
gauravndabhade/MyCart
refs/heads/main
/user/cli.py
import click from user.controller import UserController user_controller = UserController() @click.group() def user(): """Manage user""" pass @user.command() def create(): """Creating new user""" click.echo("Creating new user!") username = click.prompt('Please enter a username') password = click.prompt('Please enter password', hide_input=True) re_password = click.prompt('Please reenter password', hide_input=True) is_admin = 'y' == click.prompt('Creating account as Admin?', type=click.Choice(['y', 'n']), default='n') if password == re_password: click.echo(user_controller.create(username, password, is_admin)) else: click.echo('Password mismatch!') @user.command() def login(): """User login""" click.echo("User login!") username = click.prompt('Please enter a username') password = click.prompt('Please enter password', hide_input=True) click.echo(user_controller.login(username, password)) @user.command() def logout(**kwargs): """User logout""" click.echo(user_controller.logout())
{"/category/category_controller.py": ["/models/__init__.py"], "/MyCart/__main__.py": ["/category/category_cli.py", "/models/__init__.py", "/MyCart/cli.py", "/category/cli.py", "/product/cli.py", "/user/cli.py"], "/user/user_session.py": ["/models/__init__.py"], "/product/product_controller.py": ["/models/__init__.py"], "/MyCart/cart_controller.py": ["/models/__init__.py"], "/MyCart/utils.py": ["/models/__init__.py", "/user/session.py", "/MyCart/controller.py", "/product/controller.py", "/category/controller.py"], "/tests/setup.py": ["/config/__init__.py", "/models/__init__.py"], "/MyCart/cli.py": ["/MyCart/controller.py", "/category/controller.py", "/product/controller.py", "/user/session.py", "/config/__init__.py", "/models/__init__.py", "/MyCart/utils.py"], "/user/controller.py": ["/models/__init__.py", "/user/session.py", "/MyCart/utils.py"], "/tests/test_controller_product.py": ["/tests/setup.py", "/product/controller.py"], "/category/controller.py": ["/models/__init__.py", "/user/session.py"], "/user/session.py": ["/models/__init__.py"], "/tests/test_controller_user.py": ["/tests/setup.py", "/user/controller.py"], "/product/controller.py": ["/models/__init__.py", "/user/session.py", "/category/controller.py"], "/product/cli.py": ["/product/controller.py", "/category/controller.py"], "/category/cli.py": ["/category/controller.py"], "/user/cli.py": ["/user/controller.py"], "/models/__init__.py": ["/config/__init__.py"], "/MyCart/controller.py": ["/models/__init__.py", "/user/session.py", "/category/controller.py"], "/tests/test_controller_category.py": ["/tests/setup.py", "/category/controller.py"], "/tests/test_controller_cart.py": ["/tests/setup.py", "/MyCart/controller.py"]}
24,751,540
gauravndabhade/MyCart
refs/heads/main
/models/__init__.py
from peewee import SqliteDatabase, Model from peewee import CharField, ForeignKeyField, TextField, DateTimeField, BooleanField, BigAutoField, FloatField import datetime import config db = SqliteDatabase(config.DATABASE) class BaseModel(Model): class Meta: database = db class User(BaseModel): username = CharField(unique=True) password = CharField() is_admin = BooleanField(default=False) created_date = DateTimeField(default=datetime.datetime.now) class Category(BaseModel): id = BigAutoField() name = CharField(unique=True) user = ForeignKeyField(User, backref='categories') created_date = DateTimeField(default=datetime.datetime.now) class Product(BaseModel): id = BigAutoField() name = CharField(unique=True) price = FloatField() user = ForeignKeyField(User, backref='products') category = ForeignKeyField( Category, backref='products', null=True) created_date = DateTimeField(default=datetime.datetime.now) class Cart(BaseModel): id = BigAutoField() user = ForeignKeyField(User, backref='carts') product = ForeignKeyField(Product, backref='carts') created_date = DateTimeField(default=datetime.datetime.now)
{"/category/category_controller.py": ["/models/__init__.py"], "/MyCart/__main__.py": ["/category/category_cli.py", "/models/__init__.py", "/MyCart/cli.py", "/category/cli.py", "/product/cli.py", "/user/cli.py"], "/user/user_session.py": ["/models/__init__.py"], "/product/product_controller.py": ["/models/__init__.py"], "/MyCart/cart_controller.py": ["/models/__init__.py"], "/MyCart/utils.py": ["/models/__init__.py", "/user/session.py", "/MyCart/controller.py", "/product/controller.py", "/category/controller.py"], "/tests/setup.py": ["/config/__init__.py", "/models/__init__.py"], "/MyCart/cli.py": ["/MyCart/controller.py", "/category/controller.py", "/product/controller.py", "/user/session.py", "/config/__init__.py", "/models/__init__.py", "/MyCart/utils.py"], "/user/controller.py": ["/models/__init__.py", "/user/session.py", "/MyCart/utils.py"], "/tests/test_controller_product.py": ["/tests/setup.py", "/product/controller.py"], "/category/controller.py": ["/models/__init__.py", "/user/session.py"], "/user/session.py": ["/models/__init__.py"], "/tests/test_controller_user.py": ["/tests/setup.py", "/user/controller.py"], "/product/controller.py": ["/models/__init__.py", "/user/session.py", "/category/controller.py"], "/product/cli.py": ["/product/controller.py", "/category/controller.py"], "/category/cli.py": ["/category/controller.py"], "/user/cli.py": ["/user/controller.py"], "/models/__init__.py": ["/config/__init__.py"], "/MyCart/controller.py": ["/models/__init__.py", "/user/session.py", "/category/controller.py"], "/tests/test_controller_category.py": ["/tests/setup.py", "/category/controller.py"], "/tests/test_controller_cart.py": ["/tests/setup.py", "/MyCart/controller.py"]}
24,751,541
gauravndabhade/MyCart
refs/heads/main
/MyCart/controller.py
import peewee from models import Cart, User, Product from user.session import UserSession from category.controller import CategoryController from base.controller import BaseController user_session = UserSession() class CartController(BaseController): def get_cart_products(self, username): u = User.select().where(User.username == username).get() data = [[c.product.name, c.product.price] for c in Cart.select().where(Cart.user == u.id)] return data def add(self, name): user = user_session.current_user() try: username, _ = user_session.read_current_user() user = User.select().where(User.username == username).get() product = Product.select().where(Product.name == name).get() cart = Cart.create(user=user, product=product) cart.save() return f'Product {product.name} added to cart!' except peewee.DoesNotExist: return f'Product {name} not available' def remove(self, name): try: username, _ = user_session.read_current_user() user = User.select().where(User.username == username).get() product = Product.select().where(Product.name == name).get() cart_item = Cart.get(Cart.user == user.id, Cart.product == product.id) cart_item.delete_instance() return f'Product {product.name} removed from cart!' except peewee.DoesNotExist: return f'Product {name} not available'
{"/category/category_controller.py": ["/models/__init__.py"], "/MyCart/__main__.py": ["/category/category_cli.py", "/models/__init__.py", "/MyCart/cli.py", "/category/cli.py", "/product/cli.py", "/user/cli.py"], "/user/user_session.py": ["/models/__init__.py"], "/product/product_controller.py": ["/models/__init__.py"], "/MyCart/cart_controller.py": ["/models/__init__.py"], "/MyCart/utils.py": ["/models/__init__.py", "/user/session.py", "/MyCart/controller.py", "/product/controller.py", "/category/controller.py"], "/tests/setup.py": ["/config/__init__.py", "/models/__init__.py"], "/MyCart/cli.py": ["/MyCart/controller.py", "/category/controller.py", "/product/controller.py", "/user/session.py", "/config/__init__.py", "/models/__init__.py", "/MyCart/utils.py"], "/user/controller.py": ["/models/__init__.py", "/user/session.py", "/MyCart/utils.py"], "/tests/test_controller_product.py": ["/tests/setup.py", "/product/controller.py"], "/category/controller.py": ["/models/__init__.py", "/user/session.py"], "/user/session.py": ["/models/__init__.py"], "/tests/test_controller_user.py": ["/tests/setup.py", "/user/controller.py"], "/product/controller.py": ["/models/__init__.py", "/user/session.py", "/category/controller.py"], "/product/cli.py": ["/product/controller.py", "/category/controller.py"], "/category/cli.py": ["/category/controller.py"], "/user/cli.py": ["/user/controller.py"], "/models/__init__.py": ["/config/__init__.py"], "/MyCart/controller.py": ["/models/__init__.py", "/user/session.py", "/category/controller.py"], "/tests/test_controller_category.py": ["/tests/setup.py", "/category/controller.py"], "/tests/test_controller_cart.py": ["/tests/setup.py", "/MyCart/controller.py"]}
24,751,542
gauravndabhade/MyCart
refs/heads/main
/tests/test_controller_category.py
from tests.setup import setup_database from category.controller import CategoryController mock_category = { 'name': 'Furniture', } mock_category_2 = { 'name': 'Tables', } def test_create(setup_database): category_controller = CategoryController() message = category_controller.create( mock_category['name']) assert message == 'Category {0} created!'.format(mock_category['name']) def test_remove(setup_database): category_controller = CategoryController() message = category_controller.remove( mock_category['name']) assert message == 'Category {0} removed!'.format(mock_category['name']) def test_get(setup_database): category_controller = CategoryController() category = category_controller.get(name="Books") assert category.name == 'Books' # def test_fail_get(setup_database): # category_controller = CategoryController() # message = category_controller.get(name=mock_category_2['name']) # assert message == '{0} doesn\'t exists'.format(mock_category_2['name']) # def test_fail_create(setup_database): # category_controller = CategoryController() # message = category_controller.create( # mock_category['name']) # assert message == 'Category {0} already exist!'.format(mock_category['name'])
{"/category/category_controller.py": ["/models/__init__.py"], "/MyCart/__main__.py": ["/category/category_cli.py", "/models/__init__.py", "/MyCart/cli.py", "/category/cli.py", "/product/cli.py", "/user/cli.py"], "/user/user_session.py": ["/models/__init__.py"], "/product/product_controller.py": ["/models/__init__.py"], "/MyCart/cart_controller.py": ["/models/__init__.py"], "/MyCart/utils.py": ["/models/__init__.py", "/user/session.py", "/MyCart/controller.py", "/product/controller.py", "/category/controller.py"], "/tests/setup.py": ["/config/__init__.py", "/models/__init__.py"], "/MyCart/cli.py": ["/MyCart/controller.py", "/category/controller.py", "/product/controller.py", "/user/session.py", "/config/__init__.py", "/models/__init__.py", "/MyCart/utils.py"], "/user/controller.py": ["/models/__init__.py", "/user/session.py", "/MyCart/utils.py"], "/tests/test_controller_product.py": ["/tests/setup.py", "/product/controller.py"], "/category/controller.py": ["/models/__init__.py", "/user/session.py"], "/user/session.py": ["/models/__init__.py"], "/tests/test_controller_user.py": ["/tests/setup.py", "/user/controller.py"], "/product/controller.py": ["/models/__init__.py", "/user/session.py", "/category/controller.py"], "/product/cli.py": ["/product/controller.py", "/category/controller.py"], "/category/cli.py": ["/category/controller.py"], "/user/cli.py": ["/user/controller.py"], "/models/__init__.py": ["/config/__init__.py"], "/MyCart/controller.py": ["/models/__init__.py", "/user/session.py", "/category/controller.py"], "/tests/test_controller_category.py": ["/tests/setup.py", "/category/controller.py"], "/tests/test_controller_cart.py": ["/tests/setup.py", "/MyCart/controller.py"]}
24,751,543
gauravndabhade/MyCart
refs/heads/main
/tests/test_controller_cart.py
from tests.setup import setup_database from MyCart.controller import CartController mock_product = { 'name': 'The Secret', 'price': 1000.0, 'category': 'Books' } def test_add_product(setup_database): cart_controller = CartController() message = cart_controller.add( mock_product['name']) assert message == 'Product {0} added to cart!'.format(mock_product['name']) def test_remove(setup_database): cart_controller = CartController() message = cart_controller.remove( mock_product['name']) assert message == 'Product {0} removed from cart!'.format(mock_product['name']) # def test_fail_remove(setup_database): # cart_controller = CartController() # message = cart_controller.remove( # mock_product['name']) # assert message == 'Product {0} not available'.format(mock_product['name'])
{"/category/category_controller.py": ["/models/__init__.py"], "/MyCart/__main__.py": ["/category/category_cli.py", "/models/__init__.py", "/MyCart/cli.py", "/category/cli.py", "/product/cli.py", "/user/cli.py"], "/user/user_session.py": ["/models/__init__.py"], "/product/product_controller.py": ["/models/__init__.py"], "/MyCart/cart_controller.py": ["/models/__init__.py"], "/MyCart/utils.py": ["/models/__init__.py", "/user/session.py", "/MyCart/controller.py", "/product/controller.py", "/category/controller.py"], "/tests/setup.py": ["/config/__init__.py", "/models/__init__.py"], "/MyCart/cli.py": ["/MyCart/controller.py", "/category/controller.py", "/product/controller.py", "/user/session.py", "/config/__init__.py", "/models/__init__.py", "/MyCart/utils.py"], "/user/controller.py": ["/models/__init__.py", "/user/session.py", "/MyCart/utils.py"], "/tests/test_controller_product.py": ["/tests/setup.py", "/product/controller.py"], "/category/controller.py": ["/models/__init__.py", "/user/session.py"], "/user/session.py": ["/models/__init__.py"], "/tests/test_controller_user.py": ["/tests/setup.py", "/user/controller.py"], "/product/controller.py": ["/models/__init__.py", "/user/session.py", "/category/controller.py"], "/product/cli.py": ["/product/controller.py", "/category/controller.py"], "/category/cli.py": ["/category/controller.py"], "/user/cli.py": ["/user/controller.py"], "/models/__init__.py": ["/config/__init__.py"], "/MyCart/controller.py": ["/models/__init__.py", "/user/session.py", "/category/controller.py"], "/tests/test_controller_category.py": ["/tests/setup.py", "/category/controller.py"], "/tests/test_controller_cart.py": ["/tests/setup.py", "/MyCart/controller.py"]}
24,864,268
agentsnoop/pysshclient
refs/heads/intial
/response.py
class Response(object): def __init__(self, pid, code, stdout, stderr, obj=None): super(Response, self).__init__() self.pid = pid self.code = code self.stdout = stdout self.stderr = stderr self.object = obj @property def success(self): return self._code == 0
{"/__init__.py": ["/response.py"]}
24,864,269
agentsnoop/pysshclient
refs/heads/intial
/__init__.py
# This is a test import time import os import socket import tempfile import paramiko from scp import SCPClient from response import Response CMD_PS_GREP = "ps -lfp {pid} | grep {pid}" class SshClient(object): def __init__(self, host, port=22, user="root", password=None, timeout=5, load_keys=False): self._client = None self._scp_client = None self._host = host self._port = port self._user = user self._password = password self._timeout = timeout self._load_keys = load_keys @property def connected(self): if self._client: try: transport = self._client.get_transport() if transport and transport.is_active(): transport.send_ignore() return True except EOFError as e: pass return False def connect(self, retry_count=5): self._client = paramiko.SSHClient() self._client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) if self._password is None: self._client.load_system_host_keys() if not self._client: return False attempt = 0 while attempt < retry_count: if self._connect(): return True attempt += 1 time.sleep(5.0) return False def _connect(self): try: self._client.connect( self._host, self._port, self._user, self._password, timeout=self._timeout, allow_agent=(self._password is None), look_for_keys=(self._password is None)) # self._client.get_transport().set_keepalive(1) # if self._scp_client: # self._scp_client = SCPClient(self._client.get_transport()) return True except paramiko.BadHostKeyException as e1: print("Bad Host Key for {host}:{port} as {user}: {error}".format(host=self._host, port=self._port, user=self._user, error=e1)) except paramiko.AuthenticationException as e2: print("Bad Authentication for {host}:{port} as {user}: {error}".format(host=self._host, port=self._port, user=self._user, error=e2)) except paramiko.SSHException as e3: print("SSH Exception for {host}:{port} as {user}: {error}".format(host=self._host, port=self._port, user=self._user, error=e3)) except socket.error as e4: print("Socket error for {host}:{port} as {user}: {error}".format(host=self._host, port=self._port, user=self._user, error=e4)) except Exception as e5: print(type(e5)) print("Unable to connect to {host}:{port} as {user}: {error}".format(host=self._host, port=self._port, user=self._user, error=e5)) return False def disconnect(self): """Disconnect SSH session, if active""" if self._client: try: self._client.close() except Exception: pass self._client = None def run_and_wait(self, command, search, max_time=60, redirect=""): (pid,) = self.run(command, redirect, background=True, max_wait=5) return self.wait_for_remote_task(pid, search, max_time=max_time) def run(self, command, redirect="", background=False, max_wait=None): """ Run command on remote machine. Output redirection, whether to run in the background, how long to wait for output, and the response type can all be set. :param string command: Command to execute remotely :param string redirect: Output redirect paramters, if desired. :param boolean background: Whether or not to run the command in the background, and not wait for the result of the command. :param float max_wait: Maximum time to wait for output from the command. None allows for an unlimited amount of time. :param int response_type: Which data to output from the command. Logical or values together to get more data :return: One or more values based on response type: (RES_PID, RES_CODE, RES_SUCCESS, RES_STDOUT, RES_STDERR) :rtype: tuple """ stdout = None stderr = None pid = -1 code = -999 pre_command = "echo $$; exec" post_command = "" if background: redirect = "> /dev/null 2>&1" if not redirect else redirect parts = redirect.split() if parts[0] != ">": parts.insert(0, ">") if len(parts) == 3 and parts[2] != "2>&1": parts[2] = "2>&1" if len(parts) == 2: parts.append("2>&1") redirect = " ".join(parts) pre_command = "" post_command = "& echo $!" if self.connected or self.connect(): try: tmp_file = None if "&&" in command or "||" in command or ";" in command: tmp_file = tempfile.NamedTemporaryFile(delete=False) tmp_file.write("#!/bin/sh\n\n") tmp_file.write(command) tmp_file.close() self.put_file(tmp_file.name, "/tmp") os.unlink(tmp_file.name) # self._client.exec_command("echo '#!/bin/sh\n\n{command}' > /tmp/cmd.sh; chmod +x /tmp/cmd.sh".format(command=command)) command = "sh /tmp/{filename}".format(filename=os.path.basename(tmp_file.name)) cmd = "{pre} {command} {redirect} {post}".format(pre=pre_command, command=command, redirect=redirect, post=post_command) start_time = time.time() stdin_obj, stdout_obj, stderr_obj = self._client.exec_command(cmd) # If channel stays open longer than desired while max_wait and not stdout_obj.channel.eof_received: time.sleep(1) if time.time() - start_time > max_wait: stdout_obj.channel.close() if not stderr_obj.channel.eof_received: stderr_obj.channel.close() break code = stdout_obj.channel.recv_exit_status() stderr = stderr_obj.readlines() stdout = stdout_obj.readlines() if stdout: pid = stdout[0].strip() stdout = [l.strip() for l in stdout[1:]] if stderr: stderr = [l.strip() for l in stderr] if tmp_file: self._client.exec_command("rm -f /tmp/{filename}".format(filename=os.path.basename(tmp_file.name))) except Exception as e: print("Encountered a problem while performing SSH ({command}): {error}".format(command=command, error=str(e))) return Response(obj=None, pid=pid, code=code, stdout=stdout, stderr=stderr) # def get_file(self, src, dst, verify=False): # return scp_io.get_file(src, dst, self._host, self._port, self._user, self._password) # def put_file(self, src, dst, owner=None, group=None, verify=False): # return scp_io.put_file(src, dst, self._host, self._port, self._user, self._password, owner=owner, group=group) def get_file(self, src, dst, recursive=False, preserve_times=False, verify=False): try: if not self._scp_client: self._scp_client = SCPClient(self._client.get_transport()) self._scp_client.get(remote_path=src, local_path=dst, recursive=recursive, preserve_times=preserve_times) return True except Exception as e: print("Encountered a problem while doing SCP: {error}".format(error=str(e))) self._scp_client = None return False def put_file(self, src, dst="", permissions=None, owner=None, group=None, max_sessions=999, preserve_times=False, verify=False): if not self._create_parent(dst, max_sessions): return False try: if not self._scp_client: self._scp_client = SCPClient(self._client.get_transport()) self._scp_client.put(src, remote_path=dst, recursive=os.path.isdir(src), preserve_times=preserve_times) except Exception as e: print("Encountered a problem performing SCP: {error}".format(error=str(e))) self._scp_client = None return False self._set_permission(owner, group, permissions, dst, max_sessions) return True def get_file2(self, src, dst, checksum=None, max_attempts=None): try: if not self._scp_client: self._scp_client = SCPClient(self._client.get_transport()) except Exception as e: try: self._scp_client = SCPClient(self._client.get_transport()) except Exception as e: print("Encountered a problem while doing SCP: {error}".format(error=str(e))) return False file_io.makedirs(os.path.dirname(dst)) if not checksum: checksum = self.get_checksum(src) success = os.path.exists(dst) and file_io.get_md5(dst) == checksum if success: print("{dst} already present...skipping".format(dst=dst)) return True print("Getting {src} --> {dst}".format(src=src, dst=dst)) attempts = 0 while not success: attempts += 1 if max_attempts and attempts > max_attempts: return False self._scp_client.get(remote_path=src, local_path=dst) success = file_io.get_md5(dst) == checksum time.sleep(1) return True def put_file2(self, src, dst="", checksum=None, max_attempts=None, owner=None, group=None, permissions=None, max_sessions=999): try: if not self._scp_client: self._scp_client = SCPClient(self._client.get_transport()) except Exception as e: try: self._scp_client = SCPClient(self._client.get_transport()) except Exception as e: print("Encountered a problem while doing SCP: {error}".format(error=str(e))) return False if not self._create_parent(dst, max_sessions): return False self.run("chown -R {owner}:{group} {path}".format(owner=owner, group=group, path=dst)) if not checksum: checksum = file_io.get_md5(src) success = self.get_checksum(dst) == checksum if success: print("{dst} already present...skipping".format(dst=dst)) return True print("Putting {src} --> {dst}".format(src=src, dst=dst)) attempts = 0 while not success: attempts += 1 if max_attempts and attempts > max_attempts: return False self._client.put_file(src, remote_path=dst, recursive=os.path.isdir(src)) success = self.get_checksum(dst) == checksum time.sleep(1) self._set_permission(owner, group, permissions, dst, max_sessions) return True def wait_for_remote_task(self, pid, process_name, max_time, sleep_time=60, msg=None): """ Waits until a process has finished processing on the remote machine, based on PID and process name. It will sleep up until the max_time specified, sleeping every x seconds defined by sleep_time. A custom message can be specified by msg. :param string/int pid: PID of process to monitor :param string process_name: Name of process to match to PID, for extra verification :param float max_time: Maximum amount of time to wait for process to finish :param float sleep_time: Time to sleep inbetween checksum :param string msg: Custom message to display while waiting :return: Whether the process successfully completed in the alloted time or not :rtype: boolean """ if msg is None: msg = "Waiting for {pid} to complete" msg = msg.format(pid=pid) start_time = time.time() running = self.check_remote_process(pid, process_name) while running: if max_time and time.time()-start_time > max_time: print("Time has elapsed waiting for process, exiting") return False print("{msg}... Found [{pid}]".format(msg=msg, pid=pid)) running = self.check_remote_process(pid, process_name) time.sleep(sleep_time) return True def check_remote_process(self, pid, process_name): stdout = self.run(CMD_PS_GREP.format(pid=pid)).stdout if isinstance(stdout, list): output = "\n".join(stdout) return process_name in output def kill_process_by_pids(self, pids): """ Kills a list of processes on the remote machine based on pids. If a list is not passed in it will be converted to one. It returns a list of pids that were killed successfully. :param int/string/list pids: PID(s) to kill on the remote machine :return: List of PIDs successfully killed :rtype: list """ if not isinstance(pids, list): pids = [pids] culled_pids = [] for pid in pids: print("Killing {pid} on remote machine".format(pid=pid)) if self.run("kill -9 {pid}".format(pid=pid)).success: culled_pids.append(pid) return culled_pids def kill_processes_by_command(self, command): """ Kills a list of processes on the remote machine based on command being run. It returns a list of pids that were killed successfully. :param string command: Command to search for on the remote machine :return: List of PIDs successfully killed :rtype: list """ culled_pids = [] processes = self.run("""ps -elf | grep "{command}" | grep -v grep""".format(command=command)).stdout for process in processes: items = [item for item in process.split(" ") if item] pid = items[3] print("Killing {pid} on remote machine".format(pid=pid)) if self.run("kill -9 {pid}".format(pid=pid)).success: culled_pids.append(pid) return culled_pids @staticmethod def get_pid_from_ps(lines): """ Helper function to get pids from ps -elf command :param list lines: Lines to parse from ps -elf output """ for line in lines: items = [item for item in line.split(" ") if item] return items[3] return None def get_checksum(self, path): """ Helper function to get checksum of a file on a remote machine :param string path: Path of file on remote machine :return: Checksum of the remote file :rtype: string """ o = self.run("md5sum {path}".format(path=path)).stdout checksum = "".join(o).replace(path, "").strip() return checksum def _create_parent(self, dst, max_sessions=999): parent = os.path.dirname(dst) if max_sessions == 1: with ssh(self._host, self._port, self._user, self._password) as conn: try: # i, o, e = conn.exec_command("mkdir -p {parent} && [ -d {parent} ]".format(parent=parent)) i, o, e = conn.exec_command("mkdir -p {parent}".format(parent=parent)) code = o.channel.recv_exit_status() if code == 0: return True print("Did not create parents: Exit code {code}".format(code=code)) except Exception as e: print("Encountered a problem creating parents: {error}".format(error=str(e))) return False # return self.run("mkdir -p {parent} && [ -d {parent} ]".format(parent=parent, response_type=RES_SUCCESS)) return self.run("mkdir -p {parent}".format(parent=parent, response_type=RES_SUCCESS)) def _set_permission(self, owner, group, permissions, dst, max_sessions): if max_sessions == 1: with ssh(self._host, self._port, self._user, self._password) as conn: if owner and group: conn.exec_command("chown {owner}:{group} {path}".format(owner=owner, group=group, path=dst)) if permissions: conn.exec_command("chmod {permissions} {path}".format(permissions=permissions, path=dst)) return True if owner and group: self.run("chown {owner}:{group} {path}".format(owner=owner, group=group, path=dst)) if permissions: self.run("chmod {permissions} {path}".format(permissions=permissions, path=dst)) return True
{"/__init__.py": ["/response.py"]}
24,878,251
MatiasAdrian4/lubricentro_myc
refs/heads/develop
/django_project/lubricentro_myc/migrations/0006_auto_20190806_0042.py
# Generated by Django 2.2.3 on 2019-08-06 00:42 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("lubricentro_myc", "0005_auto_20190805_2321"), ] operations = [ migrations.AlterField( model_name="cliente", name="codigo_postal", field=models.CharField(blank=True, default="", max_length=4, null=True), ), migrations.AlterField( model_name="cliente", name="telefono", field=models.CharField(blank=True, default="", max_length=13, null=True), ), ]
{"/django_project/lubricentro_myc/views.py": ["/django_project/lubricentro_myc/models.py", "/django_project/lubricentro_myc/serializers.py", "/django_project/lubricentro_myc/utils.py"], "/django_project/lubricentro_myc/serializers.py": ["/django_project/lubricentro_myc/models.py"], "/django_project/lubricentro_myc/models/__init__.py": ["/django_project/lubricentro_myc/models/client.py", "/django_project/lubricentro_myc/models/invoice.py", "/django_project/lubricentro_myc/models/invoice_item.py", "/django_project/lubricentro_myc/models/product.py", "/django_project/lubricentro_myc/models/product_cost_history.py", "/django_project/lubricentro_myc/models/sale.py"]}