index int64 | repo_name string | branch_name string | path string | content string | import_graph string |
|---|---|---|---|---|---|
52,740 | danielbrzn/SephoraRecommender | refs/heads/master | /app/__init__.py | import os
from flask import Flask
import click
from app.api import api_rest, api_bp
from app.client import client_bp
app = Flask(__name__)
app.register_blueprint(api_bp)
app.register_blueprint(client_bp)
from . import config
app.logger.info('>>> {}'.format(config.flask_config))
| {"/app/api/rest/consumer.py": ["/app/api/rest/test.py", "/app/api/rest/product.py", "/app/api/rest/autoencoder.py"], "/app/api/rest/resources.py": ["/app/api/__init__.py", "/app/api/rest/consumer.py"], "/app/api/rest/product.py": ["/app/api/__init__.py"], "/app/__init__.py": ["/app/api/__init__.py"]} |
52,741 | danielbrzn/SephoraRecommender | refs/heads/master | /app/api/__init__.py | """ API Blueprint Application """
import os
from flask import Flask, Blueprint, session, current_app
from flask_restplus import Api
api_bp = Blueprint('api_bp', __name__,
template_folder='templates',
url_prefix='/api')
api_rest = Api(api_bp)
@api_bp.after_request
def add_header(response):
response.headers['Access-Control-Allow-Headers'] = 'Content-Type,Authorization'
# Required for Webpack dev application to make requests to flask api
# from another host (localhost:8080)
if not current_app.config['PRODUCTION']:
response.headers['Access-Control-Allow-Origin'] = '*'
return response
from app.api.rest import resources
| {"/app/api/rest/consumer.py": ["/app/api/rest/test.py", "/app/api/rest/product.py", "/app/api/rest/autoencoder.py"], "/app/api/rest/resources.py": ["/app/api/__init__.py", "/app/api/rest/consumer.py"], "/app/api/rest/product.py": ["/app/api/__init__.py"], "/app/__init__.py": ["/app/api/__init__.py"]} |
52,750 | surya-pratap-2181/maruti-academy | refs/heads/main | /home/urls.py | from django.urls import path
from home import views
from django.views.generic import TemplateView
urlpatterns = [
path('', views.home, name='home'),
path('contact/', views.contact, name='contact'),
path('facilities/', views.facilities, name='facilities'),
path('academic-details/', views.academic, name='academic'),
path('admission-details/', views.admission, name='admission'),
path('glimpses/', views.glimpses, name='glimpses'),
path('about-school/', views.about, name='about'),
path('principal-message/', views.principal, name='principal'),
path('administrator-message/', views.administrator, name='administrator'),
path('president-message/', views.president, name='president'),
]
| {"/home/admin.py": ["/home/models.py"], "/home/views.py": ["/home/models.py"]} |
52,751 | surya-pratap-2181/maruti-academy | refs/heads/main | /home/admin.py | from django.contrib import admin
from home.models import Content, Glimpses, GlimpsesImage
# Register your models here.
@admin.register(Content)
class ContentAdmin(admin.ModelAdmin):
list_display = ('id', 'title', 'name',
'position', 'category', 'photo')
search_fields = ('title', 'name')
class GlimpsesImageInline(admin.TabularInline):
model = GlimpsesImage
extra = 3
@admin.register(Glimpses)
class GlimpsesAdmin(admin.ModelAdmin):
inlines = [GlimpsesImageInline, ]
list_display = ('id', 'name',)
@admin.register(GlimpsesImage)
class GlimpsesImageAdmin(admin.ModelAdmin):
list_display = ('id', 'glimpses', 'image')
| {"/home/admin.py": ["/home/models.py"], "/home/views.py": ["/home/models.py"]} |
52,752 | surya-pratap-2181/maruti-academy | refs/heads/main | /home/models.py | from django.db import models
# Create your models here.
class Content(models.Model):
title = models.CharField(max_length=100)
description = models.TextField()
category = models.CharField(max_length=100)
name = models.CharField(max_length=100, blank=True)
position = models.CharField(max_length=100, blank=True)
photo = models.ImageField(upload_to='Images', blank=True)
class Glimpses(models.Model):
name = models.TextField()
class GlimpsesImage(models.Model):
glimpses = models.ForeignKey(
Glimpses, related_name='images', on_delete=models.CASCADE)
image = models.ImageField(upload_to='glimpses', blank=True)
| {"/home/admin.py": ["/home/models.py"], "/home/views.py": ["/home/models.py"]} |
52,753 | surya-pratap-2181/maruti-academy | refs/heads/main | /home/views.py | from django.shortcuts import render
from home.models import Content, Glimpses
# Create your views here.
def home(request):
data1, data2 = Content.objects.filter(category='Home')
cards = Content.objects.filter(category='Card')
corousel = Glimpses.objects.get(pk=4)
images = corousel.images.all()
return render(request, 'home/home.html', {'images': images, 'home1': data1, 'home2': data2, 'cards': cards})
def facilities(request):
facilities = Content.objects.filter(category='Facilities')
return render(request, 'home/facilities.html', {'facilities': facilities})
def contact(request):
return render(request, 'home/contact.html')
def academic(request):
academics = Content.objects.filter(category='Academic Details')
return render(request, 'home/academic.html', {'academics': academics})
def admission(request):
message = Content.objects.get(pk=4)
return render(request, 'home/admission.html', {'data': message})
def about(request):
message = Content.objects.get(pk=4)
corousel = Glimpses.objects.get(pk=4)
images = corousel.images.all()
return render(request, 'home/about.html', {'data': message, 'images': images})
def principal(request):
message = Content.objects.get(pk=1)
return render(request, 'home/principal.html', {'data': message})
def administrator(request):
message = Content.objects.get(pk=2)
return render(request, 'home/administrator.html', {'data': message})
def president(request):
message = Content.objects.get(pk=3)
return render(request, 'home/president.html', {'data': message})
def glimpses(request):
# luckydraw images fetch
luckydraw = Glimpses.objects.get(pk=1)
luckydraw_image = luckydraw.images.all()
# Pariksha Images fetch
pariksha = Glimpses.objects.get(pk=2)
pariksha_image = pariksha.images.all()
# yoga day images fetch
yogaday = Glimpses.objects.get(pk=3)
yogaday_image = yogaday.images.all()
return render(request, 'home/glimpses.html', {'luckydraw_image': luckydraw_image, 'pariksha_image': pariksha_image, 'yogaday_image': yogaday_image})
| {"/home/admin.py": ["/home/models.py"], "/home/views.py": ["/home/models.py"]} |
52,754 | surya-pratap-2181/maruti-academy | refs/heads/main | /home/migrations/0002_glimpses_glimpsesimage.py | # Generated by Django 3.2.4 on 2021-08-05 05:27
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('home', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Glimpses',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.TextField()),
],
),
migrations.CreateModel(
name='GlimpsesImage',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('image', models.ImageField(blank=True, upload_to='glimpses')),
('glimpses', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='images', to='home.glimpses')),
],
),
]
| {"/home/admin.py": ["/home/models.py"], "/home/views.py": ["/home/models.py"]} |
52,766 | michaeltinsley/music-gan-jupyter-app | refs/heads/main | /utils/gan_wrapper.py | """
Sonic dreams wrapper helpers.
"""
import uuid
from dataclasses import dataclass
from typing import Optional
from google.colab import files
from lucidsonicdreams import LucidSonicDream
from .music_download import download_youtube_mp3
@dataclass
class LucidDreamConfig:
"""
Lucid Dream configuration class.
"""
url: str
style: str
resolution: int
speed_fpm: int
start_time: int
pulse_react: float
pulse_percussive: bool
pulse_harmonic: bool
motion_react: float
motion_percussive: bool
motion_harmonic: bool
class_pitch_react: float
class_smooth_seconds: int
class_complexity: float
class_shuffle_seconds: int
contrast_strength: float
contrast_percussive: bool
flash_strength: float
flash_percussive: bool
length: Optional[int] = None
class LucidDreamWrapper:
"""
Lucid Sonic dreamer wrapper class
"""
def __init__(self, config: LucidDreamConfig) -> None:
"""
:param config: A LucidDreamConfig object
"""
self.config = config
self.file_id = str(uuid.uuid4())
self.video_name = f"{self.file_id}.mp4"
self.lucid_dream = None
self.audio_track = None
def download_music(self) -> None:
"""
Downloads the given track and saves the filepath.
"""
saved_file = download_youtube_mp3(self.config.url, self.file_id)
self.audio_track = saved_file
def download_weights(self) -> None:
"""
Downloads the model weights.
"""
self.lucid_dream = LucidSonicDream(
song=self.audio_track,
style=self.config.style,
)
def generate(self) -> None:
"""
Generate the output video.
"""
self.lucid_dream.hallucinate(
file_name=self.video_name,
)
def download(self) -> None:
"""
Download the generated video from Colab.
"""
files.download(self.video_name)
| {"/utils/gan_wrapper.py": ["/utils/music_download.py"]} |
52,767 | michaeltinsley/music-gan-jupyter-app | refs/heads/main | /utils/gpu.py | """
GPU info helper methods.
"""
from tensorflow.python.client import device_lib
def instance_gpu() -> str:
"""
Returns the GPU for the Colab instance.
:return: The GPU model
"""
devices = device_lib.list_local_devices()
gpu = [x.physical_device_desc for x in devices if x.device_type == "GPU"][0]
return gpu.split(",")[1].split(":")[1].strip()
| {"/utils/gan_wrapper.py": ["/utils/music_download.py"]} |
52,768 | michaeltinsley/music-gan-jupyter-app | refs/heads/main | /utils/options.py | """
Options for Streamlit widgets.
"""
style_gan_choices = [
"faces (ffhq slim 256x256)",
"lsun cats",
"wildlife",
"my little pony",
"grumpy cat",
"lsun cars",
"beetles",
"more abstract art",
"obama",
"abstract photos",
"horse",
"cakes",
"car (config-e)",
"painting faces",
"butterflies",
"faces (ffhq config-e)",
"microscope images",
"ukiyo-e faces",
"cifar 10",
"car (config-f)",
"wikiart faces",
"wikiart",
"figure drawings",
"cat",
"anime portraits",
"anime faces",
"fireworks",
"celeba hq faces",
"textures",
"fursona",
"faces (ffhq config-f 512x512)",
"trypophobia",
"abstract art",
"floor plans",
"ukiyoe faces",
"cifar 100",
"panda",
"church",
"maps",
"ffhq faces",
"lsun bedrooms",
"pokemon",
"imagenet",
"modern art",
"vases",
"flowers",
"faces (ffhq config-e 256x256)",
"doors",
"faces (ffhq config-f)",
]
| {"/utils/gan_wrapper.py": ["/utils/music_download.py"]} |
52,769 | michaeltinsley/music-gan-jupyter-app | refs/heads/main | /main.py | """
Streamlit app.
"""
import streamlit as st
from utils import gan_wrapper, gpu, options
title = st.sidebar.title(
body="Music StyleGAN App",
)
st.sidebar.markdown(
body="A Colab hosted StyleGAN app for creating music videos",
)
# YouTube download
st.sidebar.subheader(
"Video Selection",
)
video_url = st.sidebar.text_input(
label="Enter YouTube URL",
)
run = st.sidebar.button(
label="Run",
)
st.title(
body="Configuration",
)
# GPU Info
st.subheader(
body="GPU Model",
)
st.text(
body=gpu.instance_gpu(),
)
# Music GAN options
st.subheader(
"Style GAN Configuration",
)
st.subheader(
"Initialization",
)
style_dropdown = st.selectbox(
label="Select pretrained StyleGAN weights",
options=options.style_gan_choices,
index=options.style_gan_choices.index("abstract art"),
)
# Video Parameters
video_parameters_expander = st.beta_expander(
label="Video Parameters",
)
with video_parameters_expander:
resolution = st.number_input(
label="Output resolution. Lower is quicker.",
min_value=240,
max_value=2048,
step=120,
value=480,
)
speed_fpm = st.slider(
label="Speed FPM",
min_value=1,
max_value=120,
step=5,
value=12,
)
start_time = st.number_input(
label="The start seconds of the video",
value=0,
min_value=0,
step=1,
)
length = st.number_input(
label="The length of video",
value=60,
min_value=1,
step=1,
)
entire_video = st.checkbox(
label="Render entire video",
value=False,
)
# Pulse Parameters
pulse_parameters_expander = st.beta_expander(
label="Pulse parameters",
)
with pulse_parameters_expander:
pulse_react = st.slider(
label="The 'strength' of the pulse",
min_value=0.0,
max_value=2.0,
value=0.5,
)
pulse_percussive = st.checkbox(
label="Make the pulse reacts to the audio's percussive elements",
value=True,
)
pulse_harmonic = st.checkbox(
label="Make the pulse react to the audio's harmonic elements",
value=False,
)
# Motion Parameters
motion_parameters_expander = st.beta_expander(
label="Motion parameters",
)
with motion_parameters_expander:
motion_react = st.slider(
label="The 'strength' of the motion",
min_value=0.0,
max_value=2.0,
value=0.5,
)
motion_percussive = st.checkbox(
label="Make the motion reacts to the audio's percussive elements",
value=True,
)
motion_harmonic = st.checkbox(
label="Make the motion react to the audio's harmonic elements",
value=False,
)
# Class Parameters
class_parameters_expander = st.beta_expander(
label="Class Parameters",
)
with class_parameters_expander:
class_pitch_react = st.slider(
label="The 'strength' of the pitch",
min_value=0.0,
max_value=2.0,
value=0.5,
)
class_smooth_seconds = st.number_input(
label="Number of seconds spent smoothly interpolating between each "
"class vector. The higher the value, the less 'sudden' the "
"change of class.",
min_value=1,
value=1,
step=1,
)
class_complexity = st.slider(
label="Controls the 'complexity' of images generated. Lower values "
"tend to generate more simple and mundane images, while higher "
"values tend to generate more intricate and bizzare objects.",
min_value=0.0,
max_value=1.0,
value=1.0,
)
class_shuffle_seconds = st.number_input(
label="Number of seconds spent smoothly interpolating between each "
"class vector. The higher the value, the less 'sudden' the "
"change of class.",
min_value=1,
value=15,
step=1,
)
# Effects Parameters
effects_parameters_expander = st.beta_expander(
label="Effects Parameters",
)
with effects_parameters_expander:
contrast_strength = st.slider(
label="Strength of default contrast effect",
min_value=0.0,
max_value=1.0,
value=0.5,
)
contrast_percussive = st.checkbox(
label="If enabled, contrast reacts to the audio's percussive elements.",
value=True,
)
flash_strength = st.slider(
label="Strength of default flash effect",
min_value=0.0,
max_value=1.0,
value=0.5,
)
flash_percussive = st.checkbox(
label="If enabled, flash reacts to the audio's percussive elements.",
value=True,
)
if __name__ == "__main__":
if run:
config = gan_wrapper.LucidDreamConfig(
url=video_url,
style=style_dropdown,
resolution=resolution,
speed_fpm=speed_fpm,
start_time=start_time,
pulse_react=pulse_react,
pulse_percussive=pulse_percussive,
pulse_harmonic=pulse_harmonic,
motion_react=motion_react,
motion_percussive=motion_percussive,
motion_harmonic=motion_harmonic,
class_pitch_react=class_pitch_react,
class_smooth_seconds=class_smooth_seconds,
class_complexity=class_complexity,
class_shuffle_seconds=class_shuffle_seconds,
contrast_strength=contrast_strength,
contrast_percussive=contrast_percussive,
flash_strength=flash_strength,
flash_percussive=flash_percussive,
length=None if entire_video else length,
)
dream_object = gan_wrapper.LucidDreamWrapper(
config=config,
)
with st.spinner("Downloading Song..."):
dream_object.download_music()
with st.spinner("Downloading model weights..."):
dream_object.download_weights()
with st.spinner("Generating video..."):
dream_object.generate()
# Output
st.sidebar.markdown(body="---")
download = st.sidebar.button(
label="Download video",
)
if download:
with st.spinner("Downloading video..."):
dream_object.download()
| {"/utils/gan_wrapper.py": ["/utils/music_download.py"]} |
52,770 | michaeltinsley/music-gan-jupyter-app | refs/heads/main | /utils/music_download.py | """
Helper functions for donwloading music from YouTube.
"""
import os
from typing import Optional
import moviepy.editor as mp
from pytube import YouTube
def download_youtube_mp3(
url: str,
unique_id: str,
save_path: Optional[str] = "./tmp/",
) -> str:
"""
Downloads a given YouTube video to MP3.
:param url: The URL of the input video
:param unique_id: Unique identifier
:param save_path: Output path
:return: The filepath of the downloaded file.
"""
video = YouTube(url)
video = video.streams.filter(only_audio=True).first()
video.download(output_path=save_path, filename=unique_id)
video_path = f"{save_path}{unique_id}.mp4"
clip = mp.AudioFileClip(video_path)
audio_path = f"{save_path}{unique_id}.mp3"
clip.write_audiofile(f"{save_path}{unique_id}.mp3")
os.remove(video_path)
return audio_path
| {"/utils/gan_wrapper.py": ["/utils/music_download.py"]} |
52,775 | alexsh97/kol1_gr1 | refs/heads/master | /task.py | from matrix import Matrix
if __name__=="__main__":
print("matrix1")
matrix1 = Matrix(
[1,2,3],
[3,3,3],
[5,4,2]
)
print(matrix1)
print("1 + matrix1 = new_matrix1")
new_matrix1 = 1 + matrix1
print(new_matrix1)
print("matrix2")
matrix2 = Matrix(
[6,7,8],
[2,3,1],
[2,8,9]
)
print(matrix2)
print("matrix1 - matrix2")
new_matrix2 = matrix1 - matrix2
print(new_matrix2)
print("matrix1 * matrix2 = matrix3")
matrix3 = matrix1*matrix2
print(matrix3)
| {"/task.py": ["/matrix.py"]} |
52,776 | alexsh97/kol1_gr1 | refs/heads/master | /matrix.py | class Matrix:
def __init__(self,*rows):
for row in rows:
if not isinstance(row, list):
raise TypeError("It is not a row for matrix")
if len(row) != len(rows[0]):
raise TypeError("Size of columns is not the same")
for element in row:
if not isinstance(element, (int, float)):
raise TypeError("Element '"+str(element)+"' is not a number")
self.matrix = []
for row in rows:
self.matrix.append(row)
self.rows = len(self.matrix)
self.columns = len(self.matrix[0])
def myGenerator(self):
for row in self.matrix:
yield row
def __str__(self):
result = "Matrix:" + str(self.rows) + "x" + str(self.columns) + "\n"
for row in self.myGenerator():
result += str(row) + "\n"
return result
def plus(self,matrix2):
if self.rows == matrix2.rows and self.columns == matrix2.columns:
print("add matrix2")
new_matrix = []
for row in range(0,self.rows):
new_matrix.append([])
for column in range(0,self.columns):
new_matrix[row].append(self.matrix[row][column] + matrix2.matrix[row][column])
return Matrix(*new_matrix)
else:
raise TypeError("Sizes of matrixs are not the same")
def sub(self,matrix2):
if self.rows == matrix2.rows and self.columns == matrix2.columns:
print("add matrix2")
new_matrix = []
for row in range(0,self.rows):
new_matrix.append([])
for column in range(0,self.columns):
new_matrix[row].append(self.matrix[row][column] - matrix2.matrix[row][column])
return Matrix(*new_matrix)
else:
raise TypeError("Sizes of matrixs are not the same")
def __add__(self, rightObject):
if isinstance(rightObject, (int,float)):
new_matrix = []
for row in range(0,self.rows):
new_matrix.append([])
for column in range(0,self.columns):
new_matrix[row].append(self.matrix[row][column] + rightObject)
return Matrix(*new_matrix)
elif isinstance(rightObject,Matrix):
return self.plus(rightObject)
else:
raise TypeError("Element '" + str(rightObject) + "' is not a number")
def __radd__(self, leftObject):
if isinstance(leftObject, (int,float)):
new_matrix = []
for row in range(0,self.rows):
new_matrix.append([])
for column in range(0,self.columns):
new_matrix[row].append(self.matrix[row][column] + leftObject)
return Matrix(*new_matrix)
elif isinstance(leftObject,Matrix):
return self.plus(leftObject)
else:
raise TypeError("Element '" + str(leftObject) + "' is not a number")
def __sub__(self, rightObject):
if isinstance(rightObject, (int,float)):
new_matrix = []
for row in range(0,self.rows):
new_matrix.append([])
for column in range(0,self.columns):
new_matrix[row].append(self.matrix[row][column] - rightObject)
return Matrix(*new_matrix)
elif isinstance(rightObject,Matrix):
return self.sub(rightObject)
else:
raise TypeError("Element '" + str(rightObject) + "' is not a number")
def __rsub__(self, leftObject):
if isinstance(leftObject, (int,float)):
new_matrix = []
for row in range(0,self.rows):
new_matrix.append([])
for column in range(0,self.columns):
new_matrix[row].append(self.matrix[row][column] - leftObject)
return Matrix(*new_matrix)
elif isinstance(leftObject,Matrix):
return self.sub(leftObject)
else:
raise TypeError("Element '" + str(leftObject) + "' is not a number")
def mul(self,matrix2):
new_matrix = []
for i in range(0,self.rows):
new_matrix.append([])
for j in range(0,matrix2.columns):
new_element = [self.matrix[i][k] * matrix2.matrix[k][j] for k in range(0,self.columns)]
new_matrix[i].append(sum(new_element))
return Matrix(*new_matrix)
def __mul__(self,rightObject):
if isinstance(rightObject, (int,float)):
new_matrix = []
for row in range(0,self.rows):
new_matrix.append([])
for column in range(0,self.columns):
new_matrix[row].append(self.matrix[row][column] * rightObject)
return Matrix(*new_matrix)
elif isinstance(rightObject,Matrix):
if self.columns == rightObject.rows:
return self.mul(rightObject)
else:
raise TypeError("Number of columns of left matrix equal to the number of rows of right matrix ")
else:
raise TypeError("Element '" + str(rightObject) + "' is not a number")
def __rmul__(self,leftObject):
if isinstance(leftObject, (int,float)):
new_matrix = []
for row in range(0,self.rows):
new_matrix.append([])
for column in range(0,self.columns):
new_matrix[row].append(self.matrix[row][column] * leftObject)
return Matrix(*new_matrix)
elif isinstance(leftObject,Matrix):
if self.columns == leftObject.rows:
return self.mul(leftObject)
else:
raise TypeError("Number of columns of left matrix equal to the number of rows of right matrix ")
else:
raise TypeError("Element '" + str(leftObject) + "' is not a number")
def function():
print("__name__=='__main__'. This should not be printed")
if __name__ == '__main__':
function()
| {"/task.py": ["/matrix.py"]} |
52,781 | logicalbomb/boat_sinker | refs/heads/master | /src/game/migrations/0001_initial.py | # Generated by Django 2.1.7 on 2019-02-22 17:42
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Game',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('sea_map', models.CharField(max_length=200)),
('pub_date', models.DateTimeField(verbose_name='date published')),
('map_size', models.IntegerField(default=0)),
('rows', models.CharField(max_length=45)),
('cols', models.CharField(max_length=45, verbose_name='columns')),
('initial_data', models.CharField(max_length=60)),
],
),
]
| {"/src/game/views.py": ["/src/game/error.py"]} |
52,782 | logicalbomb/boat_sinker | refs/heads/master | /src/game/views.py | from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.urls import reverse
from .error import handle_create_error
from .models import Game
def index(request):
latest_game_list = Game.objects.order_by("-pub_date")[:5]
context = {"latest_game_list": latest_game_list}
return render(request, "game/index.html", context)
def create(request):
return render(request, 'game/create.html')
def add(request):
try:
sea_map = request.POST["sea_map"]
except KeyError:
return handle_create_error(request, "You didn't send a sea_map.")
if not sea_map:
return handle_create_error(request, "You sent an empty sea_map.")
# TODO: validate sea_map and save a proper game
game = Game.objects.create()
game.sea_map = sea_map
game.save()
# Always return an HttpResponseRedirect after successfully dealing
# with POST data. This prevents data from being posted twice if a
# user hits the Back button.
return HttpResponseRedirect(reverse("game:solution", args=(game.id,)))
def solution(request, game_id):
game = get_object_or_404(Game, pk=game_id)
return render(request, "game/solution.html", {"game": game})
| {"/src/game/views.py": ["/src/game/error.py"]} |
52,783 | logicalbomb/boat_sinker | refs/heads/master | /src/game/error.py | from django.shortcuts import render
import sentry_sdk
sentry_sdk.init("https://61842b75251a4ecbb84748556426aa60@sentry.io/1400606")
def handle_create_error(request, error_text):
# Go back to the index and show an error
context = {
"error_message": error_text,
}
return render(request, "game/create.html", context)
| {"/src/game/views.py": ["/src/game/error.py"]} |
52,784 | logicalbomb/boat_sinker | refs/heads/master | /src/game/migrations/0002_game_name.py | # Generated by Django 2.1.7 on 2019-02-22 18:04
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('game', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='game',
name='name',
field=models.CharField(default='Yar', max_length=128),
),
]
| {"/src/game/views.py": ["/src/game/error.py"]} |
52,811 | jokil123/mineways-block-entity-generator | refs/heads/main | /modules/model/io/load.py | from __future__ import annotations
from .. import mesh
from .. import material
from .io_util import IsInstruction
from path_tools import PathTools
# Loads an obj model and returns it
def LoadModel(file: str) -> mesh.ObjModel:
objFile = open(file, "r").read()
objInstructions = objFile.splitlines()
obj = mesh.ObjModel()
currentObject = None
currentGroup = None
currentMaterialSelection = None
mtllibs: list[str] = []
for instruction in objInstructions:
if instruction == "":
continue
instructionParams = instruction.split()[1:]
if IsInstruction("mtllib", instruction):
mtllibs.append(instructionParams[0])
elif IsInstruction("o", instruction):
currentObject = instructionParams[0]
obj.objectLabels.add(instructionParams[0])
elif IsInstruction("g", instruction):
currentGroup = instructionParams[0]
obj.groupLabels.add(instructionParams[0])
elif IsInstruction("usemtl", instruction):
currentMaterialSelection = instructionParams[0]
elif IsInstruction("vt", instruction):
uv = mesh.UvVertex([float(instructionParams[0]),
float(instructionParams[1])])
obj.uvVerts.append(uv)
elif IsInstruction("vn", instruction):
vertexNormal = mesh.VertexNormal([float(instructionParams[0]),
float(instructionParams[1]),
float(instructionParams[2])])
obj.vertexNormals.append(vertexNormal)
elif IsInstruction("v", instruction):
vertex = mesh.Vertex([float(instructionParams[0]),
float(instructionParams[1]),
float(instructionParams[2])])
obj.verts.append(vertex)
elif IsInstruction("f", instruction):
face = mesh.Face(object=currentObject,
group=currentGroup,
materialSelection=currentMaterialSelection)
for parameter in instructionParams:
args = parameter.split("/")
face.triangulation.append(obj.verts[int(args[0]) - 1])
try:
face.uv.append(obj.uvVerts[int(args[1]) - 1])
except:
pass
try:
face.normal.append(obj.vertexNormals[int(args[2]) - 1])
except:
pass
obj.faces.append(face)
for mtllib in mtllibs:
path = PathTools.JoinPath(file, mtllib)
obj.MaterialLibrary = LoadMaterialLibrary(path)
return obj
# Loads a Material Library
def LoadMaterialLibrary(path: str) -> material.MaterialLibrary:
mtllib = material.MaterialLibrary()
mtlFile = open(path, "r").read()
mtlInstructions = mtlFile.splitlines()
currentMaterial = material.Material("I HATE MYSELF") # pls fix this
for instruction in mtlInstructions:
instructionParams = instruction.split()[1:]
if instruction == "":
continue
elif IsInstruction("newmtl", instruction):
currentMaterial = material.Material(instructionParams[0])
mtllib.materials.append(currentMaterial)
elif IsInstruction("illum", instruction):
matChan = material.MaterialSetting("illum")
matChan.value = [int(instructionParams[0])]
currentMaterial.properties.append(matChan)
channels: list = ["Ka", "Kd", "Ks", "Ns", "d", "Tf"]
# This will instantiate material properties/channels twice (fix this)
for channel in channels:
matChan = material.MaterialChannel(channel)
channelExists = False
if IsInstruction(channel, instruction):
matChan.value = list(map(float, instructionParams))
channelExists = True
if IsInstruction("map_" + channel, instruction):
matChan.mapPath = instructionParams[0]
matChan.map = mtllib.textureHandler.LoadTexture(
PathTools.JoinPath(path, matChan.mapPath))
channelExists = True
if channelExists:
currentMaterial.properties.append(matChan)
return mtllib
| {"/modules/model/io/load.py": ["/modules/model/io/io_util.py"], "/modules/schematic_loader/schematic_classes.py/schematic_classes_main.py": ["/modules/schematic_loader/schematic_classes.py/tile_entity_classes.py"], "/modules/model/io/save.py": ["/modules/model/io/io_util.py"]} |
52,812 | jokil123/mineways-block-entity-generator | refs/heads/main | /modules/model/material.py | from __future__ import annotations
from . import texture
class Material():
def __init__(self, name: str) -> None:
self.name = name
self.properties: list[MaterialProperty] = []
# Holds a list of Materials
class MaterialLibrary():
def __init__(self, materials: list[Material] = None) -> None:
self.materials = materials or []
self.textureHandler = texture.TextureHandler()
class MaterialProperty():
def __init__(self, prefix: str) -> None:
self.prefix: str = prefix
def GenerateChannelInstructions(self) -> list[str]:
return [self.prefix]
class MaterialSetting(MaterialProperty):
def __init__(self, prefix: str) -> None:
super().__init__(prefix)
self.value: list[int]
def GenerateChannelInstructions(self) -> list[str]:
return [self.prefix + " " + " ".join(map(str, self.value))]
class MaterialChannel(MaterialProperty):
def __init__(self, prefix: str) -> None:
super().__init__(prefix)
self.value: list[float] = []
self.map: texture.Texture
self.mapPath: str
def GenerateChannelInstructions(self) -> list[str]:
instructions: list[str] = []
if len(self.value) != 0:
instructions.append(
self.prefix + " " +
" ".join(map(str, self.value))
)
try:
instructions.append(
"map_" + self.prefix + " " + self.mapPath
)
except:
pass
return instructions
| {"/modules/model/io/load.py": ["/modules/model/io/io_util.py"], "/modules/schematic_loader/schematic_classes.py/schematic_classes_main.py": ["/modules/schematic_loader/schematic_classes.py/tile_entity_classes.py"], "/modules/model/io/save.py": ["/modules/model/io/io_util.py"]} |
52,813 | jokil123/mineways-block-entity-generator | refs/heads/main | /modules/schematic_loader/block_parser.py | from __future__ import annotations
from dataclasses import dataclass
import numpy
@dataclass
class BlockId():
id: int
subId: int
# Height Length Width
def GetBlocks(blockIdData: list[int], blockSubIdData: list[int], dimensions: tuple[int, int, int]) -> list[list[list[BlockId]]]:
blocks = numpy.ndarray(
shape=(dimensions[0], dimensions[1], dimensions[2]), dtype=BlockId)
for height in range(dimensions[0]):
for length in range(dimensions[1]):
for width in range(dimensions[2]):
blockIndex = GetBlockIndex((height, length, width), dimensions)
block = BlockId(
blockIdData[blockIndex], blockSubIdData[blockIndex])
blocks[height, length, width] = block
return blocks.tolist()
def GetBlockIndex(position: tuple[int, int, int], dimensions: tuple[int, int, int]):
return (position[1] * dimensions[1] + position[2]) * dimensions[2] + position[0]
| {"/modules/model/io/load.py": ["/modules/model/io/io_util.py"], "/modules/schematic_loader/schematic_classes.py/schematic_classes_main.py": ["/modules/schematic_loader/schematic_classes.py/tile_entity_classes.py"], "/modules/model/io/save.py": ["/modules/model/io/io_util.py"]} |
52,814 | jokil123/mineways-block-entity-generator | refs/heads/main | /modules/schematic_loader/schematic_classes.py/nbt_loader/binary_write_test.py | from typing import ByteString
path = "modules/schematic_loader/schematic_classes.py/nbt_loader/"
f = open(path + "test", "wb")
fileBytes: bytearray = bytearray()
num = 9876
numBytes = num.to_bytes(2, "little")
fileBytes.extend(numBytes)
f.write(fileBytes)
f.close()
| {"/modules/model/io/load.py": ["/modules/model/io/io_util.py"], "/modules/schematic_loader/schematic_classes.py/schematic_classes_main.py": ["/modules/schematic_loader/schematic_classes.py/tile_entity_classes.py"], "/modules/model/io/save.py": ["/modules/model/io/io_util.py"]} |
52,815 | jokil123/mineways-block-entity-generator | refs/heads/main | /modules/schematic_loader/schematic_classes.py/nbt_loader/gzip_test.py | import gzip
f = open("tests/schematics/tileEntities.schematic", "rb").read()
fd = gzip.decompress(f)
outFile = open(
"tests/schematics/tileEntities.decompressed", "wb")
outFile.write(fd)
outFile.close()
| {"/modules/model/io/load.py": ["/modules/model/io/io_util.py"], "/modules/schematic_loader/schematic_classes.py/schematic_classes_main.py": ["/modules/schematic_loader/schematic_classes.py/tile_entity_classes.py"], "/modules/model/io/save.py": ["/modules/model/io/io_util.py"]} |
52,816 | jokil123/mineways-block-entity-generator | refs/heads/main | /modules/path_tools.py | from __future__ import annotations
from ast import parse
from enum import Enum, auto
import os
from pathlib import Path
class PathTools:
def __init__(self, path: str) -> None:
self.__path = self.__ParsePath(path)
self.__isFile: bool = self.IsFile()
self.__fileExt: str
def __ParsePath(self, pathStr: str) -> list[str]:
path: list[str] = []
for sPathSegment in pathStr.split("/"):
path.extend(sPathSegment.split("\\"))
"""
filteredPath: list[str] = []
for pathSegment in path:
if len(pathSegment) != 0:
filteredPath.append(pathSegment)
return filteredPath
"""
return path
@staticmethod
def JoinPath(rootPath: str, subPath: str) -> str:
pathSegments = rootPath.split("/")[0:-1]
pathSegments.append(subPath)
newPath = "/".join(pathSegments)
return newPath
def IsFile(self) -> bool:
return os.path.isfile(self.Path())
def IsDir(self) -> bool:
return os.path.isdir(self.Path())
def Exists(self) -> bool:
return os.path.exists(self.Path())
def Create(self) -> str:
if not self.Exists():
Path(self.Dir()).mkdir(parents=True, exist_ok=True)
return self.Path()
def Name(self) -> str:
return self.__path[-1]
def Dir(self) -> str:
return "/".join(self.__path[:-1])
def Path(self) -> str:
return "/".join(self.__path)
| {"/modules/model/io/load.py": ["/modules/model/io/io_util.py"], "/modules/schematic_loader/schematic_classes.py/schematic_classes_main.py": ["/modules/schematic_loader/schematic_classes.py/tile_entity_classes.py"], "/modules/model/io/save.py": ["/modules/model/io/io_util.py"]} |
52,817 | jokil123/mineways-block-entity-generator | refs/heads/main | /modules/schematic_loader/schematic_classes.py/nbt_parser.py | from __future__ import annotations
from nbt import nbt
from .schematic_classes_main import *
def ParseNbtFile(nbtFile: nbt.NBTFile) -> Schematic:
| {"/modules/model/io/load.py": ["/modules/model/io/io_util.py"], "/modules/schematic_loader/schematic_classes.py/schematic_classes_main.py": ["/modules/schematic_loader/schematic_classes.py/tile_entity_classes.py"], "/modules/model/io/save.py": ["/modules/model/io/io_util.py"]} |
52,818 | jokil123/mineways-block-entity-generator | refs/heads/main | /modules/model/mesh.py | from __future__ import annotations
from . import material
# Holds a vertex normal vector
class VertexNormal():
def __init__(self, normal: list[float]) -> None:
self.normal = normal or []
# Holds a vertex (3D Point)
class Vertex():
def __init__(self, position: list[float]) -> None:
self.position = position or []
# Holds a texture vertex (2D Point on a Texture)
class UvVertex():
def __init__(self, uv: list[float]) -> None:
self.uv = uv or []
# Holds a face (poly or n-gon).
class Face():
def __init__(self, triangulation: list[Vertex] = None, uv: list[UvVertex] = None, normal: list[VertexNormal] = None, object: str = None, group: str = None, materialSelection: str = None) -> None:
self.triangulation = triangulation or []
self.uv = uv or []
self.normal = normal or []
self.objectLabel = object
self.groupLabel = group
self.materialSelection = materialSelection
# Holds all data of an OBJ file
class ObjModel():
def __init__(self, verts: list[Vertex] = None, faces: list[Face] = None, uvVerts: list[UvVertex] = None, vertexNormals: list[VertexNormal] = None, materialLibrary: material.MaterialLibrary = None) -> None:
self.verts = verts or []
self.faces = faces or []
self.uvVerts = uvVerts or []
self.vertexNormals = vertexNormals or []
self.MaterialLibrary = materialLibrary or material.MaterialLibrary()
self.objectLabels: set[str] = set()
self.groupLabels: set[str] = set()
| {"/modules/model/io/load.py": ["/modules/model/io/io_util.py"], "/modules/schematic_loader/schematic_classes.py/schematic_classes_main.py": ["/modules/schematic_loader/schematic_classes.py/tile_entity_classes.py"], "/modules/model/io/save.py": ["/modules/model/io/io_util.py"]} |
52,819 | jokil123/mineways-block-entity-generator | refs/heads/main | /modules/random_error.py | import random
class CryAboutIt(Exception):
pass
class ImposterAmongUs(Exception):
pass
class GetFuckedRetard(Exception):
pass
class HaHaJonathan(Exception):
pass
def RandomError() -> Exception:
errorList: list[Exception] = [
CryAboutIt(),
ImposterAmongUs(),
GetFuckedRetard(),
HaHaJonathan()
]
errorIndex = random.randint(0, len(errorList) - 1)
return errorList[errorIndex]
| {"/modules/model/io/load.py": ["/modules/model/io/io_util.py"], "/modules/schematic_loader/schematic_classes.py/schematic_classes_main.py": ["/modules/schematic_loader/schematic_classes.py/tile_entity_classes.py"], "/modules/model/io/save.py": ["/modules/model/io/io_util.py"]} |
52,820 | jokil123/mineways-block-entity-generator | refs/heads/main | /modules/schematic_loader/schematic_classes.py/schematic_classes_main.py | from __future__ import annotations
from dataclasses import dataclass
from enum import Enum
from nbt import nbt
from .tile_entity_classes import *
class MaterialType(Enum):
CLASSIC = "Classic" # <v0.3 (2009-11-10)
ALPHA = "Alpha" # >v0.3
POCKET = "Pocket" # Pocket (probably Bedrock) Edition
class ItemStackVersion(Enum):
NUMERIC = 17 # Numeric IDs
TEXT = 18 # Text ID
class Platform(Enum):
BUKKIT = "bukkit"
@dataclass
class TileTick:
# The ID of the block; used to activate the correct block update procedure.
i: str
# If multiple tile ticks are scheduled for the same tick, tile ticks with lower p are processed first. If they also have the same p, the order is unknown.
p: int
# The number of ticks until processing should occur. May be negative when processing is overdue.
t: int
# position
x: int
y: int
z: int
@dataclass
class Id:
namespace: str
path: str
@dataclass
class Icon:
count: int
id: Id
tag: nbt.NBTFile
@dataclass
class UUID:
uuid: list[int]
@dataclass
class Item:
count: int
slot: int
id: Id
tag: nbt.NBTFile
@dataclass
class Entity:
air: int
customName: str
customNameVisible: bool
fallDistance: float
fire: int
glowing: bool
hasVisualFire: bool
id: Id
invulnerable: bool
motion: tuple[float, float, float]
noGravity: bool
onGround: bool
passengers: Entity
portalCooldown: int
pos: tuple[float, float, float]
rotation: tuple[float, float]
silent: bool
tags: list
ticksFrozen: int
uuid: UUID
@dataclass
class Schematic:
# dimensions
width: int
height: int
length: int
# version
materials: MaterialType
platform: Platform
blocks: bytearray
# usage unknown
addblocks: bytearray
# schematica only (deprecated)
add: bytearray
data: bytearray
entities: list[Entity]
tileEntities: list[BlockEntity]
# schematica only
icon: Icon
# schematica only
schematicaMapping: dict[int, str]
# schematica only
extendedMetadata: nbt.NBTFile
# WorldEdit-only
weOriginX: int
weOriginY: int
weOriginZ: int
weOffsetX: int
weOffsetY: int
weOffsetZ: int
# MCEdit-Unified only
itemStackVersion: ItemStackVersion
# MCEdit-Unified only
blockIds: dict[int, str]
# MCEdit-Unified only
itemIds: dict[int, str]
# MCEdit-Unified only
tileTicks: list[TileTick]
schematicTileTick: TileTick
# MCEdit-Unified only
biomes: bytearray
| {"/modules/model/io/load.py": ["/modules/model/io/io_util.py"], "/modules/schematic_loader/schematic_classes.py/schematic_classes_main.py": ["/modules/schematic_loader/schematic_classes.py/tile_entity_classes.py"], "/modules/model/io/save.py": ["/modules/model/io/io_util.py"]} |
52,821 | jokil123/mineways-block-entity-generator | refs/heads/main | /modules/schematic_loader/schematic_classes.py/schematic_class.py | from __future__ import annotations
class Block:
def __init__(self) -> None:
self.namespace: str = "minecraft"
self.id: int
self.subId: int
class Schematic:
def __init__(self) -> None:
self.blocks: list[Block] = []
| {"/modules/model/io/load.py": ["/modules/model/io/io_util.py"], "/modules/schematic_loader/schematic_classes.py/schematic_classes_main.py": ["/modules/schematic_loader/schematic_classes.py/tile_entity_classes.py"], "/modules/model/io/save.py": ["/modules/model/io/io_util.py"]} |
52,822 | jokil123/mineways-block-entity-generator | refs/heads/main | /modules/schematic_loader/tile_entity_parser.py | from __future__ import annotations
from nbt import nbt, region, world
class TileEntity():
def __init__(self, x, y, z, id):
self.x = x
self.y = y
self.z = z
self.id = id
def generateMesh():
pass
class Bed(TileEntity):
pass
def main():
tileEntityObjects = []
filePath = "schematics/tileEntities.schematic"
nbtFile = nbt.NBTFile(filename=filePath)
for tag in nbtFile.tags:
if tag.name == "TileEntities":
tileEntities = tag.tags
tileEntityTypes = []
for tileEntity in tileEntities:
for tag in tileEntity.tags:
if tag.name == "id":
tileEntityTypes.append(tag.value)
continue
uniqueTileEntityTypes = set(tileEntityTypes)
print(uniqueTileEntityTypes)
if __name__ == "__main__":
main()
| {"/modules/model/io/load.py": ["/modules/model/io/io_util.py"], "/modules/schematic_loader/schematic_classes.py/schematic_classes_main.py": ["/modules/schematic_loader/schematic_classes.py/tile_entity_classes.py"], "/modules/model/io/save.py": ["/modules/model/io/io_util.py"]} |
52,823 | jokil123/mineways-block-entity-generator | refs/heads/main | /modules/schematic_loader/ids_to_json.py | from dataclasses import dataclass
from os import name
f = open("ids", "r").read()
outFile = []
block: dict[]
for i in range(len(f.splitlines())):
if i % 3 == 0:
blocks
| {"/modules/model/io/load.py": ["/modules/model/io/io_util.py"], "/modules/schematic_loader/schematic_classes.py/schematic_classes_main.py": ["/modules/schematic_loader/schematic_classes.py/tile_entity_classes.py"], "/modules/model/io/save.py": ["/modules/model/io/io_util.py"]} |
52,824 | jokil123/mineways-block-entity-generator | refs/heads/main | /modules/schematic_loader/schematic_parser.py | from __future__ import annotations
from dataclasses import dataclass
import dataclasses
from enum import Enum, auto
from nbt import nbt
def ParseSchematic(schematic: nbt.NBTFile) -> NbtFile:
nbtFile = NbtFile()
| {"/modules/model/io/load.py": ["/modules/model/io/io_util.py"], "/modules/schematic_loader/schematic_classes.py/schematic_classes_main.py": ["/modules/schematic_loader/schematic_classes.py/tile_entity_classes.py"], "/modules/model/io/save.py": ["/modules/model/io/io_util.py"]} |
52,825 | jokil123/mineways-block-entity-generator | refs/heads/main | /modules/schematic_loader/schematic_classes.py/nbt_loader/nbt.py | from __future__ import annotations
import struct
class NbtTag:
tagId: int
def __init__(self, name: str, value) -> None:
self.name = name
def AsBinary(self) -> bytearray:
bytes = bytearray()
bytes.append(self.tagId)
bytes.extend(len(self.name).to_bytes(2, "big"))
bytes.extend(self.name.encode())
bytes.extend(self.ValueAsBinary())
return bytes
def ValueAsBinary(self) -> bytearray:
return bytearray()
class Byte(NbtTag):
tagId = 1
def __init__(self, name: str, value: int) -> None:
super().__init__(name, value)
self.value = value
def ValueAsBinary(self) -> bytearray:
binaryValue = bytearray()
binaryValue.extend(self.value.to_bytes(1, "big"))
return binaryValue
class Short(NbtTag):
tagId = 2
def __init__(self, name: str, value: int) -> None:
super().__init__(name, value)
self.value = value
def ValueAsBinary(self) -> bytearray:
binaryValue = bytearray()
binaryValue.extend(self.value.to_bytes(2, "big"))
return binaryValue
class Int(NbtTag):
tagId = 3
def __init__(self, name: str, value: int) -> None:
super().__init__(name, value)
self.value = value
def ValueAsBinary(self) -> bytearray:
binaryValue = bytearray()
binaryValue.extend(self.value.to_bytes(4, "big"))
return binaryValue
class Long(NbtTag):
tagId = 4
def __init__(self, name: str, value: int) -> None:
super().__init__(name, value)
self.value = value
def ValueAsBinary(self) -> bytearray:
binaryValue = bytearray()
binaryValue.extend(self.value.to_bytes(8, "big"))
return binaryValue
class Float(NbtTag):
tagId = 5
def __init__(self, name: str, value: float) -> None:
super().__init__(name, value)
self.value = value
def ValueAsBinary(self) -> bytearray:
binaryValue = bytearray()
binaryValue.extend(self.value.to_bytes(4, "big"))
return binaryValue
| {"/modules/model/io/load.py": ["/modules/model/io/io_util.py"], "/modules/schematic_loader/schematic_classes.py/schematic_classes_main.py": ["/modules/schematic_loader/schematic_classes.py/tile_entity_classes.py"], "/modules/model/io/save.py": ["/modules/model/io/io_util.py"]} |
52,826 | jokil123/mineways-block-entity-generator | refs/heads/main | /app/main.py | from __future__ import annotations
from model.io.load import LoadModel
from model.io.save import SaveModel
def main():
obj = LoadModel("tests/3d/tileEntities/tileEntities.obj")
for texture in obj.MaterialLibrary.textureHandler.textures:
print(texture.name)
SaveModel(obj, "export/yourMum")
if __name__ == "__main__":
main()
| {"/modules/model/io/load.py": ["/modules/model/io/io_util.py"], "/modules/schematic_loader/schematic_classes.py/schematic_classes_main.py": ["/modules/schematic_loader/schematic_classes.py/tile_entity_classes.py"], "/modules/model/io/save.py": ["/modules/model/io/io_util.py"]} |
52,827 | jokil123/mineways-block-entity-generator | refs/heads/main | /modules/schematic_loader/schematic_classes.py/tile_entity_classes.py | from __future__ import annotations
from dataclasses import dataclass
from enum import Enum
from .schematic_classes_main import Id, Entity, Item, UUID
from nbt import nbt
@dataclass
class CustomName:
customName: str
@dataclass
class BlockEntity:
id: Id
keepPacked: bool
x: int
y: int
z: int
@dataclass
class Banner(BlockEntity, CustomName):
patterns: list[BannerPattern]
@dataclass
class BannerPattern:
color: int
pattern: str
@dataclass
class Lock:
lock: str
@dataclass
class LootTable:
lootTable: str
lootTableSeed: int
@dataclass
class Beacon(BlockEntity, CustomName, Lock):
levels: int
primary: int
secondary: int
@dataclass
class Bed(BlockEntity):
pass
@dataclass
class BeeHive(BlockEntity):
bees: list[Bee]
flowerPos: tuple[int, int, int]
@dataclass
class Bee:
entity: list[Entity]
minOccupationTicks: int
ticksInHive: int
@dataclass
class Bell(BlockEntity):
pass
@dataclass
class Comparator(BlockEntity):
outputSignal: int
@dataclass
class CommandBlock(BlockEntity, CustomName):
auto: bool
command: str
conditionMet: bool
lastExecution: int
lastOutput: str
powered: bool
successCount: int
trackOutput: bool
updateLastExecution: bool
@dataclass
class Conduit(BlockEntity):
target: UUID
@dataclass
class DaylightDetector(BlockEntity):
pass
@dataclass
class InventoryBlock(BlockEntity, CustomName, LootTable, Lock):
items: list[Item]
@dataclass
class Barrel(InventoryBlock):
pass
@dataclass
class Chest(InventoryBlock):
pass
@dataclass
class ShulkerBox(InventoryBlock):
pass
@dataclass
class TrappedChest(InventoryBlock):
pass
@dataclass
class BrewingStand(BlockEntity, CustomName, Lock):
brewTime: int
Fuel: int
items: list[Item]
@dataclass
class Campfire(BlockEntity):
cookingTime: list[int]
cookingTotalTimes: list[int]
items: list[Item]
@dataclass
class SoulCampfire(Campfire):
pass
@dataclass
class Dispenser(InventoryBlock):
pass
@dataclass
class Dropper(InventoryBlock):
pass
@dataclass
class Hopper(InventoryBlock):
transferCooldown: int
@dataclass
class EnchantingTable(BlockEntity, CustomName):
pass
@dataclass
class EnderChest(BlockEntity):
pass
@dataclass
class EndGateway(BlockEntity):
age: int
exactTeleport: bool
exitPortal: tuple[int, int, int]
@dataclass
class EndPortal(BlockEntity):
pass
@dataclass
class SmeltingBlock(BlockEntity, CustomName, Lock):
burnTime: int
cookTime: int
cookTimeTotal: int
items: list[Item]
recipesUsed: int
@dataclass
class BlastFurnace(SmeltingBlock):
pass
@dataclass
class Furnace(SmeltingBlock):
pass
@dataclass
class Smoker(SmeltingBlock):
pass
@dataclass
class Jigsaw(BlockEntity):
finalState: str
joint: str
name: str
pool: str
target: str
@dataclass
class Jukebox(BlockEntity):
recordItem: Item
@dataclass
class Lectern(BlockEntity):
book: Item
page: int
@dataclass
class mobSpawner(BlockEntity):
delay: int
maxNearbyEntities: int
maxSpawnDelay: int
minSpawnDelay: int
requiredPlayerRange: int
spawnCount: int
spawnData: nbt.NBTFile
spawnPotentials:
spawnRange: int
@dataclass
class Piston(BlockEntity):
blockStates:
extending: bool
facing: int
progress: float
source: bool
@dataclass
class Sign(BlockEntity):
glowingText: bool
color: str
text1: str
text2: str
text3: str
text4: str
@dataclass
class Skull(BlockEntity):
extraType: str
skullOwner: SkullOwner
@dataclass
class SkullOwner:
id: UUID
name: str
properties: list[Texture]
@dataclass
class Texture:
value: str
signature: str
@dataclass
class StructureBlock:
author: str
ignoreEntities: bool
integrity: float
metadata: str
mirror: MirrorMode
mode: StructureBlockMode
name: str
posX: int
posY: int
posZ: int
powered: bool
rotation: StructureBlockRotation
seed: int
showboundingbox: bool
sizeX: int
sizeY: int
sizeZ: int
class StructureBlockRotation(Enum):
CW0 = "NONE"
CW90 = "CLOCKWISE_90"
CW180 = "CLOCKWISE_180"
CW270 = "COUNTERCLOCKWISE_90"
class StructureBlockMode(Enum):
SAVE = "SAVE"
LOAD = "LOAD"
CORNER = "CORNER"
DATA = "DATA"
class MirrorMode(Enum):
NONE = "NONE"
XAXIS = "LEFT_RIGHT"
ZAXIS = "FRONT_BACK"
| {"/modules/model/io/load.py": ["/modules/model/io/io_util.py"], "/modules/schematic_loader/schematic_classes.py/schematic_classes_main.py": ["/modules/schematic_loader/schematic_classes.py/tile_entity_classes.py"], "/modules/model/io/save.py": ["/modules/model/io/io_util.py"]} |
52,828 | jokil123/mineways-block-entity-generator | refs/heads/main | /modules/model/texture.py | from __future__ import annotations
from PIL import Image
from random_error import RandomError
from path_tools import PathTools
class TextureHandler:
def __init__(self) -> None:
self.textures: list[Texture] = []
def LoadTexture(self, path: str) -> Texture:
textures = list(filter(lambda x: x.path == path, self.textures))
if len(textures) == 0:
newTexture = self.CreateTexture(path)
self.textures.append(newTexture)
return newTexture
elif len(textures) == 1:
return textures[0]
else:
raise RandomError()
def OpenImage(self, path: str) -> Image.Image:
return Image.open(path).copy()
def CreateTexture(self, path) -> Texture:
return Texture(PathTools(path).Name(), PathTools(path).Path(), self.OpenImage(path))
def SaveTextures(self, path) -> None:
for texture in self.textures:
newPath = PathTools.JoinPath(path, texture.name)
texture.texture.save(PathTools(newPath).Create())
texture.path = newPath
class Texture:
def __init__(self, name: str, path: str, texture: Image.Image) -> None:
self.name = name
self.path = path
self.texture = texture
| {"/modules/model/io/load.py": ["/modules/model/io/io_util.py"], "/modules/schematic_loader/schematic_classes.py/schematic_classes_main.py": ["/modules/schematic_loader/schematic_classes.py/tile_entity_classes.py"], "/modules/model/io/save.py": ["/modules/model/io/io_util.py"]} |
52,829 | jokil123/mineways-block-entity-generator | refs/heads/main | /modules/model/io/save.py | from __future__ import annotations
from .. import mesh
from .. import material
from .io_util import SaveFile
from path_tools import PathTools
# Saves a Model
def SaveModel(model: mesh.ObjModel, path: str, mtlPath: str = None) -> None:
instructions: list[str] = []
if not mtlPath:
mtlPath = path.split("/")[-1]
instructions.append("mtllib " + mtlPath + ".mtl")
SaveMaterialLibrary(model.MaterialLibrary,
PathTools.JoinPath(path, mtlPath))
for vertexNormal in model.vertexNormals:
command = "vn " + " ".join(map(str, vertexNormal.normal))
instructions.append(command)
for uvVert in model.uvVerts:
command = "vt " + " ".join(map(str, uvVert.uv))
instructions.append(command)
for vert in model.verts:
command = "v " + " ".join(map(str, vert.position))
instructions.append(command)
faceList = model.faces.copy()
for objectLabel in model.objectLabels:
objectFaceList = list(filter(
lambda i: i.objectLabel == objectLabel, faceList))
faceList = list(set(faceList) - set(objectFaceList))
if len(objectFaceList) != 0:
instructions.append("o " + objectLabel)
for groupLabel in model.groupLabels:
groupFaceList = list(filter(
lambda i: i.groupLabel == groupLabel, objectFaceList))
objectFaceList = list(set(objectFaceList) - set(groupFaceList))
if len(groupFaceList) != 0:
instructions.append("g " + groupLabel)
for materialLabel in map(lambda i: i.name, model.MaterialLibrary.materials):
materialFaceList = list(filter(
lambda i: i.materialSelection == materialLabel, groupFaceList))
groupFaceList = list(set(groupFaceList) -
set(materialFaceList))
if len(materialFaceList) != 0:
instructions.append("usemtl " + materialLabel)
for face in materialFaceList:
instructions.append(
CreateFaceInstruction(face, model))
else:
if len(groupFaceList) != 0:
instructions.append("usemtl None")
for face in groupFaceList:
instructions.append(
CreateFaceInstruction(face, model))
else:
if len(objectFaceList) != 0:
instructions.append("g None")
for face in objectFaceList:
instructions.append(CreateFaceInstruction(face, model))
else:
if len(faceList) != 0:
instructions.append("o None")
for face in faceList:
instructions.append(CreateFaceInstruction(face, model))
SaveFile("\n".join(instructions), path, "obj")
# Saves a Material Library
def SaveMaterialLibrary(mtllib: material.MaterialLibrary, path: str) -> None:
mtllib.textureHandler.SaveTextures(path)
instructions: list[str] = []
for material in mtllib.materials:
instructions.append("newmtl " + material.name)
for property in material.properties:
instructions.extend(property.GenerateChannelInstructions())
SaveFile("\n".join(instructions), path, "mtl")
# Creates OBJ instruction for a face
def CreateFaceInstruction(face: mesh.Face, model: mesh.ObjModel) -> str:
command = "f"
for i in range(len(face.triangulation)):
args: list[str] = []
args.append(str(model.verts.index(face.triangulation[i]) + 1))
if len(face.normal) != 0:
if len(face.uv) != 0:
args.append(str(model.uvVerts.index(face.uv[i]) + 1))
else:
args.append("")
args.append(str(model.vertexNormals.index(face.normal[i]) + 1))
elif len(face.uv) != 0:
args.append(str(model.uvVerts.index(face.uv[i]) + 1))
command += " " + "/".join(args)
return command
| {"/modules/model/io/load.py": ["/modules/model/io/io_util.py"], "/modules/schematic_loader/schematic_classes.py/schematic_classes_main.py": ["/modules/schematic_loader/schematic_classes.py/tile_entity_classes.py"], "/modules/model/io/save.py": ["/modules/model/io/io_util.py"]} |
52,830 | jokil123/mineways-block-entity-generator | refs/heads/main | /modules/model/io/io_util.py | from __future__ import annotations
import re
from pathlib import Path
# Test if an obj instruction is the requested one
def IsInstruction(instructionName: str, instruction: str) -> bool:
return bool(re.search("^(" + instructionName + ") .*$", instruction))
# Saves a raw file
def SaveFile(file: str, path: str, ext: str):
Path("/".join(path.split("/")[:-1])).mkdir(parents=True, exist_ok=True)
f = open(path + "." + ext, "w")
f.write(file)
f.close()
| {"/modules/model/io/load.py": ["/modules/model/io/io_util.py"], "/modules/schematic_loader/schematic_classes.py/schematic_classes_main.py": ["/modules/schematic_loader/schematic_classes.py/tile_entity_classes.py"], "/modules/model/io/save.py": ["/modules/model/io/io_util.py"]} |
52,833 | swetha-1994/jyothsna | refs/heads/master | /FP/inside/urls.py | from django.urls import path,include
from inside import views
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
path('', views.index, name= "index"),
path('profile/', views.profiles, name="profile"),
path('step1/', views.step1, name= "step1"),
path('vp/<int:id>/',views.viewpro, name= "viewprofile"),
path('sv/', views.save, name='save'),
path('edit/<int:id>/', views.edit, name= "editor"),
path('del/<int:id>/', views.delete, name= "del"),
path('register/',views.register,name="register"),
path('logout/',views.logout,name='log'),
path('login/',views.login,name='login'),
path('auth/', include('social_django.urls', namespace='social')),
] + static(settings.MEDIA_URL, document_root= settings.MEDIA_ROOT) | {"/FP/inside/views.py": ["/FP/inside/models.py"], "/FP/inside/admin.py": ["/FP/inside/models.py"]} |
52,834 | swetha-1994/jyothsna | refs/heads/master | /FP/inside/migrations/0005_sai_about.py | # Generated by Django 2.2.7 on 2019-12-19 04:35
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('inside', '0004_sai_state'),
]
operations = [
migrations.AddField(
model_name='sai',
name='about',
field=models.CharField(default=django.utils.timezone.now, max_length=40),
preserve_default=False,
),
]
| {"/FP/inside/views.py": ["/FP/inside/models.py"], "/FP/inside/admin.py": ["/FP/inside/models.py"]} |
52,835 | swetha-1994/jyothsna | refs/heads/master | /FP/inside/models.py | from django.db import models
from django.db.models import CharField
# Create your models here.
class Age(models.Model):
age = models.CharField(max_length=4)
def __str__(self):
return self.age
class Sai(models.Model):
fname = models.CharField(max_length=20)
lname = models.CharField(max_length=20)
gender = models.CharField(max_length=20)
agee = models.ForeignKey(Age, on_delete=models.CASCADE)
city = models.CharField(max_length=20)
state = models.CharField(max_length=15)
mob = models.IntegerField()
mail = models.EmailField(max_length=20)
image = models.FileField(upload_to='img')
about = models.CharField(max_length=40)
def __str__(self):
return self.fname
| {"/FP/inside/views.py": ["/FP/inside/models.py"], "/FP/inside/admin.py": ["/FP/inside/models.py"]} |
52,836 | swetha-1994/jyothsna | refs/heads/master | /FP/inside/views.py | from django.shortcuts import render, redirect
from .models import Sai, Age
from django.contrib.auth import authenticate,login as auth_login,logout as auth_logout
from django.contrib import messages
from django.contrib import auth
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
# Create your views here.
def index(request):
hl = Age.objects.all()
return render( request,"index.html", {'ask':hl})
@login_required
def profiles(request):
pk = Sai.objects.all()
ag = request.POST.get('age')
st = request.POST.get('state')
gen = request.POST.get('gender')
cit = request.POST.get('city')
if gen:
pk=pk.filter(gender=gen)
if ag:
pk=pk.filter(agee=ag)
if st:
pk = pk.filter(state=st)
if cit:
pk = pk.filter(city=cit)
return render(request,"profiles.html", {'lk':pk})
def viewpro(request,id):
sk=Sai.objects.get(id=id)
return render(request,'viewprofile.html',{'sp':sk})
def step1(request):
xx = Age.objects.all()
return render(request, "step1.html",{'sk': xx})
def save(request):
uid = request.POST.get('sai')
fname = request.POST.get('fn')
sname = request.POST.get('sn')
phone = request.POST.get('mobile')
mail = request.POST.get('mail')
gen = request.POST.get('gen')
ag = request.POST.get('a')
kk = Age.objects.get(id= ag)
city = request.POST.get('city')
photo = request.FILES.get('myfiles[]')
sta = request.POST.get('state')
abt = request.POST.get('abou')
if uid == '':
ss = Sai(fname = fname, lname= sname, mob= phone, gender= gen, mail= mail, agee= kk, city=city,
image= photo, state = sta, about = abt)
ss.save()
return render(request, "step1.html")
else:
ke = Sai.objects.filter(id=uid).update(fname = fname, lname= sname, mob= phone, gender= gen, mail= mail,
agee= kk, city=city, image= photo, state = sta, about = abt)
return render(request, "index.html", {'ss': ke})
def edit(request,id):
ex = Sai.objects.get(id=id)
xx = Age.objects.all()
return render(request, "step1.html", {'ss':ex,'sk': xx})
def delete(request,id):
mp = Sai.objects.get(id=id)
mp.delete()
return redirect (step1)
def register(request):
if request.method == 'POST':
finame=request.POST.get('fname')
lastname=request.POST.get('lname')
email=request.POST.get('Email')
password1=request.POST.get('pwd')
password2=request.POST.get('cpwd')
if password1 == password2:
if User.objects.filter(email=email).exists():
messages.error(request,'Email already exists')
return redirect(index)
else:
user=User.objects.create_user(username=email,first_name=finame,last_name=lastname,email=email,password=password1)
Log_User=authenticate(username=email,password=password1)
auth.login(request,user)
messages.success(request,'Form submited successfully...')
return redirect(index)
else:
messages.error(request, 'username or password are not matching')
return redirect(index)
else:
return render(request,'index.html')
def logout(request):
auth_logout(request)
messages.success(request,'logout successfully')
return redirect(index)
def login(request):
if request.method == 'POST':
username=request.POST.get('uname')
raw_password=request.POST.get('password')
user=auth.authenticate(username=username,password=raw_password)
if user is not None:
auth_login(request,User)
messages.success(request,'login sucessfully')
return redirect(index)
else:
messages.error(request,'Invalid credentials...')
return redirect(index)
else:
return redirect(index)
| {"/FP/inside/views.py": ["/FP/inside/models.py"], "/FP/inside/admin.py": ["/FP/inside/models.py"]} |
52,837 | swetha-1994/jyothsna | refs/heads/master | /FP/inside/migrations/0001_initial.py | # Generated by Django 2.2.7 on 2019-12-16 06:37
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Age',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('age', models.CharField(max_length=4)),
],
),
migrations.CreateModel(
name='Sai',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('fname', models.CharField(max_length=20)),
('lname', models.CharField(max_length=20)),
('gender', models.CharField(max_length=20)),
('mob', models.IntegerField()),
('mail', models.EmailField(max_length=20)),
('agee', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='inside.Age')),
],
),
]
| {"/FP/inside/views.py": ["/FP/inside/models.py"], "/FP/inside/admin.py": ["/FP/inside/models.py"]} |
52,838 | swetha-1994/jyothsna | refs/heads/master | /FP/inside/admin.py | from django.contrib import admin
from .models import Sai, Age
# Register your models here.
admin.site.register(Sai)
admin.site.register(Age)
| {"/FP/inside/views.py": ["/FP/inside/models.py"], "/FP/inside/admin.py": ["/FP/inside/models.py"]} |
52,839 | swetha-1994/jyothsna | refs/heads/master | /FP/inside/migrations/0003_sai_image.py | # Generated by Django 2.2.7 on 2019-12-17 05:32
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('inside', '0002_sai_city'),
]
operations = [
migrations.AddField(
model_name='sai',
name='image',
field=models.FileField(default=django.utils.timezone.now, upload_to='img'),
preserve_default=False,
),
]
| {"/FP/inside/views.py": ["/FP/inside/models.py"], "/FP/inside/admin.py": ["/FP/inside/models.py"]} |
52,840 | swetha-1994/jyothsna | refs/heads/master | /FP/inside/migrations/0004_sai_state.py | # Generated by Django 2.2.7 on 2019-12-17 07:17
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('inside', '0003_sai_image'),
]
operations = [
migrations.AddField(
model_name='sai',
name='state',
field=models.CharField(default=django.utils.timezone.now, max_length=15),
preserve_default=False,
),
]
| {"/FP/inside/views.py": ["/FP/inside/models.py"], "/FP/inside/admin.py": ["/FP/inside/models.py"]} |
52,841 | laughinghan/rapidsms-core-dev | refs/heads/master | /lib/rapidsms/tests/backend/test_http.py | from nose.tools import assert_equals, assert_true
from django.http import HttpRequest, HttpResponse
from rapidsms.tests.harness import MockRouter
from rapidsms.backends.http import RapidHttpBacked
class NewBackend(RapidHttpBacked):
def configure(self, *args, **kwargs):
self.username = kwargs.pop('username')
super(NewBackend, self).configure(*args, **kwargs)
def test_handle_request():
""" handle_request must return a HttpResponse """
router = MockRouter()
backend = RapidHttpBacked(name='test', router=router)
response = backend.handle_request(HttpRequest())
assert_true(isinstance(response, HttpResponse))
def test_extra_config():
""" Allow custom configuration """
router = MockRouter()
backend = NewBackend(name='test', router=router, username='rapidsms')
assert_equals('rapidsms', backend.username)
| {"/lib/rapidsms/views.py": ["/lib/rapidsms/models.py"]} |
52,842 | laughinghan/rapidsms-core-dev | refs/heads/master | /lib/rapidsms/urls.py | #!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4
from django.conf.urls.defaults import *
from . import views
urlpatterns = patterns('',
url(r'^$', views.dashboard),
url(r'^dashboard/add/widget/$', views.add_dashboard_widget),
url(r'^dashboard/add/widget_entry/$', views.add_dashboard_widget_entry),
url(r'^dashboard/del/$', views.delete_dashboard_widget),
url(r'^accounts/login/$', views.login),
url(r'^accounts/logout/$', views.logout),
)
| {"/lib/rapidsms/views.py": ["/lib/rapidsms/models.py"]} |
52,843 | laughinghan/rapidsms-core-dev | refs/heads/master | /lib/rapidsms/views.py | #!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4
from django.template import RequestContext
from django.shortcuts import render_to_response
from django.shortcuts import redirect
from django.views.decorators.http import require_GET
from django.contrib.auth.views import login as django_login
from django.contrib.auth.views import logout as django_logout
from django.db import models
from .models import *
@require_GET
def dashboard(req):
context = {} # the variables to be used in the template
# list of models that may be summarized
# with info that add_dashboard_widget needs to identify them
context['models'] = [
{
'name': "%s (%s)" % (model.__name__, model._meta.app_label),
'id': "%s+%s" % (model.__name__, model._meta.app_label)
}
for model in models.get_models()
if not issubclass(model, WidgetBase)
and not issubclass(model, WidgetEntryBase)
and not model.__module__.startswith('django.contrib.')
]
# 3 lists of currently saved widgets to be displayed in the 3 columns
for i in 1,2,3:
this_col = context["col%s" % i] = []
for widget in Widget.objects.filter(column=i):
this_col.append(widget.derivative)
return render_to_response(
'dashboard.html',
context,
context_instance=RequestContext(req))
def add_dashboard_widget(req):
# if a nonempty string was submitted as the identifying info of a model,
# create a widget to summarize the model's info
if req.GET['model']:
model_name, model_app_label = req.GET['model'].split('+')
widg = Widget.create_and_link(title=req.GET['title'], column=req.GET['column'],
model_name=model_name, model_app_label=model_app_label)
ModelCount.create_and_link(widget=widg, label='Number Of %ss' % widg.model_name)
# regardless, redirect to Dashboard
""" ** TODO: **
present some kind of error message if there's an error,
present a "Widget Was Created!" message and highlight the newly
created widget otherwise
"""
return redirect('/')
def add_dashboard_widget_entry(req):
# if all the info needed is there, create a new entry in the appropriate widget
if req.GET['widget_id'] and req.GET['field'] and req.GET['stats']:
widget = Widget.objects.get(pk=req.GET['widget_id'])
FieldStats.create_and_link(widget=widget, label=req.GET['label'],
field=req.GET['field'], statistic=req.GET['stats'])
return redirect('/')
def delete_dashboard_widget(req):
if req.GET.get('base_id', None):
Widget.objects.get(pk=req.GET['base_id']).delete()
return redirect('/')
""" ** TODO: **
def delete_dashboard_widget_entry(req):
...
"""
def login(req, template_name="rapidsms/login.html"):
return django_login(req, **{"template_name" : template_name})
def logout(req, template_name="rapidsms/loggedout.html"):
return django_logout(req, **{"template_name" : template_name})
| {"/lib/rapidsms/views.py": ["/lib/rapidsms/models.py"]} |
52,844 | laughinghan/rapidsms-core-dev | refs/heads/master | /lib/rapidsms/models.py | #!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4
from datetime import datetime
from django.db import models
from .utils.modules import try_import, get_classes
from .conf import settings
class ExtensibleModelBase(models.base.ModelBase):
def __new__(cls, name, bases, attrs):
module_name = attrs["__module__"]
app_label = module_name.split('.')[-2]
extensions = _find_extensions(app_label, name)
bases = tuple(extensions) + bases
return super(ExtensibleModelBase, cls).__new__(
cls, name, bases, attrs)
def _find_extensions(app_label, model_name):
ext = []
suffix = "extensions.%s.%s" % (
app_label, model_name.lower())
modules = filter(None, [
try_import("%s.%s" % (app_name, suffix))
for app_name in settings.INSTALLED_APPS ])
for module in modules:
for cls in get_classes(module, models.Model):
ext.append(cls)
return ext
class Backend(models.Model):
"""
This model isn't really a backend. Those are regular Python classes,
in rapidsms/backends. This is just a stub model to provide a primary
key for each running backend, so other models can be linked to it
with ForeignKeys.
"""
name = models.CharField(max_length=20, unique=True)
def __unicode__(self):
return self.name
def __repr__(self):
return '<%s: %s>' %\
(type(self).__name__, self)
class App(models.Model):
"""
This model isn't really a RapidSMS App. Like Backend, it's just a
stub model to provide a primary key for each app, so other models
can be linked to it.
The Django ContentType stuff doesn't quite work here, since not all
RapidSMS apps are valid Django apps. It would be nice to fill in the
gaps and inherit from it at some point in the future.
Instances of this model are generated by the update_apps management
command, (which is hooked on Router startup (TODO: webui startup)),
and probably shouldn't be messed with after that.
"""
module = models.CharField(max_length=100, unique=True)
active = models.BooleanField()
def __unicode__(self):
return self.module
def __repr__(self):
return '<%s: %s>' %\
(type(self).__name__, self)
class ContactBase(models.Model):
name = models.CharField(max_length=100, blank=True)
# the spec: http://www.w3.org/International/articles/language-tags/Overview
# reference:http://www.iana.org/assignments/language-subtag-registry
language = models.CharField(max_length=6, blank=True, help_text=
"The language which this contact prefers to communicate in, as "
"a W3C language tag. If this field is left blank, RapidSMS will "
"default to: " + settings.LANGUAGE_CODE)
class Meta:
abstract = True
def __unicode__(self):
return self.name or "Anonymous"
def __repr__(self):
return '<%s: %s>' %\
(type(self).__name__, self)
@property
def is_anonymous(self):
return not self.name
@property
def default_connection(self):
"""
Return the default connection for this person.
"""
# TODO: this is defined totally arbitrarily for a future
# sane implementation
if self.connection_set.count() > 0:
return self.connection_set.all()[0]
return None
class Contact(ContactBase):
__metaclass__ = ExtensibleModelBase
class ConnectionBase(models.Model):
"""
This model pairs a Backend object with an identity unique to it (eg.
a phone number, email address, or IRC nick), so RapidSMS developers
need not worry about which backend a messge originated from.
"""
backend = models.ForeignKey(Backend)
identity = models.CharField(max_length=100)
contact = models.ForeignKey(Contact, null=True, blank=True)
class Meta:
abstract = True
def __unicode__(self):
return "%s via %s" %\
(self.identity, self.backend)
def __repr__(self):
return '<%s: %s>' %\
(type(self).__name__, self)
class Connection(ConnectionBase):
__metaclass__ = ExtensibleModelBase
class PolymorphicModel(models.Model):
"""
An abstract Model base class that provides descendant Model classes
with more polymorphism than normal Django Models.
Note: Overrides primary key to be base_id.
Usage:
class BaseClass(PolymorphicModel):
bar = models.CharField(max_length=100)
def foo(self):
return bar
class DerivedClass(models.Model):
def foo(self):
return "derived " + bar
later...
DerivedClass.create_and_link(bar='bar')
assertEquals('derived bar',
BaseClass.objects.get(bar='bar').derivative.foo())
"""
base_id = models.AutoField(primary_key=True)
# because id is overwritten in derived classes
# since Django doesn't allow generic ForeignKeys to arbitrary models
# (which makes sense since they're actually implemented as number fields
# containing the primary key of the predetermined table), these identify
# the derivative subclass this model object was created as
derivative_name = models.CharField(max_length=50)
derivative_app_label = models.CharField(max_length=100)
@classmethod
def create_and_link(cls, **kwargs):
"""
Create a Widget and link to given class.
Meant to be called on subclasses of PolymorphicModel.
See Usage in PolymorphicModel.__doc__.
"""
return cls.objects.create(derivative_name=cls.__name__,
derivative_app_label=cls._meta.app_label, **kwargs)
@property
def derivative(self):
"""
Use the self.derivative_* identifying info to get an instance of the
derivative subclass this model object was originally created as
representing the same object in the database as self.
"""
return models.get_model(self.derivative_app_label, self.derivative_name)\
.objects.get(base_id=self.base_id)
class Meta:
abstract = True
class WidgetBase(PolymorphicModel):
"""
A Dashboard widget that displays at-a-glance summary statistics info.
"""
title = models.CharField(max_length=40)
column = models.PositiveSmallIntegerField()
# these identify the model that this widget summarizes
# (See above about generic ForeignKeys to arbitrary models)
model_name = models.CharField(max_length=100)
model_app_label = models.CharField(max_length=100)
@property
def model(self):
"Use the self.model_* identifying info to get the model class"
return models.get_model(self.model_app_label, self.model_name)
def field_names(self):
"""
Get the field names of the model (important mainly because _meta
starts with an underscore so off-limits to template)
"""
return [field.name for field in self.model._meta.fields if
not isinstance(field, models.AutoField)]
def __unicode__(self):
return self.title or (str(self.model_name).split('.')[-1] + " Dashboard Widget")
def __repr__(self):
return '<%s: %s>' %\
(type(self).__name__, self)
class Widget(WidgetBase):
__metaclass__ = ExtensibleModelBase
class WidgetEntryBase(PolymorphicModel):
"""
A line of data in a Dashboard Widget.
"""
widget = models.ForeignKey(Widget, related_name='data')
label = models.CharField(max_length=50)
@property
def model(self):
"My model is my widget's model"
return self.widget.model
def data(self):
"Some summary data about the widget's model."
return '[WidgetEntryBase.data not overridden]'
class WidgetEntry(WidgetEntryBase):
__metaclass__ = ExtensibleModelBase
class ModelCount(WidgetEntry):
"""
Counts how many objects of the widget's model are in the database.
"""
def data(self):
return self.model.objects.count()
class Meta:
proxy = True
class FieldStats(WidgetEntry):
"""
Applies one of Django's statistical aggregation functions to a field
of the widget's model.
"""
field = models.CharField(max_length=50)
statistic = models.CharField(max_length=10) # i.e. which aggregation function
def data(self):
return self.model.objects.aggregate(
data=models.__dict__[self.statistic](self.field))['data']
""" ** TODO: **
FieldStats are only for numerical fields, a WidgetEntry of stats about
the lengths of CharFields and TextFields could be useful
"""
| {"/lib/rapidsms/views.py": ["/lib/rapidsms/models.py"]} |
52,845 | laughinghan/rapidsms-core-dev | refs/heads/master | /lib/rapidsms/backends/http.py | import select
from django import http
from django.core.handlers.wsgi import WSGIHandler, STATUS_CODE_TEXT
from django.core.servers.basehttp import WSGIServer, WSGIRequestHandler
from rapidsms.log.mixin import LoggerMixin
from rapidsms.backends.base import BackendBase
class RapidWSGIHandler(WSGIHandler, LoggerMixin):
""" WSGIHandler without Django middleware and signal calls """
def _logger_name(self):
return "%s/%s" % (self.backend._logger_name(), 'handler')
def __call__(self, environ, start_response):
request = self.request_class(environ)
self.debug('Request from %s' % request.get_host())
try:
response = self.backend.handle_request(request)
except Exception, e:
self.exception(e)
response = http.HttpResponseServerError()
try:
status_text = STATUS_CODE_TEXT[response.status_code]
except KeyError:
status_text = 'UNKNOWN STATUS CODE'
status = '%s %s' % (response.status_code, status_text)
response_headers = [(str(k), str(v)) for k, v in response.items()]
start_response(status, response_headers)
return response
class RapidHttpServer(WSGIServer):
""" WSGIServer that doesn't block on handle_request """
def handle_request(self, timeout=1.0):
reads, writes, errors = (self, ), (), ()
reads, writes, errors = select.select(reads, writes, errors, timeout)
if reads:
WSGIServer.handle_request(self)
class RapidHttpBacked(BackendBase):
""" RapidSMS backend that creates and handles an HTTP server """
def configure(self, host="localhost", port=8080):
self.host = host
self.port = port
self.handler = RapidWSGIHandler()
self.handler.backend = self
def run(self):
server_address = (self.host, int(self.port))
self.info('Starting HTTP server on {0}:{1}'.format(*server_address))
self.server = RapidHttpServer(server_address, WSGIRequestHandler)
self.server.set_app(self.handler)
while self.running:
self.server.handle_request()
def handle_request(self, request):
""" Override this in a subclass to create and route messages """
return http.HttpResponse('OK')
| {"/lib/rapidsms/views.py": ["/lib/rapidsms/models.py"]} |
52,849 | alex-carneiro/BoxImageAnn | refs/heads/main | /labels.py | # -*- coding: utf-8 -*-
"""
Created on Mon Sep 6 19:35:51 2021
@author: Alex Carneiro
"""
import cv2
import numpy as np
import pandas as pd
class Interface:
GROUND_COLOR = 120
def __init__(self, names, win_name):
self.names = names
self.win_name = win_name
self.last_selected = -1
self.image = self.create()
def get_image(self):
return self.image
def get_selected(self):
return self.last_selected
def set_support(self, obj):
self.obj = obj
def support(self):
if 0 <= self.last_selected < len(self.names):
selected_name = self.names[self.last_selected]
self.obj.set_label(selected_name, self.last_selected)
elif self.last_selected == len(self.names):
self.obj.reset()
self.obj.set_label(None, None)
else:
self.obj.set_label(None, None)
def create_piece(self, name, shape=(50, 400, 3), margin=10, ground=None, text_color=(255, 255, 255)):
image = np.ones(shape, dtype=np.uint8)
if ground is None:
image[:] = self.GROUND_COLOR
else:
image[:,:] = ground
h, w = shape[:2]
h -= margin
cv2.putText(image, name, (margin, h),
cv2.FONT_HERSHEY_COMPLEX, 1, text_color, 2, cv2.LINE_AA)
return image
def create(self, selected=-1, mouse_on=-1):
self.last_selected = selected
self.pieces = []
for i, name in enumerate(self.names):
if i == self.last_selected and i == mouse_on:
self.pieces.append(self.create_piece(name.lower(),
ground=(150, 50, 50),
text_color=(0, 255, 255)))
elif i == self.last_selected:
self.pieces.append(self.create_piece(name.lower(),
ground=(150, 50, 50)))
elif i == mouse_on:
self.pieces.append(self.create_piece(name.lower(),
text_color=(0, 255, 255)))
else:
self.pieces.append(self.create_piece(name.lower()))
if mouse_on == len(self.names):
self.pieces.append(self.create_piece("CLEAR ANNOTATIONS",
text_color=(0, 255, 255)))
else:
self.pieces.append(self.create_piece("CLEAR ANNOTATIONS"))
self.ranges = []
h_total = 0
for p in self.pieces:
h = p.shape[0]
self.ranges.append((h_total, h_total + h - 1))
h_total += h
return np.vstack(self.pieces)
def select_label(self, event, x, y, flags, param):
if event == cv2.EVENT_LBUTTONDOWN:
for i, r in enumerate(self.ranges):
v_min, v_max = r
if v_min <= y <= v_max:
break
self.image = self.create(selected=i)
self.support()
cv2.imshow(self.win_name, self.image)
elif event == cv2.EVENT_MOUSEMOVE:
for i, r in enumerate(self.ranges):
v_min, v_max = r
if v_min <= y <= v_max:
break
self.image = self.create(selected=self.last_selected, mouse_on=i)
cv2.imshow(self.win_name, self.image)
def save_annotations(annotations, image_filename):
ann_filename = '.'.join(image_filename.split('.')[:-1]) + '.txt'
df = pd.DataFrame({0: [ann[0] for ann in annotations],
1: [ann[1] for ann in annotations],
2: [ann[2] for ann in annotations],
3: [ann[3] for ann in annotations],
4: [ann[4] for ann in annotations]})
df.to_csv(ann_filename, sep=' ', header=None, index=None)
| {"/ann.py": ["/drawing.py", "/labels.py"]} |
52,850 | alex-carneiro/BoxImageAnn | refs/heads/main | /drawing.py | # -*- coding: utf-8 -*-
"""
Created on Mon Sep 6 18:04:19 2021
@author: Alex Carneiro
"""
import cv2
class BoxDrawing:
def __init__(self):
self.ref_pt = []
self.cropping = False
self.win_name = 'Image'
self.box_color = (0, 255, 0)
self.label = None
self.label_id = None
self.points = []
self.annotations = []
def set_image(self, image):
self.image = image.copy()
self.original_image = image.copy()
def set_win_name(self, win_name):
self.win_name = win_name
def set_box_color(self, box_color):
self.box_color = box_color
def set_label(self, label, label_id):
self.label = label
self.label_id = label_id
if label is not None:
print('INFO: Next annotation is a', label)
def get_label(self):
return self.label, self.label_id
def get_annotations(self):
return self.annotations
def reset(self):
self.ref_pt = []
self.cropping = False
self.win_name = 'Image'
self.box_color = (0, 255, 0)
self.image = self.original_image.copy()
self.label = None
self.label_id = None
self.points = []
self.annotations = []
cv2.imshow(self.win_name, self.image)
def make_box(self, event, x, y, flags, param):
if self.label is not None:
if event == cv2.EVENT_LBUTTONDOWN:
self.ref_pt = [(x, y)]
self.cropping = True
elif self.cropping and event == cv2.EVENT_MOUSEMOVE:
image_aux = self.image.copy()
x0, y0 = self.ref_pt[0]
margin = 10
cv2.rectangle(image_aux, self.ref_pt[0], (x, y),
self.box_color, 2)
cv2.putText(image_aux, self.label, (x0, y0 - margin),
cv2.FONT_HERSHEY_COMPLEX, 1, (0, 255, 0), 2, cv2.LINE_AA)
cv2.imshow(self.win_name, image_aux)
elif event == cv2.EVENT_LBUTTONUP:
self.ref_pt.append((x, y))
self.cropping = False
x0, y0 = self.ref_pt[0]
margin = 10
cv2.rectangle(self.image, self.ref_pt[0], self.ref_pt[1],
self.box_color, 2)
cv2.putText(self.image, self.label, (x0, y0 - margin),
cv2.FONT_HERSHEY_COMPLEX, 1, (0, 255, 0), 2, cv2.LINE_AA)
cv2.imshow(self.win_name, self.image)
h, w = self.image.shape[:2]
p = self.ref_pt[0] + self.ref_pt[1]
self.points.append(p)
ann = (self.label_id, (p[2] + p[0])/(2*w), (p[3] + p[1])/(2*h), (p[2] - p[0])/w, (p[3] - p[1])/h)
self.annotations.append(ann)
| {"/ann.py": ["/drawing.py", "/labels.py"]} |
52,851 | alex-carneiro/BoxImageAnn | refs/heads/main | /ann.py | # -*- coding: utf-8 -*-
"""
Created on Mon Sep 6 15:48:37 2021
@author: Alex Carneiro
"""
import cv2
from drawing import BoxDrawing
from labels import Interface, save_annotations
import os
import argparse
from glob import glob
WIN_NAME = 'Image'
WIN_AUX = 'Select the name'
if __name__ == '__main__':
# Set the input command line arguments
parser = argparse.ArgumentParser(description='Read all images from folder')
parser.add_argument('--folder', default='.',
help='folder to be read')
parser.add_argument('--extensions', default=['jpg', 'jpeg', 'png', 'bmp'],
type=list, help='list of accepted extensions')
parser.add_argument('--names', default='names.txt',
help='file to be read with the labels')
parser.add_argument('--max_side', default=None,
type=int, help='maximum size for image side')
args = parser.parse_args()
folder_path = args.folder
# Get the paths for all images inside --folder
images_paths = []
for ext in args.extensions:
images_paths += glob(os.path.join(folder_path, '*.' + ext))
# Draw boxes and save the coordinates
draw = BoxDrawing()
draw.set_win_name(WIN_NAME)
with open(args.names, 'r') as names_file:
names = names_file.read().splitlines()
names_interface = Interface(names, WIN_AUX)
for image_path in images_paths:
image = cv2.imread(image_path)
if args.max_side is not None:
rate = args.max_side / max(image.shape[:2])
image = cv2.resize(image, None, fx=rate, fy=rate,
interpolation=cv2.INTER_LINEAR)
cv2.namedWindow(WIN_AUX)
cv2.setMouseCallback(WIN_AUX, names_interface.select_label)
aux_image = names_interface.get_image()
selected_label_id = names_interface.get_selected()
cv2.imshow(WIN_AUX, aux_image)
names_interface.set_support(draw)
draw.set_image(image)
draw.reset()
names_interface.support()
cv2.namedWindow(WIN_NAME)
cv2.setMouseCallback(WIN_NAME, draw.make_box)
cv2.imshow(WIN_NAME, image)
if cv2.waitKey(0) & 0xFF == ord('q'):
break
save_annotations(draw.get_annotations(), image_path)
cv2.destroyAllWindows()
| {"/ann.py": ["/drawing.py", "/labels.py"]} |
52,878 | pysyun/python-compute-graph | refs/heads/master | /compute/graph/structure.py | class Graph:
def __init__(self):
self.nodes = []
self.firstNode = None
self.previousNode = None
def add(self, node):
if None == self.firstNode:
self.firstNode = node
if None != self.previousNode:
self.previousNode.add(Synapse().add(node))
self.previousNode = node
self.nodes.append(node)
return node
def connect(self, subgraph):
self.add(subgraph.first())
def first(self):
return self.firstNode
def write(self, data):
self.firstNode.write(data)
class Node:
def __init__(self):
self.__arguments = []
self.__synapses = []
def add(self, synapse):
self.__synapses.append(synapse)
return self
def arguments(self, value):
self.__arguments = value
def read(self):
result = self.__arguments
self.__arguments = []
return result
def write(self, data):
if None != data:
self.__arguments += data
def initialize(self):
return
def activate(self):
self.process()
data = self.read()
if None != data:
for i in range(len(self.__synapses)):
synapse = self.__synapses[i]
synapse.write(data)
def process(self):
return
def synapses(self):
return self.__synapses
class Synapse:
__node: None
def add(self, node):
self.__node = node
return self
def node(self):
return self.__node
def write(self, data):
self.__node.write(data)
| {"/compute/graph/profile.py": ["/compute/graph/structure.py"], "/compute/graph/visualization.py": ["/compute/graph/structure.py", "/compute/graph/profile.py"]} |
52,879 | pysyun/python-compute-graph | refs/heads/master | /setup.py | from setuptools import setup
setup (
name = 'compute_graph',
version = '1.0',
description = 'Compute graph implementation for Python.',
author = 'Vitche Research Team Developer',
author_email = 'developer@vitche.com',
py_modules = ['compute.graph', 'compute.graph.structure', 'compute.graph.profile', 'compute.graph.activation', 'compute.graph.visualization'],
install_requires = []
)
| {"/compute/graph/profile.py": ["/compute/graph/structure.py"], "/compute/graph/visualization.py": ["/compute/graph/structure.py", "/compute/graph/profile.py"]} |
52,880 | pysyun/python-compute-graph | refs/heads/master | /compute/graph/profile.py | from compute.graph.structure import Graph
from compute.graph.structure import Node
class ProfileGraph(Graph):
def add(self, node):
node = super().add(node)
node.add(ProfileNode())
return node
class ProfileNode(Node):
def write(self, data):
if None != data:
self.arguments(data)
| {"/compute/graph/profile.py": ["/compute/graph/structure.py"], "/compute/graph/visualization.py": ["/compute/graph/structure.py", "/compute/graph/profile.py"]} |
52,881 | pysyun/python-compute-graph | refs/heads/master | /compute/graph/visualization.py | from graphviz import Digraph
from graphviz import Source
import graphviz
from IPython.display import display
from compute.graph.structure import Node
from compute.graph.profile import ProfileNode
class GraphvizNode(Node):
def __traverse(self, graph, node):
synapses = node.synapses()
# Extract deltas from profiler nodes if any
delta = None
for i in range(len(synapses)):
neighborNode = synapses[i].node()
if isinstance(neighborNode, ProfileNode):
deltas = neighborNode.read()
if 0 < len(deltas):
delta = deltas[0]
for i in range(len(synapses)):
neighborNode = synapses[i].node()
if isinstance(neighborNode, ProfileNode):
continue
graph.node(str(neighborNode))
self.__traverse(graph, neighborNode)
label = ""
if None != delta:
label = str(delta["amount"]) + " (N), " + str(delta["time"]) + " (s)"
graph.edge(str(node), str(neighborNode), label = label)
def process(self):
dot = Digraph()
self.__traverse(dot, self)
display(Source(dot))
| {"/compute/graph/profile.py": ["/compute/graph/structure.py"], "/compute/graph/visualization.py": ["/compute/graph/structure.py", "/compute/graph/profile.py"]} |
52,882 | TokiedaKodai/Bitcoin-Analysis | refs/heads/main | /tool.py | import pandas as pd
from pandas import Series, DataFrame
from pandas_datareader import DataReader
import numpy as np
import matplotlib.pyplot as plt
import mplfinance as mpf
import seaborn as sns
import time
from datetime import datetime
import os
import poloniex
import config as cf
############################### LOAD DATA ###############################
# Load Coin Price from Poloniex
def loadChart(
price='USDT_BTC',
length=365
):
polo = poloniex.Poloniex()
period = polo.DAY # period of data
end = time.time()
start = end - period * length
chart = polo.returnChartData(price, period=period, start=start, end=end)
df = DataFrame.from_dict(chart, dtype=float)
return df
# Load Stock Price from Yahoo
def loadStock(
brand='AAPL',
year=1
):
end = datetime.now()
start = datetime(end.year - year, end.month, end.day)
return DataReader(brand, 'yahoo', start, end)
############################### EDIT TIME ###############################
# Timestamp to Date (year/month/day)
def timestamp2date(timestamp):
return [datetime.fromtimestamp(timestamp[i]).date() for i in range(len(timestamp))]
# Date to String
def date2str(date):
return [date[i].strftime('%Y-%m-%d') for i in range(len(date))]
############################### EDIT DATA FRAME ###############################
# Get Date from DataFrame
def getDate(df):
timestamp = df['date'].values.tolist() # Series -> ndarray -> list
date = timestamp2date(timestamp) # timestamp -> year/month/day
return date
# Get price and date values
def getPrice(
price='USDT_BTC',
kind='open',
length=365
):
df = loadChart(price=price, length=length)
date = getDate(df)
price = df[kind].values.tolist()
return (date, price)
# Get Stock price and date values
def getStockPrice(
brand='AAPL',
kind='Open',
year=1
):
df = loadStock(brand=brand, year=year)
date = df.index.tolist()
price = df[kind].values.tolist()
return (date, price)
# Unify Coin DataFrame
def unifyCoinDF(df):
date = getDate(df)
df.drop(['date', 'quoteVolume', 'weightedAverage'], axis=1, inplace=True)
df.index = pd.to_datetime(date)
df.index.name = 'Date'
df.columns = cf.unit_columns
return df
# Unify Stock DataFrame
def unifyStockDF(df):
return df.drop('Adj Close', axis=1)
# Concat DataFrame
def concatDF(list_df, list_name, column):
newdf = pd.concat([df[column] for df in list_df], axis=1)
newdf.columns = list_name
newdf.dropna(inplace=True)
return newdf
# Add Technical Index
def addTechnicalIndex(df, kind='Open', bw=20):
df['Return'] = df[kind].pct_change() # Daily Return
df['EMA20'] = df[kind].ewm(span=20).mean() # 20days EMA
df['SMA50'] = df[kind].rolling(window=50).mean() # 50days SMA
# Bollinger Band
r = df[kind].rolling(bw)
df['Upper'] = r.mean() + 2 * r.std()
df['Lower'] = r.mean() - 2 * r.std()
return df
############################### PLOT CHART ###############################
# Save Figure by some formats
def savefig(name):
for fmt in cf.save_formats:
plt.savefig(cf.save_dir + name + fmt)
# Plot graph
def plotGraph(
price='USDT_BTC',
kind='open',
length=365,
name='chart-BTC'
):
date, price = getPrice(
price=price,
kind=kind,
length=length)
plt.plot(date, price)
savefig(name)
# Plot CandleStick Chart
def plotCandlestickChart(
price='USDT_BTC',
kind='Open',
length=100,
name='candlestick_BTC'
):
df = loadChart(price=price, length=length)
df = unifyCoinDF(df)
df = addTechnicalIndex(df, kind=kind)
fig, axes = mpf.plot(df, type='candle', returnfig=True, figratio=(12,4))
savefig(name)
# Plot Technical Chart
def plotTechnicalChart(
price='USDT_BTC',
kind='Open',
length=100,
name='technical_BTC'
):
# length+50 to calcurate SMA50
df = loadChart(price=price, length=length+50)
# Prepare data
df = unifyCoinDF(df)
df = addTechnicalIndex(df, kind=kind)
df = df.tail(length)
# Plot
addplot = mpf.make_addplot(df[['EMA20', 'SMA50']])
fig, axes = mpf.plot(
df, type='candle', addplot=addplot, volume=True,
fill_between=dict(y1=df['Lower'].values, y2=df['Upper'].values, color='lightblue', alpha=.3),
style='charles', returnfig=True, figratio=(12,8))
axes[0].legend(['EMA20', 'SMA50'], loc=2)
savefig(name)
############################### PLOT GRAPH ###############################
# JointPlot
def plotJoint(df1, df2, kind='Open', scatter='hex', name='jointplot', color=None):
plt.figure()
sns.jointplot(x=df1[kind], y=df2[kind], kind=scatter, color=color)
savefig(name)
def plotPair(df, name='pairplot'):
plt.figure()
fig = sns.PairGrid(df)
fig.map_upper(plt.scatter)
fig.map_lower(sns.kdeplot, cmap='cool_d')
fig.map_diag(plt.hist, color='purple')
savefig(name)
def plotHeatmap(df, name='heatmap', annot=True):
plt.figure()
sns.heatmap(df.corr(), annot=annot)
savefig(name) | {"/tool.py": ["/config.py"], "/btc_predoct.py": ["/tool.py", "/predict_tool.py"], "/btc_analysis.py": ["/tool.py"], "/twitter_tool.py": ["/config.py"]} |
52,883 | TokiedaKodai/Bitcoin-Analysis | refs/heads/main | /btc_predoct.py | import pandas as pd
from pandas import Series, DataFrame
import numpy as np
import matplotlib.pyplot as plt
import tool
import predict_tool as ptl
# coin_name_list = ['BTC', 'ETH']
coin_name_list = ['BTC']
coin_list = []
#### Get Data
# Coin
for coin in coin_name_list:
df = tool.loadChart(price='USDT_%s'%coin)
globals()[coin] = tool.unifyCoinDF(df)
coin_list.append(globals()[coin])
#### Predict BTC by Monte Carlo
start = 200
split = 315
train = BTC.iloc[start:split]
test = BTC['Open'].iloc[split-1:]
pred = ptl.predictMonteCarlo(train, 50, 50, runs=100)
plt.figure(figsize=(15, 5))
plt.plot(pred['Open'])
plt.plot(test)
plt.plot(pred['Best'])
plt.legend(['Train','Test', 'Predict'])
tool.savefig('monte_carlo_btc')
# plt.plot(pred)
# plt.plot(test)
# plt.legend(pred.columns)
# tool.savefig('monte_carlo_btc_10simu') | {"/tool.py": ["/config.py"], "/btc_predoct.py": ["/tool.py", "/predict_tool.py"], "/btc_analysis.py": ["/tool.py"], "/twitter_tool.py": ["/config.py"]} |
52,884 | TokiedaKodai/Bitcoin-Analysis | refs/heads/main | /predict_tool.py | import pandas as pd
from pandas import Series, DataFrame
import numpy as np
import time
from datetime import datetime, timedelta
#### Monte Carlo
def monte_carlo(start_price, days, dt, mu, sigma):
prices = np.zeros(days)
prices[0] = start_price
shocks = np.zeros(days)
drifts = np.zeros(days)
for i in range(1, days):
shocks[i] = np.random.normal(loc=0, scale=sigma*np.sqrt(dt))
drifts[i] = mu * dt
prices[i] = prices[i-1] + (prices[i-1] * (drifts[i] + shocks[i]))
return prices
# Only Simulation
def simulateMonteCarlo(df, days, runs=5, kind='Open'):
length = len(df) - days
dt = 1 / days
returns = df[kind].head(length).pct_change()
mu = returns.mean()
sigma = returns.std()
simudf = DataFrame(df[kind])
for run in range(runs):
simu = np.full(len(df), None)
simu[length:] = monte_carlo(df.iloc[length][kind], days, dt, mu, sigma)
simudf['Simulate {}'.format(run+1)] = simu
return simudf
# Predict by Monte Carlo
def predictMonteCarlo(df, days, val_days, runs=5, kind='Open'):
length = len(df)
dt = 1
returns = df[kind].head(length).pct_change()
mu = returns.mean()
sigma = returns.std()
simudf = DataFrame(df[kind])
preddf = DataFrame(np.full(days, None), columns=[kind])
preddf.index = pd.date_range(df.tail(1).index.values[0], periods=days+1, freq='D')[1:]
simudf = pd.concat([simudf, preddf])
# Simulate
for run in range(1, runs+1):
simu = np.full(len(df)+days, None)
simu[length-val_days:] = monte_carlo(df.iloc[length-val_days][kind], val_days+days, dt, mu, sigma)
simudf['Simulate {}'.format(run)] = simu
# Evaluate
score = []
val = length - 1
goal = df[kind][val]
for run in range(1, runs+1):
score.append(np.mean(np.square(
simudf['Simulate {}'.format(run)].iloc[length-val_days:length]
- simudf[kind].iloc[length-val_days:length])))
best = np.argmin(score) + 1
for run in range(1, runs+1):
if run == best:
simudf['Best'] = simudf['Simulate {}'.format(run)]
else:
simudf['Simulate {}'.format(run)].iloc[len(df):] = None
print('Best model : ', best)
return simudf
| {"/tool.py": ["/config.py"], "/btc_predoct.py": ["/tool.py", "/predict_tool.py"], "/btc_analysis.py": ["/tool.py"], "/twitter_tool.py": ["/config.py"]} |
52,885 | TokiedaKodai/Bitcoin-Analysis | refs/heads/main | /btc_analysis.py | # import pandas as pd
# from pandas import Series, DataFrame
# import numpy as np
# import matplotlib.pyplot as plt
# import seaborn as sns
import tool
###################################### Plot BTC Chart
tool.plotGraph()
tool.plotCandlestickChart()
tool.plotTechnicalChart()
###################################### Plot Graphs
coin_name_list = ['BTC', 'ETH']
coin_list = []
tech_name_list = ['AAPL', 'GOOG']
tech_list = []
#### Get Data
# Coin
for coin in coin_name_list:
df = tool.loadChart(price='USDT_%s'%coin)
globals()[coin] = tool.unifyCoinDF(df)
coin_list.append(globals()[coin])
# Stock
for brand in tech_name_list:
df = tool.loadStock(brand=brand)
globals()[brand] = tool.unifyStockDF(df)
tech_list.append(globals()[brand])
# Joint List
brand_list = coin_list
brand_list.extend(tech_list)
brand_name_list = coin_name_list
brand_name_list.extend(tech_name_list)
# Add Technical Index
for brand in brand_list:
brand = tool.addTechnicalIndex(brand)
# New DataFrame
df_opens = tool.concatDF(brand_list, brand_name_list, 'Open')
df_returns = tool.concatDF(brand_list, brand_name_list, 'Return')
#### Plot
tool.plotJoint(BTC, ETH, name='joint_coin_open')
tool.plotJoint(AAPL, GOOG, kind='Return', name='joint_stock_return', color='seagreen')
tool.plotJoint(BTC, GOOG, kind='Return', name='joint_coin-stock_return', color='indianred')
tool.plotPair(df_returns, name='pair_return')
tool.plotHeatmap(df_opens, name='heatmap_open') | {"/tool.py": ["/config.py"], "/btc_predoct.py": ["/tool.py", "/predict_tool.py"], "/btc_analysis.py": ["/tool.py"], "/twitter_tool.py": ["/config.py"]} |
52,886 | TokiedaKodai/Bitcoin-Analysis | refs/heads/main | /config.py | # Directory
save_dir = '../Output/'
model_dir = '../Model'
# Figure
save_formats = ['.png', '.pdf', '.svg']
save_formats = ['.png']
# Data
unit_columns = ['High', 'Low', 'Open', 'Close', 'Volume'] | {"/tool.py": ["/config.py"], "/btc_predoct.py": ["/tool.py", "/predict_tool.py"], "/btc_analysis.py": ["/tool.py"], "/twitter_tool.py": ["/config.py"]} |
52,887 | TokiedaKodai/Bitcoin-Analysis | refs/heads/main | /twitter_tool.py | import pandas as pd
from pandas import DataFrame
import json
from janome.tokenizer import Tokenizer
from requests_oauthlib import OAuth1Session
from wordcloud import WordCloud
import emoji
import re
import csv
import config as cf
keysfile = '../twitter_API/key/keys.json'
# signature = '#TweetFromPython'
signature = ''
##################### Twitter API #####################
def create_oauth_session(oauth_key_dict):
oauth = OAuth1Session(
oauth_key_dict['consumer_key'],
oauth_key_dict['consumer_secret'],
oauth_key_dict['access_token'],
oauth_key_dict['access_token_secret']
)
return oauth
def tweet(oauth, text):
url = 'https://api.twitter.com/1.1/statuses/update.json'
params = {'status': text + '\n' + signature}
req = oauth.post(url, params)
if req.status_code == 200:
print('tweet succeed!')
else:
print('tweet failed')
def search_tweet(word, count, oauth):
url = 'https://api.twitter.com/1.1/search/tweets.json'
params = {
'q': word,
'count' : count,
'result_type' : 'recent',
'exclude': 'retweets',
'lang' : 'ja'
}
responce = oauth.get(url, params=params)
if responce.status_code != 200:
print("Error code: %d" %(responce.status_code))
return None
tweets = json.loads(responce.text)
return tweets
def tweet_image(oauth, text, image_file):
url_media = "https://upload.twitter.com/1.1/media/upload.json"
url_text = "https://api.twitter.com/1.1/statuses/update.json"
files = {"media" : open(image_file, 'rb')}
req_media = oauth.post(url_media, files = files)
if req_media.status_code != 200:
print ('media upload failed: %s', req_media.text)
exit()
media_id = json.loads(req_media.text)['media_id']
print ("Media ID: %d" % media_id)
params = {'status': text + '\n' + signature, 'media_ids': [media_id]}
req = oauth.post(url_text, params)
if req.status_code == 200:
print('tweet succeed!')
else:
print('tweet failed')
##################### Text Normalization #####################
def remove_emoji(text):
return ''.join(c for c in text if c not in emoji.UNICODE_EMOJI['en'])
def remove_url(text):
return re.sub(r'https?://[\w/:%#\$&\?\(\)~\.=\+\-]+', '', text)
##################### Morph #####################
# Get Wakachigaki
def get_wakachi(list_text, word, hinshi=['名詞', '形容詞']):
remove_words = ['こと', 'よう', 'そう', 'これ', 'それ', 'もの', 'ここ', 'さん', 'ちゃん',
'ところ', 'とこ', 'の', 'ん', word]
t = Tokenizer()
wakachi = ''
for text in list_text:
malist = t.tokenize(text)
for w in malist:
word = w.surface
part = w.part_of_speech
hit = False
for h in hinshi:
hit = hit or (h in part)
if not hit:
continue
if word not in remove_words:
wakachi += word + ' '
return wakachi
##################### Twitter Tools #####################
# Tweet Normalization
def normalize_tweets(tweets):
normalized = []
for tweet in tweets:
text = tweet
text = remove_emoji(text)
text = remove_url(text)
normalized.append(text)
return normalized
# Initialize Negative-Positive Dictionary
pn_dic = {}
fp = open('../lib/pn.csv', 'rt', encoding='utf-8')
reader = csv.reader(fp, delimiter='\t')
for i, row in enumerate(reader):
name = row[0]
result = row[1]
pn_dic[name] = result
# Color Function for Word Cloud
def get_pn_color(word, font_size, **kwargs):
r, g, b = 0, 0, 0
pn = 'e'
if word in pn_dic:
pn = pn_dic[word]
if pn == 'p':
b = 255
elif pn == 'n':
r = 255
else:
g = 255
return (r, g, b)
# return (255, 255, 255)
# Word Cloud
def word_cloud(words, image_file, num,
font_path='C:/Windows/Fonts/MSGOTHIC.TTC'):
wordcloud = WordCloud(
# background_color='white',
background_color='black',
color_func=get_pn_color,
max_words=num,
font_path=font_path,
width=800, height=400).generate(words)
wordcloud.to_file(cf.save_dir + image_file)
return True
# Tweet Trends Words by Word Cloud
def tweetTrendWords(oauth, word, count=100, num=100, name='trend'):
image_file = name + '.jpg'
search = search_tweet(word, count, oauth)
df_search = DataFrame.from_dict(search['statuses'])
tweets = df_search['text'].tolist()
tweets = normalize_tweets(tweets)
wakachi = get_wakachi(tweets, word)
word_cloud(wakachi, image_file, num)
tweet_text = 'search word: {}\nsearch tweets num: {}\ntrend words num: {}'.format(word, count, num)
tweet_image(oauth, tweet_text, cf.save_dir + image_file)
def main():
keys = json.load(open(keysfile))
twitter = create_oauth_session(keys)
search_words = ['ビットコイン', 'イーサリアム']
# search_words = ['九大', '九州大学']
# search_words = ['ウイルス']
# search_words = ['GW', 'ゴールデンウィーク', '大学', '学校', '仕事']
search_num = 100
trend_num = 200
for word in search_words:
image_name = word+'_{}-{}'.format(search_num, trend_num)
tweetTrendWords(twitter, word, count=search_num, num=trend_num, name=image_name)
# words = '''
# 緊急事態宣言 発令中 新型コロナウイルス 警告 変異種 襲来 感染 密 禍
# Emergency Alert COVID-19 Corona Virus NewType Pandemic 自粛 SocialDistance
# StayHome 要請 接触 ソーシャルディスタンス
# '''
# word_cloud(words, 'emergency_alert_3.jpg', 100)
# tweet_image(twitter, '#新型コロナウイルス #COVID19 #緊急事態宣言', cf.save_dir + 'emergency_alert_2.jpg')
if __name__ == '__main__':
main() | {"/tool.py": ["/config.py"], "/btc_predoct.py": ["/tool.py", "/predict_tool.py"], "/btc_analysis.py": ["/tool.py"], "/twitter_tool.py": ["/config.py"]} |
52,888 | jniemeyer46/Evolutionary_2A | refs/heads/master | /main.py | import sys
import time
import string
import random
import threading
from operator import itemgetter
# Personal Files
from Container import Container
from Tree import Tree
import operations
import parser
def main():
# Holds all the config values
container = Container()
#obtain configs in a list format
config = open(sys.argv[1]).read().splitlines()
parser.setup(container, config)
random.seed(container.seed)
# opening the log file
result_log = open(container.prob_log_file, 'w')
# initial formatting of the result log with Result Log at the top and the parameters underneath that
result_log.write("Result Log \n")
result_log.write("Random Seed = %s \n" % container.seed)
result_log.write("Parameters used = {'fitness evaluations': %s, 'number of runs': %s, 'problem solution location': '%s'}\n\n"
% (container.fitness, container.runs, container.prob_solution_file))
threads = []
for run in range(1, container.runs + 1):
# Used in the result log
thread_name = run
# Spins up the number of runs wanted to be executed for the program
t = threading.Thread(name=thread_name, target=evaluations, args=(thread_name, container))
threads.append(t)
# Start all threads
for x in threads:
x.start()
# Wait for all of them to finish
for x in threads:
threads.remove(x)
x.join()
print(container.results)
for i in container.results:
print(i)
container.results.sort(key=itemgetter(0))
print(container.results)
# Inputting the results into the result log
for list in container.results:
for i in range(len(list)):
if i == 0:
result_log.write("Run " + str(list[i]) + "\n")
else:
evalValue, fitnessValue = list[i]
result_log.write(str(evalValue) + " " + str(fitnessValue) + "\n")
result_log.write("\n")
result_log.close()
# Write to solution log
# figure out a way to create the correct solutino file with 30 different running threads
# The core of the program
def evaluations(name, container):
print(str(name) + ' Starting')
# Memory used for the tree
memory = []
# Log list is used to write to the result log after the run
log_list = []
# Best solution found during this particular run
solution = []
# Best fitness found which corresponds to the best solution found
solution_fitness = []
# Holds the highest fitness this particular run
highest_fitness = 0
# Places the name at the top of the list for the log file
log_list.append(name)
# Create the memory list for the current run
for num in range(0, container.k):
x = random.randrange(0, 2, 1)
y = random.randrange(0, 2, 1)
# Create the memory for a given run
memory.append((x, y))
# Fitness Evaluations begin
for evals in range(1, container.fitness + 1):
# Holds the values used to calculate the fitness at the end of an eval
PfitnessValues = []
OfitnessValues = []
# Holds the evals fitness value
PfitnessValue = 0
OfitnessValue = 0
tempP = 0
tempO = 0
# This is where the game is actually played
for play in range(container.l):
# Creates the tree and a list of the elements in the tree in order that they were created
tree, tree_list = operations.createTree(container.d, container.k)
# Reorders the list so that they are in the preordered form
tree_list = operations.reorder(container.d, tree_list)
newDecision = operations.evaluate(memory, container.k, tree_list, container.decision)
fitnessP, fitnessO = operations.yearsInJail(newDecision, container.decision)
# Set the new tit-for-tat decision
container.decision = newDecision
PfitnessValues.append(fitnessP)
OfitnessValues.append(fitnessO)
if fitnessP > container.solution_fitness:
container.solution_fitness = fitnessP
solution_log = open(container.prob_solution_file, 'w')
for i in tree_list:
solution_log.write(str(i) + " ")
for value in PfitnessValues:
tempP += value
for value in OfitnessValues:
tempO += value
PfitnessValue = tempP / len(PfitnessValues)
OfitnessValue = tempO / len(OfitnessValues)
if PfitnessValue > highest_fitness:
highest_fitness = PfitnessValue
log_list.append((evals, PfitnessValue))
if evals % 1000 == False:
print("\n" + str(name) + "\n" + str(evals) + " " + str(PfitnessValue))
container.results.append(log_list)
print(str(name) + ' Exiting')
if __name__ == "__main__":
main() | {"/main.py": ["/Container.py", "/operations.py", "/parser.py"], "/operations.py": ["/Container.py"]} |
52,889 | jniemeyer46/Evolutionary_2A | refs/heads/master | /parser.py | import string
import time
def setup(container, config):
# setting up variables using config file
for rules in config:
# split the rules into words
info = rules.split(" ")
if info[0] == "runs":
container.runs = int(info[2])
elif info[0] == "fitness":
container.fitness = int(info[2])
elif info[0] == "k":
container.k = int(info[2])
elif info[0] == "d":
container.d = int(info[2])
elif info[0] == "l":
container.l = int(info[2])
elif info[0] == "prob_log_file":
container.prob_log_file = info[2]
elif info[0] == "prob_solution_file":
container.prob_solution_file = info[2]
elif info[0] == "newSeed":
if info[2] == '1':
container.seed = time.time()
break
else:
obtained_seed = open(container.prob_log_file).read().splitlines(2)
for lines in obtained_seed:
line = lines.split(" ")
if line[0] == "Random":
container.seed = line[3]
break
| {"/main.py": ["/Container.py", "/operations.py", "/parser.py"], "/operations.py": ["/Container.py"]} |
52,890 | jniemeyer46/Evolutionary_2A | refs/heads/master | /operations.py | from copy import deepcopy
import random
from Container import Container
from Tree import Tree
def createTree(depth, memoryLength):
funcNodes = ['AND', 'OR', 'NOT', 'XOR']
agents = ['P', 'O']
tree_list = []
# Initialize a tree
tree = Tree()
if depth == 1:
# Obtain the two things needed to make a leaf
agent = random.choice(agents)
num = random.randrange(1, (memoryLength + 1))
# The termination node created
leaf = agent + str(num)
# Set the value equal to the created leaf
tree.add(leaf)
tree_list.append(leaf)
else:
for level in range(depth):
if level == 0:
value = random.choice(funcNodes)
tree.add(value)
tree_list.append(value)
elif level is not (depth - 1):
for node in range(2 ** level):
value = random.choice(funcNodes)
tree.add(value)
tree_list.append(value)
else:
for node in range(2 ** level):
agent = random.choice(agents)
num = random.randrange(1, (memoryLength + 1))
leaf = agent + str(num)
tree.add(leaf)
tree_list.append(leaf)
return tree, tree_list
# Make the list a preorder the list
def reorder(depth, list):
count = 0
num = 0
# Holds the position of the element we want to move
position = (2**(depth - 1) - 1)
# We don't need to worry about these two trees
if depth == 1 or depth == 2:
return list
# Worry about the rest
else:
# If the depth is 3 then we move the elements 1 back
if depth == 3:
count = 2
# Otherwise we move the elements back by a power of 2 (in terms of the loop)
else:
num = depth - 2
count += 2**num
for level in reversed(range(count)):
for i in range(0, 2):
x = list[position]
del list[position]
list.insert(position - level, x)
position += 1
return list
def evaluate(memory, memoryLength, tree, decision):
# Holds a tree that I can change
temp = deepcopy(tree)
# Go through the list backwards
for loc in reversed(range(len(temp))):
# Determine whether it is a leaf node or not
if temp[loc][1:].isdigit():
# Location of the memory spot
memoryLocation = memoryLength - int(temp[loc][1:])
# Unpacking the memory tuple
x, y = memory[memoryLocation]
# If the leaf has a P in it use the x position, else use the y
if temp[loc][0] == 'P':
temp[loc] = x
elif temp[loc][0] == 'O':
temp[loc] = y
else:
# If the locations to the right of temp have been evaluated already
if temp[loc+1] == 0 or temp[loc+1] == 1:
if temp[loc] == 'NOT':
if temp[loc+1] >= temp[loc+2]:
t = temp[loc+1] - temp[loc+2]
else:
t = temp[loc+2] - temp[loc+1]
# Does the flipping of the bit
if t == 1:
t = 0
else:
t = 1
# Gets rid of the completely evaluated locations
del temp[loc + 2]
del temp[loc + 1]
temp[loc] = t
elif temp[loc] == 'AND':
# Determines whether it should be a 1 or a zero
if temp[loc+1] == 1 and temp[loc+2] == 1:
t = 1
else:
t = 0
# Gets rid of the completely evaluated locations
del temp[loc + 2]
del temp[loc + 1]
temp[loc] = t
if temp[loc] == 'OR':
# Determines whether it should be a 1 or a zero
if temp[loc+1] == 1 or temp[loc+2] == 1:
t = 1
else:
t = 0
# Gets rid of the completely evaluated locations
del temp[loc + 2]
del temp[loc + 1]
temp[loc] = t
if temp[loc] == 'XOR':
# Determines whether it should be a 1 or a zero
if temp[loc+1] == 1 and temp[loc+2] == 0:
t = 1
elif temp[loc+1] == 0 and temp[loc+2] == 1:
t = 1
else:
t = 0
# Gets rid of the completely evaluated locations
del temp[loc + 2]
del temp[loc + 1]
temp[loc] = t
# Determines whether the agent cooperates or defects based on the tree evaluation
if temp[0] == 1:
return 'cooperate'
elif temp[0] == 0:
return 'defect'
def yearsInJail(decisionP, decisionO):
fitnessP = 0
fitnessO = 0
# If they both cooperate, they get 2 years in jail, 3 fitness point
if decisionP == decisionO and decisionP == 'cooperate':
fitnessP += 3
fitnessO += 3
# If they both defect, they get 4 years in jail, 1 fitness point
elif decisionP == decisionO and decisionP == 'defect':
fitnessP += 1
fitnessO += 1
# If they both defect, they get 4 years in jail, 1 fitness point
elif decisionP == 'cooperate' and decisionO == 'defect':
fitnessP += 0
fitnessO += 5
# If they both defect, they get 4 years in jail, 1 fitness point
elif decisionP == 'defect' and decisionO == 'cooperate':
fitnessP += 5
fitnessO += 0
return fitnessP, fitnessO
| {"/main.py": ["/Container.py", "/operations.py", "/parser.py"], "/operations.py": ["/Container.py"]} |
52,891 | jniemeyer46/Evolutionary_2A | refs/heads/master | /Container.py | class Container:
# The seed used in the current run
seed = 0
# Number of runs to be executed
runs = 0
# Number of Fitness Evaluations to be done
fitness = 0
# Length of Agent Memory
k = 5
# Tree Depth
d = 4
# Number of iterations to be played in a given evaluation
l = 5
# Holds the best fitness found for a given execution
solution_fitness = 0
# Holds the previous decision, starts with defect
decision = 'defect'
# Holds all log_lists which will be used to write to the result file
results = []
# Result Log File
prob_log_file = 0
# Solution File
prob_solution_file = 0 | {"/main.py": ["/Container.py", "/operations.py", "/parser.py"], "/operations.py": ["/Container.py"]} |
52,895 | GenyLeong/python-athelas-cms | refs/heads/master | /app/models/__init__.py | from sqlalchemy_wrapper import SQLAlchemy
from app.config.base import SQLALCHEMY_DATABASE_URI
db = SQLAlchemy(SQLALCHEMY_DATABASE_URI, echo=True, record_queries=True) | {"/app/models/__init__.py": ["/app/config/base.py"], "/manager.py": ["/app/__init__.py", "/app/models/__init__.py", "/app/models/student.py", "/app/models/company.py", "/app/models/skill.py"], "/app/models/relationships.py": ["/app/models/__init__.py"], "/app/__init__.py": ["/app/models/__init__.py", "/app/models/student.py", "/app/models/skill.py", "/app/models/company.py"], "/app/models/skill.py": ["/app/models/__init__.py"], "/app/models/company.py": ["/app/models/__init__.py", "/app/models/relationships.py"], "/app/blueprints/frontend.py": ["/app/models/__init__.py", "/app/models/student.py", "/app/models/company.py", "/app/models/skill.py"]} |
52,896 | GenyLeong/python-athelas-cms | refs/heads/master | /manager.py | # coding: utf-8
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
from app import create_app
from app.models import db
from app.models.student import Student
from app.models.company import Company
from app.models.skill import Skill
app = create_app()
manager = Manager(app)
migrate = Migrate(app, db)
manager.add_command("db", MigrateCommand)
@manager.shell
def make_shell_context():
return dict(
app=app,
db=db,
# add models
Student=Student,
Company=Company,
Skill=Skill
)
@manager.option("-p", "--populate", default="Populating")
def populate(populate):
"""
Populate the database
"""
skills = ["Javascript", "HTML", "CSS", "SASS", "PHP", "Python"]
for name in skills:
skill = Skill(name=name)
db.session.add(skill)
student_1 = Student(
name="Lucia",
last_name="Cardenas",
age=18,
email="lucia.c@gmail.com"
)
student_2 = Student(
name="Maria Gracia",
last_name="Silva",
age=22,
email="mg.s@hotmail.com"
)
db.session.add_all([student_1, student_2])
company = Company(
name="Athelas",
address="Recavarren esquina con pardo",
phone="+51961738608",
website="https://www.athelas.pe"
)
db.session.add(company)
company2 = Company(
name=u"Lucuma Labs",
address="Cerca al faro de miraflores",
phone="+511 681 0041",
website="https://lucumalabs.com/"
)
db.session.add(company2)
company3 = Company(
name=u"Codepicnic",
address="Por todo el mundo",
phone="+48652689522",
website="https://codepicnic.com/"
)
db.session.add(company3)
db.session.commit()
skills = db.session.query(Skill).all()
company.skills.append(skills[0])
company.skills.append(skills[1])
company.skills.append(skills[2])
company.skills.append(skills[3])
company2.skills.append(skills[4])
company2.skills.append(skills[5])
company2.skills.append(skills[1])
company3.skills.append(skills[3])
company3.skills.append(skills[5])
company3.skills.append(skills[1])
student_1.skills.append(skills[0])
student_1.skills.append(skills[1])
student_1.skills.append(skills[2])
student_2.skills.append(skills[0])
student_2.skills.append(skills[1])
student_2.skills.append(skills[2])
student_2.skills.append(skills[3])
db.session.commit()
if __name__ == '__main__':
manager.run()
| {"/app/models/__init__.py": ["/app/config/base.py"], "/manager.py": ["/app/__init__.py", "/app/models/__init__.py", "/app/models/student.py", "/app/models/company.py", "/app/models/skill.py"], "/app/models/relationships.py": ["/app/models/__init__.py"], "/app/__init__.py": ["/app/models/__init__.py", "/app/models/student.py", "/app/models/skill.py", "/app/models/company.py"], "/app/models/skill.py": ["/app/models/__init__.py"], "/app/models/company.py": ["/app/models/__init__.py", "/app/models/relationships.py"], "/app/blueprints/frontend.py": ["/app/models/__init__.py", "/app/models/student.py", "/app/models/company.py", "/app/models/skill.py"]} |
52,897 | GenyLeong/python-athelas-cms | refs/heads/master | /migrations/versions/175c80bee699_modelos_actualizado.py | """modelos actualizado
Revision ID: 175c80bee699
Revises: None
Create Date: 2016-05-19 10:38:47.632650
"""
# revision identifiers, used by Alembic.
revision = '175c80bee699'
down_revision = None
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.create_table('companies',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.Unicode(length=100), nullable=True),
sa.Column('address', sa.Unicode(length=255), nullable=True),
sa.Column('phone', sa.Unicode(length=50), nullable=True),
sa.Column('website', sa.Unicode(length=255), nullable=True),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('name'),
sa.UniqueConstraint('website')
)
op.create_table('skills',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.Unicode(length=50), nullable=True),
sa.Column('description', sa.UnicodeText(), nullable=True),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('name')
)
op.create_table('students',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.Unicode(length=255), nullable=True),
sa.Column('last_name', sa.Unicode(length=255), nullable=True),
sa.Column('age', sa.Integer(), nullable=True),
sa.Column('email', sa.Unicode(length=50), nullable=True),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('email')
)
op.create_table('company_skills',
sa.Column('company_id', sa.Integer(), nullable=True),
sa.Column('skills_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['company_id'], ['companies.id'], ),
sa.ForeignKeyConstraint(['skills_id'], ['skills.id'], )
)
op.create_table('student_skills',
sa.Column('student_id', sa.Integer(), nullable=True),
sa.Column('skills_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['skills_id'], ['skills.id'], ),
sa.ForeignKeyConstraint(['student_id'], ['students.id'], )
)
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_table('student_skills')
op.drop_table('company_skills')
op.drop_table('students')
op.drop_table('skills')
op.drop_table('companies')
### end Alembic commands ###
| {"/app/models/__init__.py": ["/app/config/base.py"], "/manager.py": ["/app/__init__.py", "/app/models/__init__.py", "/app/models/student.py", "/app/models/company.py", "/app/models/skill.py"], "/app/models/relationships.py": ["/app/models/__init__.py"], "/app/__init__.py": ["/app/models/__init__.py", "/app/models/student.py", "/app/models/skill.py", "/app/models/company.py"], "/app/models/skill.py": ["/app/models/__init__.py"], "/app/models/company.py": ["/app/models/__init__.py", "/app/models/relationships.py"], "/app/blueprints/frontend.py": ["/app/models/__init__.py", "/app/models/student.py", "/app/models/company.py", "/app/models/skill.py"]} |
52,898 | GenyLeong/python-athelas-cms | refs/heads/master | /migrations/versions/2975329c1f3b_modificacion.py | """modificacion
Revision ID: 2975329c1f3b
Revises: 175c80bee699
Create Date: 2016-05-20 16:55:16.021312
"""
# revision identifiers, used by Alembic.
revision = '2975329c1f3b'
down_revision = '175c80bee699'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.add_column('skills', sa.Column('logo', sa.Unicode(length=255), nullable=True))
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_column('skills', 'logo')
### end Alembic commands ###
| {"/app/models/__init__.py": ["/app/config/base.py"], "/manager.py": ["/app/__init__.py", "/app/models/__init__.py", "/app/models/student.py", "/app/models/company.py", "/app/models/skill.py"], "/app/models/relationships.py": ["/app/models/__init__.py"], "/app/__init__.py": ["/app/models/__init__.py", "/app/models/student.py", "/app/models/skill.py", "/app/models/company.py"], "/app/models/skill.py": ["/app/models/__init__.py"], "/app/models/company.py": ["/app/models/__init__.py", "/app/models/relationships.py"], "/app/blueprints/frontend.py": ["/app/models/__init__.py", "/app/models/student.py", "/app/models/company.py", "/app/models/skill.py"]} |
52,899 | GenyLeong/python-athelas-cms | refs/heads/master | /app/models/relationships.py | from app.models import db
company_skills = db.Table("company_skills",
db.Column("company_id", db.Integer, db.ForeignKey("companies.id")),
db.Column("skills_id", db.Integer, db.ForeignKey("skills.id"))
)
student_skills = db.Table("student_skills",
db.Column("student_id", db.Integer, db.ForeignKey("students.id")),
db.Column("skills_id", db.Integer, db.ForeignKey("skills.id"))
) | {"/app/models/__init__.py": ["/app/config/base.py"], "/manager.py": ["/app/__init__.py", "/app/models/__init__.py", "/app/models/student.py", "/app/models/company.py", "/app/models/skill.py"], "/app/models/relationships.py": ["/app/models/__init__.py"], "/app/__init__.py": ["/app/models/__init__.py", "/app/models/student.py", "/app/models/skill.py", "/app/models/company.py"], "/app/models/skill.py": ["/app/models/__init__.py"], "/app/models/company.py": ["/app/models/__init__.py", "/app/models/relationships.py"], "/app/blueprints/frontend.py": ["/app/models/__init__.py", "/app/models/student.py", "/app/models/company.py", "/app/models/skill.py"]} |
52,900 | GenyLeong/python-athelas-cms | refs/heads/master | /app/config/base.py | # coding: utf-8
import os
# DATABASE SETTINGS
SQLALCHEMY_DATABASE_URI = 'sqlite:////{}/laboratoria.db'.format(os.getcwd())
# General
DEBUG = True
SECRET_KEY = "saddlñd2a34334DRFFTJ7554684342424#" | {"/app/models/__init__.py": ["/app/config/base.py"], "/manager.py": ["/app/__init__.py", "/app/models/__init__.py", "/app/models/student.py", "/app/models/company.py", "/app/models/skill.py"], "/app/models/relationships.py": ["/app/models/__init__.py"], "/app/__init__.py": ["/app/models/__init__.py", "/app/models/student.py", "/app/models/skill.py", "/app/models/company.py"], "/app/models/skill.py": ["/app/models/__init__.py"], "/app/models/company.py": ["/app/models/__init__.py", "/app/models/relationships.py"], "/app/blueprints/frontend.py": ["/app/models/__init__.py", "/app/models/student.py", "/app/models/company.py", "/app/models/skill.py"]} |
52,901 | GenyLeong/python-athelas-cms | refs/heads/master | /app/__init__.py | from flask import Flask
from flask_zurb_foundation import Foundation
from flask_admin import Admin
from flask_admin.contrib.sqla import ModelView
from app.models import db
from app.models.student import Student
from app.models.skill import Skill
from app.models.company import Company
from blueprints.frontend import frontend
from blueprints.admin import AdminStudentView, AdminCompanyView, AdminSkillView
def create_app(app=None, config_file=None):
if not app:
app = Flask(__name__, template_folder="views")
# Config files
app.config.from_pyfile("config/base.py")
if config_file:
app.config.from_pyfile("config/{}.py".format(config_file))
# Extensions
Foundation(app)
admin = Admin(app, name='Bolsa de Trabajo', template_mode='bootstrap3')
"""
CONTROLADORES
"""
# Blueprints
app.register_blueprint(frontend)
# Admin Views
admin.add_view(AdminSkillView(Skill, db.session))
admin.add_view(AdminStudentView(Student, db.session))
admin.add_view(AdminCompanyView(Company, db.session))
return app
| {"/app/models/__init__.py": ["/app/config/base.py"], "/manager.py": ["/app/__init__.py", "/app/models/__init__.py", "/app/models/student.py", "/app/models/company.py", "/app/models/skill.py"], "/app/models/relationships.py": ["/app/models/__init__.py"], "/app/__init__.py": ["/app/models/__init__.py", "/app/models/student.py", "/app/models/skill.py", "/app/models/company.py"], "/app/models/skill.py": ["/app/models/__init__.py"], "/app/models/company.py": ["/app/models/__init__.py", "/app/models/relationships.py"], "/app/blueprints/frontend.py": ["/app/models/__init__.py", "/app/models/student.py", "/app/models/company.py", "/app/models/skill.py"]} |
52,902 | GenyLeong/python-athelas-cms | refs/heads/master | /app/models/student.py | from app.models import db
from app.models.relationships import student_skills
from app.models.company import Company
from app.models.skill import Skill
class Student(db.Model):
__tablename__ = "students"
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Unicode(255))
last_name = db.Column(db.Unicode(255))
age = db.Column(db.Integer)
email = db.Column(db.Unicode(50), unique=True)
skills = db.relationship("Skill", secondary=student_skills,
backref=db.backref("students", lazy="dynamic"))
def __repr__(self):
return "{}, {}".format(self.name, self.email)
@property
def _student_skills_as_set(self):
"""
returns student skills as set to work with it
"""
return set([skill.id for skill in self.skills])
def matching_companies(self):
"""
Returns a list of matching companiesordered by relevance
"""
student_skills = self._student_skills_as_set
companies = db.session.query(Company).all()
print companies
matching_companies = []
for company in companies:
company_skills = set([skill.id for skill in company.skills])
match_skills = [skill for skill in student_skills & company_skills]
other_skills = [skill for skill in company_skills - student_skills]
if len(match_skills) > 0:
# Model lists
match_skills_obj = [
db.session.query(Skill).get(skill) for skill in match_skills]
other_skills_obj = [
db.session.query(Skill).get(skill) for skill in other_skills]
match = {
"model": company,
"matches": len(match_skills),
"skills": match_skills_obj,
"other_skills": other_skills_obj
}
matching_companies.append(match)
# sort the list by matches, most matches first
from operator import itemgetter
sorted_matching_companies = sorted(matching_companies,
key=itemgetter('matches'),
reverse=True)
return sorted_matching_companies
| {"/app/models/__init__.py": ["/app/config/base.py"], "/manager.py": ["/app/__init__.py", "/app/models/__init__.py", "/app/models/student.py", "/app/models/company.py", "/app/models/skill.py"], "/app/models/relationships.py": ["/app/models/__init__.py"], "/app/__init__.py": ["/app/models/__init__.py", "/app/models/student.py", "/app/models/skill.py", "/app/models/company.py"], "/app/models/skill.py": ["/app/models/__init__.py"], "/app/models/company.py": ["/app/models/__init__.py", "/app/models/relationships.py"], "/app/blueprints/frontend.py": ["/app/models/__init__.py", "/app/models/student.py", "/app/models/company.py", "/app/models/skill.py"]} |
52,903 | GenyLeong/python-athelas-cms | refs/heads/master | /app/blueprints/admin.py | from flask_admin.contrib.sqla import ModelView
class AdminStudentView(ModelView):
"""Vista que permite realizar operaciones CRUD sobre el modelo Student"""
column_list = ("name", "last_name", "age", "email", "skills")
class AdminCompanyView(ModelView):
"""Vista que permite realizar operaciones CRUD sobre el modelo Company"""
column_list = ("name", "address", "phone", "website", "skills")
class AdminSkillView(ModelView):
"""Vista que permite realizar operaciones CRUD sobre el modelo Skill"""
column_list = ("name", "description", "logo")
| {"/app/models/__init__.py": ["/app/config/base.py"], "/manager.py": ["/app/__init__.py", "/app/models/__init__.py", "/app/models/student.py", "/app/models/company.py", "/app/models/skill.py"], "/app/models/relationships.py": ["/app/models/__init__.py"], "/app/__init__.py": ["/app/models/__init__.py", "/app/models/student.py", "/app/models/skill.py", "/app/models/company.py"], "/app/models/skill.py": ["/app/models/__init__.py"], "/app/models/company.py": ["/app/models/__init__.py", "/app/models/relationships.py"], "/app/blueprints/frontend.py": ["/app/models/__init__.py", "/app/models/student.py", "/app/models/company.py", "/app/models/skill.py"]} |
52,904 | GenyLeong/python-athelas-cms | refs/heads/master | /app/models/skill.py | from app.models import db
class Skill(db.Model):
__tablename__ = "skills" #dar nombre a la db
id = db.Column(db.Integer, primary_key=True) #crear columna id
name = db.Column(db.Unicode(50), unique=True) #Unicode:permite representar todo tipo de data
description = db.Column(db.UnicodeText)
# agregar un logo para cada item
logo = db.Column(db.Unicode(255))
def __repr__(self):
return "{}".format(self.name) | {"/app/models/__init__.py": ["/app/config/base.py"], "/manager.py": ["/app/__init__.py", "/app/models/__init__.py", "/app/models/student.py", "/app/models/company.py", "/app/models/skill.py"], "/app/models/relationships.py": ["/app/models/__init__.py"], "/app/__init__.py": ["/app/models/__init__.py", "/app/models/student.py", "/app/models/skill.py", "/app/models/company.py"], "/app/models/skill.py": ["/app/models/__init__.py"], "/app/models/company.py": ["/app/models/__init__.py", "/app/models/relationships.py"], "/app/blueprints/frontend.py": ["/app/models/__init__.py", "/app/models/student.py", "/app/models/company.py", "/app/models/skill.py"]} |
52,905 | GenyLeong/python-athelas-cms | refs/heads/master | /app/models/company.py | from app.models import db
from app.models.relationships import company_skills
class Company(db.Model):
__tablename__ = "companies"
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Unicode(100), unique=True)
address = db.Column(db.Unicode(255))
phone = db.Column(db.Unicode(50))
website = db.Column(db.Unicode(255), unique=True)
skills = db.relationship("Skill", secondary=company_skills,
backref=db.backref("companies", lazy="dynamic"))
mapa = db.Column(db.Unicode(255))
def __repr__(self):
return u"{} - {}".format(self.name, self.address) | {"/app/models/__init__.py": ["/app/config/base.py"], "/manager.py": ["/app/__init__.py", "/app/models/__init__.py", "/app/models/student.py", "/app/models/company.py", "/app/models/skill.py"], "/app/models/relationships.py": ["/app/models/__init__.py"], "/app/__init__.py": ["/app/models/__init__.py", "/app/models/student.py", "/app/models/skill.py", "/app/models/company.py"], "/app/models/skill.py": ["/app/models/__init__.py"], "/app/models/company.py": ["/app/models/__init__.py", "/app/models/relationships.py"], "/app/blueprints/frontend.py": ["/app/models/__init__.py", "/app/models/student.py", "/app/models/company.py", "/app/models/skill.py"]} |
52,906 | GenyLeong/python-athelas-cms | refs/heads/master | /migrations/versions/89aa2646be23_modificacion.py | """modificacion
Revision ID: 89aa2646be23
Revises: 2975329c1f3b
Create Date: 2016-05-20 17:07:56.149371
"""
# revision identifiers, used by Alembic.
revision = '89aa2646be23'
down_revision = '2975329c1f3b'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.add_column('companies', sa.Column('mapa', sa.Unicode(length=255), nullable=True))
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_column('companies', 'mapa')
### end Alembic commands ###
| {"/app/models/__init__.py": ["/app/config/base.py"], "/manager.py": ["/app/__init__.py", "/app/models/__init__.py", "/app/models/student.py", "/app/models/company.py", "/app/models/skill.py"], "/app/models/relationships.py": ["/app/models/__init__.py"], "/app/__init__.py": ["/app/models/__init__.py", "/app/models/student.py", "/app/models/skill.py", "/app/models/company.py"], "/app/models/skill.py": ["/app/models/__init__.py"], "/app/models/company.py": ["/app/models/__init__.py", "/app/models/relationships.py"], "/app/blueprints/frontend.py": ["/app/models/__init__.py", "/app/models/student.py", "/app/models/company.py", "/app/models/skill.py"]} |
52,907 | GenyLeong/python-athelas-cms | refs/heads/master | /app/blueprints/frontend.py | # coding: utf-8
from flask import Blueprint, render_template, abort
from app.models import db
from app.models.student import Student
from app.models.company import Company
from app.models.skill import Skill
frontend = Blueprint("front", __name__, template_folder="views")
@frontend.route("/")
def index():
"""
Explains whats going on and shows a list of companies and students
"""
companies = db.session.query(Company).all()
students = db.session.query(Student).all()
return render_template(
"index.html",
students=students,
companies=companies
)
@frontend.route("/student/<int:student_id>")
def students(student_id):
"""
student details
"""
student = db.session.query(Student).get(student_id)
if not student:
abort(500, "Ese estudiante no existe")
# Retorna listado de compañias que requieren al menos 1 skill de
# la alumna ordenador por ranking
matching_companies = student.matching_companies()
return render_template(
"student.html",
student=student,
matching_companies=matching_companies
)
@frontend.route("/company/<int:company_id>")
def companies(company_id):
"""
company details
"""
company = db.session.query(Company).get(company_id)
if not company:
abort(500, "Esa compañia no existe")
return render_template(
"company.html",
company=company
)
| {"/app/models/__init__.py": ["/app/config/base.py"], "/manager.py": ["/app/__init__.py", "/app/models/__init__.py", "/app/models/student.py", "/app/models/company.py", "/app/models/skill.py"], "/app/models/relationships.py": ["/app/models/__init__.py"], "/app/__init__.py": ["/app/models/__init__.py", "/app/models/student.py", "/app/models/skill.py", "/app/models/company.py"], "/app/models/skill.py": ["/app/models/__init__.py"], "/app/models/company.py": ["/app/models/__init__.py", "/app/models/relationships.py"], "/app/blueprints/frontend.py": ["/app/models/__init__.py", "/app/models/student.py", "/app/models/company.py", "/app/models/skill.py"]} |
52,923 | cathfoliveira/data_platform_bootcamp | refs/heads/main | /data_platform/environment.py |
from enum import Enum
# Criando uma classe de enum para os ambientes que quero criar.
class Environment(Enum):
PRODUCTION = 'production'
STAGING = 'staging'
DEVELOP = 'develop' | {"/data_platform/data_lake/base.py": ["/data_platform/environment.py"], "/data_platform/redshift/stack.py": ["/data_platform/data_lake/base.py"], "/app.py": ["/data_platform/data_lake/stack.py", "/data_platform/athena/stack.py", "/data_platform/redshift/stack.py"], "/data_platform/data_lake/stack.py": ["/data_platform/data_lake/base.py"]} |
52,924 | cathfoliveira/data_platform_bootcamp | refs/heads/main | /revisao_orientacao_a_objeto.py | class Pessoa:
# Metódo para inicialização da classe pessoa
def __init__(self, nome, sobrenome, idade):
self.sobrenome = sobrenome
self.nome = nome
self.idade = idade
# Ao dar um print no objeto, o que vai aparecer?
def __str__(self):
return f"{self.nome} {self.sobrenome} tem {self.idade} anos."
# Teste 1:
catharina = Pessoa(nome='Catharina', sobrenome='Oliveira',idade='34')
print(catharina)
class Cachorro:
def __init__(self, nome, raca, idade):
self.raca = raca
self.nome = nome
self.idade = idade
def __str__(self):
return f"{self.nome} é da raça {self.raca} e tem {self.idade} anos."
def is_cachorro(self):
return True
# Teste 2:
belisco = Cachorro(nome='Belisco', raca='Lhasa',idade='1.9')
print(belisco)
print(belisco.is_cachorro())
# Declarando uma classe engenheiro de dados que herda de Pessoa (o DE é uma pessoa).
class EngenheiroDeDados(Pessoa):
# Recupero a inicialização, passando para a classe mão os dados dela e iniciando o DE com algo que é
# próprio dele, no caso, a experiencia. O.S., estou modificando o método.
def __init__(self, nome, sobrenome, idade, experiencia):
super().__init__(nome, sobrenome, idade)
self.experiencia = experiencia
# Modificando o método str herdado de Pessoa.
def __str__(self):
return f"{self.nome} {self.sobrenome} tem {self.idade} anos, " \
f"é Engenheiro de Dados e tem {self.experiencia} anos de experiencia"
andre = EngenheiroDeDados(nome='Andre', sobrenome='Sionek', idade=30, experiencia=4)
print(andre)
# Declaro uma nova classe que herda os métodos originais de Cahorro e adiciona um método a mais.
class CatiorinhoDanadinho(Cachorro):
def is_danadinho(self):
return True
belisco = CatiorinhoDanadinho(nome='Belisco', raca='Lhasa', idade=1.5)
print(belisco)
print(belisco.is_danadinho())
print(belisco.is_cachorro()) | {"/data_platform/data_lake/base.py": ["/data_platform/environment.py"], "/data_platform/redshift/stack.py": ["/data_platform/data_lake/base.py"], "/app.py": ["/data_platform/data_lake/stack.py", "/data_platform/athena/stack.py", "/data_platform/redshift/stack.py"], "/data_platform/data_lake/stack.py": ["/data_platform/data_lake/base.py"]} |
52,925 | cathfoliveira/data_platform_bootcamp | refs/heads/main | /data_platform/athena/stack.py | from aws_cdk import core
from data_platform.athena.base import BaseAthenaBucket, BaseAthenaWorkgroup
from data_platform import active_environment
''' O Athena vai apontar para o glue_catalog e vai rodar a query em cima do database criado utilizando os metadados advindos do glue.
Assim, se fizermos um count por exemplo, será rápido pq será um metadado já mapeado no glue.
'''
class AthenaStack(core.Stack):
def __init__(self, scope: core.Construct, **kwargs) -> None:
self.deploy_env = active_environment
super().__init__(scope, id=f'{self.deploy_env.value}-athena', **kwargs)
self.athena_bucket = BaseAthenaBucket(
self,
deploy_env=self.deploy_env
)
self.athena_workgroup = BaseAthenaWorkgroup(
self,
deploy_env=self.deploy_env,
athena_bucket=self.athena_bucket,
gb_scanned_cutoff_per_query=1
) | {"/data_platform/data_lake/base.py": ["/data_platform/environment.py"], "/data_platform/redshift/stack.py": ["/data_platform/data_lake/base.py"], "/app.py": ["/data_platform/data_lake/stack.py", "/data_platform/athena/stack.py", "/data_platform/redshift/stack.py"], "/data_platform/data_lake/stack.py": ["/data_platform/data_lake/base.py"]} |
52,926 | cathfoliveira/data_platform_bootcamp | refs/heads/main | /data_platform/data_lake/base.py | from enum import Enum
from aws_cdk import core
from aws_cdk import (
aws_s3 as s3,
)
# Importando a classe Environment criada na raiz do data_platform.
from data_platform.environment import Environment
# Atribuindo um enum para não ficar escrevendo uma string toda hora.
class DataLakeLayer(Enum):
RAW = 'raw'
PROCESSED = 'processed'
AGGREGATED = 'aggregated'
'''
Criando uma classe que tem todas as característico de um S3 Bucket
e quero padronizar para a minha necessidade como um bucket de data lake é criado.
Ao mudar o método, o self é padrão e o scope que é o app.py é obrigatório para a passagem de parâmetros customizados.
'''
class BaseDataLakeBucket(s3.Bucket):
# Estou acrescentando o ambiente e a camada que seria o enum acima, mais o nome padrão para novos buckets criados.
def __init__(self, scope: core.Construct, deploy_env: Environment, layer: DataLakeLayer, **kwargs):
self.layer = layer
self.deploy_env = deploy_env
self.obj_name = f's3-bck-{self.deploy_env.value}-data-lake-{self.layer.value}'
# Obrigatório, inicializando a camada mãe, passo o scope, o id é o nome lógico. E posso adicionar tudo o que
# gostaria de configuração, a exemplo do bloqueio de acesso público.
super().__init__(
scope,
id=self.obj_name,
bucket_name=self.obj_name,
block_public_access=self.default_block_public_access, # Quando chamar este default, ele está declarado abaixo
encryption=self.default_encryption,
versioned=True, # Se deletar, ex, ele faz a deleção lógica. E com o mesmo nome, ele versiona.
**kwargs
)
self.set_default_lifecycle_rules()
# Propriedade default acima usada, virá aqui onde defino o que quero um a um.
@property
def default_block_public_access(self):
return s3.BlockPublicAccess(
ignore_public_acls=True,
block_public_acls=True,
block_public_policy=True,
restrict_public_buckets=True
)
# Optando pela criptografia gerenciada pela AWS.
@property
def default_encryption(self):
return s3.BucketEncryption.S3_MANAGED
def set_default_lifecycle_rules(self):
"""
Sets lifecycle rule by default
"""
self.add_lifecycle_rule(
# Tenho um upload muito grande de várias partes, após 7 dias executando o upload, aborta a operação.
abort_incomplete_multipart_upload_after=core.Duration.days(7),
enabled=True
)
self.add_lifecycle_rule(
noncurrent_version_transitions=[
# Cinco versões de um mesmo objeto, após 30 dias, move as versões inativas para a camada infrequent_access
s3.NoncurrentVersionTransition(
storage_class=s3.StorageClass.INFREQUENT_ACCESS,
transition_after=core.Duration.days(30)
),
# Após 60 dias na camada infrequent, move as versões inativas para a camada glacier
s3.NoncurrentVersionTransition(
storage_class=s3.StorageClass.GLACIER,
transition_after=core.Duration.days(60)
)
]
)
self.add_lifecycle_rule(
# Expirar uma versão não corrente após 360 dias.
noncurrent_version_expiration=core.Duration.days(360)
) | {"/data_platform/data_lake/base.py": ["/data_platform/environment.py"], "/data_platform/redshift/stack.py": ["/data_platform/data_lake/base.py"], "/app.py": ["/data_platform/data_lake/stack.py", "/data_platform/athena/stack.py", "/data_platform/redshift/stack.py"], "/data_platform/data_lake/stack.py": ["/data_platform/data_lake/base.py"]} |
52,927 | cathfoliveira/data_platform_bootcamp | refs/heads/main | /data_platform/active_environment.py | import os
from environment import Environment
# Pega qual é a variável de ambiente que estou usando naquele momento e passa como parâmetro pra classe que
# criamos o enum e a classe irá atribuir a informação de acordo.
active_environment = Environment[os.environ['ENVIRONMENT']] | {"/data_platform/data_lake/base.py": ["/data_platform/environment.py"], "/data_platform/redshift/stack.py": ["/data_platform/data_lake/base.py"], "/app.py": ["/data_platform/data_lake/stack.py", "/data_platform/athena/stack.py", "/data_platform/redshift/stack.py"], "/data_platform/data_lake/stack.py": ["/data_platform/data_lake/base.py"]} |
52,928 | cathfoliveira/data_platform_bootcamp | refs/heads/main | /data_platform/redshift/stack.py | from aws_cdk import core
from aws_cdk import aws_redshift as redshift, aws_ec2 as ec2, aws_iam as iam
from data_platform.data_lake.base import BaseDataLakeBucket
from data_platform import active_environment
from data_platform.common_stack import CommonStack
'''
CREATE EXTERNAL SCHEMA [IF NOT EXISTS] data_lake_raw
FROM DATA CATALOG
DATABASE 'glue_db_develop_data_lake_raw' #nome da database do glue
REGION 'sa-east-1'
IAM_ROLE 'arn:aws:iam:0dfshdfuhdsfahfdhfa'
Executamos esta query uma única vez, pq uma vez que criou o schema,
Ele estará criado e a conexão com o glue estará feita.
O create external schema redshift é o que vai possibilitar=> O redshift vai se conectar ao glue
para pegar o catálogo de dados e vai usar o Athena para ler os dados do S3. Poderia se conectar a outras fontes.
O que fizemos, temos um RDS postgres que através do DMS carregarmos dados para o S3 em arquivos parquet e configuramos
o glue para termos os metadados e podermos ler de maneira otimizada via Athena que tem algo custo e é indicado para
inspeções. Agora precisamos ler os dados do S3 e carregarmos no nosso DW (que é o redshift que criamos).
Para essa leitura, precisamos da tecnologia spectrum.
'''
class SpectrumRole(iam.Role):
def __init__(
self, scope: core.Construct, data_lake_raw: BaseDataLakeBucket, data_lake_processed: BaseDataLakeBucket, **kwargs
) -> None:
self.deploy_env = data_lake_raw.deploy_env
self.data_lake_raw = data_lake_raw
self.data_lake_processed = data_lake_processed
super().__init__(
scope,
id=f"iam-{self.deploy_env.value}-redshift-spectrum-role",
assumed_by=iam.ServicePrincipal("redshift.amazonaws.com"),
description="Role to allow Redshift to access data lake using spectrum",
)
policy = iam.Policy(
scope,
id=f"iam-{self.deploy_env.value}-redshift-spectrum-policy",
policy_name=f"iam-{self.deploy_env.value}-redshift-spectrum-policy",
statements=[
iam.PolicyStatement(actions=["glue:*", "athena:*"], resources=["*"]),
iam.PolicyStatement(
actions=["s3:Get*", "s3:List*", "s3:Put*"],
resources=[
# dando acesso tanto no dl raw quanto no dl process
self.data_lake_raw.bucket_arn,
f"{self.data_lake_raw.bucket_arn}/*",
self.data_lake_processed.bucket_arn,
f"{self.data_lake_processed.bucket_arn}/*",
],
),
],
)
self.attach_inline_policy(policy)
class RedshiftStack(core.Stack):
def __init__(
self,
scope: core.Construct,
data_lake_raw: BaseDataLakeBucket,
data_lake_processed: BaseDataLakeBucket,
common_stack: CommonStack,
**kwargs,
) -> None:
self.common_stack = common_stack
self.data_lake_raw = data_lake_raw
self.deploy_env = active_environment
self.data_lake_processed = data_lake_processed
super().__init__(scope, id=f"{self.deploy_env.value}-redshift-stack", **kwargs)
self.redshift_sg = ec2.SecurityGroup(
self,
f"redshift-{self.deploy_env.value}-sg",
vpc=self.common_stack.custom_vpc,
allow_all_outbound=True,
security_group_name=f"redshift-{self.deploy_env.value}-sg",
)
self.redshift_sg.add_ingress_rule(
peer=ec2.Peer.ipv4("0.0.0.0/0"), connection=ec2.Port.tcp(5439)
)
for subnet in self.common_stack.custom_vpc.private_subnets:
self.redshift_sg.add_ingress_rule(
peer=ec2.Peer.ipv4(subnet.ipv4_cidr_block), connection=ec2.Port.tcp(5439)
)
self.redshift_cluster = redshift.Cluster(
self,
f"db-cluster-{self.deploy_env.value}-redshift",
cluster_name=f"db-cluster-{self.deploy_env.value}-redshift",
vpc=self.common_stack.custom_vpc,
cluster_type=redshift.ClusterType.MULTI_NODE,
node_type=redshift.NodeType.DC2_LARGE,
default_database_name="dw",
number_of_nodes=2,
removal_policy=core.RemovalPolicy.DESTROY,
master_user=redshift.Login(master_username="admin"),
publicly_accessible=True,
roles=[SpectrumRole(self, self.data_lake_raw, self.data_lake_processed)],
security_groups=[self.redshift_sg],
vpc_subnets=ec2.SubnetSelection(subnet_type=ec2.SubnetType.PUBLIC),
) | {"/data_platform/data_lake/base.py": ["/data_platform/environment.py"], "/data_platform/redshift/stack.py": ["/data_platform/data_lake/base.py"], "/app.py": ["/data_platform/data_lake/stack.py", "/data_platform/athena/stack.py", "/data_platform/redshift/stack.py"], "/data_platform/data_lake/stack.py": ["/data_platform/data_lake/base.py"]} |
52,929 | cathfoliveira/data_platform_bootcamp | refs/heads/main | /app.py |
from aws_cdk import core
from data_platform.data_lake.stack import DataLakeStack
from data_platform.common_stack import CommonStack
from data_platform.dms.stack import DmsStack
from data_platform.kinesis.stack import KinesisStack
from data_platform.glue_catalog.stack import GlueCatalogStack
from data_platform.athena.stack import AthenaStack
from data_platform.redshift.stack import RedshiftStack
from data_platform.databricks.stack import DatabricksStack
app = core.App()
# Instanciando a stack (Estrutura do data lake)
data_lake = DataLakeStack(app)
# Instanciando a VPC, políticas, BD PostgreSQL, gateways etc. (RDS + VPC)
common_stack = CommonStack(app)
# Common_stack pega a vpc e a instância do RDS e o datalake pega o bucket de destino
dms = DmsStack(app,
common_stack=common_stack,
data_lake_raw_bucket=data_lake.data_lake_raw_bucket)
kinenis = KinesisStack(app,
data_lake_raw_bucket=data_lake.data_lake_raw_bucket)
glue_catalog = GlueCatalogStack(app,
data_lake_raw_bucket=data_lake.data_lake_raw_bucket,
data_lake_processed_bucket=data_lake.data_lake_processed_bucket)
athena = AthenaStack(app)
redshift = RedshiftStack(app,
data_lake_raw=data_lake.data_lake_raw_bucket,
data_lake_processed=data_lake.data_lake_processed_bucket,
common_stack=common_stack)
# databricks = DatabricksStack(app)
app.synth()
| {"/data_platform/data_lake/base.py": ["/data_platform/environment.py"], "/data_platform/redshift/stack.py": ["/data_platform/data_lake/base.py"], "/app.py": ["/data_platform/data_lake/stack.py", "/data_platform/athena/stack.py", "/data_platform/redshift/stack.py"], "/data_platform/data_lake/stack.py": ["/data_platform/data_lake/base.py"]} |
52,930 | cathfoliveira/data_platform_bootcamp | refs/heads/main | /data_platform/data_lake/stack.py | # Criando a estrutura de armazenamento padrão do meu Data Lake
from data_platform.data_lake.base import BaseDataLakeBucket, DataLakeLayer #Importando as classes de base
from aws_cdk import core
from aws_cdk import (
aws_s3 as s3,
)
from data_platform import active_environment
# Criando a minha stack de fato, herdo da Stack mãe. Novamente o scope do app.py e o ambiente ativo.
class DataLakeStack(core.Stack):
def __init__(self, scope: core.Construct, **kwargs) -> None:
self.deploy_env = active_environment
super().__init__(scope, id=f'{self.deploy_env.value}-data-lake-stack', **kwargs)
# Definindo que a stack terá um bucket raw
self.data_lake_raw_bucket = BaseDataLakeBucket(
self,
deploy_env=self.deploy_env,
layer=DataLakeLayer.RAW
)
# Como é uma camada raw, quero definir o lifecycle como abaixo
self.data_lake_raw_bucket.add_lifecycle_rule(
transitions=[
s3.Transition(
storage_class=s3.StorageClass.INTELLIGENT_TIERING, # Um pouco mais barato que o standard
transition_after=core.Duration.days(90)
),
s3.Transition(
storage_class=s3.StorageClass.GLACIER,
transition_after=core.Duration.days(360)
)
],
enabled=True
)
# Data Lake Processed
self.data_lake_processed_bucket = BaseDataLakeBucket(
self,
deploy_env=self.deploy_env,
layer=DataLakeLayer.PROCESSED
)
# Data Lake Aggregated
self.data_lake_aggregated_bucket = BaseDataLakeBucket(
self,
deploy_env=self.deploy_env,
layer=DataLakeLayer.AGGREGATED
) | {"/data_platform/data_lake/base.py": ["/data_platform/environment.py"], "/data_platform/redshift/stack.py": ["/data_platform/data_lake/base.py"], "/app.py": ["/data_platform/data_lake/stack.py", "/data_platform/athena/stack.py", "/data_platform/redshift/stack.py"], "/data_platform/data_lake/stack.py": ["/data_platform/data_lake/base.py"]} |
53,004 | daldal-Mango/Miracle30 | refs/heads/main | /groups/urls.py | from django.urls import path
from . import views
app_name = 'groups'
urlpatterns = [
path('<int:goal_id>', views.main, name="main"),
path('<int:goal_id>/certify/', views.certify, name="certify"),
path('group_list/', views.group_list, name="group_list"),
path('group_detail/', views.group_detail, name="group_detail"),
path('make_group/', views.make_group, name="make_group"),
path('<int:goal_id>/date_check', views.date_check, name="date_check"),
path('<int:goal_id>/<int:user_id>/delete_member', views.delete_member, name="delete_member"),
]
| {"/groups/admin.py": ["/groups/models.py"], "/groups/views.py": ["/main/models.py", "/groups/models.py"], "/groups/models.py": ["/main/models.py"], "/main/admin.py": ["/main/models.py"], "/users/views.py": ["/main/models.py"], "/main/views.py": ["/main/models.py"]} |
53,005 | daldal-Mango/Miracle30 | refs/heads/main | /groups/admin.py | from django.contrib import admin
from .models import Certify
admin.site.register(Certify)
| {"/groups/admin.py": ["/groups/models.py"], "/groups/views.py": ["/main/models.py", "/groups/models.py"], "/groups/models.py": ["/main/models.py"], "/main/admin.py": ["/main/models.py"], "/users/views.py": ["/main/models.py"], "/main/views.py": ["/main/models.py"]} |
53,006 | daldal-Mango/Miracle30 | refs/heads/main | /groups/migrations/0004_alter_certify_achievement.py | # Generated by Django 3.2.5 on 2021-08-10 00:54
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('groups', '0003_auto_20210809_2345'),
]
operations = [
migrations.AlterField(
model_name='certify',
name='achievement',
field=models.BooleanField(default=True),
),
]
| {"/groups/admin.py": ["/groups/models.py"], "/groups/views.py": ["/main/models.py", "/groups/models.py"], "/groups/models.py": ["/main/models.py"], "/main/admin.py": ["/main/models.py"], "/users/views.py": ["/main/models.py"], "/main/views.py": ["/main/models.py"]} |
53,007 | daldal-Mango/Miracle30 | refs/heads/main | /main/migrations/0002_alter_goal_value.py | # Generated by Django 3.2.5 on 2021-08-09 23:07
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('main', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='goal',
name='value',
field=models.FloatField(blank=True, null=True),
),
]
| {"/groups/admin.py": ["/groups/models.py"], "/groups/views.py": ["/main/models.py", "/groups/models.py"], "/groups/models.py": ["/main/models.py"], "/main/admin.py": ["/main/models.py"], "/users/views.py": ["/main/models.py"], "/main/views.py": ["/main/models.py"]} |
53,008 | daldal-Mango/Miracle30 | refs/heads/main | /groups/views.py | from django.shortcuts import render, get_object_or_404, redirect
from main.models import Goal
from .models import Certify, User
from datetime import datetime, timedelta
import datetime
from django.utils import timezone
def date_check(request, goal_id):
goal = get_object_or_404(Goal, pk=goal_id)
today = datetime.date.today()
if today < goal.start_date:
return redirect('main:goal_detail', goal_id)
else:
return redirect('groups:main', goal_id)
def main(request, goal_id):
level = []
total_name = []
goal = get_object_or_404(Goal, pk=goal_id)
board = get_board(goal)
member_count = goal.member.count() + 1
for date in board['dates']:
certifies = goal.certifies.filter(created=date)
count = certifies.count()
if count == 0:
success_level = 1
elif count <= member_count * (1/4):
success_level = 2
elif count <= member_count * (2/4):
success_level = 3
elif count <= member_count * (3/4):
success_level = 4
else:
success_level = 5
level.append(success_level)
daily_name = []
for certify in certifies:
name = certify.user.username
daily_name.append(name)
total_name.append(daily_name)
certifiy_list = goal.certifies.all()
status = get_status(goal)
today = datetime.date.today()
today_certify = certifiy_list.filter(created=today)
isCertify = today_certify.filter(user=request.user).exists()
context = {
'goal': goal,
'dates': board['dates'],
'member_count': member_count,
'level': level,
'name': total_name,
'certifies': certifiy_list,
'achievements': board['achievements'],
'start_days': status['start_days'],
'success_days': status['success_days'],
'continuity_days': status['continuity_days'],
'isCertify':isCertify,
}
return render(request, 'groups/main.html', context)
def certify(request, goal_id):
goal = get_object_or_404(Goal, pk=goal_id)
if request.method == 'POST':
user = request.user
created = timezone.now()
text = request.POST.get('text')
image = request.FILES.get('image')
figure = request.POST.get('figure')
achievement = True
if goal.certify_method == 'figure':
if goal.criteria: # 이상이어야 성공
if float(figure) < goal.value:
achievement = False
else: # 이하여야 성공
if float(figure) > goal.value:
achievement = False
if achievement:
user.profile.cash += 20
user.profile.save()
Certify.objects.create(goal=goal, user=user, created=created, text=text, image=image, figure=figure, achievement=achievement)
return redirect('groups:main', goal_id)
return render(request, 'groups/certify.html', {'goal': goal})
def get_status(goal): # 시작, 성공, 연속 일수를 리턴하는 함수
certifies = goal.certifies.all()
start_days = (datetime.date.today() - goal.start_date).days + 1
success_days = goal.certifies.filter(achievement=True).count()
continuity_days = 0
for i in range(certifies.count()):
date = datetime.date.today() - timedelta(days=i+1) # 어제부터 거꾸로 가면서 성공했는지 확인
certify = goal.certifies.filter(created=date)
if not certify.first(): # 인증이 없다면 종료
break
if not certify.first().achievement: # 인증이 있으나 실패했으면 종료
break
continuity_days += 1 # 성공했으면 연속 일수를 1씩 증가
res = {
'start_days': start_days,
'success_days': success_days,
'continuity_days': continuity_days,
}
return res
def get_board(goal): # 도장판의 날짜와 성공 여부를 리턴하는 함수
dates = []
achievements = []
for i in range(30):
date = goal.start_date + timedelta(days=i)
dates.append(date)
# 성공 여부
certify = goal.certifies.filter(created=date)
if certify: # 날짜에 해당하는 인증이 있으면
achievements.append(certify.first().achievement)
else: # 인증 안 했으면
if date < datetime.date.today(): # 과거라면
achievements.append(False) # 실천 실패로 처리
else: # 미래라면
achievements.append(None) # 아무것도 보여주지 않음
res = {
'dates': dates,
'achievements': achievements,
}
return res
def group_list(request):
return render(request, 'groups/group_list.html')
def group_detail(request):
return render(request, 'groups/group_detail.html')
def make_group(request):
return render(request, 'groups/make_group.html')
def delete_member(request, goal_id, user_id):
goal = Goal.objects.get(pk=goal_id)
delete_user = User.objects.get(pk=user_id)
delete_user.members.remove(goal)
return redirect('groups:main', goal_id) | {"/groups/admin.py": ["/groups/models.py"], "/groups/views.py": ["/main/models.py", "/groups/models.py"], "/groups/models.py": ["/main/models.py"], "/main/admin.py": ["/main/models.py"], "/users/views.py": ["/main/models.py"], "/main/views.py": ["/main/models.py"]} |
53,009 | daldal-Mango/Miracle30 | refs/heads/main | /groups/models.py | from django.db import models
from django.contrib.auth.models import User
from main.models import Goal
class Certify(models.Model):
goal = models.ForeignKey(Goal, on_delete=models.CASCADE, related_name='certifies')
user = models.ForeignKey(User, on_delete=models.CASCADE)
created = models.DateField()
image = models.ImageField(upload_to='certify_image/', null=True, blank=True)
text = models.TextField(null=True, blank=True)
figure = models.FloatField(null=True, blank=True)
achievement = models.BooleanField(default=True)
| {"/groups/admin.py": ["/groups/models.py"], "/groups/views.py": ["/main/models.py", "/groups/models.py"], "/groups/models.py": ["/main/models.py"], "/main/admin.py": ["/main/models.py"], "/users/views.py": ["/main/models.py"], "/main/views.py": ["/main/models.py"]} |
53,010 | daldal-Mango/Miracle30 | refs/heads/main | /main/migrations/0003_auto_20210822_1410.py | # Generated by Django 3.2.5 on 2021-08-22 14:10
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('main', '0002_alter_goal_value'),
]
operations = [
migrations.AddField(
model_name='goal',
name='deadline',
field=models.DateField(default=datetime.date(2021, 8, 22)),
preserve_default=False,
),
migrations.AddField(
model_name='goal',
name='member_limit',
field=models.IntegerField(default=10),
),
]
| {"/groups/admin.py": ["/groups/models.py"], "/groups/views.py": ["/main/models.py", "/groups/models.py"], "/groups/models.py": ["/main/models.py"], "/main/admin.py": ["/main/models.py"], "/users/views.py": ["/main/models.py"], "/main/views.py": ["/main/models.py"]} |
53,011 | daldal-Mango/Miracle30 | refs/heads/main | /groups/migrations/0001_initial.py | # Generated by Django 3.2.5 on 2021-08-02 02:40
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('main', '0001_initial'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='CertifyText',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created', models.DateField()),
('text', models.TextField()),
('achievement', models.BooleanField(default=False)),
('goal', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='texts', to='main.goal')),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
migrations.CreateModel(
name='CertifyImage',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created', models.DateField()),
('image', models.ImageField(upload_to='certify_image/')),
('achievement', models.BooleanField(default=False)),
('goal', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='images', to='main.goal')),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
migrations.CreateModel(
name='CertifyFigure',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created', models.DateField()),
('figure', models.IntegerField()),
('achievement', models.BooleanField(default=False)),
('goal', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='figures', to='main.goal')),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
]
| {"/groups/admin.py": ["/groups/models.py"], "/groups/views.py": ["/main/models.py", "/groups/models.py"], "/groups/models.py": ["/main/models.py"], "/main/admin.py": ["/main/models.py"], "/users/views.py": ["/main/models.py"], "/main/views.py": ["/main/models.py"]} |
53,012 | daldal-Mango/Miracle30 | refs/heads/main | /main/admin.py | from django.contrib import admin
from .models import Goal
admin.site.register(Goal)
| {"/groups/admin.py": ["/groups/models.py"], "/groups/views.py": ["/main/models.py", "/groups/models.py"], "/groups/models.py": ["/main/models.py"], "/main/admin.py": ["/main/models.py"], "/users/views.py": ["/main/models.py"], "/main/views.py": ["/main/models.py"]} |
53,013 | daldal-Mango/Miracle30 | refs/heads/main | /users/views.py | from django.db.models import manager
from django.shortcuts import redirect, render
from main.models import Goal
def mypage(request):
user = request.user
goals = Goal.objects.all()
my_goal = []
participate_goal = []
for goal in goals:
if goal.manager == user:
my_goal.append(goal)
elif user in goal.member.all():
participate_goal.append(goal)
context = {
'user':user,
'my_goal':my_goal,
'participate_goal':participate_goal
}
return render(request, 'users/mypage.html', context)
def mypage_update(request):
user = request.user
if request.method == "POST":
user.profile.nickname = request.POST.get('nickname')
if request.FILES.get('image'):
user.profile.image = request.FILES.get('image')
user.save()
return redirect('users:mypage')
return render(request, 'users/mypage_update.html', {'user': user})
| {"/groups/admin.py": ["/groups/models.py"], "/groups/views.py": ["/main/models.py", "/groups/models.py"], "/groups/models.py": ["/main/models.py"], "/main/admin.py": ["/main/models.py"], "/users/views.py": ["/main/models.py"], "/main/views.py": ["/main/models.py"]} |
53,014 | daldal-Mango/Miracle30 | refs/heads/main | /main/models.py | from django.db import models
from django.contrib.auth.models import User
class Goal(models.Model):
GOAL_CATEGORY_CHOICES = [
('study', 'study'),
('hobby', 'hobby'),
('etc', 'etc'),
]
CERTIFY_CATEGORY_CHOICES = [
('image', 'image'),
('text', 'text'),
('figure', 'figure'),
]
category = models.CharField(choices=GOAL_CATEGORY_CHOICES, max_length=50) # 카테고리(공부, 취미, 기타)
certify_method = models.CharField(choices=CERTIFY_CATEGORY_CHOICES, max_length=50) # 인증 방식(이미지, 글, 수치)
manager = models.ForeignKey(User, on_delete=models.CASCADE) # 목표 작성자 = 매니저
name = models.CharField(max_length=100) # 목표 이름
description = models.TextField() # 목표 설명
created = models.DateField() # 목표 글 작성 날짜
start_date = models.DateField() # 목표 시행 날짜
deadline = models.DateField() # 참여 마감 날짜
fee = models.IntegerField(default=500) # 참가비
value = models.FloatField(null=True, blank=True) # 인증 방식이 수치인 경우만
unit = models.CharField(max_length=10, null=True, blank=True) # 인증 방식이 수치인 경우만
criteria = models.BooleanField(default=True) # 인증 방식이 수치인 경우만. true면 이상, false면 이하로 처리
member = models.ManyToManyField(User, related_name='members') # 참여 인원
member_limit = models.IntegerField(default=10) # 참여 인원수 제한
| {"/groups/admin.py": ["/groups/models.py"], "/groups/views.py": ["/main/models.py", "/groups/models.py"], "/groups/models.py": ["/main/models.py"], "/main/admin.py": ["/main/models.py"], "/users/views.py": ["/main/models.py"], "/main/views.py": ["/main/models.py"]} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.