index int64 | repo_name string | branch_name string | path string | content string | import_graph string |
|---|---|---|---|---|---|
46,844 | maciejbiesek/poleval-cyberbullying | refs/heads/master | /config.py | import configparser
class Parser:
def __init__(self):
self.parser = configparser.ConfigParser()
self.parser.read("params.ini")
def get_section(self, section_name):
return dict(self.parser.items(section_name))
def get_sections(self, section_names):
args = {}
for section in section_names:
args.update(self.get_section(section))
return args
| {"/run_svm.py": ["/dataset.py", "/models/svm_classifier.py"], "/utils.py": ["/config.py"], "/dataset.py": ["/config.py"], "/models/flair_classifier.py": ["/config.py"], "/run_rnn.py": ["/config.py", "/dataset.py", "/models/gru_classifier.py", "/utils.py"], "/models/svm_classifier.py": ["/config.py"], "/run_flair.py": ["/dataset.py", "/models/flair_classifier.py"], "/models/gru_classifier.py": ["/config.py"]} |
46,846 | brynpatel/Deck-of-cards | refs/heads/master | /black_jack.py | from deck_of_cards import *
def check(card1, card2):
if card1.number == card2.number:
check = True
#Add special cards
elif card1.suit == card2.suit:
check = True
else:
check = False
return check
def turn(myCard, myHand, opponentsHand, deck):
cardplayed = False
while cardplayed == False:
myCard = input("what card would you like to put down?, press P to pick up. ")
if myCard.lower() == "p":
deck.cards[0].move(deck.cards, myHand.cards)
print("You picked up")
cardplayed = True
elif myCard.isdigit():
if len(myHand.cards) >= int(myCard):
myCard = int(myCard)-1
if check(myHand.cards[myCard], discard_pile.get_face_card()) == True:
print("You played", myHand.cards[myCard])
myHand.cards[myCard].move(myHand.cards, discard_pile.cards)
cardplayed = True
else:
print("You can't play that card right now, try again")
else:
print("You don't have that many cards!")
else:
print("That is not a valid option, try again")
cardplayed = False
for card in opponentsHand.cards:
if check(card, discard_pile.get_face_card()) == True:
print("I played", card)
card.move(opponentsHand.cards, discard_pile.cards)
return
deck.cards[0].move(deck.cards, opponentsHand.cards)
print("I had to pick up")
hand_size = 7
deck =Deck()
my_hand = Hand()
opponents_hand = Hand()
discard_pile = Discard_Pile()
my_card = 0
opponents_card = 0
win = False
deck.shuffle()
for i in range(hand_size):
deck.deal(my_hand)
deck.deal(opponents_hand)
print(my_hand)
#print(opponents_hand)
deck.cards[0].move(deck.cards, discard_pile.cards)
print(discard_pile.get_face_card())
while win == False:
turn(my_card, my_hand, opponents_hand, deck)
if len(my_hand.cards) == 0:
print("You win")
win = True
elif len(opponents_hand.cards) == 0:
print("You lose")
win = True
else:
win = False
print("=========================NEXT TURN======================")
print(my_hand)
print(discard_pile.get_face_card())
| {"/black_jack.py": ["/deck_of_cards.py"]} |
46,847 | brynpatel/Deck-of-cards | refs/heads/master | /deck_of_cards.py | import random
class Card:
"""
The Card class represents a single playing card and is initialised by passing a suit and number.
"""
def __init__(self, suit, number):
self._suit = suit
self._number = number
def __repr__(self):
return self._number + " of " + self._suit
def move(self, origin, destination):
if self in origin:
posOrigin = origin.index(self)
origin.pop(posOrigin)
destination.insert(0,self)
else:
print(str(self) + " is not in " + str(origin))
@property
def suit(self):
"""
Gets or sets the suit of a card
"""
return self._suit
@suit.setter
def suit(self, suit):
if suit in ["hearts", "clubs", "diamonds", "spades"]:
self._suit = suit
else:
print("That's not a suit!")
@property
def number(self):
"""
Gets or sets the number of a card
"""
return self._number
@number.setter
def number(self, number):
valid = [str(n) for n in range(2,11)] + ["J", "Q", "K", "A"]
if number in valid:
self._number = number
else:
print("That's not a valid number")
class Deck:
"""
The Deck class represents a deck of playing cards in order.
"""
def __init__(self):
self._cards = []
self.populate()
@property
def cards(self):
return self._cards
def populate(self):
"""
The populate method fills the deck with cards in order
"""
suits = ["hearts", "clubs", "diamonds", "spades"]
numbers = [str(n) for n in range(2,11)] + ["J", "Q", "K", "A"]
self._cards = [ Card(s, n) for s in suits for n in numbers ]
def shuffle(self):
"""
The shuffle method sorts the code within the deck into a random order
"""
random.shuffle(self._cards)
def deal(self, hand):
"""
The deal method automaticaly adds a single card to an array that is specified within the code
"""
dealt_card = self._cards.pop(0)
hand._cards.append(dealt_card)
def __repr__(self):
cards_in_deck = len(self._cards)
return "Deck of " + str(cards_in_deck) + " cards"
class Hand:
"""
The Hand class represents a hand of playing cards held by a single player in a typical card game.
"""
def __init__(self):
self._cards = []
@property
def cards(self):
return self._cards
def __repr__(self):
i = 1
rep = ""
for card in self._cards:
rep = rep+str(i)+". "+str(card)+"\n"
i += 1
return rep
class Discard_Pile:
"""
The Discard_Pile class represents a discard pile in a card game.
"""
def __init__(self):
self._discard_pile = []
@property
def cards(self):
return self._discard_pile
def discard(self, hand, card_number):
"""
The discard method moves a card from a hand into a seperate list
"""
discarded_card = hand._cards.pop(0)
self._discard_pile.append(self._discard_pile)
def get_face_card(self):
"""
The get_face_card method retrieves the first card from the discard pile list
"""
face_discard_card = self._discard_pile[0]
return face_discard_card
def __repr__(self):
return str(self._discard_pile)
| {"/black_jack.py": ["/deck_of_cards.py"]} |
46,856 | onionwyl/score-crawler | refs/heads/master | /score.py | import requests
import getpass
import os
import io, sys
from decaptcha import decaptcha
from bs4 import BeautifulSoup
sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='gb18030')
print('\n********** 欢迎使用东北大学研究生成绩查询系统 **********')
s = requests.Session()
url_home = "http://219.216.96.73/pyxx/login.aspx"
req = s.get(url_home)
soup = BeautifulSoup(req.text, "html.parser")
VIEWSTATE = soup.select("#__VIEWSTATE")[0]['value']
VIEWSTATEGENERATOR = soup.select('#__VIEWSTATEGENERATOR')[0]['value']
while 1:
username = input('请输入学号:')
if username:
break
while 1:
password = getpass.getpass('请输入密码:')
if password:
break
# username = ""
# password = ""
count = 0
while 1:
ir = s.get('http://219.216.96.73/pyxx/PageTemplate/NsoftPage/yzm/createyzm.aspx')
if ir.status_code == 200:
open('code.jpg', 'wb').write(ir.content)
# 调用pytesseract识别验证码
code = decaptcha('code.jpg')
print("识别验证码:" + code)
# os.system('code.jpg')
# while 1:
# code = input('请输入验证码:')
# if code:
# break
headers = {
'Origin': 'http://219.216.96.73',
'Referer': 'http://219.216.96.73/pyxx/login.aspx',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36'
}
data = {
'__VIEWSTATE': VIEWSTATE,
'__VIEWSTATEGENERATOR': VIEWSTATEGENERATOR,
'ctl00$txtusername': username,
'ctl00$txtpassword': password,
'ctl00$txtyzm': code,
'ctl00$ImageButton1.x': 0,
'ctl00$ImageButton1.y': 0
}
req = s.post('http://219.216.96.73/pyxx/login.aspx', data=data, headers=headers)
soup = BeautifulSoup(req.text, 'html.parser')
if(req.text.find("用户名不存在") != -1):
print("用户名不存在")
exit(0)
if(req.text.find("密码错误") != -1):
print("密码错误")
exit(0)
f = soup.select('frameset')
if len(f) > 0:
print('登录成功!')
break
else:
print('验证码错误,重新识别验证码')
if(count > 10):
print("识别系统故障")
exit(0)
count += 1
req = s.get('http://219.216.96.73/pyxx/grgl/xskccjcx.aspx?xh=%s' % username)
soup = BeautifulSoup(req.text, 'html.parser')
bx_scores = soup.select('#MainWork_dgData tr')[1:]
print('\n共找到%d条必修课成绩' % len(bx_scores))
for score in bx_scores:
soup1 = BeautifulSoup(str(score), 'html.parser')
name = soup1.select('td')[0].text.replace(u'\xa0', u' ')
value = soup1.select('td')[2].text.replace(u'\xa0', u' ')
print(name, value)
xx_scores = soup.select('#MainWork_Datagrid1 tr')[1:]
print('\n共找到%d条选修课成绩' % len(xx_scores))
for score in xx_scores:
soup2 = BeautifulSoup(str(score), 'html.parser')
name = soup2.select('td')[0].text.replace(u'\xa0', u' ')
value = soup2.select('td')[2].text.replace(u'\xa0', u' ')
print(name, value)
input('\n按Enter键退出...') | {"/score.py": ["/decaptcha.py"]} |
46,857 | onionwyl/score-crawler | refs/heads/master | /decaptcha.py | from PIL import Image
import pytesseract
def decaptcha(image="code.jpg"):
# 替换列表
rep = {'O': '0', 'D': '0',
'I': '1', 'L': '1', 'T': '7',
'Z': '2',
'S': '8', 'E': '8', 'A': '8', 'B': '8'
};
im = Image.open(image)
# im = im.convert("L")
threshold = 54
table = []
for i in range(256):
if i < threshold:
table.append(0)
else:
table.append(1)
im = im.point(table,'1')
im = im.crop((0,10, 70, 35))
captcha = pytesseract.image_to_string(im, config='-psm 7')
for r in rep:
text = captcha.replace(r, rep[r])
return captcha
if __name__ == '__main__':
decaptcha() | {"/score.py": ["/decaptcha.py"]} |
46,858 | Josedaniel98/Cotizaciones | refs/heads/master | /api/serializers/historialProducto.py | from rest_framework import serializers
from api.models import historialProducto
class historialProductoSerializer(serializers.ModelSerializer):
class Meta:
model = historialProducto
fields = '__all__'
class historialProductoRegistroSerializer(serializers.ModelSerializer):
class Meta:
model = historialProducto
fields = '__all__' | {"/api/serializers/historialProducto.py": ["/api/models/__init__.py"], "/api/viewsets/cotizaciones.py": ["/api/models/__init__.py", "/api/serializers/__init__.py"], "/api/models/__init__.py": ["/api/models/cotizaciones.py", "/api/models/historialProducto.py"], "/api/viewsets/productos.py": ["/api/models/__init__.py", "/api/serializers/__init__.py"], "/api/viewsets/__init__.py": ["/api/viewsets/productos.py", "/api/viewsets/cotizaciones.py", "/api/viewsets/historialProducto.py"], "/api/viewsets/historialProducto.py": ["/api/models/__init__.py", "/api/serializers/__init__.py"], "/api/serializers/cotizaciones.py": ["/api/models/__init__.py"], "/api/serializers/__init__.py": ["/api/serializers/cotizaciones.py", "/api/serializers/historialProducto.py"]} |
46,859 | Josedaniel98/Cotizaciones | refs/heads/master | /api/viewsets/cotizaciones.py | import json
from django.core.files import File
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import status, filters, viewsets
from django.contrib.auth.models import User
from rest_framework.authtoken.models import Token
from rest_framework.decorators import action
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.response import Response
from rest_framework.settings import api_settings
from api.models import Cotizacion
from api.serializers import CotizacionReadSerializer, CotizacionRegistroSerializer
from copy import deepcopy
class CotizacionViewset(viewsets.ModelViewSet):
queryset = Cotizacion.objects.filter(activo=True)
filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)
filter_fields = ("usuario",)
search_fields = ("usuario",)
ordering_fields = ("usuario",)
def get_serializer_class(self):
"""Define serializer for API"""
if self.action == 'list' or self.action == 'retrieve':
return CotizacionReadSerializer
else:
return CotizacionRegistroSerializer
def get_permissions(self):
"""" Define permisos para este recurso """
if self.action == "create" or self.action == "token":
permission_classes = [AllowAny]
else:
permission_classes = [IsAuthenticated]
return [permission() for permission in permission_classes]
@action(detail=False, methods=['get'])
def total_usuarios(self, request, *args, **kwargs):
"""Reporte promedio totales por usuario"""
data=[]
total=0
count=0
promedio=0
for u in User.objects.filter(is_active=True):
for c in Cotizacion.objects.filter(activo=True):
if u.id == c.usuario.id:
total += c.total
count +=1
promedio=round(total/count, 2)
data.append({
'usuario': u.username,
'promedio': promedio
})
promedio=0
count=0
total=0
print("data ", data)
return Response({'data': data})
@action(detail=False, methods=['get'])
def total_numero(self, request, *args, **kwargs):
"""Reporte promedio numero de cotizaciones de los usuario"""
count_cot=0
count_user=0
promedio=0
for u in User.objects.filter(is_active=True):
count_user += 1
for c in Cotizacion.objects.filter(activo=True):
count_cot += 1
promedio = count_cot / count_user
print("data ", promedio)
return Response({'data':promedio})
| {"/api/serializers/historialProducto.py": ["/api/models/__init__.py"], "/api/viewsets/cotizaciones.py": ["/api/models/__init__.py", "/api/serializers/__init__.py"], "/api/models/__init__.py": ["/api/models/cotizaciones.py", "/api/models/historialProducto.py"], "/api/viewsets/productos.py": ["/api/models/__init__.py", "/api/serializers/__init__.py"], "/api/viewsets/__init__.py": ["/api/viewsets/productos.py", "/api/viewsets/cotizaciones.py", "/api/viewsets/historialProducto.py"], "/api/viewsets/historialProducto.py": ["/api/models/__init__.py", "/api/serializers/__init__.py"], "/api/serializers/cotizaciones.py": ["/api/models/__init__.py"], "/api/serializers/__init__.py": ["/api/serializers/cotizaciones.py", "/api/serializers/historialProducto.py"]} |
46,860 | Josedaniel98/Cotizaciones | refs/heads/master | /api/models/__init__.py | from .profile import Profile
from .productos import Producto
from .cotizaciones import Cotizacion
from .historialProducto import historialProducto | {"/api/serializers/historialProducto.py": ["/api/models/__init__.py"], "/api/viewsets/cotizaciones.py": ["/api/models/__init__.py", "/api/serializers/__init__.py"], "/api/models/__init__.py": ["/api/models/cotizaciones.py", "/api/models/historialProducto.py"], "/api/viewsets/productos.py": ["/api/models/__init__.py", "/api/serializers/__init__.py"], "/api/viewsets/__init__.py": ["/api/viewsets/productos.py", "/api/viewsets/cotizaciones.py", "/api/viewsets/historialProducto.py"], "/api/viewsets/historialProducto.py": ["/api/models/__init__.py", "/api/serializers/__init__.py"], "/api/serializers/cotizaciones.py": ["/api/models/__init__.py"], "/api/serializers/__init__.py": ["/api/serializers/cotizaciones.py", "/api/serializers/historialProducto.py"]} |
46,861 | Josedaniel98/Cotizaciones | refs/heads/master | /api/models/historialProducto.py | from django.db import models
from django.contrib.auth.models import User
class historialProducto(models.Model):
id_producto=models.IntegerField()
nombre = models.CharField(max_length=15)
activo = models.BooleanField(default=True)
creado = models.DateTimeField(auto_now_add=True)
modificado = models.DateTimeField(auto_now=True)
def __unicode__(self):
return self.nombre
def delete(self, *args):
self.activo = False
self.save()
return True | {"/api/serializers/historialProducto.py": ["/api/models/__init__.py"], "/api/viewsets/cotizaciones.py": ["/api/models/__init__.py", "/api/serializers/__init__.py"], "/api/models/__init__.py": ["/api/models/cotizaciones.py", "/api/models/historialProducto.py"], "/api/viewsets/productos.py": ["/api/models/__init__.py", "/api/serializers/__init__.py"], "/api/viewsets/__init__.py": ["/api/viewsets/productos.py", "/api/viewsets/cotizaciones.py", "/api/viewsets/historialProducto.py"], "/api/viewsets/historialProducto.py": ["/api/models/__init__.py", "/api/serializers/__init__.py"], "/api/serializers/cotizaciones.py": ["/api/models/__init__.py"], "/api/serializers/__init__.py": ["/api/serializers/cotizaciones.py", "/api/serializers/historialProducto.py"]} |
46,862 | Josedaniel98/Cotizaciones | refs/heads/master | /api/viewsets/productos.py | import json
from django.core.files import File
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import status, filters, viewsets
from django.contrib.auth.models import User
from rest_framework.authtoken.models import Token
from rest_framework.decorators import action
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.response import Response
from rest_framework.settings import api_settings
from api.models import Producto
from api.serializers import ProductoSerializer, ProductoRegistroSerializer
from copy import deepcopy
class ProductoViewset(viewsets.ModelViewSet):
queryset = Producto.objects.filter(activo=True)
filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)
filter_fields = ("nombre",)
search_fields = ("nombre",)
ordering_fields = ("nombre",)
def get_serializer_class(self):
"""Define serializer for API"""
if self.action == 'list' or self.action == 'retrieve':
return ProductoSerializer
else:
return ProductoRegistroSerializer
def get_permissions(self):
"""" Define permisos para este recurso """
if self.action == "create" or self.action == "token":
permission_classes = [AllowAny]
else:
permission_classes = [IsAuthenticated]
return [permission() for permission in permission_classes]
def create(self, request, *args, **kwargs):
try:
data = request.data
serializer = ProductoRegistroSerializer(data=request.data)
if(serializer.is_valid()):
producto = Producto.objects.create(
nombre = data.get('nombre'),
descripcion = data.get('descripcion'),
precio = data.get('precio'),
)
return Response(serializer.data, status=status.HTTP_201_CREATED)
else:
Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
except Exception as e:
return Response({'detalle': str(e)}, status=status.HTTP_400_BAD_REQUEST)
def update(self, request, *args, **kwargs):
try:
instancia = self.get_object()
data = request.data
serializer = ProductoRegistroSerializer(data=request.data)
if(serializer.is_valid()):
instancia.nombre = data.get('nombre')
instancia.descripcion= data.get('descripcion')
instancia.precio= data.get('precio')
instancia.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
else:
Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
except Exception as e:
return Response({'detail': str(e)}, status=status.HTTP_400_BAD_REQUEST) | {"/api/serializers/historialProducto.py": ["/api/models/__init__.py"], "/api/viewsets/cotizaciones.py": ["/api/models/__init__.py", "/api/serializers/__init__.py"], "/api/models/__init__.py": ["/api/models/cotizaciones.py", "/api/models/historialProducto.py"], "/api/viewsets/productos.py": ["/api/models/__init__.py", "/api/serializers/__init__.py"], "/api/viewsets/__init__.py": ["/api/viewsets/productos.py", "/api/viewsets/cotizaciones.py", "/api/viewsets/historialProducto.py"], "/api/viewsets/historialProducto.py": ["/api/models/__init__.py", "/api/serializers/__init__.py"], "/api/serializers/cotizaciones.py": ["/api/models/__init__.py"], "/api/serializers/__init__.py": ["/api/serializers/cotizaciones.py", "/api/serializers/historialProducto.py"]} |
46,863 | Josedaniel98/Cotizaciones | refs/heads/master | /api/viewsets/__init__.py | from .user import UserViewset
from .productos import ProductoViewset
from .cotizaciones import CotizacionViewset
from .historialProducto import historialProductoViewset | {"/api/serializers/historialProducto.py": ["/api/models/__init__.py"], "/api/viewsets/cotizaciones.py": ["/api/models/__init__.py", "/api/serializers/__init__.py"], "/api/models/__init__.py": ["/api/models/cotizaciones.py", "/api/models/historialProducto.py"], "/api/viewsets/productos.py": ["/api/models/__init__.py", "/api/serializers/__init__.py"], "/api/viewsets/__init__.py": ["/api/viewsets/productos.py", "/api/viewsets/cotizaciones.py", "/api/viewsets/historialProducto.py"], "/api/viewsets/historialProducto.py": ["/api/models/__init__.py", "/api/serializers/__init__.py"], "/api/serializers/cotizaciones.py": ["/api/models/__init__.py"], "/api/serializers/__init__.py": ["/api/serializers/cotizaciones.py", "/api/serializers/historialProducto.py"]} |
46,864 | Josedaniel98/Cotizaciones | refs/heads/master | /api/viewsets/historialProducto.py | import json
from django.core.files import File
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import status, filters, viewsets
from django.contrib.auth.models import User
from rest_framework.authtoken.models import Token
from rest_framework.decorators import action
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.response import Response
from rest_framework.settings import api_settings
from api.models import historialProducto, Producto
from api.serializers import historialProductoSerializer, historialProductoRegistroSerializer
from copy import deepcopy
class historialProductoViewset(viewsets.ModelViewSet):
queryset = historialProducto.objects.filter(activo=True)
filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)
filter_fields = ("nombre",)
search_fields = ("nombre",)
ordering_fields = ("nombre",)
def get_serializer_class(self):
"""Define serializer for API"""
if self.action == 'list' or self.action == 'retrieve':
return historialProductoSerializer
else:
return historialProductoRegistroSerializer
def get_permissions(self):
"""" Define permisos para este recurso """
if self.action == "create" or self.action == "token":
permission_classes = [AllowAny]
else:
permission_classes = [IsAuthenticated]
return [permission() for permission in permission_classes]
@action(detail=False, methods=['get'])
def top_producto(self, request, *args, **kwargs):
"""Top 5 de productos mas cotizados"""
data=[]
count=0
newData=[]
for p in Producto.objects.filter(activo=True):
for h in historialProducto.objects.filter(activo=True):
if p.id == h.id_producto:
count +=1
data.append({
'producto': p.nombre,
'cantidad': count
})
count=0
print("data ", data)
print("data ", newData)
return Response({'data': data})
| {"/api/serializers/historialProducto.py": ["/api/models/__init__.py"], "/api/viewsets/cotizaciones.py": ["/api/models/__init__.py", "/api/serializers/__init__.py"], "/api/models/__init__.py": ["/api/models/cotizaciones.py", "/api/models/historialProducto.py"], "/api/viewsets/productos.py": ["/api/models/__init__.py", "/api/serializers/__init__.py"], "/api/viewsets/__init__.py": ["/api/viewsets/productos.py", "/api/viewsets/cotizaciones.py", "/api/viewsets/historialProducto.py"], "/api/viewsets/historialProducto.py": ["/api/models/__init__.py", "/api/serializers/__init__.py"], "/api/serializers/cotizaciones.py": ["/api/models/__init__.py"], "/api/serializers/__init__.py": ["/api/serializers/cotizaciones.py", "/api/serializers/historialProducto.py"]} |
46,865 | Josedaniel98/Cotizaciones | refs/heads/master | /api/models/cotizaciones.py | from django.db import models
from django.contrib.auth.models import User
class Cotizacion(models.Model):
usuario = models.ForeignKey(User, on_delete=models.CASCADE, null=False)
productos = models.ManyToManyField('Producto', related_name='producto')
total= models.IntegerField(null=False)
activo = models.BooleanField(default=True)
creado = models.DateTimeField(auto_now_add=True)
modificado = models.DateTimeField(auto_now=True)
def __unicode__(self):
return self.usuario
def delete(self, *args):
self.activo = False
self.save()
return True | {"/api/serializers/historialProducto.py": ["/api/models/__init__.py"], "/api/viewsets/cotizaciones.py": ["/api/models/__init__.py", "/api/serializers/__init__.py"], "/api/models/__init__.py": ["/api/models/cotizaciones.py", "/api/models/historialProducto.py"], "/api/viewsets/productos.py": ["/api/models/__init__.py", "/api/serializers/__init__.py"], "/api/viewsets/__init__.py": ["/api/viewsets/productos.py", "/api/viewsets/cotizaciones.py", "/api/viewsets/historialProducto.py"], "/api/viewsets/historialProducto.py": ["/api/models/__init__.py", "/api/serializers/__init__.py"], "/api/serializers/cotizaciones.py": ["/api/models/__init__.py"], "/api/serializers/__init__.py": ["/api/serializers/cotizaciones.py", "/api/serializers/historialProducto.py"]} |
46,866 | Josedaniel98/Cotizaciones | refs/heads/master | /api/serializers/cotizaciones.py |
# Django REST framework
from rest_framework import serializers
# Model
from api.models import Producto
from api.models import Cotizacion
class ProductoReadSerializer( serializers.ModelSerializer ):
class Meta:
model = Producto
fields = ('id','nombre','descripcion','precio')
class CotizacionReadSerializer( serializers.ModelSerializer ):
usuario = serializers.SerializerMethodField("getUsuarios")
productos = ProductoReadSerializer(many=True)
class Meta:
model = Cotizacion
fields = '__all__'
def getUsuarios(self, obj):
return {'value': obj.usuario.id, 'label': obj.usuario.username}
class CotizacionRegistroSerializer(serializers.ModelSerializer):
class Meta:
model = Cotizacion
fields = ('usuario', 'productos', 'total') | {"/api/serializers/historialProducto.py": ["/api/models/__init__.py"], "/api/viewsets/cotizaciones.py": ["/api/models/__init__.py", "/api/serializers/__init__.py"], "/api/models/__init__.py": ["/api/models/cotizaciones.py", "/api/models/historialProducto.py"], "/api/viewsets/productos.py": ["/api/models/__init__.py", "/api/serializers/__init__.py"], "/api/viewsets/__init__.py": ["/api/viewsets/productos.py", "/api/viewsets/cotizaciones.py", "/api/viewsets/historialProducto.py"], "/api/viewsets/historialProducto.py": ["/api/models/__init__.py", "/api/serializers/__init__.py"], "/api/serializers/cotizaciones.py": ["/api/models/__init__.py"], "/api/serializers/__init__.py": ["/api/serializers/cotizaciones.py", "/api/serializers/historialProducto.py"]} |
46,867 | Josedaniel98/Cotizaciones | refs/heads/master | /api/serializers/__init__.py | from .user import UserSerializer, UserReadSerializer
from .productos import ProductoSerializer, ProductoRegistroSerializer
from .cotizaciones import CotizacionReadSerializer, CotizacionRegistroSerializer
from .historialProducto import historialProductoSerializer, historialProductoRegistroSerializer | {"/api/serializers/historialProducto.py": ["/api/models/__init__.py"], "/api/viewsets/cotizaciones.py": ["/api/models/__init__.py", "/api/serializers/__init__.py"], "/api/models/__init__.py": ["/api/models/cotizaciones.py", "/api/models/historialProducto.py"], "/api/viewsets/productos.py": ["/api/models/__init__.py", "/api/serializers/__init__.py"], "/api/viewsets/__init__.py": ["/api/viewsets/productos.py", "/api/viewsets/cotizaciones.py", "/api/viewsets/historialProducto.py"], "/api/viewsets/historialProducto.py": ["/api/models/__init__.py", "/api/serializers/__init__.py"], "/api/serializers/cotizaciones.py": ["/api/models/__init__.py"], "/api/serializers/__init__.py": ["/api/serializers/cotizaciones.py", "/api/serializers/historialProducto.py"]} |
46,872 | rfarrow1010/economistaudio | refs/heads/master | /playecon.py | #!/usr/bin/env python
# Author: Ryan Farrow
# Date created: 10 Apr 2020
# https://docs.python-guide.org/writing/structure/
# For the terminal scripting:
# https://unix.stackexchange.com/questions/43075/how-to-change-the-contents-of-a-line-on-the-terminal-as-opposed-to-writing-a-new
# http://www.tldp.org/HOWTO/NCURSES-Programming-HOWTO/intro.html
import wave
import time
import sys, os, subprocess, shutil
from src import fetch, play, unzip, utils
# labels for catalogue navigation
LABELS = [
'1',
'2',
'3',
'4',
'5',
'6',
'7',
'8',
'9',
'a',
's',
'd',
'f',
'g',
'h',
'j'
]
# note: will need to take options for specifying the path
# no options should first search for a directory, then ask
# for download link if it is not found
def usage(exitcode=0):
print('''
Usage: ./playecon.py [ path/to/mp3folder ]
Options: -c (clean out econdata)
Path is optional; if no path is provided,
interactive prompt will start
''')
exit(exitcode)
def main():
audio_player = ''
playlist = []
val = 0
# command line inputs
if len(sys.argv) >= 2:
if sys.argv[1] == '-h':
usage(0)
elif sys.argv[1] == '-c':
shutil.rmtree('econdata')
# interactive prompt
else:
if sys.platform == 'darwin':
audio_player = 'afplay'
if not os.path.isdir("./econdata"):
(zippath, zipbool) = unzip.scan()
else:
(zippath, zipbool) = ("./econdata", False)
index = -1
# unzip if it needs unzipping
if zipbool:
unzip.unzip(zippath)
try:
for items in os.walk("./econdata"):
for track in items[2]:
playlist.append(track)
playlist.sort()
except OSError:
print("Audio zip file not found. Please download the zip file")
print("and put it in Downloads, Desktop, or this directory.")
exit(1)
if len(playlist) == 0:
print("Playlist construction failed. Exiting")
exit(1)
# make catalogue of sections
catalogue = utils.catalogue(playlist, LABELS)
while index < 0 or index > len(playlist) - 1:
index = int(input("Enter number of track you wish to play: ")) - 1
# play each track starting at index while checking for user input
while index < len(playlist):
val = play.playfile(audio_player, zippath, playlist[index], catalogue, utils.last_call(val, playlist, index))
# index check
if index < 0:
index = 0
# user termination
if val == ord('q'):
break
# skip to next track, increment index
elif val == ord('n'):
index += 1
# restart this track; index doesn't change
elif val == ord('z'):
continue
# go back to previous track; decrement index
elif val == ord('p'):
index -= 1
# all other cases: assume it timed out, increment index
else:
index += 1
if index >= len(playlist):
utils.debug("Playlist fully traversed")
break
if __name__ == "__main__":
main() | {"/src/play.py": ["/src/utils.py"]} |
46,873 | rfarrow1010/economistaudio | refs/heads/master | /src/unzip.py | #!/usr/bin/env python
# Author: Ryan Farrow
# Date: 16 May 2020
import zipfile
import os
def unzip(path, cleanup=False, dest=os.path.dirname(os.path.realpath(__file__))):
"""
Unzips the file with path given in first parameter. Deletes the zip file
and puts the new folder in the specified destination, default this file's directory. If cleanup is set to
True, then the .zip file will be deleted.
Returns the path of the unzipped folder (or 0 on failure).
"""
# make directory to store stuff
# directory name defined by dest param so can be modified
# if it is the default dest, append "/data" to it
if dest == os.path.dirname(os.path.realpath(__file__)):
dest += "/econdata"
# if not, just proceed with whatever is supplied
try:
os.mkdir(dest)
except OSError as e:
print("Could not make directory: " + str(e))
# check that the given file is a zip file
if ".zip" in path:
# use absolute path
abspath = os.path.abspath(path)
with zipfile.ZipFile(abspath, "r") as zip:
zip.extractall(path=dest)
# remove zip file
if cleanup:
try:
os.remove(abspath)
except OSError as e:
print("Could not delete origin")
return abspath
# not a zip file
else:
print("Supplied file not a zip file")
return 0
def scan(datascan=True):
'''
Scans this file's directory, the Downloads directory, and the Desktop directory
for a zip file starting with "Issue_", assumed to be an Economist Audio zip file.
If it finds the file, it then scans the same directories for a directory called econdata
if datascan is True.
Returns a tuple whose first member is the path to the zip file (or econdata if it exists) and whose second
member is True if it needs unzipping, False otherwise.
'''
r = ('', False)
zipfound = False
datafound = False
print("Searching this directory...")
for root, dirs, files in os.walk("."):
for f in files:
if "Issue_" in f:
print("Zip file found!")
r = (os.path.join(root, f), r[1])
zipfound = True
if not zipfound:
print("Searching Downloads...")
for root, dirs, files in os.walk(os.path.join(os.environ['HOME']), "/Downloads"):
for f in files:
if "Issue_" in f:
print("Zip file found!")
r = (os.path.join(root, f), r[1])
zipfound = True
if not zipfound:
print("Searching Desktop...")
for root, dirs, files in os.walk(os.path.join(os.environ['HOME']), "/Desktop"):
for f in files:
if "Issue_" in f:
print("Zip file found!")
r = (os.path.join(root, f), r[1])
zipfound = True
if not zipfound:
print("Could not find zip file. Is it in Downloads or Desktop?")
return r
if datascan:
for root, dirs, files in os.walk("."):
for d in dirs:
if "econdata" in d:
datafound = True
r = (os.path.join(root, d), r[1])
if not datafound:
for root, dirs, files in os.walk(os.path.join(os.environ['HOME']), "/Downloads"):
for d in dirs:
if "econdata" in d:
datafound = True
r = (os.path.join(root, d), r[1])
if not datafound:
for root, dirs, files in os.walk(os.path.join(os.environ['HOME']), "/Desktop"):
for d in dirs:
if "econdata" in d:
datafound = True
r = (os.path.join(root, d), r[1])
if datascan:
if not datafound:
r = (r[0], True)
return r
if __name__ == "__main__":
unzip("../Desktop/Issue_9194_20200516_The_Economist_Full_edition.zip")
scan() | {"/src/play.py": ["/src/utils.py"]} |
46,874 | rfarrow1010/economistaudio | refs/heads/master | /src/setup.py | #!/usr/bin/env python
from distutils.core import setup, Extension
def main():
ncurses = Extension('termUtils', sources = ['termUtils.c'])
setup(name = 'termUtils', version = '1.0',
description = 'Package for employing the ncurses terminal features in Economist Command Line Player',
author='Ryan Farrow',
ext_modules = [ncurses])
# next step: make a little bash script to do the following
# python setup.py build
# python setup.py install
# {everything else for running the script}
if __name__ == "__main__":
main() | {"/src/play.py": ["/src/utils.py"]} |
46,875 | rfarrow1010/economistaudio | refs/heads/master | /src/fetch.py | #!/usr/bin/env python
# Author: Ryan Farrow
# Date created: 10 Apr 2020
# For reference: https://people.csail.mit.edu/hubert/pyaudio/#docs
# pydub: https://github.com/jiaaro/pydub
# simpleaudio: https://simpleaudio.readthedocs.io/en/latest/tutorial.html
import wave
import time
import sys, os
def get_files(path):
'''
Returns a list of files to be played in sequence in a given
directory.
PARAM:
path: path to directory
'''
flist = []
for files in os.walk(path):
for item in files[2]:
if item in flist:
continue
elif item.endswith('.mp3'):
flist.append(item)
return sorted(flist)
# for controls e.g. restart, go 10 seconds back, change audio
# may need some sneaky start and stop with pydub
# kill a subprocess playing the audio file, create new file object
# with altered parameters, then export it and play whatever that is | {"/src/play.py": ["/src/utils.py"]} |
46,876 | rfarrow1010/economistaudio | refs/heads/master | /src/utils.py | #!/usr/bin/env python
# Author: Ryan Farrow
# Date created: 23 Jun 2020
# note: may just need to use the Python curses library documented here:
# https://docs.python.org/3/howto/curses.html
import curses
def catalogue(playlist, labels):
'''
Catalogues the articles into sections based on topic.
Return a dict with strings of section names as keys and their indices
in the playlist as values.
'''
i = 0
sections = [
"Leaders.mp3",
"United States.mp3",
"The Americas.mp3",
"Briefing.mp3",
"Asia.mp3",
"Middle East and Africa.mp3",
"Europe.mp3",
"Britain.mp3",
"International.mp3",
"Special report.mp3",
"Business.mp3",
"Finance and economics.mp3",
"Science and technology.mp3",
"Books and arts.mp3",
"Graphic detail.mp3",
"Obituary -"
]
cat = {}
cat["Introduction"] = 0
for a in playlist:
if sections[0] in a:
if sections[0] is "Obituary -":
cat["Obituary"] = labels[playlist.index(a)]
else:
# chop off .mp3 from section headers
cat[sections[0][:-4]] = labels[i]
# remove this header
sections.pop(0)
i += 1
return cat
def cat_to_str(cat):
'''
Transforms the catalogue to be a formatted string. Returns the string.
'''
RSPACE = 4
lspace = max(map(len, cat.keys())) + 1
s = f""
newheads = cat.keys()
# format the strings
for h in newheads:
h.ljust(lspace)
newvals = list(map(str, cat.values()))
for v in newvals:
v.rjust(RSPACE)
# plus 1 for center divider in table
s += ('-'*(lspace+RSPACE+1))
s += '\n'
for i, h in enumerate(newheads):
s += f"{h}|{newvals[i]}"
s += ('-'*(lspace+RSPACE+1))
return s
def last_call(uin, playlist, index):
'''
Produces a string describing the previous user call, which
will be displayed as the first line of the ncurses terminal
output. Takes in the previous user input and the most recently
played track. Returns the string. No newline at the end.
'''
# jump back a track
if uin == 'p':
return f"Jumped back from {playlist[index + 1]}"
# rewind this track
elif uin == 'z':
return f"Rewound {playlist[index]}"
# jump to next track
elif uin == 'n':
return f"Jumped forward from {playlist[index - 1]}"
# nothing
else:
return ""
def curses_ui(audioname, catstring, lastcall):
'''
Python-based curses UI function. Invokes the curses terminal API, displays
info, and then returns the user-input value.
Accepts the name of the track currently being played, the string representing
the catalogue, and the details of the previous user input, if applicable.
'''
uin = 0
stdscr = curses.initscr()
curses.noecho()
curses.cbreak()
stdscr.keypad(True)
stdscr.addstr(lastcall)
stdscr.addstr("\n\n")
stdscr.addstr(f"Now playing: {audioname}\n")
stdscr.addstr("Press q to quit, right key -> to rewind/go back one track,\n")
stdscr.addstr("or left key <- to jump to the next track.\n")
stdscr.addstr("Want to jump to a section? Press that section's corresponding key in the table below.\n\n")
stdscr.addstr(catstring)
stdscr.refresh()
while True:
uin = stdscr.getch()
# right key
if uin == curses.KEY_RIGHT:
uin = ord('n')
break
elif uin == curses.KEY_LEFT:
uin = ord('p')
break
elif uin == ord('q'):
break
curses.nocbreak()
stdscr.keypad(False)
curses.echo()
curses.endwin()
return uin
def debug(msg):
'''
Writes debug info to a file in relative location data/debug.txt.
Returns null.
'''
f = open("data/debug.txt", "a")
f.write(msg)
f.write('\n')
f.close()
| {"/src/play.py": ["/src/utils.py"]} |
46,877 | rfarrow1010/economistaudio | refs/heads/master | /src/play.py | #!/usr/bin/env python
# Creates subprocess that plays audio, allowing parent process to take inputs
# Requires mp3info to be present on the machine
# Author: Ryan Farrow
# Date created: 11 Apr 2020
import os, signal, subprocess, time
import src.utils
import ctypes, pathlib
# main file needs to intelligently use the return value here to restart the
def playfile(audio_player, dpath, audioname, catalogue, lastcall):
'''
Plays the file at the target directory with the target name.
dpath: The path to the directory containing the target file
audioname: The name of the file to be played
Returns result of user input. -1 if restarting this track, -2 if going back to
previous track, 1 if jumping to next track, 2 if user terminates playback (results in
program closing), and 0 if playback finishes normally.
'''
r = 0
# convert catalogue into string for ncurses to display
strcat = src.utils.cat_to_str(catalogue)
# spawns child process that plays audio
fpath = os.path.join(dpath, audioname)
sub = subprocess.Popen([audio_player, '{}'.format(fpath)])
# finds runtime of audio file with a system call to mp3info
call_path = dpath + '/\"' + audioname + '\"'
runtime = subprocess.check_output('mp3info -p \"%S\\n\" ' + call_path, shell=True)
int_runtime = int(runtime)
start = time.time()
# note to self: the way to do this might be to fork off a child process that checks for
# input and have the parent contain the while loop
# once the while loop concludes, kill child process and print out exit code 0
fpid = os.fork()
# parent process
if fpid > 0:
# wait for runtime to elapse
while time.time() < start + int_runtime:
# check if user has cancelled playback
try:
# looking for upper byte of second element in this tuple
pid, r = os.wait()
r = r >> 8
# if so, exit loop
except ChildProcessError:
break
try:
os.kill(fpid, signal.SIGKILL)
except OSError:
pass
try:
os.kill(sub.pid, signal.SIGKILL)
except OSError:
pass
return r
# child process
else:
while True:
# TODO: put the ncurses stuff here
# read:
# https://realpython.com/build-python-c-extension-module/
uin = src.utils.curses_ui(audioname, "", lastcall)
if uin == ord('q'):
# user ends playback
# using child's PID, sends kill signal
os.kill(sub.pid, signal.SIGKILL)
exit(uin)
elif uin == ord('p'):
os.kill(sub.pid, signal.SIGKILL)
# not within 5 seconds of start so give signal to rewind this track
if time.time() - start > 5:
uin = ord('z')
# if it is within 5 seconds, no action needed
exit(uin)
elif uin == ord('n'):
os.kill(sub.pid, signal.SIGKILL)
# no matter what the track time is, this will skip to next
exit(uin)
# if it somehow breaks free of while loop, exit -1
exit(-1) | {"/src/play.py": ["/src/utils.py"]} |
46,882 | danielforgacs/NamingConvention | refs/heads/master | /basecls_test.py | import basecls
import pytest
@pytest.mark.parametrize('value', (
1, (), [], 1.23,
))
def test_StringType_is_string_only(value):
class TestClass:
testattr = basecls.StringType(attr='testattr')
name = TestClass()
name.testattr = '123'
with pytest.raises(Exception):
name.testattr = value
@pytest.mark.parametrize('value', (
'1', (), [], 1.23, ))
def test_IntType_is_int_only(value):
class TestClass:
testattr = basecls.IntType(attr='testattr')
name = TestClass()
name.testattr = 123
with pytest.raises(Exception):
name.testattr = value
@pytest.mark.parametrize('value', (
'', 'a', 'aaaa', 1, ))
def test_SizedString_has_limited_lenght(value):
class TestClass:
testattr = basecls.SizedString(attr='testattr', lenmin=2, lenmax=3)
name = TestClass()
name.testattr = '12'
with pytest.raises(Exception):
name.testattr = value
@pytest.mark.parametrize('value', (
1, 'x', '23fks', ))
def test_optioned(value):
class TestClass:
testattr = basecls.Optioned(attr='testattr', options=('a', 'b'))
name = TestClass()
name.testattr = 'a'
assert name.testattr == 'a'
name.testattr = 'b'
assert name.testattr == 'b'
with pytest.raises(Exception):
name.testattr = value
@pytest.mark.parametrize('value', (
-1, 0, 4, 5, 6, 7, ))
def test_LimitedInt(value):
class TestClass:
testattr = basecls.LimitedInt(attr='testattr', minint=1, maxint=3)
name = TestClass()
name.testattr = 1
assert name.testattr == 1
with pytest.raises(Exception):
name.testattr = value
def test_BaseName():
pass
if __name__ == '__main__':
pytest.main([
__file__,
])
| {"/basecls_test.py": ["/basecls.py"]} |
46,883 | danielforgacs/NamingConvention | refs/heads/master | /basecls.py | # module to create sanity checked strings like
# product names. The string consist of multiple
# elements. Rules for the elements come
# from a configuration.
class Descriptor:
"""
Root descriptor class. All elements are set here
if they passed the tests in the subclasses.
The attributes name must be added.
"""
def __init__(self, attr):
self.attr = attr
def __get__(self, instance, cls):
if self.attr not in instance.__dict__:
return None
return instance.__dict__[self.attr]
def __set__(self, instance, value):
instance.__dict__[self.attr] = value
class TypeBase(Descriptor):
"""
This class checkes if the attribute is the
right type. Types are set in the sublcasses
"typebase" attribute.
"""
def __set__(self, instance, value):
if not isinstance(value, self.typebase):
raise Exception('==> MUST BE TYPE: '+str(self.typebase))
super().__set__(instance, value)
class StringType(TypeBase):
typebase = str
class IntType(TypeBase):
typebase = int
class SizedStrBase(Descriptor):
"""
Base class testing the lenght of a string.
Lenght is configured with the "lenmin"
and "lenmax" attributes.
"""
def __init__(self, lenmin, lenmax, **kwargs):
super().__init__(**kwargs)
self.lenmin = lenmin
self.lenmax = lenmax
def __set__(self, instance, value):
if not self.lenmin <= len(value) <= self.lenmax:
raise Exception('==> MUST BE LENGTH: %i - %i' % (self.lenmin, self.lenmax))
super().__set__(instance, value)
class SizedString(StringType, SizedStrBase):
pass
class LimitedIntBase(Descriptor):
"""
Base class for testing integer limits.
Limits are configured with the "minint"
and "maxint" attrs.
"""
def __init__(self, minint, maxint, **kwargs):
super().__init__(**kwargs)
self.minint = minint
self.maxint = maxint
def __set__(self, instance, value):
if not self.minint <= value <= self.maxint:
raise Exception('==> MUST BE %i < x < %i' % (self.minint, self.maxint))
super().__set__(instance, value)
class LimitedInt(IntType, LimitedIntBase):
pass
class Optioned(Descriptor):
"""
Main class for elements that have options.
Options are configured with the "options"
argument. "options" must be sequence type.
"""
def __init__(self, options, **kwargs):
super().__init__(**kwargs)
self.options = options
def __set__(self, instance, value):
if not value in self.options:
raise Exception('==> NOT AN OPTION')
super().__set__(instance, value)
class BaseNameMeta(type):
"""
Metaclass to create the string classes.
It populates class dictionaries with elements
configured in the "conf" attr in the classes.
"""
def __new__(cls, name, bases, namespace):
"""
this is where string element classes get
set up based on the config.
"""
for attr, attrtype in namespace['conf'].items():
if not isinstance(attrtype, dict):
namespace[attr] = None
continue
if tuple(attrtype.keys())[0] == 'choices':
choices = tuple(attrtype.values())[0]
namespace[attr] = Optioned(options=choices, attr=attr)
elif tuple(attrtype.keys())[0] == 'number':
namespace[attr] = IntType(attr=attr)
elif tuple(attrtype.keys())[0] == 'limitednumber':
minint, maxint = tuple(attrtype.values())[0]
namespace[attr] = LimitedInt(minint=minint, maxint=maxint, attr=attr)
newcls = type.__new__(cls, name, bases, namespace)
return newcls
CONFIG = {
'a': {'choices': (1, 2)},
'b': {'choices': ('a', 'b')},
'c': {'number': None},
'd': {'limitednumber': (2, 5)},
'e': None,
}
class BaseName(metaclass=BaseNameMeta):
conf = CONFIG
@property
def name(self):
if not self:
return None
elements = (getattr(self, attr) for attr in self.conf.keys())
name = '_'.join(str(element) for element in elements)
return name
def __bool__(self):
allvalues = (getattr(self, attr) for attr in self.conf.keys())
allset = all(allvalues)
return allset
name = BaseName()
name.a = 1
name.b = 'a'
name.c = 1
name.d = 4
name.e = 'E'
print(bool(name))
print(name.name)
# name.a = 0
# name.b = 0
# print(name.conf)
# print(dir(name))
# print(vars(name))
# print(vars(BaseName))
# print(BaseName.members)
# print(name.members)
# class TEMP:
# k = SizedString(lenmin=2, lenmax=3)
# t = TEMP()
# t.k = 1
| {"/basecls_test.py": ["/basecls.py"]} |
46,908 | toytag/LanguageModeling | refs/heads/master | /tokenizer.py | import re, json
from collections import Counter
class WordTokenizer:
def __init__(
self,
vocab_file=None,
vocab_size_limit=10000,
min_freq=10,
lowercase=True,
special_tokens=[]
):
pattern = r'[a-zA-Z0-9\']+|[,<.>/?;:\'\"\[\{\]\}\\\|\-_=\+`~!@#$%^&*\(\)]'
if vocab_file:
with open(vocab_file, 'r') as f:
config = json.load(f)
lowercase = config['lowercase']
special_tokens = config['special_tokens']
self.p = re.compile(r''.join([s + r'|' for s in special_tokens]) + pattern)
self.vocab_size_limit = vocab_size_limit
self.min_freq = min_freq
self.lowercase = lowercase
self.special_tokens = special_tokens
self.vocab = Counter() if not vocab_file else Counter(config['vocab'])
self.vocab_size = 0
self.token2id = {}
self._token2id_updated = False
self.id2token = {}
self._id2token_updated = False
if vocab_file:
self._update_token2id()
self._update_id2token()
def build_vocab(self, corpus):
if self.lowercase:
corpus = corpus.lower()
tokens = self.p.findall(corpus)
self.vocab += Counter(tokens)
self._token2id_updated = False
self._id2token_updated = False
def _update_token2id(self):
# 0 reserved, 1 for unknown token
self.token2id = {special_token: i + 2 for i, special_token in enumerate(self.special_tokens)}
for i, (vocab, freq) in enumerate(self.vocab.most_common()):
i = i + len(self.special_tokens) + 2
if freq >= self.min_freq and i < self.vocab_size_limit:
self.token2id[vocab] = i
self.vocab_size = len(self.token2id.keys()) + 2
self._token2id_updated = True
def _update_id2token(self):
# 0 reserved, 1 for unknown token
self.id2token = {i + 2: special_token for i, special_token in enumerate(self.special_tokens)}
for i, (vocab, freq) in enumerate(self.vocab.most_common()):
i = i + len(self.special_tokens) + 2
if freq >= self.min_freq and i < self.vocab_size_limit:
self.id2token[i] = vocab
self.vocab_size = len(self.id2token.keys()) + 2
self._id2token_updated = True
def encode(self, text):
if not self._token2id_updated:
self._update_token2id()
if self.lowercase:
text = text.lower()
return [self.token2id.get(token, 1) for token in self.p.findall(text)]
def decode(self, ids):
if not self._id2token_updated:
self._update_id2token()
return ' '.join([self.id2token.get(id_, '[UNK]') for id_ in ids])
def save(self, filename):
with open(filename, 'w') as f:
json.dump({
'lowercase': self.lowercase,
'special_tokens': self.special_tokens,
'vocab': self.vocab
},f, indent=4)
import os
from tqdm import tqdm
if __name__ == '__main__':
data_dir = 'data/Gutenberg/split/'
txt_files = [data_dir + file_name for file_name in os.listdir(data_dir)]
tokenizer = WordTokenizer(special_tokens=['<mask>'])
for txt_file in tqdm(txt_files):
with open(txt_file, 'r') as f:
text = f.read()
tokenizer.build_vocab(text)
print(tokenizer.decode(tokenizer.encode('what are you <mask> fadskjfaf')))
print('vocab size:', tokenizer.vocab_size)
tokenizer.save('models/tokenizer/tokenizer.json')
tokenizer = WordTokenizer('models/tokenizer/tokenizer.json', vocab_size_limit=30000)
print(tokenizer.decode(tokenizer.encode('what are you <mask> fadskjfaf')))
print('vocab size:', tokenizer.vocab_size) | {"/evaluate.py": ["/tokenizer.py", "/model.py"], "/dataset.py": ["/tokenizer.py"], "/train.py": ["/dataset.py", "/model.py"]} |
46,909 | toytag/LanguageModeling | refs/heads/master | /model.py | import torch
from torch import nn
from LearnTransformer import PositionalEncoding, TransformerBlock
class LanguageModel(nn.Module):
def __init__(self, n_vocab, d_model=256, d_hidden=1024, n_layer=8,
n_head=8, d_k=32, d_v=32, n_position=64, dropout=0.1,
embed_weight_sharing=True):
super(LanguageModel, self).__init__()
self.embed = nn.Embedding(n_vocab, d_model, padding_idx=0)
self.pos_enc = PositionalEncoding(d_model, n_position=n_position)
self.dropout = nn.Dropout(p=dropout)
self.transformers = nn.ModuleList([
TransformerBlock(d_model, d_hidden, n_head, d_k, d_v, dropout=dropout)
for _ in range(n_layer)
])
self.lm_head = nn.Linear(d_model, n_vocab, bias=False)
self.bias = nn.Parameter(torch.zeros(n_vocab))
if embed_weight_sharing:
self.lm_head.weight = self.embed.weight
def forward(self, src_seq, src_mask=None):
output = self.dropout(self.pos_enc(self.embed(src_seq)))
for transformer_block in self.transformers:
output, _ = transformer_block(output, src_mask)
output = self.lm_head(output) + self.bias
return output,
def num_params(self):
return sum(p.numel() for p in self.parameters() if p.requires_grad)
if __name__ == '__main__':
# test
model = LanguageModel(n_vocab=10000)
print(model.num_params())
with torch.no_grad():
model.eval()
input_, mask = torch.LongTensor([[1, 2, 4, 8]]), torch.LongTensor([[1, 1, 1, 0]])
output, *_ = model(input_.masked_fill(mask==0, 0), src_mask=mask)
print(output)
| {"/evaluate.py": ["/tokenizer.py", "/model.py"], "/dataset.py": ["/tokenizer.py"], "/train.py": ["/dataset.py", "/model.py"]} |
46,910 | toytag/LanguageModeling | refs/heads/master | /evaluate.py | import torch
import torch.nn.functional as F
from tokenizer import WordTokenizer
from model import LanguageModel
if __name__ == '__main__':
tokenizer = WordTokenizer('models/tokenizer/tokenizer.json')
checkpoint = torch.load('models/lm/latest.pth')
model = LanguageModel(n_vocab=10000)
model.load_state_dict(checkpoint['model_state_dict'])
input_tokens = tokenizer.encode('a king is a man and a queen is a <mask>')
input_tokens = torch.LongTensor([input_tokens])
input_mask = torch.ones_like(input_tokens)
input_mask[0, -1] = 0
with torch.no_grad():
model.eval()
output, *_ = model(input_tokens, src_mask=input_mask)
output = torch.argmax(F.softmax(output, dim=-1), dim=-1).squeeze(0).numpy()
print(tokenizer.decode(output)) | {"/evaluate.py": ["/tokenizer.py", "/model.py"], "/dataset.py": ["/tokenizer.py"], "/train.py": ["/dataset.py", "/model.py"]} |
46,911 | toytag/LanguageModeling | refs/heads/master | /preprocess.py | import os, shutil
from tqdm.contrib.concurrent import thread_map
data_dir = 'data/Gutenberg/txt/'
txt_files = [(i, data_dir + file_name) for i, file_name in enumerate(os.listdir(data_dir))]
split_file_dir = 'data/Gutenberg/split/'
def proprocess(args):
idx, file_name = args
with open(file_name, 'r', encoding='utf-8', errors='ignore') as f:
text = [string.replace('\n', ' ') for string in f.read().split('\n\n')]
with open(split_file_dir + f'f{idx%100:02d}.txt', 'a') as f:
f.write('\n\n'.join(text) + '\n')
if __name__ == '__main__':
if os.path.exists(split_file_dir):
shutil.rmtree(split_file_dir)
os.mkdir(split_file_dir)
thread_map(proprocess, txt_files, max_workers=os.cpu_count()) | {"/evaluate.py": ["/tokenizer.py", "/model.py"], "/dataset.py": ["/tokenizer.py"], "/train.py": ["/dataset.py", "/model.py"]} |
46,912 | toytag/LanguageModeling | refs/heads/master | /dataset.py | import os, time
from multiprocessing import Pool, Manager
import numpy as np
from tqdm import tqdm
import torch
from torch.utils.data import Dataset, DataLoader
from tokenizer import WordTokenizer
tokenizer = WordTokenizer('models/tokenizer/tokenizer.json')
class TextDataset(Dataset):
def __init__(self, txt_file, block_len=64, mlm_percentage=0.15):
with open(txt_file, 'r', encoding='utf-8') as f:
textlines = f.readlines()
self.examples = []
self.block_len = block_len
for line in textlines:
new_tokens = tokenizer.encode(line)
if len(new_tokens) < self.block_len:
new_tokens = [0,] * ((64 - len(new_tokens)) // 2) + \
new_tokens + [0,] * ((64 - len(new_tokens)) // 2 + 1)
self.examples.append(new_tokens)
self.mlm_percentage = mlm_percentage
def __len__(self):
return len(self.examples)
def __getitem__(self, idx):
seq = self.examples[idx]
i = np.random.randint(0, len(seq) - self.block_len) if len(seq) > self.block_len else 0
seq = torch.LongTensor(seq[i:i + self.block_len])
mask_idx = np.random.randint(0, self.block_len, size=np.int(self.block_len * self.mlm_percentage))
mask = torch.ones_like(seq)
mask[mask_idx] = 0
return seq, mask
def _enqueue_dataloader(txt_file, batch_size, block_len, shuffle, pin_memory, num_workers, q):
# enqueue (file_name, DataLoader)
q.put(DataLoader(TextDataset(txt_file, block_len),
batch_size, shuffle=shuffle, pin_memory=pin_memory, num_workers=num_workers))
class TextDataLoaderIterator:
def __init__(self, txt_files, batch_size=64, block_len=64, shuffle=True,
pin_memory=True, num_workers=os.cpu_count(), prefetch_limit=10):
self.m = Manager()
self.p = Pool(num_workers)
self.q = self.m.Queue(prefetch_limit)
for txt_file in txt_files:
self.p.apply_async(_enqueue_dataloader,
(txt_file, batch_size, block_len, shuffle, pin_memory, num_workers, self.q))
self.idx = 0
self.end_idx = len(txt_files)
def __len__(self):
return self.end_idx
def __iter__(self):
return self
def __next__(self):
if self.idx == self.end_idx:
self.p.close()
raise StopIteration
self.idx += 1
return self.q.get()
from tqdm import tqdm
if __name__ == '__main__':
data_dir = 'data/Gutenberg/txt/'
txt_files = [data_dir+file_name for file_name in os.listdir(data_dir)][:2]
dataloader_iter = TextDataLoaderIterator(txt_files, 64, 64)
dataloader = next(iter(dataloader_iter))
seq, mask = next(iter(dataloader))
assert seq.shape == mask.shape | {"/evaluate.py": ["/tokenizer.py", "/model.py"], "/dataset.py": ["/tokenizer.py"], "/train.py": ["/dataset.py", "/model.py"]} |
46,913 | toytag/LanguageModeling | refs/heads/master | /train.py | import os, time
import numpy as np
from tqdm import tqdm
import torch
from torch import nn, optim
import torch.nn.functional as F
from torch.utils.tensorboard import SummaryWriter
from dataset import TextDataLoaderIterator
from model import LanguageModel
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
data_dir = 'data/Gutenberg/split/'
txt_files = [data_dir + file_name for file_name in os.listdir(data_dir)][:5]
if __name__ == '__main__':
# checkpoint = torch.load('models/lm/latest.pth')
model = LanguageModel(n_vocab=10000).to(device)
# model.load_state_dict(checkpoint['model_state_dict'])
optimizer = optim.Adam(model.parameters(), lr=1e-4)
# optimizer.load_state_dict(checkpoint['optimizer_state_dict'])
lr_scheduler = optim.lr_scheduler.ReduceLROnPlateau(optimizer, factor=0.95, patience=100, min_lr=1e-6)
# lr_scheduler.load_state_dict(checkpoint['lr_scheduler_state_dict'])
criterion = nn.CrossEntropyLoss()
writer = SummaryWriter(f'runs/{time.strftime('%Y%m%d-%I:%M%p', time.localtime())}')
dummy_input = torch.LongTensor([[1]]).to(device)
writer.add_graph(model, dummy_input)
# global_step = checkpoint['global_step']
global_step = 0
for epoch in range(10):
pbar = tqdm(TextDataLoaderIterator(txt_files, batch_size=16, block_len=64))
for data_loader in pbar:
for seq, mask in data_loader:
seq, mask = seq.to(device), mask.to(device)
output, *_ = model(seq.masked_fill(mask==0, 0), src_mask=mask)
# loss = criterion(output[mask==0], seq[mask==0])
loss = criterion(output.view(-1, 10000), seq.view(-1))
optimizer.zero_grad()
loss.backward()
optimizer.step()
lr_scheduler.step(loss)
global_step += 1
writer.add_scalar('loss', loss.item(), global_step)
writer.add_scalar('lr', optimizer.param_groups[0]['lr'], global_step)
pbar.set_postfix({'loss': loss.item(), 'lr': optimizer.param_groups[0]['lr']})
torch.save({
'global_step': global_step,
'model_state_dict': model.state_dict(),
'optimizer_state_dict': optimizer.state_dict(),
'lr_scheduler_state_dict': lr_scheduler.state_dict(),
}, 'models/lm/latest.pth')
| {"/evaluate.py": ["/tokenizer.py", "/model.py"], "/dataset.py": ["/tokenizer.py"], "/train.py": ["/dataset.py", "/model.py"]} |
46,919 | siliconcortex/caminade_shop | refs/heads/master | /shop/standard_email.py | import yagmail
def send_email(sender, contents):
"""yagmail is a library to manage google smtp in a more simpler manner,
for more information, visit https://github.com/kootenpv/yagmail"""
USERNAME = 'cortexsilicon'
APP_PASSWORD = 'jnzbhrbqcsavnlhu'
yag = yagmail.SMTP(USERNAME, APP_PASSWORD) #input the email username and app password
SEND_TO = ['lesliecaminade@gmail.com'] #this will be a list of receivers
SUBJECT = f"""From: {sender} via caminadeshop.pythonanywhere.com"""
CONTENTS = contents
yag.send(to = SEND_TO, subject = SUBJECT, contents = CONTENTS) #send the email
if __name__ == '__main__':
send_email()
| {"/shop/models.py": ["/shop/standard_email.py"], "/shop/views.py": ["/shop/standard_email.py"]} |
46,920 | siliconcortex/caminade_shop | refs/heads/master | /shop/models.py | from django.db import models
from django.urls import reverse_lazy, reverse
from .image_helpers import Thumbnail
from django.contrib.auth.models import User
from .standard_email import send_email
# Create your models here.
class Image(models.Model):
caption = models.CharField(max_length = 100)
image = models.ImageField(upload_to = 'shop/images')
class Item(models.Model):
name = models.CharField(max_length = 500)
price = models.DecimalField(decimal_places = 2, max_digits = 10)
main_image = models.ImageField(upload_to = 'shop/main_images', null = True)
thumbnail = models.ImageField(upload_to = 'shop/thumbnails', null = True)
images = models.ManyToManyField(Image)
stars = models.IntegerField(default = 5)
description = models.CharField(max_length = 2000)
stock = models.IntegerField(default = 1)
def get_absolute_url(self):
return reverse('shop:item_detail', kwargs={'pk': self.pk})
def get_success_url(self):
return reverse('shop:item_list')
def create_thumbnail(self):
self.thumbnail = self.main_image
self.save()
image_generator = Thumbnail(source=self.thumbnail)
modified_image_file = image_generator.generate()
dest = open(self.thumbnail.path, 'wb')
dest.write(modified_image_file.read())
dest.close()
class Customer(models.Model):
full_name = models.CharField(max_length = 100)
email = models.EmailField()
contact_number = models.CharField(max_length = 100)
message = models.TextField()
def get_success_url(self):
return reverse('shop:item_list')
def get_absolute_url(self):
return reverse('shop:item_list')
def send(self):
contents = f"""
<html>
<body>
<ul>
<li>{self.full_name} </li>
<li>{self.email} </li>
<li>{self.contact_number} </li>
<li>{self.message} </li>
</ul>
</body>
</html>"""
send_email(self.full_name, contents)
| {"/shop/models.py": ["/shop/standard_email.py"], "/shop/views.py": ["/shop/standard_email.py"]} |
46,921 | siliconcortex/caminade_shop | refs/heads/master | /shop/views.py | from django.shortcuts import render
from django.urls import reverse_lazy, reverse
from django.http import HttpResponse, HttpResponseRedirect
from django.views.generic import View
from . import models
from . import forms
from django.utils import timezone
from django.views.generic.edit import FormView, CreateView, DeleteView, UpdateView
from django.views.generic.list import ListView
from django.views.generic.detail import DetailView
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
import requests
from .standard_email import send_email
class AdminStaffRequiredMixin(LoginRequiredMixin, UserPassesTestMixin):
def test_func(self):
return self.request.user.is_superuser or self.request.user.is_staff
class IndexView(ListView):
model = models.Item
class ItemCreateView(CreateView, AdminStaffRequiredMixin):
model = models.Item
fields = ['name', 'description','main_image', 'price', 'stock']
#modify the createview to create a thumbnail while saving the files
def form_valid(self, form):
#the thumbnail code
self.object = form.save()
self.object.create_thumbnail()
#inheritance code(do not modify)
return super().form_valid(form)
class ItemDetailView(DetailView):
model = models.Item
class ItemDeleteView(DeleteView, AdminStaffRequiredMixin):
model = models.Item
success_url = reverse_lazy('shop:item_list')
class ItemUpdateView(UpdateView, AdminStaffRequiredMixin):
model = models.Item
fields = ['name', 'description', 'main_image', 'price', 'stock']
#modify the createview to create a thumbnail while saving the files
def form_valid(self, form):
#the thumbnail code
self.object = form.save()
self.object.create_thumbnail()
#inheritance code(do not modify)
return super().form_valid(form)
# Create your views here.
class OrderRequest(CreateView):
model = models.Customer
fields = '__all__'
def form_valid(self, form):
SECRET_KEY = '6Lfh4r0ZAAAAAGcQz-3_OUkWr2kOgOXVk7zigK3v'
recaptcha_response = self.request.POST.get('g-recaptcha-response') #get ggoogle recapthcha response from form
r = requests.post('https://www.google.com/recaptcha/api/siteverify', data = {
'secret': SECRET_KEY,
'response': recaptcha_response,
})
r = r.json()
if r['success'] == 'false':
return render(self.request, 'shop/failed.html')
pass
else:
self.object = form.save()
self.object.send()
#inheritance code(do not modify)
return super().form_valid(form)
| {"/shop/models.py": ["/shop/standard_email.py"], "/shop/views.py": ["/shop/standard_email.py"]} |
46,922 | siliconcortex/caminade_shop | refs/heads/master | /shop/urls.py | from django.urls import path
from . import views
from django.urls import include, path
app_name = 'shop'
urlpatterns = [
path('item_list', views.IndexView.as_view(), name = 'item_list'),
path('item_create', views.ItemCreateView.as_view(), name = 'item_create'),
path('item_detail/<pk>', views.ItemDetailView.as_view(), name = 'item_detail'),
path('item_delete/<pk>', views.ItemDeleteView.as_view(), name = 'item_delete'),
path('item_update/<pk>', views.ItemUpdateView.as_view(), name = 'item_update'),
path('order_request/', views.OrderRequest.as_view(), name = 'order_request'),
]
| {"/shop/models.py": ["/shop/standard_email.py"], "/shop/views.py": ["/shop/standard_email.py"]} |
46,923 | mr-sagarmandal/modtran_requester | refs/heads/main | /csv_writer_utils.py | import csv
import sys
import utils
from datetime import datetime
def merge_lists(list1, list2):
list1.extend(list2)
return list1
def merge_dicts(base_dict, curr_dict):
used_keys = {'x'}
for key in base_dict.keys():
if key in used_keys:
continue
closest_key = ''
closest_diff = sys.float_info.max
backward = False
for curr_key in curr_dict.keys():
if curr_key in used_keys:
continue
base_last_curr_first = abs(base_dict[key][-1] - curr_dict[curr_key][0])
if closest_diff > base_last_curr_first:
closest_diff = base_last_curr_first
closest_key = curr_key
used_keys.add(closest_key)
base_dict[key] = merge_lists(base_dict[key], curr_dict[closest_key])
base_dict['x'] = merge_lists(base_dict['x'], curr_dict['x'])
return base_dict
def merge_all_dicts(data):
merged_rows = {}
for key in sorted(data.keys()):
if len(merged_rows) == 0:
merged_rows = data[key]
continue
merged_rows = merge_dicts(merged_rows, data[key])
return merged_rows
def write_csv(content, payLoad, fileName):
datetimeNow = datetime.utcnow().strftime('%y-%m-%d_%H-%M-%S')
utils.make_outputdir_if_absent()
with open("./out/{}_{}.csv".format(fileName, datetimeNow), 'w+', newline='') as output_file:
data_writer = csv.writer(output_file, delimiter='\t', quotechar='"', quoting=csv.QUOTE_MINIMAL)
data_writer.writerow(payLoad.keys())
data_writer.writerow(payLoad.values())
header_row = sorted(content.keys(), reverse=True)
data_writer.writerow(header_row)
for i in range(0, len(content['x'])):
row = []
for key in sorted(content.keys(), reverse=True):
row.append(content[key][i])
data_writer.writerow(row)
| {"/csv_writer_utils.py": ["/utils.py"], "/modtran_request.py": ["/modtran_client.py"], "/verification.py": ["/csv_writer_utils.py", "/formatting_utils.py"], "/modtran_client.py": ["/csv_writer_utils.py", "/formatting_utils.py", "/utils.py"]} |
46,924 | mr-sagarmandal/modtran_requester | refs/heads/main | /formatting_utils.py |
import json
def getFormattedData(content):
flux_script = json.loads(content)['flux_script']
docs_json_first_ind = flux_script.index("docs_json = ") + len("docs_json = ")
docs_json_end_ind = flux_script.index(";", docs_json_first_ind)
docs_json = flux_script[docs_json_first_ind + 1:docs_json_end_ind - 1]
docs_json = json.loads(docs_json)
out_data = {}
for key in docs_json:
data_root = docs_json[key]
for reference in data_root["roots"]["references"]:
if "attributes" in reference:
if "data" in reference["attributes"]:
if "x" in reference["attributes"]["data"]:
out_data["x"] = reference["attributes"]["data"]["x"]
if "y" in reference["attributes"]["data"]:
out_data[reference["id"]] = reference["attributes"]["data"]["y"]
return out_data | {"/csv_writer_utils.py": ["/utils.py"], "/modtran_request.py": ["/modtran_client.py"], "/verification.py": ["/csv_writer_utils.py", "/formatting_utils.py"], "/modtran_client.py": ["/csv_writer_utils.py", "/formatting_utils.py", "/utils.py"]} |
46,925 | mr-sagarmandal/modtran_requester | refs/heads/main | /modtran_request.py | import modtran_client
## rtmode choices are: RT_SOLAR_AND_THERMAL, RT_TRANSMITTANCE
## atmosphere_model choices are: ATM_MIDLAT_SUMMER, ATM_US_STANDARD_1976, ATM_SUBARC_WINTER, ATM_SUBARC_SUMMER, ATM_TROPICAL, ATM_MIDLAT_WINTER
## spectral_units choices are: microns, wavenumbers
## aerosol_model are: AER_MARITIME_NAVY, AER_RURAL, AER_DESERT, AER_URBAN
payLoad = {
"csrfmiddlewaretoken" : "bh9S5umFxQk4EFeYJjH7qmdQS4acxNVI",
"rtmode" : "RT_SOLAR_AND_THERMAL" ,
"atmosphere_model" : "ATM_MIDLAT_SUMMER" ,
"water_column" : 5000 ,
"ozone_column" : 0.33176 ,
"co2_ppmv" : 400 ,
"co_ppmv" : 0.15 ,
"co_ppmv_ref" : 0.15 ,
"ch4_ppmv" : 1.8 ,
"ch4_ppmv_ref" : 1.7 ,
"n2o_ppmv" : 0.32 ,
"n2o_ppmv_ref" : 0.32 ,
"f11_ppbv" : 0.14 ,
"f11_ppbv_ref" : 0.14 ,
"f12_ppbv" : 0.24 ,
"f12_ppbv_ref" : 0.24 ,
"f22_ppbv" : 0.06 ,
"f22_ppbv_ref" : 0.06 ,
"f113_ppbv" : 0.019 ,
"f113_ppbv_ref" : 0.019 ,
"f114_ppbv" : 0.012 ,
"f114_ppbv_ref" : 0.012 ,
"ccl4_ppbv" : 0.13 ,
"ccl4_ppbv_ref" : 0.13 ,
"ground_temp_K" : 294.2 ,
"ground_emission" : 0 ,
"aerosol_model" : "AER_RURAL" ,
"visibility_km" : 23.0 ,
"sens_altitude_km" : 50 ,
"sens_zenith_deg" : 180 ,
"path_range_km" : 70 ,
"solar_zenith_deg" : 0 ,
"solar_azimuth_deg" : 0 ,
"spectral_units" : "wavenumbers" ,
"specrng_min" : 250 ,
"specrng_max" : 500 ,
"resolution" : 0.2,
}
range_pairs = [
[250, 2500, 2.2],
[2500, 4000, 4]
]
if __name__ == "__main__":
modtran_client.get_and_write_data(range_pairs, payLoad)
| {"/csv_writer_utils.py": ["/utils.py"], "/modtran_request.py": ["/modtran_client.py"], "/verification.py": ["/csv_writer_utils.py", "/formatting_utils.py"], "/modtran_client.py": ["/csv_writer_utils.py", "/formatting_utils.py", "/utils.py"]} |
46,926 | mr-sagarmandal/modtran_requester | refs/heads/main | /verification.py |
import csv_writer_utils
import formatting_utils
def getSampleContent(fileName):
all_of_it = ""
try:
with open(fileName, mode='r') as file:
all_of_it = file.read()
finally:
file.close()
return all_of_it
if __name__ == "__main__":
content = getSampleContent("test.txt")
formatted_data = formatting_utils.getFormattedData(content)
csv_writer_utils.write_csv(formatted_data, "validation")
| {"/csv_writer_utils.py": ["/utils.py"], "/modtran_request.py": ["/modtran_client.py"], "/verification.py": ["/csv_writer_utils.py", "/formatting_utils.py"], "/modtran_client.py": ["/csv_writer_utils.py", "/formatting_utils.py", "/utils.py"]} |
46,927 | mr-sagarmandal/modtran_requester | refs/heads/main | /modtran_client.py | import requests
import time
import csv_writer_utils
import formatting_utils
import utils
headers = {
'Host' : 'modtran.spectral.com',
'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:88.0) Gecko/20100101 Firefox/88.0',
'Accept' : 'application/json, text/javascript, */*; q=0.01',
'Accept-Language' : 'en-US,en;q=0.5',
'Accept-Encoding' : 'gzip, deflate',
'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8',
'X-CSRFToken' : 'bh9S5umFxQk4EFeYJjH7qmdQS4acxNVI',
'X-Requested-With' : 'XMLHttpRequest',
'Content-Length' : '725',
'Origin' : 'http://modtran.spectral.com',
'Connection' : 'keep-alive',
'Referer' : 'http://modtran.spectral.com/modtran_home',
'Cookie' : 'csrftoken=bh9S5umFxQk4EFeYJjH7qmdQS4acxNVI'
}
def getContentText(headers, payLoad):
url = "http://modtran.spectral.com/ajaxRunModtran"
s = requests.Session()
content = s.post(url, data=payLoad, headers=headers)
return content.text
def get_data_for_ranges(range_params, payLoad):
data_for_ranges = {}
range_params.sort(key=lambda params : params[0])
for range in range_params:
payLoad['specrng_min'] = range[0]
payLoad['specrng_max'] = range[1]
payLoad['resolution'] = range[2]
headers["Content-Length"] = str(utils.calculate_content_length(payLoad))
content = getContentText(headers, payLoad)
formatted_data = formatting_utils.getFormattedData(content)
data_for_ranges[range[0]] = formatted_data
time.sleep(1)
merged_rows = csv_writer_utils.merge_all_dicts(data_for_ranges)
return merged_rows
def write_rows_to_csv(fileName,merged_rows, payLoad):
csv_writer_utils.write_csv(merged_rows, payLoad, fileName)
def get_and_write_data(range_params, payLoad):
merged_rows = get_data_for_ranges(range_params, payLoad)
fileName = utils.get_file_name(range_params)
[payLoad.pop(key) for key in ["specrng_max", "specrng_min", "resolution", "csrfmiddlewaretoken"]]
write_rows_to_csv(fileName, merged_rows, payLoad) | {"/csv_writer_utils.py": ["/utils.py"], "/modtran_request.py": ["/modtran_client.py"], "/verification.py": ["/csv_writer_utils.py", "/formatting_utils.py"], "/modtran_client.py": ["/csv_writer_utils.py", "/formatting_utils.py", "/utils.py"]} |
46,928 | mr-sagarmandal/modtran_requester | refs/heads/main | /utils.py | import os
import sys
def dumpContent(content):
try:
with open('./out/out.json', 'w+') as file:
file.write(json.dumps(content, indent=4))
finally:
file.close()
def calculate_content_length(payload):
keys = payload.keys()
values = payload.values()
totalLength = len(keys) - 1 + len(keys) #ampersands in between each kv pair and = sign
for key in keys:
totalLength += len(str(key))
for val in values:
totalLength += len(str(val))
return totalLength
def make_outputdir_if_absent():
if not os.path.isdir('./out'):
os.mkdir('./out')
def get_min_max_range(range_params):
minimum = sys.maxsize
maximum = -1
for range in range_params:
minimum = min(minimum, range[0])
maximum = max(maximum, range[1])
return [minimum, maximum]
def get_file_name(range_params):
min_max = get_min_max_range(range_params)
return "{}-{}".format(min_max[0], min_max[1])
def get_payload_row(payLoad):
row = []
for key, value in payLoad:
if key in ("specrng_max", "specrng_min", "resolution"):
continue
row.append("{}-{}".format(key, value))
return row
if __name__ == "__main__":
make_outputdir_if_absent() | {"/csv_writer_utils.py": ["/utils.py"], "/modtran_request.py": ["/modtran_client.py"], "/verification.py": ["/csv_writer_utils.py", "/formatting_utils.py"], "/modtran_client.py": ["/csv_writer_utils.py", "/formatting_utils.py", "/utils.py"]} |
46,935 | EliRibble/pre-commit-change-id | refs/heads/main | /setup.py | "Logic for installing the module."
import setuptools # type: ignore
setuptools.setup(
install_requires=[
"precommit-message-preservation==0.6",
],
extras_require={
"develop": [
"mypy",
"nose2",
"pylint",
"twine",
"wheel",
]
},
)
| {"/test_pcci.py": ["/precommit_changeid/__init__.py"]} |
46,936 | EliRibble/pre-commit-change-id | refs/heads/main | /test_pcci.py | "Tests for the eureka_prepare_commit_message module"
import contextlib
import re
from typing import Generator
import unittest
import unittest.mock
from nose2.tools import params # type: ignore
import precommit_changeid as pci
SAMPLE_VERBOSE_COMMIT_LINES = [
"This is some summary line.",
"",
"You'll notice that even though this is just a test I have ",
"a properly formatted fake git commit message here. That's ",
"dedication to my craft, baby.",
"# Please enter the commit message for your changes. Lines starting",
"# with '#' will be ignored, and an empty message aborts the commit.",
"#",
"# On branch master",
"# Your branch is up to date with 'eureka/master'.",
"#",
"# Changes to be committed:",
"# modified: .pre-commit-config.yaml",
"#",
"# ------------------------ >8 ------------------------",
"# Do not modify or remove the line above.",
"# Everything below it will be ignored.",
"diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml",
"index d4fa34892..ae20e5c0a 100644",
"--- a/.pre-commit-config.yaml",
"+++ b/.pre-commit-config.yaml",
"@@ -31,13 +31,13 @@ repos:",
"...and so on.",
]
SAMPLE_VERBOSE_COMMIT = "\n".join(SAMPLE_VERBOSE_COMMIT_LINES)
SAMPLE_VERBOSE_COMMIT_CONTENT = "\n".join(SAMPLE_VERBOSE_COMMIT_LINES[:5])
SAMPLE_VERBOSE_COMMIT_DIFF = "\n" + "\n".join(SAMPLE_VERBOSE_COMMIT_LINES[5:])
@contextlib.contextmanager
def fake_cached_message(message: str) -> Generator[None, None, None]:
"Patch the routine to get the cached message to return something."
with unittest.mock.patch(
"precommit_message_preservation.get_cached_message",
return_value=message):
yield
@contextlib.contextmanager
def fake_current_message(message: str) -> Generator[None, None, None]:
"Patch the routine to get the current message to return something."
with unittest.mock.patch("builtins.open", unittest.mock.mock_open(read_data=message)):
yield
@contextlib.contextmanager
def specific_change_id(change_id: str) -> Generator[None, None, None]:
"Make sure that a specific commit Id tag is generated."
with unittest.mock.patch("precommit_changeid.create_change_id", return_value=change_id):
yield
class ChangeIdTestBase(unittest.TestCase):
"Base class includes some asserts for Change-Id tags."
def assert_has_changeid(self, content: str, value: str) -> None:
"Assert that we can find the provided tag in the content."
_, change_id = pci.extract_change_id(content)
self.assertEqual(change_id, value)
def assert_not_has_changeid(self, content: str) -> None:
"Assert that we can find the provided tag in the content."
_, change_id = pci.extract_change_id(content)
self.assertEqual(change_id, "")
class TestGetSuggestedContent(ChangeIdTestBase):
"Tests for all suggested commit message content."
def test_previous_commit_message(self) -> None:
"Test that we use the previous commit message."
with fake_cached_message("Some summary"):
suggestion = pci.get_suggested_content("somefile")
self.assertTrue(suggestion.startswith("Some summary"))
def test_adds_tag_placeholders(self) -> None:
"Can we add tag placeholders for all the tags/"
with fake_cached_message("Some summary"):
with specific_change_id("Iabcde1234567890"):
suggestion = pci.get_suggested_content("somefile")
self.assert_has_changeid(suggestion, "Iabcde1234567890")
def test_changeid_length(self) -> None:
"Does our suggested changeid have the proper length?"
with fake_cached_message(""):
with fake_current_message("Some summary\n\nmore information"):
suggestion = pci.get_suggested_content("somefile")
match = re.search(r"Change-Id: (?P<changeid>\w+)", suggestion)
assert match
changeid = match.group("changeid")
self.assertEqual(len(changeid), 41)
def test_new_commit_message(self) -> None:
"Test that we honor what the user provided on the commandline via 'git commit -m"
with fake_cached_message(""):
with fake_current_message("Some summary\n\nmore information"):
suggestion = pci.get_suggested_content("somefile")
self.assertTrue(suggestion.startswith("Some summary\n\nmore information"))
def test_new_commit_message_and_previous(self) -> None:
"Test that we present both the current commit message and previous commit messages."
with fake_cached_message("An old summary\n\nold details"):
with fake_current_message("Some summary\n\nmore information"):
suggestion = pci.get_suggested_content("somefile")
self.assertTrue(suggestion.startswith("Some summary\n\nmore information"))
self.assertIn("An old summary\n\nold details", suggestion)
self.assertIn("previously saved message below", suggestion)
def test_verbose_commit_no_cached(self) -> None:
"When user specifies 'git commit -m \"something\" -v' we put everything in the right order."
with fake_cached_message(""):
with fake_current_message(SAMPLE_VERBOSE_COMMIT):
with specific_change_id("Iabcde1234567890"):
suggestion = pci.get_suggested_content("somefile")
expected = (SAMPLE_VERBOSE_COMMIT_CONTENT + "\n\n" +
"Change-Id: Iabcde1234567890" +
SAMPLE_VERBOSE_COMMIT_DIFF)
self.assertEqual(suggestion, expected)
def test_verbose_commit_with_cached(self) -> None:
"When user specifies 'git commit -m \"something\" -v' we put everything in the right order."
with fake_cached_message("Some summary.\n\nSome body"):
with fake_current_message(SAMPLE_VERBOSE_COMMIT):
with specific_change_id("Iabcde1234567890"):
suggestion = pci.get_suggested_content("somefile")
expected = (SAMPLE_VERBOSE_COMMIT_CONTENT + "\n" +
"# ==== previously saved message below ====\n" +
"Some summary.\n\n" +
"Some body\n\n" +
"Change-Id: Iabcde1234567890" +
SAMPLE_VERBOSE_COMMIT_DIFF)
self.assertEqual(suggestion, expected)
def test_change_id_blank_line_after(self) -> None:
"Do we detect the Change-Id when present with a blank line after?"
message = "\n".join((
"A summary line",
"",
"Some detailed message line.",
"Change-Id: I0102030405060708090001020304050607080900",
"",
))
with fake_current_message(message):
with fake_cached_message(""):
suggestion = pci.get_suggested_content("somefile")
expected = "\n".join((
"A summary line",
"",
"Some detailed message line.",
"",
"Change-Id: I0102030405060708090001020304050607080900",
))
self.assertEqual(suggestion, expected)
def test_change_id_blank_line_before(self) -> None:
"Do we detect the Change-Id when present with a blank line before?"
message = "\n".join((
"A summary line",
"",
"Some detailed message line.",
"",
"Change-Id: I0102030405060708090001020304050607080900",
))
with fake_current_message(message):
with fake_cached_message(""):
suggestion = pci.get_suggested_content("somefile")
expected = "\n".join((
"A summary line",
"",
"Some detailed message line.",
"",
"Change-Id: I0102030405060708090001020304050607080900",
))
self.assertEqual(suggestion, expected)
def test_change_id_blank_line_both(self) -> None:
"Do we detect the Change-Id when present with a blank line before?"
message = "\n".join((
"A summary line",
"",
"Some detailed message line.",
"",
"Change-Id: I0102030405060708090001020304050607080900",
))
with fake_current_message(message):
with fake_cached_message(""):
suggestion = pci.get_suggested_content("somefile")
expected = "\n".join((
"A summary line",
"",
"Some detailed message line.",
"",
"Change-Id: I0102030405060708090001020304050607080900",
))
self.assertEqual(suggestion, expected)
class TestExtractTags(ChangeIdTestBase):
"Tests for logic around extracting tags."
@params(("Change-Id",), ("CHANGE-ID",), ("change-id",))
def test_has_change_id_tag(self, name: str) -> None:
"Test we can detect change_id tags."
self.assert_has_changeid("Foo\n{}: I12345abcde".format(name), "I12345abcde")
def test_no_change_id_tag(self) -> None:
"Test we can detect lack of change_id tag."
self.assert_not_has_changeid("No\nChange-Id\nTag")
class TestSplitVerboseCode(unittest.TestCase):
"Test split_verbose_code()"
def test_no_verbose_code(self) -> None:
"Ensure we get correct split when no verbose code is present."
content = "\n".join([
"This is some summary line.",
"",
"This is just some text where I don't have anything useful ",
"to say. I'm just showing that there's no verbose code here.",
])
before, after = pci.split_verbose_code(content)
self.assertEqual(before, content)
self.assertEqual("", after)
def test_verbose_code(self) -> None:
"Ensure we split between message and verbose code"
before, after = pci.split_verbose_code("\n".join(SAMPLE_VERBOSE_COMMIT_LINES))
self.assertEqual(before, SAMPLE_VERBOSE_COMMIT_CONTENT)
self.assertEqual(after, SAMPLE_VERBOSE_COMMIT_DIFF)
| {"/test_pcci.py": ["/precommit_changeid/__init__.py"]} |
46,937 | EliRibble/pre-commit-change-id | refs/heads/main | /precommit_changeid/__init__.py | "All module logic."
import argparse
import logging
import os
import re
import sys
import uuid
from typing import Dict, Tuple
import precommit_message_preservation
LOGGER = logging.getLogger("precommit-changeid")
def create_change_id() -> str:
"Create a Change-Id that Gerrit will accept."
return "I" + uuid.uuid4().hex + uuid.uuid4().hex[:8]
def get_suggested_content(filename: str) -> str:
"""Get the full content suggested for the git commit message.
Suggested content should look like:
[message provided on commandline]
[previously saved message, if any]
[injected tags]
[verbose code added by 'git commit -v']
Args:
The file path to the existing commit message provided by 'git commit -m'.
Returns:
The suggested content.
"""
try:
with open(filename, "r") as inp:
current_message = inp.read()
except OSError:
current_message = ""
current_message, verbose_code = split_verbose_code(current_message)
# Remove any trailing whitespace so we don't have blank lines between our tags.
current_message = current_message.rstrip()
previous_commit_message = precommit_message_preservation.get_cached_message()
if previous_commit_message and current_message:
current_message, change_id = extract_change_id(current_message)
previous_commit_message, previous_change_id = extract_change_id(previous_commit_message)
change_id = change_id or previous_change_id
suggested = (current_message +
"\n# ==== previously saved message below ====\n" +
previous_commit_message)
else:
suggested = current_message or previous_commit_message
suggested, change_id = extract_change_id(suggested)
change_id = change_id or create_change_id()
# Parse out the current tags and organize them appropriately
suggested = suggested.rstrip() + "\n\nChange-Id: " + change_id
if verbose_code:
suggested += verbose_code
return suggested
def extract_change_id(content: str) -> Tuple[str, str]:
"""Extract the Change-Id tag from a commit message, if any.
Returns:
The content without the Change-Id tag, if present, otherwise the full
content and an empty string.
"""
lines = []
change_id = ""
for line in content.split("\n"):
match = re.match(r"^Change-Id:\s*(I[0-9a-f]{8,40})", line, re.IGNORECASE)
if not match:
lines.append(line)
continue
new_line = line[:match.start()] + line[match.end():]
lines.append(new_line)
change_id = match.group(1)
return "\n".join(lines), change_id
def has_editor() -> bool:
"Return whether or not git will be using an editor for the commit message."
return os.environ.get("GIT_EDITOR") != ":"
def main() -> None:
"Main entrypoint for the hook."
parser = argparse.ArgumentParser()
parser.add_argument("file", help="The current git commit message file, provided by pre-commit.")
parser.add_argument("-v", "--verbose", action="store_true", help="Use verbose logging.")
args = parser.parse_args()
logging.basicConfig(
level = logging.DEBUG if args.verbose else logging.INFO
)
if not has_editor():
sys.exit(0)
suggested_content = get_suggested_content(args.file)
with open(args.file, "w") as out:
out.write(suggested_content)
LOGGER.debug("Write new commit message to %s", args.file)
def split_verbose_code(current_message: str) -> Tuple[str, str]:
"""Split code message on the 'git commit -v' verbose marker.
This uses a less stable marker than the official marker. The stable marker
is ------------ >8 -----------. However, we want to ensure we don't
interleave the tag suggestions into the comments in front of this marker,
so we use the less-stable English explanatory comment.
Args:
current_message: The current commit message to split.
Returns:
The commit message before the '-v' comment section and the comments
and code after the '-v' comment section, as a tuple of text.
"""
index = current_message.find("\n# Please enter the commit message for your changes.")
if index == -1:
return (current_message, "")
return current_message[:index], current_message[index:]
| {"/test_pcci.py": ["/precommit_changeid/__init__.py"]} |
46,941 | rgaudin/tools | refs/heads/master | /ethiopian_date/ethiopian_date/tests.py | #!/usr/bin/env python
# encoding=utf-8
# maintainer: rgaudin
from __future__ import absolute_import
from __future__ import unicode_literals
import unittest
import datetime
from ethiopian_date import EthiopianDateConverter
class TestEthiopianCalendar(unittest.TestCase):
def test_gregorian_to_ethiopian(self):
conv = EthiopianDateConverter.to_ethiopian
self.assertEqual(conv(1982, 11, 21), datetime.date(1975, 3, 12))
self.assertEqual(conv(1941, 12, 7), datetime.date(1934, 3, 28))
self.assertEqual(conv(2010, 12, 22), datetime.date(2003, 4, 13))
def test_date_gregorian_to_ethiopian(self):
self.assertEqual(
EthiopianDateConverter.date_to_ethiopian(datetime.date(1982, 11, 21)),
datetime.date(1975, 3, 12),
)
self.assertEqual(
EthiopianDateConverter.date_to_ethiopian(datetime.date(1941, 12, 7)),
datetime.date(1934, 3, 28),
)
self.assertEqual(
EthiopianDateConverter.date_to_ethiopian(datetime.date(2010, 12, 22)),
datetime.date(2003, 4, 13),
)
def test_ethiopian_to_gregorian(self):
conv = EthiopianDateConverter.to_gregorian
self.assertEqual(conv(2003, 4, 11).strftime("%F"), "2010-12-20")
self.assertEqual(conv(1975, 3, 12).strftime("%F"), "1982-11-21")
def test_date_ethiopian_to_gregorian(self):
self.assertEqual(
EthiopianDateConverter.date_to_gregorian(datetime.date(2003, 4, 11)),
datetime.date(2010, 12, 20),
)
self.assertEqual(
EthiopianDateConverter.date_to_gregorian(datetime.date(1975, 3, 12)),
datetime.date(1982, 11, 21),
)
if __name__ == "__main__":
unittest.main()
| {"/ethiopian_date/ethiopian_date/__init__.py": ["/ethiopian_date/ethiopian_date/ethiopian_date.py"]} |
46,942 | rgaudin/tools | refs/heads/master | /ethiopian_date/setup.py | #!/usr/bin/env python
# encoding=utf-8
# maintainer: rgaudin
from __future__ import absolute_import
from __future__ import unicode_literals
import setuptools
setuptools.setup(
name='ethiopian_date',
version='1.0',
license='GNU General Public License (GPL), Version 3',
provides=['ethiopian_date'],
description='Ethiopian date converter.',
long_description=open('README.rst').read(),
url='http://github.com/rgaudin/tools',
packages=['ethiopian_date'],
install_requires=[
'six>=1.11.0',
],
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: GNU Library or '
'Lesser General Public License (LGPL)',
'Programming Language :: Python',
],
)
| {"/ethiopian_date/ethiopian_date/__init__.py": ["/ethiopian_date/ethiopian_date/ethiopian_date.py"]} |
46,943 | rgaudin/tools | refs/heads/master | /ethiopian_date/ethiopian_date/ethiopian_date.py | #!/usr/bin/env python
# encoding=utf-8
# maintainer: rgaudin
""" Ethiopian Calendar tool for Python 2.6
Copyright (c) 2010 Renaud Gaudin <rgaudin@gmail.com>
This tool is a python port of Java Code from Ealet 2.0 by Senamirmir Project.
This code is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This code is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Foobar; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA """
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import datetime
from six.moves import range
class EthiopianDateConverter(object):
""" Class methods for converting between Ethiopian and Gregorian """
@classmethod
def _start_day_of_ethiopian(cls, year):
""" returns first day of that Ethiopian year
Params:
* year: an int """
# magic formula gives start of year
new_year_day = (year // 100) - (year // 400) - 4
# if the prev ethiopian year is a leap year, new-year occrus on 12th
if (year - 1) % 4 == 3:
new_year_day += 1
return new_year_day
@classmethod
def date_to_gregorian(cls, adate):
""" Gregorian date object representation of provided Ethiopian date
Shortcut to to_gregorian() classmethod using a date parameter
Params:
* adate: date object """
return cls.to_gregorian(adate.year, adate.month, adate.day)
@classmethod
def date_to_ethiopian(cls, adate):
""" Ethiopian date object representation of provided Gregorian date
Shortcut to to_ethiopian() classmethod using a date parameter
Params:
* adate: date object """
return cls.to_ethiopian(adate.year, adate.month, adate.day)
@classmethod
def to_gregorian(cls, year, month, date):
""" Gregorian date object representation of provided Ethiopian date
Params:
* year: an int
* month: an int
* date: an int """
# prevent incorect input
inputs = (year, month, date)
if 0 in inputs or [data.__class__ for data in inputs].count(int) != 3:
raise ValueError("Malformed input can't be converted.")
# Ethiopian new year in Gregorian calendar
new_year_day = cls._start_day_of_ethiopian(year)
# September (Ethiopian) sees 7y difference
gregorian_year = year + 7
# Number of days in gregorian months
# starting with September (index 1)
# Index 0 is reserved for leap years switches.
gregorian_months = [0, 30, 31, 30, 31, 31, 28, \
31, 30, 31, 30, 31, 31, 30]
# if next gregorian year is leap year, February has 29 days.
next_year = gregorian_year + 1
if (next_year % 4 == 0 and next_year % 100 != 0) \
or next_year % 400 == 0:
gregorian_months[6] = 29
# calculate number of days up to that date
until = ((month - 1) * 30) + date
if until <= 37 and year <= 1575: # mysterious rule
until += 28
gregorian_months[0] = 31
else:
until += new_year_day - 1
# if ethiopian year is leap year, paguemain has six days
if year - 1 % 4 == 3:
until += 1
# calculate month and date incremently
m = 0
for i in range(0, gregorian_months.__len__()):
if until <= gregorian_months[i]:
m = i
gregorian_date = until
break
else:
m = i
until -= gregorian_months[i]
# if m > 4, we're already on next Gregorian year
if m > 4:
gregorian_year += 1
# Gregorian months ordered according to Ethiopian
order = [8, 9, 10, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9]
gregorian_month = order[m]
return datetime.date(gregorian_year, gregorian_month, gregorian_date)
@classmethod
def to_ethiopian(cls, year, month, date):
""" Ethiopian date string representation of provided Gregorian date
Params:
* year: an int
* month: an int
* date: an int """
# prevent incorect input
inputs = (year, month, date)
if 0 in inputs or [data.__class__ for data in inputs].count(int) != 3:
raise ValueError("Malformed input can't be converted.")
# date between 5 and 14 of May 1582 are invalid
if month == 10 and date >= 5 and date <= 14 and year == 1582:
raise ValueError("Invalid Date between 5-14 May 1582.")
# Number of days in gregorian months
# starting with January (index 1)
# Index 0 is reserved for leap years switches.
gregorian_months = [0, 31, 28, 31, 30, 31, 30, \
31, 31, 30, 31, 30, 31]
# Number of days in ethiopian months
# starting with January (index 1)
# Index 0 is reserved for leap years switches.
ethiopian_months = [0, 30, 30, 30, 30, 30, 30, 30, \
30, 30, 5, 30, 30, 30, 30]
# if gregorian leap year, February has 29 days.
if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
gregorian_months[2] = 29
# September sees 8y difference
ethiopian_year = year - 8
# if ethiopian leap year pagumain has 6 days
if ethiopian_year % 4 == 3:
ethiopian_months[10] = 6
else:
ethiopian_months[10] = 5
# Ethiopian new year in Gregorian calendar
new_year_day = cls._start_day_of_ethiopian(year - 8)
# calculate number of days up to that date
until = 0
for i in range(1, month):
until += gregorian_months[i]
until += date
# update tahissas (december) to match january 1st
if ethiopian_year % 4 == 0:
tahissas = 26
else:
tahissas = 25
# take into account the 1582 change
if year < 1582:
ethiopian_months[1] = 0
ethiopian_months[2] = tahissas
elif until <= 277 and year == 1582:
ethiopian_months[1] = 0
ethiopian_months[2] = tahissas
else:
tahissas = new_year_day - 3
ethiopian_months[1] = tahissas
# calculate month and date incremently
m = 0
for m in range(1, ethiopian_months.__len__()):
if until <= ethiopian_months[m]:
if m == 1 or ethiopian_months[m] == 0:
ethiopian_date = until + (30 - tahissas)
else:
ethiopian_date = until
break
else:
until -= ethiopian_months[m]
# if m > 4, we're already on next Ethiopian year
if m > 10:
ethiopian_year += 1
# Ethiopian months ordered according to Gregorian
order = [0, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1, 2, 3, 4]
ethiopian_month = order[m]
return datetime.date(ethiopian_year, ethiopian_month, ethiopian_date)
| {"/ethiopian_date/ethiopian_date/__init__.py": ["/ethiopian_date/ethiopian_date/ethiopian_date.py"]} |
46,944 | rgaudin/tools | refs/heads/master | /gcontact2nokia/gcontact2nokia.py | #!/usr/bin/env python
# encoding=utf-8
''' Generates Gammu-formatted backup file from Google Contact CSV file
Takes a CSV file (Google CSV format) as input and generates a
plain text file for use with gammu.
Examples:
gcontact2nokia.py google.csv gammu.bck && gammu restore gammu.bck -yes
This script has _only_ been tested with my Nokia 1680 but should work
with any gammu-compatible phone.
LICENSE: WTF Public License. '''
import sys
import pprint
from datetime import datetime
class NokiaEntry(object):
TEMPLATE = u"Entry%(num)sType = %(type)s\n" \
"Entry%(num)sText = \"%(value)s\"\n"
def __init__(self, key=None, value=None, position=None, *args, **kwargs):
self.key = key
self.value = value
self.position = position
def get_position(self):
return str(self.position).zfill(2)
def to_s(self, position=None):
try:
return self.TEMPLATE % {'num': self.get_position(), \
'type': self.key, \
'value': self.value}
except:
print self.key
print self.value
raise
class NokiaContact(object):
_entries = []
TEMPLATE = "[PhonePBK%(num)s]\n" \
"Location = %(num)s\n" \
"%(entries)s\n"
def __init__(self, position=None, *args, **kwargs):
self._entries = []
self.position = position
cptr = 0
for key, value in kwargs.items():
if value:
entry = NokiaEntry(key=key, value=value, position=cptr)
cptr = cptr + 1
self._entries.append(entry)
def get_position(self):
return str(self.position).zfill(3)
def to_s(self):
return self.TEMPLATE % {'num': self.get_position(), \
'entries': self.entries()}
def entries(self):
out = u""
for entry in self._entries:
out += entry.to_s()
return out
class NokiaBook(object):
TEMPLATE = u"[Backup]\n" \
"IMEI = \"%(imei)s\"\n" \
"Phone = \"%(phone)s\"\n" \
"Creator = \"%(creator)s\"\n" \
"DateTime = %(date)s\n" \
"Format = %(format)s\n\n" \
"%(contacts)s"
imei = '0000000000'
phone = 'Nokia Unknown'
creator = 'gcontact2nokia.py'
date = datetime.now().strftime("%Y%m%dT%H%M%SZ")
_contacts = []
def __init__(self, *args, **kwargs):
self._contacts = []
def add(self, contact):
self._contacts.append(contact)
def to_s(self):
return self.TEMPLATE % {'imei': self.imei, 'phone': self.phone, \
'creator': self.creator, 'date': self.date, \
'format': u"1.04", 'contacts': self.contacts()}
def contacts(self):
out = u""
for contact in self._contacts:
out += contact.to_s()
return out
def str_decode(str_):
encodings = ('utf-8', 'iso-8859-1')
for enc in encodings:
try:
str_ = str_.decode(enc)
return str_
except UnicodeDecodeError:
pass
def cleanup(str_):
try:
return str_.strip().title()
except AttributeError:
return str_
def usage():
print "Usage: %s source.csv destination.bck\n" % sys.argv[0]
def main():
# default settings
GAMMU_IMEI = '356782027329625'
GAMMU_PHONE = 'Nokia 1680 05.61'
try:
input_file = sys.argv[1]
output_file = sys.argv[2]
except IndexError:
usage()
exit(1)
# create phone book
book = NokiaBook()
book.imei = GAMMU_IMEI
book.phone = GAMMU_PHONE
# open CSV file.
print "Opening %s file as Google CSV data." % input_file
inf = open(input_file, "r")
# setup contact counter
cptr = 0
# loop on CSV file lines
for line in inf:
# skip first line (header)
if cptr == 0:
cptr = 1
continue
# entries holds the valueable data
entries = {}
# split CSV line
data = line.replace('"', '').split(',')
# retrieve, clean up and store each wanted field.
for key, index in (('FirstName', 1), ('LastName', 3), \
('NumberGeneral', 36), ('NumberWork', 38)):
try:
fdata = data[index]
except IndexError:
fdata = None
if fdata:
fdata = str_decode(fdata)
fdata = cleanup(fdata)
entries[key] = fdata
# skype contacts without phone number
if not entries['NumberGeneral'] \
or entries['NumberGeneral'].__len__() <= 1:
continue
# pretty print retrieved infos
# pprint.pprint(entries)
# create the contact with a position number.
contact = NokiaContact(position=cptr, **entries)
# increment contact counter
cptr = cptr + 1
# add contact to phonebook
book.add(contact)
print "Book created: %d contacts" % book._contacts.__len__()
# write phone book dump into destination file.
outf = open(output_file, "w")
outf.write(book.to_s().encode('utf-8'))
if __name__ == '__main__':
main()
| {"/ethiopian_date/ethiopian_date/__init__.py": ["/ethiopian_date/ethiopian_date/ethiopian_date.py"]} |
46,945 | rgaudin/tools | refs/heads/master | /ethiopian_date/ethiopian_date/__init__.py | #!/usr/bin/env python
# encoding=utf-8
# maintainer: rgaudin
""" Ethiopian Date Converter
Convert from Ethiopian date to Gregorian date (and vice-versa)
Examples:
greg_date = EthiopianDateConverter.to_gregorian(2003, 4, 11)
ethi_date = EthiopianDateConverter.date_to_ethiopian(datetime.date.today())
"""
from __future__ import absolute_import
from __future__ import unicode_literals
from .ethiopian_date import EthiopianDateConverter
| {"/ethiopian_date/ethiopian_date/__init__.py": ["/ethiopian_date/ethiopian_date/ethiopian_date.py"]} |
46,948 | atpham4/virtual_xray | refs/heads/master | /x_ray.py | import matplotlib.pyplot as plt
import numpy as np
import math
from tkinter import *
from phantom import generate_2d_phantom, generate_bigger_broken_leg, generate_leg, generate_3d_phantom, generate_tissue, generate_broken_leg, get_2d_profile, intensity_function, intensity_line_graph
#Simple GUI to input values to run code
def runGUI():
window = Tk()
window.title('X-Ray GUI')
window.geometry('500x500')
Label(window, text = "X-Ray configuration", font=("Helvetica", 12), anchor = "w").grid(stick= 'W', row = 0, column = 0)
Label(window, text = "Enter a X-Ray Energy value: ").grid(stick= 'W', row = 1, column = 0)
xray_intensity = StringVar()
set1 = OptionMenu(window, xray_intensity, "20", "30", "40").grid(row = 1, column = 1)
xray_intensity.set("20")
Label(window, text = "Enter a X-Ray angle value: ").grid(stick= 'W', row = 2, column = 0)
xray_angle = StringVar()
set2 = OptionMenu(window, xray_angle, "20", "30", "40", "60", "80", "90").grid(stick= 'W', row = 2, column = 1)
xray_angle.set("90")
Label(window, text = "\nPhantom configuration", font=("Helvetica", 12), anchor = "w").grid(stick= 'W', row = 3, column = 0)
Label(window, text = "Enter attenuation(u) of leg: ").grid(stick= 'W', row = 4, column = 0)
u_leg = StringVar()
set3 = OptionMenu(window, u_leg, ".5", ".025", ".01").grid(row = 4, column = 1)
u_leg.set(".5")
Label(window, text = "Enter attenuation(u) of bone: ").grid(stick= 'W', row = 5, column = 0)
u_bone = StringVar()
set4 = OptionMenu(window, u_bone, ".99", ".90", ".85").grid(row = 5, column = 1)
u_bone.set(".99")
Label(window, text = "Leg condition: ").grid(stick = 'W', row = 6, column = 0)
leg_condition = StringVar()
set_leg_condition = OptionMenu(window, leg_condition, "Normal", "Broken", "Bigger Angled Slit").grid(row = 6, column = 1)
leg_condition.set("Normal")
Label(window, text = "Leg View: ").grid(stick = 'W', row = 7, column = 0)
leg_angle = StringVar()
set_leg_angle = OptionMenu(window, leg_angle, "Front", "Side").grid(row = 7, column = 1)
leg_angle.set("Front")
Label(window, text = "\nChange Distance", font=("Helvetica", 12), anchor = "w").grid(stick= 'W', row = 8, column = 0)
Label(window, text = "Film to Phantom: ").grid(stick= 'W', row = 9, column = 0)
film_to_phantom = StringVar()
set5 = OptionMenu(window, film_to_phantom, "1", "2", "3", "4").grid(row = 9, column = 1)
film_to_phantom.set("1")
Label(window, text = "X-Ray Source to Phantom: ").grid(stick= 'W', row = 10, column = 0)
source_to_phantom = StringVar()
set6 = OptionMenu(window, source_to_phantom, "7", "6", "5", "4").grid(row = 10, column = 1)
source_to_phantom.set("7")
def clicked():
total_length = int(source_to_phantom.get()) - int(film_to_phantom.get())
test_phantom = generate_tissue(float(u_leg.get()), float(u_bone.get()))
intensityList = intensity_function(float(xray_intensity.get()), test_phantom)
leg_phantom = generate_leg(float(u_leg.get()), float(u_bone.get()))
if leg_condition.get() == "Broken":
leg_phantom = generate_broken_leg(float(u_leg.get()), float(u_bone.get()))
elif leg_condition.get() == "Bigger Angled Slit":
leg_phantom = generate_bigger_broken_leg(float(u_leg.get()), float(u_bone.get()))
generate_3d_phantom(leg_phantom[0], leg_phantom[1])
get_2d_profile(int(xray_intensity.get()), leg_phantom, total_length, int(xray_angle.get()), leg_angle.get())
plt.show()
btn = Button(window, text="Start", command=clicked)
btn.grid(column=0, row=11)
window.mainloop()
runGUI()
| {"/x_ray.py": ["/phantom.py"]} |
46,949 | atpham4/virtual_xray | refs/heads/master | /phantom.py | import matplotlib.pyplot as plt
import numpy as np
import math
import mpl_toolkits.mplot3d.axes3d as axes3d
import scipy.misc
from scipy import ndimage
from scipy.interpolate import spline
from mpl_toolkits.mplot3d import Axes3D
from scipy.ndimage import generic_filter, correlate, minimum_filter
#Function to calculate intensities of the x-ray when passing through a slice of tissues
def intensity_function(Io, xray):
Istart = Io
L = len(xray[0])
Ifilm = []
for j in xray:
layerposition = 0
for k in j:
layerposition += 1
I = Io * math.exp(-k * L)
Io = I
if layerposition == len(j):
Ifilm.append(I)
Io = Istart
return Ifilm
#Line Graph of Intensities for each slice
def intensity_line_graph(intensityList, Io):
plt.figure(4)
plt.title("Intensity Line Graph")
x = range(len(intensityList))
y = intensityList
plt.plot(x, y)
plt.axis([0, len(intensityList), 0, Io])
plt.xlabel("Rays")
plt.ylabel("Intensity")
#Function to generate and show 2D Phantom based on input tissue with length and angle
def generate_2d_phantom(tissue_array, length, angle):
if angle != 90:
percent = 7-(7*(angle/90))
else:
percent = 0
plt.figure(1)
plt.title("Phantom 2-D")
#x 0-6, y 7-0
if length == 6:
plt.imshow(tissue_array, cmap= "gray")
elif length == 5:
plt.xlim(0.5, 5.5)
plt.ylim(7 - percent - .5, percent)
blur_img = ndimage.gaussian_filter(tissue_array, sigma = .4)
plt.imshow(tissue_array, cmap= "gray")
elif length == 4:
plt.xlim(.8, 5.2)
plt.ylim(7 - percent -.8, percent + .3)
blur_img = ndimage.gaussian_filter(tissue_array, sigma = .4)
plt.imshow(tissue_array, cmap= "gray")
elif length == 3:
plt.xlim([1, 5])
plt.ylim([6 - percent - .5, 1 + percent])
blur_img = ndimage.gaussian_filter(tissue_array, sigma = .4)
plt.imshow(blur_img, cmap="gray")
elif length == 2:
plt.xlim([1.5, 4.5])
plt.ylim([5.5 - percent, 1.5 + percent])
blur_img = ndimage.gaussian_filter(tissue_array, sigma = .5)
plt.imshow(blur_img, cmap="gray")
elif length == 1:
plt.xlim([2, 4])
plt.ylim([5 - percent, 2 + percent])
blur_img = ndimage.gaussian_filter(tissue_array, sigma = .6)
plt.imshow(blur_img, cmap="gray")
elif length == 0:
plt.xlim([2.5, 3.5])
plt.ylim([4.5 - percent, 2.5 + percent])
blur_img = ndimage.gaussian_filter(tissue_array, sigma = .7)
plt.imshow(blur_img, cmap="gray")
#Function to generate 3D phantom of leg
def generate_3d_phantom(skin_array, bone_array):
fig = plt.figure(2)
ax = fig.add_subplot(111, projection = '3d')
data = np.array(skin_array)
h, w = data.shape
theta, z = np.linspace(0, 2 * np.pi, w), np.linspace(0, 1, h)
THETA, Z = np.meshgrid(theta, z)
X = np.cos(THETA)
Y = np.sin(THETA)
cmap = plt.get_cmap('gray_r')
ax.plot_surface(
X, Y, Z, rstride = 1, cstride = 1, facecolors = cmap(data),
linewidth = 0, antialiased = False, alpha = 0.75)
X = [element/2 for element in X]
Y = [element/2 for element in Y]
data = np.array(bone_array);
cmap =plt.get_cmap('Blues')
ax.plot_surface(
X, Y, Z, rstride = 1, cstride = 1, facecolors = cmap(data),
linewidth = 0, antialiased = False, alpha = 0.75)
#Function to generate tissue of the leg for 2d phantom
def generate_tissue(u_leg, u_bone):
tissue = np.array([[u_leg, u_leg, u_bone, u_bone, u_bone, u_leg, u_leg], [u_leg, u_leg, u_bone, u_bone, u_leg, u_leg, u_leg], [u_leg, u_leg, u_bone, u_leg, u_leg, u_leg, u_leg], [u_leg, u_leg, u_leg, u_leg, u_leg, u_leg, u_leg], [u_leg, u_leg, u_leg, u_leg, u_bone, u_leg, u_leg], [u_leg, u_leg, u_leg, u_bone, u_bone, u_leg, u_leg], [u_leg, u_leg, u_bone, u_bone, u_bone, u_leg, u_leg], [u_leg, u_leg, u_bone, u_bone, u_bone, u_leg, u_leg]])
return tissue
#Function to generate a healthy phantom of leg
def generate_leg(u_leg, u_bone):
skin = [[u_leg]*20]*19
bone_3d = [[u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone]]*19
return skin, bone_3d
#Function to generate a broken leg with two splits to represent breaks in the leg
def generate_broken_leg(u_leg, u_bone):
skin = [[u_leg]*20]*19
bone_3d = [[u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone],
[u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone],
[u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone],
[u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, 0, 0, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone],
[u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, 0, 0, 0, 0, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone],
[u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, 0, 0, u_bone, u_bone, 0, 0, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone],
[u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, 0, 0, u_bone, u_bone, u_bone, u_bone, 0, 0, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone],
[u_bone, u_bone, u_bone, u_bone, u_bone, 0, 0, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, 0, 0, u_bone, u_bone, u_bone, u_bone, u_bone],
[u_bone, u_bone, u_bone, u_bone, 0, 0, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, 0, 0, u_bone, u_bone, u_bone, u_bone],
[u_bone, u_bone, u_bone, 0, 0, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, 0, 0, u_bone, u_bone, u_bone],
[u_bone, u_bone, 0, 0, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, 0, 0, u_bone, u_bone],
[u_bone, 0, 0, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, 0, 0, u_bone],
[0, 0, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, 0, 0],
[0, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, 0],
[u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone],
[u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone]]
return skin, bone_3d
#Function that generate a broken leg with a bigger diagonal split for observation
def generate_bigger_broken_leg(u_leg, u_bone):
skin = [[u_leg]*20]*19
bone_3d = [[u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone],
[u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone],
[u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone],
[u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, 0, 0, 0, 0, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone],
[u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, 0, 0, 0, 0, 0, 0, 0, 0, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone],
[u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, 0, 0, 0, 0, 0, 0, 0, 0, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone],
[u_bone, u_bone, u_bone, u_bone, u_bone, 0, 0, 0, 0, u_bone, u_bone, 0, 0, 0, 0, u_bone, u_bone, u_bone, u_bone, u_bone],
[u_bone, u_bone, u_bone, u_bone, 0, 0, 0, 0, u_bone, u_bone, u_bone, u_bone, 0, 0, 0, 0, u_bone, u_bone, u_bone, u_bone],
[u_bone, u_bone, u_bone, 0, 0, 0, 0, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, 0, 0, 0, 0, u_bone, u_bone, u_bone],
[u_bone, u_bone, 0, 0, 0, 0, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, 0, 0, 0, 0, u_bone, u_bone],
[u_bone, 0, 0, 0, 0, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, 0, 0, 0, 0, u_bone],
[0, 0, 0, 0, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, 0, 0, 0, 0],
[0, 0, 0, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, 0, 0, 0],
[0, 0, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, 0, 0],
[u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone],
[u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone, u_bone]]
return skin, bone_3d
#Calculating the density based on the inputted energy and the intensities
def calculate_density(intensity_array, xray_energy):
densities = []
for intensity in intensity_array:
densities.append(math.log(xray_energy/intensity))
return densities
#Getting 1D image from a 2D phantom to represent density of the film
def get_1d_profile(xray_energy, tissue):
intensities = intensity_function(xray_energy, tissue)
density = calculate_density(intensities, xray_energy)
plt.figure(1)
x = range(len(density))
y = density
plt.plot(x, y, 'o', x, y)
#Getting the 2D image from the 3D phantom to represent the x-ray film
def get_2d_profile(xray_energy, leg, length, angle, leg_view):
if angle != 90:
percent = 18 - (18 * (angle / 90))
else:
percent = 0
intensities = []
density = []
for i in range(int(len(leg[0][0]) - 1)):
leg_and_bone = get_2d_leg(leg[1][i], leg[0][2][0])
if leg_view == "Side":
array_axis = len(leg_and_bone[0])
leg_and_bone = np.rot90(leg_and_bone, 1, axes = (0, 1))
intensities.append(intensity_function(xray_energy, leg_and_bone))
for intensity in intensities:
density.append(calculate_density(intensity, xray_energy))
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_title('film')
ax.set_aspect('equal')
#x is from 0-8, y is 18-0
if length == 6:
ax.set_ylim(18 - percent, 0 + percent)
plt.imshow(np.array(density), cmap = plt.get_cmap('gray'))
elif length == 5:
ax.set_xlim(0.5, 7.5)
ax.set_ylim(18 - percent - 1, 0.5 + percent)
blur_img = ndimage.gaussian_filter(np.array(density), sigma = .4)
plt.imshow(blur_img, cmap="gray")
elif length == 4:
ax.set_xlim(1, 7)
ax.set_ylim(17 - percent - 1, 1.5 + percent)
blur_img = ndimage.gaussian_filter(np.array(density), sigma = .5)
plt.imshow(blur_img, cmap="gray")
elif length == 3:
ax.set_xlim(1.5, 6.5)
ax.set_ylim(16 - percent - 1, 2 + percent)
blur_img = ndimage.gaussian_filter(np.array(density), sigma = .6)
plt.imshow(blur_img, cmap="gray")
elif length == 2:
ax.set_xlim(2, 6)
ax.set_ylim(15 - percent - 1, 2.5 + percent)
blur_img = ndimage.gaussian_filter(np.array(density), sigma = .7)
plt.imshow(blur_img, cmap="gray")
elif length == 1:
ax.set_xlim(2.5, 5.5)
ax.set_ylim(14 - percent - 1, 3 + percent)
blur_img = ndimage.gaussian_filter(np.array(density), sigma = .8)
plt.imshow(blur_img, cmap="gray")
elif length == 0:
ax.set_xlim(3, 5 )
ax.set_ylim(15 - percent - 1, 3.5 + percent)
blur_img = ndimage.gaussian_filter(np.array(density), sigma = .9)
plt.imshow(blur_img, cmap="gray")
cax = fig.add_axes([0.24, 0.1, 0.78, 0.8])
cax.get_xaxis().set_visible(False)
cax.get_yaxis().set_visible(False)
cax.patch.set_alpha(0)
cax.set_frame_on(False)
plt.colorbar(orientation='vertical', pad = 0.15)
#Getting slices of tissues from the leg to get the intensities of the entire leg
def get_2d_leg(array, skin_u):
leg_2d = []
end_index = int(len(array)/2)
for i in range(int(len(array)/4)):
new_array = array[i : end_index]
end_index -= 1
new_array.append(skin_u)
new_array.insert(0, skin_u)
if i != 0:
for skin in range(i):
new_array.append(0)
new_array.insert(0, 0)
leg_2d.insert(0, new_array)
start_index = int(len(array)/2)
end_index = int(len(array))
for i in range(int(len(array)/4)):
new_array = array[start_index : end_index]
new_array.reverse()
start_index += 1
end_index -= 1
new_array.append(skin_u)
new_array.insert(0, skin_u)
if i != 0:
for skin in range(i):
new_array.append(0)
new_array.insert(0, 0)
leg_2d.append(new_array)
array = np.array(leg_2d)
return(array)
| {"/x_ray.py": ["/phantom.py"]} |
46,950 | mrahul17/kgp_erp | refs/heads/master | /main.py | import requests
import json
from bs4 import BeautifulSoup
urls = {
'HOME_URL' : 'https://erp.iitkgp.ernet.in/IIT_ERP3/welcome.jsp',
'AUTH_URL' :'https://erp.iitkgp.ernet.in/SSOAdministration/auth.htm',
'SECURITYQ_URL' : 'https://erp.iitkgp.ernet.in/SSOAdministration/getSecurityQues.htm',
'TP_URL' : 'https://erp.iitkgp.ernet.in/TrainingPlacementSSO/TPStudent.jsp',
'SSO_URL' : 'https://erp.iitkgp.ernet.in/IIT_ERP3/showmenu.htm',
'CV_URL' : "https://erp.iitkgp.ernet.in/TrainingPlacementSSO/AdmFilePDF.htm?path=/DATA/ARCHIVE/TRAINGANDPLACEMNT/STUDENT/{0}/RESUME/1.pdf",
'LOGOUT_URL' : 'https://erp.iitkgp.ernet.in/IIT_ERP3/logout.htm'
}
# get credentials from json
with open('credentials.json','r') as f:
details = json.load(f)
auth = {
'USER_ID' : details['USER_ID'],
'USER_PASSWORD' : details['USER_PASSWORD'],
'SECURITY_ANSWERS' : details['SECURITY_ANSWERS']
}
def login():
''' This function returns the session object that has all the cookies you need for retrieving data from erp.'''
s = requests.Session()
r = s.get(urls['HOME_URL'])
soup = BeautifulSoup(r.text, "html5lib")
sessionToken = soup.find(id='sessionToken').get('value')
r = s.post(urls['SECURITYQ_URL'], data = {'user_id': auth['USER_ID'] })
if r.status_code != 200:
return False
security_answer = auth['SECURITY_ANSWERS'][r.text]
login_data = {
'user_id' : auth['USER_ID'],
'password' : auth['USER_PASSWORD'],
'answer' : security_answer,
'sessionToken' : sessionToken,
'requestedUrl' : urls['HOME_URL']
}
r = s.post(urls['AUTH_URL'], data = login_data)
tnp_data = {
'module_id' : '26',
'menu_id' : '11',
'link' : 'https://erp.iitkgp.ernet.in/TrainingPlacementSSO/TPStudent.jsp',
'delegated_by': '',
'module_name' : 'CDC',
'parent_display_name' : 'Student',
'display_name' : 'Application of Placement/Internship'
}
r = s.post(urls['SSO_URL'], data=tnp_data)
soup2 = BeautifulSoup(r.text, "html5lib")
ssoToken = soup2.find(id='ssoToken').get('value')
sso_data = {
'ssoToken' : ssoToken,
'module_id' : '26',
'menu_id' : '11'
}
s.post(urls['TP_URL'], data = sso_data)
return s
if __name__ == '__main__':
s = login()
| {"/resume_fetcher.py": ["/main.py"]} |
46,951 | mrahul17/kgp_erp | refs/heads/master | /resume_fetcher.py | import requests
from main import login, urls
import csv
import sys
try:
s = login()
except:
sys.exit("Unable to login. Exiting..")
with open('roll_list.csv') as f:
csvfile = csv.reader(f)
for row in csvfile:
r = s.get(urls['CV_URL'].format(row[0]))
if r.content != '':
with open("{0}.pdf".format(row[0]),'w+') as pdf:
pdf.write(r.content)
s.get(urls['LOGOUT_URL'])
s.close()
| {"/resume_fetcher.py": ["/main.py"]} |
46,975 | jmeline/DesignPatternsInPy | refs/heads/master | /Singleton/singleton_py3.py | #Python3
# singleton using metaclasses (I like this way)
class Singleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
return cls._instances[cls]
# # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Final Challenges by Youtube Channel Trevor Payne #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # #
## Create a singleton that has a function which returns a value that
# increase +1 everytime it is called (E.X. Returns 1,2,3,4,5)
class ChallengeOne(metaclass=Singleton):
def __init__(self):
print (self.__class__.__name__ + " Instantiated")
self.count = 0
def update(self):
self.count += 1
return self.count
## Create a singleton that acts like a phonebook. It has a function that you can pass in a Name and a Number to store,
## and another function to retrieve a Number and a Given Name
class ChallengeTwo(metaclass=Singleton):
def __init__(self):
self.name = ''
self.number = 0
print (self.__class__.__name__ + " Instantiated")
def updatePhoneBook(self, name, number):
self.name = name
self.number = number
def getPhoneBook(self):
return self.name, self.number | {"/tests/singleton_py2_test.py": ["/Singleton/singleton_py2.py"], "/tests/singleton_py3_test.py": ["/Singleton/singleton_py3.py"]} |
46,976 | jmeline/DesignPatternsInPy | refs/heads/master | /tests/conftest.py | ## More information
## http://pytest.org/latest/example/pythoncollection.html
# Content of conftest.py
import sys
collect_ignore = []
# collect_ignore['setup.py'] ## This is typically ignored during tests
if sys.version_info[0] > 2:
## Py3 behavior
## py.test --collect-only
collect_ignore.append('singleton_py2_test.py')
else:
## Py2 behavior
## py.test2 --collect-only
collect_ignore.append('singleton_py3_test.py')
| {"/tests/singleton_py2_test.py": ["/Singleton/singleton_py2.py"], "/tests/singleton_py3_test.py": ["/Singleton/singleton_py3.py"]} |
46,977 | jmeline/DesignPatternsInPy | refs/heads/master | /Singleton/singleton_py2.py | # # # # # # # # # # # # # # # # # # # # # # # # #
# Design Pattern: Singleton #
# singleton is a design pattern where only one #
# instance may exist at any given time #
# # # # # # # # # # # # # # # # # # # # # # # # #
# Refer here to for more information
# https://stackoverflow.com/questions/6760685/creating-a-singleton-in-python
# first way to do a singleton through hard coding
class MySingleton(object):
_instance = None
def __new__(self):
# check if _instance hasn't been set
if not self._instance:
# create a new instance
self._instance = super(MySingleton, self).__new__(self)
self.y = 10
return self._instance
# Second way to do a singleton using a decorator
def singleton(MyClass):
instances = {}
def getInstance(*args, **kwargs):
if MyClass not in instances:
instances[MyClass] = MyClass(*args, **kwargs)
return instances[MyClass]
return getInstance
@singleton
class TestClass(object):
def __init__(self):
self.value = 10
# Third way to do a singleton using metaclasses (I like this way)
class Singleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
return cls._instances[cls]
# Python2 example
class MyClass(object):
__metaclass__ = Singleton
#Python3
#class MyClass(BaseClass, metaclass=Singleton):
# pass
# # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Final Challenges by Youtube Channel Trevor Payne #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # #
## Create a singleton that has a function which returns a value that
# increase +1 everytime it is called (E.X. Returns 1,2,3,4,5)
class ChallengeOne():
__metaclass__ = Singleton
def __init__(self):
print (self.__class__.__name__ + " Instantiated")
self.count = 0
def update(self):
self.count += 1
return self.count
## Create a singleton that acts like a phonebook. It has a function that you can pass in a Name and a Number to store,
## and another function to retrieve a Number and a Given Name
class ChallengeTwo():
__metaclass__ = Singleton
def __init__(self):
self.name = ''
self.number = 0
print (self.__class__.__name__ + " Instantiated")
def updatePhoneBook(self, name, number):
self.name = name
self.number = number
def getPhoneBook(self):
return self.name, self.number
| {"/tests/singleton_py2_test.py": ["/Singleton/singleton_py2.py"], "/tests/singleton_py3_test.py": ["/Singleton/singleton_py3.py"]} |
46,978 | jmeline/DesignPatternsInPy | refs/heads/master | /Strategy/strategy.py | # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Design Pattern: Strategy Pattern #
# Strategy Pattern is a pattern that enables an algorithm's #
# behavior to be selected at runtime. The strategy pattern #
# defines a family of algorithms, encapsulates each algorithm, and #
# makes the algorithms interchangeable within that family. #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
from __future__ import print_function
__author__ = 'Jacob'
# more information about the strategy pattern: https://en.wikipedia.org/wiki/Strategy_pattern
# other resources:
# https://stackoverflow.com/questions/963965/how-is-this-strategy-pattern-written-in-python-the-sample-in-wikipedia
class StrategyDisbatcher:
def __init__(self, func=None):
if func:
self.execute = func
def execute(self, a=None, b=None):
print("Default Execution")
def executeAdd(a, b):
print("%d+%d: %d" % (a, b, a + b))
return a + b
def executeSub(a, b):
print("%d-%d: %d" % (a, b, a - b))
return a - b
def executeMul(a, b):
print("%d*%d: %d" % (a, b, a * b))
return a * b
def executeDiv(a, b):
if b != 0:
print("%d/%d: %d" % (a, b, a / b))
return a / b
return 1
def executeExp(a):
print("%d^%d: %d" % (a, a, a ** a))
return a ** a
if __name__ == "__main__":
value1 = 5
value2 = 3
strat = StrategyDisbatcher()
stratAdd = StrategyDisbatcher(executeAdd)
stratSub = StrategyDisbatcher(executeSub)
stratMul = StrategyDisbatcher(executeMul)
stratDiv = StrategyDisbatcher(executeDiv)
stratExp = StrategyDisbatcher(executeExp)
list = []
strat.execute()
list.append(stratAdd.execute(value1, value2))
list.append(stratSub.execute(value1, value2))
list.append(stratMul.execute(value1, value2))
list.append(stratDiv.execute(value1, value2))
list.append(stratExp.execute(value1))
total = 0
for l in list:
total += l
print("total: ", total)
| {"/tests/singleton_py2_test.py": ["/Singleton/singleton_py2.py"], "/tests/singleton_py3_test.py": ["/Singleton/singleton_py3.py"]} |
46,979 | jmeline/DesignPatternsInPy | refs/heads/master | /tests/singleton_py2_test.py | # # # # # # # # # # # # # # # # # # # # # # # # #
# Singleton python unittest #
# # # # # # # # # # # # # # # # # # # # # # # # #
from __future__ import print_function
from Singleton.singleton_py2 import *
import sys
class TestSingletonPy2():
def test_example1(self):
print ("Singleton Example1")
x = MySingleton()
print (x.y)
assert x.y == 10
x.y = 20
assert x.y != 10
z = MySingleton()
print (z.y)
assert x.y == z.y
def test_example2(self):
print ("Singleton Example2")
x = TestClass()
assert x.value == 10
print (x.value)
x.value *= 10
assert x.value != 10
assert x.value == 100
y = TestClass()
print (y.value)
assert x.value == y.value
def test_challengeOne(self):
instanceList = [ChallengeOne() for i in range(5)]
assert instanceList
count = 1
for i in instanceList:
print ("%s: %s" % (i.__class__.__name__, i.update()))
assert i.count == count
assert i == instanceList[0]
count += 1
print ("end of challengeOne")
def test_challengeTwo(self):
instance = ChallengeTwo()
assert instance
nameTest = "Jacob"
phoneTest = "999-999-9999"
instance.updatePhoneBook(nameTest, phoneTest)
assert instance.name is not None and instance.number is not None
name, phone = instance.getPhoneBook()
assert name == nameTest and phone == phoneTest
print ("end of challengeTwo")
| {"/tests/singleton_py2_test.py": ["/Singleton/singleton_py2.py"], "/tests/singleton_py3_test.py": ["/Singleton/singleton_py3.py"]} |
46,980 | jmeline/DesignPatternsInPy | refs/heads/master | /tests/singleton_py3_test.py | # # # # # # # # # # # # # # # # # # # # # # # # #
# Singleton python unittest #
# # # # # # # # # # # # # # # # # # # # # # # # #
from __future__ import print_function
from Singleton.singleton_py3 import *
import sys
class TestSingletonPy3():
def test_challengeOne(self):
instance = None
instanceList = [ChallengeOne() for i in range(5)]
count = 1
for i in instanceList:
print ("%s: %s" % (i.__class__.__name__, i.update()))
assert i.count == count
assert i == instanceList[0]
count += 1
print ("end of challengeOne")
def test_challengeTwo(self):
instance = None
instance = ChallengeTwo()
assert instance is not None
nameTest = "Jacob"
phoneTest = "999-999-9999"
instance.updatePhoneBook(nameTest, phoneTest)
assert instance.name is not None and instance.number is not None
name, phone = instance.getPhoneBook()
assert name == nameTest and phone == phoneTest
print ("end of challengeTwo")
| {"/tests/singleton_py2_test.py": ["/Singleton/singleton_py2.py"], "/tests/singleton_py3_test.py": ["/Singleton/singleton_py3.py"]} |
46,983 | Engineering-Geek/ThermoLab | refs/heads/main | /main.py | from System import ThermodynamicPath, ThermodynamicPoint, ClosedSystem
import numpy as np
import pyromat as pm
from typing import List, Dict, Union
import pandas as pd
from matplotlib import pyplot as plt
# noinspection PyAttributeOutsideInit
class LabExperiment:
def __init__(self, data: pd.Series, expander_length: float, fluid=None, steps=10):
self.fluid = pm.get("mp.C2H2F4") if fluid is None else fluid
self.expander_length = expander_length
self.T1 = data["T_1"] + 273.15
self.T2 = data["T_2"] + 273.15
self.T3 = data["T_3"] + 273.15
self.T4 = data["T_4"] + 273.15
self.T5 = data["T_5"] + 273.15
self.P1 = data["P_1"]
self.P2 = data["P_2"]
self.P3 = data["P_3"]
self.volumetric_flow_rate = data["MassFlowRate"]
self.power = data["Power"]
self.steps = steps
self.summary = {}
self.process_list = []
def compressor(self) -> List[ThermodynamicPath]:
T_in = self.T1
P_in = self.P1
self.compressor_in = ThermodynamicPoint(self.fluid, temperature=T_in, pressure=P_in)
compressor_entropy = self.compressor_in.entropy
T_2s = None
P_2s = self.P3
self.compressor_isentropic = ThermodynamicPoint(self.fluid, temperature=T_2s, pressure=P_2s, s=compressor_entropy)
T_2a = self.T2
P_2a = self.P3
self.compressor_output = ThermodynamicPoint(self.fluid, temperature=T_2a, pressure=P_2a)
# Generate Path for 1 -> 2s (isentropic efficiency)
compressor_isentropic_path = ThermodynamicPath(
point1=self.compressor_in,
point2=self.compressor_isentropic,
process_type="isentropic",
steps=self.steps,
name="Compressor Isentropic",
color="red"
)
# Generate Path for 2s -> 2a (isobaric)
compressor_loss_path = ThermodynamicPath(
point1=self.compressor_isentropic,
point2=self.compressor_output,
process_type="isobaric",
name="Compressor Actual",
steps=self.steps,
color="grey"
)
return [compressor_isentropic_path, compressor_loss_path]
def condenser(self) -> List[ThermodynamicPath]:
T2 = self.T2
P2 = self.P3
self.condenser_inlet = ThermodynamicPoint(self.fluid, temperature=T2, pressure=P2)
T3i = self.T3
P3i = self.P3
self.condenser_output_ideal = ThermodynamicPoint(self.fluid, temperature=T3i, pressure=P3i)
T3a = self.T3
P3a = self.P2
self.condenser_output_actual = ThermodynamicPoint(self.fluid, temperature=T3a, pressure=P3a)
condenser_ideal_path = ThermodynamicPath(
point1=self.condenser_inlet,
point2=self.condenser_output_ideal,
name="Condenser Ideal Path",
process_type="isobaric",
color="red",
steps=self.steps
)
condenser_loss_path = ThermodynamicPath(
point1=self.condenser_output_ideal,
point2=self.condenser_output_actual,
name="Condenser Loss Path",
process_type="isothermal",
color="grey",
steps=self.steps
)
return [condenser_ideal_path, condenser_loss_path]
def expander(self) -> List[ThermodynamicPath]:
T3 = self.T3
P3 = self.P2
self.expander_inlet = ThermodynamicPoint(self.fluid, temperature=T3, pressure=P3)
expander_enthalpy = self.expander_inlet.enthalpy
T4 = self.T4
P4 = None
self.expander_outlet = ThermodynamicPoint(self.fluid, temperature=T4, pressure=P4, h=expander_enthalpy)
expander_path = ThermodynamicPath(
point1=self.expander_inlet,
point2=self.expander_outlet,
process_type="isenthalpic",
name="Expander",
color="red",
steps=self.steps
)
return [expander_path]
def evaporator(self) -> List[ThermodynamicPath]:
T4 = self.T4
P4 = self.expander_outlet.pressure
self.evaporator_inlet = ThermodynamicPoint(self.fluid, temperature=T4, pressure=P4)
T5i = self.T5
P5i = self.P1
self.evaporator_ideal = ThermodynamicPoint(self.fluid, temperature=T5i, pressure=P5i)
T5a = self.T1
P5a = self.P1
self.evaporator_actual = ThermodynamicPoint(self.fluid, temperature=T5a, pressure=P5a)
evaporator_ideal_path = ThermodynamicPath(
point1=self.evaporator_inlet,
point2=self.evaporator_ideal,
process_type="linear",
name="Evaporator Ideal",
color="blue",
steps=self.steps
)
evaporator_loss_path = ThermodynamicPath(
point1=self.evaporator_ideal,
point2=self.evaporator_actual,
process_type="isobaric",
name="Evaporator Loss",
color="grey",
steps=self.steps
)
return [evaporator_ideal_path, evaporator_loss_path]
def run_model(self) -> Union[Dict, List]:
compressor = self.compressor()
condenser = self.condenser()
expander = self.expander()
evaporator = self.evaporator()
self.summary = {
"Compressor": compressor,
"Condenser": condenser,
"Expander": expander,
"Evaporator": evaporator
}
print("Compressor start: ({}, {})".format(self.compressor_in.enthalpy, self.compressor_in.pressure))
print("Compressor end: ({}, {})".format(self.compressor_output.enthalpy, self.compressor_output.pressure))
print("Condenser start: ({}, {})".format(self.condenser_inlet.enthalpy, self.condenser_inlet.pressure))
print("Condenser end: ({}, {})".format(self.condenser_output_actual.enthalpy, self.condenser_output_actual.pressure))
print("Expander start: ({}, {})".format(self.expander_inlet.enthalpy, self.expander_inlet.pressure))
print("Expander end: ({}, {})".format(self.expander_outlet.enthalpy, self.expander_outlet.pressure))
print("Evaporator start: ({}, {})".format(self.evaporator_inlet.enthalpy, self.evaporator_inlet.pressure))
print("Evaporator end: ({}, {})".format(self.evaporator_actual.enthalpy, self.evaporator_actual.pressure))
self.process_list = np.concatenate([compressor, condenser, expander, evaporator])
return [self.summary, self.process_list]
def main():
df = pd.read_csv("data/Base-Data.csv", index_col="ID")
experiment_6m = LabExperiment(df["6m"], 6.0)
experiment_3m = LabExperiment(df["3m"], 5.0)
experiment_1_5m = LabExperiment(df["1.5m"], 1.5)
experiments = [experiment_1_5m, experiment_3m, experiment_6m]
summary, processes = experiments[0].run_model()
system = ClosedSystem(processes, experiments[0].fluid)
system.plot_ph_diagram()
plt.show()
if __name__ == '__main__':
main()
| {"/main.py": ["/System.py"]} |
46,984 | Engineering-Geek/ThermoLab | refs/heads/main | /System.py | import pyromat as pm
import numpy as np
from typing import List
from matplotlib import pyplot as plt
class ThermodynamicPoint:
def __init__(self, fluid, temperature: float = None, pressure: float = None, dummy: bool = False,
h: float = None, s: float = None, d: float = None):
self.fluid = fluid
self.temp = None
self.pressure = None
self.internal_energy = None
self.enthalpy = None
self.entropy = None
self.specific_volume = None
self.density = None
if not dummy:
if h is not None:
if 0 < self.quality(t=temperature, h=h) < 1:
# inside dome
temperature = fluid.Ts(pressure) if temperature is None else temperature
pressure = fluid.ps(temperature) if pressure is None else pressure
x = self.quality(p=pressure, h=h)
t, p, e, h, s, d = self.get_quality_data(x, temperature)
self.manually_set(t, p, h, s, d, e)
else:
# outside dome
# This one is a tricky one and must be done manually
# given T and h, find p
# 1. generate 10 Ts between 200 and 350 K
# 2. generate 10 hs between 0.05 bar and 3 bar
# 3. find the closest h' to that the h value we have,
# and generate 10 Ts and hs between the last smallest window
if pressure is None:
steps = 10
closest_h = 9999
best_i = 0
best_j = 0
h_table = np.array(np.array([]))
Ps = np.array([])
T_low, T_high, P_low, P_high = 200, 375, 0.05, 3.2
for _ in range(5):
Ts = np.linspace(T_low, T_high, steps)
Ps = np.linspace(P_low, P_high, steps)
h_table = np.array([self.fluid.h(np.array([t] * steps), Ps) for t in Ts])
# rows: T ;;; columns: P
for i in range(steps):
for j in range(steps):
if (h_table[i][j] - h) < closest_h:
closest_h = h_table[i][j]
best_i, best_j = i, j
T_low = Ts[best_i] - (T_high - T_low) / steps
T_high = Ts[best_i] + (T_high - T_low) / steps
P_low = Ps[best_j] - (P_high - P_low) / steps
P_high = Ps[best_j] + (P_high - P_low) / steps
pressure = Ps[best_j]
self.default_set(temperature, pressure, h=h)
elif s is not None:
if 0 < self.quality(t=temperature, s=s) < 1:
# inside dome
temperature = fluid.Ts(pressure) if temperature is None else temperature
pressure = fluid.ps(temperature) if pressure is None else pressure
x = self.quality(p=pressure, s=s)
t, p, e, h, s, d = self.get_quality_data(x, temperature)
self.manually_set(t, p, h, s, d, e)
else:
# outside dome
self.default_set(temperature, pressure, s=s)
elif d is not None:
if 0 < self.quality(t=temperature, d=d) < 1:
# inside dome
temperature = fluid.Ts(pressure) if temperature is None else temperature
pressure = fluid.ps(temperature) if pressure is None else pressure
x = self.quality(p=pressure, d=d)
t, p, e, h, s, d = self.get_quality_data(x, temperature)
self.manually_set(t, p, h, s, d, e)
else:
self.tp_gen(temperature, pressure)
def get_quality_data(self, x, t=None, p=None):
if t is None and p is not None:
t = self.fluid.Ts(p)
elif p is None and t is not None:
p = self.fluid.ps(t)
internal_energy_liquid, internal_energy_vapor = self.fluid.es(T=t)
enthalpy_liquid, enthalpy_vapor = self.fluid.hs(T=t)
entropy_liquid, entropy_vapor = self.fluid.ss(T=t)
density_liquid, density_vapor = self.fluid.ds(T=t)
enthalpy = (1 - x) * enthalpy_liquid + x * enthalpy_vapor
entropy = (1 - x) * entropy_liquid + x * entropy_vapor
density = (1 - x) * density_liquid + x * density_vapor
internal_energy = (1 - x) * internal_energy_liquid + x * internal_energy_vapor
return t, p, internal_energy, enthalpy, entropy, density
def manually_set(self, temperature, pressure, enthalpy, entropy, density, internal_energy):
self.temp = temperature
self.pressure = pressure
self.internal_energy = internal_energy
self.enthalpy = enthalpy
self.entropy = entropy
self.specific_volume = 1 / density
self.density = density
def tp_gen(self, t, p):
self.enthalpy, self.entropy, self.density = self.fluid.hsd(T=t, p=p)
self.temp = t
self.pressure = p
self.internal_energy = self.fluid.e(T=t, p=p)
self.specific_volume = 1 / self.density
def default_set(self, t=None, p=None, h=None, s=None):
if p is not None and h is not None:
t = self.fluid.T_h(p=p, h=h)
elif p is not None and s is not None:
t = self.fluid.T_s(p=p, s=s)
self.tp_gen(t, p)
def quality(self, p=None, t=None, s=None, h=None, e=None, d=None):
p = self.fluid.ps(t) if t is not None else p
if s is not None:
s_liq, s_vap = self.fluid.ss(p=p)
return (s - s_liq) / (s_vap - s_liq)
elif h is not None:
h_liq, h_vap = self.fluid.hs(p=p)
return (h - h_liq) / (h_vap - h_liq)
elif e is not None:
e_liq, e_vap = self.fluid.es(p=p)
return (e - e_liq) / (e_vap - e_liq)
elif d is not None:
d_liq, d_vap = self.fluid.ds(p=p)
return (d - d_liq) / (d_vap - d_liq)
class ThermodynamicPath:
def __init__(self, point1: ThermodynamicPoint, point2: ThermodynamicPoint, process_type: str, color: str = "black",
name: str = "", steps: int = 10):
self.points = [point1, point2]
self.process_type = process_type
self.path = self.generate_path(steps)
self.color = color
self.name = name
def generate_path(self, steps) -> List[ThermodynamicPoint]:
fluid = self.points[0].fluid
path = self.points
if self.process_type == "isothermal":
assert np.abs(self.points[0].temp - self.points[1].temp) < 0.00001, "You did not give an isothermal process"
t = np.linspace(self.points[0].temp, self.points[1].temp, steps)
p = np.linspace(self.points[0].pressure, self.points[1].pressure, steps)
h = np.linspace(self.points[0].enthalpy, self.points[1].enthalpy, steps)
path = [ThermodynamicPoint(fluid, temperature=t_, pressure=p_, h=h_) for t_, p_, h_ in zip(t, p, h)]
elif self.process_type == "isobaric":
assert self.points[0].pressure - self.points[1].pressure < 0.00001, "You did not give an isobaric process"
p = np.linspace(self.points[0].pressure, self.points[1].pressure, steps)
h = np.linspace(self.points[0].enthalpy, self.points[1].enthalpy, steps)
path = [ThermodynamicPoint(fluid, pressure=p_, h=h_) for p_, h_ in zip(p, h)]
elif self.process_type == "isentropic":
assert np.abs(self.points[0].entropy - self.points[1].entropy) < 0.00001, "You did not give an isentropic process"
p = np.linspace(self.points[0].pressure, self.points[1].pressure, steps)
s = np.linspace(self.points[0].entropy, self.points[1].entropy, steps)
path = [ThermodynamicPoint(fluid, pressure=p_, s=s_) for p_, s_ in zip(p, s)]
elif self.process_type == "isenthalpic":
assert np.abs(self.points[0].enthalpy - self.points[1].enthalpy) < 0.00001, "You did not give an isenthalpic process"
p = np.linspace(self.points[0].pressure, self.points[1].pressure, steps)
h = np.linspace(self.points[0].enthalpy, self.points[1].enthalpy, steps)
path = [ThermodynamicPoint(fluid, pressure=p_, h=h_) for p_, h_ in zip(p, h)]
elif self.process_type == "linear":
p = np.linspace(self.points[0].pressure, self.points[1].pressure, steps)
h = np.linspace(self.points[0].enthalpy, self.points[1].enthalpy, steps)
path = [ThermodynamicPoint(fluid, pressure=p_, h=h_) for p_, h_ in zip(p, h)]
return path
def in_vapor_dome(self, p=None, t=None, s=None, h=None, e=None, d=None):
return 0.0 < self.points[0].quality(p, t, s, h, e, d) < 1.0
class ClosedSystem:
def __init__(self, thermodynamic_paths: List[ThermodynamicPath], fluid: pm.get):
# Complete the thermodynamic points from the thermodynamic processes given
self.thermodynamic_processes = thermodynamic_paths
# Prepare variables to start plotting
plt.semilogy()
(Tt, pt), (Tc, pc) = fluid.triple(), fluid.critical()
self.vapor_dome_temperatures = np.arange(Tt, Tc, 2.5)
self.vapor_dome_pressures = fluid.ps(self.vapor_dome_temperatures)
self.vapor_dome_enthalpies = fluid.hs(T=self.vapor_dome_temperatures)
self.vapor_dome_entropies = fluid.ss(T=self.vapor_dome_temperatures)
def plot_ph_diagram(self, vapor_color: str = "b"):
plt.figure(1)
liquid_enthalpies, vapor_enthalpies = self.vapor_dome_enthalpies
plt.plot(liquid_enthalpies, self.vapor_dome_pressures, vapor_color)
plt.plot(vapor_enthalpies, self.vapor_dome_pressures, vapor_color)
# Get (X, Y) coordinates for every thermodynamic process
for process in self.thermodynamic_processes:
x = [point.enthalpy for point in process.path]
y = [point.pressure for point in process.path]
plt.plot(x, y, color=process.color, label=process.name)
# Label each thermodynamic point
# Assume all thermodynamic systems fit onto each other
points = [process.points[1] for process in self.thermodynamic_processes]
for index, point in enumerate(points):
plt.scatter(x=point.enthalpy, y=point.pressure, color="k", label=str(index))
plt.xlabel("h (enthalpy) (kJ/kg)")
plt.ylabel("P (Pressure) (bar)")
def plot_ts_diagram(self, vapor_color: str = "b"):
plt.figure(2)
# Get (X, Y) coordinates for the vapor dome
liquid_entropies, vapor_entropies = self.vapor_dome_entropies
plt.plot(liquid_entropies, self.vapor_dome_temperatures, vapor_color)
plt.plot(vapor_entropies, self.vapor_dome_temperatures, vapor_color)
# Get (X, Y) coordinates for every thermodynamic process
for process in self.thermodynamic_processes:
x = [point.entropy[0] for point in process.path]
y = [point.temp[0] for point in process.path]
plt.plot(x, y, color=process.color, label=process.name)
# Label each thermodynamic point
# Assume all thermodynamic systems fit onto each other
points = [process.path[0] for process in self.thermodynamic_processes]
for index, point in enumerate(points):
plt.scatter(x=point.entropy[0], y=point.temp, color="k", label=str(index))
plt.xlabel("s (entropy) (kJ/kg)")
plt.ylabel("T (Temperature) (K)")
| {"/main.py": ["/System.py"]} |
46,988 | Root-kjh/MemorialDay-Calendar | refs/heads/master | /memorialCalender/calender/tests.py | from rest_framework.test import APITestCase
from rest_framework import status
from django.contrib.auth.models import User
from .models import Calender
import json
UPDATE_CALENDER_DATA = {
"title": "new_title",
"start_day": "2021-02-01",
"cycle_with": "day",
"cycle_unit": 10
}
CREATE_CALENDER_DATA = {
"title": "test_title",
"start_day": "2021-03-01",
"cycle_with": "day",
"cycle_unit": 100
}
class CalenderTests(APITestCase):
def setUp(self):
self.client.post("/auth/signup/",{'username': 'John', 'password': 'complex_password'})
self.user = User.objects.first()
response = self.client.post("/auth/signin/", {'username': 'John', 'password': 'complex_password'})
token = json.loads(response.content)['token']
self.user_id = json.loads(response.content)['id']
self.client.credentials(HTTP_AUTHORIZATION=f'JWT {token}')
def tearDown(self):
User.objects.all().delete()
def create_test_calender(self):
self.client.post(f"/user/{self.user_id}/calender/", CREATE_CALENDER_DATA)
def get_other_user_jwt(self):
self.client.post("/auth/signup/",{'username': 'dead', 'password': 'pool'})
self.user = User.objects.first()
response = self.client.post("/auth/signin/", {'username': 'dead', 'password': 'pool'})
token = json.loads(response.content)['token']
return f'JWT {token}'
def test_create_calender(self):
response = self.client.post(f"/user/{self.user_id}/calender/",CREATE_CALENDER_DATA)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
self.assertEqual(Calender.objects.count(), 1)
def test_create_calender_bad_request(self):
data = {
"title": "test_title",
"start_day": "2021-03-01",
"cycle_with": "day"
}
response = self.client.post(f"/user/{self.user_id}/calender/",data)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(Calender.objects.count(), 0)
def test_create_calender_no_jwt(self):
self.client.credentials(HTTP_AUTHORIZATION="no jwt")
response = self.client.post(f"/user/{self.user_id}/calender/",CREATE_CALENDER_DATA)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
self.assertEqual(Calender.objects.count(), 0)
def test_show_calender(self):
self.create_test_calender()
response = self.client.get(f"/user/{self.user_id}/calender/")
response_data = json.loads(response.content)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(Calender.objects.first().id, response_data[0]['id'])
def test_show_calender_no_jwt(self):
self.client.credentials(HTTP_AUTHORIZATION="no jwt")
response = self.client.get(f"/user/{self.user_id}/calender/")
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
def test_update_calender(self):
self.create_test_calender()
response = self.client.put(f"/user/{self.user_id}/calender/{Calender.objects.first().id}/",UPDATE_CALENDER_DATA)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(Calender.objects.first().title, UPDATE_CALENDER_DATA['title'])
def test_update_calender_other_user(self):
self.create_test_calender()
other_user_jwt = self.get_other_user_jwt()
self.client.credentials(HTTP_AUTHORIZATION=other_user_jwt)
response = self.client.put(f"/user/{self.user_id}/calender/{Calender.objects.first().id}/",UPDATE_CALENDER_DATA)
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
self.assertEqual(Calender.objects.first().title, CREATE_CALENDER_DATA['title'])
def test_update_calender_not_exist(self):
response = self.client.put(f"/user/{self.user_id}/calender/-1/",UPDATE_CALENDER_DATA)
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
def test_update_calender_bad_request(self):
self.create_test_calender()
data = {
"title": "new_title",
"start_day": "2021-02-01",
"cycle_with": "day"
}
response = self.client.put(f"/user/{self.user_id}/calender/{Calender.objects.first().id}/",data)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(Calender.objects.first().title, CREATE_CALENDER_DATA['title'])
def test_update_calender_no_jwt(self):
self.create_test_calender()
self.client.credentials(HTTP_AUTHORIZATION="no jwt")
response = self.client.put(f"/user/{self.user_id}/calender/{Calender.objects.first().id}/",UPDATE_CALENDER_DATA)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
self.assertEqual(Calender.objects.first().title, CREATE_CALENDER_DATA['title'])
def test_delete_calender(self):
self.create_test_calender()
response = self.client.delete(f"/user/{self.user_id}/calender/{Calender.objects.first().id}/")
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(Calender.objects.count(), 0)
def test_delete_calender_other_user(self):
self.create_test_calender()
other_user_jwt = self.get_other_user_jwt()
self.client.credentials(HTTP_AUTHORIZATION=other_user_jwt)
response = self.client.delete(f"/user/{self.user_id}/calender/{Calender.objects.first().id}/")
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
self.assertEqual(Calender.objects.count(), 1)
def test_delete_calender_not_exist(self):
response = self.client.delete(f"/user/{self.user_id}/calender/-1/")
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
def test_delete_calender_no_jwt(self):
self.create_test_calender()
self.client.credentials(HTTP_AUTHORIZATION="no jwt")
response = self.client.delete(f"/user/{self.user_id}/calender/{Calender.objects.first().id}/")
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
self.assertEqual(Calender.objects.count(), 1) | {"/memorialCalender/calender/tests.py": ["/memorialCalender/calender/models.py"], "/memorialCalender/calender/views.py": ["/memorialCalender/calender/serializers.py", "/memorialCalender/calender/models.py"], "/memorialCalender/calender/serializers.py": ["/memorialCalender/calender/models.py"], "/memorialCalender/user/views.py": ["/memorialCalender/user/serializers.py"], "/memorialCalender/auth/views.py": ["/memorialCalender/auth/serializers.py"]} |
46,989 | Root-kjh/MemorialDay-Calendar | refs/heads/master | /memorialCalender/memorialCalender/urls.py | from django.urls import path, include
from rest_framework_nested import routers
from calender.views import CalenderViewSet
from user.views import UserViewSet
from auth.views import SigninViewSet, SignupViewSet
router = routers.SimpleRouter()
router.register(r'auth/signup', SignupViewSet, 'Auth')
router.register(r'auth/signin', SigninViewSet, 'Auth')
router.register(r'user', UserViewSet)
calender_router = routers.NestedSimpleRouter(router, r'user', lookup="user")
calender_router.register(r'calender', CalenderViewSet)
urlpatterns = [
path(r'', include(router.urls)),
path(r'', include(calender_router.urls)),
] | {"/memorialCalender/calender/tests.py": ["/memorialCalender/calender/models.py"], "/memorialCalender/calender/views.py": ["/memorialCalender/calender/serializers.py", "/memorialCalender/calender/models.py"], "/memorialCalender/calender/serializers.py": ["/memorialCalender/calender/models.py"], "/memorialCalender/user/views.py": ["/memorialCalender/user/serializers.py"], "/memorialCalender/auth/views.py": ["/memorialCalender/auth/serializers.py"]} |
46,990 | Root-kjh/MemorialDay-Calendar | refs/heads/master | /memorialCalender/user/tests.py | from rest_framework.test import APITestCase
from rest_framework import status
from django.contrib.auth import authenticate
from django.contrib.auth.models import User
import json
PASSWORD_MODIFY_DATA = {"password": "new password"}
class CalenderTests(APITestCase):
def setUp(self):
self.client.post("/auth/signup/",{'username': 'John', 'password': 'complex_password'})
self.user = User.objects.first()
response = self.client.post("/auth/signin/", {'username': 'John', 'password': 'complex_password'})
token = json.loads(response.content)['token']
self.user_id = json.loads(response.content)['id']
self.client.credentials(HTTP_AUTHORIZATION=f'JWT {token}')
def tearDown(self):
User.objects.all().delete()
def get_other_user_jwt(self):
self.client.post("/auth/signup/",{'username': 'dead', 'password': 'pool'})
self.user = User.objects.first()
response = self.client.post("/auth/signin/", {'username': 'dead', 'password': 'pool'})
token = json.loads(response.content)['token']
return f'JWT {token}'
def test_password_modify(self):
response = self.client.patch(f"/user/{self.user_id}/",PASSWORD_MODIFY_DATA)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertTrue(authenticate(username="John", password=PASSWORD_MODIFY_DATA['password']))
def test_password_modify_other_user(self):
other_user_jwt = self.get_other_user_jwt()
self.client.credentials(HTTP_AUTHORIZATION=other_user_jwt)
response = self.client.patch(f"/user/{self.user_id}/",PASSWORD_MODIFY_DATA)
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
self.assertTrue(authenticate(username="John", password="complex_password"))
def test_password_modify_not_exist(self):
response = self.client.patch("/user/-1/",PASSWORD_MODIFY_DATA)
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
def test_password_modify_bad_request(self):
data = {"pw": "test"}
response = self.client.patch(f"/user/{self.user_id}/",data)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertTrue(authenticate(username="John", password="complex_password"))
def test_password_modify_no_jwt(self):
self.client.credentials(HTTP_AUTHORIZATION="no jwt")
response = self.client.patch(f"/user/{self.user_id}/",PASSWORD_MODIFY_DATA)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
self.assertTrue(authenticate(username="John", password="complex_password"))
def test_withdraw(self):
response = self.client.delete(f"/user/{self.user_id}/")
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(User.objects.count(), 0)
def test_withdraw_other_user(self):
other_user_jwt = self.get_other_user_jwt()
self.client.credentials(HTTP_AUTHORIZATION=other_user_jwt)
response = self.client.delete(f"/user/{self.user_id}/")
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
self.assertEqual(User.objects.count(), 2)
def test_withdraw_not_exist(self):
response = self.client.delete(f"/user/-1/")
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
self.assertEqual(User.objects.count(), 1)
def test_withdraw_no_jwt(self):
self.client.credentials(HTTP_AUTHORIZATION="no jwt")
response = self.client.delete(f"/user/{self.user_id}/")
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
self.assertEqual(User.objects.count(), 1)
| {"/memorialCalender/calender/tests.py": ["/memorialCalender/calender/models.py"], "/memorialCalender/calender/views.py": ["/memorialCalender/calender/serializers.py", "/memorialCalender/calender/models.py"], "/memorialCalender/calender/serializers.py": ["/memorialCalender/calender/models.py"], "/memorialCalender/user/views.py": ["/memorialCalender/user/serializers.py"], "/memorialCalender/auth/views.py": ["/memorialCalender/auth/serializers.py"]} |
46,991 | Root-kjh/MemorialDay-Calendar | refs/heads/master | /memorialCalender/calender/views.py | from rest_framework.response import Response
from rest_framework import viewsets
from .serializers import CalenderSerializer
from rest_framework.permissions import IsAuthenticated
from .models import Calender
from lib.response_form import CREATED_RESPONSE, SUCCESS_RESPONSE, PERMISSION_DENIED_RESPONSE
class CalenderViewSet(viewsets.GenericViewSet):
queryset = Calender.objects.all()
permission_classes = [IsAuthenticated]
serializer_class = CalenderSerializer
def create(self, request, user_pk=None):
user = request.user
if int(user_pk) != user.id:
print("test")
return PERMISSION_DENIED_RESPONSE
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
calender = serializer.create(serializer.validated_data, request.user.id)
calender.save()
return CREATED_RESPONSE
def list(self, request, user_pk=None):
user = request.user
if int(user_pk) != user.id:
return PERMISSION_DENIED_RESPONSE
serializer = self.get_serializer(Calender.objects.filter(user=user.id), many=True)
return Response(serializer.data)
def update(self, request, user_pk=None, pk=None):
user = request.user
calender = self.get_object()
if int(user_pk) != user.id or calender.user_id != request.user.id:
return PERMISSION_DENIED_RESPONSE
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
serializer.update(instance=calender, validated_data=serializer.validated_data)
return SUCCESS_RESPONSE
def destroy(self, request, user_pk=None, pk=None):
user = request.user
calender = self.get_object()
if int(user_pk) != user.id or calender.user_id != request.user.id:
return PERMISSION_DENIED_RESPONSE
calender.delete()
return SUCCESS_RESPONSE | {"/memorialCalender/calender/tests.py": ["/memorialCalender/calender/models.py"], "/memorialCalender/calender/views.py": ["/memorialCalender/calender/serializers.py", "/memorialCalender/calender/models.py"], "/memorialCalender/calender/serializers.py": ["/memorialCalender/calender/models.py"], "/memorialCalender/user/views.py": ["/memorialCalender/user/serializers.py"], "/memorialCalender/auth/views.py": ["/memorialCalender/auth/serializers.py"]} |
46,992 | Root-kjh/MemorialDay-Calendar | refs/heads/master | /memorialCalender/calender/apps.py | from django.apps import AppConfig
class CalenderConfig(AppConfig):
name = 'calender'
| {"/memorialCalender/calender/tests.py": ["/memorialCalender/calender/models.py"], "/memorialCalender/calender/views.py": ["/memorialCalender/calender/serializers.py", "/memorialCalender/calender/models.py"], "/memorialCalender/calender/serializers.py": ["/memorialCalender/calender/models.py"], "/memorialCalender/user/views.py": ["/memorialCalender/user/serializers.py"], "/memorialCalender/auth/views.py": ["/memorialCalender/auth/serializers.py"]} |
46,993 | Root-kjh/MemorialDay-Calendar | refs/heads/master | /memorialCalender/calender/serializers.py | from django.db.models import fields
from .models import Calender
from rest_framework import serializers
class CycleWithField(serializers.Field):
CYCLE_WITH_TO_INTERNAL_DICT={
"day": 0,
"week": 1,
"month": 2,
"year": 3
}
CYCLE_WITH_TO_EXTERNAL_LIST = ["day", "week", "month", "year"]
def to_internal_value(self, value):
value = self.CYCLE_WITH_TO_INTERNAL_DICT[value]
if type(value) is str:
raise serializers.ValidationError("cycle_with is in (day, week, month, year)")
return value
def to_representation(self, data):
return self.CYCLE_WITH_TO_EXTERNAL_LIST[data]
class CalenderSerializer(serializers.ModelSerializer):
cycle_with = CycleWithField()
class Meta:
model = Calender
fields = ('id', 'title', 'start_day', 'cycle_with', 'cycle_unit')
def create(self, validated_data, user_id):
calneder_data = {
"user_id": user_id,
"title": validated_data.pop("title"),
"start_day": validated_data.pop("start_day"),
"cycle_with": validated_data.pop("cycle_with"),
"cycle_unit": validated_data.pop("cycle_unit")
}
calender = super().create(calneder_data)
return calender | {"/memorialCalender/calender/tests.py": ["/memorialCalender/calender/models.py"], "/memorialCalender/calender/views.py": ["/memorialCalender/calender/serializers.py", "/memorialCalender/calender/models.py"], "/memorialCalender/calender/serializers.py": ["/memorialCalender/calender/models.py"], "/memorialCalender/user/views.py": ["/memorialCalender/user/serializers.py"], "/memorialCalender/auth/views.py": ["/memorialCalender/auth/serializers.py"]} |
46,994 | Root-kjh/MemorialDay-Calendar | refs/heads/master | /memorialCalender/user/serializers.py | from rest_framework import serializers
from django.contrib.auth import get_user_model
from django.contrib.auth.password_validation import validate_password
# User = get_user_model()
# class UserSerializer(serializers.ModelSerializer):
# class Meta:
# model = User
# fields = '__all__'
# read_only_fields = ['id']
class PasswordModifySerializer(serializers.Serializer):
password = serializers.CharField(required=True)
def validate_new_password(self, value):
validate_password(value)
return value | {"/memorialCalender/calender/tests.py": ["/memorialCalender/calender/models.py"], "/memorialCalender/calender/views.py": ["/memorialCalender/calender/serializers.py", "/memorialCalender/calender/models.py"], "/memorialCalender/calender/serializers.py": ["/memorialCalender/calender/models.py"], "/memorialCalender/user/views.py": ["/memorialCalender/user/serializers.py"], "/memorialCalender/auth/views.py": ["/memorialCalender/auth/serializers.py"]} |
46,995 | Root-kjh/MemorialDay-Calendar | refs/heads/master | /memorialCalender/calender/models.py | from django.db import models
from django.contrib.auth.models import User
class Calender(models.Model):
user = models.ForeignKey(User,on_delete=models.CASCADE)
title = models.CharField(max_length=20, null=False)
start_day = models.DateField()
# cycle_with
# 0 : day
# 1 : week
# 2 : month
# 3 : year
# cycle_with = models.CharField(max_length=5)
cycle_with = models.PositiveSmallIntegerField()
cycle_unit = models.IntegerField() | {"/memorialCalender/calender/tests.py": ["/memorialCalender/calender/models.py"], "/memorialCalender/calender/views.py": ["/memorialCalender/calender/serializers.py", "/memorialCalender/calender/models.py"], "/memorialCalender/calender/serializers.py": ["/memorialCalender/calender/models.py"], "/memorialCalender/user/views.py": ["/memorialCalender/user/serializers.py"], "/memorialCalender/auth/views.py": ["/memorialCalender/auth/serializers.py"]} |
46,996 | Root-kjh/MemorialDay-Calendar | refs/heads/master | /memorialCalender/user/views.py | from .serializers import PasswordModifySerializer
from rest_framework.permissions import IsAuthenticated
from django.contrib.auth.models import User
from rest_framework import viewsets
from lib.response_form import SUCCESS_RESPONSE, PERMISSION_DENIED_RESPONSE
class UserViewSet(viewsets.GenericViewSet):
queryset = User.objects.all()
permission_classes = [IsAuthenticated]
def partial_update(self, request, pk=None):
user = self.get_object()
if user.id == request.user.id:
serializer = PasswordModifySerializer(data=request.data)
serializer.is_valid(raise_exception=True)
user = self.request.user
user.set_password(serializer.data.get("password"))
user.save()
return SUCCESS_RESPONSE
else:
return PERMISSION_DENIED_RESPONSE
def destroy(self, request, pk=None):
user = self.get_object()
if user.id == request.user.id:
user.delete()
return SUCCESS_RESPONSE
else:
return PERMISSION_DENIED_RESPONSE | {"/memorialCalender/calender/tests.py": ["/memorialCalender/calender/models.py"], "/memorialCalender/calender/views.py": ["/memorialCalender/calender/serializers.py", "/memorialCalender/calender/models.py"], "/memorialCalender/calender/serializers.py": ["/memorialCalender/calender/models.py"], "/memorialCalender/user/views.py": ["/memorialCalender/user/serializers.py"], "/memorialCalender/auth/views.py": ["/memorialCalender/auth/serializers.py"]} |
46,997 | Root-kjh/MemorialDay-Calendar | refs/heads/master | /memorialCalender/auth/serializers.py | from rest_framework import serializers
from django.contrib.auth.models import User
from django.contrib.auth import authenticate
from rest_framework_jwt.settings import api_settings
from django.contrib.auth.models import update_last_login
from django.contrib.auth import get_user_model
# JWT 사용을 위한 설정
JWT_PAYLOAD_HANDLER = api_settings.JWT_PAYLOAD_HANDLER
JWT_ENCODE_HANDLER = api_settings.JWT_ENCODE_HANDLER
# 기본 유저 모델 불러오기
User = get_user_model()
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ['id', 'username', 'password']
read_only_fields = ['id']
def create(self, validated_data):
user = super().create(validated_data)
user.set_password(validated_data['password'])
user.save()
return user
class AuthSerializer(serializers.Serializer):
username = serializers.CharField(max_length=30)
password = serializers.CharField(max_length=128, write_only=True)
def validate(self, data):
username = data.get("username")
password = data.get("password", None)
user = authenticate(username=username, password=password)
if user is None:
return {'username': 'None'}
try:
payload = JWT_PAYLOAD_HANDLER(user)
jwt_token = JWT_ENCODE_HANDLER(payload)
update_last_login(None, user)
except User.DoesNotExist:
raise serializers.ValidationError(
'User with given username and password does not exist'
)
return {
'id' : user.id,
'username' : user.username,
'token' : jwt_token
} | {"/memorialCalender/calender/tests.py": ["/memorialCalender/calender/models.py"], "/memorialCalender/calender/views.py": ["/memorialCalender/calender/serializers.py", "/memorialCalender/calender/models.py"], "/memorialCalender/calender/serializers.py": ["/memorialCalender/calender/models.py"], "/memorialCalender/user/views.py": ["/memorialCalender/user/serializers.py"], "/memorialCalender/auth/views.py": ["/memorialCalender/auth/serializers.py"]} |
46,998 | Root-kjh/MemorialDay-Calendar | refs/heads/master | /memorialCalender/auth/views.py | from rest_framework.response import Response
from .serializers import AuthSerializer, UserSerializer
from rest_framework.permissions import AllowAny
from rest_framework import viewsets
from lib.response_form import CREATED_RESPONSE, FAILED_RESPONSE
class SignupViewSet(viewsets.GenericViewSet):
permission_classes = [AllowAny]
serializer_class = UserSerializer
def create(self, request):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
serializer.create(serializer.validated_data)
return CREATED_RESPONSE
class SigninViewSet(viewsets.GenericViewSet):
permission_classes = [AllowAny]
serializer_class = AuthSerializer
def create(self, request):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
user = serializer.validated_data
if user['username'] == "None":
return FAILED_RESPONSE
return Response(user) | {"/memorialCalender/calender/tests.py": ["/memorialCalender/calender/models.py"], "/memorialCalender/calender/views.py": ["/memorialCalender/calender/serializers.py", "/memorialCalender/calender/models.py"], "/memorialCalender/calender/serializers.py": ["/memorialCalender/calender/models.py"], "/memorialCalender/user/views.py": ["/memorialCalender/user/serializers.py"], "/memorialCalender/auth/views.py": ["/memorialCalender/auth/serializers.py"]} |
46,999 | Root-kjh/MemorialDay-Calendar | refs/heads/master | /memorialCalender/calender/migrations/0003_auto_20210306_1506.py | # Generated by Django 3.1.6 on 2021-03-06 06:06
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('calender', '0002_auto_20210215_1745'),
]
operations = [
migrations.AlterField(
model_name='calender',
name='cycle_with',
field=models.PositiveSmallIntegerField(),
),
]
| {"/memorialCalender/calender/tests.py": ["/memorialCalender/calender/models.py"], "/memorialCalender/calender/views.py": ["/memorialCalender/calender/serializers.py", "/memorialCalender/calender/models.py"], "/memorialCalender/calender/serializers.py": ["/memorialCalender/calender/models.py"], "/memorialCalender/user/views.py": ["/memorialCalender/user/serializers.py"], "/memorialCalender/auth/views.py": ["/memorialCalender/auth/serializers.py"]} |
47,000 | Root-kjh/MemorialDay-Calendar | refs/heads/master | /memorialCalender/lib/response_form.py | from rest_framework.response import Response
from rest_framework import status
CREATED_RESPONSE = Response({"Message": "Created"}, status=status.HTTP_201_CREATED)
SUCCESS_RESPONSE = Response({"Message": "Success"})
FAILED_RESPONSE = Response({"Message": "Failed"}, status=status.HTTP_400_BAD_REQUEST)
PERMISSION_DENIED_RESPONSE = Response({"Message": "Permission Denied"}, status=status.HTTP_403_FORBIDDEN) | {"/memorialCalender/calender/tests.py": ["/memorialCalender/calender/models.py"], "/memorialCalender/calender/views.py": ["/memorialCalender/calender/serializers.py", "/memorialCalender/calender/models.py"], "/memorialCalender/calender/serializers.py": ["/memorialCalender/calender/models.py"], "/memorialCalender/user/views.py": ["/memorialCalender/user/serializers.py"], "/memorialCalender/auth/views.py": ["/memorialCalender/auth/serializers.py"]} |
47,001 | Root-kjh/MemorialDay-Calendar | refs/heads/master | /memorialCalender/auth/tests.py | from rest_framework.test import APITestCase
from rest_framework import status
from django.contrib.auth.models import User
from rest_framework_jwt.settings import api_settings
import json
JWT_DECODE_HANDLER = api_settings.JWT_DECODE_HANDLER
class AuthTests(APITestCase):
def tearDown(self):
User.objects.all().delete()
def test_signup(self):
response = self.client.post("/auth/signup/",{'username': 'John', 'password': 'complex_password'})
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
self.assertEqual(User.objects.count(), 1)
def test_signup_exist_user(self):
response = self.client.post("/auth/signup/", {'username': 'John', 'password': 'complex_password'})
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
response = self.client.post("/auth/signup/", {'username': 'John', 'password': 'complex_password'})
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(User.objects.count(), 1)
def test_signup_bad_request(self):
response = self.client.post("/auth/signup/",{'username': 'John'})
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
def test_signin(self):
self.client.post("/auth/signup/",{'username': 'John', 'password': 'complex_password'})
response = self.client.post("/auth/signin/", {'username': 'John', 'password': 'complex_password'})
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(JWT_DECODE_HANDLER(json.loads(response.content)['token'])['username'], "John")
def test_signin_login_failed(self):
self.client.post("/auth/signup/",{'username': 'John', 'password': 'complex_password'})
response = self.client.post("/auth/signin/", {'username': 'John', 'password': 'no password'})
self.assertEqual(json.loads(response.content)['Message'], "Failed") | {"/memorialCalender/calender/tests.py": ["/memorialCalender/calender/models.py"], "/memorialCalender/calender/views.py": ["/memorialCalender/calender/serializers.py", "/memorialCalender/calender/models.py"], "/memorialCalender/calender/serializers.py": ["/memorialCalender/calender/models.py"], "/memorialCalender/user/views.py": ["/memorialCalender/user/serializers.py"], "/memorialCalender/auth/views.py": ["/memorialCalender/auth/serializers.py"]} |
47,008 | MichalJanusz/webshop | refs/heads/develop | /webshop/views.py | from django.contrib.auth.views import LoginView, LogoutView
from django.shortcuts import render
from django.views import View
from webshop.forms import LoginForm
# Create your views here.
class MainView(View):
def get(self, request):
return render(request, 'webshop/index.html')
class LogInView(LoginView):
template_name = 'webshop/login.html'
authentication_form = LoginForm
class LogOutView(LogoutView):
pass
| {"/webshop/views.py": ["/webshop/forms.py"]} |
47,009 | MichalJanusz/webshop | refs/heads/develop | /webshop/forms.py | from django import forms
from django.contrib.auth.forms import AuthenticationForm
# Create your forms here
class LoginForm(AuthenticationForm):
username = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'login'}), label=False)
password = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'password'}), label=False)
| {"/webshop/views.py": ["/webshop/forms.py"]} |
47,011 | williamrobotma/mlstm4reco | refs/heads/master | /experiments/run.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import os
import shutil
import pickle
import time
import argparse
import torch
import numpy as np
from IPython.core import ultratb
from spotlight.sequence.implicit import ImplicitSequenceModel
from spotlight.cross_validation import user_based_train_test_split
from spotlight.datasets.goodbooks import get_goodbooks_dataset
from spotlight.datasets.amazon import get_amazon_dataset
from spotlight.datasets.movielens import get_movielens_dataset
from spotlight.evaluation import sequence_mrr_score
from spotlight.torch_utils import set_seed
import hyperopt
from hyperopt import Trials, hp, fmin, STATUS_OK, STATUS_FAIL
from mlstm4reco.representations import mLSTMNet
CUDA = False
# Start IPython shell on exception (nice for debugging)
sys.excepthook = ultratb.FormattedTB(mode='Verbose', color_scheme='Linux', call_pdb=1)
# First element is always default
DATASETS = ['1m', '10m', 'amazon', 'goodbooks']
MODELS = ['mlstm', 'lstm']
def parse_args(args):
parser = argparse.ArgumentParser(description='Run experiment for benchmarks.')
parser.add_argument('dataset',
type=str,
choices=DATASETS,
default=DATASETS[0],
help='Name of the dataset or variant for Movielens')
parser.add_argument('-n', '--num_trials',
dest='num_trials',
default=100,
type=int,
help='Number of trials to run')
parser.add_argument('-m', '--model',
dest='model',
default=MODELS[0],
choices=MODELS,
type=str,
help='Model for experiment')
return parser.parse_args(args)
def hyperparameter_space(model_type):
"""Define hyperopt hyperparameter space
Args:
model_type: Restrict to model if provided.
Returns:
hyperparameter object
"""
common_space = {
'batch_size': hp.quniform('batch_size', 64, 256, 16),
'learn_rate': hp.loguniform('learn_rate', -6, -3),
'l2': hp.loguniform('l2', -25, -9),
'n_iter': hp.quniform('n_iter', 20, 50, 5),
'loss': hp.choice('loss', ['adaptive_hinge']),
'embedding_dim': hp.quniform('embedding_dim', 16, 128, 8),
}
models = [
{
'type': 'lstm',
'representation': 'lstm',
**common_space
},
{
'type': 'mlstm',
**common_space
}
]
space = [model for model in models if model['type'] == model_type]
assert len(space) == 1
return space[0]
def get_objective(train, valid, test, random_state=None):
def objective(space):
batch_size = int(space['batch_size'])
learn_rate = space['learn_rate']
loss = space['loss']
n_iter = int(space['n_iter'])
embedding_dim = int(space['embedding_dim'])
l2 = space['l2']
if space['type'] == 'mlstm':
representation = mLSTMNet(
train.num_items,
embedding_dim=embedding_dim)
model = ImplicitSequenceModel(
loss=loss,
batch_size=batch_size,
representation=representation,
learning_rate=learn_rate,
n_iter=n_iter,
l2=l2,
use_cuda=CUDA,
random_state=random_state)
elif space['type'] == 'lstm':
representation = space['representation']
model = ImplicitSequenceModel(
loss=loss,
embedding_dim=embedding_dim,
batch_size=batch_size,
representation=representation,
learning_rate=learn_rate,
n_iter=n_iter,
l2=l2,
use_cuda=CUDA,
random_state=random_state)
else:
raise ValueError('Unknown model type {}'.format(space.get('type', 'NA')))
start = time.clock()
try:
model.fit(train, verbose=True)
except ValueError:
elapsed = time.clock() - start
return {'loss': 0.0,
'status': STATUS_FAIL,
'validation_mrr': 0.0,
'test_mrr': 0.0,
'elapsed': elapsed,
'hyper': space}
elapsed = time.clock() - start
print(model)
validation_mrr = sequence_mrr_score(
model,
valid,
exclude_preceding=True
).mean()
test_mrr = sequence_mrr_score(
model,
test,
exclude_preceding=True
).mean()
print('MRR {} {}'.format(validation_mrr, test_mrr))
if np.isnan(validation_mrr):
status = STATUS_FAIL
else:
status = STATUS_OK
return {'loss': -validation_mrr,
'status': status,
'validation_mrr': validation_mrr,
'test_mrr': test_mrr,
'elapsed': elapsed,
'hyper': space}
return objective
def optimize(objective, space, trials_fname=None, max_evals=5):
if trials_fname is not None and os.path.exists(trials_fname):
with open(trials_fname, 'rb') as trials_file:
trials = pickle.load(trials_file)
else:
trials = Trials()
fmin(objective,
space=space,
algo=hyperopt.tpe.suggest,
trials=trials,
max_evals=max_evals)
if trials_fname is not None:
temporary = '{}.temp'.format(trials_fname)
with open(temporary, 'wb') as trials_file:
pickle.dump(trials, trials_file)
shutil.move(temporary, trials_fname)
return trials
def summarize_trials(trials):
results = trials.trials
model_type = results[0]['result']['hyper']['type']
results = sorted(results, key=lambda x: -x['result']['validation_mrr'])
if results:
print('Best {}: {}'.format(model_type, results[0]['result']))
results = sorted(results, key=lambda x: -x['result']['test_mrr'])
if results:
print('Best test {}: {}'.format(model_type, results[0]['result']))
def main(args):
status = 'available' if CUDA else 'not available'
print("CUDA is {}!".format(status))
args = parse_args(args)
# Fix random_state
seed = 72
set_seed(seed)
random_state = np.random.RandomState(seed)
max_sequence_length = 100
min_sequence_length = 20
step_size = max_sequence_length
if args.dataset == 'amazon':
max_sequence_length = 50
min_sequence_length = 5
step_size = max_sequence_length
dataset = get_amazon_dataset()
elif args.dataset == 'goodbooks':
dataset = get_goodbooks_dataset()
else:
dataset = get_movielens_dataset(args.dataset.upper())
args.variant = args.dataset
train, rest = user_based_train_test_split(
dataset,
test_percentage=0.2,
random_state=random_state)
test, valid = user_based_train_test_split(
rest,
test_percentage=0.5,
random_state=random_state)
train = train.to_sequence(
max_sequence_length=max_sequence_length,
min_sequence_length=min_sequence_length,
step_size=step_size)
test = test.to_sequence(
max_sequence_length=max_sequence_length,
min_sequence_length=min_sequence_length,
step_size=step_size)
valid = valid.to_sequence(
max_sequence_length=max_sequence_length,
min_sequence_length=min_sequence_length,
step_size=step_size)
print('model: {}, data: {}'.format(args.model, train))
fname = 'experiment_{}_{}.pickle'.format(args.model, args.dataset)
objective = get_objective(train, valid, test, random_state)
space = hyperparameter_space(args.model)
for iteration in range(args.num_trials):
print('Iteration {}'.format(iteration))
trials = optimize(objective,
space,
trials_fname=fname,
max_evals=iteration + 1)
summarize_trials(trials)
if __name__ == '__main__':
main(sys.argv[1:])
| {"/src/mlstm4reco/representations.py": ["/src/mlstm4reco/layers.py"]} |
47,012 | williamrobotma/mlstm4reco | refs/heads/master | /src/mlstm4reco/representations.py | # -*- coding: utf-8 -*-
"""
Classes defining user and item latent representations in
factorization models.
"""
import torch
from torch import nn
from spotlight.layers import ScaledEmbedding, ZeroEmbedding
from .layers import mLSTM
PADDING_IDX = 0
class mLSTMNet(nn.Module):
"""
Module representing users through running a recurrent neural network
over the sequence, using the hidden state at each timestep as the
sequence representation, a'la [2]_
During training, representations for all timesteps of the sequence are
computed in one go. Loss functions using the outputs will therefore
be aggregating both across the minibatch and across time in the sequence.
Parameters
----------
num_items: int
Number of items to be represented.
embedding_dim: int, optional
Embedding dimension of the embedding layer, and the number of hidden
units in the LSTM layer.
item_embedding_layer: an embedding layer, optional
If supplied, will be used as the item embedding layer
of the network.
References
----------
.. [2] Hidasi, Balazs, et al. "Session-based recommendations with
recurrent neural networks." arXiv preprint arXiv:1511.06939 (2015).
"""
def __init__(self, num_items, embedding_dim=32,
item_embedding_layer=None, sparse=False):
super(mLSTMNet, self).__init__()
self.embedding_dim = embedding_dim
if item_embedding_layer is not None:
self.item_embeddings = item_embedding_layer
else:
self.item_embeddings = ScaledEmbedding(num_items, embedding_dim,
padding_idx=PADDING_IDX,
sparse=sparse)
self.item_biases = ZeroEmbedding(num_items, 1, sparse=sparse,
padding_idx=PADDING_IDX)
h_init = torch.zeros(embedding_dim)
h_init.normal_(0, 1.0 / self.embedding_dim)
self.h_init = nn.Parameter(h_init, requires_grad=True)
self.mlstm = mLSTM(input_size=embedding_dim,
hidden_size=embedding_dim)
def user_representation(self, item_sequences):
"""
Compute user representation from a given sequence.
Returns
-------
tuple (all_representations, final_representation)
The first element contains all representations from step
-1 (no items seen) to t - 1 (all but the last items seen).
The second element contains the final representation
at step t (all items seen). This final state can be used
for prediction or evaluation.
"""
# Make the embedding dimension the channel dimension
sequence_embeddings = self.item_embeddings(item_sequences)
# pad from left with initial state
batch_size = sequence_embeddings.size()[0]
embedding_dim = self.h_init.size()[0]
seq_start = self.h_init.expand(batch_size, embedding_dim)
user_representations = self.mlstm(sequence_embeddings, (seq_start, seq_start))
user_representations = user_representations.permute(0, 2, 1)
return user_representations[:, :, :-1], user_representations[:, :, -1]
def forward(self, user_representations, targets):
"""
Compute predictions for target items given user representations.
Parameters
----------
user_representations: tensor
Result of the user_representation_method.
targets: tensor
A minibatch of item sequences of shape
(minibatch_size, sequence_length).
Returns
-------
predictions: tensor
of shape (minibatch_size, sequence_length)
"""
target_embedding = (self.item_embeddings(targets)
.permute(0, 2, 1)
.squeeze())
target_bias = self.item_biases(targets).squeeze()
dot = ((user_representations * target_embedding)
.sum(1)
.squeeze())
return target_bias + dot
| {"/src/mlstm4reco/representations.py": ["/src/mlstm4reco/layers.py"]} |
47,013 | williamrobotma/mlstm4reco | refs/heads/master | /src/mlstm4reco/layers.py | import math
import torch
from torch.nn import Parameter
from torch.nn.modules.rnn import RNNBase, LSTMCell
from torch.nn import functional as F
class mLSTM(RNNBase):
def __init__(self, input_size, hidden_size, bias=True):
super(mLSTM, self).__init__(
mode='LSTM', input_size=input_size, hidden_size=hidden_size,
num_layers=1, bias=bias, batch_first=True,
dropout=0, bidirectional=False)
w_im = torch.Tensor(hidden_size, input_size)
w_hm = torch.Tensor(hidden_size, hidden_size)
b_im = torch.Tensor(hidden_size)
b_hm = torch.Tensor(hidden_size)
self.w_im = Parameter(w_im)
self.b_im = Parameter(b_im)
self.w_hm = Parameter(w_hm)
self.b_hm = Parameter(b_hm)
self.lstm_cell = LSTMCell(input_size, hidden_size, bias)
self.reset_parameters()
def reset_parameters(self):
stdv = 1.0 / math.sqrt(self.hidden_size)
for weight in self.parameters():
weight.data.uniform_(-stdv, stdv)
def forward(self, input, hx):
n_batch, n_seq, n_feat = input.size()
hx, cx = hx
steps = [cx.unsqueeze(1)]
for seq in range(n_seq):
mx = F.linear(input[:, seq, :], self.w_im, self.b_im) * F.linear(hx, self.w_hm, self.b_hm)
hx = (mx, cx)
hx, cx = self.lstm_cell(input[:, seq, :], hx)
steps.append(cx.unsqueeze(1))
return torch.cat(steps, dim=1)
| {"/src/mlstm4reco/representations.py": ["/src/mlstm4reco/layers.py"]} |
47,022 | seashaw/image-site | refs/heads/master | /app/__init__.py | """
File: __init__.py
Authors:
2014-11-14 - C.Shaw <shaw.colin@gmail.com>
Description:
Initialization module for object tracker application.
Order of initializations and imports is particular.
"""
import os
from datetime import datetime
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.bcrypt import Bcrypt
from flask.ext.mail import Mail
from flask.ext.login import LoginManager, current_user
from flask.ext.admin import Admin
from flask.ext.admin.contrib.fileadmin import FileAdmin
# Initialize the application.
app = Flask(__name__)
# Add now to jinja globals for dynamic year footer.
app.jinja_env.globals.update(now=datetime.now())
def getPassword():
"""
Function to get email password from local file.
"""
# Open file for reading.
file = open('pw', mode='r')
# Read first line and strip newline character.
email_password = file.read().strip()
# Close the file and return password.
file.close()
return email_password
# Load configuration.
app.config.update(dict(
# SQLAlchemy database connection address.
SQLALCHEMY_DATABASE_URI =
'postgresql://image_app:snapsnap@localhost/image_site',
SECRET_KEY = "In development.",
# Mail settings.
MAIL_SERVER = "smtp.zoho.com",
MAIL_PORT = 465,
MAIL_USE_TLS = False,
MAIL_USE_SSL = True,
MAIL_USERNAME = "noreply@colinshaw.org",
MAIL_PASSWORD = getPassword(),
ADMIN_EMAIL = "administrator@colinshaw.org",
# Set of allowed file extensions.
EXTENSIONS = set(["png", "jpg", "jpeg", "gif"]),
# Upload settings.
MAX_CONTENT_LENGTH = 5 * 1024 * 1024 # 5MB
))
# Bcrypt object initialization.
bc = Bcrypt(app)
# Mail object initialization.
mail = Mail(app)
# SQLAlchemy object initialization.
db = SQLAlchemy(app)
# Model class imports.
from .model import User, Role, Post, Picture
# Login object initialization.
lm = LoginManager()
lm.init_app(app)
# User loader callback for LoginManager.
@lm.user_loader
def loadUser(user_id):
"""
Returns User object from database.
"""
return User.query.get(user_id)
# Principal and role based access control import.
from . import roles
# Controller import.
from . import controller
# Admin view import.
from .admin import (HomeView, UsersView, RolesView, PostsView, PicturesView,
FileView)
# Admin object initialization.
admin = Admin(app, index_view=HomeView(), name="Angry Hos")
admin.add_view(UsersView(User, db.session, name='Users'))
admin.add_view(RolesView(Role, db.session, name='Roles'))
admin.add_view(PostsView(Post, db.session, name='Posts'))
admin.add_view(PicturesView(Picture, db.session, name='Pictures'))
| {"/app/__init__.py": ["/app/model.py", "/app/admin.py"], "/manage.py": ["/app/__init__.py"], "/app/admin.py": ["/app/roles.py"], "/app/forms.py": ["/app/model.py"], "/recreate_tables.py": ["/app/__init__.py", "/app/model.py", "/app/roles.py"], "/app/controller.py": ["/app/__init__.py", "/app/roles.py", "/app/model.py", "/app/forms.py"], "/app/model.py": ["/app/__init__.py"], "/wsgi.py": ["/app/__init__.py"], "/tests.py": ["/app/__init__.py", "/app/model.py", "/app/roles.py"]} |
47,023 | seashaw/image-site | refs/heads/master | /manage.py | #!/usr/bin/env python3
"""
Name: manage.py
Authors:
2014-11-14 - C.Shaw <shaw.colin@gmail.com>
Description:
Script to manage database migrations.
"""
from app import app, db, model
from flask.ext.script import Manager
from flask.ext.migrate import Migrate, MigrateCommand
# Migrate object initialization.
mig = Migrate(app, db)
# Script manager setup.
man = Manager(app)
man.add_command('db', MigrateCommand)
if __name__ == '__main__':
man.run()
| {"/app/__init__.py": ["/app/model.py", "/app/admin.py"], "/manage.py": ["/app/__init__.py"], "/app/admin.py": ["/app/roles.py"], "/app/forms.py": ["/app/model.py"], "/recreate_tables.py": ["/app/__init__.py", "/app/model.py", "/app/roles.py"], "/app/controller.py": ["/app/__init__.py", "/app/roles.py", "/app/model.py", "/app/forms.py"], "/app/model.py": ["/app/__init__.py"], "/wsgi.py": ["/app/__init__.py"], "/tests.py": ["/app/__init__.py", "/app/model.py", "/app/roles.py"]} |
47,024 | seashaw/image-site | refs/heads/master | /app/admin.py | """
File: admin.py
Authors:
2014-12-12 - C.Shaw <shaw.colin@gmail.com>
Description:
Administrative views.
"""
from .roles import admin_permission
from flask.ext.admin import expose, BaseView, AdminIndexView
from flask.ext.admin.contrib.sqla import ModelView
from flask.ext.admin.contrib.fileadmin import FileAdmin
class HomeView(AdminIndexView):
"""
Index view route for administration.
"""
def is_accessible(self):
"""
Restrict access to authenticated users.
"""
return admin_permission.can()
class UsersView(ModelView):
"""
Admin view for user management.
"""
# Display primary key column.
column_display_pk = True
def is_accessible(self):
"""
Restrict access to authenticated users.
"""
return admin_permission.can()
class RolesView(ModelView):
"""
Admin view for role management.
"""
# Display primary key column.
column_display_pk = True
def is_accessible(self):
"""
Restrict access to authenticated users.
"""
return admin_permission.can()
class PostsView(ModelView):
"""
Admin view for post management.
"""
# Display primary key column.
column_display_pk = True
def is_accessible(self):
"""
Restrict access to authenticated users.
"""
return admin_permission.can()
class PicturesView(ModelView):
"""
Admin view for post management.
"""
# Display primary key column.
column_display_pk = True
def is_accessible(self):
"""
Restrict access to authenticated users.
"""
return admin_permission.can()
class FileView(FileAdmin):
"""
Manage uploaded files and directories.
"""
def is_accessible(self):
"""
Restrict access to authenticated users.
"""
return admin_permission.can()
| {"/app/__init__.py": ["/app/model.py", "/app/admin.py"], "/manage.py": ["/app/__init__.py"], "/app/admin.py": ["/app/roles.py"], "/app/forms.py": ["/app/model.py"], "/recreate_tables.py": ["/app/__init__.py", "/app/model.py", "/app/roles.py"], "/app/controller.py": ["/app/__init__.py", "/app/roles.py", "/app/model.py", "/app/forms.py"], "/app/model.py": ["/app/__init__.py"], "/wsgi.py": ["/app/__init__.py"], "/tests.py": ["/app/__init__.py", "/app/model.py", "/app/roles.py"]} |
47,025 | seashaw/image-site | refs/heads/master | /app/forms.py | """
File: forms.py
Created: 2014-11-14 - C.Shaw <shaw.colin@gmail.com>
Description:
Forms and custom validators for form fields.
"""
from .model import User
from flask.ext.wtf import Form
import wtforms
from flask.ext.login import current_user
from wtforms import TextField, SubmitField, PasswordField, TextAreaField, \
FieldList, FileField, BooleanField, FormField, RadioField, IntegerField
from wtforms.validators import InputRequired, Length, EqualTo, \
ValidationError, DataRequired, Email, Optional
"""
Custom validator functions.
"""
def uniqueEmailCheck(form, field):
"""
Unique email validation.
"""
if User.query.filter_by(email=field.data).first():
raise ValidationError('"{}" is already registered'.format(field.data))
def userNameExistsCheck(form, field):
"""
Ensures that user with user_name exists in the database.
"""
if not User.query.filter_by(user_name=field.data).first():
raise ValidationError('"{}" is not registered'.format(field.data))
def uniqueUserNameCheck(form, field):
"""
Unique user name validation.
"""
if User.query.filter_by(user_name=field.data).first():
raise ValidationError('"{}" is already taken'.format(field.data))
"""
Forms for user input.
"""
class LoginForm(Form):
"""
User authentication.
"""
user_name = TextField("User", validators=[InputRequired(),
userNameExistsCheck])
password = PasswordField("Password", validators=[InputRequired()])
submit = SubmitField("Login")
class RegisterForm(Form):
"""
User registration.
"""
email = TextField("Email",
validators=[Optional(),
Email(message="Invalid email address format."),
uniqueEmailCheck])
user_name = TextField("User Name", validators=[DataRequired(),
uniqueUserNameCheck])
password = PasswordField("New Password", validators=[InputRequired(),
EqualTo("confirm", message="Passwords must match."),
Length(min=8, max=64, message="Password must be between 8 and 64 "
"characters.")])
confirm = PasswordField("Confirm Password", validators=[InputRequired()])
submit = SubmitField("Register")
class ServiceRequestForm(Form):
"""
Allows users to input their email to process service requests.
"""
email = TextField("Email", validators=[InputRequired()] )
submit = SubmitField("Send Request")
class PasswordResetForm(Form):
"""
Password reset form.
"""
password = PasswordField("New Password", validators=[InputRequired(),
EqualTo("confirm", message="Passwords must match."),
Length(min=8, max=64, message="Password must be between 8 and 64 "
"characters.")])
confirm = PasswordField("Confirm Password", validators=[InputRequired()])
submit = SubmitField("Reset")
class CreatePostForm(Form):
"""
Post creation.
"""
pics = FileField('Add Pictures')
title = TextField('Title', validators=[InputRequired()])
subtitle = TextField('Subtitle')
body = TextAreaField('Body')
submit = SubmitField("Post")
class EditImageDataForm(wtforms.Form):
"""
For editing picture data.
"""
title = TextField('Title')
position = IntegerField('position')
delete = BooleanField('Delete', default=False)
class EditPostForm(CreatePostForm):
"""
Post editing and updating posts.
"""
pic_forms = FieldList(FormField(EditImageDataForm))
submit = SubmitField("Update")
class CommentForm(Form):
"""
Form for adding comments to post.
"""
body = TextAreaField('Leave a comment', validators=[InputRequired()])
parent_id = IntegerField('Parent ID', default=0)
submit = SubmitField("Comment")
| {"/app/__init__.py": ["/app/model.py", "/app/admin.py"], "/manage.py": ["/app/__init__.py"], "/app/admin.py": ["/app/roles.py"], "/app/forms.py": ["/app/model.py"], "/recreate_tables.py": ["/app/__init__.py", "/app/model.py", "/app/roles.py"], "/app/controller.py": ["/app/__init__.py", "/app/roles.py", "/app/model.py", "/app/forms.py"], "/app/model.py": ["/app/__init__.py"], "/wsgi.py": ["/app/__init__.py"], "/tests.py": ["/app/__init__.py", "/app/model.py", "/app/roles.py"]} |
47,026 | seashaw/image-site | refs/heads/master | /recreate_tables.py | #!/usr/bin/env python3
from app import db, bc
import app.model
from app.model import User, Role
import os
import shutil
from datetime import datetime
from pytz import utc
# Drop all database tables.
print("Dropping and recreating database tables.")
db.drop_all()
db.create_all()
# Remove all user uploads.
print("Removing and recreating upload folder.")
shutil.rmtree('app/static/uploads/1/')
os.mkdir('app/static/uploads/1')
os.chmod('app/static/uploads/1', mode=0o777)
# Create default user.
print("Creating new user.")
user = User(password=bc.generate_password_hash('la73ralu5', rounds=12),
user_name='cshaw')
# Creating roles.
print("Creating roles.")
from app.roles import active_role, admin_role, verified_role
print("Adding roles to session.")
db.session.add(admin_role)
db.session.add(active_role)
db.session.add(verified_role)
db.session.flush()
# Add roles to user object.
print("Adding roles to user.")
user.roles.append(admin_role)
user.roles.append(active_role)
user.roles.append(verified_role)
print("Adding user to session.")
db.session.add(user)
print("Commiting session to database.")
db.session.commit()
| {"/app/__init__.py": ["/app/model.py", "/app/admin.py"], "/manage.py": ["/app/__init__.py"], "/app/admin.py": ["/app/roles.py"], "/app/forms.py": ["/app/model.py"], "/recreate_tables.py": ["/app/__init__.py", "/app/model.py", "/app/roles.py"], "/app/controller.py": ["/app/__init__.py", "/app/roles.py", "/app/model.py", "/app/forms.py"], "/app/model.py": ["/app/__init__.py"], "/wsgi.py": ["/app/__init__.py"], "/tests.py": ["/app/__init__.py", "/app/model.py", "/app/roles.py"]} |
47,027 | seashaw/image-site | refs/heads/master | /app/controller.py | """
File: controller.py
Authors:
2014-11-14 - C.Shaw <shaw.colin@gmail.com>
Description:
Routing for web application, generates views using templates,
and handles logic for user input.
"""
import os
import uuid
import math
import re
from datetime import datetime
import pytz
from pytz import timezone, utc
from PIL import Image
from werkzeug import secure_filename
from sqlalchemy import desc
from flask import (Flask, render_template, jsonify, request, redirect,
url_for, flash, current_app, session, abort)
from flask.ext.login import (login_required, login_user, logout_user,
current_user)
from flask.ext.mail import Message
from flask.ext.principal import Identity, AnonymousIdentity, identity_changed
from . import app, bc, mail, db
from .roles import EditBlogPostPermission, activeRole, verifiedRole, \
adminRole, active_permission, verified_permission
from .model import User, Post, Picture, Comment, Role
from .forms import LoginForm, RegisterForm, CreatePostForm, EditPostForm, \
ServiceRequestForm, PasswordResetForm, EditImageDataForm, RadioField, \
CommentForm
"""
Helper functions.
"""
def allowedFile(file_name):
"""
Checks file name for allowed extension.
"""
# Split file_name from the right at period, check if in extensions set,
# and return.
return "." in file_name and file_name.rsplit(".", 1)[1] in \
app.config["EXTENSIONS"]
def renameFile(file_name):
"""
Takes file_name, appends current datetime stamp, and returns it.
"""
# Split off extension.
splits = file_name.rsplit('.', 1)
# Compile number finding regex.
rc = re.compile("-cp:(\\d+)$")
# Search for existing copy timestamp.
res = re.findall(rc, splits[0])
now = datetime.now(tz=utc)
stamp = "-cp:" + str(now.year) + str(now.month) + str(now.day) + \
str(now.hour) + str(now.minute) + str(now.second) + \
str(now.microsecond)
# If none append new one.
if len(res) == 0:
return splits[0] + stamp + "." + splits[1]
# Else replace old one with new one.
else:
return rc.sub(stamp, splits[0]) + "." + splits[1]
"""
Routing functions, controller logic, view redirection.
"""
@app.route("/", defaults={"page": 1})
@app.route('/index/', defaults={"page": 1})
@app.route("/index/<int:page>")
def index(page):
"""
Application index, contains list of recent posts.
"""
# Number of posts per page.
ppp = 2
# Limit of range of pagination.
range_limit = 10
# Get posts for page.
posts = Post.query.order_by(desc("id")).offset(
(page-1) * ppp).limit(ppp).all()
# Get total number of posts and divide into number of pages.
count = Post.query.count() # Is this the best way to get count?
pages = math.ceil(count / ppp)
if page - range_limit - 1 < 0:
prev = 0
else:
prev = page - range_limit - 1
if page + range_limit + 1 > pages + 1:
next = pages + 1
else:
next = page + range_limit + 1
page_range = list(range(prev+1, next))
if next > pages:
next = 0
# Check if end was reached.
if len(posts) < ppp or page == pages:
end = True
else:
end = False
return render_template("index.html", posts=posts, page=page, end=end,
page_range=page_range)
@app.route("/register", methods=["GET", "POST"])
def register():
"""
Create and set up new user.
"""
form = RegisterForm()
if form.validate_on_submit():
# Feed form data into User object creation.
user = User(password=bc.generate_password_hash(form.password.data,
rounds=12), user_name=form.user_name.data)
user.roles.append(activeRole())
db.session.flush()
path = "{}/{}".format(app.config['UPLOAD_FOLDER'], user.id)
os.mkdir(path)
os.chmod(path, mode=0o777)
if form.email.data:
user.email = form.email.data
# Generate cryptographic nonce with datetime.
user.confirm_nonce = uuid.uuid4().hex
user.confirm_nonce_issued_at = datetime.now(tz=utc)
try:
# URL for user confirmation.
confirm_url = url_for("confirmUser", nonce=user.confirm_nonce,
_external=True)
# Create and send confirmation email.
subject = "Please confirm your account."
html = "Click <a href='{}'>here</a> to confirm.".format(
confirm_url)
msg = Message(sender=app.config["MAIL_USERNAME"],
subject=subject, recipients=[user.email], html=html)
mail.send(msg)
flash("Confirmation email sent.", "info")
except Exception as e:
flash("Failed to send confirmation email.", "danger")
try:
db.session.add(user)
db.session.commit()
flash("Registration succesful. You may now sign-in.", "success")
return redirect(request.args.get("next") or url_for("login"))
except Exception as e:
flash("User creation failed.", "danger")
return redirect(url_for("login"))
return render_template("register.html", form=form)
@app.route("/confirm/<nonce>")
def confirmUser(nonce):
"""
Confirms user account.
"""
user = User.query.filter_by(confirm_nonce=nonce).first()
if user is None:
return abort(404)
else:
now = datetime.now(tz=utc)
if (now - user.confirm_nonce_issued_at).days >= 1:
flash("Confirmation link has expired. Click <a href='" +
url_for('reconfirm') + "'>here</a> to request another.",
"warning")
else:
if user.confirmed_at is None:
# Log out user.
logout_user()
# Remove session keys set by Principal.
for key in ("identity.name", "identity.auth_type"):
session.pop(key, None)
# Signal Principal that identity changed.
identity_changed.send(current_app._get_current_object(),
identity=AnonymousIdentity())
user.confirmed_at = now
user.roles.append(verifiedRole())
flash("Account confirmation successful.", "success")
else:
flash("Account already confirmed.", "warning")
user.confirm_nonce = None
user.confirm_nonce_issued_at = None
try:
db.session.commit()
except Exception as e:
flash("User confirmation failed", 'danger')
return redirect(url_for("login"))
@app.route("/reconfirm", methods=["GET", "POST"])
@login_required
@active_permission.require(http_exception=403)
def reconfirm():
"""
Allows registered users to request a new confirmation link.
"""
form = ServiceRequestForm()
if form.validate_on_submit():
user = user.query.filter_by(email=form.email.data).first()
if user and not user.confirmed_at:
# Generate cryptographic nonce with datetime.
user.confirm_nonce = uuid.uuid4().hex
user.confirm_nonce_issued_at = datetime.now(tz=utc)
try:
db.session.commit()
# URL for user confirmation.
confirm_url = url_for("confirmUser", nonce=user.confirm_nonce,
_external=True)
# Create and send confirmation email.
subject = "Please confirm your account."
html = "Click <a href='{}'>here</a> to confirm.".format(
confirm_url)
msg = Message(sender=app.config["MAIL_USERNAME"],
subject=subject, recipients=[user.email], html=html)
mail.send(msg)
flash("Confirmation email sent.", "info")
return redirect(request.args.get("next") or url_for("login"))
except Exception as e:
flash("Confirmation request failed.", "danger")
return redirect(url_for("login"))
else:
flash("Account already confirmed.", "warning")
return redirect(url_for("login"))
return render_template("reconfirm.html", form=form)
@app.route("/verify/<user_name>", methods=["GET", "POST"])
@login_required
@active_permission.require(http_exception=403)
def verify(user_name):
"""
Allows users to request a confirmation link to verify account.
"""
form = ServiceRequestForm()
if current_user.user_name != user_name:
abort(404)
if form.validate_on_submit():
print(form.email.data)
user = User.query.filter_by(user_name=user_name).first()
# Generate cryptographic nonce with datetime.
user.email = form.email.data
user.confirm_nonce = uuid.uuid4().hex
user.confirm_nonce_issued_at = datetime.now(tz=utc)
try:
db.session.commit()
# URL for user confirmation.
confirm_url = url_for("confirmUser", nonce=user.confirm_nonce,
_external=True)
# Create and send confirmation email.
subject = "Please confirm your account."
html = "Click <a href='{}'>here</a> to confirm.".format(
confirm_url)
msg = Message(sender=app.config["MAIL_USERNAME"],
subject=subject, recipients=[user.email], html=html)
mail.send(msg)
flash("Confirmation email sent.", "info")
return redirect(request.args.get("next") or url_for("login"))
except Exception as e:
flash("Confirmation request failed.", "danger")
return redirect(url_for("login"))
return redirect(url_for("login"))
return render_template('verify.html', form=form)
@app.route("/login", methods=["GET", "POST"])
def login():
form = LoginForm()
if form.validate_on_submit():
user = User.query.filter_by(user_name=form.user_name.data).first()
if user is None:
flash("No account for '{}'".format(form.user_name.data), "warning")
return redirect(url_for("login"))
elif 'Active' not in user.roles:
flash("Account has been deactivated. Contact support.", 'warning')
return redirect(url_for('index'))
else:
if bc.check_password_hash(user.password, form.password.data):
login_user(user)
# Signal Principal that identity changed.
identity_changed.send(current_app._get_current_object(),
identity=Identity(user.id))
flash("Login successful.", "success")
return redirect(request.args.get("next") or url_for("index"))
else:
flash("Incorrect password.", "warning")
return redirect(url_for("login"))
return render_template("login.html", form=form)
@app.route("/logout")
@login_required
def logout():
"""
Exit point for logged in users.
"""
# Log out user.
logout_user()
# Remove session keys set by Principal.
for key in ("identity.name", "identity.auth_type"):
session.pop(key, None)
# Signal Principal that identity changed.
identity_changed.send(current_app._get_current_object(),
identity=AnonymousIdentity())
flash("Logout successful.", "success")
return redirect(url_for("index"))
@app.route("/reset", methods=["GET", "POST"])
def requestReset():
"""
Endpoint to allow users to request a password reset.
"""
form = ServiceRequestForm()
if form.validate_on_submit():
user = User.query.filter_by(email=form.email.data).first()
if user:
# Generate cryptographic nonce with datetime.
user.reset_nonce = uuid.uuid4().hex
user.reset_nonce_issued_at = datetime.now(tz=utc)
try:
db.session.commit()
# URL for user confirmation.
confirm_url = url_for("passwordReset", nonce=user.reset_nonce,
_external=True)
# Create and send confirmation email.
subject = "Password reset request."
html = "Click <a href='{}'>here</a> to reset password.".format(
confirm_url)
msg = Message(sender=app.config["MAIL_USERNAME"],
subject=subject, recipients=[user.email], html=html)
mail.send(msg)
flash("Check your email for instructions"
" to reset your password.", "info")
return redirect(request.args.get("next") or url_for("login"))
except Exception as e:
flash("Request failed.", "danger")
return redirect(url_for("login"))
else:
flash("Invalid email.", 'warning')
return render_template("reset-request.html", form=form)
@app.route("/reset/<nonce>", methods=["GET", "POST"])
def passwordReset(nonce):
"""
Reset password form.
"""
user = User.query.filter_by(reset_nonce=nonce).first()
if user is None:
return abort(404)
else:
now = datetime.now(tz=utc)
if (now - user.reset_nonce_issued_at).days >= 1:
user.reset_nonce = None
user.reset_nonce_issued_at = None
db.session.commit()
flash("Password reset link has expired.", "warning")
return redirect(url_for("login"))
else:
form = PasswordResetForm()
if form.validate_on_submit():
user.password = bc.generate_password_hash(
form.password.data, rounds=12)
user.reset_nonce = None
user.reset_nonce_issued_at = None
db.session.commit()
flash("Password reset successful. You can now login.",
"success")
return redirect(url_for("login"))
return render_template("password-reset.html", form=form, nonce=nonce)
@app.route('/users/<user_name>')
def viewProfile(user_name):
"""
Display user information and profile.
"""
user = User.query.filter_by(user_name=user_name).first()
return render_template('view-profile.html', user=user,
verified=verified_permission.can())
@app.route('/create', methods=["GET", "POST"])
@login_required
@active_permission.require(http_exception=403)
def createPost():
"""
Create, save, and post new entries.
"""
if current_user.posts and (datetime.now(tz=utc) -
current_user.posts[-1].posted_at).days <= 1 and \
verified_permission.can() is False:
flash("You can only post once per 24 hours period.", 'warning')
return redirect(url_for('index'))
form = CreatePostForm()
if form.validate_on_submit():
# Feed form data into post object.
post = Post(title=form.title.data, subtitle=form.subtitle.data,
body=form.body.data, posted_at=datetime.now(tz=utc),
user_id=current_user.id)
# Add post to session and flush to update post object.
db.session.add(post)
db.session.flush()
# Check submitted form if any files have been loaded.
if form.pics.data:
# Generate path for post uploads.
pic_dest = os.path.join("{}/{}/{}".format(
app.config["UPLOAD_FOLDER"], current_user.id, post.id))
# Create post directory on file system.
os.mkdir(pic_dest)
os.chmod(pic_dest, mode=0o777)
# Path and size of thumbnails.
thumb_dest = "{}/{}".format(pic_dest, "thumbnails")
thumb_size = (256, 256)
# Create directory for thumbnails.
os.mkdir(thumb_dest)
os.chmod(thumb_dest, mode=0o777)
# Get list of upload files.
pics = request.files.getlist('pics')
if len(pics) > 8:
flash("Posts cannot have more than 8 pictures.", "warning")
for pic in pics:
if allowedFile(pic.filename):
# Get form data.
form_title = request.form[pic.filename]
form_position = request.form[pic.filename + '-pos']
# Create secure filename and save picture.
file_name = secure_filename(pic.filename)
# Loop through gallery and check for file_name conflicts.
# Rename if conflict found.
for pp in post.gallery:
if pp.title == file_name:
file_name = renameFile(file_name)
pic.save("{}/{}".format(pic_dest, file_name))
# Create and save thumbnail.
thumb = Image.open("{}/{}".format(pic_dest, file_name))
thumb.thumbnail(thumb_size)
thumb.save("{}/{}".format(thumb_dest, file_name),
thumb.format)
# Create Picture model object and add to list in post.
picture = Picture(filename=file_name, title=form_title);
picture.position = form_position
post.gallery.append(picture)
if pic.filename == request.form['choice']:
post.cover = picture
# Commit changes to database.
try:
db.session.commit()
flash("Post published successfully.", 'success')
return redirect(url_for('index'))
except Exception as e:
flash("Post creation failed.", 'danger')
return redirect(url_for("createPost"))
return render_template('create-post.html', form=form)
@app.route('/edit')
@login_required
def userPosts():
"""
Lists user posts.
"""
posts = Post.query.filter_by(user_id=current_user.id).order_by(
Post.id).all()
return render_template("user-posts.html", posts=posts)
@app.route('/edit/<post_id>', methods=["GET", "POST"])
@login_required
@active_permission.require(http_exception=403)
def editPost(post_id):
"""
Editing existing posts.
This is a horrible, horrible mess... Jesus, Lord have mercy!
"""
permission = EditBlogPostPermission(post_id)
if permission.can():
# Get post object from database.
post = Post.query.get(post_id)
# Create new form instance.
form = EditPostForm()
if request.method == "GET":
for pic in post.gallery:
form.pic_forms.append_entry()
for p, f in zip(post.gallery, form.pic_forms):
f.title.data = p.title
f.position.data = p.position
form.title.data = post.title
form.subtitle.data = post.subtitle
form.body.data = post.body
elif request.method == "POST" and form.validate_on_submit():
# Check to make sure that post will have 8 or less pictures.
deletes = 0
for fp in form.pic_forms:
if fp.delete.data:
deletes += 1
# Get list of uploaded pics, if any.
uploads = 0
pics = request.files.getlist('pics')
uploads = len(pics)
if uploads == 1:
if not pics[0].filename:
uploads = 0
if len(post.gallery) + uploads - deletes <= 8:
# Paths for pictures and thumbnails.
pic_dest = os.path.join("{}/{}/{}".format(
app.config["UPLOAD_FOLDER"], current_user.id, post.id))
thumb_dest = os.path.join("{}/{}".format(pic_dest,
"thumbnails"))
# Get radio choice value from submitted form.
choice = request.form['choice']
# Loop through form fields and gallery pics.
for fp, pp in zip(form.pic_forms, list(post.gallery)):
# If pic selected for deletion.
if fp.delete.data:
os.remove("{}/{}".format(pic_dest, pp.filename))
os.remove("{}/{}".format(thumb_dest, pp.filename))
post.gallery.remove(pp)
# If deleted pic was post cover, reassign to
# first pic in gallery or none if no more pics.
if pp == post.cover:
if len(post.gallery) == 0:
post.cover = None
else:
post.cover = post.gallery[0]
# Remove from database and reset form field.
db.session.delete(pp)
fp.delete.data = False
# Assign new title if pic renamed.
if fp.title.data != pp.title:
pp.title = fp.title.data
# Assign new position if changed.
if fp.position.data != pp.position:
pp.position = fp.position.data;
# Check form for changes and save.
if post.title != form.title.data:
post.title = form.title.data
if post.subtitle != form.subtitle.data:
post.subtitle = form.subtitle.data
if post.body != form.body.data:
post.body = form.body.data
# Set thumbnail size.
thumb_size = (256, 256)
if pics[0].filename:
for pic in pics:
if allowedFile(pic.filename):
# Get form data.
form_title = request.form[pic.filename]
# Good god, a suffix to get unique input name?
form_position = request.form[pic.filename + '-pos']
# Create secure filename and save picture.
file_name = secure_filename(pic.filename)
# Loop through gallery and check for file_name
# conflicts. Rename if conflict found.
for pp in post.gallery:
if pp.title == file_name:
file_name = renameFile(file_name)
pic.save("{}/{}".format(pic_dest, file_name))
# Create and save thumbnail.
thumb = Image.open("{}/{}".format(pic_dest,
file_name))
thumb.thumbnail(thumb_size)
thumb.save("{}/{}".format(thumb_dest, file_name),
thumb.format)
# Add Picture object to post list.
picture = Picture(filename=file_name,
title=form_title)
picture.position = form_position
post.gallery.append(picture)
# Really hacky way of adding form entry...
form.pic_forms.append_entry()
last_index = len(form.pic_forms) - 1
form.pic_forms[last_index].title.data = \
picture.filename
form.pic_forms[last_index].position.data = \
picture.position
else:
flash("Invalid file extension: {}".format(
pic.filename), "warning")
# Update form title data and set post cover with given choice.
for p, f in zip(post.gallery, form.pic_forms):
if p.filename == request.form['choice']:
post.cover = p
f.title.data = p.title
try:
db.session.commit()
flash("Post has been updated.", "success")
return redirect(url_for('viewPost', post_id=post_id))
except Exception as e:
flash("Error saving post data.", "danger")
else:
flash("Posts cannot have more than 8 pictures.", "warning")
# Zip pics and forms for easy iterating in template.
return render_template('edit-post.html', form=form, post=post,
zipped=zip(form.pic_forms, post.gallery))
else:
flash("You lack editing rights for this post.", "warning")
return redirect(url_for('userPosts'))
@app.route('/view/<post_id>', methods=["GET", "POST"])
def viewPost(post_id):
"""
View an individual post and handle comment posting.
"""
post = Post.query.get(post_id)
form = CommentForm()
if form.validate_on_submit():
# Might need to check form.parent_id for null value.
comment = Comment(body=form.body.data, posted_at=datetime.now(tz=utc),
user_id=current_user.id, post_id=post.id)
# If no parent_id suppplied, then comment.parent_id is null.
if form.parent_id.data == 0:
comment.parent_id = None
else:
comment.parent_id = form.parent_id.data
db.session.add(comment)
try:
db.session.commit()
flash("Comment has been posted.", "success")
except Exception as e:
flash("There was an error posting your comment.", "danger")
return redirect(url_for('viewPost', post_id=post_id))
return render_template('view-post.html', post=post, form=form)
| {"/app/__init__.py": ["/app/model.py", "/app/admin.py"], "/manage.py": ["/app/__init__.py"], "/app/admin.py": ["/app/roles.py"], "/app/forms.py": ["/app/model.py"], "/recreate_tables.py": ["/app/__init__.py", "/app/model.py", "/app/roles.py"], "/app/controller.py": ["/app/__init__.py", "/app/roles.py", "/app/model.py", "/app/forms.py"], "/app/model.py": ["/app/__init__.py"], "/wsgi.py": ["/app/__init__.py"], "/tests.py": ["/app/__init__.py", "/app/model.py", "/app/roles.py"]} |
47,028 | seashaw/image-site | refs/heads/master | /app/model.py | '''
File: model.py
Authors:
2014-11-14 - C.Shaw <shaw.colin@gmail.com>
Description:
Handles database connection and manipulation.
'''
from . import app, db
from flask.ext.sqlalchemy import SQLAlchemy
from sqlalchemy import desc
from sqlalchemy.ext.orderinglist import ordering_list
from flask.ext.login import UserMixin
"""
Relation tables.
"""
# Link tables 'users' and 'roles'.
user_roles = db.Table('user_roles',
db.Column('user_id', db.Integer, db.ForeignKey('users.id')),
db.Column('role_id', db.Integer, db.ForeignKey('roles.id')))
"""
Classes to define database table schema.
"""
class User(db.Model, UserMixin):
"""
User information.
"""
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(255), nullable=True, unique=True, index=True)
password = db.Column(db.String(255))
user_name = db.Column(db.String(80), unique=True, index=True)
confirmed_at = db.Column(db.DateTime(timezone=True), nullable=True)
confirm_nonce = db.Column(db.String(), unique=True, nullable=True)
confirm_nonce_issued_at = db.Column(db.DateTime(timezone=True),
nullable=True)
reset_nonce = db.Column(db.String(), unique=True, nullable=True)
reset_nonce_issued_at = db.Column(db.DateTime(timezone=True),
nullable=True)
roles = db.relationship('Role', secondary=user_roles,
backref=db.backref('users', lazy='dynamic'))
posts = db.relationship('Post', backref='user', order_by="desc(Post.id)")
comments = db.relationship('Comment', backref='user',
order_by="desc(Comment.id)")
def __init__(self, password='', user_name=''):
self.password = password
self.user_name = user_name
def __repr__(self):
return '<id: {} username: {}>'.format(self.id, self.user_name)
class Role(db.Model):
"""
User roles.
"""
__tablename__ = 'roles'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80), unique=True)
description = db.Column(db.String(255))
def __init__(self, name='', description=''):
self.name = name
self.description = description
def __eq__(self, other):
return self.name == other
def __hash__(self):
return hash(self.name)
def __repr__(self):
return '<id: {} name: {}>'.format(self.id, self.name)
class Post(db.Model):
"""
Blog posts.
"""
__tablename__ = 'posts'
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(80))
subtitle = db.Column(db.String(80), nullable=True)
body = db.Column(db.Text, nullable=True)
posted_at = db.Column(db.DateTime(timezone=True))
user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
cover_id = db.Column(db.Integer, db.ForeignKey('pictures.id',
use_alter=True, name='fk_post_cover_id'))
# Image relationships. 'Foreign key' construct to specify a
# singular post cover. 'Primary key' to make explicit one to many
# join condition.
cover = db.relationship('Picture', uselist=False, foreign_keys=cover_id,
post_update=True)
gallery = db.relationship('Picture',
primaryjoin="Post.id==Picture.post_id",
order_by='Picture.position',
collection_class=ordering_list('position', count_from=1))
# 'And' construct used to specify that only top level comments
# without a parent are listed here. Each comment has its own
# list of reply comments.
"""
comments = db.relationship('Comment', order_by="desc(Comment.id)",
primaryjoin='and_(Post.id==Comment.post_id, '
'Comment.parent_id==None)')
"""
# Select all comments related to post, filter out root level commet
# in the template.
comments = db.relationship('Comment', order_by='desc(Comment.id)',
primaryjoin='Post.id==Comment.post_id')
# Post votes and total score.
votes = db.relationship('Vote', backref='post')
def __init__(self, title='', subtitle='', body='', posted_at='',
user_id=0):
self.title = title
self.subtitle = subtitle
self.body = body
self.posted_at = posted_at
self.user_id = user_id
def __repr__(self):
return '<id: {} title: {}>'.format(self.id, self.title)
class Picture(db.Model):
"""
Blog post pictures.
"""
__tablename__ = 'pictures'
id = db.Column(db.Integer, primary_key=True)
filename = db.Column(db.String(80))
title = db.Column(db.String(80))
position = db.Column(db.Integer)
post_id = db.Column(db.Integer, db.ForeignKey('posts.id'))
def __init__(self, filename='', title=''):
self.filename = filename
if title == '':
self.title = filename
else:
self.title = title
def __repr__(self):
return '<id: {} filename: {} position: {}>'.format(
self.id, self.filename, self.position)
class Comment(db.Model):
"""
Post comments.
"""
__tablename__ = 'comments'
id = db.Column(db.Integer, primary_key=True)
body = db.Column(db.Text, nullable=True)
posted_at = db.Column(db.DateTime(timezone=True))
user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
post_id = db.Column(db.Integer, db.ForeignKey('posts.id'))
parent_id = db.Column(db.Integer, db.ForeignKey('comments.id'))
children = db.relationship('Comment', backref=db.backref('parent',
remote_side=[id]), order_by="desc(Comment.id)")
def __init__(self, body='', posted_at = '', user_id=0, post_id=0,
parent_id=None):
self.body = body
self.posted_at = posted_at
self.user_id = user_id
self.post_id = post_id
self.parent_id = parent_id
def __repr__(self):
return '<id: {} parent_id: {} body: {}>'.format(self.id,
self.parent_id, self.body)
class Vote(db.Model):
"""
Post votes come in two variants: for / against.
"""
__tablename__ = 'votes'
id = db.Column(db.Integer, primary_key=True)
post_id = db.Column(db.Integer, db.ForeignKey('posts.id'))
| {"/app/__init__.py": ["/app/model.py", "/app/admin.py"], "/manage.py": ["/app/__init__.py"], "/app/admin.py": ["/app/roles.py"], "/app/forms.py": ["/app/model.py"], "/recreate_tables.py": ["/app/__init__.py", "/app/model.py", "/app/roles.py"], "/app/controller.py": ["/app/__init__.py", "/app/roles.py", "/app/model.py", "/app/forms.py"], "/app/model.py": ["/app/__init__.py"], "/wsgi.py": ["/app/__init__.py"], "/tests.py": ["/app/__init__.py", "/app/model.py", "/app/roles.py"]} |
47,029 | seashaw/image-site | refs/heads/master | /wsgi.py | #!/usr/bin/env python3
'''
File: wsgi.py
Authors:
2014-11-14 - C.Shaw <shaw.colin@gmail.com>
Description:
Application entry point for uWSGI.
'''
from app import app, admin, FileView
app.config['SERVER_NAME'] = 'image-site.colinshaw.org'
app.config['UPLOAD_FOLDER'] = \
'/home/colin/applications/image-site/app/static/uploads'
admin.add_view(FileView(app.config["UPLOAD_FOLDER"], '/static/uploads/',
name="Uploaded Files"))
| {"/app/__init__.py": ["/app/model.py", "/app/admin.py"], "/manage.py": ["/app/__init__.py"], "/app/admin.py": ["/app/roles.py"], "/app/forms.py": ["/app/model.py"], "/recreate_tables.py": ["/app/__init__.py", "/app/model.py", "/app/roles.py"], "/app/controller.py": ["/app/__init__.py", "/app/roles.py", "/app/model.py", "/app/forms.py"], "/app/model.py": ["/app/__init__.py"], "/wsgi.py": ["/app/__init__.py"], "/tests.py": ["/app/__init__.py", "/app/model.py", "/app/roles.py"]} |
47,030 | seashaw/image-site | refs/heads/master | /app/roles.py | '''
File: roles.py
Authors:
2015-03-09 by C. Shaw <shaw.colin@gmail.com>
Description:
Settings and initialization for role based access control using principal.
'''
from collections import namedtuple
from functools import partial
from flask.ext.principal import Principal, identity_loaded, Permission, \
RoleNeed, UserNeed
from flask.ext.login import current_user
from . import app, lm
from .model import Role
# Principal object initialization.
principal = Principal(app)
"""
Methods to retrieve roles from database.
"""
active_role = Role(name="Active", description="Active user.")
verified_role = Role(name="Verified",
description="User with a verified email.")
admin_role = Role(name="Administrator", description="Administrator.")
def adminRole():
"""
Returns administrator role from database.
"""
return Role.query.get(1)
def activeRole():
"""
Returns active role from database.
"""
return Role.query.get(2)
def verifiedRole():
"""
Returns verified role from database.
"""
return Role.query.get(3)
"""
User permission definitions.
"""
admin_permission = Permission(RoleNeed("Administrator"))
active_permission = Permission(RoleNeed("Active"))
verified_permission = Permission(RoleNeed("Verified"))
# Need and permission for editing user posts.
BlogPostNeed = namedtuple('blog_post', ['method', 'value'])
EditBlogPostNeed = partial(BlogPostNeed, 'edit')
class EditBlogPostPermission(Permission):
"""
Permission definition for editing blog posts.
"""
def __init__(self, post_id):
need = EditBlogPostNeed(str(post_id))
super(EditBlogPostPermission, self).__init__(need)
@identity_loaded.connect_via(app)
def onIdentityLoaded(sender, identity):
"""
Connects to the identity-loaded signal to add additional information to
the Identity instance, like user roles.
"""
# Set the identity user object.
identity.user = current_user
# Add UserNeed to the identity.
if hasattr(current_user, 'id'):
identity.provides.add(UserNeed(str(current_user.id)))
# Update identity with list of roles that User provides.
# Refers to relationship 'roles' from User model.
if hasattr(current_user, 'roles'):
for role in current_user.roles:
identity.provides.add(RoleNeed(role.name))
# Update identity with list of posts that user authored.
# Refers to relationship 'posts' from User model.
if hasattr(current_user, 'posts'):
for post in current_user.posts:
identity.provides.add(EditBlogPostNeed(str(post.id)))
| {"/app/__init__.py": ["/app/model.py", "/app/admin.py"], "/manage.py": ["/app/__init__.py"], "/app/admin.py": ["/app/roles.py"], "/app/forms.py": ["/app/model.py"], "/recreate_tables.py": ["/app/__init__.py", "/app/model.py", "/app/roles.py"], "/app/controller.py": ["/app/__init__.py", "/app/roles.py", "/app/model.py", "/app/forms.py"], "/app/model.py": ["/app/__init__.py"], "/wsgi.py": ["/app/__init__.py"], "/tests.py": ["/app/__init__.py", "/app/model.py", "/app/roles.py"]} |
47,031 | seashaw/image-site | refs/heads/master | /local.py | #!/usr/bin/env python3
'''
File: local.py
Authors:
2015-04-15 - C.Shaw <shaw.colin@gmail.com>
Description:
DEVELOPMENT ONLY
'''
from app import app, admin, FileView
app.config['SERVER_NAME'] = 'localhost:8080'
app.config['UPLOAD_FOLDER'] = \
'/home/colin/workspace/image-site/app/static/uploads'
admin.add_view(FileView(app.config["UPLOAD_FOLDER"], 'static/uploads/',
name="Uploaded Files"))
app.config['DEBUG'] = True
| {"/app/__init__.py": ["/app/model.py", "/app/admin.py"], "/manage.py": ["/app/__init__.py"], "/app/admin.py": ["/app/roles.py"], "/app/forms.py": ["/app/model.py"], "/recreate_tables.py": ["/app/__init__.py", "/app/model.py", "/app/roles.py"], "/app/controller.py": ["/app/__init__.py", "/app/roles.py", "/app/model.py", "/app/forms.py"], "/app/model.py": ["/app/__init__.py"], "/wsgi.py": ["/app/__init__.py"], "/tests.py": ["/app/__init__.py", "/app/model.py", "/app/roles.py"]} |
47,032 | seashaw/image-site | refs/heads/master | /tests.py | #!/usr/bin/env python3
'''
File: tests.py
Authors:
2015-03-17 - C.Shaw <shaw.colin@gmail.com>
Description:
Test suite for angryhos.com, makes use of selenium to drive
testing procedures.
'''
import os
import shutil
from datetime import datetime
from pytz import utc
import unittest
from app import db, bc
import app.model
from app.model import User, Role
from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
def recreateDatabase():
"""
Function to recreate database tables, make a user for testing,
and create application roles.
"""
print("Dropping and recreating database tables.")
db.drop_all()
db.create_all()
print("Cleansing user uploads folder.")
shutil.rmtree('app/static/uploads/1/')
os.mkdir('app/static/uploads/1')
os.chmod('app/static/uploads/1', mode=0o777)
print("Creating application roles and first user.")
user = User(password=bc.generate_password_hash('la73ralu5', rounds=12),
user_name='cshaw')
from app.roles import active_role, admin_role, verified_role
db.session.add(admin_role)
db.session.add(active_role)
db.session.add(verified_role)
db.session.flush()
user.roles.append(admin_role)
user.roles.append(active_role)
user.roles.append(verified_role)
db.session.add(user)
db.session.commit()
recreateDatabase()
class TestAngryHos(unittest.TestCase):
"""
Test case for angryhos.com
"""
def setUp(self):
"""
Resets everything and prepares test driver.
"""
# Prepares driver for browser automation.
self.firefox = webdriver.Firefox()
def test_logInOut(self):
"""
Tests for confirming user functionality:
signing in
create post without title
creat post without picture
creat post with picture
creat post with multiple pictures
creat post with too many pictures
add picture to post
"""
ff = self.firefox
# User login.
ff.get("localhost:8080/index")
ff.find_element_by_id('login').click()
input = ff.find_element_by_id('user_name')
input.send_keys("cshaw")
input = ff.find_element_by_id('password')
input.send_keys("la73ralu5")
input.submit()
success_alert = ff.find_element_by_class_name(
'alert-success')
# User logout.
ff.find_element_by_id('logout').click()
success_alert = ff.find_element_by_class_name(
'alert-success')
def test_postActions(self):
"""
docstring for test_postActions
"""
ff = self.firefox
# User login.
ff.get("localhost:8080/index")
ff.find_element_by_id('login').click()
input = ff.find_element_by_id('user_name')
input.send_keys("cshaw")
input = ff.find_element_by_id('password')
input.send_keys("la73ralu5")
input.submit()
success_alert = ff.find_element_by_class_name(
'alert-success')
# Create post without title.
ff.find_element_by_id('create-post').click()
input = ff.find_element_by_id('title')
input.submit()
ff.find_element_by_class_name('alert-warning')
# Create post without picture
input = ff.find_element_by_id('title')
input.send_keys('Title 1')
input = ff.find_element_by_id('subtitle')
input.send_keys('Subtitle 1')
input = ff.find_element_by_id('body')
body = \
"""
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed
do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam, quis nostrud exercitation ullamco
laboris nisi ut aliquip ex ea commodo consequat. Duis aute
irure dolor in reprehenderit in voluptate velit esse cillum
dolore eu fugiat nulla pariatur. Excepteur sint occaecat
cupidatat non proident, sunt in culpa qui officia deserunt
mollit anim id est laborum.
"""
input.send_keys(body)
input.submit()
ff.find_element_by_class_name('alert-success')
# Create post with one picture.
ff.find_element_by_id('create-post').click()
input = ff.find_element_by_id('pics')
input.send_keys(
'/home/colin/Pictures/1240565_406439336124583_1778167961_n.jpg')
input = ff.find_element_by_id('title')
input.send_keys('Title 2')
input = ff.find_element_by_id('subtitle')
input.send_keys('Subtitle 2')
input = ff.find_element_by_id('body')
body = \
"""
Sed ut perspiciatis unde omnis iste natus error sit voluptatem
accusantium doloremque laudantium, totam rem aperiam, eaque
ipsa quae ab illo inventore veritatis et quasi architecto
beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem
quia voluptas sit aspernatur aut odit aut fugit, sed quia
consequuntur magni dolores eos qui ratione voluptatem sequi
nesciunt. Neque porro quisquam est, qui dolorem ipsum quia
dolor sit amet, consectetur, adipisci velit, sed quia non
numquam eius modi tempora incidunt ut labore et dolore magnam
aliquam quaerat voluptatem. Ut enim ad minima veniam, quis
nostrum exercitationem ullam corporis suscipit laboriosam,
nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum
iure reprehenderit qui in ea voluptate velit esse quam nihil
molestiae consequatur, vel illum qui dolorem eum fugiat quo
voluptas nulla pariatur?
"""
input.send_keys(body)
input.submit()
ff.find_element_by_class_name('alert-success')
# Add second picture to post.
ff.get('localhost:8080/edit/2')
input = ff.find_element_by_id('pics')
input.send_keys('/home/colin/Pictures/2014-12-02-123635.jpg')
ff.find_element_by_id('submit').submit()
ff.find_element_by_class_name('alert-success')
# Add third picture to post and change picture ordering.
# Picture is a duplicate to test renaming.
ff.get('localhost:8080/edit/2')
input = ff.find_element_by_id('pics')
input.send_keys('/home/colin/Pictures/2014-12-02-123635.jpg')
ff.find_element_by_class_name('down').click()
ff.find_element_by_id('submit').submit()
ff.find_element_by_class_name('alert-success')
# Add fourth picture to post, rename picture.
ff.get('localhost:8080/edit/2')
input = ff.find_element_by_id('pics')
input.send_keys(
'/home/colin/Pictures/45e2ea709e55687d60bcb6008efb6081.jpg')
title = ff.find_element_by_id('pic_forms-2-title')
title.clear()
title.send_keys("ticket2")
ff.find_element_by_id('submit').submit()
ff.find_element_by_class_name('alert-success')
# Add fifth picture to post, rename pictures, and change
# picture ordering, and change cover choice.
ff.get('localhost:8080/edit/2')
ff.find_element_by_id('pics').send_keys(
'/home/colin/Pictures/'
'811-Get_money_fuck_bitches_smoke_trees.jpg')
titles = ff.find_elements_by_class_name('title')
names = ["ticket 1", "twins", "ticket 2", "dino", "wisdom"]
for title, name in zip(titles, names):
title.clear()
title.send_keys(name)
ups = ff.find_elements_by_class_name('up')
downs = ff.find_elements_by_class_name('down')
ups[3].click()
ups[3].click()
ups[3].click()
downs[1].click()
downs[2].click()
ups[4].click()
ff.find_element_by_name('choice').click()
ff.find_element_by_id('submit').submit()
ff.find_element_by_class_name('alert-success')
# Add three more pictures, delete one, rename some,
# change ordering again, and change cover choice again.
files = ['dafsdfasf.jpeg', 'images.jpeg',
'Ger-ma-bethi-ho-bag-to-side-per-rakh-do.jpg']
names = ['nympho', 'mean girl', 'durrrr']
for file in files:
ff.get('localhost:8080/edit/2')
ff.find_element_by_id('pics').send_keys(
'/home/colin/Pictures/' + file)
ff.find_element_by_id('submit').submit()
ff.find_element_by_class_name('alert-success')
ff.get('localhost:8080/edit/2')
ff.find_element_by_id('pic_forms-4-delete').click()
titles = ff.find_elements_by_class_name('title')
for i in range(3):
titles[len(titles) - 1 - i].clear()
titles[len(titles) - 1 - i].send_keys(names[i])
ups = ff.find_elements_by_class_name('up')
downs = ff.find_elements_by_class_name('down')
ups[4].click()
ups[4].click()
ups[4].click()
downs[3].click()
downs[3].click()
ff.find_element_by_id('pics').send_keys(
'/home/colin/Pictures/resized_ap_gqhunter.jpg')
ff.find_elements_by_name('choice')[4].click()
ff.find_element_by_id('submit').submit()
ff.find_element_by_class_name('alert-success')
# Add one picture.
ff.get('localhost:8080/edit/2')
ff.find_element_by_id('pics').send_keys(
'/home/colin/Pictures/windows.png')
ff.find_element_by_id('submit').submit()
ff.find_element_by_class_name('alert-warning')
# Add comment.
ff.get('localhost:8080/view/2')
ff.find_element_by_id('body').send_keys('This is one fine post. rekt.')
ff.find_element_by_id('submit').submit()
ff.find_element_by_class_name('alert-success')
# Reply to previous comment.
# Changed to click the internal icon and not the link itself.
ff.find_element_by_class_name('fa-reply').click()
ff.find_element_by_id('body').send_keys('10/10 would read again.')
ff.find_element_by_id('submit').submit()
ff.find_element_by_class_name('alert-success')
def tearDown(self):
"""
Close driver connection and clean up.
"""
self.firefox.quit()
if __name__ == '__main__':
unittest.main()
| {"/app/__init__.py": ["/app/model.py", "/app/admin.py"], "/manage.py": ["/app/__init__.py"], "/app/admin.py": ["/app/roles.py"], "/app/forms.py": ["/app/model.py"], "/recreate_tables.py": ["/app/__init__.py", "/app/model.py", "/app/roles.py"], "/app/controller.py": ["/app/__init__.py", "/app/roles.py", "/app/model.py", "/app/forms.py"], "/app/model.py": ["/app/__init__.py"], "/wsgi.py": ["/app/__init__.py"], "/tests.py": ["/app/__init__.py", "/app/model.py", "/app/roles.py"]} |
47,033 | friku/game | refs/heads/master | /test_main.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 23 17:31:40 2018
@author: riku
"""
import pytest
import unittest
from main import main
from setting import follower,field,BattleDeck,makeCard,makeDeck,BattleSystem
class TestMain(unittest.TestCase):
def test_main(self):
main()
pass
if __name__ == "__main__":
unittest.main() | {"/test_main.py": ["/main.py", "/setting.py"], "/makecard.py": ["/Utils.py"], "/setting.py": ["/makecard.py"], "/main.py": ["/setting.py", "/makecard.py"], "/test_setting.py": ["/main.py"]} |
47,034 | friku/game | refs/heads/master | /Utils.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 30 15:20:38 2018
@author: riku
"""
def selectMyPlace(Field,PlayerID,fanfareFlag=0):#自カードを対象にしたくない時はfanfareFlagを1にする
selectFlag = 0
while selectFlag == 0:
SelectFieldID = int(input('カードを選択0~4>> ')) #0~4 placeのカード 5~13手札 14END 15自情報取得 16敵情報取得
if SelectFieldID >= (len(Field[PlayerID].place)-fanfareFlag):#選択したplaceにカードがない
print("error")
selectFlag = 0
else:
return SelectFieldID
def selectEnemyPlace(Field,PlayerID):
selectFlag = 0
while selectFlag == 0:
SelectEnemyFieldID = int(input('カードを選択0~4>> ')) #0~4 placeのカード 5~13手札 14END 15自情報取得 16敵情報取得
if SelectEnemyFieldID >= len(Field[1-PlayerID].place):#選択したplaceにカードがない
print("error")
selectFlag = 0
else:
return SelectEnemyFieldID
def evolveChangeStatus(ThisFollower):
ThisFollower.AP +=ThisFollower.EAP
ThisFollower.HP +=ThisFollower.EHP
ThisFollower.MaxAP +=ThisFollower.EAP
ThisFollower.MaxHP +=ThisFollower.EHP
def addRush(Field,PlayerID,selectCard):
Field[PlayerID].place[selectCard].RushFlag = 1
def ReduceDamage(Field,PlayerID,selectCard,ReduceDamage):#ダメージ軽減
Field[PlayerID].place[selectCard].RushFlag = ReduceDamage | {"/test_main.py": ["/main.py", "/setting.py"], "/makecard.py": ["/Utils.py"], "/setting.py": ["/makecard.py"], "/main.py": ["/setting.py", "/makecard.py"], "/test_setting.py": ["/main.py"]} |
47,035 | friku/game | refs/heads/master | /makecard.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 30 02:45:08 2018
@author: riku
"""
from Utils import selectMyPlace,selectEnemyPlace,evolveChangeStatus,addRush,ReduceDamage
class card:
def __init__(self,name,cost,Enhance=[100],Accelerate=None):
self.name = name
self.cost = cost
self.Enhance = Enhance
self.Accelerate = Accelerate
self.EnhanceNumber = -1 #0以上ならEnhanceを実行する。
def fanfare(self,Field,PlayerID):
print("fanfare pass")
pass
def lastWord(self,Field):
print("fanfare pass")
pass
def EndPhase(self,Field,PlayerID):
pass
class follower(card):
def __init__(self,name,cost,AP,HP,EAP=2,EHP=2,Enhance=[100],Accelerate=None):
card.__init__(self,name,cost,Enhance=Enhance,Accelerate=Accelerate)
self.AP = AP
self.HP = HP
self.EAP = EAP
self.EHP = EHP
self.MaxAP = AP
self.MaxHP = HP
self.SummonFlag = 1
self.AttackFlag = 0
self.EvolveFlag = 0
self.RushFlag = 0
self.StormFlag = 0
self.BaneFlag = 0
self.WardFlag = 0
self.ReduceDamage = 0
self.cardType = "follower"
def changeHP(self,plusHP,Field,PlayerID):
if self.ReduceDamage == -1:
plusHP = 0
elif self.ReduceDamage <= plusHP:
plusHP -= self.ReduceDamage
else:
plusHP = 0
self.HP = self.HP + plusHP
print(str(self.name) +"HP:" + str(self.HP))
return self.HP
def StandbyPhase(self,):
self.SummonFlag = 0
self.AttackFlag = 0
def evolution(self,Field,PlayerID):
evolveChangeStatus(self)
class Amulet(card):
def __init__(self,name,cost,count=None):
card.__init__(self,name,cost)
self.count = count
self.cardType = "Amulet"
def changeCount(self,plusCount):
self.count = self.count + plusCount
print(str(self.name) +"count:" + str(self.count))
return self.count
def StandbyPhase(self,):#オーバーライドして使う
pass
class Spell(card):
def __init__(self,name,cost,Enhance=[100],Accelerate=None):
card.__init__(self,name,cost,Enhance=Enhance,Accelerate=Accelerate)
self.cardType = "Spell"
def PlaySpell(self,Field,PlayerID):#オーバーライドして使う
return True
class BubetuNoSinja(follower):
def __init__(self,name="BubetuNoSinja",cost=1,AP=1,HP=1,):
follower.__init__(self,name,cost,AP,HP)
self.AP = AP
self.HP = HP
self.AttackFlag = 1
self.cardType = "follower"
def fanfare(self,Field,PlayerID):
print("fanfare:"+str(self.name))
if len(Field[PlayerID].place)>=2:
SelectFieldID = selectMyPlace(Field,PlayerID,fanfareFlag=1)
Field[PlayerID].place[SelectFieldID].changeHP(-1,Field,PlayerID)
Field[PlayerID].checkDestroy(SelectFieldID,Field)
Field[PlayerID].draw(1)
class BubetuNoEnsou(Spell):
def __init__(self,name="BubetuNoEnsou",cost=1):
super().__init__(name,cost)
self.cardType = "Spell"
def PlaySpell(self,Field,PlayerID):
if len(Field[PlayerID].place) == 0: return False
if len(Field[1-PlayerID].place) == 0: return False
SelectFieldID = selectMyPlace(Field,PlayerID,fanfareFlag=0)
SelectEnemyFieldID = selectEnemyPlace(Field,PlayerID)
Field[PlayerID].place[SelectFieldID].changeHP(-1,Field,PlayerID)
Field[PlayerID].checkDestroy(SelectFieldID,Field)
Field[1-PlayerID].place[SelectEnemyFieldID].changeHP(-3,Field,PlayerID)
Field[1-PlayerID].checkDestroy(SelectEnemyFieldID,Field)
return True
class Aira(follower):
def __init__(self,name="Aira",cost=2,AP=2,HP=2,):
follower.__init__(self,name,cost,AP,HP)
self.AP = AP
self.HP = HP
self.AttackFlag = 1
self.cardType = "follower"
def evolution(self,Field,PlayerID):
evolveChangeStatus(self)
if Field[PlayerID].MaxPP <= 9:
Field[PlayerID].MaxPP +=1
class WhitefrostWhisper(Spell):
def __init__(self,name="WhitefrostWhisper",cost=2):
super().__init__(name,cost)
self.cardType = "Spell"
def PlaySpell(self,Field,PlayerID):
if len(Field[1-PlayerID].place) == 0: return False
SelectEnemyFieldID = selectEnemyPlace(Field,PlayerID)
if Field[1-PlayerID].place[SelectEnemyFieldID].HP < Field[1-PlayerID].place[SelectEnemyFieldID].MaxHP:
Field[1-PlayerID].GoToCementery(SelectEnemyFieldID,Field)
else:
Field[1-PlayerID].place[SelectEnemyFieldID].changeHP(-1,Field,PlayerID)
Field[1-PlayerID].checkDestroy(SelectEnemyFieldID,Field)
return True
class Filene(follower):
def __init__(self,name="Filene",cost=2,AP=1,HP=3):
follower.__init__(self,name,cost,AP,HP)
self.AP = AP
self.HP = HP
self.EAP = 1
self.EHP = 1
self.AttackFlag = 1
self.cardType = "follower"
def fanfare(self,Field,PlayerID):
print("fanfare:"+str(self.name))
if len(Field[PlayerID].hand) <=8:
Field[PlayerID].hand.append(WhitefrostWhisper())
def evolution(self,Field,PlayerID):
evolveChangeStatus(self)
if len(Field[1-PlayerID].place) == 0: return False
SelectEnemyFieldID = selectEnemyPlace(Field,PlayerID)
Field[1-PlayerID].place[SelectEnemyFieldID].changeHP(-1,Field,PlayerID)
Field[1-PlayerID].checkDestroy(SelectEnemyFieldID,Field)
return True
class ServantOfDisdain(follower):
def __init__(self,name="ServantOfDisdain",cost=2,AP=2,HP=2):
follower.__init__(self,name,cost,AP,HP)
self.AP = AP
self.HP = HP
self.AttackFlag = 1
self.cardType = "follower"
def changeHP(self,plusHP,Field,PlayerID):
if self.ReduceDamage == -1:
plusHP = 0
elif self.ReduceDamage <= plusHP:
plusHP -= self.ReduceDamage
else:
plusHP = 0
self.HP = self.HP + plusHP
print(str(self.name) +"_HP:" + str(self.HP))
print(self.HP,plusHP)
if self.HP >=1 and plusHP <=0:
Field[PlayerID].draw(1)
return self.HP
class DragonOracle(Spell):
def __init__(self,name="DragonOracle",cost=2):
super().__init__(name,cost)
self.cardType = "Spell"
def PlaySpell(self,Field,PlayerID):
if Field[PlayerID].MaxPP >= 7:
Field[PlayerID].draw(1)
if Field[PlayerID].MaxPP <= 9:
Field[PlayerID].MaxPP +=1
return True
class VileVioletDragon(follower):
def __init__(self,name="VileVioletDragon",cost=5,AP=4,HP=4):
follower.__init__(self,name,cost,AP,HP)
self.AP = AP
self.HP = HP
self.AttackFlag = 1
self.cardType = "follower"
def changeHP(self,plusHP,Field,PlayerID):
if self.ReduceDamage == -1:
plusHP = 0
elif self.ReduceDamage <= plusHP:
plusHP -= self.ReduceDamage
else:
plusHP = 0
self.HP = self.HP + plusHP
print(str(self.name) +"_HP:" + str(self.HP))
print(self.HP,plusHP)
if self.HP >=1 and plusHP <=0:
Field[PlayerID].draw(2)
return self.HP
class Megalorca(follower):
def __init__(self,name="Megalorca",cost=2,AP=2,HP=2):
follower.__init__(self,name,cost,AP,HP)
self.AP = AP
self.HP = HP
self.AttackFlag = 1
self.cardType = "follower"
class WatersOfTheOrca(Spell):
def __init__(self,name="WatersOfTheOrca",cost=2,Enhance=[4,6,8,10]):
super().__init__(name,cost,Enhance=Enhance)
self.cardType = "Spell"
def PlaySpell(self,Field,PlayerID):
if self.EnhanceNumber == -1:
Field[PlayerID].place.append(Megalorca())
elif self.EnhanceNumber == 0:
for i in range(2):
Field[PlayerID].place.append(Megalorca())
elif self.EnhanceNumber == 1:
for i in range(3):
Field[PlayerID].place.append(Megalorca())
elif self.EnhanceNumber == 2:
for i in range(4):
Field[PlayerID].place.append(Megalorca())
elif self.EnhanceNumber == 3:
for i in range(5):
Field[PlayerID].place.append(Megalorca())
for i in range(5):
if len(Field[PlayerID].place) >=6:
Field[PlayerID].Extinction.append(Field[PlayerID].place.pop(5))#placeからあふれたカードを消滅
return True
class MasamuneRagingDragon(follower):
def __init__(self,name="MasamuneRagingDragon",cost=2,AP=2,HP=2):
super().__init__(self,name,cost,AP,HP)
self.cardType = "follower"
self.BaneFlag = 1
def fanfare(self,Field,PlayerID):
print("fanfare:"+str(self.name))
if Field[PlayerID].MaxPP < 10:
pass
else:
for i in range(len(Field[PlayerID])):
addRush(Field,PlayerID,i)#突進付与
ReduceDamage(Field,PlayerID,i,-1)#ダメージ軽減
return True
#戦闘準備用
class BattleDeck:
deck = []
def __init__(self,deck):
self.deck = deck
def addCardToDeck(self,card):
self.deck.append(card)
class makeCard:
def makeFollower(self,name,cost,AP,HP):
card = follower(name,cost,AP,HP)
return card
class makeDeck:
def makeDeck(self,cards):
deck = []
for i in range(40):
deck.append(card)
return deck | {"/test_main.py": ["/main.py", "/setting.py"], "/makecard.py": ["/Utils.py"], "/setting.py": ["/makecard.py"], "/main.py": ["/setting.py", "/makecard.py"], "/test_setting.py": ["/main.py"]} |
47,036 | friku/game | refs/heads/master | /calculator.py | # -*- coding: utf-8 -*-
"""
Created on Sun Dec 23 00:44:03 2018
@author: 陸
"""
class Calculator():
def add(self, a, b):
return a + b
def sub(self, a, b):
return a - b
def mul(self, a, b):
return a * b
def div(self, a, b):
return a / b | {"/test_main.py": ["/main.py", "/setting.py"], "/makecard.py": ["/Utils.py"], "/setting.py": ["/makecard.py"], "/main.py": ["/setting.py", "/makecard.py"], "/test_setting.py": ["/main.py"]} |
47,037 | friku/game | refs/heads/master | /setting.py | # -*- coding: utf-8 -*-
"""
Created on Thu Dec 20 23:11:33 2018
@author: 陸
"""
from makecard import follower
class field:
def __init__(self,playerName,BTDeck,PlayerID,EP):
self.HP = 20
self.PP = 0
self.EP = EP
self.MaxPP = 0
self.TurnNum = 0
self.cemetery = []
self.playerName = playerName
self.BTDeck = BTDeck
self.hand = []
self.place = []
self.Extinction = []
self.PlayerID = PlayerID
def checkOutOfDeck(self):
if len(self.BTDeck.deck) == 0:
print("OutOfDeck")
return True
else: False
def GoToCementery(self,FieldID,Field):
if FieldID <= 4:
self.cemetery.append(self.place.pop(FieldID))
self.cemetery[-1].lastWord(Field)
elif FieldID <= 14:
self.cemetery.append(self.hand.pop(FieldID-5))
def checkDestroy(self,FieldID,Field):
if self.place[FieldID].HP <= 0:
self.GoToCementery(FieldID,Field)
def draw(self,drawNum):
for i in range(drawNum):
if self.checkOutOfDeck():return True
self.hand.append(self.BTDeck.deck.pop(0))
if len(self.hand) >=10:
self.cemetery.append(self.hand.pop(9))
def PlayCard(self,handID,Field,PlayerID):
self.place.append(self.hand.pop(handID))
if len(self.place) >=6:
self.Extinction.append(self.place.pop(5))
else:
self.place[-1].fanfare(Field,PlayerID)
def PlaySpell(self,Spell,Field,PlayerID,handID):
UseSpellFlag = Spell.PlaySpell(Field,PlayerID)
if UseSpellFlag == True:
self.cemetery.append(self.hand.pop(handID))
def Marigan(self,):
self.draw(3)
def changeHP(self,plusHP):
self.HP = self.HP + plusHP
print(str(self.playerName) +"HP:" + str(self.HP))
def info(self,):
print("playerName:%s,HP:%d,MaxPP:%d,PP:%d,EP:%d,TurnNum:%d,len(hand):%d,len(place):%d,len(cemetery):%d" %(self.playerName,self.HP,self.MaxPP,self.PP,self.EP,self.TurnNum,len(self.hand),len(self.place),len(self.cemetery)))
print("Hand info")
for card in self.hand:
if card.cardType == "follower":
print(card.name,card.AP,card.HP)
elif card.cardType == "Amulet":
print(card.name,card.count)
elif card.cardType == "Spell":
print(card.name)
print("Place info")
for card in self.place:
if card.cardType == "follower":
print(card.name,card.AP,card.HP,card.AttackFlag)
elif card.cardType == "Amulet":
print(card.name,card.count)
class BattleSystem:
def BattlePreparation(self,BTDeck0,BTDeck1):
self.Field = []
self.Field.append(field("player0",BTDeck0,0,2))
self.Field.append(field("player1",BTDeck1,1,3))
self.Field[0].Marigan()
self.Field[1].Marigan()
def fight(self,Follower0,Follower1,SelectFieldID,SelectEnemyFieldID,PlayerID):#交戦処理
Follower0.changeHP(-Follower1.AP,self.Field,PlayerID)
Follower1.changeHP(-Follower0.AP,self.Field,PlayerID)
Follower0.AttackFlag=1 #AttackFlagを攻撃済みに変更
if self.Field[PlayerID].place[SelectFieldID].HP <= 0 or self.Field[1-PlayerID].place[SelectFieldID].BaneFlag == 1: #破壊判定処理
self.Field[PlayerID].GoToCementery(SelectFieldID,self.Field)
if self.Field[1-PlayerID].place[SelectEnemyFieldID].HP <= 0 or self.Field[PlayerID].place[SelectFieldID].BaneFlag == 1: #破壊判定処理
self.Field[1-PlayerID].GoToCementery(SelectEnemyFieldID,self.Field)
def AttackFace(self,Follower0,EnemyPlayer,PlayerID):
EnemyPlayer.changeHP(-Follower0.AP)
Follower0.AttackFlag=1 #AttackFlagを攻撃済みに変更
def CostCheck(self,Field,PlayerID,SelectHandID):
if Field[PlayerID].hand[SelectHandID].Enhance[0] <= Field[PlayerID].PP:#Enhanceが可能かPPを確認する。可能ならPPを減らす。実行するEnhanceの番号を代入する。
EnhanceCost = max([i for i in Field[PlayerID].hand[SelectHandID].Enhance if i <= Field[PlayerID].PP])
Field[PlayerID].PP -= EnhanceCost
Field[PlayerID].hand[SelectHandID].EnhanceNumber = Field[PlayerID].hand[SelectHandID].Enhance.index(EnhanceCost)
return True
elif Field[PlayerID].hand[SelectHandID].cost <= Field[PlayerID].PP:
Field[PlayerID].PP -= Field[PlayerID].hand[SelectHandID].cost
return True
else:
print("コストが足りません error")
return False
def EnhanceCheck(self,Field,PlayerID,SelectHandID):
if Field[PlayerID].hand[SelectHandID].Enhance[0] >= Field[PlayerID].PP:return False
[i for i in Field[PlayerID].hand[SelectHandID].Enhance if i <= Field[PlayerID].PP]
def setPP(self,Field):
Field.PP = Field.MaxPP
def drawPhase(self,PlayerID):
OutOfDeckFlag = self.Field[PlayerID].draw(1)
return OutOfDeckFlag
def StanbyFaze(self,PlayerID):
for i in range(len(self.Field[PlayerID].place)):
self.Field[PlayerID].place[i].StandbyPhase()
def checkError(self,PlayerID):
assert len(self.Field[PlayerID].hand)<=9
assert len(self.Field[1-PlayerID].hand)<=9
assert len(self.Field[PlayerID].place)<=5
assert len(self.Field[1-PlayerID].place)<=5
assert self.Field[PlayerID].MaxPP <= 10
assert self.Field[1-PlayerID].MaxPP <= 10
def turn(self,PlayerID):
ENDFlag = 0
EvolveFlag = 0
self.Field[PlayerID].TurnNum += 1
self.StanbyFaze(PlayerID)#フォロワーの攻撃を可能にする
if self.Field[PlayerID].MaxPP<=9: self.Field[PlayerID].MaxPP += 1
self.setPP(self.Field[PlayerID])
OutOfDeckFlag = self.drawPhase(PlayerID)
if OutOfDeckFlag == True: return
while ENDFlag == 0:
print(str(self.Field[PlayerID].playerName) + "turn")
SelectFieldID = int(input('カードを選択0~16>> ')) #0~4 placeのカード 5~13手札 14END 15自情報取得 16敵情報取得
print(str(SelectFieldID))
if SelectFieldID <= 4:#自分のPlace選択
if SelectFieldID >= len(self.Field[PlayerID].place):print(str(SelectFieldID)+"Out of Place error")#自分のPlaceにカードがなかったらエラー
else:
print(self.Field[PlayerID].place[SelectFieldID].name)
SelectCard = self.Field[PlayerID].place[SelectFieldID]
SelectEnemyFieldID = int(input('相手のカードか顔を選択0~6>> ')) #0~6 相手placeのカード 0~4手札 5顔 6進化
print(str(SelectEnemyFieldID))
if SelectEnemyFieldID == 6 and self.Field[PlayerID].place[SelectFieldID].cardType =="follower" and EvolveFlag == 0 and self.Field[PlayerID].place[SelectFieldID].EvolveFlag == 0 and self.Field[PlayerID].EP >=1 and ((self.Field[PlayerID].TurnNum>=5 and PlayerID==0)or(self.Field[PlayerID].TurnNum>=4 and PlayerID==1)):
self.Field[PlayerID].place[SelectFieldID].evolution(self.Field,PlayerID)
self.Field[PlayerID].EP -=1
EvolveFlag = 1
self.Field[PlayerID].place[SelectFieldID].EvolveFlag = 1
elif SelectEnemyFieldID <=5 and self.Field[PlayerID].place[SelectFieldID].SummonFlag == 1 and (self.Field[PlayerID].place[SelectFieldID].RushFlag == 0 or self.Field[PlayerID].place[SelectFieldID].StormFlag == 0):
print(str(self.Field[PlayerID].place[SelectFieldID]) + "は攻撃できません.召喚酔い error")#召喚酔い
elif SelectEnemyFieldID <=5 and self.Field[PlayerID].place[SelectFieldID].AttackFlag == 1:
print(str(self.Field[PlayerID].place[SelectFieldID]) + "は攻撃できません.攻撃済み error")#攻撃済みだったらエラー
elif SelectEnemyFieldID <=4:#相手のPlace選択
if SelectEnemyFieldID >= len(self.Field[1-PlayerID].place):print("Out of Place error")#相手のPlaceにカードがなかったらエラー
else:
Enemy = self.Field[1-PlayerID].place[SelectEnemyFieldID]
print("Enemy")
print(Enemy.name)
self.fight(SelectCard,Enemy,SelectFieldID,SelectEnemyFieldID,PlayerID)#交戦
elif SelectEnemyFieldID == 5 and self.Field[PlayerID].place[SelectFieldID].SummonFlag == 1 and self.Field[PlayerID].place[SelectFieldID].RushFlag == 1:
print(str(self.Field[PlayerID].place[SelectFieldID]) + "は顔を攻撃できません.突進持ち召喚酔い error")
elif SelectEnemyFieldID == 5:#相手の顔選択
EnemyPlayer = self.Field[1-PlayerID]
self.AttackFace(SelectCard,EnemyPlayer,PlayerID)
else: print("0~6の適切な値を入力してください") #入力値がエラー
elif SelectFieldID <=13:#自分の手札選択
SelectHandID = SelectFieldID - 5
if SelectHandID >= len(self.Field[PlayerID].hand):print("Out of Hand error")#自分のHandにカードがなかったらエラー
elif self.CostCheck(self.Field,PlayerID,SelectHandID) == False:print("PPがたりません error")
elif self.Field[PlayerID].hand[SelectHandID].cardType == "Spell": #スペルを選択した時
print(self.Field[PlayerID].hand[SelectHandID].name)
self.Field[PlayerID].PlaySpell(self.Field[PlayerID].hand[SelectHandID],self.Field,PlayerID,SelectHandID)
elif len(self.Field[PlayerID].place) >= 5:print("Place が埋まっています error")
else:
print(self.Field[PlayerID].hand[SelectHandID].name)
self.Field[PlayerID].PlayCard(SelectHandID,self.Field,PlayerID)
elif SelectFieldID <= 14:#END
print(str(self.Field[PlayerID].playerName) + "END")
ENDFlag = 1
elif SelectFieldID == 15:#自分の情報
self.Field[PlayerID].info()
elif SelectFieldID == 16:#相手の情報
self.Field[1-PlayerID].info()
else:
print("Unexpected Number.You should select from 0 to 16. error")
self.checkError(PlayerID)
print("PlayerHP")
print(self.Field[PlayerID].HP,self.Field[1-PlayerID].HP)
if self.Field[PlayerID].HP <= 0 or self.Field[1-PlayerID].HP<=0:
return
self.turn(1-PlayerID)
| {"/test_main.py": ["/main.py", "/setting.py"], "/makecard.py": ["/Utils.py"], "/setting.py": ["/makecard.py"], "/main.py": ["/setting.py", "/makecard.py"], "/test_setting.py": ["/main.py"]} |
47,038 | friku/game | refs/heads/master | /main.py | # -*- coding: utf-8 -*-
"""
Created on Thu Dec 20 23:55:18 2018
@author: 陸
"""
from setting import field,BattleSystem
from makecard import card,follower,Amulet,Spell,BubetuNoSinja,makeCard,makeDeck,BattleDeck,BubetuNoEnsou,Aira,Filene,ServantOfDisdain,DragonOracle,VileVioletDragon,WatersOfTheOrca
def main():
cardMaker = makeCard()
Faiters = []
for i in range(8):
Faiters.append(WatersOfTheOrca())
Faiters.append(DragonOracle())
Faiters.append(cardMaker.makeFollower(name="Faiter"+str(i),cost=2,AP=2,HP=2))
Faiters.append(Filene())
Faiters.append(BubetuNoSinja())
ghosts = []
for i in range(10):
ghosts.append(BubetuNoEnsou())
ghosts.append(ServantOfDisdain())
ghosts.append(Aira())
ghosts.append(VileVioletDragon())
# ghosts.append(cardMaker.makeFollower(name="ghost"+str(i),cost=1,AP=1,HP=1))
BTDeck = BattleDeck(Faiters)
BTGDeck = BattleDeck(ghosts)
print(BTDeck.deck[0].name)
print("Got Deck")
print(BTGDeck.deck[0].name)
print("Got GDeck")
BTSystem = BattleSystem()
BTSystem.BattlePreparation(BTDeck,BTGDeck)
print(BTSystem.Field[0].playerName)
BTSystem.turn(0)
print("main result")
return True
if __name__ == '__main__':
main()
| {"/test_main.py": ["/main.py", "/setting.py"], "/makecard.py": ["/Utils.py"], "/setting.py": ["/makecard.py"], "/main.py": ["/setting.py", "/makecard.py"], "/test_setting.py": ["/main.py"]} |
47,039 | friku/game | refs/heads/master | /test_setting.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 24 00:00:06 2018
@author: riku
"""
import unittest
from main import main
from io import StringIO
import contextlib
from parameterized import parameterized, param
import numpy as np
class redirect_stdin(contextlib._RedirectStream):
_stream = "stdin"
inputDatas = []
class Test(unittest.TestCase):
def makeInputDataHP(self,commnet):
data = "14\n14\n14\n14\n"
for i in range(200):
data += "6\n15\n16\n14\n6\n15\n16\n14\n0\n5\n14\n6\n15\n16\n0\n5\n1\n5\n14\n"
return data
def makeInputDataDeck(self,commnet):
data = "14\n14\n14\n14\n"
for i in range(200):
data += "14\n15\n16\n14\n15\n16\n14\n15\n16\n14\n15\n16\n"
return data
def makeInputDataRandom(self,commnet):
data = ""
for i in range(20000):
command = np.random.randint(0,17)
data += str(command) + "\n"
return data
def setFile(self,data):
buf = StringIO()
buf.write(data)
buf.seek(0)
return buf
def setUp(self):
global inputDatas
inputDatas.append(self.makeInputDataHP(""))
inputDatas.append(self.makeInputDataDeck(""))
for i in range(10):
inputDatas.append(self.makeInputDataRandom(""))
# print(inputDatas)
print("setup")
# @parameterized.expand([param(DataID=0),param(DataID=1)])
@parameterized.expand([param(DataID=0),param(DataID=1),param(DataID=2),param(DataID=3),param(DataID=4),param(DataID=5),param(DataID=6),param(DataID=7),param(DataID=8),param(DataID=9)])
def test_turn(self,DataID):
data = inputDatas[DataID]
buf = self.setFile(data)
with redirect_stdin(buf):
result = main()
assert result == True
def teardown_method(self):
BattleSystem.BSinput = input
if __name__ == "__main__":
unittest.main()
| {"/test_main.py": ["/main.py", "/setting.py"], "/makecard.py": ["/Utils.py"], "/setting.py": ["/makecard.py"], "/main.py": ["/setting.py", "/makecard.py"], "/test_setting.py": ["/main.py"]} |
47,052 | alka653/PrediosEjido | refs/heads/master | /PrediosEjido/apps/principal/views.py | from django.contrib.auth.decorators import user_passes_test
from django.http import HttpResponseRedirect, HttpResponse
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from easy_pdf.views import PDFTemplateView
from django.contrib.auth import logout
from django.shortcuts import render
from django.db.models import Sum
from .models import Predio
from .forms import *
import json
@login_required
def home(request):
return render(request, 'home.html', {'title': 'Bienvenido'})
@login_required
def list_predio(request):
predios = Predio.objects.all()
return render(request, 'list-predio.html', {'title': 'Listado de Predios', 'predios': predios})
def view_predio(request, predio_pk):
predio = Predio.objects.get(pk = predio_pk)
return render(request, 'show-predio.html', {'title': 'Detalle del Predio', 'predio': predio})
def predio(request, predio_pk = 0):
try:
predio = Predio.objects.get(pk = predio_pk)
except Predio.DoesNotExist:
predio = predio_pk
if request.method == 'POST':
response = {}
form = PredioForm(request.POST, instance = predio)
if form.is_valid():
if predio != 0:
response['sold'] = True
else:
response['sold'] = False
predio_data = form.save()
response['pk'] = predio_data.pk
response['c_catastral'] = predio_data.c_catastral
response['dir_predio'] = predio_data.dir_predio
response['hectarea'] = predio_data.hectarea
response['met2'] = predio_data.met2
response['avaluo_catastral'] = str(predio_data.avaluo_catastral)
else:
response['response'] = "Ha ocurrido un error"
return HttpResponse(json.dumps(response), content_type = 'application/json')
else:
form = PredioForm(instance = predio)
return render(request, 'form-predio.html', {'title': 'Nuevo Predio', 'predio_val': predio, 'forms': form})
def sold_predio(request, predio_pk):
predio = Predio.objects.get(pk = predio_pk)
if request.method == 'POST':
response = {}
predio.c_recaja = request.POST['c_recaja']
predio.f_recaja = request.POST['f_recaja']
predio.v_recaja = request.POST['v_recaja']
if request.POST['id_propieta'] != "" and request.POST['id_propieta_fin'] == "":
propieta = Propieta(id_propieta = request.POST['id_propieta'], name = request.POST['name'])
propieta.save()
else:
propieta = Propieta.objects.get(pk = request.POST['id_propieta_fin'])
predio.id_propieta_fin = propieta
predio.save(update_fields = ['c_recaja', 'f_recaja', 'v_recaja', 'id_propieta_fin'])
response['response'] = predio.pk
return HttpResponse(json.dumps(response), content_type = 'application/json')
else:
form = PropietarioVentaForm()
return render(request, 'sold-predio.html', {'title': 'Nuevo Propietario de Predio', 'forms': form, 'predio_pk': predio_pk})
def delete_predio(request, predio_pk):
response = {}
predio = Predio.objects.get(pk = predio_pk)
response['response'] = predio.pk
predio.delete()
return HttpResponse(json.dumps(response), content_type = 'application/json')
class PredioAllPDFView(PDFTemplateView):
template_name = "pdf_all_predio.html"
def get_context_data(self, **kwargs):
context = super(PredioAllPDFView, self).get_context_data(**kwargs)
context['option'] = self.kwargs['option']
if context['option'] == "1":
predios = Predio.objects.exclude(c_recaja__isnull = True)
else:
predios = Predio.objects.all()
context['predios'] = predios
context['cont'] = 0
context['total'] = predios.aggregate(avaluo_catastral_sum = Sum('avaluo_catastral'))
context['title'] = 'Listado de Predios y Propietarios'
return context
def upload_data_predio(request):
message = ""
type_m = ""
if request.method == 'POST':
form = UploadForm(request.POST or None, request.FILES or None)
if form.is_valid():
if form.upload():
message = "Importacion Exitosa"
type_m = "success"
else:
message = "Ha Ocurrido un Error"
type_m = "danger"
else:
form = UploadForm()
return render(request, 'importer.html', {'title': 'Importar', 'form': form, 'message': message, 'type_m': type_m})
def propietario(request, propieta_pk):
try:
propieta = Propieta.objects.get(pk = propieta_pk)
propieta_val = propieta.pk
except Propieta.DoesNotExist:
propieta = propieta_pk
propieta_val = propieta
if request.method == 'POST':
response = {}
form = PropietaForm(request.POST, instance = propieta)
if form.is_valid():
if propieta != 0:
response['sold'] = True
else:
response['sold'] = False
propieta_data = form.save()
response['pk'] = propieta_data.pk
response['id_propieta'] = propieta_data.id_propieta
response['name'] = propieta_data.name
else:
response['response'] = "Ha ocurrido un error"
return HttpResponse(json.dumps(response), content_type = 'application/json')
else:
form = PropietaForm(instance = propieta)
return render(request, 'form-propieta.html', {'title': 'Nuevo Propietario', 'propieta_val': propieta_val, 'forms': form})
def delete_propieta(request, propieta_pk):
response = {}
propieta = Propieta.objects.get(pk = propieta_pk)
response['response'] = propieta.pk
propieta.delete()
return HttpResponse(json.dumps(response), content_type = 'application/json')
@login_required
def list_propieta(request):
propietas = Propieta.objects.all()
return render(request, 'list-propieta.html', {'title': 'Listado de Propietarios', 'propietas': propietas})
def logout_user(request):
logout(request)
return HttpResponseRedirect('/')
@user_passes_test(lambda u: u.is_superuser)
def list_user(request):
users = User.objects.all()
return render(request, 'list-user.html', {'title': 'Listado de Usuarios', 'users': users})
def user(request):
if request.method == 'POST':
response = {}
form = UserForm(request.POST)
if form.is_valid():
user_data = User.objects.create_user(**form.cleaned_data)
response['pk'] = user_data.pk
response['username'] = user_data.username
response['first_name'] = user_data.first_name
else:
response['response'] = "Ha ocurrido un error"
return HttpResponse(json.dumps(response), content_type = 'application/json')
else:
form = UserForm()
return render(request, 'form-user.html', {'title': 'Nuevo Propietario', 'forms': form})
| {"/PrediosEjido/apps/principal/views.py": ["/PrediosEjido/apps/principal/models.py", "/PrediosEjido/apps/principal/forms.py"], "/PrediosEjido/apps/principal/admin.py": ["/PrediosEjido/apps/principal/models.py"], "/PrediosEjido/apps/principal/urls.py": ["/PrediosEjido/apps/principal/views.py"], "/PrediosEjido/apps/principal/forms.py": ["/PrediosEjido/apps/principal/models.py"]} |
47,053 | alka653/PrediosEjido | refs/heads/master | /PrediosEjido/apps/principal/migrations/0001_initial.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Predio',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('c_catastral', models.CharField(max_length=15)),
('t_ord', models.CharField(max_length=3)),
('t_tot', models.CharField(max_length=3)),
('propieta', models.CharField(max_length=50)),
('e', models.CharField(max_length=1)),
('d', models.CharField(max_length=1)),
('id_propietario', models.CharField(max_length=15)),
('dir_predio', models.CharField(max_length=30)),
('hectarea', models.IntegerField()),
('met2', models.IntegerField()),
('area_con', models.IntegerField()),
('avaluo_catastral', models.DecimalField(max_digits=9, decimal_places=2)),
('c_recaja', models.IntegerField()),
('f_recaja', models.DateField()),
('v_recaja', models.DecimalField(max_digits=9, decimal_places=2)),
],
),
migrations.CreateModel(
name='Propieta',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('id_propieta', models.CharField(max_length=15)),
('name', models.CharField(max_length=30)),
],
),
migrations.AddField(
model_name='predio',
name='id_propieta_fin',
field=models.ForeignKey(to='principal.Propieta', null=True),
),
]
| {"/PrediosEjido/apps/principal/views.py": ["/PrediosEjido/apps/principal/models.py", "/PrediosEjido/apps/principal/forms.py"], "/PrediosEjido/apps/principal/admin.py": ["/PrediosEjido/apps/principal/models.py"], "/PrediosEjido/apps/principal/urls.py": ["/PrediosEjido/apps/principal/views.py"], "/PrediosEjido/apps/principal/forms.py": ["/PrediosEjido/apps/principal/models.py"]} |
47,054 | alka653/PrediosEjido | refs/heads/master | /PrediosEjido/apps/principal/models.py | from django.db import models
class Propieta(models.Model):
id_propieta = models.CharField(max_length = 15)
name = models.CharField(max_length = 30)
def __unicode__(self):
return self.id_propieta+' '+self.name
class Predio(models.Model):
c_catastral = models.CharField(max_length = 15)
t_ord = models.CharField(max_length = 3)
t_tot = models.CharField(max_length = 3)
propieta = models.CharField(max_length = 50)
e = models.CharField(max_length = 1, blank = True, null = True)
d = models.CharField(max_length = 1, blank = True, null = True)
id_propietario = models.CharField(max_length = 15, default = '0')
dir_predio = models.CharField(max_length = 30)
hectarea = models.IntegerField(default = 0)
met2 = models.IntegerField()
area_con = models.IntegerField(default = 0)
avaluo_catastral = models.DecimalField(max_digits = 11, decimal_places = 2)
c_recaja = models.IntegerField(blank = True, null = True)
f_recaja = models.DateField(auto_now = False, blank = True, null = True)
v_recaja = models. DecimalField(max_digits = 11, decimal_places = 2, blank = True, null = True)
id_propieta_fin = models.ForeignKey(Propieta, blank = True, null = True)
def __unicode__(self):
return str(self.pk) | {"/PrediosEjido/apps/principal/views.py": ["/PrediosEjido/apps/principal/models.py", "/PrediosEjido/apps/principal/forms.py"], "/PrediosEjido/apps/principal/admin.py": ["/PrediosEjido/apps/principal/models.py"], "/PrediosEjido/apps/principal/urls.py": ["/PrediosEjido/apps/principal/views.py"], "/PrediosEjido/apps/principal/forms.py": ["/PrediosEjido/apps/principal/models.py"]} |
47,055 | alka653/PrediosEjido | refs/heads/master | /PrediosEjido/apps/principal/migrations/0002_auto_20151222_1504.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('principal', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='predio',
name='area_con',
field=models.IntegerField(default=0),
),
migrations.AlterField(
model_name='predio',
name='d',
field=models.CharField(max_length=1, blank=True),
),
migrations.AlterField(
model_name='predio',
name='e',
field=models.CharField(max_length=1, blank=True),
),
migrations.AlterField(
model_name='predio',
name='hectarea',
field=models.IntegerField(default=0),
),
migrations.AlterField(
model_name='predio',
name='id_propieta_fin',
field=models.ForeignKey(blank=True, to='principal.Propieta', null=True),
),
migrations.AlterField(
model_name='predio',
name='id_propietario',
field=models.CharField(default=b'0', max_length=15),
),
]
| {"/PrediosEjido/apps/principal/views.py": ["/PrediosEjido/apps/principal/models.py", "/PrediosEjido/apps/principal/forms.py"], "/PrediosEjido/apps/principal/admin.py": ["/PrediosEjido/apps/principal/models.py"], "/PrediosEjido/apps/principal/urls.py": ["/PrediosEjido/apps/principal/views.py"], "/PrediosEjido/apps/principal/forms.py": ["/PrediosEjido/apps/principal/models.py"]} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.